-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
async_helpers.js
173 lines (152 loc) · 4.39 KB
/
async_helpers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
Meteor._noYieldsAllowed = function (f) {
var result = f();
if (Meteor._isPromise(result)) {
throw new Error("function is a promise when calling Meteor._noYieldsAllowed");
}
return result
};
function FakeDoubleEndedQueue () {
this.queue = [];
}
FakeDoubleEndedQueue.prototype.push = function (task) {
this.queue.push(task);
};
FakeDoubleEndedQueue.prototype.shift = function () {
return this.queue.shift();
};
FakeDoubleEndedQueue.prototype.isEmpty = function () {
return this.queue.length === 0;
};
Meteor._DoubleEndedQueue = Meteor.isServer ? Npm.require('denque') : FakeDoubleEndedQueue;
// Meteor._SynchronousQueue is a queue which runs task functions serially.
// Tasks are assumed to be synchronous: ie, it's assumed that they are
// done when they return.
//
// It has two methods:
// - queueTask queues a task to be run, and returns immediately.
// - runTask queues a task to be run, and then yields. It returns
// when the task finishes running.
//
// It's safe to call queueTask from within a task, but not runTask (unless
// you're calling runTask from a nested Fiber).
//
// Somewhat inspired by async.queue, but specific to blocking tasks.
// XXX break this out into an NPM module?
// XXX could maybe use the npm 'schlock' module instead, which would
// also support multiple concurrent "read" tasks
//
function AsynchronousQueue () {
this._taskHandles = new Meteor._DoubleEndedQueue();
this._runningOrRunScheduled = false;
// This is true if we're currently draining. While we're draining, a further
// drain is a noop, to prevent infinite loops. "drain" is a heuristic type
// operation, that has a meaning like unto "what a naive person would expect
// when modifying a table from an observe"
this._draining = false;
}
Object.assign(AsynchronousQueue.prototype, {
queueTask(task) {
const self = this;
self._taskHandles.push({
task: task,
name: task.name
});
self._scheduleRun();
},
async _scheduleRun() {
// Already running or scheduled? Do nothing.
if (this._runningOrRunScheduled)
return;
this._runningOrRunScheduled = true;
let resolve;
const promise = new Promise(r => resolve = r);
const runImmediateHandle = (fn) => {
if (Meteor.isServer) {
setImmediate(fn);
return;
}
setTimeout(fn, 0);
};
runImmediateHandle(() => {
this._run().finally(resolve);
});
return promise;
},
async _run() {
if (!this._runningOrRunScheduled)
throw new Error("expected to be _runningOrRunScheduled");
if (this._taskHandles.isEmpty()) {
// Done running tasks! Don't immediately schedule another run, but
// allow future tasks to do so.
this._runningOrRunScheduled = false;
return;
}
const taskHandle = this._taskHandles.shift();
let exception;
// Run the task.
try {
await taskHandle.task();
} catch (err) {
if (taskHandle.resolver) {
// We'll throw this exception through runTask.
exception = err;
} else {
Meteor._debug("Exception in queued task", err);
}
}
// Soon, run the next task, if there is any.
this._runningOrRunScheduled = false;
this._scheduleRun();
if (taskHandle.resolver) {
if (exception) {
taskHandle.resolver(null, exception);
} else {
taskHandle.resolver();
}
}
},
async runTask(task) {
let resolver;
const promise = new Promise(
(resolve, reject) =>
(resolver = (res, rej) => {
if (rej) {
reject(rej);
return;
}
resolve(res);
})
);
const handle = {
task: Meteor.bindEnvironment(task, function (e) {
Meteor._debug('Exception from task', e);
throw e;
}),
name: task.name,
resolver,
};
this._taskHandles.push(handle);
await this._scheduleRun();
return promise;
},
flush() {
return this.runTask(() => { });
},
async drain() {
if (this._draining)
return;
this._draining = true;
while (!this._taskHandles.isEmpty()) {
await this.flush();
}
this._draining = false;
}
});
Meteor._AsynchronousQueue = AsynchronousQueue;
// Sleep. Mostly used for debugging (eg, inserting latency into server
// methods).
//
const _sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
Meteor._sleepForMs = function (ms) {
return _sleep(ms);
};