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:
co-authored by
Claude Opus 5
parent
8f67974f68
commit
cc4e875c2d
@@ -0,0 +1,139 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
compensateLateHandle,
|
||||
createAbortableOperation,
|
||||
} from "../../src/adapters/platform/abortable-operation.ts";
|
||||
|
||||
/**
|
||||
* BT-X-01 golden tests. The utility owns abort mechanics only: it must never
|
||||
* import or imply a subsystem result taxonomy.
|
||||
*/
|
||||
describe("shared abortable operation mechanics", () => {
|
||||
it("records the first terminal owner and never overwrites it", async () => {
|
||||
const caller = new AbortController();
|
||||
const timers: Array<() => void> = [];
|
||||
const operation = createAbortableOperation({
|
||||
signal: caller.signal,
|
||||
timeoutMs: 10,
|
||||
setTimer: (callback) => {
|
||||
timers.push(callback);
|
||||
return timers.length;
|
||||
},
|
||||
clearTimer: () => {},
|
||||
});
|
||||
|
||||
expect(operation.terminal()).toBeNull();
|
||||
caller.abort();
|
||||
expect(operation.terminal()).toBe("CALLER_ABORT");
|
||||
|
||||
// A later deadline or close cannot rewrite the owner.
|
||||
timers.forEach((callback) => callback());
|
||||
operation.close();
|
||||
expect(operation.terminal()).toBe("CALLER_ABORT");
|
||||
});
|
||||
|
||||
it("reports a deadline owner and aborts the composed signal", async () => {
|
||||
const timers: Array<() => void> = [];
|
||||
const operation = createAbortableOperation({
|
||||
timeoutMs: 5,
|
||||
setTimer: (callback) => {
|
||||
timers.push(callback);
|
||||
return timers.length;
|
||||
},
|
||||
clearTimer: () => {},
|
||||
});
|
||||
timers[0]?.();
|
||||
expect(operation.terminal()).toBe("DEADLINE");
|
||||
expect(operation.signal.aborted).toBe(true);
|
||||
});
|
||||
|
||||
it("race returns a terminal owner instead of a bare value", async () => {
|
||||
const caller = new AbortController();
|
||||
const operation = createAbortableOperation({ signal: caller.signal });
|
||||
let release: ((value: string) => void) | undefined;
|
||||
const pending = new Promise<string>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
|
||||
const raced = operation.race(pending);
|
||||
caller.abort();
|
||||
await expect(raced).resolves.toEqual({
|
||||
kind: "TERMINAL",
|
||||
terminal: "CALLER_ABORT",
|
||||
});
|
||||
|
||||
// The late value is observed and discarded.
|
||||
release?.("late");
|
||||
await expect(operation.race(pending)).resolves.toEqual({
|
||||
kind: "TERMINAL",
|
||||
terminal: "CALLER_ABORT",
|
||||
});
|
||||
});
|
||||
|
||||
it("race returns the value when nothing terminal happened", async () => {
|
||||
const operation = createAbortableOperation();
|
||||
await expect(operation.race(Promise.resolve(7))).resolves.toEqual({
|
||||
kind: "VALUE",
|
||||
value: 7,
|
||||
});
|
||||
operation.close();
|
||||
expect(operation.terminal()).toBe("CLOSED");
|
||||
});
|
||||
|
||||
it("observes a late rejection instead of leaking it", async () => {
|
||||
const operation = createAbortableOperation();
|
||||
const rejected = Promise.reject(new Error("late"));
|
||||
await expect(operation.race(rejected)).resolves.toEqual({
|
||||
kind: "TERMINAL",
|
||||
terminal: "CLOSED",
|
||||
});
|
||||
});
|
||||
|
||||
it("close is idempotent and releases listeners and timers exactly once", () => {
|
||||
const caller = new AbortController();
|
||||
const remove = vi.spyOn(caller.signal, "removeEventListener");
|
||||
const clearTimer = vi.fn();
|
||||
const operation = createAbortableOperation({
|
||||
signal: caller.signal,
|
||||
timeoutMs: 10,
|
||||
setTimer: () => "handle",
|
||||
clearTimer,
|
||||
});
|
||||
|
||||
operation.close();
|
||||
operation.close();
|
||||
operation.close();
|
||||
|
||||
expect(remove).toHaveBeenCalledTimes(1);
|
||||
expect(clearTimer).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("survives a throwing scheduler without leaking a listener", () => {
|
||||
const caller = new AbortController();
|
||||
const remove = vi.spyOn(caller.signal, "removeEventListener");
|
||||
const operation = createAbortableOperation({
|
||||
signal: caller.signal,
|
||||
timeoutMs: 10,
|
||||
setTimer: () => {
|
||||
throw new TypeError("scheduler exploded");
|
||||
},
|
||||
clearTimer: () => {},
|
||||
});
|
||||
|
||||
expect(operation.terminal()).toBeNull();
|
||||
expect(remove).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("compensates a late native handle without changing the outcome", async () => {
|
||||
const cancel = vi.fn(async () => {});
|
||||
compensateLateHandle(Promise.resolve({ body: { cancel } }));
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
|
||||
// A rejecting handle is swallowed.
|
||||
compensateLateHandle(Promise.reject(new Error("late")));
|
||||
await Promise.resolve();
|
||||
});
|
||||
});
|
||||
@@ -1479,6 +1479,10 @@ describe("browser image probe", () => {
|
||||
close: vi.fn(),
|
||||
}));
|
||||
for (const cacheControl of [
|
||||
// BT-IMG-02. Unmatched quotes must not be unwrapped into a bare number.
|
||||
'public, max-age="31536000, immutable',
|
||||
'public, max-age=31536000", immutable',
|
||||
'public, max-age="31536000\\", immutable',
|
||||
"public, public, max-age=31536000, immutable",
|
||||
"public, max-age=31536000, s-maxage=60, immutable",
|
||||
"public, max-age=31536000, immutable, must-revalidate",
|
||||
|
||||
@@ -602,13 +602,15 @@ describe("presigned transfer", () => {
|
||||
});
|
||||
expect(issued.ok).toBe(true);
|
||||
if (!issued.ok) return;
|
||||
expect(
|
||||
await harness.executor.downloadSources.open({
|
||||
resourceId: "resource-1",
|
||||
capability: issued.value,
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toMatchObject({
|
||||
await expect(
|
||||
firstStreamResult(
|
||||
await harness.executor.downloadSources.open({
|
||||
resourceId: "resource-1",
|
||||
capability: issued.value,
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { code: "POLICY_REJECTED" },
|
||||
});
|
||||
@@ -621,13 +623,15 @@ describe("presigned transfer", () => {
|
||||
});
|
||||
expect(issued.ok).toBe(true);
|
||||
if (!issued.ok) return;
|
||||
expect(
|
||||
await harness.executor.downloadSources.open({
|
||||
resourceId: "resource-1",
|
||||
capability: issued.value,
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toMatchObject({
|
||||
await expect(
|
||||
firstStreamResult(
|
||||
await harness.executor.downloadSources.open({
|
||||
resourceId: "resource-1",
|
||||
capability: issued.value,
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { code: "POLICY_REJECTED" },
|
||||
});
|
||||
@@ -640,18 +644,101 @@ describe("presigned transfer", () => {
|
||||
});
|
||||
expect(issued.ok).toBe(true);
|
||||
if (!issued.ok) return;
|
||||
expect(
|
||||
await harness.executor.downloadSources.open({
|
||||
resourceId: "resource-1",
|
||||
capability: issued.value,
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toMatchObject({
|
||||
await expect(
|
||||
firstStreamResult(
|
||||
await harness.executor.downloadSources.open({
|
||||
resourceId: "resource-1",
|
||||
capability: issued.value,
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { code: "INTEGRITY_FAILED" },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not fetch a presigned download until stream consumption", async () => {
|
||||
const bytes = new Uint8Array([1, 2, 3]);
|
||||
const responsePayload = downloadCapabilityPayload(bytes);
|
||||
let downloadFetches = 0;
|
||||
const fetcher = vi.fn(async (input: RequestInfo | URL) => {
|
||||
if (String(input) === CONTROL_ENDPOINT) {
|
||||
return jsonResponse(responsePayload);
|
||||
}
|
||||
downloadFetches += 1;
|
||||
return downloadResponse(bytes.slice().buffer, responsePayload);
|
||||
}) as unknown as typeof fetch;
|
||||
const { provider, executor } = createHarness({ fetcher });
|
||||
const signal = new AbortController().signal;
|
||||
const issued = await provider.issueDownload({
|
||||
resourceId: "resource-1",
|
||||
signal,
|
||||
});
|
||||
expect(issued.ok).toBe(true);
|
||||
if (!issued.ok) return;
|
||||
|
||||
const opened = await executor.downloadSources.open({
|
||||
resourceId: "resource-1",
|
||||
capability: issued.value,
|
||||
signal,
|
||||
});
|
||||
expect(opened.ok).toBe(true);
|
||||
if (!opened.ok) return;
|
||||
// BT-PRE-01. open() performs no network I/O.
|
||||
expect(downloadFetches).toBe(0);
|
||||
|
||||
for await (const chunk of opened.value.stream(signal)) {
|
||||
expect(chunk.ok).toBe(true);
|
||||
}
|
||||
expect(downloadFetches).toBe(1);
|
||||
opened.value.close();
|
||||
});
|
||||
|
||||
it("closes an unused download source without network I/O", async () => {
|
||||
const bytes = new Uint8Array([1, 2, 3]);
|
||||
const responsePayload = downloadCapabilityPayload(bytes);
|
||||
let downloadFetches = 0;
|
||||
const fetcher = vi.fn(async (input: RequestInfo | URL) => {
|
||||
if (String(input) === CONTROL_ENDPOINT) {
|
||||
return jsonResponse(responsePayload);
|
||||
}
|
||||
downloadFetches += 1;
|
||||
return downloadResponse(bytes.slice().buffer, responsePayload);
|
||||
}) as unknown as typeof fetch;
|
||||
const { provider, executor } = createHarness({ fetcher });
|
||||
const signal = new AbortController().signal;
|
||||
const issued = await provider.issueDownload({
|
||||
resourceId: "resource-1",
|
||||
signal,
|
||||
});
|
||||
expect(issued.ok).toBe(true);
|
||||
if (!issued.ok) return;
|
||||
|
||||
const opened = await executor.downloadSources.open({
|
||||
resourceId: "resource-1",
|
||||
capability: issued.value,
|
||||
signal,
|
||||
});
|
||||
expect(opened.ok).toBe(true);
|
||||
if (!opened.ok) return;
|
||||
|
||||
opened.value.close();
|
||||
// close() is idempotent and never starts the transfer.
|
||||
opened.value.close();
|
||||
expect(downloadFetches).toBe(0);
|
||||
|
||||
// A stream after close is one terminal conflict, still without fetching.
|
||||
const results = [];
|
||||
for await (const chunk of opened.value.stream(signal)) {
|
||||
results.push(chunk);
|
||||
}
|
||||
expect(results).toMatchObject([
|
||||
{ ok: false, error: { code: "CONFLICT" } },
|
||||
]);
|
||||
expect(downloadFetches).toBe(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "truncation",
|
||||
@@ -1633,3 +1720,27 @@ describe("presigned transfer", () => {
|
||||
expect(written).toEqual([...bytes]);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* BT-PRE-01. The download lease is lazy, so a response-shape rejection is
|
||||
* observed on first consumption rather than at `open()`.
|
||||
*/
|
||||
async function firstStreamResult(
|
||||
opened: Awaited<
|
||||
ReturnType<
|
||||
ReturnType<typeof createHarness>["executor"]["downloadSources"]["open"]
|
||||
>
|
||||
>,
|
||||
): Promise<unknown> {
|
||||
if (!opened.ok) return opened;
|
||||
try {
|
||||
for await (const chunk of opened.value.stream(
|
||||
new AbortController().signal,
|
||||
)) {
|
||||
if (!chunk.ok) return chunk;
|
||||
}
|
||||
return { ok: true };
|
||||
} finally {
|
||||
opened.value.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,7 +183,7 @@ describe("IndexedDB resumable upload checkpoint", () => {
|
||||
).toMatchObject({ ok: true });
|
||||
expect(await runtime.admin.deletePartition()).toEqual({
|
||||
ok: true,
|
||||
value: { state: "DELETED" },
|
||||
value: { state: "DELETED", effect: "APPLIED" },
|
||||
});
|
||||
expect(await runtime.store.read("upload_key_01")).toMatchObject({
|
||||
ok: false,
|
||||
@@ -191,21 +191,48 @@ describe("IndexedDB resumable upload checkpoint", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("bounds a partition deletion blocked by another browser context", async () => {
|
||||
it("returns PENDING UNKNOWN when deleteDatabase is still blocked", async () => {
|
||||
const memory = new MemoryIndexedDbFactory();
|
||||
const factory = deletingFactory(memory, "BLOCKED");
|
||||
const runtime = createIndexedDbResumableUploadCheckpointRuntime({
|
||||
scope,
|
||||
factory: deletingFactory(memory, "BLOCKED"),
|
||||
factory,
|
||||
blockedTimeoutMs: 1,
|
||||
});
|
||||
// BT-UP-03. The native request is still live, so the deadline is not
|
||||
// evidence that nothing happened.
|
||||
expect(await runtime.admin.deletePartition()).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
state: "PENDING",
|
||||
effect: "UNKNOWN",
|
||||
reason: "BLOCKED_DEADLINE",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the checkpoint store closed until a pending delete is resolved externally", async () => {
|
||||
const memory = new MemoryIndexedDbFactory();
|
||||
const factory = deletingFactory(memory, "BLOCKED");
|
||||
const runtime = createIndexedDbResumableUploadCheckpointRuntime({
|
||||
scope,
|
||||
factory,
|
||||
blockedTimeoutMs: 1,
|
||||
});
|
||||
expect(await runtime.admin.deletePartition()).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
code: "BLOCKED",
|
||||
retryable: true,
|
||||
recovery: "RELOAD_OTHER_CONTEXTS",
|
||||
},
|
||||
ok: true,
|
||||
value: { state: "PENDING" },
|
||||
});
|
||||
|
||||
// A second runtime over the same realm and database would race an unknown
|
||||
// native effect.
|
||||
expect(() =>
|
||||
createIndexedDbResumableUploadCheckpointRuntime({
|
||||
scope,
|
||||
factory,
|
||||
blockedTimeoutMs: 1,
|
||||
}),
|
||||
).toThrow(TypeError);
|
||||
});
|
||||
|
||||
it("never reports a false abort after irreversible deleteDatabase dispatch", async () => {
|
||||
@@ -219,7 +246,7 @@ describe("IndexedDB resumable upload checkpoint", () => {
|
||||
controller.abort();
|
||||
expect(await deletion).toEqual({
|
||||
ok: true,
|
||||
value: { state: "DELETED" },
|
||||
value: { state: "DELETED", effect: "APPLIED" },
|
||||
});
|
||||
|
||||
const preAborted = new AbortController();
|
||||
|
||||
Reference in New Issue
Block a user