Files
clean-architecture-frontend…/tests/unit/resumable-upload-runtime-contract.test.ts
T
DongHyeonka 9142390422 fix(browser-transfer): upload 실패 번역이 code도 보고 행동을 고른다 (0929/01-01)
문제: 포트는 upload() 실패의 recovery가 호출자 행동 하나를 가리킨다고
적는다. 번역은 toUploadAction 한 곳이 하는데 recovery 단어만 본다. 표
밖 값이면 REISSUE_CAPABILITY·RETRY만 RESUME, 나머지는 NONE으로 바꾸고
retryable은 그대로 둔다. 그래서 지난 리뷰 실험 X1의 경로들이 표와 다른
행동을 가리킨다.
- ① 고른 파일이 바뀜(NOT_READABLE/REOPEN): NONE에 retryable:true.
  표대로면 RESELECT다.
- ② IndexedDB 일시 오류(UNAVAILABLE/REOPEN, retryable:true): NONE.
  다시 부르면 성공한다.
- ③ part 발급 404(서버가 session을 모름): NONE. 다시 부르면 새
  session으로 성공한다.
- ⑤ 닫힌 runtime: RESUME. 같은 runtime은 늘 같은 답이다.
- ⑥ session보다 긴 capability(POLICY_REJECTED/REISSUE_CAPABILITY):
  RESUME. 서버가 같은 값을 다시 준다.

고른 방법(지난 리뷰 3절 D1의 (a), 번역 기준 보강): 번역은 계속 한 곳에
둔다. 몇 가지 code가 먼저 정한다. POLICY_REJECTED → NONE, file store의
NOT_READABLE/REOPEN → RESELECT, UPLOAD_PART의 NOT_FOUND → RECONCILE.
나머지는 지금처럼 표 안 값은 그대로 두고, 표 밖이면 retryable:true나
REISSUE_CAPABILITY·RETRY일 때 RESUME, 아니면 NONE이다. NONE과 RESELECT는
번역 끝에서 retryable:false로 맞춘다. 닫힌 runtime은 NONE을 돌려준다.
포트 표 주석과 설계 문서 표에 이 규칙을 적었다.

버린 대안:
- 리뷰 예시의 STALE_RESULT → RESELECT. 기존 STALE_RESULT/RECONCILE
  경로(resumable-upload-runtime.ts의 재조정)를 깨뜨린다. 지금
  STALE_RESULT는 모두 표 안 값을 갖고 있어 규칙이 필요 없다.
- 리뷰 예시의 NOT_READABLE → RESELECT(조건 없이). PUT 중 네트워크 읽기
  실패도 NOT_READABLE(REISSUE_CAPABILITY)이라 파일 재선택으로 잘못
  보낸다. 그래서 REOPEN(file store가 붙이는 값)일 때만 RESELECT다.
- 출처마다 포트 어휘를 만들게 하는 안(b), action 필드 추가(c). 지난
  리뷰가 다른 포트를 틀어지게 하거나 공유 타입을 바꾼다고 기각했다.

위험·한계:
- ④ part 발급(BFF) 401/403은 고치지 않았다. 지금도 RESUME이다. object
  store PUT 403(재발급으로 풀리고, 기존 01-05 표 테스트가 RESUME으로
  고정)과 code·단계·recovery가 모두 같아 번역 한 곳에서 가를 수 없다.
  리뷰 예시("PERMISSION_DENIED는 단계와 무관하게 NONE")와 보존 조건
  ("기존 7경로 기대값 유지")이 이 경로에서 서로 어긋난다. runtime
  호출 지점에서 발급 거절만 따로 표시할지는 소유자 판단이 필요하다.
  그래서 이 발견은 부분 충족이다.
- 몇 경로의 recovery 값이 바뀐다(위 ①②③⑤⑥). 기존 테스트 하나
  (resumable-upload-runtime-contract.test.ts "rejects a part capability
  that outlives its session")의 기대값을 RESUME → NONE으로 바꿨다.
  다운스트림 화면이 이 값으로 분기하므로 CHANGELOG [계약] 한 줄이
  필요하다. 이번 수정 묶음은 CHANGELOG를 한 번에 쓰므로 여기서는 쓰지
  않았다.
- 실제 브라우저 오류 발생은 재현하지 않았다. 단위 harness에서 오류
  값을 주입했다.
- file-transfer 레시피 번들이 55,937 → 56,031 gzip bytes가 되어 예산
  56,000을 넘었다. 다음 백 단위 규칙대로 56,100으로 올렸다.

검증:
- RED(수정 전): resumable-upload-runtime-recovery.test.ts 새 5건 실패.
  ① recovery NONE·retryable true(기대 RESELECT·false), ② NONE(기대
  RESUME), ③ NONE(기대 RECONCILE), ⑤ RESUME(기대 NONE), ⑥ RESUME(기대
  NONE). 수정 전 번역 규칙으로 되돌리면 같은 5건이 실패한다.
- GREEN: 같은 파일 통과. 기존 7경로 표 테스트에 "NONE이면
  retryable:false" 단언을 더했고 통과한다.
- 회귀: resumable-upload·presigned·upload-cancellation·browser-file·
  image-cdn 단위 20파일 326건 통과. tsc app·test·recipes 통과. 바꾼
  파일 eslint 통과. verify-documentation-readiness PASS_SCOPED.
  check-architecture(exec 전용 shim) 통과. check-optional-recipes
  (source) file-transfer 56031/56100.

Refs: docs/reviews/2026-09-29-maturity-review/01-adapters-browser-transfer.md
2026-11-01 23:14:48 +09:00

375 lines
12 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",
// 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,
// 0929/01-01. The server would issue the same capability again, so a
// new upload() only replays this refusal.
error: {
code: "POLICY_REJECTED",
operation: "UPLOAD_PART",
retryable: false,
recovery: "NONE",
},
});
});
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");
});
});