Files
DongHyeonka 762393a940 fix(contracts): 짝 백엔드 pin을 백엔드 main d32b4b53으로 옮긴다
문제: pin(45d2a478)이 백엔드 main보다 한참 뒤라 drift 검사가 exit 1이다.
그사이 백엔드가 폴더를 다시 배치하고(scaffold 원본 셋의 경로) 샘플을
지웠다. 계약 문서 6.1절 근거 파일 넷과 위치 목록이 main에 없고, 매뉴얼
04는 pin과 다른 bbe944bd를 기준이라 적는다. Fileserver 업로드 client의
게시 전 5xx 표는 pin 대조 밖이다(1105/01-02). 백엔드 697e62e8c부터
fileserver의 permit·pool 포화가 429에서 503 SERVER_BUSY로 바뀌어, client는
작업 전에 거절된 업로드를 결과 불명으로 읽는다.

고른 방법(R9-D4):
- pin, 답 표 source, 표 사본(--write-excerpt)을 d32b4b53으로 옮긴다.
  §4의 새 행 404 OPERATION_NOT_FOUND는 durable operation 조회의 답이라
  notCopied에 이유와 함께 둔다.
- scaffold 원본 세 경로를 새 위치로 고친다(내용 0줄 변경 확인).
- pin에 backend.codeSources를 더한다. Fileserver code 파일과 게시 전
  5xx 표(codes)를 적고, readers에 fileserver-upload.ts를 넣는다. drift
  검사가 그 파일들의 변경과, pin 커밋에 없는 경로(옮겨진 파일)를 알린다.
  pin 시험이 client 표와 pin 사본을 양쪽으로 대조한다.
- NOT_APPLIED_5XX_CODES에 SERVER_BUSY를 더한다. raise 자리 둘
  (TransferAdmissionController, BlockingTransferExecutor)이 모두 작업 전이다.
- 6.1절 표의 백엔드 파일:줄을 d32b4b53에서 다시 찾았다. 판정은 같다.
  샘플과 함께 사라진 근거(참조 도메인 행, WorkLogWebMapper 등)는 뺐고,
  새 출처(PatchBodies, 알림 컨트롤러 필드 거절)를 적었다.
- 매뉴얼 04의 기준을 pin으로 바꾸고 백엔드 경로 셋을 고친다.
버린 대안: 문서만 옛 pin 기준으로 맞추기 — drift 검사는 계속 막힌다.

위험·한계: V3 경로의 503 SERVER_BUSY는 상태만 정해진 모든 503에도 붙어
code로 단계를 가를 수 없다. 그래서 V3 표에 넣지 않고 결과 불명 쪽에
둔다(6.1절). 백엔드 main은 계속 움직이므로 다음 백엔드 병합 뒤 drift가
다시 1일 수 있다(설계된 신호).

검증: 노트북, 공유 clone(d32b4b53)으로
node scripts/check-backend-contract-drift.ts --backend <clone>: 옮기기 전
exit 1(문서·scaffold 4건), 옮긴 뒤 exit 0. desktop RED — pin·drift·
업로드 표 시험이 고치기 전 코드에서 실패
(/tmp/claude-gates/r9b-pr1-red/exec_node.log). merge 단계는 PR 본문.

Refs: 1112/02-05, 1112/08-18, 1105/01-02
2026-11-13 19:02:07 +09:00

790 lines
31 KiB
TypeScript

import { readFileSync } from "node:fs";
import { delay, HttpResponse, http, type JsonBodyType } from "msw";
import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { z } from "zod";
import type { FileByteSource } from "../../src/application/ports/browser-file-storage/file.ts";
import { envelopeFailureEffect } from "../../src/adapters/http/backend-envelope.ts";
import {
createFileserverUploadClient,
type CredentialPatchOutcome,
type FileserverUploadClientDependencies,
} from "../../src/adapters/http/index.ts";
import type { RestAuthProfile } from "../../src/contracts/rest-profiles.ts";
/**
* 2026-11-03 01-01. The paired backend Fileserver's `POST /v1/files`, answered
* as clean-architecture-backend-template at the pinned commit answers it in
* code, not only as its docs/fileserver/http-contract.md lists it.
*
* 1105/01-01. The document lists 202 VERIFYING alone. The code verifies the
* upload synchronously and answers 201 for `READY` and 202 for every other
* state (`FileUploadController#created`): `VERIFYING` (a verifier asked to
* retry), `QUARANTINED` and `REJECTED` (a refusal other than malware,
* `FinalizeUploadApplicationUseCase#applyNonAcceptVerdict`). The default
* verifier chain rejects an empty file that way (`LengthVerifier`). A record
* not yet published reports `application/octet-stream` (`FileRecord#toDescriptor`).
*
* Failure bodies, `details.ambiguous` and `Retry-After` follow the Fileserver
* handler; Envelope keys and the idempotency answers follow
* docs/web/http-contract.md §1–§2 (409 IDEMPOTENT_IN_FLIGHT with
* `Retry-After: 2`). The success body is `UploadedFileResponse` wrapped by
* `EnvelopeBodyAdvice`.
*/
const BASE_URL = "https://api.test/api/";
const UPLOAD_URL = "https://api.test/api/v1/files";
const FILE_ID = "6f1c2d3e-4a5b-4c6d-8e9f-0a1b2c3d4e5f";
const SHA256 = "a".repeat(64);
const META = Object.freeze({ requestId: "req-1", traceId: "trace-1" });
const COOKIE_PROFILE: RestAuthProfile = Object.freeze({
authProfileId: "BACKEND_SESSION",
transport: "SAME_ORIGIN_COOKIE",
credentials: "same-origin",
allowedCredentialHeaders: Object.freeze(["x-xsrf-token"] as const),
requiredCredentialHeaders: Object.freeze(["x-xsrf-token"] as const),
});
const server = setupServer();
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
function byteSource(
bytes: Uint8Array,
options: Readonly<{ byteLength?: number | null; chunkBytes?: number }> = {},
): FileByteSource {
const chunkBytes = options.chunkBytes ?? 3;
return Object.freeze({
byteLength:
options.byteLength === undefined ? bytes.byteLength : options.byteLength,
async *stream() {
for (let offset = 0; offset < bytes.byteLength; offset += chunkBytes) {
yield Object.freeze({
ok: true as const,
value: bytes.slice(offset, offset + chunkBytes),
});
}
},
});
}
const FILE_BYTES = new TextEncoder().encode("%PDF-1.7 tiny file");
function uploaded(state: string, overrides: Readonly<Record<string, unknown>> = {}) {
return {
fileId: FILE_ID,
state,
filename: "report.pdf",
mediaType: "application/pdf",
size: FILE_BYTES.byteLength,
sha256: SHA256,
etag: `"${SHA256}"`,
...overrides,
};
}
const successEnvelope = (data: unknown) => ({ success: true, data, meta: META });
const failureEnvelope = (
code: string,
category: string,
retryable: boolean,
details?: Readonly<Record<string, unknown>>,
) => ({
success: false,
error: {
code,
category,
message: "현재 상태에서는 요청을 처리할 수 없습니다.",
retryable,
...(details === undefined ? {} : { details }),
},
meta: META,
});
type Captured = Readonly<{
headers: Headers;
form: FormData;
}>;
/** Answers every upload with `answers[i]`, the last one repeating. */
function answer(
...answers: readonly (Readonly<{
status: number;
body: JsonBodyType;
headers?: Record<string, string>;
}> | "NETWORK_ERROR")[]
): Captured[] {
const captured: Captured[] = [];
server.use(
http.post(UPLOAD_URL, async ({ request }) => {
captured.push({
headers: request.headers,
form: await request.formData(),
});
const next = answers[Math.min(captured.length, answers.length) - 1];
if (!next || next === "NETWORK_ERROR") return HttpResponse.error();
return HttpResponse.json(next.body, {
status: next.status,
...(next.headers === undefined ? {} : { headers: next.headers }),
});
}),
);
return captured;
}
function client(overrides: Partial<FileserverUploadClientDependencies> = {}) {
const attachCredentials = vi.fn(
(): CredentialPatchOutcome => ({
kind: "READY",
headers: { "x-xsrf-token": "csrf-token-1" },
}),
);
return {
attachCredentials,
client: createFileserverUploadClient({
baseUrl: BASE_URL,
authProfile: COOKIE_PROFILE,
attachCredentials,
maxFileBytes: 1_024,
nowEpochMs: () => 1_000_000,
...overrides,
}),
};
}
const upload = (
overrides: Readonly<Record<string, unknown>> = {},
) => ({
source: byteSource(FILE_BYTES),
filename: "report.pdf",
mediaType: "application/pdf",
idempotencyKey: "upload-key-01",
signal: new AbortController().signal,
...overrides,
});
describe("Fileserver multipart upload — success", () => {
it("sends one multipart part named file and reads 201 READY", async () => {
const captured = answer({ status: 201, body: successEnvelope(uploaded("READY")) });
const { client: uploader, attachCredentials } = client();
const result = await uploader.upload(upload());
expect(result).toEqual({ ok: true, value: uploaded("READY") });
expect(captured).toHaveLength(1);
const [request] = captured;
const part = request?.form.get("file");
expect(part).toBeInstanceOf(File);
expect((part as File).name).toBe("report.pdf");
expect((part as File).type).toBe("application/pdf");
expect(new Uint8Array(await (part as File).arrayBuffer())).toEqual(FILE_BYTES);
expect([...(request?.form.keys() ?? [])]).toEqual(["file"]);
expect(request?.headers.get("idempotency-key")).toBe("upload-key-01");
expect(request?.headers.get("x-xsrf-token")).toBe("csrf-token-1");
expect(request?.headers.get("accept")).toBe("application/json");
expect(request?.headers.get("content-type")).toMatch(
/^multipart\/form-data; boundary=----FileserverUpload[0-9a-f]{32}$/u,
);
expect(attachCredentials).toHaveBeenCalledWith(
{ operationId: "FILESERVER_UPLOAD", authProfileId: "BACKEND_SESSION", method: "POST" },
expect.objectContaining({ signal: expect.any(AbortSignal) }),
);
});
it("reads 202 VERIFYING as a stored file that is not readable yet", async () => {
answer({ status: 202, body: successEnvelope(uploaded("VERIFYING")) });
const result = await client().client.upload(upload());
expect(result).toEqual({ ok: true, value: uploaded("VERIFYING") });
});
it("reads 202 QUARANTINED as a stored file held until an operator decides", async () => {
const held = uploaded("QUARANTINED", { mediaType: "application/octet-stream" });
answer({ status: 202, body: successEnvelope(held) });
const result = await client().client.upload(upload());
expect(result).toEqual({ ok: true, value: held });
});
it("reads 202 REJECTED as a refused file, not as a broken answer", async () => {
// 1105/01-01. A verifier refused the file for a reason other than malware.
// 1106/01-01. The server answered, so its `meta.traceId` comes with the
// failure for support to find the upload in the server logs.
answer({
status: 202,
body: successEnvelope(
uploaded("REJECTED", { mediaType: "application/octet-stream" }),
),
});
const result = await client().client.upload(upload());
expect(result).toEqual({
ok: false,
error: expect.objectContaining({
kind: "VALIDATION_REJECTED",
code: "FILE_REJECTED",
httpStatus: 202,
effect: "NOT_APPLIED",
retryable: false,
action: "none",
operationId: "FILESERVER_UPLOAD",
traceId: "trace-1",
}),
});
});
it("sends a source whose size is not declared up front", async () => {
const captured = answer({ status: 201, body: successEnvelope(uploaded("READY")) });
const result = await client().client.upload(
upload({ source: byteSource(FILE_BYTES, { byteLength: null }) }),
);
expect(result).toEqual({ ok: true, value: uploaded("READY") });
const part = captured[0]?.form.get("file") as File;
expect(new Uint8Array(await part.arrayBuffer())).toEqual(FILE_BYTES);
});
it("ignores a field the backend adds later instead of copying it", async () => {
answer({
status: 201,
body: successEnvelope(uploaded("READY", { storageKey: "never-copied" })),
});
const result = await client().client.upload(upload());
expect(result).toEqual({ ok: true, value: uploaded("READY") });
});
it("sends a UTF-8 filename and no key when the caller gives none", async () => {
const captured = answer({
status: 201,
body: successEnvelope(uploaded("READY", { filename: "보고서.pdf" })),
});
const result = await client().client.upload(
upload({ filename: "보고서.pdf", idempotencyKey: undefined }),
);
expect(result.ok).toBe(true);
expect((captured[0]?.form.get("file") as File).name).toBe("보고서.pdf");
expect(captured[0]?.headers.has("idempotency-key")).toBe(false);
});
it("uses the profile's Fetch policy, never the provider's", async () => {
const fetcher = vi.fn(
async (_input: RequestInfo | URL, _init?: RequestInit) =>
new Response(JSON.stringify(successEnvelope(uploaded("READY"))), {
status: 201,
headers: { "content-type": "application/json" },
}),
);
const result = await client({
fetcher: fetcher as unknown as typeof fetch,
}).client.upload(upload({ filename: 'a"b\r\nc.pdf' }));
expect(result.ok).toBe(true);
const [url, init] = fetcher.mock.calls[0] ?? [];
expect(url).toBe(UPLOAD_URL);
expect(init).toMatchObject({
method: "POST",
credentials: "same-origin",
redirect: "error",
referrerPolicy: "no-referrer",
cache: "no-store",
});
const head = new TextDecoder().decode(
(init?.body as Uint8Array).subarray(0, 200),
);
// The HTML form encoder's escaping, so the part header cannot be split.
expect(head).toContain('filename="a%22b%0D%0Ac.pdf"');
});
});
describe("Fileserver multipart upload — answers that do not match the contract", () => {
it.each([
["201 with a state that is not READY", 201, successEnvelope(uploaded("VERIFYING")), "SCHEMA_MISMATCH"],
["202 with READY", 202, successEnvelope(uploaded("READY")), "SCHEMA_MISMATCH"],
["201 with REJECTED", 201, successEnvelope(uploaded("REJECTED")), "SCHEMA_MISMATCH"],
["a size other than the bytes sent", 201, successEnvelope(uploaded("READY", { size: 1 })), "SCHEMA_MISMATCH"],
["the DTO without its Envelope", 201, uploaded("READY"), "ENVELOPE_MISMATCH"],
] as const)("%s is a created file the client cannot read", async (_label, status, body, kind) => {
answer({ status, body });
const result = await client().client.upload(upload());
// Created, so the user must not upload it again; the id is not known.
expect(result).toMatchObject({
ok: false,
error: { kind, effect: "APPLIED_CONFIRMED", retryable: false, httpStatus: status },
});
});
it("reads a gateway 502 without an Envelope as a server outage that may have applied", async () => {
server.use(
http.post(UPLOAD_URL, () =>
new HttpResponse("<html>bad gateway</html>", {
status: 502,
headers: { "content-type": "text/html" },
}),
),
);
const result = await client().client.upload(upload());
expect(result).toMatchObject({
ok: false,
error: { kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", retryable: false },
});
});
it("refuses a response body above maxResponseBytes", async () => {
answer({
status: 201,
body: successEnvelope(uploaded("READY", { filename: "x".repeat(900) })),
});
const result = await client({ maxResponseBytes: 256 }).client.upload(upload());
expect(result).toMatchObject({
ok: false,
error: { kind: "RESPONSE_BODY_LIMIT", effect: "APPLIED_CONFIRMED" },
});
});
});
describe("Fileserver multipart upload — Envelope failures", () => {
it.each([
{ status: 400, code: "IDEMPOTENCY_KEY_INVALID", category: "VALIDATION", retryable: false, kind: "UNKNOWN_CLIENT_FAILURE", effect: "NOT_APPLIED", clientRetryable: false },
{ status: 401, code: "UNAUTHENTICATED", category: "AUTH", retryable: false, kind: "AUTH_REQUIRED", effect: "NOT_APPLIED", clientRetryable: false },
{ status: 403, code: "ACCESS_DENIED", category: "AUTHZ", retryable: false, kind: "FORBIDDEN", effect: "NOT_APPLIED", clientRetryable: false },
{ status: 413, code: "FILE_TOO_LARGE", category: "VALIDATION", retryable: false, kind: "VALIDATION_REJECTED", effect: "NOT_APPLIED", clientRetryable: false },
{ status: 413, code: "QUOTA_EXCEEDED", category: "CONFLICT", retryable: false, kind: "VALIDATION_REJECTED", effect: "NOT_APPLIED", clientRetryable: false },
{ status: 415, code: "UNSUPPORTED_MEDIA_TYPE", category: "VALIDATION", retryable: false, kind: "VALIDATION_REJECTED", effect: "NOT_APPLIED", clientRetryable: false },
{ status: 422, code: "MALWARE_DETECTED", category: "DATA_INTEGRITY", retryable: false, kind: "VALIDATION_REJECTED", effect: "NOT_APPLIED", clientRetryable: false },
{ status: 422, code: "IDEMPOTENT_REQUEST_MISMATCH", category: "VALIDATION", retryable: false, kind: "UNKNOWN_CLIENT_FAILURE", effect: "NOT_APPLIED", clientRetryable: false },
{ status: 500, code: "PARTIAL_WRITE", category: "TRANSIENT_DEPENDENCY", retryable: false, kind: "SERVER_FAILURE", effect: "NOT_APPLIED", clientRetryable: false },
{ status: 500, code: "AMBIGUOUS_COMPLETION", category: "DATA_INTEGRITY", retryable: false, details: { ambiguous: true, reconciliationRequired: true }, kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", clientRetryable: false },
{ status: 500, code: "INTERNAL_ERROR", category: "INTERNAL", retryable: false, kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", clientRetryable: false },
{ status: 503, code: "STORAGE_UNAVAILABLE", category: "TRANSIENT_DEPENDENCY", retryable: true, kind: "SERVER_FAILURE", effect: "NOT_APPLIED", clientRetryable: true },
// 1105/01-04. The atomic move itself was refused: nothing was published.
{ status: 503, code: "ATOMIC_PUBLISH_UNSUPPORTED", category: "PERMANENT_DEPENDENCY", retryable: false, kind: "SERVER_FAILURE", effect: "NOT_APPLIED", clientRetryable: false },
{ status: 503, code: "STORAGE_UNAVAILABLE", category: "TRANSIENT_DEPENDENCY", retryable: true, details: { ambiguous: true }, kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", clientRetryable: false },
// 1105/01-02. As the V3 table reads it: only an unknown result keeps the key.
{ status: 503, code: "IDEMPOTENCY_UNAVAILABLE", category: "TRANSIENT_DEPENDENCY", retryable: true, kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", clientRetryable: false },
{ status: 503, code: "IDEMPOTENCY_COMPLETION_UNKNOWN", category: "TRANSIENT_DEPENDENCY", retryable: true, kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", clientRetryable: false },
// 1112/02-05. A full server, refused before the work runs (backend 697e62e8c).
{ status: 503, code: "SERVER_BUSY", category: "TRANSIENT_DEPENDENCY", retryable: true, kind: "SERVER_FAILURE", effect: "NOT_APPLIED", clientRetryable: true },
{ status: 507, code: "STORAGE_FULL", category: "TRANSIENT_DEPENDENCY", retryable: false, kind: "SERVER_FAILURE", effect: "NOT_APPLIED", clientRetryable: false },
// 1105/01-02. Raised by the waiting thread at any stage of the work, which
// may still publish the file: the backend's own retryable:true does not
// make a resend safe.
{ status: 504, code: "TRANSFER_TIMEOUT", category: "TRANSIENT_DEPENDENCY", retryable: true, kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", clientRetryable: false },
])(
"$status $code → $kind, $effect, retryable $clientRetryable",
async ({ status, code, category, retryable, details, kind, effect, clientRetryable }) => {
answer({ status, body: failureEnvelope(code, category, retryable, details) });
const result = await client().client.upload(upload());
expect(result).toMatchObject({
ok: false,
error: {
kind,
code,
httpStatus: status,
effect,
retryable: clientRetryable,
operationId: "FILESERVER_UPLOAD",
// 1105/01-03. The Envelope's meta.traceId, as V3 carries it.
traceId: META.traceId,
},
});
},
);
// 1112/07-01. A 401 is the server's verdict on the credential the upload
// carried; the composition hears it through `onUnauthenticated`.
it("tells onUnauthenticated once about a 401, and about nothing else", async () => {
const onUnauthenticated = vi.fn();
answer({ status: 401, body: failureEnvelope("UNAUTHENTICATED", "AUTH", false) });
const result = await client({ onUnauthenticated }).client.upload(upload());
expect(result).toMatchObject({ ok: false, error: { kind: "AUTH_REQUIRED" } });
expect(onUnauthenticated).toHaveBeenCalledExactlyOnceWith({
operationId: "FILESERVER_UPLOAD",
authProfileId: expect.any(String),
});
onUnauthenticated.mockClear();
answer({ status: 403, body: failureEnvelope("ACCESS_DENIED", "AUTHZ", false) });
await client({ onUnauthenticated }).client.upload(upload());
expect(onUnauthenticated).not.toHaveBeenCalled();
});
it("keeps the 401 outcome when onUnauthenticated throws", async () => {
answer({ status: 401, body: failureEnvelope("UNAUTHENTICATED", "AUTH", false) });
const result = await client({
onUnauthenticated: () => {
throw new Error("hook defect");
},
}).client.upload(upload());
expect(result).toMatchObject({ ok: false, error: { kind: "AUTH_REQUIRED" } });
});
it("carries no traceId when the failure Envelope has none", async () => {
const envelope = failureEnvelope("STORAGE_UNAVAILABLE", "TRANSIENT_DEPENDENCY", true);
answer({
status: 503,
body: { success: envelope.success, error: envelope.error, meta: { requestId: "req-1" } },
});
const result = await client().client.upload(upload());
expect(result.ok).toBe(false);
expect(result.ok ? undefined : Object.hasOwn(result.error, "traceId")).toBe(false);
});
it("409 IDEMPOTENT_IN_FLIGHT keeps the server's wait and asks for the same key", async () => {
const captured = answer(
{
status: 409,
body: failureEnvelope("IDEMPOTENT_IN_FLIGHT", "CONFLICT", true),
headers: { "Retry-After": "2" },
},
{ status: 201, body: successEnvelope(uploaded("READY")) },
);
const { client: uploader } = client();
const inFlight = await uploader.upload(upload());
expect(inFlight).toMatchObject({
ok: false,
error: {
kind: "CONFLICT",
code: "IDEMPOTENT_IN_FLIGHT",
effect: "MAYBE_APPLIED",
// Not a fresh retry: the caller resends the same request on purpose.
retryable: false,
retryAfterMs: 2_000,
},
});
// The client never resends on its own.
expect(captured).toHaveLength(1);
const resent = await uploader.upload(upload());
expect(resent).toEqual({ ok: true, value: uploaded("READY") });
expect(captured.map(({ headers }) => headers.get("idempotency-key"))).toEqual([
"upload-key-01",
"upload-key-01",
]);
});
it("504 TRANSFER_TIMEOUT is an unknown result the client does not offer to retry", async () => {
// 1105/01-02. The backend sends Retry-After: 5 with it.
answer({
status: 504,
body: failureEnvelope("TRANSFER_TIMEOUT", "TRANSIENT_DEPENDENCY", true),
headers: { "Retry-After": "5" },
});
const result = await client().client.upload(upload());
expect(result).toMatchObject({
ok: false,
error: {
kind: "SERVER_FAILURE",
code: "TRANSFER_TIMEOUT",
effect: "MAYBE_APPLIED",
retryable: false,
action: "contact-support",
},
});
});
it.each([
{ retryAfter: "3", retryable: true, retryAfterMs: 3_000 },
// 2026-11-03 01-02: past the ceiling, neither the wait nor an immediate retry.
{ retryAfter: "45", retryable: false, retryAfterMs: undefined },
])(
"429 TRANSFER_ADMISSION_REJECTED with Retry-After $retryAfter",
async ({ retryAfter, retryable, retryAfterMs }) => {
answer({
status: 429,
body: failureEnvelope("TRANSFER_ADMISSION_REJECTED", "RATE_LIMIT", true),
headers: { "Retry-After": retryAfter },
});
const result = await client().client.upload(upload());
expect(result).toMatchObject({
ok: false,
error: { kind: "RATE_LIMITED", effect: "NOT_APPLIED", retryable },
});
expect(result.ok ? undefined : result.error.retryAfterMs).toBe(retryAfterMs);
},
);
});
/**
* 1105/01-02. The backend answer table copied next to the pin
* (config/contracts/backend-contract-pin.json) holds the V3 Envelope table in
* tests/unit/backend-contract-pin.test.ts. The same rows hold this client, so
* one backend code has one verdict and a pin move rechecks both readers.
*/
const PINNED_ANSWERS = (() => {
const pin = z
.object({ tables: z.object({ idempotencyAnswers: z.string().min(1) }) })
.parse(JSON.parse(readFileSync("config/contracts/backend-contract-pin.json", "utf8")));
return z
.object({
answers: z
.array(z.object({ code: z.string().min(1), status: z.number().int() }))
.min(1),
})
.parse(JSON.parse(readFileSync(pin.tables.idempotencyAnswers, "utf8"))).answers;
})();
describe("Fileserver multipart upload — the pinned backend answer table", () => {
it.each(PINNED_ANSWERS.map((row) => [`${row.status} ${row.code}`, row] as const))(
"reads %s as the V3 Envelope table does",
async (_label, row) => {
answer({
status: row.status,
body: failureEnvelope(row.code, "TRANSIENT_DEPENDENCY", false),
});
const result = await client().client.upload(upload());
expect(result.ok ? undefined : result.error.effect).toBe(
envelopeFailureEffect(row.status, { code: row.code }),
);
},
);
});
describe("Fileserver multipart upload — unknown results", () => {
it("a network failure after sending is MAYBE_APPLIED, and the resend keeps the key", async () => {
const captured = answer("NETWORK_ERROR", {
status: 201,
body: successEnvelope(uploaded("READY")),
});
const { client: uploader } = client();
const lost = await uploader.upload(upload());
expect(lost).toMatchObject({
ok: false,
error: { kind: "NETWORK_UNREACHABLE", effect: "MAYBE_APPLIED", retryable: false },
});
const resent = await uploader.upload(upload());
expect(resent).toEqual({ ok: true, value: uploaded("READY") });
expect(captured.map(({ headers }) => headers.get("idempotency-key"))).toEqual([
"upload-key-01",
"upload-key-01",
]);
});
it("ends at the deadline as REQUEST_TIMEOUT that may have applied", async () => {
server.use(
http.post(UPLOAD_URL, async () => {
await delay("infinite");
return HttpResponse.json({});
}),
);
const result = await client({
timeoutMs: 30,
minTransferBytesPerSecond: 1_000_000_000,
}).client.upload(upload());
expect(result).toMatchObject({
ok: false,
error: { kind: "REQUEST_TIMEOUT", effect: "MAYBE_APPLIED", retryable: false },
});
});
it("adds the file's transfer allowance to the base deadline", async () => {
// 1105/01-04. At one byte per second the file earns one second per byte
// on top of the one-second base, so an answer after 1.5 s still counts.
// Without the allowance a large file on a slow uplink ends at the base.
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
try {
let respond: (response: Response) => void = () => {};
let sent: () => void = () => {};
const requestSent = new Promise<void>((resolve) => {
sent = resolve;
});
const fetcher = vi.fn(
() =>
new Promise<Response>((resolve) => {
respond = resolve;
sent();
}),
);
const { client: uploader, attachCredentials } = client({
fetcher: fetcher as unknown as typeof fetch,
timeoutMs: 1_000,
minTransferBytesPerSecond: 1,
monotonicNow: () => 0,
});
const pending = uploader.upload(upload());
await requestSent;
await vi.advanceTimersByTimeAsync(1_500);
respond(
new Response(JSON.stringify(successEnvelope(uploaded("READY"))), {
status: 201,
headers: { "content-type": "application/json" },
}),
);
expect(await pending).toEqual({ ok: true, value: uploaded("READY") });
expect(attachCredentials).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
deadlineAtMonotonicMs: 1_000 + FILE_BYTES.byteLength * 1_000,
}),
);
} finally {
vi.useRealTimers();
}
});
it("a caller abort after sending may have applied; before sending it did not", async () => {
const controller = new AbortController();
let arrived: () => void = () => {};
const requestArrived = new Promise<void>((resolve) => {
arrived = resolve;
});
server.use(
http.post(UPLOAD_URL, async () => {
arrived();
await delay("infinite");
return HttpResponse.json({});
}),
);
const { client: uploader } = client();
const pending = uploader.upload(upload({ signal: controller.signal }));
await requestArrived;
controller.abort();
expect(await pending).toMatchObject({
ok: false,
error: { kind: "REQUEST_ABORTED", effect: "MAYBE_APPLIED" },
});
const fetcher = vi.fn();
const aborted = await client({
fetcher: fetcher as unknown as typeof fetch,
}).client.upload(upload({ signal: controller.signal }));
expect(aborted).toMatchObject({
ok: false,
error: { kind: "REQUEST_ABORTED", effect: "NOT_STARTED" },
});
expect(fetcher).not.toHaveBeenCalled();
});
});
describe("Fileserver multipart upload — refused before sending", () => {
const unsent = async (
overrides: Partial<FileserverUploadClientDependencies>,
request: Readonly<Record<string, unknown>>,
) => {
const fetcher = vi.fn();
const result = await client({
fetcher: fetcher as unknown as typeof fetch,
...overrides,
}).client.upload(upload(request));
expect(fetcher).not.toHaveBeenCalled();
return result;
};
it.each([
["a declared size above maxFileBytes", { source: byteSource(new Uint8Array(2_000)) }, "VALIDATION_REJECTED", "FILE_TOO_LARGE"],
// 1105/01-01. The backend's default verifier chain rejects these.
["an empty file", { source: byteSource(new Uint8Array(0)) }, "VALIDATION_REJECTED", "FILE_EMPTY"],
["an undeclared size that turns out empty", { source: byteSource(new Uint8Array(0), { byteLength: null }) }, "VALIDATION_REJECTED", "FILE_EMPTY"],
["an undeclared size that grows past maxFileBytes", { source: byteSource(new Uint8Array(2_000), { byteLength: null, chunkBytes: 512 }) }, "VALIDATION_REJECTED", "FILE_TOO_LARGE"],
["a file that shrank after selection", { source: byteSource(FILE_BYTES, { byteLength: FILE_BYTES.byteLength + 1 }) }, "VALIDATION_REJECTED", "FILE_NOT_READABLE"],
["a file that grew after selection", { source: byteSource(FILE_BYTES, { byteLength: FILE_BYTES.byteLength - 1 }) }, "VALIDATION_REJECTED", "FILE_NOT_READABLE"],
["a key outside the backend's key grammar", { idempotencyKey: "has space" }, "UNKNOWN_CLIENT_FAILURE", "FILESERVER_UPLOAD_INPUT_INVALID"],
["a media type that is not a type/subtype", { mediaType: "pdf" }, "UNKNOWN_CLIENT_FAILURE", "FILESERVER_UPLOAD_INPUT_INVALID"],
] as const)("%s", async (_label, request, kind, code) => {
expect(await unsent({}, request)).toMatchObject({
ok: false,
error: { kind, code, effect: "NOT_STARTED" },
});
});
it("refuses a declared size above maxFileBytes without reading a byte", async () => {
// 1105/01-04. Before the body buffer is sized from the declared length.
const stream = vi.fn(async function* () {
yield { ok: true as const, value: new Uint8Array(3) };
});
const source: FileByteSource = { byteLength: 2_000, stream };
expect(await unsent({}, { source })).toMatchObject({
ok: false,
error: { kind: "VALIDATION_REJECTED", code: "FILE_TOO_LARGE", effect: "NOT_STARTED" },
});
expect(stream).not.toHaveBeenCalled();
});
it("a source that fails mid-stream is not readable", async () => {
const source: FileByteSource = {
byteLength: 6,
async *stream() {
yield { ok: true as const, value: new Uint8Array(3) };
yield {
ok: false as const,
error: {
code: "NOT_READABLE",
operation: "FILE_READ",
retryable: false,
recovery: "REOPEN",
},
};
},
};
expect(await unsent({}, { source })).toMatchObject({
ok: false,
error: { kind: "VALIDATION_REJECTED", code: "FILE_NOT_READABLE", effect: "NOT_STARTED" },
});
});
it.each([
["no session", { kind: "UNAUTHENTICATED" }, "AUTH_REQUIRED", "UNAUTHENTICATED"],
["a header the profile does not allow", { kind: "READY", headers: { authorization: "Bearer t" } }, "AUTH_INTEGRATION_FAILURE", "CREDENTIAL_HEADER_NOT_ALLOWED"],
["the profile's required header missing", { kind: "READY", headers: {} }, "AUTH_INTEGRATION_FAILURE", "MISSING_REQUIRED_CREDENTIAL_HEADER"],
["a session change in progress", { kind: "SCOPE_FENCED" }, "SCOPE_GENERATION_CHANGED", "SCOPE_FENCED"],
] as const)("credentials: %s", async (_label, outcome, kind, code) => {
const result = await unsent(
{ attachCredentials: () => outcome as CredentialPatchOutcome },
{},
);
expect(result).toMatchObject({
ok: false,
error: { kind, code, effect: "NOT_STARTED" },
});
});
it.each([
["a base URL whose path does not end in a slash", { baseUrl: "https://api.test/api" }],
["no maxFileBytes", { maxFileBytes: undefined as unknown as number }],
["a non-http base URL", { baseUrl: "file:///tmp/" }],
])("refuses to compose with %s", (_label, overrides) => {
expect(() => client(overrides)).toThrow(TypeError);
});
});