-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathabort.spec.js
More file actions
569 lines (451 loc) · 18.6 KB
/
Copy pathabort.spec.js
File metadata and controls
569 lines (451 loc) · 18.6 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
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
565
566
567
568
569
/* eslint-disable promise/prefer-await-to-then */
import { getEventListeners } from 'node:events';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import {
bufferedAsyncMap,
} from '../index.js';
import {
collectNextOutcomes,
expectSingleRejectionThenDone,
promisableTimeout,
yieldValuesOverTime,
} from './utils.js';
/**
* @param {number} delayBeforeFirstYield
* @returns {AsyncIterable<number>}
*/
async function * slowSource (delayBeforeFirstYield) {
await promisableTimeout(delayBeforeFirstYield);
yield 0;
await promisableTimeout(delayBeforeFirstYield);
yield 1;
await promisableTimeout(delayBeforeFirstYield);
yield 2;
}
/**
* Async generator whose `finally` block hangs forever — its `.return()`
* runs through the `finally` and never settles, modelling a source stuck
* in slow teardown.
*
* @returns {AsyncGenerator<number>}
*/
async function * wedgedSource () {
try {
yield 1;
yield 2;
} finally {
await new Promise(() => {}); // hung forever
}
}
chai.use(chaiAsPromised);
chai.use(sinonChai);
const should = chai.should();
describe('bufferedAsyncMap() options.signal', () => {
/** @type {import('sinon').SinonFakeTimers} */
let clock;
beforeEach(() => {
clock = sinon.useFakeTimers();
});
afterEach(() => {
sinon.restore();
});
// --- Validation ---
it('throws TypeError when signal is not an AbortSignal', () => {
should.Throw(() => {
bufferedAsyncMap(
yieldValuesOverTime(1, 100),
async (item) => item,
// @ts-expect-error
{ signal: 'not-a-signal' }
);
}, TypeError, 'Expected signal to be an AbortSignal');
});
it('omitting signal keeps plain iteration unchanged (no abort-wiring behavior leaks in)', async () => {
/** @type {number[]} */
const result = [];
const iterator = bufferedAsyncMap(yieldValuesOverTime(3, 100), async (item) => item);
const flow = (async () => {
for await (const v of iterator) result.push(v);
})();
await clock.runAllAsync();
await flow;
result.should.have.members([0, 1, 2]);
});
// --- Pre-aborted signal ---
it('pre-aborted signal: source.next never called, first .next() rejects with reason, subsequent return done', async () => {
const reason = new Error('Pre-aborted');
const ac = new AbortController();
ac.abort(reason);
const source = yieldValuesOverTime(6, 100);
const sourceIterator = source[Symbol.asyncIterator]();
const nextSpy = sinon.spy(sourceIterator, 'next');
const iterator = bufferedAsyncMap(
{ [Symbol.asyncIterator]: () => sourceIterator },
async (item) => item,
{ signal: ac.signal }
);
const first = iterator.next().catch(err => ({ rejectedWith: err }));
await clock.runAllAsync();
chai.expect(await first).to.deep.equal({ rejectedWith: reason });
nextSpy.should.not.have.been.called;
await iterator.next().should.eventually.deep.equal({ done: true, value: undefined });
await iterator.next().should.eventually.deep.equal({ done: true, value: undefined });
});
it('return() after pre-abort resolves done without throwing', async () => {
const ac = new AbortController();
ac.abort(new Error('Pre-aborted'));
const iterator = bufferedAsyncMap(
yieldValuesOverTime(3, 100),
async (item) => item,
{ signal: ac.signal }
);
const ret = iterator.return();
await clock.runAllAsync();
await ret.should.eventually.deep.equal({ done: true, value: undefined });
});
// --- Mid-iteration abort ---
it('parked .next() rejects with signal.reason (identity preserved)', async () => {
const reason = { custom: 'reason-object' };
const ac = new AbortController();
const iterator = bufferedAsyncMap(
slowSource(1000),
async (item) => item,
{ signal: ac.signal }
);
const parkedNext = iterator.next().catch(err => ({ rejectedWith: err }));
// Defer the abort to fire while the .next() is parked on the slow source.
setTimeout(() => ac.abort(reason), 10);
await clock.runAllAsync();
chai.expect(await parkedNext).to.deep.equal({ rejectedWith: reason });
});
it('exactly one .next() rejects with reason; subsequent calls return done', async () => {
const reason = new Error('Once');
const ac = new AbortController();
const iterator = bufferedAsyncMap(
yieldValuesOverTime(6, 100),
async (item) => item,
{ signal: ac.signal }
);
const first = iterator.next();
await clock.runAllAsync();
await first;
ac.abort(reason);
const sequence = collectNextOutcomes(iterator, 3);
await clock.runAllAsync();
const results = await sequence;
// The rejection lands on the very FIRST post-abort pull (stronger than
// the helper's exactly-once: no value may precede it).
chai.expect(results[0]).to.deep.equal({ rejected: true, value: reason });
expectSingleRejectionThenDone(results, reason);
});
it('source.next not called after abort; source.return called once', async () => {
const ac = new AbortController();
const source = yieldValuesOverTime(20, 100);
const sourceIterator = source[Symbol.asyncIterator]();
const nextSpy = sinon.spy(sourceIterator, 'next');
const returnSpy = sinon.spy(sourceIterator, 'return');
const iterator = bufferedAsyncMap(
{ [Symbol.asyncIterator]: () => sourceIterator },
async (item) => item,
{ signal: ac.signal, bufferSize: 2 }
);
const first = iterator.next();
await clock.runAllAsync();
await first;
const callsBeforeAbort = nextSpy.callCount;
ac.abort(new Error('stop'));
const next = iterator.next().catch(err => ({ rejectedWith: err }));
await clock.runAllAsync();
const r = await next;
should.exist(r);
// After the first rejecting .next() resolves, markAsEnded must have
// already run: source.return is called as part of the abort-delivery
// path, not deferred to the next consumer pull.
returnSpy.should.have.been.calledOnce;
// Drain any further calls (should be none).
await iterator.next();
await clock.runAllAsync();
nextSpy.callCount.should.equal(callsBeforeAbort);
returnSpy.should.have.been.calledOnce;
});
it('in-flight callbacks observe signal.aborted=true after external abort', async () => {
const ac = new AbortController();
/** @type {AbortSignal | undefined} */
let captured;
const iterator = bufferedAsyncMap(
yieldValuesOverTime(6, 100),
async (item, { signal }) => {
captured = signal;
return item;
},
{ signal: ac.signal }
);
const first = iterator.next();
await clock.runAllAsync();
await first;
chai.expect(captured?.aborted).to.equal(false);
ac.abort(new Error('stop'));
const n = iterator.next().catch(err => err);
await clock.runAllAsync();
await n;
chai.expect(captured?.aborted).to.equal(true);
});
// --- Close races ---
it('return() before abort makes subsequent .next() return done without throwing', async () => {
const ac = new AbortController();
const iterator = bufferedAsyncMap(
yieldValuesOverTime(6, 100),
async (item) => item,
{ signal: ac.signal }
);
const first = iterator.next();
await clock.runAllAsync();
await first;
const returned = iterator.return();
await clock.runAllAsync();
await returned;
ac.abort(new Error('late'));
const final = iterator.next();
await clock.runAllAsync();
await final.should.eventually.deep.equal({ done: true, value: undefined });
});
it('return() and abort fired together: cleanup runs once, no double-throw', async () => {
const ac = new AbortController();
// 200 items so the source is not naturally exhausted between consuming
// the first item and calling return() — that way markAsEnded actually
// has work to do on the source iterator.
const source = yieldValuesOverTime(200, 100);
const sourceIterator = source[Symbol.asyncIterator]();
const returnSpy = sinon.spy(sourceIterator, 'return');
const iterator = bufferedAsyncMap(
{ [Symbol.asyncIterator]: () => sourceIterator },
async (item) => item,
{ signal: ac.signal, bufferSize: 2 }
);
const first = iterator.next();
// Advance only enough for the first item to land, leaving the source live.
await clock.tickAsync(0);
await first;
const ret = iterator.return();
ac.abort(new Error('parallel'));
await clock.runAllAsync();
await ret;
returnSpy.should.have.been.calledOnce;
});
it('throw(err) after abort delivered behaves like throw on a closed iterator', async () => {
const ac = new AbortController();
const reason = new Error('aborted');
const tossed = new Error('post-abort throw');
const iterator = bufferedAsyncMap(
yieldValuesOverTime(6, 100),
async (item) => item,
{ signal: ac.signal }
);
const first = iterator.next();
await clock.runAllAsync();
await first;
ac.abort(reason);
const aborted = iterator.next().catch(err => err);
await clock.runAllAsync();
await aborted;
const tossedNext = iterator.throw(tossed).catch(err => ({ rejectedWith: err }));
await clock.runAllAsync();
chai.expect(await tossedNext).to.deep.equal({ rejectedWith: tossed });
});
// --- ordered:true coverage ---
it('abort works in ordered:true mode', async () => {
const ac = new AbortController();
const reason = new Error('ordered-abort');
const iterator = bufferedAsyncMap(
yieldValuesOverTime(6, 100),
async (item) => item,
{ signal: ac.signal, ordered: true }
);
const first = iterator.next();
await clock.runAllAsync();
await first;
ac.abort(reason);
const next = iterator.next().catch(err => ({ rejectedWith: err }));
await clock.runAllAsync();
chai.expect(await next).to.deep.equal({ rejectedWith: reason });
const after = iterator.next();
await clock.runAllAsync();
await after.should.eventually.deep.equal({ done: true, value: undefined });
});
// This deterministic 11-offset sweep is the regression PIN for the
// drain-race identity contract; test/properties.spec.js's abort property
// is the accumulating SEARCH over the surrounding geometry (same
// commit-point oracle). Neither replaces the other — keep both.
it('delivers exactly one rejection when an abort races the drain-throw, with the winner owning the identity', async () => {
// The window: fail-eventually captured an error and the buffer drained;
// an external abort landing in the await-gap between error capture and
// the drain-throw commits a shutdown race. The guard's observable
// defect when reverted is rejection IDENTITY, not count (the
// closed-iterator suppression keeps the total at one either way): the
// abort reason would lose to the captured callback error despite
// winning the commit race.
//
// The commit-point oracle is the per-callback signal's reason:
// requestConsumerAbort writes the external reason; a plain close aborts
// the internal controller bare (default AbortError); whichever aborts
// first wins, and the reason is immutable afterwards. Observed
// abort-vs-rejection ORDER is NOT a valid oracle — the rejection
// settles many microtasks after the commit, so an abort can fire first
// and still correctly lose.
for (let hops = 0; hops <= 10; hops++) {
const ac = new AbortController();
const reason = new Error(`abort-at-${hops}`);
const cbError = new Error(`cb-${hops}`);
/** @type {AbortSignal | undefined} */
let capturedSignal;
const iterator = bufferedAsyncMap(['only'], async (_item, { signal }) => {
capturedSignal = signal;
throw cbError;
}, {
bufferSize: 1,
signal: ac.signal,
});
// Land the abort behind `hops` microtask boundaries — varying points
// inside nextValue's internal await chain.
const abortTask = (async () => {
for (let i = 0; i < hops; i++) {
await Promise.resolve();
}
ac.abort(reason);
})();
const outcomes = await collectNextOutcomes(iterator, 3);
await abortTask;
const rejections = outcomes.filter(o => o.rejected);
rejections.should.have.length(1, `offset ${hops} saw ${rejections.length} rejections`);
// Sampled after settlement: the signal's reason is the immutable
// record of which side committed the shutdown first.
const abortWon = capturedSignal?.aborted === true && capturedSignal.reason === reason;
const expected = abortWon ? reason : cbError;
chai.expect(rejections[0]?.value).to.equal(
expected,
`offset ${hops}: abortWon=${abortWon}, expected ${/** @type {Error} */ (expected).message}`
);
const firstReject = outcomes.findIndex(o => o.rejected);
for (const o of outcomes.slice(firstReject + 1)) {
o.should.deep.equal({ rejected: false, value: { done: true, value: undefined } });
}
}
});
it('suppresses an undelivered abort once the consumer explicitly closes via return()', async () => {
const ac = new AbortController();
const iterator = bufferedAsyncMap(['a', 'b', 'c'], async (item) => item, { signal: ac.signal });
await iterator.next();
// Abort fires between pulls (no next() pending), but the consumer
// reacts by closing the iterator instead of pulling again.
ac.abort(new Error('stale'));
await iterator.return().should.eventually.deep.equal({ done: true, value: undefined });
// Native AsyncGenerator semantics: next() after return() is done —
// pre-fix this rejected with the stale abort reason through a closed
// iterator.
await iterator.next().should.eventually.deep.equal({ done: true, value: undefined });
});
it('suppresses an undelivered abort once the consumer explicitly closes via throw()', async () => {
const ac = new AbortController();
const consumerError = new Error('consumer-throw');
const iterator = bufferedAsyncMap(['a', 'b'], async (item) => item, { signal: ac.signal });
await iterator.next();
ac.abort(new Error('stale'));
const thrown = await iterator.throw(consumerError).catch(err => ({ rejectedWith: err }));
chai.expect(thrown).to.deep.equal({ rejectedWith: consumerError });
await iterator.next().should.eventually.deep.equal({ done: true, value: undefined });
});
it('suppresses a pre-aborted signal once the consumer closes before pulling', async () => {
const ac = new AbortController();
ac.abort(new Error('pre-aborted'));
const iterator = bufferedAsyncMap(['a'], async (item) => item, { signal: ac.signal });
await iterator.return().should.eventually.deep.equal({ done: true, value: undefined });
await iterator.next().should.eventually.deep.equal({ done: true, value: undefined });
});
// --- external-signal listener lifecycle ---
it('detaches its external-signal abort listener when the iterator closes', async () => {
const ac = new AbortController();
// Several sequential short-lived iterators sharing one long-lived signal —
// the standard server pattern. Each must remove its listener on close
// (natural drain and early return() alike), or the signal retains every
// closed iterator's state machine until the signal itself aborts / is GC'd.
for (let i = 0; i < 5; i++) {
const iterator = bufferedAsyncMap(['a', 'b'], async (item) => item, { signal: ac.signal });
getEventListeners(ac.signal, 'abort').length.should.equal(1);
if (i % 2 === 0) {
// Timer-free array source, so the inline for-await is safe under fake timers
// eslint-disable-next-line no-unused-vars, no-empty
for await (const _value of iterator) {}
} else {
await iterator.return();
}
}
getEventListeners(ac.signal, 'abort').length.should.equal(0);
});
// --- cleanupTimeout ---
it('cleanupTimeout caps the wait for a wedged source.return()', async () => {
const ac = new AbortController();
const reason = new Error('abort');
const iterator = bufferedAsyncMap(
wedgedSource(),
async (item) => item,
{ signal: ac.signal, bufferSize: 1, cleanupTimeout: 50 }
);
const first = iterator.next();
await clock.runAllAsync();
await first;
ac.abort(reason);
const next = iterator.next().catch(err => ({ rejectedWith: err }));
// Advance past the cleanupTimeout — without it the parked .next() would
// hang on markAsEnded forever.
await clock.tickAsync(60);
chai.expect(await next).to.deep.equal({ rejectedWith: reason });
});
it('cleanupTimeout clears its timer when cleanup wins the race', async () => {
// A well-behaved source whose .return() settles promptly: cleanup wins the
// race well before cleanupTimeout. The timer must be cleared, not left
// pending — otherwise it keeps the event loop alive for the full window
// after the iterator has already closed.
const timersBefore = clock.countTimers();
const iterator = bufferedAsyncMap(
['a', 'b', 'c'],
async (item) => item,
{ bufferSize: 1, cleanupTimeout: 100_000 }
);
const first = iterator.next();
await clock.runAllAsync();
await first;
// Close the iterator. The source's .return() resolves via microtasks, so
// the race settles without the clock ever reaching cleanupTimeout.
await iterator.return();
// No leftover timer: the 100s cleanupTimeout was cleared in markAsEnded's
// finally. Asserted as a delta against the pre-construction count so the
// spec pins "close leaves no timer behind", not "nothing else in the
// process owns a timer right now".
(clock.countTimers() - timersBefore).should.equal(0);
});
it('default (no cleanupTimeout) still waits forever for a wedged source', async () => {
// Sanity check that the unbounded default behaviour is preserved when
// the option is left undefined.
const ac = new AbortController();
const iterator = bufferedAsyncMap(
wedgedSource(),
async (item) => item,
{ signal: ac.signal, bufferSize: 1 }
);
const first = iterator.next();
await clock.runAllAsync();
await first;
ac.abort(new Error('abort'));
// Race the next() against a finite tick. Without the option, the
// parked next() never settles because markAsEnded awaits the wedged
// source.return().
let settled = false;
const next = iterator.next().finally(() => { settled = true; });
next.catch(() => {}); // attach a no-op handler — we never await it
await clock.tickAsync(10_000);
settled.should.equal(false);
});
});