문제: readFailureEnvelope는 실패 Envelope의 meta.traceId를 함께 돌려주고, V3 실행기는 그 값을 AppFailure.traceId로 싣는다(1103/03-06). Fileserver client는 envelope.value만 넘겨 traceId를 버린다. 지원 담당이 업로드 실패를 서버 로그의 요청과 잇지 못한다. 같은 백엔드의 다른 쓰기 실패는 이을 수 있다. 고른 방법: envelopeFailure가 읽은 Envelope 전체를 받아 traceId가 있으면 createFailure의 traceId로 싣는다. V3와 같은 규칙이다. 없으면 키를 두지 않는다. 매뉴얼 7절 결과 읽기에 한 줄 적었다. 위험·한계: Envelope 실패에만 싣는다. 성공 Envelope을 읽지 못한 실패 (SCHEMA_MISMATCH 등, 202 REJECTED 포함)는 readSuccessEnvelope가 meta를 돌려주지 않아 traceId가 없다. V3도 같다. 검증: desktop batch에서 확인. node scripts/run-vitest.ts run tests/integration/fileserver-upload.test.ts RED(이 커밋의 테스트 + 부모 src): Envelope failures 표 17행이 traceId "trace-1"이 없어 모두 실패한다. Refs: 1105/01-03
803 lines
28 KiB
TypeScript
803 lines
28 KiB
TypeScript
import {
|
|
createFailure,
|
|
type AppFailure,
|
|
type FailureEffectCertainty,
|
|
type FailureKind,
|
|
} from "../../contracts/errors.ts";
|
|
import { isValidIdempotencyKey } from "../../contracts/mutation-intent.ts";
|
|
import type { RestAuthProfile } from "../../contracts/rest-profiles.ts";
|
|
import type { Result } from "../../contracts/result.ts";
|
|
import { z } from "../../contracts/zod.ts";
|
|
import {
|
|
cancelBody,
|
|
createAbortableOperation,
|
|
type AbortableOperation,
|
|
} from "../platform/abortable-operation.ts";
|
|
import { parseRetryAfterDelay } from "../platform/retry-after.ts";
|
|
import {
|
|
envelopeFailureEffect,
|
|
envelopeFailureReading,
|
|
gatewayFailureOr,
|
|
maybeAppliedAnswerRows,
|
|
readFailureEnvelope,
|
|
readSuccessEnvelope,
|
|
refusedBeforeWriteRows,
|
|
type EnvelopeError,
|
|
} from "./backend-envelope.ts";
|
|
import {
|
|
declaredContentLength,
|
|
isJsonMediaType,
|
|
readBoundedBytes,
|
|
} from "./bounded-body-reader.ts";
|
|
import {
|
|
admitCredentialHeaders,
|
|
type CredentialPatchOutcome,
|
|
} from "./http-contract-bridge.ts";
|
|
import type { AuthOperationContext } from "./http-execution-v3.ts";
|
|
|
|
/**
|
|
* 2026-11-03 01-01. A client for the paired backend Fileserver's multipart
|
|
* single upload, `POST /v1/files` (clean-architecture-backend-template
|
|
* `45d2a478`, the commit config/contracts/backend-contract-pin.json pins;
|
|
* docs/fileserver/http-contract.md and its code; Envelope and idempotency in
|
|
* docs/web/http-contract.md §1–§2).
|
|
*
|
|
* The paired backend removed presigned and direct multipart transfer on
|
|
* 2026-09-25, so the presigned resumable recipe in `browser-transfer` has no
|
|
* server there. This is the path that pairs with it: the bytes go to the
|
|
* application server in one request, and the answer is the stored file's
|
|
* public descriptor.
|
|
*
|
|
* The file arrives as the `FileByteSource` that `FileContentPort.openSource`
|
|
* gives (`FileserverByteSource` is its shape), so no `File` or `Blob` crosses
|
|
* into this adapter. Its bytes are read
|
|
* once into the multipart body, at most `maxFileBytes` of them; a file that
|
|
* declares a larger size is refused before reading, and an empty file is
|
|
* never sent.
|
|
*
|
|
* One request per call. The client never resends: the body is the whole
|
|
* file, and only the caller knows whether to spend that again. It keeps the
|
|
* recipe's transport rules: Fetch credentials from the auth profile, proof
|
|
* headers admitted against that profile, `redirect: "error"`, no referrer, no
|
|
* cache, a bounded response body, and one deadline that grows with the bytes.
|
|
*/
|
|
|
|
export type FileserverFileState = "READY" | "UPLOADED" | "VERIFYING" | "QUARANTINED";
|
|
|
|
/**
|
|
* 1105/01-01. The states the backend answers `POST /v1/files` with. It
|
|
* verifies synchronously and answers 202 for every state but `READY`
|
|
* (`FileUploadController#created`), so a file its verifiers refused, for a
|
|
* reason other than malware, comes back as 202 `REJECTED`. That one is not a
|
|
* stored file: the client returns it as a `FILE_REJECTED` failure.
|
|
*/
|
|
type FileserverAnswerState = FileserverFileState | "REJECTED";
|
|
|
|
type FileserverAnswer = Readonly<
|
|
Omit<FileserverUploadedFile, "state"> & { state: FileserverAnswerState }
|
|
>;
|
|
|
|
/**
|
|
* The bytes to send: structurally the browser-file-storage port's
|
|
* `FileByteSource`, which a product passes as it is. Written here instead of
|
|
* imported so this adapter does not depend on that optional runtime's port;
|
|
* test:browser-file-storage-removal deletes the port and this client stays.
|
|
*/
|
|
export type FileserverByteSource = Readonly<{
|
|
byteLength: number | null;
|
|
stream(
|
|
signal: AbortSignal,
|
|
): AsyncIterable<Result<Uint8Array, Readonly<{ code: string }>>>;
|
|
}>;
|
|
|
|
/** The stored file, as the backend's `UploadedFileResponse` describes it. */
|
|
export type FileserverUploadedFile = Readonly<{
|
|
fileId: string;
|
|
/**
|
|
* `READY` with 201: readable now. With 202 the file is not readable:
|
|
* `VERIFYING` means a verifier asked to check again later, and `QUARANTINED`
|
|
* means it is held until an operator decides, so a screen must not wait for
|
|
* it as for a check in progress.
|
|
*/
|
|
state: FileserverFileState;
|
|
filename: string;
|
|
mediaType: string;
|
|
size: number;
|
|
sha256: string;
|
|
etag: string;
|
|
}>;
|
|
|
|
export type FileserverUploadRequest = Readonly<{
|
|
source: FileserverByteSource;
|
|
/** The multipart filename, untrusted on the server. Defaults to `upload.bin`. */
|
|
filename?: string;
|
|
/** The part's Content-Type, a claim the server verifies. */
|
|
mediaType?: string;
|
|
/**
|
|
* Sent as `Idempotency-Key`. After a `MAYBE_APPLIED` failure, resend with
|
|
* the same key and never a new one. At `45d2a478` the backend runs
|
|
* `POST /v1/files` without its idempotency executor, so the key protects
|
|
* only a deployment that routes the upload through it.
|
|
*/
|
|
idempotencyKey?: string;
|
|
signal: AbortSignal;
|
|
}>;
|
|
|
|
export type FileserverUploadClient = Readonly<{
|
|
upload(
|
|
request: FileserverUploadRequest,
|
|
): Promise<Result<FileserverUploadedFile, AppFailure>>;
|
|
}>;
|
|
|
|
export type FileserverUploadClientDependencies = Readonly<{
|
|
/** Origin and optional path prefix; `v1/files` is resolved under it. */
|
|
baseUrl: string;
|
|
/** Owns Fetch `credentials` and the proof headers a provider may add. */
|
|
authProfile: RestAuthProfile;
|
|
/** Same contract as the V3 executor's `attachCredentials`. */
|
|
attachCredentials(
|
|
operation: Readonly<{
|
|
operationId: string;
|
|
authProfileId: string;
|
|
method: string;
|
|
}>,
|
|
context: AuthOperationContext,
|
|
): Promise<CredentialPatchOutcome> | CredentialPatchOutcome;
|
|
/** A larger file is refused before it is read. */
|
|
maxFileBytes: number;
|
|
fetcher?: typeof fetch;
|
|
/** Base deadline in ms. The transfer allowance is added on top. */
|
|
timeoutMs?: number;
|
|
/** Lowest supported uplink; sets the per-byte allowance. */
|
|
minTransferBytesPerSecond?: number;
|
|
maxResponseBytes?: number;
|
|
/** A longer server `Retry-After` is dropped and ends `retryable: false`. */
|
|
maxRetryAfterMs?: number;
|
|
nowEpochMs?: () => number;
|
|
monotonicNow?: () => number;
|
|
}>;
|
|
|
|
export const FILESERVER_UPLOAD_OPERATION_ID = "FILESERVER_UPLOAD";
|
|
|
|
const DEFAULTS = Object.freeze({
|
|
timeoutMs: 30_000,
|
|
// The resumable runtime's default uplink floor (runtime-policy.ts).
|
|
minTransferBytesPerSecond: 64 * 1024,
|
|
maxResponseBytes: 16 * 1024,
|
|
maxRetryAfterMs: 30_000,
|
|
filename: "upload.bin",
|
|
mediaType: "application/octet-stream",
|
|
});
|
|
|
|
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
|
|
const SHA256_HEX = /^[0-9a-f]{64}$/u;
|
|
const MEDIA_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/u;
|
|
const MAX_FILENAME_LENGTH = 255;
|
|
|
|
/**
|
|
* Backend `UploadFileApplicationUseCase` cancels the upload on every failure
|
|
* its worker raises except an ambiguous completion, and the Fileserver
|
|
* contract marks a failure that may already have taken effect with
|
|
* `details.ambiguous`. So a 4xx Envelope is NOT_APPLIED unless it says
|
|
* otherwise. A 5xx stays MAYBE_APPLIED except these codes, which the worker
|
|
* raises before the file is published (`FileserverErrorCode`,
|
|
* `AtomicMoveContentPublisher`). Recheck the list when the pinned backend
|
|
* commit moves; contract §6.1 says why the 4xx reading differs from its
|
|
* fileserver row.
|
|
*
|
|
* 1105/01-02. 504 TRANSFER_TIMEOUT is not here. The waiting servlet thread
|
|
* raises it when `await-seconds` runs out, whatever stage the worker is in
|
|
* (`BlockingTransferExecutor`), and the interrupt that follows does not stop a
|
|
* publish rename or the READY commit. The file may still become READY, so a
|
|
* resend can store it twice.
|
|
*/
|
|
const NOT_APPLIED_5XX_CODES: ReadonlySet<string> = new Set([
|
|
"PARTIAL_WRITE",
|
|
"ATOMIC_PUBLISH_UNSUPPORTED",
|
|
"STORAGE_UNAVAILABLE",
|
|
"STORAGE_FULL",
|
|
]);
|
|
|
|
/**
|
|
* 1105/01-02. The web contract's own answers (idempotency §2, and the other
|
|
* codes the V3 table lists) read as the V3 executor reads them, so the same
|
|
* backend code has one verdict in this repository. The idempotency codes are
|
|
* taken by prefix: one the table does not list yet stays MAYBE_APPLIED.
|
|
*/
|
|
function sharedAnswerEffect(
|
|
status: number,
|
|
error: EnvelopeError,
|
|
): "NOT_APPLIED" | "MAYBE_APPLIED" | undefined {
|
|
const listed = (rows: readonly Readonly<{ code: string; status: number }>[]) =>
|
|
rows.some((row) => row.code === error.code && row.status === status);
|
|
if (
|
|
!/^IDEMPOTEN(?:T|CY)_/u.test(error.code) &&
|
|
!listed(refusedBeforeWriteRows()) &&
|
|
!listed(maybeAppliedAnswerRows())
|
|
) {
|
|
return undefined;
|
|
}
|
|
return envelopeFailureEffect(status, error) ?? "MAYBE_APPLIED";
|
|
}
|
|
|
|
export function createFileserverUploadClient(
|
|
dependencies: FileserverUploadClientDependencies,
|
|
): FileserverUploadClient {
|
|
const settings = snapshotDependencies(dependencies);
|
|
const fetcher = dependencies.fetcher ?? fetch;
|
|
if (typeof fetcher !== "function") {
|
|
throw new TypeError("Fileserver upload dependency is invalid: fetcher.");
|
|
}
|
|
// Built here, not at module scope, so an app that never composes the client
|
|
// carries none of it in its boot bundle.
|
|
const uploadedFileSchema = z
|
|
.object({
|
|
fileId: z.string().regex(UUID),
|
|
state: z.enum(["READY", "UPLOADED", "VERIFYING", "QUARANTINED", "REJECTED"]),
|
|
filename: z.string().min(1).max(1_024),
|
|
mediaType: z.string().min(1).max(255),
|
|
size: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
|
sha256: z.string().regex(SHA256_HEX),
|
|
etag: z.string().min(1).max(256),
|
|
})
|
|
// A field the backend adds later is ignored, not copied.
|
|
.strip();
|
|
|
|
return Object.freeze({
|
|
async upload(request) {
|
|
const admitted = admitRequest(request);
|
|
if (!admitted.ok) return admitted;
|
|
const { idempotencyKey, signal } = admitted.value;
|
|
const body = await readMultipartBody(admitted.value, settings.maxFileBytes);
|
|
if (!body.ok) return body;
|
|
const timeoutMs =
|
|
settings.timeoutMs +
|
|
Math.ceil(
|
|
(body.value.fileBytes / settings.minTransferBytesPerSecond) * 1_000,
|
|
);
|
|
const attempt = createAbortableOperation({ signal, timeoutMs });
|
|
try {
|
|
if (attempt.terminal() !== null) {
|
|
return terminalFailure(attempt, "NOT_STARTED");
|
|
}
|
|
const credentials = await credentialHeaders(
|
|
settings,
|
|
attempt,
|
|
settings.monotonicNow() + timeoutMs,
|
|
);
|
|
if (!credentials.ok) return credentials;
|
|
const headers: Record<string, string> = {
|
|
...credentials.value,
|
|
accept: "application/json",
|
|
"content-type": `multipart/form-data; boundary=${body.value.boundary}`,
|
|
...(idempotencyKey === undefined
|
|
? {}
|
|
: { "idempotency-key": idempotencyKey }),
|
|
};
|
|
let pendingResponse: Promise<Response>;
|
|
try {
|
|
pendingResponse = fetcher(settings.url, {
|
|
method: "POST",
|
|
headers,
|
|
body: body.value.bytes,
|
|
credentials: settings.authProfile.credentials,
|
|
redirect: "error",
|
|
referrerPolicy: "no-referrer",
|
|
cache: "no-store",
|
|
signal: attempt.signal,
|
|
});
|
|
} catch {
|
|
// A synchronous throw from fetch means nothing went out.
|
|
return failure("NETWORK_UNREACHABLE", "NETWORK_UNREACHABLE", {
|
|
effect: "NOT_STARTED",
|
|
});
|
|
}
|
|
const sent = await attempt.race(pendingResponse, cancelBody);
|
|
if (sent.kind === "TERMINAL") {
|
|
return terminalFailure(attempt, "MAYBE_APPLIED");
|
|
}
|
|
if (sent.kind === "REJECTED") {
|
|
// The bytes may have reached the server before the connection broke.
|
|
return failure("NETWORK_UNREACHABLE", "NETWORK_UNREACHABLE", {
|
|
effect: "MAYBE_APPLIED",
|
|
});
|
|
}
|
|
return await readAnswer(
|
|
sent.value,
|
|
attempt,
|
|
settings,
|
|
uploadedFileSchema,
|
|
body.value.fileBytes,
|
|
);
|
|
} finally {
|
|
attempt.close();
|
|
}
|
|
},
|
|
});
|
|
}
|
|
|
|
type Settings = Readonly<{
|
|
url: string;
|
|
authProfile: RestAuthProfile;
|
|
attachCredentials: FileserverUploadClientDependencies["attachCredentials"];
|
|
maxFileBytes: number;
|
|
timeoutMs: number;
|
|
minTransferBytesPerSecond: number;
|
|
maxResponseBytes: number;
|
|
maxRetryAfterMs: number;
|
|
nowEpochMs: () => number;
|
|
monotonicNow: () => number;
|
|
}>;
|
|
|
|
function snapshotDependencies(
|
|
dependencies: FileserverUploadClientDependencies,
|
|
): Settings {
|
|
const invalid = (field: string): never => {
|
|
throw new TypeError(`Fileserver upload dependency is invalid: ${field}.`);
|
|
};
|
|
if (!dependencies || typeof dependencies !== "object") invalid("dependencies");
|
|
let base: URL | null = null;
|
|
try {
|
|
base = new URL(dependencies.baseUrl);
|
|
} catch {
|
|
invalid("baseUrl");
|
|
}
|
|
if (!base || (base.protocol !== "https:" && base.protocol !== "http:")) {
|
|
return invalid("baseUrl");
|
|
}
|
|
// Same join as the V3 request projection: under the base path, never above.
|
|
const url = new URL("v1/files", base);
|
|
if (url.origin !== base.origin || !url.pathname.startsWith(base.pathname)) {
|
|
invalid("baseUrl");
|
|
}
|
|
const profile = dependencies.authProfile;
|
|
if (
|
|
!profile ||
|
|
typeof profile.authProfileId !== "string" ||
|
|
!["omit", "same-origin", "include"].includes(profile.credentials) ||
|
|
!Array.isArray(profile.allowedCredentialHeaders) ||
|
|
!Array.isArray(profile.requiredCredentialHeaders)
|
|
) {
|
|
invalid("authProfile");
|
|
}
|
|
if (typeof dependencies.attachCredentials !== "function") {
|
|
invalid("attachCredentials");
|
|
}
|
|
const positive = (value: number | undefined, fallback: number, field: string) => {
|
|
const resolved = value ?? fallback;
|
|
return Number.isSafeInteger(resolved) && resolved > 0
|
|
? resolved
|
|
: invalid(field);
|
|
};
|
|
return Object.freeze({
|
|
url: url.href,
|
|
authProfile: Object.freeze({
|
|
...profile,
|
|
allowedCredentialHeaders: Object.freeze([...profile.allowedCredentialHeaders]),
|
|
requiredCredentialHeaders: Object.freeze([...profile.requiredCredentialHeaders]),
|
|
}),
|
|
attachCredentials: dependencies.attachCredentials,
|
|
maxFileBytes: positive(dependencies.maxFileBytes, 0, "maxFileBytes"),
|
|
timeoutMs: positive(dependencies.timeoutMs, DEFAULTS.timeoutMs, "timeoutMs"),
|
|
minTransferBytesPerSecond: positive(
|
|
dependencies.minTransferBytesPerSecond,
|
|
DEFAULTS.minTransferBytesPerSecond,
|
|
"minTransferBytesPerSecond",
|
|
),
|
|
maxResponseBytes: positive(
|
|
dependencies.maxResponseBytes,
|
|
DEFAULTS.maxResponseBytes,
|
|
"maxResponseBytes",
|
|
),
|
|
maxRetryAfterMs: positive(
|
|
dependencies.maxRetryAfterMs,
|
|
DEFAULTS.maxRetryAfterMs,
|
|
"maxRetryAfterMs",
|
|
),
|
|
nowEpochMs: dependencies.nowEpochMs ?? (() => Date.now()),
|
|
monotonicNow: dependencies.monotonicNow ?? (() => performance.now()),
|
|
});
|
|
}
|
|
|
|
type AdmittedRequest = Readonly<{
|
|
source: FileserverByteSource;
|
|
filename: string;
|
|
mediaType: string;
|
|
idempotencyKey?: string;
|
|
signal: AbortSignal;
|
|
}>;
|
|
|
|
function admitRequest(
|
|
request: FileserverUploadRequest,
|
|
): Result<AdmittedRequest, AppFailure> {
|
|
const inputInvalid = () =>
|
|
failure("UNKNOWN_CLIENT_FAILURE", "FILESERVER_UPLOAD_INPUT_INVALID", {
|
|
effect: "NOT_STARTED",
|
|
});
|
|
if (!request || typeof request !== "object") return inputInvalid();
|
|
const { source, idempotencyKey, signal } = request;
|
|
const filename = request.filename ?? DEFAULTS.filename;
|
|
const mediaType = request.mediaType ?? DEFAULTS.mediaType;
|
|
if (
|
|
!source ||
|
|
typeof source.stream !== "function" ||
|
|
(source.byteLength !== null && !Number.isSafeInteger(source.byteLength)) ||
|
|
typeof filename !== "string" ||
|
|
filename.length === 0 ||
|
|
filename.length > MAX_FILENAME_LENGTH ||
|
|
typeof mediaType !== "string" ||
|
|
!MEDIA_TYPE.test(mediaType) ||
|
|
(idempotencyKey !== undefined && !isValidIdempotencyKey(idempotencyKey)) ||
|
|
!(signal instanceof AbortSignal)
|
|
) {
|
|
return inputInvalid();
|
|
}
|
|
return Object.freeze({
|
|
ok: true as const,
|
|
value: Object.freeze({
|
|
source,
|
|
filename,
|
|
mediaType,
|
|
...(idempotencyKey === undefined ? {} : { idempotencyKey }),
|
|
signal,
|
|
}),
|
|
});
|
|
}
|
|
|
|
type MultipartBody = Readonly<{
|
|
bytes: Uint8Array<ArrayBuffer>;
|
|
boundary: string;
|
|
fileBytes: number;
|
|
}>;
|
|
|
|
/**
|
|
* RFC 7578 with one part named `file`, the backend's `@RequestParam("file")`.
|
|
* The filename is escaped as the HTML form encoder does (`"` → `%22`, CR and
|
|
* LF → `%0D` `%0A`) and sent as UTF-8.
|
|
*/
|
|
async function readMultipartBody(
|
|
request: AdmittedRequest,
|
|
maxFileBytes: number,
|
|
): Promise<Result<MultipartBody, AppFailure>> {
|
|
const notSent = { effect: "NOT_STARTED" } as const;
|
|
if (request.signal.aborted) {
|
|
return failure("REQUEST_ABORTED", "REQUEST_ABORTED", notSent);
|
|
}
|
|
const declared = request.source.byteLength;
|
|
if (declared !== null && declared > maxFileBytes) {
|
|
// The server's code for the same refusal, so a feature handles one code.
|
|
return failure("VALIDATION_REJECTED", "FILE_TOO_LARGE", notSent);
|
|
}
|
|
// 1105/01-01. The backend's default verifier chain rejects empty content
|
|
// first (`LengthVerifier`), and that answer is a 202 `REJECTED` with no
|
|
// reason. Refused here instead, under a code that says why.
|
|
const empty = () => failure("VALIDATION_REJECTED", "FILE_EMPTY", notSent);
|
|
if (declared === 0) return empty();
|
|
const random = new Uint8Array(16);
|
|
crypto.getRandomValues(random);
|
|
const boundary = `----FileserverUpload${[...random]
|
|
.map((byte) => byte.toString(16).padStart(2, "0"))
|
|
.join("")}`;
|
|
const filename = request.filename.replace(
|
|
/["\r\n]/gu,
|
|
(character) =>
|
|
character === '"' ? "%22" : character === "\r" ? "%0D" : "%0A",
|
|
);
|
|
const encoder = new TextEncoder();
|
|
const head = encoder.encode(
|
|
`--${boundary}\r\n` +
|
|
`Content-Disposition: form-data; name="file"; filename="${filename}"\r\n` +
|
|
`Content-Type: ${request.mediaType}\r\n\r\n`,
|
|
);
|
|
const tail = encoder.encode(`\r\n--${boundary}--\r\n`);
|
|
// A declared size is written straight into the one body buffer. Without
|
|
// one, chunks are kept (still bounded by maxFileBytes) and copied once.
|
|
const sized =
|
|
declared === null
|
|
? null
|
|
: new Uint8Array(head.byteLength + declared + tail.byteLength);
|
|
sized?.set(head, 0);
|
|
const chunks: Uint8Array[] = [];
|
|
let fileBytes = 0;
|
|
// The file changed between selection and reading.
|
|
const changed = () =>
|
|
failure("VALIDATION_REJECTED", "FILE_NOT_READABLE", notSent);
|
|
try {
|
|
for await (const chunk of request.source.stream(request.signal)) {
|
|
if (request.signal.aborted) {
|
|
return failure("REQUEST_ABORTED", "REQUEST_ABORTED", notSent);
|
|
}
|
|
if (!chunk.ok) {
|
|
return chunk.error.code === "ABORTED"
|
|
? failure("REQUEST_ABORTED", "REQUEST_ABORTED", notSent)
|
|
: changed();
|
|
}
|
|
if (fileBytes + chunk.value.byteLength > maxFileBytes) {
|
|
return failure("VALIDATION_REJECTED", "FILE_TOO_LARGE", notSent);
|
|
}
|
|
if (sized) {
|
|
if (fileBytes + chunk.value.byteLength > (declared ?? 0)) {
|
|
return changed();
|
|
}
|
|
sized.set(chunk.value, head.byteLength + fileBytes);
|
|
} else {
|
|
chunks.push(chunk.value);
|
|
}
|
|
fileBytes += chunk.value.byteLength;
|
|
}
|
|
} catch {
|
|
return changed();
|
|
}
|
|
if (request.signal.aborted) {
|
|
return failure("REQUEST_ABORTED", "REQUEST_ABORTED", notSent);
|
|
}
|
|
if (declared !== null && fileBytes !== declared) return changed();
|
|
if (fileBytes === 0) return empty();
|
|
let bytes: Uint8Array<ArrayBuffer>;
|
|
if (sized) {
|
|
bytes = sized;
|
|
} else {
|
|
bytes = new Uint8Array(head.byteLength + fileBytes + tail.byteLength);
|
|
bytes.set(head, 0);
|
|
let offset = head.byteLength;
|
|
for (const chunk of chunks) {
|
|
bytes.set(chunk, offset);
|
|
offset += chunk.byteLength;
|
|
}
|
|
}
|
|
bytes.set(tail, head.byteLength + fileBytes);
|
|
return Object.freeze({
|
|
ok: true as const,
|
|
value: Object.freeze({ bytes, boundary, fileBytes }),
|
|
});
|
|
}
|
|
|
|
async function credentialHeaders(
|
|
settings: Settings,
|
|
attempt: AbortableOperation,
|
|
deadlineAtMonotonicMs: number,
|
|
): Promise<Result<Readonly<Record<string, string>>, AppFailure>> {
|
|
const notSent = { effect: "NOT_STARTED" } as const;
|
|
let pending: Promise<CredentialPatchOutcome>;
|
|
try {
|
|
pending = Promise.resolve(
|
|
settings.attachCredentials(
|
|
Object.freeze({
|
|
operationId: FILESERVER_UPLOAD_OPERATION_ID,
|
|
authProfileId: settings.authProfile.authProfileId,
|
|
method: "POST",
|
|
}),
|
|
Object.freeze({ signal: attempt.signal, deadlineAtMonotonicMs }),
|
|
),
|
|
);
|
|
} catch {
|
|
pending = Promise.reject(new Error("credential owner failed"));
|
|
}
|
|
const answered = await attempt.race(pending);
|
|
if (answered.kind === "TERMINAL") {
|
|
return terminalFailure(attempt, "NOT_STARTED");
|
|
}
|
|
if (answered.kind === "REJECTED" || !answered.value) {
|
|
return failure("AUTH_INTEGRATION_FAILURE", "CREDENTIAL_OWNER_FAILED", notSent);
|
|
}
|
|
const patch = answered.value;
|
|
switch (patch.kind) {
|
|
case "READY": {
|
|
// The profile, not the provider, decides which proof headers go out.
|
|
const admitted = admitCredentialHeaders(
|
|
patch.headers ?? {},
|
|
settings.authProfile,
|
|
);
|
|
return admitted.ok
|
|
? Object.freeze({
|
|
ok: true as const,
|
|
value: admitted.headers as Readonly<Record<string, string>>,
|
|
})
|
|
: failure("AUTH_INTEGRATION_FAILURE", admitted.failure, notSent);
|
|
}
|
|
case "UNAUTHENTICATED":
|
|
return failure("AUTH_REQUIRED", "UNAUTHENTICATED", notSent);
|
|
case "SCOPE_FENCED":
|
|
return failure("SCOPE_GENERATION_CHANGED", "SCOPE_FENCED", notSent);
|
|
default:
|
|
return failure(
|
|
"AUTH_INTEGRATION_FAILURE",
|
|
"CREDENTIAL_OWNER_UNAVAILABLE",
|
|
notSent,
|
|
);
|
|
}
|
|
}
|
|
|
|
async function readAnswer(
|
|
response: Response,
|
|
attempt: AbortableOperation,
|
|
settings: Settings,
|
|
uploadedFileSchema: z.ZodType<FileserverAnswer>,
|
|
sentBytes: number,
|
|
): Promise<Result<FileserverUploadedFile, AppFailure>> {
|
|
const status = response.status;
|
|
const created = status === 201 || status === 202;
|
|
// A 2xx the contract does not list says something happened; what is unknown.
|
|
const effect: FailureEffectCertainty = created
|
|
? "APPLIED_CONFIRMED"
|
|
: "MAYBE_APPLIED";
|
|
const unreadable = (kind: FailureKind, code: string) =>
|
|
failure(created ? kind : gatewayFailureOr(status, kind), code, {
|
|
httpStatus: status,
|
|
effect,
|
|
});
|
|
if (response.type === "opaqueredirect" || response.redirected) {
|
|
cancelBody(response);
|
|
return unreadable("ENVELOPE_MISMATCH", "REDIRECT_REFUSED");
|
|
}
|
|
if (!isJsonMediaType(response.headers.get("content-type"))) {
|
|
cancelBody(response);
|
|
return unreadable("CONTENT_TYPE_MISMATCH", "CONTENT_TYPE_MISMATCH");
|
|
}
|
|
// Checked here as well so the refusal does not wait on the body's cancel,
|
|
// which `readBoundedBytes` awaits.
|
|
const declaredLength = declaredContentLength(response);
|
|
if (declaredLength !== null && declaredLength > settings.maxResponseBytes) {
|
|
cancelBody(response);
|
|
return unreadable("RESPONSE_BODY_LIMIT", "RESPONSE_TOO_LARGE");
|
|
}
|
|
const read = await attempt.race(
|
|
readBoundedBytes(response, settings.maxResponseBytes, attempt.signal),
|
|
);
|
|
if (read.kind === "TERMINAL") {
|
|
cancelBody(response);
|
|
return terminalFailure(attempt, effect, status);
|
|
}
|
|
const bytes = read.kind === "VALUE" ? read.value : null;
|
|
if (!bytes?.ok) {
|
|
return bytes?.code === "RESPONSE_TOO_LARGE"
|
|
? unreadable("RESPONSE_BODY_LIMIT", "RESPONSE_TOO_LARGE")
|
|
: failure("NETWORK_UNREACHABLE", "RESPONSE_STREAM_FAILURE", {
|
|
httpStatus: status,
|
|
effect,
|
|
});
|
|
}
|
|
let json: unknown;
|
|
try {
|
|
json = JSON.parse(
|
|
new TextDecoder("utf-8", { fatal: true }).decode(bytes.bytes),
|
|
);
|
|
} catch {
|
|
return unreadable("MALFORMED_JSON", "JSON_INVALID");
|
|
}
|
|
|
|
if (created) {
|
|
const envelope = readSuccessEnvelope(json);
|
|
if (!envelope.ok) return unreadable("ENVELOPE_MISMATCH", "ENVELOPE_INVALID");
|
|
const parsed = uploadedFileSchema.safeParse(envelope.value);
|
|
if (
|
|
!parsed.success ||
|
|
(status === 201) !== (parsed.data.state === "READY") ||
|
|
parsed.data.size !== sentBytes
|
|
) {
|
|
return unreadable("SCHEMA_MISMATCH", "UPLOADED_FILE_INVALID");
|
|
}
|
|
const { state, ...file } = parsed.data;
|
|
if (state === "REJECTED") {
|
|
// 1105/01-01. The file is the user's to replace, as with a 413, 415 or
|
|
// 422 refusal. The backend keeps the record unpublished and schedules
|
|
// its bytes for removal, so nothing usable was stored.
|
|
return failure("VALIDATION_REJECTED", "FILE_REJECTED", {
|
|
httpStatus: status,
|
|
effect: "NOT_APPLIED",
|
|
});
|
|
}
|
|
return Object.freeze({
|
|
ok: true as const,
|
|
value: Object.freeze({ ...file, state }),
|
|
});
|
|
}
|
|
if (status < 400) return unreadable("ENVELOPE_MISMATCH", "STATUS_UNEXPECTED");
|
|
const envelope = readFailureEnvelope(json);
|
|
if (!envelope.ok) return unreadable("ENVELOPE_MISMATCH", "ENVELOPE_INVALID");
|
|
return envelopeFailure(status, envelope, response, settings);
|
|
}
|
|
|
|
function envelopeFailure(
|
|
status: number,
|
|
envelope: Readonly<{ value: EnvelopeError; traceId?: string }>,
|
|
response: Response,
|
|
settings: Settings,
|
|
): Result<never, AppFailure> {
|
|
const error = envelope.value;
|
|
const effect = fileserverFailureEffect(status, error);
|
|
const retryAfterMs = parseRetryAfterDelay(
|
|
response.headers.get("retry-after"),
|
|
settings.nowEpochMs(),
|
|
);
|
|
// 2026-11-03 01-02. A wait past the ceiling is not passed on as one to
|
|
// honour, and the failure is not retryable at once either.
|
|
const waitRefused =
|
|
retryAfterMs !== null && retryAfterMs > settings.maxRetryAfterMs;
|
|
const reading = envelopeFailureReading(status, error);
|
|
// A file the server refuses by size, type, digest, signature or scan is the
|
|
// user's to replace, as the same refusal before sending is
|
|
// (`readMultipartBody`). A 422 for a reused key with another body is not
|
|
// about the file and reads as the shared table reads it (2026-11-03 08-05).
|
|
const fileRefused =
|
|
status === 413 ||
|
|
status === 415 ||
|
|
(status === 422 && error.code !== "IDEMPOTENT_REQUEST_MISMATCH");
|
|
const kind: FailureKind = fileRefused ? "VALIDATION_REJECTED" : reading.kind;
|
|
const created = createFailure(kind, FILESERVER_UPLOAD_OPERATION_ID, 0, {
|
|
code: reading.code,
|
|
httpStatus: status,
|
|
effect,
|
|
...(retryAfterMs === null || waitRefused ? {} : { retryAfterMs }),
|
|
...(reading.validationIssues === undefined
|
|
? {}
|
|
: { validationIssues: reading.validationIssues }),
|
|
// 1105/01-03. The backend's `meta.traceId`, as the V3 executor carries it
|
|
// (1103/03-06), so support can find this upload in the server logs.
|
|
...(envelope.traceId === undefined ? {} : { traceId: envelope.traceId }),
|
|
});
|
|
// `retryable` in the Envelope is the server's decision for this answer and
|
|
// can only narrow the client's.
|
|
const retryable =
|
|
created.retryable && error.retryable !== false && !waitRefused;
|
|
return Object.freeze({
|
|
ok: false as const,
|
|
error:
|
|
retryable === created.retryable
|
|
? created
|
|
: Object.freeze({ ...created, retryable }),
|
|
});
|
|
}
|
|
|
|
/**
|
|
* In this order: an ambiguous answer, then the web contract's own answers
|
|
* (`sharedAnswerEffect`), then the Fileserver reading (`NOT_APPLIED_5XX_CODES`).
|
|
*/
|
|
export function fileserverFailureEffect(
|
|
status: number,
|
|
error: EnvelopeError,
|
|
): "NOT_APPLIED" | "MAYBE_APPLIED" {
|
|
const details = error.details;
|
|
const ambiguous =
|
|
details !== null &&
|
|
typeof details === "object" &&
|
|
!Array.isArray(details) &&
|
|
(details as Readonly<Record<string, unknown>>)["ambiguous"] === true;
|
|
if (ambiguous || error.code === "AMBIGUOUS_COMPLETION") return "MAYBE_APPLIED";
|
|
const shared = sharedAnswerEffect(status, error);
|
|
if (shared !== undefined) return shared;
|
|
if (status >= 400 && status < 500) return "NOT_APPLIED";
|
|
return NOT_APPLIED_5XX_CODES.has(error.code) ? "NOT_APPLIED" : "MAYBE_APPLIED";
|
|
}
|
|
|
|
function terminalFailure(
|
|
attempt: AbortableOperation,
|
|
effect: FailureEffectCertainty,
|
|
httpStatus?: number,
|
|
): Result<never, AppFailure> {
|
|
const details = {
|
|
effect,
|
|
...(httpStatus === undefined ? {} : { httpStatus }),
|
|
};
|
|
return attempt.terminal() === "DEADLINE"
|
|
? failure("REQUEST_TIMEOUT", "TIMEOUT", details)
|
|
: failure("REQUEST_ABORTED", "REQUEST_ABORTED", details);
|
|
}
|
|
|
|
function failure(
|
|
kind: FailureKind,
|
|
code: string,
|
|
details: Readonly<{
|
|
effect: FailureEffectCertainty;
|
|
httpStatus?: number;
|
|
}>,
|
|
): Result<never, AppFailure> {
|
|
return Object.freeze({
|
|
ok: false as const,
|
|
error: createFailure(kind, FILESERVER_UPLOAD_OPERATION_ID, 0, {
|
|
code,
|
|
...details,
|
|
}),
|
|
});
|
|
}
|