Skip to content

Commit 111e06f

Browse files
committed
fix(ios-snapshot): end a detached wait the answer already settled
`value()` raced the attempt against the caller's wait and left the loser running. A capture answered by the attempt still held its timer and abort listener until the budget ran out — 1.5 s for discovery, 2 s for preparation — so a poll loop could stack one pending timer and one listener per capture. The `awaitDiscovery` it replaced cleared both in a `finally`. `wait` now takes a per-call stop signal that `value()` aborts in a `finally`, and both owners release their timer and listener on it: `waitForDiscoveryAttempt` resolves, and `waitForSnapshotSourceDelay` grows an optional `stop` that ends the sleep without spending the deadline it is measured against. Waiting inside the caller's own deadline still matters, so a client abort keeps rejecting with the typed cancellation; the stop only ever lands after the race is already decided, which is why the losing wait resolves rather than rejecting, and why the race keeps a handler of its own.
1 parent 506fb18 commit 111e06f

6 files changed

Lines changed: 122 additions & 6 deletions

File tree

‎packages/platform-apple/src/detached-attempt.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,45 @@ test('an attempt that throws before awaiting is reported as its own failure', as
210210
);
211211
});
212212

213+
test('a caller answered by the attempt stops the wait it left running', async () => {
214+
const attempts = createDetachedAttempts<string>({ waitMs: 60_000 });
215+
let releaseBuild: (value: string) => void = () => {};
216+
const building = new Promise<string>((resolve) => {
217+
releaseBuild = resolve;
218+
});
219+
let stopSignal: AbortSignal | undefined;
220+
let waitState: 'pending' | 'resolved' = 'pending';
221+
222+
const caller = attempts.value('bridge', {
223+
start: () => building,
224+
// Deliberately has no timer of its own: only the stop can end it, so a wait that is never
225+
// stopped stays observable as `pending` instead of quietly expiring.
226+
wait: (_waitMs, stop) => {
227+
stopSignal = stop;
228+
return new Promise<void>((resolve) => {
229+
stop.addEventListener(
230+
'abort',
231+
() => {
232+
waitState = 'resolved';
233+
resolve();
234+
},
235+
{ once: true },
236+
);
237+
});
238+
},
239+
pending: () => PENDING,
240+
});
241+
242+
await settle();
243+
assert.equal(waitState, 'pending');
244+
releaseBuild('binary');
245+
assert.equal(await caller, 'binary');
246+
await settle();
247+
248+
assert.ok(stopSignal?.aborted, 'the losing wait is stopped once the attempt settles');
249+
assert.equal(waitState, 'resolved');
250+
});
251+
213252
function identity(error: unknown): unknown {
214253
return error;
215254
}

‎packages/platform-apple/src/detached-attempt.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,11 @@ export type DetachedAttempts<Value> = Readonly<{
3030
/**
3131
* Sleeps inside the caller's own deadline, so a client abort rejects this call with the
3232
* caller's typed cancellation instead of reporting a fresh `pending`.
33+
*
34+
* `stop` is aborted as soon as this caller has its answer from somewhere else; the wait has to
35+
* release its timer and listeners then and resolve, since nobody is racing it any more.
3336
*/
34-
wait: (waitMs: number) => Promise<void>;
37+
wait: (waitMs: number, stop: AbortSignal) => Promise<void>;
3538
pending: () => Error;
3639
}>,
3740
): Promise<Value>;
@@ -136,7 +139,16 @@ export function createDetachedAttempts<Value>(
136139
if (attempt.status === 'pending' && (waitGrant === 'every-caller' || !attempt.waitSpent)) {
137140
// Marked before waiting: two captures arriving together must not each spend the budget.
138141
attempt.waitSpent = true;
139-
await Promise.race([attempt.settled, params.wait(deps.waitMs)]);
142+
const stopWaiting = new AbortController();
143+
const waiting = params.wait(deps.waitMs, stopWaiting.signal);
144+
// A wait can still reject after it lost the race, e.g. a client aborting in the moment
145+
// between the attempt settling and this call returning; nobody awaits it by then.
146+
waiting.catch(() => {});
147+
try {
148+
await Promise.race([attempt.settled, waiting]);
149+
} finally {
150+
stopWaiting.abort();
151+
}
140152
}
141153
if (attempt.status === 'ready') return attempt.value;
142154
if (attempt.status === 'failed') throw attempt.error;
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import assert from 'node:assert/strict';
2+
import { test } from 'vitest';
3+
import { createSnapshotSourceDeadline, waitForSnapshotSourceDelay } from './deadline.ts';
4+
import { SnapshotSourceError } from './errors.ts';
5+
6+
const WAIT_CODE = 'bridge-preparation-pending';
7+
8+
test('a stopped delay returns without spending the rest of the deadline', async () => {
9+
const stop = new AbortController();
10+
const deadline = createSnapshotSourceDeadline(60_000, undefined);
11+
const waiting = waitForSnapshotSourceDelay(deadline, 60_000, WAIT_CODE, stop.signal);
12+
13+
const startedAt = Date.now();
14+
stop.abort();
15+
await waiting;
16+
assert.ok(Date.now() - startedAt < 5_000, 'a stopped wait does not sleep out its budget');
17+
});
18+
19+
test('a delay started with its stop already aborted does not sleep', async () => {
20+
const stop = new AbortController();
21+
stop.abort();
22+
const deadline = createSnapshotSourceDeadline(60_000, undefined);
23+
24+
const startedAt = Date.now();
25+
await waitForSnapshotSourceDelay(deadline, 60_000, WAIT_CODE, stop.signal);
26+
assert.ok(Date.now() - startedAt < 5_000);
27+
});
28+
29+
test('an aborted caller signal stays typed cancellation next to a stop', async () => {
30+
const caller = new AbortController();
31+
const deadline = createSnapshotSourceDeadline(60_000, caller.signal);
32+
const waiting = waitForSnapshotSourceDelay(
33+
deadline,
34+
60_000,
35+
WAIT_CODE,
36+
new AbortController().signal,
37+
);
38+
39+
caller.abort();
40+
await assert.rejects(waiting, (error: unknown) => {
41+
assert.ok(error instanceof SnapshotSourceError);
42+
assert.equal(error.failureKind, 'cancelled');
43+
assert.equal(error.failureCode, 'abort-signal');
44+
return true;
45+
});
46+
});

‎packages/platform-apple/src/snapshot-source/deadline.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,16 @@ export function remainingSnapshotSourceMs(deadline: SnapshotSourceDeadline, code
2424
return Math.max(1, Math.floor(remainingMs));
2525
}
2626

27+
/**
28+
* Sleeps inside the caller's own deadline. `stop` is for a caller that no longer needs the sleep
29+
* because the work it was waiting on answered elsewhere: the delay resolves instead of burning its
30+
* remaining budget, while an aborted `deadline` stays a typed `cancelled`.
31+
*/
2732
export async function waitForSnapshotSourceDelay(
2833
deadline: SnapshotSourceDeadline,
2934
requestedMs: number,
3035
code: string,
36+
stop?: AbortSignal,
3137
): Promise<void> {
3238
const delayMs = Math.min(requestedMs, remainingSnapshotSourceMs(deadline, code));
3339
await new Promise<void>((resolve, reject) => {
@@ -36,14 +42,18 @@ export async function waitForSnapshotSourceDelay(
3642
const onAbort = () => {
3743
finish(() => reject(snapshotSourceError('cancelled', 'abort-signal')));
3844
};
45+
const onStop = () => finish(resolve);
3946
const finish = (action: () => void) => {
4047
if (settled) return;
4148
settled = true;
4249
clearTimeout(timer);
4350
deadline.signal?.removeEventListener('abort', onAbort);
51+
stop?.removeEventListener('abort', onStop);
4452
action();
4553
};
54+
if (stop?.aborted) return finish(resolve);
4655
deadline.signal?.addEventListener('abort', onAbort, { once: true });
4756
if (deadline.signal?.aborted) onAbort();
57+
stop?.addEventListener('abort', onStop, { once: true });
4858
});
4959
}

‎packages/platform-apple/src/snapshot-source/preparation.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ export function createSnapshotBridgePreparation(
119119
start: (signal) => build(runtime, signal),
120120
// Waiting inside the request's own deadline keeps a genuine client abort typed
121121
// `cancelled`: only a preparation that is simply still running is reported as `preparing`.
122-
wait: (waitMs) => waitForSnapshotSourceDelay(deadline, waitMs, code),
122+
wait: (waitMs, stop) => waitForSnapshotSourceDelay(deadline, waitMs, code, stop),
123123
pending: () => snapshotSourceError('preparing', 'bridge-preparation-pending'),
124124
});
125125
},

‎packages/platform-apple/src/snapshot-target.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,26 +59,35 @@ export function createSimulatorSnapshotTargetResolver(): SimulatorSnapshotTarget
5959
targets.set(key, target);
6060
return target;
6161
},
62-
wait: (waitMs) => waitForDiscoveryAttempt(waitMs, signal),
62+
wait: (waitMs, stop) => waitForDiscoveryAttempt(waitMs, signal, stop),
6363
pending: () => targetError('simulator-target-discovery-pending', device, appBundleId),
6464
});
6565
};
6666
}
6767

6868
/**
6969
* One caller's wait for a discovery it did not start. Resolving is the wait being spent, not the
70-
* discovery failing: a client abort rejects with its own reason so it stays typed `cancelled`.
70+
* discovery failing: a client abort rejects with its own reason so it stays typed `cancelled`, while
71+
* `stop` means this caller already has its answer and is only letting go of the timer.
7172
*/
72-
function waitForDiscoveryAttempt(waitMs: number, signal: AbortSignal): Promise<void> {
73+
function waitForDiscoveryAttempt(
74+
waitMs: number,
75+
signal: AbortSignal,
76+
stop: AbortSignal,
77+
): Promise<void> {
7378
return new Promise<void>((resolve, reject) => {
7479
const onAbort = () => finish(() => reject(signal.reason));
80+
const onStop = () => finish(resolve);
7581
const timer = setTimeout(() => finish(resolve), waitMs);
7682
function finish(settle: () => void): void {
7783
clearTimeout(timer);
7884
signal.removeEventListener('abort', onAbort);
85+
stop.removeEventListener('abort', onStop);
7986
settle();
8087
}
88+
if (stop.aborted) return finish(resolve);
8189
signal.addEventListener('abort', onAbort, { once: true });
90+
stop.addEventListener('abort', onStop, { once: true });
8291
});
8392
}
8493

0 commit comments

Comments
 (0)