/
posterus.mjs
517 lines (431 loc) · 11.2 KB
/
posterus.mjs
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
export function isTask(val) {
return isObj(val) &&
isFun(val.isDone) &&
isFun(val.map) &&
isFun(val.mapErr) &&
isFun(val.mapVal) &&
isFun(val.finally) &&
isFun(val.onDeinit) &&
isFun(val.done) &&
isFun(val.deinit)
}
export class Task {
constructor() {
this.d = false // "done"
this.i = undefined // "inner"
this.m = undefined // "mappers"
this.e = undefined // "deiniters"
}
// True if completed OR deinited.
isDone() {return this.d}
done(err, val) {
const self = this
if (self.d) return undefined
try {
/*
Note: this flag may flip back to "false" after flushing the mappers, but
pretending that we're "done" during this process prevents reentrant calls
from mappers.
*/
self.d = true
clearInner(self)
for (;;) {
if (isTask(err)) {
linkInnerTaskErr(self, err)
return self
}
if (isTask(val)) {
linkInnerTask(self, val)
return self
}
let fun
if (isSeq(this.m)) {
fun = this.m.shift()
}
else {
fun = this.m
this.m = undefined
}
if (err) val = undefined
else err = undefined
if (fun) {
try {
val = fun(err, val)
err = undefined
}
catch (error) {
val = undefined
err = error
}
continue
}
maybeThrow(err)
return val
}
}
finally {
self.d = !self.i
}
}
map(fun) {
valid(fun, isFun)
if (this.d) throw Error(`can't map: task is done`)
this.m = collPush(this.m, fun)
return this
}
mapErr(fun) {
valid(fun, isFun)
this.map(bind(asMapErr, fun))
return this
}
mapVal(fun) {
valid(fun, isFun)
this.map(bind(asMapVal, fun))
return this
}
// Conceptually similar to "try/finally". The function will run when the task
// is done, regardless of the result, and without changing the result.
finally(fun) {
valid(fun, isFun)
this.map(bind(finalize, fun))
return this
}
onDeinit(fun) {
valid(fun, isFun)
if (this.d) throw Error(`can't deinit: task is done`)
this.e = collPush(this.e, fun)
}
deinit() {
if (this.d) return
this.d = true
this.m = undefined
for (;;) {
let deiniter
if (isSeq(this.e)) {
deiniter = this.e.shift()
}
else {
deiniter = this.e
this.e = undefined
}
if (!deiniter) break
deiniter()
}
clearInner(this)
}
toPromise() {
if (this.isDone()) throw Error(`can't convert to promise: task is done`)
return new Promise(bind(taskToPromise, this))
}
toString() {return 'Task'}
// Match the behavior of `JSON.stringify` for `Function` instances. Users may
// intuitively expect this. It's unfortunate that promises don't also
// implement this.
toJSON() {return null}
}
function asMapErr(fun, err, val) {
if (err) return fun(err)
return val
}
function asMapVal(fun, err, val) {
maybeThrow(err)
return fun(val)
}
function finalize(fun, err, val) {
fun(err, val)
maybeThrow(err)
return val
}
const ARRAY_THRESHOLD = 20
function collPush(items, item) {
if (!items) return item
if (isArr(items)) {
if (items.length > ARRAY_THRESHOLD) {
items = new Que(items)
}
items.push(item)
return items
}
if (isInst(items, Que)) {
items.push(item)
return items
}
items = [items, item, undefined, undefined]
items.length = 2
return items
}
function setInner(outer, innerNext) {
const inner = outer.i
outer.i = innerNext
if (isTask(inner)) inner.deinit()
}
function clearInner(outer) {
setInner(outer, undefined)
}
function linkInnerTask(outer, inner) {
setInner(outer, inner.map(bind(transferTaskResult, outer)))
}
function linkInnerTaskErr(outer, inner) {
setInner(outer, inner.map(bind(transferTaskErr, outer)))
}
function linkInnerPromise(task, promise) {
setInner(task, promise.then(task.done.bind(task, undefined), task.done.bind(task)))
}
function transferTaskResult(task, err, val) {
task.done(err, val)
}
function transferTaskErr(task, err, val) {
task.done(err || val)
}
/*
Creates a branch that inherits the original's error or val. Deiniting the
original also deinits the branch, but deiniting the branch has no effect on the
original.
Note that not handling the original's error might result in unhandled exceptions
that crash a server.
Minor design issue: can we simultaneously handle the original's error and allow
it to propagate to branches? Do we really want to?
*/
export function branch(task) {
valid(task, isTask)
const out = new Task()
task.map(bind(copyResult, out))
task.onDeinit(out.deinit.bind(out))
return out
}
function copyResult(out, err, val) {
out.done(err, val)
maybeThrow(err)
return val
}
export function all(vals) {
vals = arr(vals)
return initAll(vals, Array(vals.length))
}
export function dictAll(vals) {
return initAll(dict(vals), {})
}
function initAll(vals, outputs) {
const task = new Task()
const counter = {n: 0}
each(vals, initElement, vals, outputs, task, counter)
task.onDeinit(bind(deinitTasks, vals))
if (!counter.n) async.push(task, undefined, outputs)
return task
}
function initElement(input, key, vals, outputs, task, counter) {
if (isTask(input)) {
counter.n++
input.map(bind(onElementDone, key, vals, outputs, task, counter))
}
else {
outputs[key] = input
}
}
function onElementDone(key, vals, outputs, task, counter, err, val) {
if (err) {
task.done(err)
deinitTasks(vals)
}
else {
outputs[key] = val
if (!--counter.n) task.done(undefined, outputs)
}
}
export function race(vals) {
vals = arr(vals)
if (!vals.length) return async.fromVal()
const nonTaskIndex = vals.findIndex(isNonTask)
if (nonTaskIndex >= 0) {
deinitTasks(vals)
return async.fromVal(vals[nonTaskIndex])
}
const task = new Task()
const onDone = bind(onRaceElementDone, task, vals)
for (let i = 0; i < vals.length; i += 1) vals[i].map(onDone)
task.onDeinit(bind(deinitTasks, vals))
return task
}
function onRaceElementDone(task, vals, err, val) {
task.done(err, val)
deinitTasks(vals)
}
export function fromPromise(promise) {
valid(promise, isPromise)
const out = new Task()
linkInnerPromise(out, promise)
return out
}
// Should this be a method of `Scheduler`?
export function toTask(val) {
if (isTask(val)) return val
if (isPromise(val)) return fromPromise(val)
return async.fromVal(val)
}
function taskToPromise(task, res, rej) {
task.map(bind(promiseSettle, res, rej))
task.onDeinit(bind(promiseDeinit, rej))
}
function promiseSettle(res, rej, err, val) {
if (err) rej(err)
else res(val)
}
function promiseDeinit(rej) {
rej(Error(`deinit`))
}
export class AsyncTask extends Task {
done(err, val) {
// True if deinited.
if (this.isDone()) return
this.done = super.done
async.push(this, err, val)
}
}
/*
Adapted from https://github.com/creationix/fastqueue. Modifications:
* Can be created from an existing array.
* Mangle private properties to reduce code size.
* Removed `unshift` support to reduce code size.
*/
export class Que {
constructor(tail) {
const self = this
tail = arr(tail)
self.length = tail.length
self.h = [] // "head"
self.t = tail // "tail"
self.i = 0 // "index"
self.l = 0 // "l"
}
push(val) {
this.length++
this.t.push(val)
}
shift() {
const self = this
if (self.i >= self.l) {
const t = self.h
t.length = 0
self.h = self.t
self.t = t
self.i = 0
self.l = self.h.length
if (!self.l) return undefined
}
const val = self.h[self.i]
self.h[self.i++] = undefined
self.length--
return val
}
}
/*
Allows to settle task instances asynchronously. Useful for "pre-done" tasks.
See the `async` variable.
Can be synchronously flushed on demand.
*/
export class Scheduler {
constructor() {
const self = this
self.p = new Que() // "pending"
self.s = false // "is scheduled"
const schedule = chooseAsync(function scheduledTick() {
self.s = false
self.tick()
})
self.t = function scheduleTick() {
if (!self.s) {
self.s = true
schedule()
}
}
}
push(task, err, val) {
valid(task, isTask)
const pending = this.p
pending.push(task)
pending.push(err)
pending.push(val)
this.t()
}
fromErr(err) {
if (!err) throw Error(`expected an error`)
const out = new Task()
this.push(out, err, undefined)
return out
}
fromVal(val) {
const out = new Task()
this.push(out, undefined, val)
return out
}
tick() {
const pending = this.p
while (pending.length) {
const task = pending.shift()
const err = pending.shift()
const val = pending.shift()
task.done(err, val)
}
}
}
// Default scheduler. Useful for making mappable "pre-done" tasks.
export const async = new Scheduler()
/* eslint-disable no-restricted-globals */
function chooseAsync(fun) {
if (typeof self === 'undefined' && typeof process === 'object' && process && process.nextTick) {
return function usingNextTick() {
process.nextTick(fun)
}
}
if (typeof MessageChannel === 'function') {
const channel = new MessageChannel()
channel.port1.onmessage = fun
return function usingMessageChannel() {
// Note: `postMessage` requires an argument.
channel.port2.postMessage(undefined)
}
}
return function usingSetTimeout() {
setTimeout(fun)
}
}
/* eslint-enable no-restricted-globals */
function each(vals, fun, ...args) {
if (isArr(vals)) {
for (let i = 0; i < vals.length; i += 1) {
fun(vals[i], i, ...args)
}
}
else {
for (const key in vals) fun(vals[key], key, ...args)
}
}
function deinitTasks(vals) {each(vals, deinitTask)}
function deinitTask(val) {if (isTask(val)) val.deinit()}
function isNil(val) {return val == null}
function isStr(val) {return typeof val === 'string'}
function isFun(val) {return typeof val === 'function'}
function isObj(val) {return val !== null && typeof val === 'object'}
function isArr(val) {return isInst(val, Array)}
function isSeq(val) {return isInst(val, Que) || isArr(val)}
function isPromise(val) {return isObj(val) && isFun(val.then)}
function isNonTask(val) {return !isTask(val)}
function isInst(val, Class) {return (isObj(val) || isFun(val)) && val instanceof Class}
function isDict(val) {
if (!isObj(val)) return false
const proto = Object.getPrototypeOf(val)
return proto === null || proto === Object.prototype
}
function arr(val) {return isNil(val) ? [] : only(val, isArr)}
function dict(val) {return isNil(val) ? {} : only(val, isDict)}
function only(val, test) {valid(val, test); return val}
function valid(val, test) {
if (!test(val)) throw Error(`expected ${show(val)} to satisfy test ${show(test)}`)
}
function show(val) {
if (isFun(val) && val.name) return val.name
if (isArr(val) || isDict(val) || isStr(val)) return JSON.stringify(val)
return `${val}`
}
function bind(fun, ...args) {return fun.bind(undefined, ...args)}
function maybeThrow(err) {if (err) throw err}