perf(browser-transfer): race presigned body reads on the kernel operation (R3-2)

readWithSignal now races reader.read() through createAbortableOperation
instead of its own abort listener, and createAbortScope takes the single
consumer signal its only caller passes instead of looping over an array.
Adds a characterization test for a consumer-only abort during a pending
read (ABORTED, owner signal untouched, body cancelled).

file-transfer gzip: 54546 -> 54500

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-24 15:33:13 +09:00
co-authored by Claude Opus 5.5
parent 02fc2a384c
commit ce03745b66
3 changed files with 64 additions and 34 deletions
@@ -42,7 +42,7 @@ export function createAbortScope(
external: AbortSignal,
timeoutMs: number,
timers: AbortTimerSnapshot,
additionalSignals: readonly AbortSignal[] = [],
consumer?: AbortSignal,
) {
const operation = createAbortableOperation({
signal: external,
@@ -50,23 +50,19 @@ export function createAbortScope(
setTimer: timers.setTimer,
clearTimer: timers.clearTimer,
});
const releases: (() => void)[] = [];
for (const extra of additionalSignals) {
if (!extra) continue;
if (extra.aborted) {
operation.close();
continue;
}
let release = () => {};
if (consumer?.aborted) operation.close();
else if (consumer) {
const onAbort = () => operation.close();
try {
extra.addEventListener("abort", onAbort, { once: true });
releases.push(() => {
consumer.addEventListener("abort", onAbort, { once: true });
release = () => {
try {
extra.removeEventListener("abort", onAbort);
consumer.removeEventListener("abort", onAbort);
} catch {
// A hostile signal facade cannot block the rest of cleanup.
}
});
};
} catch {
// A signal that refuses a listener cannot bound this operation, so the
// operation closes rather than running unbounded.
@@ -75,7 +71,7 @@ export function createAbortScope(
}
const end = () => {
operation.close();
for (const release of releases.splice(0)) release();
release();
};
return Object.freeze({
signal: operation.signal,
@@ -100,29 +96,18 @@ export function createAbortScope(
});
}
export function readWithSignal(
export async function readWithSignal(
reader: ReadableStreamDefaultReader<Uint8Array>,
signal: AbortSignal,
): Promise<ReadableStreamReadResult<Uint8Array>> {
if (signal.aborted) {
return Promise.reject(new DOMException("Aborted", "AbortError"));
}
return new Promise((resolve, reject) => {
const onAbort = () => {
reject(new DOMException("Aborted", "AbortError"));
};
signal.addEventListener("abort", onAbort, { once: true });
reader.read().then(
(result) => {
signal.removeEventListener("abort", onAbort);
resolve(result);
},
(error: unknown) => {
signal.removeEventListener("abort", onAbort);
reject(error);
},
);
});
if (signal.aborted) throw new DOMException("Aborted", "AbortError");
const operation = createAbortableOperation({ signal });
const outcome = await operation.race(reader.read());
operation.close();
if (outcome.kind === "VALUE") return outcome.value;
throw outcome.kind === "REJECTED"
? outcome.reason
: new DOMException("Aborted", "AbortError");
}
/**
@@ -199,7 +199,7 @@ export function createPresignedTransferExecutor(
signal,
timeoutMs,
timers,
consumerSignal ? [consumerSignal] : [],
consumerSignal,
),
recheckExpiry: () =>
validateExpiry(capability, minimumRemainingLifetimeMs, now()),
@@ -445,6 +445,51 @@ describe("presigned download stream lifecycle", () => {
]);
});
it("ends a pending read when only the stream consumer signal aborts", async () => {
// R3-2 characterization: the consumer signal is composed into the read
// scope separately from the owner signal, which stays live here.
const bytes = new Uint8Array([1]);
const payload = downloadCapabilityPayload(bytes);
let cancelled = false;
const fetcher = vi.fn(async (input: RequestInfo | URL) =>
String(input) === CONTROL_ENDPOINT
? jsonResponse(payload)
: downloadResponse(
new ReadableStream<Uint8Array>({
pull() {},
cancel() {
cancelled = true;
},
}),
payload,
),
) as unknown as typeof fetch;
const harness = createHarness({ fetcher });
const owner = new AbortController();
const issued = await harness.provider.issueDownload({
resourceId: "resource-1",
signal: owner.signal,
});
expect(issued.ok).toBe(true);
if (!issued.ok) return;
const opened = await harness.executor.downloadSources.open({
resourceId: "resource-1",
capability: issued.value,
signal: owner.signal,
});
expect(opened.ok).toBe(true);
if (!opened.ok) return;
const consumer = new AbortController();
const pending = collect(opened.value, consumer.signal);
await new Promise((resolve) => setTimeout(resolve, 0));
consumer.abort("consumer");
expect(await pending).toMatchObject([
{ ok: false, error: { code: "ABORTED" } },
]);
expect(owner.signal.aborted).toBe(false);
expect(cancelled).toBe(true);
});
it("rejects an expired capability before data-plane fetch", async () => {
const bytes = new Uint8Array([1]);
const payload = downloadCapabilityPayload(bytes);