-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathgate-executor.ts
More file actions
374 lines (301 loc) · 11.4 KB
/
gate-executor.ts
File metadata and controls
374 lines (301 loc) · 11.4 KB
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/* Copyright (c) 2014-2021 Richard Rodger, MIT License */
type Work = {
id: string // Identifier
ge: string // GateExecutor identifier
tm: number // Timeout
dn: string // Description
fn: (callback: () => void) => void
start: number
end: number
gate?: any
callback: () => void
ctxt: { [key: string]: any }
}
// Create root instance. Exported as module.
// * `options` (object): instance options as key-value pairs.
//
// The options are:
// * `interval` (integer): millisecond interval for timeout checks. Default: 111.
// * `timeout` (integer): common millisecond timeout.
// Can be overridden by work item options. Default: 2222.
function MakeGateExecutor(options?: any) {
options = options || {}
options.interval = null == options.interval ? 111 : options.interval
options.timeout = null == options.timeout ? 2222 : options.timeout
return GateExecutor(options, 0)
}
// Create a new instance.
// * `options` (object): instance options as key-value pairs.
// * `instance_counter` (integer): count number of instances created;
// used as identifier.
function GateExecutor(this: any, options: any, instance_counter: number) {
let self: any = {}
self.id = ++instance_counter
self.options = options
// Work queue.
let q: Work[] = []
// Work-in-progress set.
let progress: any = {
// Lookup work by id.
lookup: {},
// Work history - a list of work items in the order executed.
history: [],
}
// List of work items to check for timeouts.
let timeout_checklist: any[] = []
// Internal state.
let s: any = {
// Count of work items added to this instance. Used as generated work identifier.
work_counter: 0,
// When `true`, the instance is in a gated state, and work cannot proceed
// until the gated in-progress work item is completed.
gate: false,
// When `true`, the instance processes work items as they arrive.
// When `false`, no processing happens, and the instance must be started by
// calling the `start` method.
running: false,
// A function called when the work queue and work-in-progress set
// are empty. Set by calling the `clear` method. Will be called
// each time the instance empty.
clear: null,
// A function called once only when the work queue and
// work-in-progress set are first emptied after each start. Set as
// an optional argument to the `start` method.
firstclear: null,
// Timeout interval reference value returned by `setInterval`.
// Timeouts are not checked using `setTimeout`, as it is more
// efficient, and more than sufficient, to check timeouts periodically.
tm_in: null,
hw_tmc: 0,
hw_hst: 0,
}
// Process the next work item.
function processor() {
// If not running, don't process any work items.
if (!s.running) {
return
}
// The timeout interval check is stopped and started only as needed.
if (!self.isclear() && !s.tm_in) {
s.tm_in = setInterval(timeout_check, options.interval)
}
// Process the next work item, returning `true` if there was one.
let next = false
do {
next = false
let work = null
// Remove next work item from the front of the work queue.
if (!s.gate) {
work = q.shift()
}
if (work) {
// Add work item to the work-in-progress set.
progress.lookup[work.id] = work
progress.history.push(work)
s.hw_hst =
progress.history.length > s.hw_hst ? progress.history.length : s.hw_hst
// If work item is a gate, set the state of the instance as
// gated. This work item will need to complete before later
// work items in the queue can be processed.
s.gate = work.gate
// Call the work item function (which does the real work),
// passing a callback. This callback has no arguments
// (including no error!). It is called only to indicate
// completion of the work item. Work items must handle their
// own errors and results.
work.start = Date.now()
work.callback = make_work_fn_callback(work)
timeout_checklist.push(work)
s.hw_tmc =
timeout_checklist.length > s.hw_tmc ? timeout_checklist.length : s.hw_tmc
work.fn(work.callback)
next = true
}
} while (next)
// Keep processing work items until none are left or a gate is reached.
}
// Create the callback for the work function
function make_work_fn_callback(work: any) {
return function work_fn_callback() {
if (work.done) {
return
}
work.end = Date.now()
// Remove the work item from the work-in-progress set. As
// work items may complete out of order, prune the history
// of all work items that are complete.Later complete work items
// will eventually be reached on another processing round.
work.done = true
delete progress.lookup[work.id]
progress.history = progress.history.filter((workItem: any) => {
return !workItem.done
})
timeout_checklist = timeout_checklist.filter((workItem: any) => {
return !workItem.done
})
// If the work item was a gate, it is now complete, and the
// instance can be ungated, allowing later work items in the
// queue to be processed.
if (work.gate) {
s.gate = false
}
// If work queue and work-in-progress set are empty, then
// call the registered clear functions.
if (0 === q.length && 0 === progress.history.length) {
clearInterval(s.tm_in)
s.tm_in = null
if (s.firstclear) {
let fc = s.firstclear
s.firstclear = null
fc()
}
if (s.clear) {
s.clear()
}
}
// Process each work item on next tick to avoid lockups.
setImmediate(processor)
}
}
// To be run periodically via setInterval. For timed out work items,
// calls the done callback to allow work queue to proceed, and marks
// the work item as finished. Work items can receive notification of
// timeouts by providing an `ontm` callback property in the
// work definition object. Work items must handle timeout errors
// themselves, gate-executor cares only for the fact that a timeout
// happened, so it can continue processing.
function timeout_check() {
let now = Date.now()
let work = null
for (let i = 0; i < timeout_checklist.length; ++i) {
work = timeout_checklist[i]
if (!work.gate && !work.done && work.tm < now - work.start) {
if (work.ontm) {
work.ontm(work.tm, work.start, now)
}
work.callback()
}
}
}
// Start processing work items. Must be called to start processing.
// Can be called at anytime, interspersed with calls to other
// methods, including `add`. Takes a function as argument, which is
// called only once on the next time the queues are clear.
self.start = function(firstclear: any) {
// Allow API chaining by not starting in current execution path.
setImmediate(function() {
s.running = true
if (firstclear) {
s.firstclear = firstclear
}
processor()
})
return self
}
// Pause the processing of work items. Newly added items, and items
// not yet started, will not proceed, but items already in progress
// will complete, and the clear function will be called once all in
// progress items finish.
self.pause = function() {
s.running = false
}
// Submit a function that will be called each time there are no more
// work items to process. Multiple calls to this method will replace
// the previously registered clear function.
self.clear = function(done: any) {
s.clear = done
return self
}
// Returns `true` when there are no more work items to process.
self.isclear = function() {
return 0 === q.length && 0 === progress.history.length
}
// Add a work item. This is an object with fields:
// * `fn` (function): the function that performs the work. Takes a
// single argument, the callback function to call when the work is
// complete. THis callback does **not** accept errors or
// results. It's only purpose is to indicate that the work is
// complete (whether failed or not). The work function itself must
// handle callbacks to the application. Required.
// * `id` (string): identifier for the work item. Optional.
// * `tm` (integer): millisecond timeout specific to this work item,
// overrides general timeout. Optional.
// * `ontm` (function): callback to indicate work item timeout. Optional.
// * `dn` (string): description of the work item, used in the
// state description. Optional.
self.add = function(work: Work) {
s.work_counter += 1
work.id = work.id || '' + s.work_counter
work.ge = self.id
work.tm = null == work.tm ? options.timeout : work.tm
work.dn = work.dn || work.fn.name || '' + Date.now()
// Used by calling code to store additional context.
work.ctxt = {}
q.push(work)
if (s.running) {
// Work items are **not** processed in the current execution path!
// This prevents lockup, and avoids false positives in unit tests.
// Work items are assumed to be inherently asynchronous.
setImmediate(processor)
}
return self
}
// Create a new gate. Returns a new `GateExecutor` instance. All
// work items added to the new instance must complete before the
// gate is cleared, and work items in the queue can be processed. A
// gate is cleared when the new instance is **first** cleared. Work
// items subsequently added to the new instance are not considered
// part of the gate. Gates can extend to any depth and form a tree
// structure that requires breadth-first traversal in terms of the
// work item queue. Gates do not have timeouts, and can only be
// cleared when all added work items complete.
self.gate = function() {
let ge: any = GateExecutor(options, instance_counter)
let fn = function gate(done: any) {
// This is the work function of the gate, which starts the new
// instance, and considers the gate work item complete when the
// work queue clears for the first time.
ge.start(done)
}
self.add({ gate: ge, fn: fn })
return ge
}
// Return a data structure describing the current state of the work
// queues, and organised as a tree structure indicating the gating
// relationships.
self.state = function() {
let out: any = []
// First list any in-progress work items.
for (let hI = 0; hI < progress.history.length; ++hI) {
let pe = progress.history[hI]
if (!pe.done) {
out.push({ s: 'a', ge: pe.ge, dn: pe.dn, id: pe.id })
}
}
// Then list any waiting work items.
for (let qI = 0; qI < q.length; ++qI) {
let qe = q[qI]
if (qe.gate) {
// Go down a level when there's a gate.
out.push(qe.gate.state())
} else {
out.push({ s: 'w', ge: qe.ge, dn: qe.dn, id: qe.id })
}
}
out.internal = {
qlen: q.length,
hlen: progress.history.length,
klen: Object.keys(progress.lookup).length,
tlen: timeout_check.length,
hw_hst: s.hw_hst,
hw_tmc: s.hw_tmc,
}
return out
}
return self
}
// The module function
export default MakeGateExecutor
if (undefined != typeof (module.exports)) {
module.exports = MakeGateExecutor
}