Files
clean-architecture-frontend…/tests/unit/resumable-upload-runtime-contract.test.ts
T
DongHyeonkaandClaude Opus 5.5 7e610d1d05 refactor(browser-transfer): split validation and dependency snapshots out of the upload runtime (Q-6.1-10)
resumable-upload-runtime.ts carried the upload flow, retry/deadline, the
server response decoders and eight dependency snapshot wrappers in one
2.3k-line file. Moved without changing behavior:
- runtime-dependencies.ts: the dependency types, snapshotDependencies and
  its per-collaborator wrappers, safeNow/safeRandom and the default sleep.
- upload-response-validation.ts: validateSession, validateStatus,
  validatePartCapability, the receipt check and the small shared helpers
  (exactKeys, sameFingerprint, snapshotReceipts).
The runtime re-exports ResumableUploadRuntimeDependencies, so the public
surface is unchanged. The default sleep now waits on the kernel
createAbortableOperation instead of its own timer/listener pair, so the
moved file does not add a hand-rolled abort offender (ratchet stays 20/21).
INVENTORY and the detail review list the two files.

Verified: new characterization suite resumable-upload-runtime-contract
(invalid collaborators throw at composition, methods captured at
composition, frozen observer copies, throwing clock, default sleep retry
and abort, session/capability/status/receipt rejections) written and green
before the move, still green after + existing runtime suites + all gates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 13:33:05 +09:00

368 lines
11 KiB
TypeScript

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<TestCapability>> = {},
): ResumableUploadRuntimeDependencies<TestCapability> {
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<TestCapability>,
) {
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<TestCapability>
>[] = [
{
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<void>((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",
recovery: "RECONCILE",
},
});
});
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("restarts 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,
error: {
code: "EXPIRED_RESOURCE",
operation: "UPLOAD_SESSION",
recovery: "RESTART",
},
});
});
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,
error: {
code: "CORRUPT_DATA",
operation: "UPLOAD_PART",
recovery: "REISSUE_CAPABILITY",
},
});
});
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: "REISSUE_CAPABILITY",
},
});
});
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: "RECONCILE",
},
});
});
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");
});
});