import { describe, expect, it } from "vitest"; import type { BrowserDataObservation } from "../../src/application/ports/browser-file-storage/shared.ts"; import { browserDataFailure, browserDataSuccess, } from "../../src/adapters/browser-file-storage/result.ts"; import { createResumableUploadRuntime, type ResumableUploadRuntimeDependencies, } from "../../src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts"; import { activeSignal, createControlHarness, executorFor, MemoryCheckpointStore, noContentionLock, rangeSource, runtimePolicy, type ControlHarness, type TestCapability, } from "./resumable-upload-runtime-fixture.ts"; /** * Q-6.1-10. Characterization of the two blocks moved out of the runtime file: * the dependency snapshot wrappers and the server response validators. The * other runtime suites reach them only on their happy paths. */ function dependencies( harness: ControlHarness, overrides: Partial> = {}, ): ResumableUploadRuntimeDependencies { return { controlPlane: harness.control, partExecutor: executorFor(harness), checkpoints: new MemoryCheckpointStore(), mutationLock: noContentionLock, crypto, policy: runtimePolicy(), now: () => 1_000, random: () => 0, sleep: async () => {}, ...overrides, }; } async function upload( input: ResumableUploadRuntimeDependencies, ) { return await createResumableUploadRuntime(input).upload({ uploadKey: "upload_key_contract", purpose: "attachment", mediaType: "application/octet-stream", source: rangeSource(new Uint8Array([1, 2, 3, 4, 5])), signal: activeSignal, }); } describe("resumable upload runtime dependency snapshots", () => { it("rejects an invalid collaborator at composition", () => { const harness = createControlHarness(); const invalid: Partial< ResumableUploadRuntimeDependencies >[] = [ { controlPlane: { ...harness.control, abort: undefined, } as unknown as typeof harness.control, }, { partExecutor: {} as never }, { checkpoints: { read: async () => browserDataSuccess(null), } as never, }, { checkpoints: Object.assign(new MemoryCheckpointStore(), { removeUnreadable: "not a function", }) as never, }, { mutationLock: {} as never }, { crossContextCancellation: { publish: () => true, subscribe: () => () => {}, } as never, }, { crossContextCancellation: { publish: () => true, subscribe: () => "not a release", close: () => {}, } as never, }, { observer: {} as never }, { now: 1_000 as never }, { random: "0" as never }, { sleep: 1 as never }, ]; for (const override of invalid) { expect( () => createResumableUploadRuntime(dependencies(harness, override)), Object.keys(override).join(","), ).toThrow(TypeError); } }); it("captures collaborator methods once at composition", async () => { const harness = createControlHarness(); const runtime = createResumableUploadRuntime(dependencies(harness)); harness.control.createSession = async () => { throw new Error("replaced after composition"); }; await expect( runtime.upload({ uploadKey: "upload_key_contract", purpose: "attachment", mediaType: "application/octet-stream", source: rangeSource(new Uint8Array([1, 2, 3, 4, 5])), signal: activeSignal, }), ).resolves.toMatchObject({ ok: true, value: { state: "QUARANTINED" }, }); }); it("hands the observer frozen copies and survives a throwing one", async () => { const observations: BrowserDataObservation[] = []; const harness = createControlHarness(); await expect( upload( dependencies(harness, { observer: { record(observation) { observations.push(observation); throw new Error("observer failure"); }, }, }), ), ).resolves.toMatchObject({ ok: true }); expect(observations.length).toBeGreaterThan(0); expect(observations.every((value) => Object.isFrozen(value))).toBe(true); }); it("sleeps between retries with the default timer when none is injected", async () => { const harness = createControlHarness(); const create = harness.control.createSession.bind(harness.control); let creates = 0; harness.control.createSession = async (input) => { creates += 1; return creates === 1 ? browserDataFailure("UNAVAILABLE", "UPLOAD_SESSION", { retryable: true, recovery: "RESUME", }) : await create(input); }; const { sleep: _injected, ...withoutSleep } = dependencies(harness); await expect(upload(withoutSleep)).resolves.toMatchObject({ ok: true, value: { state: "QUARANTINED" }, }); expect(creates).toBe(2); }); it("ends the default retry sleep when the caller aborts", async () => { const harness = createControlHarness(); let failed: () => void = () => {}; const firstFailure = new Promise((resolve) => { failed = resolve; }); harness.control.createSession = async () => { failed(); return browserDataFailure("UNAVAILABLE", "UPLOAD_SESSION", { retryable: true, recovery: "RESUME", }); }; const { sleep: _injected, ...withoutSleep } = dependencies(harness, { policy: runtimePolicy({ retryBaseDelayMs: 60_000, retryMaxDelayMs: 60_000, }), }); const controller = new AbortController(); const uploading = createResumableUploadRuntime(withoutSleep).upload({ uploadKey: "upload_key_contract", purpose: "attachment", mediaType: "application/octet-stream", source: rangeSource(new Uint8Array([1, 2, 3, 4, 5])), signal: controller.signal, }); await firstFailure; controller.abort(); await expect(uploading).resolves.toMatchObject({ ok: false, error: { code: "ABORTED" }, }); }); it("treats a throwing clock as UNAVAILABLE", async () => { const harness = createControlHarness(); await expect( upload( dependencies(harness, { now: () => { throw new Error("clock"); }, }), ), ).resolves.toMatchObject({ ok: false, error: { code: "UNAVAILABLE", operation: "UPLOAD_SESSION" }, }); }); }); describe("resumable upload runtime server response validation", () => { it("rejects a created session with an unknown field", async () => { const harness = createControlHarness(); const create = harness.control.createSession.bind(harness.control); harness.control.createSession = async (input) => { const created = await create(input); return created.ok ? browserDataSuccess({ ...created.value, uploadUrl: "https://objects.invalid/secret", }) : created; }; await expect(upload(dependencies(harness))).resolves.toMatchObject({ ok: false, error: { code: "INTEGRITY_FAILED", operation: "UPLOAD_SESSION", // 01-05. The create key replays the same answer. recovery: "NONE", }, }); }); it("rejects a session concurrency above the local policy", async () => { const harness = createControlHarness({ serverMaxConcurrency: 4 }); await expect(upload(dependencies(harness))).resolves.toMatchObject({ ok: false, error: { code: "INTEGRITY_FAILED", operation: "UPLOAD_SESSION" }, }); }); it("refuses a session whose lifetime exceeds the policy ceiling", async () => { const harness = createControlHarness(); const create = harness.control.createSession.bind(harness.control); harness.control.createSession = async (input) => { const created = await create(input); return created.ok ? browserDataSuccess({ ...created.value, expiresAtEpochMs: 1_000 + 20_000, }) : created; }; await expect(upload(dependencies(harness))).resolves.toMatchObject({ ok: false, // 01-05. A restart gets the same session back, so there is no caller // action; this is a server/policy mismatch. error: { code: "POLICY_REJECTED", operation: "UPLOAD_SESSION", recovery: "NONE", }, }); }); it("rejects a part capability with an unknown field", async () => { const harness = createControlHarness({ issueCapability: (input) => browserDataSuccess({ capability: Object.freeze({ id: "cap" }), uploadBindingSha256: input.uploadBindingSha256, expiresAtEpochMs: 1_000 + 4_000, href: "https://objects.invalid/secret", } as never), }); await expect(upload(dependencies(harness))).resolves.toMatchObject({ ok: false, // 01-05. The caller's action for a capability refusal is upload(). error: { code: "CORRUPT_DATA", operation: "UPLOAD_PART", recovery: "RESUME", }, }); }); it("rejects a part capability that outlives its session", async () => { const harness = createControlHarness({ issueCapability: (input) => browserDataSuccess({ capability: Object.freeze({ id: "cap" }), uploadBindingSha256: input.uploadBindingSha256, expiresAtEpochMs: 1_000 + 5_000 + 1, }), }); await expect(upload(dependencies(harness))).resolves.toMatchObject({ ok: false, error: { code: "POLICY_REJECTED", operation: "UPLOAD_PART", recovery: "RESUME", }, }); }); it("rejects a status in a state outside the protocol", async () => { const harness = createControlHarness(); harness.control.getStatus = async (input) => browserDataSuccess({ state: "PAUSED", protocol: input.protocol, sessionId: input.sessionId, requestBindingSha256: input.requestBindingSha256, } as never); await expect(upload(dependencies(harness))).resolves.toMatchObject({ ok: false, error: { code: "INTEGRITY_FAILED", operation: "UPLOAD_RECONCILE", recovery: "RESTART", }, }); }); it("rejects server receipts that are out of part order", async () => { const harness = createControlHarness({ statusParts: (_session, accepted) => [...accepted.values()].sort( (left, right) => right.partNumber - left.partNumber, ), }); // The first status has no parts; once parts are accepted the reversed // list is what the final reconcile reads. await expect(upload(dependencies(harness))).resolves.toMatchObject({ ok: false, error: { code: "INTEGRITY_FAILED", operation: "UPLOAD_RECONCILE" }, }); }); it("treats a definitive not-found status as terminal and restarts", async () => { const harness = createControlHarness({ sessionId: (index) => `session_0${index}`, }); let statusCalls = 0; const status = harness.control.getStatus.bind(harness.control); harness.control.getStatus = async (input) => { statusCalls += 1; return statusCalls === 1 ? browserDataFailure("NOT_FOUND", "UPLOAD_RECONCILE") : await status(input); }; await expect(upload(dependencies(harness))).resolves.toMatchObject({ ok: true, value: { state: "QUARANTINED", replayed: false }, }); expect(harness.getSession()?.sessionId).toBe("session_02"); }); });