diff --git a/src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts b/src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts index bd2928c9..794738e4 100644 --- a/src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts +++ b/src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts @@ -193,6 +193,7 @@ export function createResumableUploadRuntime( let closed = false; let lifecycle: "OPEN" | "CLOSING" | "CLOSED" = "OPEN"; let drain: Promise> | null = null; + let quiescent: Promise<"DRAINED"> | null = null; const cancelLocalUploads = (uploadKey: string): void => { if (!SAFE_UPLOAD_KEY.test(uploadKey)) return; for (const controller of localUploads.get(uploadKey) ?? []) { @@ -329,15 +330,7 @@ export function createResumableUploadRuntime( function startDrain(): Promise> { drain ??= (async () => { - closed = true; - lifecycle = "CLOSING"; - releaseCrossContextCancellation?.(); - dependencies.crossContextCancellation?.close(); - // Abort every admitted operation, then wait for their real settlement. - lifetime.abort(); - for (const controllers of localUploads.values()) { - for (const controller of controllers) controller.abort(); - } + quiescent ??= beginTeardown(); // TR-RR-06. Bounded. A non-cooperative mutation lock or provider must not // make teardown unbounded, and an unproved drain is reported as such // rather than closed over. @@ -348,20 +341,13 @@ export function createResumableUploadRuntime( dependencies.policy.cleanupDeadlineMs, ); }); - // TR-04. Quiescence means both registries: the bounded wrappers and the - // raw provider work they may have outlived. A settling wrapper can still - // register more physical work, so the drain repeats until both are empty - // or the cleanup deadline expires. - const quiescent = (async () => { - while (activeOperations.size > 0 || physicalTasks.size > 0) { - await Promise.allSettled([...activeOperations, ...physicalTasks]); - } - return "DRAINED" as const; - })(); const drained = await Promise.race([quiescent, expired]); if (timer !== undefined) clearTimeout(timer); if (drained === "EXPIRED") { // The store stays open: something can still write a checkpoint. + // R-1.1. The failure is retryable, so a later dispose() starts a new + // bounded wait on the same quiescence instead of replaying this one. + drain = null; return browserDataFailure("UNAVAILABLE", "UPLOAD_ABORT", { retryable: true, recovery: "RESUME", @@ -374,6 +360,28 @@ export function createResumableUploadRuntime( })(); return drain; } + + /** One-shot admission close; returns the quiescence every drain waits on. */ + function beginTeardown(): Promise<"DRAINED"> { + closed = true; + lifecycle = "CLOSING"; + releaseCrossContextCancellation?.(); + dependencies.crossContextCancellation?.close(); + // Abort every admitted operation, then wait for their real settlement. + lifetime.abort(); + for (const controllers of localUploads.values()) { + for (const controller of controllers) controller.abort(); + } + // TR-04. Quiescence means both registries: the bounded wrappers and the + // raw provider work they may have outlived. A settling wrapper can still + // register more physical work, so the drain repeats until both are empty. + return (async () => { + while (activeOperations.size > 0 || physicalTasks.size > 0) { + await Promise.allSettled([...activeOperations, ...physicalTasks]); + } + return "DRAINED" as const; + })(); + } return runtime; } diff --git a/tests/unit/resumable-upload-runtime-teardown.test.ts b/tests/unit/resumable-upload-runtime-teardown.test.ts index d15b5c78..c33d0d1a 100644 --- a/tests/unit/resumable-upload-runtime-teardown.test.ts +++ b/tests/unit/resumable-upload-runtime-teardown.test.ts @@ -185,4 +185,57 @@ describe("TR-04 teardown waits for raw provider work, not only its wrapper", () await expect(disposing).resolves.toMatchObject({ ok: true }); expect(runtime.lifecycle()).toBe("CLOSED"); }); + + // R-1.1. The expired drain was cached, so a retry after the work settled + // returned the same failure and the store stayed open forever. + it("closes on a later dispose() once work that outlived the deadline settles", async () => { + const harness = createControlHarness(); + const checkpoints = new MemoryCheckpointStore(); + let releaseProvider: (() => void) | undefined; + harness.control.createSession = () => + new Promise((resolve) => { + releaseProvider = () => + resolve( + browserDataFailure("UNAVAILABLE", "UPLOAD_SESSION", { + retryable: true, + recovery: "RESUME", + }), + ); + }); + + const runtime = createResumableUploadRuntime({ + controlPlane: harness.control, + partExecutor: executorFor(harness), + checkpoints, + mutationLock: noContentionLock, + crypto, + policy: runtimePolicy({ + providerAttemptTimeoutMs: 5, + cleanupDeadlineMs: 25, + maxRetries: 0, + }), + now: () => 1_000, + random: () => 0, + sleep: async () => {}, + }); + + const uploading = runtime.upload({ + uploadKey: "upload_key_retry", + purpose: "attachment", + mediaType: "application/octet-stream", + source: byteStreamSource(new Uint8Array([1, 2, 3, 4, 5])), + signal: activeSignal, + }); + await vi.waitFor(() => expect(releaseProvider).toBeDefined()); + await uploading; + + const first = await runtime.dispose(); + expect(first.ok).toBe(false); + expect(runtime.lifecycle()).toBe("CLOSING"); + + releaseProvider?.(); + await expect(runtime.dispose()).resolves.toMatchObject({ ok: true }); + expect(runtime.lifecycle()).toBe("CLOSED"); + expect(checkpoints.closed).toBe(true); + }); });