|
| 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 | +} |
0 commit comments