Offload functions to worker threads with shared memory primitives for Node.js.
8
fork

Configure Feed

Select the types of activity you want to include in your feed.

at e2cebd539403475e2f4e79d55ca1a84a0ce3510d 60 lines 2.0 kB view raw
1import { setTimeout } from 'node:timers/promises'; 2import { describe, it } from 'node:test'; 3import assert from 'node:assert/strict'; 4import { workers } from 'moroutine'; 5import { slowTask, waitForAbort, slowStream } from './fixtures/async-dispose.ts'; 6 7describe('async dispose', () => { 8 it('waits for in-flight tasks to complete', async () => { 9 const run = workers(1); 10 const promise = run(slowTask(100)); 11 await run[Symbol.asyncDispose](); 12 const result = await promise; 13 assert.equal(result, 'done'); 14 }); 15 16 it('fires signal on async dispose', async () => { 17 const run = workers(1); 18 const promise = run(waitForAbort(run.signal)); 19 await run[Symbol.asyncDispose](); 20 const result = await promise; 21 assert.equal(result, 'aborted'); 22 }); 23 24 it('fires signal on sync dispose', async () => { 25 const run = workers(1); 26 assert.equal(run.signal.aborted, false); 27 run[Symbol.dispose](); 28 assert.equal(run.signal.aborted, true); 29 }); 30 31 it('rejects new tasks after async dispose starts', async () => { 32 const run = workers(1); 33 await run[Symbol.asyncDispose](); 34 await assert.rejects(() => run(slowTask(10)), { message: /disposed/ }); 35 }); 36 37 it('force-terminates after shutdownTimeout', async () => { 38 const run = workers(1, { shutdownTimeout: 50 }); 39 run(slowTask(10_000)); // will not finish in time 40 const start = performance.now(); 41 await run[Symbol.asyncDispose](); 42 const elapsed = performance.now() - start; 43 assert.ok(elapsed < 500, `Expected fast teardown, took ${elapsed}ms`); 44 }); 45 46 it('waits for streaming task to finish', async () => { 47 const run = workers(1); 48 const results: number[] = []; 49 const iterating = (async () => { 50 for await (const n of run(slowStream(5))) { 51 results.push(n); 52 } 53 })(); 54 // Let a couple items flow before disposing 55 await setTimeout(60); 56 await run[Symbol.asyncDispose](); 57 await iterating; 58 assert.equal(results.length, 5); 59 }); 60});