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 `45d2a478` (the pin) 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> = {}) { 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>, ) => ({ 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; }> | "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 = {}) { 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> = {}, ) => ({ 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("bad gateway", { 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 }, { 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, }, }); }, ); 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((resolve) => { sent = resolve; }); const fetcher = vi.fn( () => new Promise((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((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, request: Readonly>, ) => { 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); }); });