Files
clean-architecture-frontend…/src/adapters/browser-transfer/presigned/http-common.ts
T
DongHyeonkaandClaude Opus 5.5 9e2c98272f fix(browser-transfer): share one presigned HTTP helper module (Q-6.1-9)
The presigned executor and the capability provider each carried a copy of
createAbortScope, readWithSignal, transferFailure, isAbortSignal,
byteBucket, body/reader cancel, Content-Length parsing and statusFailure.
They now import them from presigned/http-common.ts.

Behavior changes:
- statusFailure is one table. The provider used NONE for 401/403 and RETRY
  for 429/5xx; it now answers REISSUE_CAPABILITY like the executor. Retry
  decisions (retryable) are unchanged. Chosen because capabilities are
  single-use and the architecture doc (3.2) and BT-PRE-04 already say a
  refusal is recovered by a new capability.
- The download check used Number(Content-Length), which let "5e0", "0x5",
  "+5" and "5.0" through; it now uses the strict decimal parser the upload
  path and the provider already had.
- The executor's compensateLateResponse had no caller and is deleted.
- The resumable runtime's invokeProviderAttempt now bounds each attempt with
  the kernel createAbortableOperation instead of its own listener/timer
  race; outcomes (ABORTED on caller abort, retryable UNAVAILABLE on the
  deadline) are unchanged.

INVENTORY and the browser-transfer detail review list the new file. The
hand-rolled abort ratchet drops to 20/21; the ceiling constant is left for
the integration step so parallel lanes do not conflict on it.

Verified: RED tests "rejects a download Content-Length that is not a plain
decimal" (5e0 was accepted) and "maps capability endpoint statuses with the
executor's recovery table" (401 was NONE); existing presigned and runtime
suites cover the moved code + all gates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 13:32:56 +09:00

255 lines
7.7 KiB
TypeScript

import {
createAbortableOperation,
type AbortTimerSnapshot,
} from "../../platform/abortable-operation.ts";
import type {
BrowserDataFailureCode,
BrowserDataRecovery,
BrowserDataResult,
} from "../../../application/ports/browser-file-storage/shared.ts";
import { browserDataFailure } from "../../browser-file-storage/result.ts";
/**
* Q-6.1-9. HTTP mechanics shared by the presigned executor (object-store
* GET/PUT) and the capability provider (BFF issuance). They were two
* near-identical copies whose status table had already drifted apart.
*/
/** BT-PRE-03. The scope ended before the task settled. */
export const SCOPE_ENDED = Symbol("presigned-scope-ended");
export type PresignedAbortScope = ReturnType<typeof createAbortScope>;
/**
* TR-RR-01 / TR-RR-05. A thin projection of the shared
* `createAbortableOperation` primitive into this subsystem's vocabulary.
*
* `abort()` exists, so `close()` on a download can actually stop a pending
* fetch instead of only dropping listeners; and additional ownership signals —
* a consumer's stream signal — are composed into the same operation *before*
* any I/O starts, so an already-aborted consumer never causes a fetch.
*/
export function createAbortScope(
external: AbortSignal,
timeoutMs: number,
timers: AbortTimerSnapshot,
additionalSignals: readonly AbortSignal[] = [],
) {
const operation = createAbortableOperation({
signal: external,
timeoutMs,
setTimer: timers.setTimer,
clearTimer: timers.clearTimer,
});
const releases: (() => void)[] = [];
for (const extra of additionalSignals) {
if (!extra) continue;
if (extra.aborted) {
operation.close();
continue;
}
const onAbort = () => operation.close();
try {
extra.addEventListener("abort", onAbort, { once: true });
releases.push(() => {
try {
extra.removeEventListener("abort", onAbort);
} catch {
// A hostile signal facade cannot block the rest of cleanup.
}
});
} catch {
// A signal that refuses a listener cannot bound this operation, so the
// operation closes rather than running unbounded.
operation.close();
}
}
const end = () => {
operation.close();
for (const release of releases.splice(0)) release();
};
return Object.freeze({
signal: operation.signal,
timedOut: () => operation.terminal() === "DEADLINE",
/** Bounds a fetch that ignores its signal; a late response is cancelled. */
async race<Value>(task: Promise<Value>): Promise<Value | typeof SCOPE_ENDED> {
const outcome = await operation.race(task, (value) => {
const body = (
value as { body?: { cancel(): Promise<void> } | null } | null
)?.body;
void body?.cancel().catch(() => undefined);
});
if (outcome.kind === "VALUE") return outcome.value;
// A collaborator's own rejection stays a rejection: the caller's existing
// catch classifies it, and it is never forged into a cancellation.
if (outcome.kind === "REJECTED") throw outcome.reason;
return SCOPE_ENDED;
},
/** TR-RR-01. Ends the physical work, not just the bookkeeping. */
abort: end,
release: end,
});
}
export function readWithSignal(
reader: ReadableStreamDefaultReader<Uint8Array>,
signal: AbortSignal,
): Promise<ReadableStreamReadResult<Uint8Array>> {
if (signal.aborted) {
return Promise.reject(new DOMException("Aborted", "AbortError"));
}
return new Promise((resolve, reject) => {
const onAbort = () => {
reject(new DOMException("Aborted", "AbortError"));
};
signal.addEventListener("abort", onAbort, { once: true });
reader.read().then(
(result) => {
signal.removeEventListener("abort", onAbort);
resolve(result);
},
(error: unknown) => {
signal.removeEventListener("abort", onAbort);
reject(error);
},
);
});
}
export function cancelBody(response: Response): void {
try {
void response.body?.cancel().catch(() => {
// Cancellation is best effort after the result is classified.
});
} catch {
// A response already classified as failure/success is not reclassified by
// best-effort body cancellation.
}
}
export function cancelReader(
reader: ReadableStreamDefaultReader<Uint8Array>,
): void {
try {
void reader.cancel().catch(() => {
// Cancellation is best effort after the result is classified.
});
} catch {
// Reader cancellation cannot alter the terminal closed result.
}
}
/**
* A plain decimal `Content-Length`. `Number()` alone accepted `"5e0"`,
* `"0x5"`, `"+5"` and `""`. An absent header is `null` unless the caller's
* binding allows an implicit zero.
*/
export function normalizedContentLength(
value: string | null,
allowImplicitZero = false,
): number | null {
if (value === null) return allowImplicitZero ? 0 : null;
const trimmed = value.trim();
if (!/^(?:0|[1-9][0-9]{0,15})$/.test(trimmed)) return null;
const length = Number(trimmed);
return Number.isSafeInteger(length) ? length : null;
}
/**
* One status table for both HTTP exchanges. Presigned capabilities are
* single-use, so every recoverable refusal — an expired or rejected signature
* (401/403), a conflict, a gone resource or a transient 429/5xx — is recovered
* by issuing a new capability, never by replaying the same one.
*/
export function statusFailure(
status: number,
): BrowserDataResult<never> {
let code: BrowserDataFailureCode = "UNAVAILABLE";
let recovery: BrowserDataRecovery = "REISSUE_CAPABILITY";
let retryable = status === 429 || status >= 500;
if (status === 401 || status === 403) {
code = "PERMISSION_DENIED";
retryable = false;
} else if (status === 404) {
code = "NOT_FOUND";
recovery = "NONE";
retryable = false;
} else if (status === 409) {
code = "CONFLICT";
retryable = false;
} else if (status === 410) {
code = "EXPIRED_RESOURCE";
retryable = false;
} else if (status === 413) {
code = "LIMIT_EXCEEDED";
recovery = "NONE";
retryable = false;
} else if (status >= 400 && status < 500 && status !== 429) {
code = "POLICY_REJECTED";
recovery = "NONE";
retryable = false;
}
return browserDataFailure(code, "PRESIGNED_TRANSFER", {
retryable,
recovery,
});
}
export function transferFailure(
externalSignal: AbortSignal,
timedOut: boolean,
): BrowserDataResult<never> {
if (externalSignal.aborted) {
return browserDataFailure("ABORTED", "PRESIGNED_TRANSFER");
}
return browserDataFailure(
timedOut ? "UNAVAILABLE" : "NOT_READABLE",
"PRESIGNED_TRANSFER",
{
retryable: true,
recovery: "REISSUE_CAPABILITY",
},
);
}
export function isAbortSignal(value: unknown): value is AbortSignal {
try {
if (!value || typeof value !== "object") return false;
const abortedGetter = Object.getOwnPropertyDescriptor(
AbortSignal.prototype,
"aborted",
)?.get;
return Boolean(
abortedGetter &&
typeof abortedGetter.call(value) === "boolean" &&
typeof (value as AbortSignal).addEventListener === "function" &&
typeof (value as AbortSignal).removeEventListener === "function",
);
} catch {
return false;
}
}
export function byteBucket(
byteLength: number | undefined,
):
| "ZERO"
| "LT1MIB"
| "1_TO_9MIB"
| "10_TO_99MIB"
| "GTE100MIB"
| undefined {
if (
byteLength === undefined ||
!Number.isSafeInteger(byteLength) ||
byteLength < 0
) {
return undefined;
}
if (byteLength === 0) return "ZERO";
if (byteLength < 1_048_576) return "LT1MIB";
if (byteLength < 10_485_760) return "1_TO_9MIB";
if (byteLength < 104_857_600) return "10_TO_99MIB";
return "GTE100MIB";
}