forked from origamitower/folktale
/
task.js
564 lines (474 loc) · 17.6 KB
/
task.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
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//----------------------------------------------------------------------
//
// This source file is part of the Folktale project.
//
// Licensed under MIT. See LICENCE for full licence information.
// See CONTRIBUTORS for the list of contributors to the project.
//
//----------------------------------------------------------------------
const { property } = require('jsverify');
const env = require('../environment');
const Task = require('folktale/concurrency/task');
const Future = require('folktale/concurrency/future');
const { _ExecutionState, _Deferred: Deferred } = Future;
const { Resolved, Rejected, Cancelled } = _ExecutionState;
const cancelled = () => {
const d = new Deferred();
d.cancel();
return d.future();
};
const eq = function(that) {
return this._state.equals(that._state);
}
describe('Data.Task', () => {
describe('Conversions', () => {
property('fromPromised(a => Promise.resolve(a)) → (a) => Task.of(a)', 'nat', async (a) => {
return (await Task.fromPromised(x => Promise.resolve(x))(a).run().promise()) === a
});
property('fromPromised(a => Promise.reject(a)) → (a) => Task.rejected(a)', 'nat', async (a) => {
return await Task.fromPromised(x => Promise.reject(x))(a).run().promise().catch(x => x === a);
});
});
describe('Tasks', () => {
property('#chain(f) transforms successful tasks', 'nat', 'nat -> task nat', env, (a, f) => {
return Task.of(a).chain(f).run().future() ::eq(f(a).run().future());
});
property('#chain(f) ignores failures', 'nat', 'nat -> task nat', env, (a, f) => {
return Task.rejected(a).chain(f).run().future() ::eq(Future.rejected(a));
});
property('#chain(f) ignores cancellations', 'nat', 'nat -> task nat', env, (a, f) => {
const execution = Task.task(r => r.cancel()).chain(f).run();
return execution.future() ::eq(cancelled());
});
property('#orElse(f) transforms failed tasks', 'nat', 'nat -> task nat', env, (a, f) => {
return Task.rejected(a).orElse(f).run().future() ::eq(f(a).run().future());
});
property('#orElse(f) ignores successful tasks', 'nat', 'nat -> task nat', env, (a, f) => {
return Task.of(a).orElse(f).run().future() ::eq(Future.of(a));
});
property('#orElse(f) ignores cancellations', 'nat', 'nat -> task nat', env, (a, f) => {
const execution = Task.task(r => r.cancel()).orElse(f).run();
return execution.future() ::eq(cancelled());
});
property('#map(f) transforms successful tasks', 'nat', 'nat -> nat', (a, f) => {
return Task.of(a).map(f).run().future() ::eq(Future.of(f(a)));
});
property('#map(f) ignores failures', 'nat', 'nat -> nat', (a, f) => {
return Task.rejected(a).map(f).run().future() ::eq(Future.rejected(a));
});
property('#map(f) ignores cancellations', 'nat', 'nat -> nat', (a, f) => {
return Task.task(r => r.cancel()).map(f).run().future() ::eq(cancelled());
});
property('#mapRejected(f) transforms rejected tasks', 'nat', 'nat -> nat', (a, f) => {
return Task.rejected(a).mapRejected(f).run().future() ::eq(Future.rejected(f(a)));
});
property('#mapRejected(f) ignores successes', 'nat', 'nat -> nat', (a, f) => {
return Task.of(a).mapRejected(f).run().future() ::eq(Future.of(a));
});
property('#mapRejected(f) ignores cancellations', 'nat', 'nat -> nat', (a, f) => {
return Task.task(r => r.cancel()).mapRejected(f).run().future() ::eq(cancelled());
});
property('#apply(a) applies successes', 'nat', 'nat -> nat', (a, f) => {
return Task.of(f).apply(Task.of(a)).run().future() ::eq(Future.of(f(a)));
});
property('#apply(a) ignores failures', 'nat', 'nat -> nat', (a, f) => {
return Task.rejected(f).apply(Task.of(a)).run().future() ::eq(Future.rejected(f));
});
property('#apply(a) ignores cancellations', 'nat', 'nat -> nat', (a, f) => {
return Task.task(r => r.cancel()).apply(Task.of(a)).run().future()
::eq (cancelled());
});
property('#bimap(f, g) applies g to successes', 'nat', 'nat -> nat', 'nat -> nat', (a, f, g) => {
return Task.of(a).bimap(f, g).run().future() ::eq(Future.of(g(a)));
});
property('#bimap(f, g) applies f to failures', 'nat', 'nat -> nat', 'nat -> nat', (a, f, g) => {
return Task.rejected(a).bimap(f, g).run().future() ::eq(Future.rejected(f(a)));
});
property('#bimap(f, g) ignores cancellation', 'nat', 'nat -> nat', 'nat -> nat', (a, f, g) => {
return Task.task(r => r.cancel()).bimap(f, g).run().future() ::eq(cancelled());
});
describe('#willMatchWith(pattern)', () => {
property('calls .Cancelled for cancellations', 'nat', 'nat -> task nat', 'nat -> task nat', 'nat -> task nat', env, (a, f, g, h) => {
return Task.task(r => r.cancel())
.willMatchWith({
Cancelled: f,
Rejected: g,
Resolved: h
})
.run().future()
::eq(f().run().future());
});
property('calls .Rejected for rejections', 'nat', 'nat -> task nat', 'nat -> task nat', 'nat -> task nat', env, (a, f, g, h) => {
return Task.rejected(a)
.willMatchWith({
Cancelled: f,
Rejected: g,
Resolved: h
}).run().future()
::eq(g(a).run().future());
});
property('calls .Resolved for successes', 'nat', 'nat -> task nat', 'nat -> task nat', 'nat -> task nat', env, (a, f, g, h) => {
return Task.of(a)
.willMatchWith({
Cancelled: f,
Rejected: g,
Resolved: h
}).run().future()
::eq(h(a).run().future());
});
});
});
property('#swap() swaps rejections and successes', 'nat', 'nat', (a, b) => {
return Task.of(a).swap().run().future() ::eq(Future.rejected(a))
&& Task.rejected(b).swap().run().future() ::eq(Future.of(b));
});
property('#swap() ignores cancellations', () => {
return Task.task(r => r.cancel()).run().future() ::eq(cancelled());
});
describe('#or(that)', () => {
it('Selects the first resolution', async () => {
const a = Task.of(1);
const b = Task.rejected(2);
const c = Task.of(2);
const d = Task.rejected(1);
const v1 = await a.or(b).run().promise();
$ASSERT(v1 == 1);
await b.or(a).run().promise().catch(v => $ASSERT(v == 2));
const v2 = await a.or(c).run().promise();
$ASSERT(v2 == 1);
await b.or(d).run().promise().catch(v => $ASSERT(v == 2));
});
it('Starts tasks in parallel, waits first', async () => {
let done = [false, false];
let start = [false, false];
const a = Task.task(r => {
start[0] = true;
const timer = setTimeout(_ => { done[0] = true; r.resolve(1); }, 150);
r.cleanup(() => clearTimeout(timer));
});
const b = Task.task(r => {
start[1] = true;
const timer = setTimeout(_ => { done[1] = true; r.resolve(2); }, 100);
r.cleanup(() => clearTimeout(timer));
});
const p = a.or(b).run().promise();
$ASSERT(start == [true, true]);
const v = await p;
$ASSERT(v == 2);
$ASSERT(done == [false, true]);
});
it('Cancels the task that hasn’t resolved', async () => {
let cancelled = [false, false];
const a = Task.task(r => {
const timer = setTimeout(r.resolve, 100);
r.onCancelled(() => { cancelled[0] = true });
r.cleanup(() => clearTimeout(timer));
});
const b = Task.task(r => {
const timer = setTimeout(r.resolve, 200);
r.onCancelled(() => { cancelled[1] = true });
r.cleanup(() => clearTimeout(timer));
});
await a.or(b).run().promise().catch(() => null);
$ASSERT(cancelled == [false, true]);
});
it('When cancelled, should cancel both tasks', async () => {
let cancelled = [false, false];
const a = Task.task(r => {
const timer = setTimeout(r.resolve, 100);
r.onCancelled(() => { cancelled[0] = true });
r.cleanup(() => clearTimeout(timer));
});
const b = Task.task(r => {
const timer = setTimeout(r.reject, 100);
r.onCancelled(() => { cancelled[1] = true });
r.cleanup(() => clearTimeout(timer));
});
const execution = a.or(b).run();
execution.cancel();
await execution.promise().catch(() => null);
$ASSERT(cancelled == [true, true]);
});
});
describe('#and(that)', () => {
it('waits for both values in parallel, maintains tuple ordering', async () => {
const a = Task.task(r => {
const timer = setTimeout(_ => r.resolve(1), 150);
r.cleanup(() => clearTimeout(timer));
});
const b = Task.task(r => {
const timer = setTimeout(_ => r.resolve(2), 100);
r.cleanup(() => clearTimeout(timer));
});
const val = await a.and(b).run().promise();
$ASSERT(val == [1, 2]);
});
it('When cancelled, should cancel both tasks', async () => {
let cancelled = [false, false];
const a = Task.task(r => {
const timer = setTimeout(r.resolve, 100);
r.onCancelled(() => { cancelled[0] = true });
r.cleanup(() => clearTimeout(timer));
});
const b = Task.task(r => {
const timer = setTimeout(r.reject, 100);
r.onCancelled(() => { cancelled[1] = true });
r.cleanup(() => clearTimeout(timer));
});
const execution = a.and(b).run();
execution.cancel();
await execution.promise().catch(() => null);
$ASSERT(cancelled == [true, true]);
});
it('Cancelling after partial resolution is okay', async () => {
let resolved = [false, false];
let cancellations = [false, false];
const a = Task.task(r => {
const timer = setTimeout(_ => {
resolved[0] = true;
r.resolve(1);
}, 200);
r.onCancelled(() => { cancellations[0] = true });
r.cleanup(() => clearTimeout(timer));
});
const b = Task.task(r => {
const timer = setTimeout(_ => {
resolved[1] = true;
r.resolve(2);
}, 100);
r.onCancelled(() => { cancellations[1] = true });
r.cleanup(() => clearTimeout(timer));
});
const ex = a.and(b).run();
setTimeout(_ => { ex.cancel() }, 120);
await ex.promise().catch(() => null);
$ASSERT(ex.future() ::eq(cancelled()));
$ASSERT(resolved == [false, true]);
$ASSERT(cancellations == [true, false]);
});
});
it('waitAll()', async () => {
const result = await Task.waitAll([Task.of(1), Task.of(2), Task.of(3)]).run().promise();
$ASSERT(result == [1, 2, 3]);
const result2 = await Task.waitAll([Task.of(1), Task.rejected(2), Task.of(3)]).run().promise().catch(e => e);
$ASSERT(result2 == 2);
});
it('waitAny()', async () => {
const delay = (ms) => Task.task((r) => {
const timer = setTimeout(() => r.resolve(ms), ms);
r.cleanup(() => clearTimeout(timer));
});
const result = await Task.waitAny([delay(100), delay(30), delay(200)]).run().promise();
$ASSERT(result == 30);
const result2 = await Task.waitAny([delay(100), delay(200), delay(30).swap()]).run().promise().catch(e => e == 30);
$ASSERT(result2 == true);
});
it('do()', async () => {
const delay = (ms) => Task.task((r) => {
const timer = setTimeout(() => r.resolve(ms), ms);
r.cleanup(() => clearTimeout(timer));
});
const result = await Task.do(function *() {
const a = yield delay(10);
const b = yield delay(11);
const c = yield Task.of(5);
return Task.of(a + b + c + 4);
}).run().promise();
$ASSERT(result == 30)
const exceptionThrown = [false, false];
await Task.do(function *() {
const a = yield Task.rejected(5);
return Task.of(a);
}).run().promise().catch((exception) => {
exceptionThrown[0] = true;
$ASSERT(exception == 5);
})
$ASSERT(exceptionThrown[0] == true);
const resultCancel = await Task.do(function *() {
const a = yield Task.task(r => r.cancel());
return Task.of(a);
}).run().promise().catch(() => {
exceptionThrown[1] = true;
});
$ASSERT(exceptionThrown[1] == true);
});
describe('#run()', () => {
it('Executes the computation for the task', () => {
let ran = false;
const a = Task.task(r => {
ran = true;
r.resolve(1);
});
a.run();
$ASSERT(ran == true);
});
it('Always invokes cleanup after the task resolves', async () => {
let stack = [];
let d = new Deferred();
Task.task(r => {
stack.push(1);
r.cleanup(() => {
stack.push(2);
d.resolve(2)
});
r.resolve(1)
}).run();
await d.promise();
$ASSERT(stack == [1, 2]);
stack = [];
d = new Deferred();
Task.task(r => {
stack.push(3);
r.cleanup(() => {
stack.push(4);
d.resolve(2);
});
r.reject(1)
}).run();
await d.promise();
$ASSERT(stack == [3, 4]);
stack = [];
d = new Deferred();
Task.task(r => {
stack.push(5);
r.cleanup(() => {
stack.push(6);
d.resolve(2);
})
}).run().cancel();
await d.promise();
$ASSERT(stack == [5, 6]);
});
it('Invokes onCancelled callbacks if the task is cancelled', async () => {
let stack = [];
let d = new Deferred();
Task.task(r => {
stack.push(1);
r.cleanup(() => {
stack.push(2);
d.resolve(2);
});
r.onCancelled(() => {
stack.push(r.isCancelled);
});
stack.push(r.isCancelled);
r.resolve(1);
}).run().cancel();
await d.promise();
$ASSERT(stack == [1, false, 2]);
stack = [];
d = new Deferred();
Task.task(r => {
stack.push(3);
r.cleanup(() => {
stack.push(4);
d.resolve(2);
})
r.onCancelled(() => {
stack.push(r.isCancelled);
});
stack.push(r.isCancelled);
r.reject(1)
}).run();
await d.promise();
$ASSERT(stack == [3, false, 4]);
stack = [];
d = new Deferred();
Task.task(r => {
stack.push(5);
stack.push(r.isCancelled);
r.cleanup(() => {
stack.push(6);
d.resolve(2)
});
r.onCancelled(() => {
stack.push(r.isCancelled);
});
}).run().cancel();
await d.promise();
$ASSERT(stack == [5, false, true, 6]);
});
});
property('#of(v) creates a task containing v', 'nat', (a) => {
return Task.of(a).run().future() ::eq(Future.of(a));
});
property('#rejected(v) creates a rejected task containing v', 'nat', (a) => {
return Task.rejected(a).run().future() ::eq(Future.rejected(a));
});
describe('TaskExecution', () => {
describe('#listen(pattern)', () => {
it('invokes pattern.Resolved for successes', () => {
let a = [0, 0, 0];
Task.of(1).run().listen({
onCancelled: _ => a[0]++,
onRejected: b => a[1] += b,
onResolved: b => a[2] += b
});
$ASSERT(a == [0, 0, 1]);
});
it('invokes pattern.Rejected for rejections', () => {
let a = [0, 0, 0];
Task.rejected(2).run().listen({
onCancelled: _ => a[0]++,
onRejected: b => a[1] += b,
onResolved: b => a[2] += b
});
$ASSERT(a == [0, 2, 0]);
});
it('invokes pattern.Cancelled for cancellations', () => {
let a = [0, 0, 0];
let ex = Task.task(r => {}).run();
ex.listen({
onCancelled: _ => a[0]++,
onRejected: b => a[1] += b,
onResolved: b => a[2] += b
});
ex.cancel();
$ASSERT(a == [1, 0, 0]);
});
});
describe('#promise()', () => {
it('Returns a resolved promise for successes', async () => {
let a = await Task.of(1).run().promise();
$ASSERT(a == 1);
});
it('Returns a rejected promise for rejections', async () => {
return Task.rejected(1).run().promise().catch(v => $ASSERT(v == 1));
});
it('Returns a rejected promise containing Cancelled for cancellations', async () => {
let ex = Task.task(r => {}).run();
ex.cancel();
return ex.promise().catch(v => $ASSERT(Cancelled.hasInstance(v)));
});
});
describe('#future()', () => {
property('Returns a resolved future for succeses', 'nat', (a) => {
return Task.of(a).run().future() ::eq(Future.of(a));
});
property('Returns a rejected future for failures', 'nat', (a) => {
return Task.rejected(a).run().future() ::eq(Future.rejected(a));
});
property('Returns a cancelled future for cancellations', () => {
let ex = Task.task(r => {}).run();
ex.cancel();
return ex.future() ::eq(cancelled());
});
});
});
describe('#fromNodeback', () => {
it('Returns the nodeback data after conversion to a task', async () => {
const fn = (str, str2, cb) => cb(null, str + str2 + 'processed');
const convertedFn = Task.fromNodeback(fn);
const task = convertedFn('test', '-was-');
const value = await task.run().promise();
$ASSERT(value === 'test-was-processed');
});
it('Returns the nodeback error after conversion to a task', async () => {
const error = 'failed';
const fn = (str, cb) => cb(error, '');
const convertedFn = Task.fromNodeback(fn);
const task = convertedFn('test');
await task.run().promise().catch(e => $ASSERT(e === error));
});
});
});