Files
clean-architecture-frontend…/tests/integration/fileserver-upload.test.ts
T
DongHyeonka f800549315 feat(http): 짝 백엔드 Fileserver의 multipart 한 번 업로드 client를 더한다
문제: 두 템플릿을 짝으로 쓰면 파일 업로드 경로가 없다. 프론트 업로드
레시피는 PRESIGNED_MULTIPART_V1 서버를 가정하는데 짝 백엔드는 그 코드를
지웠고, 짝 백엔드 Fileserver(POST /v1/files)를 부를 프론트 client는 없다.
src 전체에 multipart 요청을 만드는 코드가 없다.

고친 방법(리뷰 D1 (나-1)): src/adapters/http/fileserver-upload.ts에
createFileserverUploadClient를 둔다. 백엔드 bbe944bd 계약 그대로다.
- 입력은 FileContentPort.openSource가 주는 FileByteSource다. 바이트를 한
  번 읽어 multipart 본문(파트 이름 file, RFC 7578, 파일 이름은 HTML 폼
  인코더처럼 escape)을 직접 만든다. File·Blob은 이 adapter에 들어오지
  않는다(eslint browser-data 경계). 선언 크기가 maxFileBytes보다 크면 읽기
  전에 거절하고, 읽는 중에 넘어도 멈춘다. 선언 크기가 있으면 본문 버퍼
  하나에 바로 쓴다.
- 전송 규칙은 레시피와 V3 실행기와 같다. credentials는 인증 프로필이
  정하고, 자격 증명 헤더는 admitCredentialHeaders로 프로필에 맞춰 받는다.
  redirect "error", no-referrer, no-store, 응답 본문 상한, 바이트에 비례한
  deadline 하나, 호출자 abort(커널 createAbortableOperation).
- 성공: 201 READY / 202 그 밖의 state를 Envelope에서 읽는다. 201과 202의
  state가 맞지 않거나 size가 보낸 바이트와 다르면 SCHEMA_MISMATCH,
  APPLIED_CONFIRMED.
- 실패: backend-envelope.ts의 readFailureEnvelope와 envelopeFailureReading을
  그대로 쓴다. 효과 판정은 Fileserver 계약을 따른다. details.ambiguous,
  AMBIGUOUS_COMPLETION, IDEMPOTENT_IN_FLIGHT, IDEMPOTENCY_COMPLETION_UNKNOWN은
  MAYBE_APPLIED. 그 밖의 4xx는 NOT_APPLIED(백엔드 UploadFile use case가
  모호하지 않은 실패에서 업로드를 취소한다). 5xx는 이름 붙인 Fileserver
  code만 NOT_APPLIED이고 나머지는 MAYBE_APPLIED. 보낸 뒤 네트워크 실패·
  시간 초과·abort도 MAYBE_APPLIED. Envelope의 retryable:false와 상한(기본
  30초)을 넘는 Retry-After는 retryable을 false로 만든다(01-02와 같은 규칙).
- Idempotency-Key 헤더를 보낸다. client는 스스로 다시 보내지 않는다.

위치를 http adapter로 고른 이유: Envelope 해석(backend-envelope.ts), 자격
증명 admission(http-contract-bridge.ts), bounded reader를 adapter 안
import로 다시 쓴다. 새 adapter 사이 import 예외가 필요 없다. 바꾼 http
파일은 index.ts의 export 한 묶음뿐이다.
버린 대안:
- backend-envelope.ts를 커널(src/adapters/platform/)로 옮기고 client를
  browser-transfer에 둔다. 다른 작업이 지금 고치는 파일을 옮겨야 하고,
  커널은 제품 중립 primitive 자리인데 백엔드 짝 정책이 들어간다.
  file-transfer 레시피 예산 여유도 1.7KB뿐이고, 이 client는 presigned
  레시피와 무관한데 그 제거 드릴에 함께 지워진다.
- browser-transfer에 Envelope 파서를 하나 더 둔다. 갈라진 사본이다.
- V3 실행기에 multipart 본문을 더한다. 1,900줄짜리 실행기를 다른 작업과
  동시에 크게 고쳐야 한다.
- FormData와 Blob을 쓴다. http adapter는 File·Blob을 쓸 수 없고(eslint),
  기능은 Blob을 갖지 않는다.

조립: 제품이 product-composition.ts에서 client 재료
(FileserverUploadClientDependencies)를 capability로 넘기고, 기능 adapter가
createFileserverUploadClient를 부른다. 그래서 템플릿 boot 번들에는 들지
않는다. 매뉴얼 02 결정표 7절, patterns.md, 두 architecture 문서, 레시피
fallback이 이 경로를 가리킨다. adapter INVENTORY와 상세 리뷰 표에 행을
더했다(번호는 끝에 141로 붙였다).

위험·한계:
- 재개가 없다. 파일 전체를 메모리에 한 번 읽는다(maxFileBytes까지). tus
  client는 없다.
- 짝 백엔드 bbe944bd의 POST /v1/files는 멱등 키를 읽지 않는다
  (NOT_IDEMPOTENT). MAYBE_APPLIED 뒤 같은 키로 다시 보내도 파일이 두 개
  생길 수 있다. 매뉴얼에 적었다.
- 효과 판정 표(NOT_APPLIED_5XX_CODES, MAYBE_APPLIED_CODES)는 백엔드
  bbe944bd 기준이다. 어긋남을 알리는 검사는 없다(12-06과 같은 종류).
- 실제 짝 백엔드를 띄운 업로드는 하지 않았다. 테스트는 계약대로 답하는
  MSW다. 실제 브라우저(Playwright)에서도 돌리지 않았다.
- 템플릿 기본 product-composition.ts가 자격 증명 owner를 노출하지 않으므로,
  템플릿 세션(EXTERNAL_BEARER)으로 올리려면 제품이 자기 credential
  provider를 써야 한다.

검증:
- tests/integration/fileserver-upload.test.ts 48건 통과(201/202 본문,
  Envelope 실패 16종, 409 IDEMPOTENT_IN_FLIGHT + Retry-After 2, 상한 밖
  Retry-After, 보낸 뒤 네트워크 실패 뒤 같은 키 재전송, 시간 초과, abort,
  자격 증명 거절, 크기·입력 거절). multipart 본문은 undici FormData
  파서로 다시 읽어 확인했다.
- 변이 7건(4xx 판정, ambiguous 무시, 상한 무시, credentials 고정, 키 누락,
  201/202 state 검사 제거, Envelope retryable 무시) 모두 실패를 만들었다.
- check:types, lint(바꾼 파일), check:architecture, check:adapter-inventory,
  verify:documentation, check:registries, check:ci 통과
- check:bundle PASS: initial JS 201,921 / 204,800 gzip bytes. 빌드 산출물
  어디에도 client 코드가 없다(dist grep). check:optional-recipes:source PASS
  (file-transfer 56,082 / 57,800)

Refs: docs/reviews/2026-11-03-maturity-review/01-adapters-browser-transfer.md 01-01
2026-11-04 21:05:23 +09:00

558 lines
21 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
* exactly as clean-architecture-backend-template `bbe944bd` documents it:
* docs/fileserver/http-contract.md (201 READY / 202 VERIFYING, Envelope
* failure body, `details.ambiguous`, `Retry-After`) and docs/web/http-contract.md
* §1–§2 (Envelope keys, 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("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"],
["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: "VALIDATION_REJECTED", 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"],
["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);
});
});