perf(file-transfer): use the abort kernel instead of local copies and wrappers (Q-B)

- cancelBody / cancelReader move from presigned/http-common.ts into
  platform/abortable-operation.ts next to compensateLateHandle; the probe's
  own cancelResponseBody/cancelReader copies are dropped and every caller
  imports the kernel pair.
- fetch-json-transport uses the kernel operation directly: the FetchAttempt
  projection only renamed terminal() (ABORT/TIMEOUT/CLOSED), and only the
  CALLER_ABORT case was ever read.
- browser-image-probe uses the kernel operation directly (awaitOwned /
  unanswered helpers replace the ProbeAbortScope object), and the body read
  goes through the same race instead of the hand-written readOrAbort.
- storage-manager-adapter's inspection wait is the kernel race: a caller
  abort ends the wait and a later settlement, including a rejection, is
  consumed, exactly as the hand-written listener did. The hand-rolled abort
  ratchet drops 19 -> 18 for this file.

file-transfer reference runtime: 55154 -> 54894 gzip bytes.
offline-indexeddb: 35951 -> 35854. service-worker-pwa: 9581 -> 9500.
realtime unchanged.

Verified: check:architecture, check:types:app, check:types:test, lint,
test:unit, test:component, check:adapter-inventory (hand-rolled abort
wiring 17/18).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-24 14:49:19 +09:00
co-authored by Claude Opus 5.5
parent 09402478d6
commit 6c69df572b
8 changed files with 101 additions and 240 deletions
+3 -1
View File
@@ -203,7 +203,9 @@ async function main(): Promise<void> {
// 이것으로 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"],
@@ -8,6 +8,7 @@ import {
browserDataSuccess,
mapBrowserDataException,
} from "./result.ts";
import { createAbortableOperation } from "../platform/abortable-operation.ts";
export type StorageManagerFacade = Readonly<{
estimate(): Promise<Readonly<{ usage?: number; quota?: number }>>;
@@ -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<Value>(
inspection: Promise<Value>,
signal: AbortSignal | undefined,
): Promise<Value | typeof STORAGE_INSPECTION_ABORTED> {
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<Value | typeof STORAGE_INSPECTION_ABORTED>(
(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(
@@ -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<Uint8Array> {
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<Value>(
task: Promise<Value>,
onLateValue: (value: Value) => void,
): Promise<Value>;
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<Value>(
task: Promise<Value>,
onLateValue: (value: Value) => void,
): Promise<Value> {
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<Value>(
async function awaitOwned<Value>(
scope: AbortableOperation,
task: Promise<Value>,
signal: AbortSignal,
onLateValue: (value: Value) => void,
): Promise<Value> {
return new Promise<Value>((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<Uint8Array>,
): 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();
@@ -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<Uint8Array>,
): 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
@@ -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,
@@ -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,
@@ -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<UploadProviderResult<unknown>> {
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<Value>(
task: Promise<Value>,
compensate?: (value: Value) => void,
): Promise<AbortRace<Value>>;
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: <Value,>(
task: Promise<Value>,
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<never> {
return attempt.terminalKind() === "ABORT"
return attempt.terminal() === "CALLER_ABORT"
? failure("ABORTED", operation, false, "NONE")
: failure("UNAVAILABLE", operation, true, "RESUME");
}
@@ -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<Uint8Array>,
): void {
try {
void reader.cancel().catch(() => undefined);
} catch {
// The classified result wins over reader cancellation.
}
}