Files
clean-architecture-frontend…/tests/integration/fileserver-upload.test.ts
T
DongHyeonka 6608fef4ba fix(http): Fileserver 202 REJECTED를 파일 거절로 읽고 빈 파일은 보내지 않는다
문제: 짝 백엔드(45d2a478)는 POST /v1/files를 요청 안에서 동기로 검증하고
READY가 아닌 state를 모두 202로 답한다(FileUploadController#created).
악성 코드가 아닌 이유로 검증기가 거절하면 예외 없이 202 REJECTED다
(FinalizeUploadApplicationUseCase#applyNonAcceptVerdict). 기본 검증기 사슬의
첫 검증기(LengthVerifier)가 빈 파일을 그렇게 거절하므로, 0바이트 파일
하나로 닿는다. client schema에는 REJECTED가 없어 이 답이 SCHEMA_MISMATCH,
APPLIED_CONFIRMED, "응답 형식 오류" 문구로 끝난다. 사용자는 파일을 바꾸라는
안내 대신 지원 문의를 보게 된다. 테스트의 MSW는 202 VERIFYING만 적은 백엔드
문서에서 왔고, 매뉴얼도 202를 "아직 검사 중"으로 적어 QUARANTINED(동기
검증 202의 대부분)를 끝나지 않는 대기로 보이게 한다.

고른 방법(리뷰 01-01 최소 개선 방향 (가)):
- schema가 REJECTED를 받는다. 202 REJECTED는 성공이 아니라 실패
  VALIDATION_REJECTED, code FILE_REJECTED, NOT_APPLIED, httpStatus 202다.
  413·415·422 파일 거절과 같은 규칙이다. 백엔드는 그 레코드를 공개하지
  않고 바이트 정리를 예약하므로 쓸 수 있는 파일이 남지 않는다. 공개 타입
  FileserverFileState와 FileserverUploadedFile은 바꾸지 않았다(REJECTED는
  성공 값으로 나오지 않는다).
- 빈 파일은 읽기 전(선언 크기 0) 또는 읽은 뒤(선언 없음, 0바이트)
  보내지 않고 FILE_EMPTY, NOT_STARTED로 끝낸다. 서버의 202 REJECTED에는
  이유가 없어 기능이 "빈 파일"이라고 말할 수 없기 때문이다.
- 201⇔READY 검사, size 일치 검사, 모르는 필드 무시는 그대로다. 201
  REJECTED는 여전히 SCHEMA_MISMATCH다.
- MSW 설명을 백엔드 코드(45d2a478) 기준으로 고치고 202 QUARANTINED·
  REJECTED 행을 더했다(1103/01-01의 "MSW가 문서에서 왔다" 부분).
- 매뉴얼 7절이 202 state 셋의 뜻(VERIFYING 재검사 대기, QUARANTINED 관리자
  결정 전 내려받기 불가, REJECTED는 실패)과 FILE_EMPTY를 적는다.
버린 대안:
- REJECTED를 성공 state로 넘긴다: 타입 변경은 작지만 기능마다 성공 값에서
  거절을 다시 찾아야 하고, 공개 타입 FileserverFileState가 넓어진다.
- 빈 파일 거절만 한다: 기본 사슬은 막지만 제품이 더한 검증기의 REJECT는
  그대로 SCHEMA_MISMATCH다.

위험·한계:
- upload() 결과가 바뀐다. 202 REJECTED가 SCHEMA_MISMATCH에서
  VALIDATION_REJECTED/FILE_REJECTED로, 빈 파일이 서버 요청에서 FILE_EMPTY로
  바뀐다. CHANGELOG [계약] 한 줄이 필요하다.
- 빈 파일 거절은 짝 백엔드 기본 검증기 사슬을 가정한다. 제품이 사슬에서
  LengthVerifier를 빼 빈 파일을 받게 하면 client 규칙도 바꿔야 한다.
- 실제 짝 백엔드를 띄워 빈 파일을 올려 보지 않았다(미검증). 응답 모양은
  백엔드 코드(UploadedFileResponse, FileRecord#toDescriptor)를 읽은 것이다.
- 1103/01-01의 남은 부분은 이 커밋 밖이다: 백엔드 매뉴얼의 짝 경로 안내와
  docs/fileserver/http-contract.md의 202 state 목록(백엔드로 넘김), 실제
  업로드 검증(미검증).

검증: desktop batch에서 확인.
node scripts/run-vitest.ts run tests/integration/fileserver-upload.test.ts
RED(이 커밋의 테스트 + 부모 src): "reads 202 REJECTED as a refused file,
not as a broken answer"(SCHEMA_MISMATCH로 끝남), "an empty file", "an
undeclared size that turns out empty"(fetch를 부름)가 실패한다.

Refs: 1105/01-01, 1103/01-01
2026-11-05 22:07:43 +09:00

607 lines
24 KiB
TypeScript

import { delay, HttpResponse, http, type JsonBodyType } from "msw";
import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import type { FileByteSource } from "../../src/application/ports/browser-file-storage/file.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<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.
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",
}),
});
});
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 },
{ status: 503, code: "STORAGE_UNAVAILABLE", category: "TRANSIENT_DEPENDENCY", retryable: true, details: { ambiguous: true }, kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED", clientRetryable: false },
{ status: 503, code: "IDEMPOTENCY_UNAVAILABLE", category: "TRANSIENT_DEPENDENCY", retryable: true, kind: "SERVER_FAILURE", effect: "NOT_APPLIED", clientRetryable: true },
{ 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 },
])(
"$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",
},
});
},
);
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.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);
},
);
});
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("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("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);
});
});