문제 fix/r1103-transfer의 Fileserver 업로드 client는 실패 kind를 공유 Envelope 판정(envelopeFailureReading)에서 받고 413·415만 VALIDATION_REJECTED로 바꾼다. fix/r1103-http(1103/08-05)는 필드 목록 없는 422를 UNKNOWN_CLIENT_FAILURE로 읽게 했다. 두 브랜치를 합치자 Fileserver의 422(digest·서명·검사기 거절, 예: MALWARE_DETECTED)가 입력 거절이 아니게 되어 통합 테스트 2건이 실패한다. 고른 방법 - Fileserver 계약에서 422는 파일 자체의 거절이다(백엔드 docs/fileserver/http-contract.md 상태 표). 사용자가 파일을 바꿔야 하는 413·415와 같이 VALIDATION_REJECTED로 둔다. - 422 IDEMPOTENT_REQUEST_MISMATCH(같은 키, 다른 본문)는 파일 문제가 아니므로 08-05의 공통 판정(UNKNOWN_CLIENT_FAILURE)을 따른다. 테스트 기대값도 그렇게 바꿨다. - 버린 대안: 공통 판정을 422 전체 입력 거절로 되돌리기. 08-05가 고친 결함(같은 키 불일치를 입력 오류로 보임)이 다시 생긴다. 위험·한계 - 422 code 목록을 파일 거절로 고정하지 않고 "불일치가 아니면 파일 거절"로 본다. 백엔드가 파일 업로드에 다른 뜻의 422를 더하면 다시 본다. 검증 - test:integration 189건(fileserver-upload 48건 포함), check:types, lint 통과. Refs: docs/reviews/2026-11-03-maturity-review/01-adapters-browser-transfer.md 01-01, 08-presentation.md 08-05
558 lines
21 KiB
TypeScript
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: "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"],
|
|
["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);
|
|
});
|
|
});
|