fix: bound browser transfer leases and effect reporting

BT-X-01: add the shared abortable-operation utility with golden tests for first
terminal owner, idempotent close, listener and timer cleanup under a throwing
scheduler, observed late rejection and late-handle compensation. It carries no
subsystem result taxonomy.

BT-PRE-01: make the presigned download lease lazy and single-start. open() now
validates, claims and consumes the capability without any network I/O; the
fetch, the transfer deadline and the expiry recheck happen at first stream
consumption. The source gained close(), which discards an unused lease with no
I/O and otherwise cancels the body and releases the scope exactly once.

BT-UP-01: require removeEventListener in the AbortSignal structural guard and
isolate release cleanup so a hostile facade cannot replace a typed terminal
result with a rejection.

BT-UP-03: deleteDatabase cannot be cancelled after dispatch, so a blocked
deadline now returns PENDING with effect UNKNOWN instead of a failure that reads
as NOT_APPLIED. A realm-scoped (factory, databaseName) registry prevents
recreating the partition until the native request settles.

BT-UP-04: reject non-finite and negative upload clocks as a dependency failure
instead of letting them bypass every capability expiry comparison.

BT-IMG-02: replace the naive Cache-Control quote stripping with a quote- and
escape-aware tokenizer, so max-age="60 or 60" is no longer read as 60 and a
comma inside a quoted extension is not a directive boundary.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-08-14 00:13:54 +09:00
co-authored by Claude Opus 5
parent 8f67974f68
commit cc4e875c2d
13 changed files with 831 additions and 134 deletions
@@ -0,0 +1,190 @@
/**
* BT-X-01. Shared abort and deadline mechanics.
*
* Several adapters independently reimplemented "race a promise against a
* caller signal and a deadline, then clean up listeners and timers". Only the
* mechanics are shared here; every subsystem keeps its own result taxonomy and
* recovery vocabulary, so this module deliberately imports none of them and is
* not a generic middleware layer.
*/
export type AbortTerminalReason = "CALLER_ABORT" | "DEADLINE" | "CLOSED";
export type AbortRace<Value> =
| Readonly<{ kind: "VALUE"; value: Value }>
| Readonly<{ kind: "TERMINAL"; terminal: AbortTerminalReason }>;
export type AbortableOperation = Readonly<{
/** The composed signal: caller abort, deadline and close all feed it. */
readonly signal: AbortSignal;
/**
* The first terminal owner, or `null` while the operation is still live.
* This is a live accessor, not a snapshot.
*/
terminal(): AbortTerminalReason | null;
/**
* Resolves with the operation's value, or with the first terminal owner.
* A terminal race never returns a bare value.
*/
race<Value>(operation: Promise<Value>): Promise<AbortRace<Value>>;
/**
* Idempotent. Removes listeners, clears the deadline timer and marks the
* operation `CLOSED` if nothing terminal happened first.
*/
close(): void;
}>;
export type AbortableOperationInput = Readonly<{
signal?: AbortSignal;
timeoutMs?: number;
/** Scheduler seam; a throwing scheduler must not leak a listener. */
setTimer?: (callback: () => void, delayMs: number) => unknown;
clearTimer?: (handle: unknown) => void;
}>;
export function createAbortableOperation(
input: AbortableOperationInput = {},
): AbortableOperation {
const controller = new AbortController();
const setTimer =
input.setTimer ??
((callback: () => void, delayMs: number) => setTimeout(callback, delayMs));
const clearTimer =
input.clearTimer ??
((handle: unknown) => {
clearTimeout(handle as ReturnType<typeof setTimeout>);
});
let terminalReason: AbortTerminalReason | null = null;
let disposed = false;
let timer: unknown;
/** First terminal owner wins; later owners never overwrite it. */
const settle = (reason: AbortTerminalReason) => {
terminalReason ??= reason;
if (!controller.signal.aborted) controller.abort();
};
const onCallerAbort = () => {
settle("CALLER_ABORT");
dispose();
};
function dispose(): void {
if (disposed) return;
disposed = true;
try {
input.signal?.removeEventListener("abort", onCallerAbort);
} catch {
// A hostile signal facade cannot block cleanup of the rest.
}
if (timer !== undefined) {
try {
clearTimer(timer);
} catch {
// A throwing scheduler cannot leave the operation un-disposed.
}
timer = undefined;
}
}
if (input.signal?.aborted) {
settle("CALLER_ABORT");
disposed = true;
} else if (input.signal) {
input.signal.addEventListener("abort", onCallerAbort, { once: true });
}
if (
terminalReason === null &&
input.timeoutMs !== undefined &&
Number.isFinite(input.timeoutMs) &&
input.timeoutMs >= 0
) {
try {
timer = setTimer(() => {
settle("DEADLINE");
dispose();
}, input.timeoutMs);
} catch {
// A scheduler that throws leaves no timer behind; the operation stays
// bounded only by the caller signal.
timer = undefined;
dispose();
}
}
return Object.freeze({
signal: controller.signal,
terminal: () => terminalReason,
async race<Value>(operation: Promise<Value>): Promise<AbortRace<Value>> {
// Observe a late rejection so an abandoned operation cannot surface as an
// unhandled rejection.
operation.catch(() => {});
if (terminalReason !== null) {
return Object.freeze({
kind: "TERMINAL" as const,
terminal: terminalReason,
});
}
const raced = await Promise.race([
operation.then(
(value) => Object.freeze({ kind: "VALUE" as const, value }),
() =>
Object.freeze({
kind: "TERMINAL" as const,
terminal: terminalReason ?? ("CLOSED" as const),
}),
),
new Promise<AbortRace<Value>>((resolve) => {
if (controller.signal.aborted) {
resolve(
Object.freeze({
kind: "TERMINAL" as const,
terminal: terminalReason ?? ("CLOSED" as const),
}),
);
return;
}
controller.signal.addEventListener(
"abort",
() =>
resolve(
Object.freeze({
kind: "TERMINAL" as const,
terminal: terminalReason ?? ("CLOSED" as const),
}),
),
{ once: true },
);
}),
]);
// A value that arrives after a terminal owner is not admitted.
return terminalReason !== null && raced.kind === "VALUE"
? Object.freeze({
kind: "TERMINAL" as const,
terminal: terminalReason,
})
: raced;
},
close() {
settle("CLOSED");
dispose();
},
});
}
/**
* Compensates a native handle that arrives after the operation ended. The
* compensation itself is best effort and can never change the already selected
* outcome.
*/
export function compensateLateHandle(
handle: Promise<Readonly<{ body?: { cancel(): Promise<void> } | null }> | null>,
): void {
void handle
.then(async (value) => {
await value?.body?.cancel();
})
.catch(() => undefined);
}