Skip to content

Commit ca2044f

Browse files
authored
Share internal cancellation and deadline mechanisms (#155)
Cancellation-aware waits and deadlines repeated listener registration, first-settlement guards, and timer cleanup across byte collection, JSON-RPC, DNS, HTTP/3, HTTP client deadlines, and the load runner. Add private `internal:abort` mechanisms for disposable subscriptions, cancellation-aware waits, and owned parent/deadline scopes, then adopt them in those callers. Cancellation retains the exact reason and safely observes late outcomes; resource closure, RPC cancellation messages, and protocol error translation stay in their adapters. JSON-RPC also now cleans up pending calls when transport send throws synchronously. Validation: - Generic regression tests cover disposal, already-aborted signals, exact reasons, success/failure cleanup, synchronous abort, late rejection, deadline expiry, and parent/timer ownership. - The synchronous-send RPC regression failed before the migration and passes after it. - Focused byte, RPC, DNS, HTTP client, HTTP/3, and load suites passed. - Full macOS CI-mode suite: `FINO_REQUIRE_SQLITE=1 ./target/debug/fino test --parallel tests` — 1,006 passed, 4 skipped (1,010 groups). - Formatting, runtime lint, Rust formatting/clippy, Rust tests, and diff checks passed. TypeScript checking retains repository baseline errors with no additional normalized diagnostics. - Linux and opt-in external conformance suites were not run locally. Performance was not benchmarked. <!-- codesmith:footer --> --- <a href="https://app.blacksmith.sh/Sequins-dev/codesmith/fino/pr/155?autoLogin=true&ref=codesmith_pr_footer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://pr-comments-assets.blacksmith.sh/codesmith/view-with-codesmith-dark-v3.svg"><source media="(prefers-color-scheme: light)" srcset="https://pr-comments-assets.blacksmith.sh/codesmith/view-with-codesmith-light-v3.svg"><img alt="View with [code]smith" src="https://pr-comments-assets.blacksmith.sh/codesmith/view-with-codesmith-dark-v3.svg"></picture></a> <a href="https://backend.blacksmith.sh/track/enable-autofix?expires=1794228914&installation_model_id=429094&pr_number=155&ref=codesmith_pr_footer&repository=Sequins-dev%2Ffino&return_to=https%3A%2F%2Fgithub.com%2FSequins-dev%2Ffino%2Fpull%2F155&signature=d07ad353061a3e89f714da5877917387feb9ada619e30137514540dc0ee95e9e"><picture><source media="(prefers-color-scheme: dark)" srcset="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-light.svg"><img alt="Autofix with [code]smith" src="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-dark.svg"></picture></a> <sup>Need help on this PR? Tag <code>@codesmith-bot</code> with what you need. Autofix is disabled.</sup> <!-- codesmith:autofix:disabled --> <!-- /codesmith:footer -->
1 parent b5526e4 commit ca2044f

11 files changed

Lines changed: 439 additions & 116 deletions

File tree

‎js/internal/abort.ts‎

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
/**
2+
* internal:abort — disposable cancellation subscriptions, waits, and deadlines.
3+
*
4+
* These Realm-local mechanisms retain AbortSignal's reason and compose with
5+
* caller-owned resource policy. Rejecting a wait does not stop its operation;
6+
* callers must cancel or close underlying work themselves. Disposal removes
7+
* subscriptions and timers without aborting the signal or operation.
8+
*
9+
* @internal
10+
*/
11+
12+
/** Minimal structural signal contract shared by runtime and native signal adapters. */
13+
export interface AbortSource {
14+
readonly aborted: boolean;
15+
readonly reason: unknown;
16+
addEventListener(type: string, callback: () => void, options?: { once?: boolean }): void;
17+
removeEventListener(type: string, callback: () => void): void;
18+
}
19+
20+
/**
21+
* Subscribe once, removing the listener before invoking `callback`.
22+
* Already-aborted signals invoke it immediately. Missing signals do nothing.
23+
* The returned disposer is idempotent; callback exceptions propagate normally.
24+
*/
25+
export function onAbort(
26+
signal: AbortSource | null | undefined,
27+
callback: (reason: unknown) => void,
28+
): () => void {
29+
if (!signal) return () => {};
30+
let disposed = false;
31+
const dispose = () => {
32+
if (disposed) return;
33+
disposed = true;
34+
signal.removeEventListener('abort', abort);
35+
};
36+
const abort = () => {
37+
if (disposed) return;
38+
dispose();
39+
callback(signal.reason);
40+
};
41+
if (signal.aborted) {
42+
disposed = true;
43+
callback(signal.reason);
44+
} else {
45+
signal.addEventListener('abort', abort, { once: true });
46+
if (signal.aborted) abort();
47+
}
48+
return dispose;
49+
}
50+
51+
/**
52+
* Invoke `operation` unless already aborted and wait for its result or abort.
53+
* Both late fulfillment and rejection are observed after cancellation, avoiding
54+
* unhandled rejection. All settlement paths remove the abort subscription.
55+
* The operation starts synchronously; active cancellation is caller-owned.
56+
*/
57+
export function withAbort<T>(
58+
operation: () => T | PromiseLike<T>,
59+
signal?: AbortSource | null,
60+
): Promise<T> {
61+
if (signal?.aborted) return Promise.reject(signal.reason);
62+
return new Promise<T>((resolve, reject) => {
63+
let settled = false;
64+
let dispose = () => {};
65+
const settle = (success: boolean, value: unknown) => {
66+
if (settled) return;
67+
settled = true;
68+
dispose();
69+
if (success) resolve(value as T);
70+
else reject(value);
71+
};
72+
dispose = onAbort(signal, (reason) => settle(false, reason));
73+
if (settled) {
74+
dispose();
75+
return;
76+
}
77+
try {
78+
Promise.resolve(operation()).then(
79+
(value) => settle(true, value),
80+
(reason) => settle(false, reason),
81+
);
82+
} catch (error) {
83+
settle(false, error);
84+
}
85+
});
86+
}
87+
88+
/** Deadline configuration. The default scheduler uses Realm-owned timers. */
89+
export interface AbortScopeOptions {
90+
/** Parent signal whose cancellation is forwarded with its exact reason. */
91+
signal?: AbortSource | null;
92+
/** Optional finite non-negative delay in milliseconds. */
93+
timeoutMs?: number;
94+
/** Reason for expiry; defaults to a TimeoutError DOMException. */
95+
timeoutReason?: unknown;
96+
/** Schedule an asynchronous callback and return its idempotent cancellation. */
97+
schedule?: (callback: () => void, delayMs: number) => () => void;
98+
}
99+
100+
/** Owned signal plus cleanup; neither this object nor its resources cross Realms. */
101+
export interface AbortScope {
102+
/** Signal aborted by the parent, deadline, or explicit abort. */
103+
signal: AbortSignal;
104+
/** Abort with `reason` and release all owned subscriptions and timers. */
105+
abort(reason?: unknown): void;
106+
/** Release resources without aborting. Repeated calls are safe. */
107+
dispose(): void;
108+
}
109+
110+
/**
111+
* Create an owned cancellation scope linked to an optional parent and deadline.
112+
* The first abort reason wins. Expiry, parent cancellation, explicit abort, and
113+
* disposal release the timer and parent subscription. A pre-aborted parent
114+
* prevents scheduling the timer. Disposed signals can still be aborted explicitly.
115+
*/
116+
export function abortScope(options: AbortScopeOptions = {}): AbortScope {
117+
const delay = options.timeoutMs;
118+
if (delay !== undefined && (!Number.isFinite(delay) || delay < 0))
119+
throw new RangeError('timeoutMs must be finite and non-negative');
120+
const controller = new AbortController();
121+
let disposed = false;
122+
let parent = () => {};
123+
let timer = () => {};
124+
let own = () => {};
125+
const dispose = () => {
126+
if (disposed) return;
127+
disposed = true;
128+
own();
129+
parent();
130+
timer();
131+
};
132+
own = onAbort(controller.signal, dispose);
133+
parent = onAbort(options.signal, (reason) => controller.abort(reason));
134+
if (disposed) parent();
135+
if (!disposed && delay !== undefined) {
136+
const schedule =
137+
options.schedule ??
138+
((callback: () => void, ms: number) => {
139+
const handle = setTimeout(callback, ms);
140+
return () => clearTimeout(handle);
141+
});
142+
try {
143+
timer = schedule(
144+
() =>
145+
controller.abort(
146+
options.timeoutReason === undefined
147+
? new DOMException('The operation timed out.', 'TimeoutError')
148+
: options.timeoutReason,
149+
),
150+
delay,
151+
);
152+
if (disposed) timer();
153+
} catch (error) {
154+
dispose();
155+
throw error;
156+
}
157+
}
158+
return { signal: controller.signal, abort: (reason) => controller.abort(reason), dispose };
159+
}

‎js/internal/bytes.ts‎

Lines changed: 2 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
* @internal
3636
*/
3737

38+
import { withAbort } from 'internal:abort';
3839
import { AbortSignal } from '../globals/abort.ts';
3940

4041
type ByteSource = ArrayBuffer | ArrayBufferView;
@@ -169,42 +170,7 @@ function pullWithSignal(
169170
iterator: Iterator<Uint8Array> | AsyncIterator<Uint8Array>,
170171
signal: AbortSignal | undefined,
171172
): Promise<IteratorResult<Uint8Array>> {
172-
if (signal === undefined) return Promise.resolve(iterator.next());
173-
throwIfAborted(signal);
174-
175-
return new Promise((resolve, reject) => {
176-
let settled = false;
177-
const beginSettle = (): boolean => {
178-
if (settled) return false;
179-
settled = true;
180-
signal.removeEventListener('abort', onAbort);
181-
return true;
182-
};
183-
const onAbort = (): void => {
184-
if (beginSettle()) reject(signal.reason);
185-
};
186-
signal.addEventListener('abort', onAbort, { once: true });
187-
if (signal.aborted) {
188-
onAbort();
189-
return;
190-
}
191-
192-
let next: IteratorResult<Uint8Array> | PromiseLike<IteratorResult<Uint8Array>>;
193-
try {
194-
next = iterator.next();
195-
} catch (error) {
196-
if (beginSettle()) reject(error);
197-
return;
198-
}
199-
Promise.resolve(next).then(
200-
(result) => {
201-
if (beginSettle()) resolve(result);
202-
},
203-
(error) => {
204-
if (beginSettle()) reject(error);
205-
},
206-
);
207-
});
173+
return withAbort(() => iterator.next(), signal);
208174
}
209175

210176
/**

‎js/internal/load.ts‎

Lines changed: 16 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
*
1414
* @internal
1515
*/
16+
import { abortScope, onAbort } from 'internal:abort';
1617
import { HttpClient } from '../net/http/client.ts';
1718
import type { HttpResponse } from '../net/http/client.ts';
1819
import { Headers } from '../net/http/index.ts';
@@ -488,28 +489,20 @@ class LoadRecorder {
488489
}
489490

490491
function phaseSignal(parent: AbortSignal | null, durationMs: number | null): PhaseSignal {
491-
const controller = new AbortController();
492-
const abortFromParent = () => controller.abort(parent?.reason);
493-
if (parent?.aborted) abortFromParent();
494-
else parent?.addEventListener('abort', abortFromParent, { once: true });
495-
const deadline = durationMs === null ? null : performance.now() + durationMs;
496-
const timer =
497-
durationMs === null
498-
? null
499-
: setTimeout(
500-
() => controller.abort(new Error('fino load: measured phase ended')),
501-
Math.max(0, durationMs),
502-
);
492+
const scope = abortScope({
493+
signal: parent,
494+
...(durationMs === null
495+
? {}
496+
: {
497+
timeoutMs: Math.max(0, durationMs),
498+
timeoutReason: new Error('fino load: measured phase ended'),
499+
}),
500+
});
503501
return {
504-
signal: controller.signal,
505-
deadline,
506-
abort(reason?: unknown) {
507-
controller.abort(reason);
508-
},
509-
close() {
510-
if (timer !== null) clearTimeout(timer);
511-
parent?.removeEventListener('abort', abortFromParent);
512-
},
502+
signal: scope.signal,
503+
deadline: durationMs === null ? null : performance.now() + durationMs,
504+
abort: scope.abort,
505+
close: scope.dispose,
513506
};
514507
}
515508

@@ -854,8 +847,7 @@ export async function runLoadEngine(rawOptions: LoadOptions): Promise<LoadResult
854847
});
855848
const runController = new AbortController();
856849
const abortFromParent = () => runController.abort(options.signal?.reason);
857-
if (options.signal?.aborted) abortFromParent();
858-
else options.signal?.addEventListener('abort', abortFromParent, { once: true });
850+
const stopParent = onAbort(options.signal, abortFromParent);
859851
let reconnectGate = Promise.resolve();
860852
const maybeReconnect = async (sequence: number): Promise<void> => {
861853
if (
@@ -965,7 +957,7 @@ export async function runLoadEngine(rawOptions: LoadOptions): Promise<LoadResult
965957
bailout: recorder.bailoutReason,
966958
};
967959
} finally {
968-
options.signal?.removeEventListener('abort', abortFromParent);
960+
stopParent();
969961
await reconnectGate;
970962
await client.close();
971963
}

‎js/internal/net/http/h3/client.ts‎

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
*
5656
* @internal
5757
*/
58+
import { withAbort } from 'internal:abort';
5859
import { DEFAULT_MAX_FIELD_SECTION_SIZE, Nghttp3Session, h3FieldSize } from './session.ts';
5960
import type { H3BodySource, H3SessionCallbacks, H3SessionOptions } from './session.ts';
6061
import { H3BodyQueue } from './body-queue.ts';
@@ -78,22 +79,10 @@ const EARLY_DATA_SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE']);
7879

7980
async function waitForHandshake(conn: QuicConnection, signal?: AbortSignal | null): Promise<void> {
8081
if (conn.handshakeComplete) return;
81-
if (signal?.aborted) throw abortError(signal.reason);
82-
if (signal === undefined || signal === null) {
83-
await conn[quicConnectionInternals.waitHandshake]();
84-
return;
85-
}
86-
let onAbort!: () => void;
8782
try {
88-
await Promise.race([
89-
conn[quicConnectionInternals.waitHandshake](),
90-
new Promise<never>((_, reject) => {
91-
onAbort = () => reject(abortError(signal.reason));
92-
signal.addEventListener('abort', onAbort, { once: true });
93-
}),
94-
]);
95-
} finally {
96-
signal.removeEventListener('abort', onAbort);
83+
await withAbort(() => conn[quicConnectionInternals.waitHandshake](), signal);
84+
} catch (error) {
85+
throw signal?.aborted ? abortError(signal.reason) : error;
9786
}
9887
}
9988
/**

‎js/jsonrpc.ts‎

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
* await server.ready;
5050
* ```
5151
*/
52+
import { onAbort, withAbort } from 'internal:abort';
5253
import { serveHttp } from 'fino:net/http/server';
5354
import type { ServeServer } from 'fino:net/http/server';
5455
import { compile } from 'fino:validate';
@@ -679,19 +680,19 @@ export class JsonRpcPeer {
679680
};
680681
if (params !== undefined) body.params = params;
681682
return new Promise((resolve, reject) => {
682-
const onAbort = () => {
683+
const cancel = (reason: unknown) => {
683684
if (!this.#pending.delete(id)) return;
684685
void this.notify('$/cancel_request', { requestId: id }).catch(() => {});
685-
reject(opts.signal!.reason);
686+
reject(reason);
686687
};
687-
const cleanup = () => opts.signal?.removeEventListener('abort', onAbort);
688-
opts.signal?.addEventListener('abort', onAbort, { once: true });
689-
this.#pending.set(id, {
690-
resolve,
691-
reject,
692-
cleanup,
693-
});
694-
Promise.resolve(this.#transport.send(JSON.stringify(body))).catch((error) => {
688+
const pending = { resolve, reject, cleanup: () => {} };
689+
this.#pending.set(id, pending);
690+
pending.cleanup = onAbort(opts.signal, cancel);
691+
if (!this.#pending.has(id)) {
692+
pending.cleanup();
693+
return;
694+
}
695+
withAbort(() => this.#transport.send(JSON.stringify(body))).catch((error) => {
695696
const pending = this.#pending.get(id);
696697
if (!pending) return;
697698
this.#pending.delete(id);

‎js/net/dns.ts‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@
154154
* const addresses = await resolver.resolve('example.com', 'A');
155155
* ```
156156
*/
157+
import { onAbort } from 'internal:abort';
157158
import * as sock from './socket.ts';
158159
import * as loop from '../internal/runtime/loop.ts';
159160
import { DiskFileSystem } from '../file/fs.ts';
@@ -2340,16 +2341,11 @@ function _abortPromise(signal: AbortSignal): {
23402341
promise: Promise<symbol>;
23412342
dispose(): void;
23422343
} {
2343-
let onAbort!: () => void;
2344+
let dispose = () => {};
23442345
const promise = new Promise<symbol>((resolve) => {
2345-
onAbort = () => resolve(ABORTED);
2346-
if (signal.aborted) onAbort();
2347-
else signal.addEventListener('abort', onAbort, { once: true });
2346+
dispose = onAbort(signal, () => resolve(ABORTED));
23482347
});
2349-
return {
2350-
promise,
2351-
dispose: () => signal.removeEventListener('abort', onAbort),
2352-
};
2348+
return { promise, dispose };
23532349
}
23542350

23552351
let _defaultResolver: Resolver | null = null;

0 commit comments

Comments
 (0)