diff --git a/scripts/check-adapter-inventory.ts b/scripts/check-adapter-inventory.ts index 1a1ce714..9677c1a6 100644 --- a/scripts/check-adapter-inventory.ts +++ b/scripts/check-adapter-inventory.ts @@ -203,7 +203,9 @@ async function main(): Promise { // 이것으로 IndexedDB 어댑터 4벌이 모두 커널을 쓴다. // 21 → 19: `browser-files/download-delivery-adapter.ts`와 // `browser-files/browser-file-vault.ts`가 커널 race로 옮겨갔다(Q-6.2-7). - const HAND_ROLLED_ABORT_CEILING = 19; + // 19 → 18: `browser-file-storage/storage-manager-adapter.ts`의 inspection + // 대기가 커널 race로 옮겨갔다(Q-B). + const HAND_ROLLED_ABORT_CEILING = 18; const handRolledScan = spawnSync( "git", ["grep", "-l", 'addEventListener("abort"', "--", "src/adapters"], diff --git a/src/adapters/browser-file-storage/storage-manager-adapter.ts b/src/adapters/browser-file-storage/storage-manager-adapter.ts index e2b034a4..c77735a3 100644 --- a/src/adapters/browser-file-storage/storage-manager-adapter.ts +++ b/src/adapters/browser-file-storage/storage-manager-adapter.ts @@ -8,6 +8,7 @@ import { browserDataSuccess, mapBrowserDataException, } from "./result.ts"; +import { createAbortableOperation } from "../platform/abortable-operation.ts"; export type StorageManagerFacade = Readonly<{ estimate(): Promise>; @@ -155,48 +156,22 @@ function snapshotPressurePolicy( return snapshot; } +/** + * The kernel race: a caller abort ends the wait, and a native call that settles + * afterwards — including one that rejects — is consumed rather than leaked. + */ async function awaitStorageInspection( inspection: Promise, signal: AbortSignal | undefined, ): Promise { - if (!signal) return await inspection; - if (signal.aborted) { - // The native calls have already been invoked. Consume a later rejection - // even though the caller no longer waits for their result. - void inspection.catch(() => undefined); - return STORAGE_INSPECTION_ABORTED; + const operation = createAbortableOperation({ signal }); + try { + const raced = await operation.race(inspection); + if (raced.kind === "REJECTED") throw raced.reason; + return raced.kind === "VALUE" ? raced.value : STORAGE_INSPECTION_ABORTED; + } finally { + operation.close(); } - - return await new Promise( - (resolve, reject) => { - let settled = false; - const finish = ( - outcome: - | Readonly<{ kind: "VALUE"; value: Value }> - | Readonly<{ kind: "ABORTED" }> - | Readonly<{ kind: "ERROR"; error: unknown }>, - ): void => { - if (settled) return; - settled = true; - signal.removeEventListener("abort", onAbort); - if (outcome.kind === "VALUE") { - resolve(outcome.value); - } else if (outcome.kind === "ABORTED") { - resolve(STORAGE_INSPECTION_ABORTED); - } else { - reject(outcome.error); - } - }; - const onAbort = (): void => finish({ kind: "ABORTED" }); - - signal.addEventListener("abort", onAbort, { once: true }); - inspection.then( - (value) => finish({ kind: "VALUE", value }), - (error: unknown) => finish({ kind: "ERROR", error }), - ); - if (signal.aborted) onAbort(); - }, - ); } async function inspectPersistenceState( diff --git a/src/adapters/browser-transfer/image-cdn/browser-image-probe.ts b/src/adapters/browser-transfer/image-cdn/browser-image-probe.ts index a20a5882..04a32041 100644 --- a/src/adapters/browser-transfer/image-cdn/browser-image-probe.ts +++ b/src/adapters/browser-transfer/image-cdn/browser-image-probe.ts @@ -7,9 +7,11 @@ import { browserDataSuccess, } from "../../browser-file-storage/result.ts"; import { + cancelBody, + cancelReader, createAbortableOperation, snapshotAbortTimers, - type AbortTimerSnapshot, + type AbortableOperation, } from "../../platform/abortable-operation.ts"; import { parseStaticImageHeaderMetadata } from "./image-header-metadata.ts"; import { @@ -106,11 +108,15 @@ export function createBrowserImageProbe( return browserDataFailure("UNSUPPORTED", "IMAGE_RESOLVE"); } - const scope = createProbeAbortScope( - request.signal, + // X-AUDIT-02 / TR-RR-05. The probe is owned by the shared abort + // primitive: the caller listener and the deadline are installed + // together, so a throwing scheduler closes the probe instead of + // rejecting `probe()`. + const scope = createAbortableOperation({ + signal: request.signal, timeoutMs, - timers, - ); + ...timers, + }); let response: Response | undefined; try { if (scope.signal.aborted) { @@ -130,8 +136,8 @@ export function createBrowserImageProbe( signal: scope.signal, }), ); - response = await scope.await(fetchTask, (lateResponse) => { - cancelResponseBody(lateResponse); + response = await awaitOwned(scope, fetchTask, (lateResponse) => { + cancelBody(lateResponse); }); } catch { return signalFailure(request.signal); @@ -146,7 +152,7 @@ export function createBrowserImageProbe( response.url !== url.href || !validResponseHeaders(response, request) ) { - cancelResponseBody(response); + cancelBody(response); return browserDataFailure( "POLICY_REJECTED", "IMAGE_RESOLVE", @@ -158,10 +164,10 @@ export function createBrowserImageProbe( bytes = await readBoundedBody( response, request.maxEncodedBytes, - scope.signal, + scope, ); } catch (error) { - if (request.signal.aborted || scope.timedOut()) { + if (request.signal.aborted || unanswered(scope)) { return signalFailure(request.signal); } return error instanceof EncodedBodyLimitError @@ -233,7 +239,7 @@ export function createBrowserImageProbe( type: request.expectedMediaType, }), ); - bitmap = await scope.await(decodeTask, closeBitmap); + bitmap = await awaitOwned(scope, decodeTask, closeBitmap); if ( !positiveSafeInteger(bitmap.width) || !positiveSafeInteger(bitmap.height) || @@ -261,7 +267,7 @@ export function createBrowserImageProbe( }), ); } catch { - return request.signal.aborted || scope.timedOut() + return request.signal.aborted || unanswered(scope) ? signalFailure(request.signal) : browserDataFailure( "INTEGRITY_FAILED", @@ -271,7 +277,7 @@ export function createBrowserImageProbe( if (bitmap) closeBitmap(bitmap); } } finally { - scope.release(); + scope.close(); } }, }); @@ -480,7 +486,7 @@ class EncodedBodyLimitError extends Error {} async function readBoundedBody( response: Response, maximumBytes: number, - signal: AbortSignal, + scope: AbortableOperation, ): Promise { if (!response.body) { throw new TypeError("Image response body is unavailable."); @@ -490,8 +496,9 @@ async function readBoundedBody( let total = 0; try { while (true) { - if (signal.aborted) throw abortException(); - const next = await readOrAbort(reader.read(), signal); + if (scope.signal.aborted) throw abortException(); + // A late chunk is dropped: the bytes are only accumulated below. + const next = await awaitOwned(scope, reader.read(), () => undefined); if (next.done) break; if (!(next.value instanceof Uint8Array)) { throw new TypeError("Image response chunk is invalid."); @@ -521,90 +528,28 @@ async function readBoundedBody( return bytes; } -type ProbeAbortScope = Readonly<{ - signal: AbortSignal; - /** True once a deadline, or a deadline that could not be installed, ended it. */ - timedOut(): boolean; - /** - * Awaits `task` under this scope's ownership. A late value is compensated - * exactly once; a terminal owner raises the scope's abort exception. - */ - await( - task: Promise, - onLateValue: (value: Value) => void, - ): Promise; - release(): void; -}>; - /** - * X-AUDIT-02 / TR-RR-05. The probe scope is the shared abort primitive with - * this subsystem's vocabulary on top. Owning a private copy meant the caller - * listener was attached before the timer was installed, so a scheduler that - * threw rejected the public `probe()` promise and left the listener behind. + * `CLOSED` here means the deadline could never be installed, so the probe was + * never bounded: operationally the same unanswered host as a deadline. */ -function createProbeAbortScope( - externalSignal: AbortSignal, - timeoutMs: number, - timers: AbortTimerSnapshot, -): ProbeAbortScope { - const operation = createAbortableOperation({ - signal: externalSignal, - timeoutMs, - setTimer: timers.setTimer, - clearTimer: timers.clearTimer, - }); - return Object.freeze({ - signal: operation.signal, - // `CLOSED` here means the deadline could never be installed, so the probe - // was never bounded: operationally the same unanswered host as a deadline. - timedOut: () => - operation.terminal() !== "CALLER_ABORT" && operation.terminal() !== null, - async await( - task: Promise, - onLateValue: (value: Value) => void, - ): Promise { - const raced = await operation.race(task, onLateValue); - if (raced.kind === "VALUE") return raced.value; - if (raced.kind === "REJECTED") throw raced.reason; - throw abortException(); - }, - release: () => operation.close(), - }); +function unanswered(scope: AbortableOperation): boolean { + const terminal = scope.terminal(); + return terminal !== null && terminal !== "CALLER_ABORT"; } /** - * A single read raced against the probe's ownership. A late chunk is dropped: - * the bytes are only ever accumulated by the caller below. + * Awaits `task` under the probe's ownership. A late value is compensated + * exactly once; a terminal owner raises the probe's abort exception. */ -function readOrAbort( +async function awaitOwned( + scope: AbortableOperation, task: Promise, - signal: AbortSignal, + onLateValue: (value: Value) => void, ): Promise { - return new Promise((resolve, reject) => { - let settled = false; - const onAbort = () => { - if (settled) return; - settled = true; - reject(abortException()); - }; - signal.addEventListener("abort", onAbort, { once: true }); - void task.then( - (value) => { - signal.removeEventListener("abort", onAbort); - if (!settled) { - settled = true; - resolve(value); - } - }, - (error: unknown) => { - signal.removeEventListener("abort", onAbort); - if (!settled) { - settled = true; - reject(error); - } - }, - ); - }); + const raced = await scope.race(task, onLateValue); + if (raced.kind === "VALUE") return raced.value; + if (raced.kind === "REJECTED") throw raced.reason; + throw abortException(); } function signalFailure(externalSignal: AbortSignal) { @@ -618,25 +563,6 @@ function signalFailure(externalSignal: AbortSignal) { }); } -function cancelResponseBody(response: Response): void { - try { - const cancellation = response.body?.cancel(); - void cancellation?.catch(() => undefined); - } catch { - // Best-effort release cannot change the closed probe result. - } -} - -function cancelReader( - reader: ReadableStreamDefaultReader, -): void { - try { - void reader.cancel().catch(() => undefined); - } catch { - // Best-effort release cannot change the closed probe result. - } -} - function closeBitmap(bitmap: DecodedImageFacade): void { try { bitmap.close(); diff --git a/src/adapters/browser-transfer/presigned/http-common.ts b/src/adapters/browser-transfer/presigned/http-common.ts index 451d109f..8cbe3841 100644 --- a/src/adapters/browser-transfer/presigned/http-common.ts +++ b/src/adapters/browser-transfer/presigned/http-common.ts @@ -125,29 +125,6 @@ export function readWithSignal( }); } -export function cancelBody(response: Response): void { - try { - void response.body?.cancel().catch(() => { - // Cancellation is best effort after the result is classified. - }); - } catch { - // A response already classified as failure/success is not reclassified by - // best-effort body cancellation. - } -} - -export function cancelReader( - reader: ReadableStreamDefaultReader, -): void { - try { - void reader.cancel().catch(() => { - // Cancellation is best effort after the result is classified. - }); - } catch { - // Reader cancellation cannot alter the terminal closed result. - } -} - /** * A plain decimal `Content-Length`. `Number()` alone accepted `"5e0"`, * `"0x5"`, `"+5"` and `""`. An absent header is `null` unless the caller's diff --git a/src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts b/src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts index a64ddb6d..3b3fe8b0 100644 --- a/src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts +++ b/src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts @@ -10,7 +10,11 @@ import type { PresignedUploadPartCapability, PresignedUploadPartCapabilityProvider, } from "../../../application/ports/browser-transfer/presigned-transfer.ts"; -import { snapshotAbortTimers } from "../../platform/abortable-operation.ts"; +import { + cancelBody, + cancelReader, + snapshotAbortTimers, +} from "../../platform/abortable-operation.ts"; import { RESUMABLE_UPLOAD_PROTOCOL } from "../../../application/ports/browser-transfer/resumable-upload.ts"; import type { BrowserDataObserver, @@ -26,8 +30,6 @@ import type { PresignedHeaderBinding, } from "./presigned-capability-vault.ts"; import { - cancelBody, - cancelReader, createAbortScope, isAbortSignal, normalizedContentLength, diff --git a/src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts b/src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts index 8bfba6b4..32b4f452 100644 --- a/src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts +++ b/src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts @@ -8,7 +8,11 @@ import type { PresignedUploadPartOutcome, PresignedUploadPartPort, } from "../../../application/ports/browser-transfer/presigned-transfer.ts"; -import { snapshotAbortTimers } from "../../platform/abortable-operation.ts"; +import { + cancelBody, + cancelReader, + snapshotAbortTimers, +} from "../../platform/abortable-operation.ts"; import { RESUMABLE_UPLOAD_PROTOCOL } from "../../../application/ports/browser-transfer/resumable-upload.ts"; import type { BrowserDataFailureCode, @@ -32,8 +36,6 @@ import type { } from "./presigned-capability-vault.ts"; import { byteBucket, - cancelBody, - cancelReader, createAbortScope, isAbortSignal, normalizedContentLength, diff --git a/src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts b/src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts index 427f6bc2..a943007f 100644 --- a/src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts +++ b/src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts @@ -12,15 +12,15 @@ import { browserDataSuccess, } from "../../browser-file-storage/result.ts"; import { + cancelBody, + cancelReader, createAbortableOperation, - type AbortRace, - type AbortTerminalReason, + type AbortableOperation, } from "../../platform/abortable-operation.ts"; import type { ResumableUploadControlOperation, ResumableUploadJsonTransport, } from "./http-control-plane-adapter.ts"; -import { cancelBody, cancelReader } from "../presigned/http-common.ts"; import { isAbortSignal } from "./checkpoint-schema.ts"; export type ResumableUploadEndpointMap = Readonly< @@ -185,14 +185,17 @@ export function createResumableUploadFetchJsonTransport( "NONE", ); } - const attempt = createFetchAttempt( + // X-AUDIT-02 / TR-RR-05. The attempt is the shared abort primitive: + // the listener and the timer are installed together, so a throwing + // scheduler closes the attempt instead of rejecting `execute()`. + const attempt = createAbortableOperation({ signal, timeoutMs, setTimer, clearTimer, - ); + }); try { - if (attempt.terminalKind() !== null) { + if (attempt.terminal() !== null) { // The attempt was closed before it could be bounded, so no request is // ever put on the wire. return attemptFailure(attempt, operation); @@ -264,7 +267,9 @@ export function createResumableUploadFetchJsonTransport( } catch { return attemptFailure(attempt, operation); } finally { - attempt.release(); + // BT-UP-01. Cleanup is best effort and never replaces the classified + // terminal result with a rejection. + attempt.close(); } }, }; @@ -408,7 +413,7 @@ async function readBoundedJson( response: Response, maxBytes: number, operation: ResumableUploadControlOperation, - attempt: FetchAttempt, + attempt: AbortableOperation, ): Promise> { const contentLength = response.headers.get("content-length"); let declaredLength: number | null = null; @@ -577,63 +582,11 @@ function failure( return Object.freeze({ ok: false, error }); } -type FetchAttemptTerminalKind = "ABORT" | "TIMEOUT" | "CLOSED"; - -type FetchAttempt = Readonly<{ - signal: AbortSignal; - terminalKind(): FetchAttemptTerminalKind | null; - race( - task: Promise, - compensate?: (value: Value) => void, - ): Promise>; - release(): void; -}>; - -/** - * X-AUDIT-02 / TR-RR-05. The attempt is the shared abort primitive with this - * subsystem's vocabulary on top. Owning a private copy meant the listener was - * attached before the timer was installed, so a scheduler that threw rejected - * the public `execute()` promise and left the listener on the caller's signal. - */ -function createFetchAttempt( - parent: AbortSignal, - timeoutMs: number, - setTimer: (callback: () => void, delayMs: number) => unknown, - clearTimer: (handle: unknown) => void, -): FetchAttempt { - const operation = createAbortableOperation({ - signal: parent, - timeoutMs, - setTimer, - clearTimer, - }); - const kindOf = ( - reason: AbortTerminalReason | null, - ): FetchAttemptTerminalKind | null => { - if (reason === null) return null; - if (reason === "CALLER_ABORT") return "ABORT"; - return reason === "DEADLINE" ? "TIMEOUT" : "CLOSED"; - }; - return Object.freeze({ - signal: operation.signal, - terminalKind: () => kindOf(operation.terminal()), - race: ( - task: Promise, - compensate?: (value: Value) => void, - ) => operation.race(task, compensate), - release() { - // BT-UP-01. Cleanup is best effort and must never replace the already - // classified terminal result with a rejection. - operation.close(); - }, - }); -} - function attemptFailure( - attempt: FetchAttempt, + attempt: AbortableOperation, operation: ResumableUploadControlOperation, ): UploadProviderResult { - return attempt.terminalKind() === "ABORT" + return attempt.terminal() === "CALLER_ABORT" ? failure("ABORTED", operation, false, "NONE") : failure("UNAVAILABLE", operation, true, "RESUME"); } diff --git a/src/adapters/platform/abortable-operation.ts b/src/adapters/platform/abortable-operation.ts index c577f5d0..4084e0d8 100644 --- a/src/adapters/platform/abortable-operation.ts +++ b/src/adapters/platform/abortable-operation.ts @@ -267,3 +267,27 @@ export function compensateLateHandle( }) .catch(() => undefined); } + +/** + * Best-effort release of a response body whose result is already classified. + * Neither a synchronous throw nor a rejected cancellation can change that + * result. + */ +export function cancelBody(response: Response): void { + try { + void response.body?.cancel().catch(() => undefined); + } catch { + // The classified result wins over body cancellation. + } +} + +/** `cancelBody` for a reader that already holds the body's lock. */ +export function cancelReader( + reader: ReadableStreamDefaultReader, +): void { + try { + void reader.cancel().catch(() => undefined); + } catch { + // The classified result wins over reader cancellation. + } +}