refactor(http)!: V2 HTTP 클라이언트를 지우고 V3 실행기 하나만 남긴다
문제
HTTP 실행 경로가 둘이다. V3 실행기(createContractHttpExecutor)가 모든 기능을
실행하고, V2 클라이언트(createHttpClient)는 bootstrap의
createRuntimeHttpClient에서만 만들어지는데 그 함수를 앱 안에서 부르는 곳이
없다(테스트만 부른다). tech-log·memento도 같다. 그런데도 V2는 초기 청크에
들어가고, 짝 백엔드 해석(7db32e1~3261208)과 테스트를 두 벌로 유지하게 했다.
사용자 지시: 레거시를 두지 말고 최신 경로 하나만 남긴다.
고른 방법
- src/adapters/http/의 client.ts, bounded-json.ts, request-builder.ts,
resource-mapper.ts, retry-policy.ts, schema-registry.ts를 지웠다. Envelope
스키마는 backend-envelope.ts로 옮겼다. V3가 retry-policy.ts에서 쓰던
parseRetryAfter는 그것이 감싸던 platform/retry-after.ts의
parseRetryAfterDelay를 직접 부른다.
- 배럴의 V2 export와 bootstrap의 createRuntimeHttpClient·RuntimeHttpContract를
지웠다.
- V2 전용 테스트(http-client, http-diagnostics, auth-recovery,
legacy-http-credential-authority, bounded-json-compatibility,
request-builder, retry-policy)와 tests/helpers/http-contract-fixture.ts를
지웠다. 섞인 파일(http-execution-contract, runtime-adapters,
boundary-mapper)은 V2 블록만 지웠다.
- V2로 돌던 폼 테스트(form-foundation)는 Envelope을 읽는 V3 keyed create
계약으로 옮겼다. 400 VALIDATION_FAILED 필드 오류, {cause} 뒤 다시 저장,
422 뒤 저장 꺼짐을 그대로 검사한다. http-execution-v3-envelope 테스트는 V2와
비교하던 행을 기대 판정을 직접 적는 행으로 바꿨다.
- drill:runbook FE-RB-003은 V2 shouldRetry 대신 V3 실행기를 실제로 돌려
보낸 요청 수를 센다(NEVER 503: 1회, SAFE 503: 재시도, SAFE 스키마 불일치:
1회).
- check:diagnostics의 http 이벤트 생산자, registry-governance의 오류 표 소비자,
risk-coverage 고위험 경로, 아키텍처 금지 fixture, adapter INVENTORY, 문서의
경로를 V3 파일로 바꿨다.
버린 대안
- V2를 @deprecated로 한 릴리스 남기기: 템플릿과 두 다운스트림 모두 부르는
곳이 없어 옮겨 갈 사용자가 없다. 남기면 초기 JS와 두 벌 유지 비용만 남는다.
위험·한계
- BREAKING: 배럴과 bootstrap의 V2 이름을 쓰던 제품 코드는 컴파일이 깨진다.
CHANGELOG에 옮기는 방법을 적었다.
- V2에만 있던 동작이 사라졌다: 401 뒤 세션 복구 후 한 번 재전송, KEYED 503
자동 재시도. V3는 401을 UNAUTHENTICATED로 넘기고 KEYED 요청은 보낸 뒤
재시도하지 않는다.
- 기능마다 적는 V2 API 행(*-api-contract.ts, check:registries가 읽음)은 이
커밋에서 지우지 않았다. 다음 커밋이 지운다.
검증
- check:types, lint, check:architecture(금지 fixture 9건 거절),
check:adapter-inventory(140 files), check:diagnostics, check:registries,
check:ci, verify:documentation 통과.
- test:unit 2,585, test:integration 114, test:component 245, test:contract 23,
test:runtime-schema 56, tests/features 101 통과.
- drill:runbook FE-RB-003: no local check failed.
- check:bundle 통과. 초기 JS 203,354 → 201,598 B(−1,756 B).
BREAKING CHANGE: src/adapters/http/index.ts가 createHttpClient, HttpClient,
HttpClientDependencies, HttpFailure, HttpResult, LegacyHttpInput, Scheduler,
OperationRequestInput를, src/bootstrap/runtime-adapters.ts가
createRuntimeHttpClient, RuntimeHttpContract를 내보내지 않는다. 그 operation의
V3 descriptor를 만들어 createFeatureHttpBinding으로 실행한다.
This commit is contained in:
@@ -4,19 +4,52 @@ import {
|
||||
type FailureKind,
|
||||
type ValidationIssue,
|
||||
} from "../../contracts/errors.ts";
|
||||
import {
|
||||
failureEnvelopeSchema,
|
||||
successEnvelopeSchema,
|
||||
} from "./schema-registry.ts";
|
||||
import { z } from "../../contracts/zod.ts";
|
||||
|
||||
/**
|
||||
* 1101 README 14.3. How this client reads the paired backend's Envelope
|
||||
* (clean-architecture-backend-template docs/web/http-contract.md §1, §2, §4).
|
||||
* The V2 client and a V3 operation that declares
|
||||
* `responseEnvelope: "ENVELOPE_V1"` both read it here, so the same answer gets
|
||||
* the same verdict on both paths.
|
||||
* (clean-architecture-backend-template docs/web/http-contract.md §1, §2, §4)
|
||||
* for a V3 operation that declares `responseEnvelope: "ENVELOPE_V1"`.
|
||||
*/
|
||||
|
||||
/**
|
||||
* 백엔드 1101/02-02. The paired backend drops a null field together with its
|
||||
* key (§1). The id keys are absent on an answer written before its request id
|
||||
* filter, so they are optional here too.
|
||||
*/
|
||||
const metaSchema = z
|
||||
.object({
|
||||
requestId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(),
|
||||
traceId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(),
|
||||
correlationId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(),
|
||||
})
|
||||
.strip();
|
||||
|
||||
export const successEnvelopeSchema = z
|
||||
.object({
|
||||
success: z.literal(true),
|
||||
// A missing `data` is the null the backend dropped.
|
||||
data: z.unknown().default(null),
|
||||
meta: metaSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const failureEnvelopeSchema = z
|
||||
.object({
|
||||
success: z.literal(false),
|
||||
error: z
|
||||
.object({
|
||||
code: z.string().regex(/^[A-Z0-9_]{1,64}$/),
|
||||
category: z.string().min(1).max(64).optional(),
|
||||
message: z.string().max(1_024).optional(),
|
||||
retryable: z.boolean().optional(),
|
||||
details: z.unknown().optional(),
|
||||
})
|
||||
.strict(),
|
||||
meta: metaSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type EnvelopeError = Readonly<{
|
||||
code: string;
|
||||
category?: string;
|
||||
@@ -150,7 +183,7 @@ export function gatewayFailureOr(status: number, kind: FailureKind): FailureKind
|
||||
: kind;
|
||||
}
|
||||
|
||||
/** The failure kind, code and field issues the V2 client reports. */
|
||||
/** The failure kind, code and field issues an unmapped problem reads as. */
|
||||
export function envelopeFailureReading(
|
||||
status: number,
|
||||
error: EnvelopeError,
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import { decodeJsonBytes, readBoundedBytes } from "./bounded-body-reader.ts";
|
||||
|
||||
export type BoundedJsonResult =
|
||||
| Readonly<{ ok: true; value: unknown }>
|
||||
| Readonly<{ ok: false; code: "RESPONSE_BODY_LIMIT" | "MALFORMED_JSON" }>;
|
||||
|
||||
/**
|
||||
* N-08. The V2 compatibility reader delegates to the common bounded reader
|
||||
* instead of maintaining a second stream-reading strategy.
|
||||
*
|
||||
* `bounded-body-reader` already isolates `cancel()` and `releaseLock()` throws
|
||||
* so a cleanup failure cannot escape the closed result. Only the legacy failure
|
||||
* codes are preserved here:
|
||||
*
|
||||
* - `RESPONSE_TOO_LARGE` → `RESPONSE_BODY_LIMIT`
|
||||
* - `RESPONSE_STREAM_FAILURE` / `UTF8_INVALID` / `JSON_INVALID` →
|
||||
* `MALFORMED_JSON`
|
||||
*/
|
||||
export async function readBoundedJson(
|
||||
response: Response,
|
||||
maxBytes: number,
|
||||
): Promise<BoundedJsonResult> {
|
||||
const bytes = await readBoundedBytes(response, maxBytes);
|
||||
if (!bytes.ok) {
|
||||
return Object.freeze({
|
||||
ok: false as const,
|
||||
code:
|
||||
bytes.code === "RESPONSE_TOO_LARGE"
|
||||
? ("RESPONSE_BODY_LIMIT" as const)
|
||||
: ("MALFORMED_JSON" as const),
|
||||
});
|
||||
}
|
||||
// An absent body decodes to zero bytes, which is not valid JSON. The legacy
|
||||
// contract reported that as MALFORMED_JSON, and that is preserved.
|
||||
const decoded = decodeJsonBytes(bytes.bytes);
|
||||
return decoded.ok
|
||||
? Object.freeze({ ok: true as const, value: decoded.value })
|
||||
: Object.freeze({ ok: false as const, code: "MALFORMED_JSON" as const });
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -298,8 +298,8 @@ export function createFeatureHttpBinding<
|
||||
|
||||
/**
|
||||
* 1101 README 14.3. An Envelope operation's problem is the backend `error`
|
||||
* object, so what the feature does not map reads as the V2 client reads it:
|
||||
* the backend code, field issues from a validation failure, and the V2 kind.
|
||||
* object, so what the feature does not map still reads as the backend means
|
||||
* it: its code, field issues from a validation failure, and the status kind.
|
||||
*/
|
||||
function problemMapper<Problem>(
|
||||
mapProblem:
|
||||
@@ -524,7 +524,7 @@ function failureKindForViolation(violation: HttpContractViolation): FailureKind
|
||||
// 03-02. Only input the user can change is "input rejected"; a client
|
||||
// wiring defect (contract not installed, path template and projection
|
||||
// disagree, intent policy disagrees with the contract) cannot be fixed by
|
||||
// the user, the same reading as the V2 client's OPERATION_NOT_REGISTERED.
|
||||
// the user.
|
||||
case "FINAL_REQUEST_INVARIANT_FAILED":
|
||||
return violation.reason === undefined ||
|
||||
USER_INPUT_REJECTIONS.has(violation.reason)
|
||||
|
||||
@@ -51,7 +51,7 @@ export type CredentialAdmissionOutcome =
|
||||
const MAX_CREDENTIAL_HEADER_VALUE_BYTES = 8_192;
|
||||
|
||||
/**
|
||||
* R-3.4. The one credential value rule for V2 and V3: a ByteString (every code
|
||||
* R-3.4. The one credential value rule: a ByteString (every code
|
||||
* unit one byte on the wire) with no C0/C1 control characters. Fetch rejects
|
||||
* anything else only after the request counts as dispatched.
|
||||
*/
|
||||
|
||||
@@ -44,7 +44,7 @@ import {
|
||||
type MutationEffectCertainty,
|
||||
type PhysicalAttemptState,
|
||||
} from "./http-effect-certainty.ts";
|
||||
import { parseRetryAfter } from "./retry-policy.ts";
|
||||
import { parseRetryAfterDelay } from "../platform/retry-after.ts";
|
||||
import {
|
||||
envelopeFailureEffect,
|
||||
idempotencyRefusalReason,
|
||||
@@ -339,8 +339,8 @@ export type HttpExecutionObservation = Readonly<{
|
||||
* - an `HttpRequestRejectionReason`: copied from the refused request's
|
||||
* violation (03-02).
|
||||
* - an `IdempotencyRefusalReason`: an Envelope operation's backend refused
|
||||
* the idempotency key, the reason the V2 client records (1101 README 14.4).
|
||||
* No other backend code reaches diagnostics; the failure's code carries it.
|
||||
* the idempotency key (1101 README 14.4). No other backend code reaches
|
||||
* diagnostics; the failure's code carries it.
|
||||
*/
|
||||
export type HttpDiagnosticReason =
|
||||
| "CLASSIFIER_FAILED"
|
||||
@@ -1233,7 +1233,10 @@ async function admitResponse<Input, WireOutput, Problem>(
|
||||
const policy = operation.frontend;
|
||||
const isCommand = contract.commandEffect !== null;
|
||||
const status = response.status;
|
||||
const retryAfterMs = parseRetryAfter(response.headers.get("retry-after"));
|
||||
const retryAfterMs = parseRetryAfterDelay(
|
||||
response.headers.get("retry-after"),
|
||||
Date.now(),
|
||||
);
|
||||
|
||||
if (response.redirected || response.type === "opaqueredirect") {
|
||||
await response.body?.cancel().catch(() => {});
|
||||
@@ -1422,7 +1425,7 @@ async function admitResponse<Input, WireOutput, Problem>(
|
||||
}
|
||||
|
||||
// 1101 README 14.3. The frame is checked after the byte and structure
|
||||
// bounds, which count the whole Envelope, as V2 counts maxResponseBytes.
|
||||
// bounds, which count the whole Envelope.
|
||||
let wireValue = decoded.value;
|
||||
if (contract.responseEnvelope === "ENVELOPE_V1") {
|
||||
const framed = readSuccessEnvelope(decoded.value);
|
||||
@@ -1600,9 +1603,8 @@ async function admitProblem<Input, WireOutput, Problem>(
|
||||
const isCommand = contract.commandEffect !== null;
|
||||
const retryable = isRetryableHttpStatus(status);
|
||||
const enveloped = contract.responseEnvelope === "ENVELOPE_V1";
|
||||
// 1101 README 14.3. V2 bounds a failure Envelope by maxResponseBytes, the
|
||||
// same value as responseByteLimit. The problem ceiling stays the upper
|
||||
// bound, so V2 alone reads a failure Envelope between it and that limit.
|
||||
// 1101 README 14.3. A failure Envelope is bounded by the operation's
|
||||
// response limit too, and never above the problem ceiling.
|
||||
const problemByteLimit = enveloped
|
||||
? Math.min(
|
||||
HTTP_EXECUTION_CEILINGS.problemResponseBytes,
|
||||
@@ -1705,7 +1707,7 @@ async function admitProblem<Input, WireOutput, Problem>(
|
||||
}
|
||||
|
||||
// The backend's own verdict, when it has one, is the same for every
|
||||
// operation and the same one V2 gives. The package classifies the rest.
|
||||
// operation. The package classifies the rest.
|
||||
const classification =
|
||||
isCommand && backendEffect !== undefined
|
||||
? Object.freeze({ effect: backendEffect, contractRuntimeFailure: false })
|
||||
|
||||
@@ -37,25 +37,3 @@ export {
|
||||
} from "./feature-http-binding.ts";
|
||||
/** V3 `attachCredentials` 콜백이 반환해야 하는 결과 타입. */
|
||||
export type { CredentialPatchOutcome } from "./http-contract-bridge.ts";
|
||||
/**
|
||||
* V2 legacy. operationId + `LegacyHttpInput`으로 호출하는 범용 클라이언트다.
|
||||
* 새 코드는 위의 V3 실행기를 쓴다.
|
||||
*
|
||||
* 이 템플릿은 V2의 오퍼레이션 레지스트리와 payload 매퍼를 비워서 출하한다.
|
||||
* 제품이 `RuntimeHttpContract`(`src/bootstrap/runtime-adapters.ts`)의 네
|
||||
* 슬롯을 주입해야 동작한다. V2는 늘 `{ success, data | error, meta }` 봉투를
|
||||
* 읽는다. V3는 descriptor가 `responseEnvelope: "ENVELOPE_V1"`일 때만 봉투를
|
||||
* 읽고, 아니면 DTO 자체를 검증한다. 두 경로는 같은 봉투 해석
|
||||
* (`backend-envelope.ts`)을 쓴다.
|
||||
*/
|
||||
export {
|
||||
createHttpClient,
|
||||
type HttpClient,
|
||||
type HttpClientDependencies,
|
||||
type HttpFailure,
|
||||
type HttpResult,
|
||||
type LegacyHttpInput,
|
||||
type Scheduler,
|
||||
} from "./client.ts";
|
||||
/** V2 `HttpClient.execute`의 첫 인자 타입. */
|
||||
export type { OperationRequestInput } from "./request-builder.ts";
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
import type { ApiOperation } from "../../contracts/api-operations.ts";
|
||||
|
||||
export type OperationRequestInput = Readonly<{
|
||||
operationId: string;
|
||||
routeId: string;
|
||||
pathParams?: Readonly<Record<string, string | number>>;
|
||||
searchParams?: unknown;
|
||||
body?: unknown;
|
||||
signal?: AbortSignal;
|
||||
idempotencyKey?: string;
|
||||
correlationId?: string;
|
||||
}>;
|
||||
|
||||
export type RequestTargetResult =
|
||||
| Readonly<{ success: true; url: URL }>
|
||||
| Readonly<{
|
||||
success: false;
|
||||
code:
|
||||
| "BASE_URL_INVALID"
|
||||
| "PATH_PARAMETER_MISSING"
|
||||
| "PATH_PARAMETER_UNEXPECTED"
|
||||
| "PATH_PARAMETER_INVALID"
|
||||
| "SEARCH_PARAMETER_INVALID";
|
||||
}>;
|
||||
|
||||
const pathParameterPattern = /:([A-Za-z][A-Za-z0-9_]*)|\{([A-Za-z][A-Za-z0-9_]*)\}/g;
|
||||
|
||||
export function buildRequestTarget(
|
||||
baseUrl: string,
|
||||
operation: ApiOperation,
|
||||
pathParams: Readonly<Record<string, string | number>> = {},
|
||||
parsedSearch: unknown = {},
|
||||
): RequestTargetResult {
|
||||
let base: URL;
|
||||
try {
|
||||
base = new URL(baseUrl);
|
||||
} catch {
|
||||
return { success: false, code: "BASE_URL_INVALID" };
|
||||
}
|
||||
if (
|
||||
(base.protocol !== "https:" &&
|
||||
!(
|
||||
base.protocol === "http:" &&
|
||||
["localhost", "127.0.0.1", "[::1]"].includes(base.hostname)
|
||||
)) ||
|
||||
base.username ||
|
||||
base.password ||
|
||||
base.search ||
|
||||
base.hash
|
||||
) {
|
||||
return { success: false, code: "BASE_URL_INVALID" };
|
||||
}
|
||||
|
||||
const placeholders = new Set<string>();
|
||||
for (const match of operation.path.matchAll(pathParameterPattern)) {
|
||||
placeholders.add(match[1] ?? match[2] ?? "");
|
||||
}
|
||||
if (Object.keys(pathParams).some((key) => !placeholders.has(key))) {
|
||||
return { success: false, code: "PATH_PARAMETER_UNEXPECTED" };
|
||||
}
|
||||
let missingPathParameter = false;
|
||||
let invalidPathParameter = false;
|
||||
const pathname = operation.path.replace(
|
||||
pathParameterPattern,
|
||||
(_token, colonName: string | undefined, braceName: string | undefined) => {
|
||||
const name = colonName ?? braceName ?? "";
|
||||
const value = pathParams[name];
|
||||
if (value === undefined) {
|
||||
missingPathParameter = true;
|
||||
return "";
|
||||
}
|
||||
const serialized = String(value);
|
||||
if (
|
||||
serialized.length === 0 ||
|
||||
serialized.length > 512 ||
|
||||
// Dot segments are not encoded and pathname assignment normalizes them.
|
||||
serialized === "." ||
|
||||
serialized === ".." ||
|
||||
[...serialized].some((character) => {
|
||||
const code = character.codePointAt(0) ?? 0;
|
||||
return code < 32 || code === 127;
|
||||
})
|
||||
) {
|
||||
invalidPathParameter = true;
|
||||
return "";
|
||||
}
|
||||
return encodeURIComponent(serialized);
|
||||
},
|
||||
);
|
||||
if (missingPathParameter) {
|
||||
return { success: false, code: "PATH_PARAMETER_MISSING" };
|
||||
}
|
||||
if (invalidPathParameter) {
|
||||
return { success: false, code: "PATH_PARAMETER_INVALID" };
|
||||
}
|
||||
|
||||
if (
|
||||
parsedSearch === null ||
|
||||
typeof parsedSearch !== "object" ||
|
||||
Array.isArray(parsedSearch)
|
||||
) {
|
||||
return { success: false, code: "SEARCH_PARAMETER_INVALID" };
|
||||
}
|
||||
|
||||
const basePrefix = base.pathname.endsWith("/")
|
||||
? base.pathname
|
||||
: `${base.pathname}/`;
|
||||
const relativePath = pathname.replace(/^\/+/, "");
|
||||
base.pathname = `${basePrefix}${relativePath}`.replace(/\/{2,}/g, "/");
|
||||
const url = base;
|
||||
const search = parsedSearch as Readonly<Record<string, unknown>>;
|
||||
for (const key of Object.keys(search).sort((left, right) =>
|
||||
left.localeCompare(right),
|
||||
)) {
|
||||
const value = search[key];
|
||||
if (value === undefined || value === null) continue;
|
||||
const values = Array.isArray(value) ? value : [value];
|
||||
for (const item of values) {
|
||||
if (
|
||||
typeof item !== "string" &&
|
||||
typeof item !== "number" &&
|
||||
typeof item !== "boolean"
|
||||
) {
|
||||
return { success: false, code: "SEARCH_PARAMETER_INVALID" };
|
||||
}
|
||||
url.searchParams.append(key, String(item));
|
||||
}
|
||||
}
|
||||
if (
|
||||
operation.maxEncodedSearchBytes !== undefined &&
|
||||
new TextEncoder().encode(url.search).byteLength >
|
||||
operation.maxEncodedSearchBytes
|
||||
) {
|
||||
return { success: false, code: "SEARCH_PARAMETER_INVALID" };
|
||||
}
|
||||
return { success: true, url };
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
import {
|
||||
mappingFailure,
|
||||
type BoundaryMappingResult,
|
||||
} from "../../contracts/boundary-mapper.ts";
|
||||
|
||||
export function mapOperationPayload(
|
||||
_operationId: string,
|
||||
_payload: unknown,
|
||||
): BoundaryMappingResult<never> {
|
||||
return mappingFailure("MAPPING_INVARIANT_REJECTED");
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
import { parseRetryAfterDelay } from "../platform/retry-after.ts";
|
||||
|
||||
const retryKinds: ReadonlySet<string> = new Set([
|
||||
"NETWORK_UNREACHABLE",
|
||||
"REQUEST_TIMEOUT",
|
||||
"RATE_LIMITED",
|
||||
"SERVER_FAILURE",
|
||||
]);
|
||||
|
||||
export function calculateBackoff(
|
||||
retryIndex: number,
|
||||
random = Math.random,
|
||||
baseDelayMs = 250,
|
||||
maxDelayMs = 2_000,
|
||||
): number {
|
||||
return Math.min(maxDelayMs, baseDelayMs * 2 ** retryIndex) * random();
|
||||
}
|
||||
|
||||
export function parseRetryAfter(
|
||||
value: string | null | undefined,
|
||||
now = Date.now(),
|
||||
): number | null {
|
||||
return parseRetryAfterDelay(value, now);
|
||||
}
|
||||
|
||||
export type RetryOperation = Readonly<{
|
||||
idempotency: "safe" | "keyed" | "none";
|
||||
retry?: "runtime" | "never";
|
||||
}>;
|
||||
|
||||
export type RetryFailure = Readonly<{
|
||||
kind: string;
|
||||
retryAfterMs?: number;
|
||||
retryAfter?: string;
|
||||
httpStatus?: number;
|
||||
}>;
|
||||
|
||||
export function shouldRetry(
|
||||
operation: RetryOperation,
|
||||
failure: RetryFailure,
|
||||
retryCount: number,
|
||||
maxRetries = 2,
|
||||
): boolean {
|
||||
if (operation.retry === "never") return false;
|
||||
if (retryCount >= maxRetries) return false;
|
||||
if (!retryKinds.has(failure.kind)) return false;
|
||||
if (
|
||||
failure.kind === "SERVER_FAILURE" &&
|
||||
failure.httpStatus !== undefined &&
|
||||
![408, 425, 502, 503, 504].includes(failure.httpStatus)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
typeof failure.retryAfterMs === "number" &&
|
||||
failure.retryAfterMs > 30_000
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return operation.idempotency === "safe" || operation.idempotency === "keyed";
|
||||
}
|
||||
|
||||
export function retryDelay(
|
||||
failure: RetryFailure,
|
||||
retryIndex: number,
|
||||
random = Math.random,
|
||||
now = Date.now(),
|
||||
): number {
|
||||
const localBackoff = calculateBackoff(retryIndex, random);
|
||||
const retryAfterMs =
|
||||
typeof failure.retryAfterMs === "number"
|
||||
? failure.retryAfterMs
|
||||
: parseRetryAfter(failure.retryAfter, now);
|
||||
|
||||
return retryAfterMs === null ? localBackoff : Math.max(localBackoff, retryAfterMs);
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
import { z } from "../../contracts/zod.ts";
|
||||
import { projectValidationIssues } from "../../contracts/validation-issues.ts";
|
||||
|
||||
/**
|
||||
* 백엔드 1101/02-02. The paired backend drops a null field together with its
|
||||
* key (clean-architecture-backend-template docs/web/http-contract.md §1). The
|
||||
* id keys are absent on an answer written before its request id filter, so
|
||||
* they are optional here too.
|
||||
*/
|
||||
const metaSchema = z
|
||||
.object({
|
||||
requestId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(),
|
||||
traceId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(),
|
||||
correlationId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(),
|
||||
})
|
||||
.strip();
|
||||
|
||||
export const successEnvelopeSchema = z
|
||||
.object({
|
||||
success: z.literal(true),
|
||||
// A missing `data` is the null the backend dropped.
|
||||
data: z.unknown().default(null),
|
||||
meta: metaSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const failureEnvelopeSchema = z
|
||||
.object({
|
||||
success: z.literal(false),
|
||||
error: z
|
||||
.object({
|
||||
code: z.string().regex(/^[A-Z0-9_]{1,64}$/),
|
||||
category: z.string().min(1).max(64).optional(),
|
||||
message: z.string().max(1_024).optional(),
|
||||
retryable: z.boolean().optional(),
|
||||
details: z.unknown().optional(),
|
||||
})
|
||||
.strict(),
|
||||
meta: metaSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const responseEnvelopeSchema = z.discriminatedUnion("success", [
|
||||
successEnvelopeSchema,
|
||||
failureEnvelopeSchema,
|
||||
]);
|
||||
|
||||
const payloadSchemas: Readonly<Record<string, z.ZodType<unknown>>> =
|
||||
Object.freeze({});
|
||||
|
||||
const requestSchemas: Readonly<Record<string, z.ZodType<unknown>>> =
|
||||
Object.freeze({});
|
||||
|
||||
export type SchemaIssue = Readonly<{
|
||||
path: string;
|
||||
code: string;
|
||||
schemaId?: string;
|
||||
}>;
|
||||
|
||||
export type SchemaValidationResult =
|
||||
| Readonly<{ success: true; data: unknown }>
|
||||
| Readonly<{ success: false; issues: readonly SchemaIssue[] }>;
|
||||
|
||||
export function validateEnvelope(value: unknown): SchemaValidationResult {
|
||||
return projectResult(responseEnvelopeSchema.safeParse(value));
|
||||
}
|
||||
|
||||
export function validateOperationPayload(
|
||||
schemaId: string,
|
||||
value: unknown,
|
||||
): SchemaValidationResult {
|
||||
const schema = payloadSchemas[schemaId];
|
||||
if (!schema) return missingSchema(schemaId);
|
||||
return projectResult(schema.safeParse(value));
|
||||
}
|
||||
|
||||
export function validateOperationRequest(
|
||||
schemaId: string,
|
||||
value: unknown,
|
||||
): SchemaValidationResult {
|
||||
const schema = requestSchemas[schemaId];
|
||||
if (!schema) return missingSchema(schemaId);
|
||||
return projectResult(schema.safeParse(value));
|
||||
}
|
||||
|
||||
function missingSchema(schemaId: string): SchemaValidationResult {
|
||||
return {
|
||||
success: false,
|
||||
issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED", schemaId }],
|
||||
};
|
||||
}
|
||||
|
||||
function projectResult(
|
||||
result:
|
||||
| Readonly<{ success: true; data: unknown }>
|
||||
| Readonly<{
|
||||
success: false;
|
||||
error: Readonly<{
|
||||
issues: readonly Readonly<{
|
||||
path: readonly PropertyKey[];
|
||||
code: string;
|
||||
}>[];
|
||||
}>;
|
||||
}>,
|
||||
): SchemaValidationResult {
|
||||
if (result.success) {
|
||||
return {
|
||||
success: true,
|
||||
data: structuredClone(result.data),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
issues: projectValidationIssues(result.error.issues),
|
||||
};
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
import { createDiagnosticsAdapter } from "../adapters/diagnostics/index.ts";
|
||||
import {
|
||||
createContractHttpExecutor,
|
||||
createHttpClient,
|
||||
type HttpExecutionObservation,
|
||||
type InstalledHttpOperationExecutor,
|
||||
} from "../adapters/http/index.ts";
|
||||
@@ -35,13 +34,8 @@ import {
|
||||
createTelemetryAdapter,
|
||||
createTelemetryCollector,
|
||||
} from "../adapters/telemetry/index.ts";
|
||||
import type { AuthSessionPort } from "../application/ports/auth-session-port.ts";
|
||||
import type { ReleaseInfo } from "../application/ports/release-info-port.ts";
|
||||
import {
|
||||
createRestProviderProfile,
|
||||
INSTALLED_REST_AUTH_PROFILES,
|
||||
} from "../contracts/rest-profiles.ts";
|
||||
import type { ClockPort } from "../application/ports/clock-port.ts";
|
||||
import { INSTALLED_REST_AUTH_PROFILES } from "../contracts/rest-profiles.ts";
|
||||
import { createInstalledFeatureLoaders } from "../features/installed-feature-adapters.ts";
|
||||
import {
|
||||
INVALIDATION_REGISTRY,
|
||||
@@ -72,41 +66,6 @@ import {
|
||||
indexInvalidationTopicVersions,
|
||||
} from "../contracts/query-invalidation.ts";
|
||||
|
||||
type HttpClientDependencies = Parameters<typeof createHttpClient>[0];
|
||||
/**
|
||||
* 제품이 V2 전송을 쓰려면 채워야 하는 슬롯 네 개.
|
||||
*
|
||||
* 이 템플릿은 넷 다 비워서 출하한다. 기본값인
|
||||
* `contracts/api-operations.ts`의 `API_OPERATIONS`는 빈 객체이고
|
||||
* `adapters/http/resource-mapper.ts`의 `mapOperationPayload`는 항상
|
||||
* `MAPPING_INVARIANT_REJECTED`를 반환한다. 그래서 **이 레포 상태 그대로는
|
||||
* V2로 어떤 오퍼레이션도 실행되지 않는다** — 그건 결함이 아니라 제품이
|
||||
* 채우는 자리다.
|
||||
*
|
||||
* V2는 V3를 그대로 되돌리는 롤백 경로가 아니다. 두 경로는 wire 형식이
|
||||
* 다르다. V2는 `{ success, data, meta }` 봉투를 검증하고
|
||||
* (`adapters/http/schema-registry.ts`), V3는 봉투 없는 DTO 자체를 검증한다.
|
||||
* 그래서 네 슬롯을 모두 주입해도 같은 백엔드로 V2로 되돌리면 모든 응답이
|
||||
* `ENVELOPE_MISMATCH`다. V2로 되돌리려면 슬롯 주입과 함께 서버도 V2 봉투로
|
||||
* 응답해야 한다.
|
||||
* V3(`createContractHttpExecutor`)는 설치된 feature 계약에서 오퍼레이션을
|
||||
* 받으므로 이 슬롯과 무관하게 동작한다.
|
||||
*/
|
||||
export type RuntimeHttpContract = Pick<
|
||||
HttpClientDependencies,
|
||||
"getOperation" | "validatePayload" | "validateRequest" | "mapPayload"
|
||||
>;
|
||||
|
||||
type RuntimeHttpContext = Readonly<{
|
||||
runtime: RuntimeConfigLoadResult;
|
||||
authSession: AuthSessionPort;
|
||||
fetcher?: typeof fetch;
|
||||
clock?: ClockPort;
|
||||
scheduler?: HttpClientDependencies["scheduler"];
|
||||
diagnostics?: HttpClientDependencies["diagnostics"];
|
||||
telemetry?: HttpClientDependencies["telemetry"];
|
||||
}>;
|
||||
|
||||
export type RuntimeAdaptersContext = Readonly<{
|
||||
runtime: RuntimeConfigLoadResult;
|
||||
release: Readonly<ReleaseManifest>;
|
||||
@@ -211,33 +170,6 @@ function storageOrUndefined(value: unknown): Storage | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runtime-aware transport factory. Feature gateway composition calls this
|
||||
* factory when a registered API capability is installed.
|
||||
*/
|
||||
export function createRuntimeHttpClient(
|
||||
context: RuntimeHttpContext,
|
||||
contract: RuntimeHttpContract = {},
|
||||
) {
|
||||
return createHttpClient({
|
||||
baseUrl: context.runtime.config.API_BASE_URL,
|
||||
timeoutMs: context.runtime.config.REQUEST_TIMEOUT_MS,
|
||||
maxRetryAttempts: context.runtime.config.MAX_RETRY_ATTEMPTS,
|
||||
authSession: context.authSession,
|
||||
providerProfile: createRestProviderProfile(
|
||||
"PRIMARY_API",
|
||||
context.runtime.config.API_BASE_URL,
|
||||
["omit"],
|
||||
),
|
||||
fetcher: context.fetcher,
|
||||
clock: context.clock,
|
||||
scheduler: context.scheduler,
|
||||
diagnostics: context.diagnostics,
|
||||
telemetry: context.telemetry,
|
||||
...contract,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* VD-07. Exactly one diagnostic per logical V3 execution and exactly one
|
||||
* `api.request.failed` telemetry event per terminal non-abort failure.
|
||||
|
||||
Reference in New Issue
Block a user