diff --git a/src/adapters/http/backend-envelope.ts b/src/adapters/http/backend-envelope.ts index f75ad745..5499f253 100644 --- a/src/adapters/http/backend-envelope.ts +++ b/src/adapters/http/backend-envelope.ts @@ -55,8 +55,12 @@ export function readFailureEnvelope( * gets the same answer. Only the documented status and code together count. * The value is the diagnostics `reason`, named for what is wrong on this side. */ +export type IdempotencyRefusalReason = + | "IDEMPOTENT_REQUEST_MISMATCH" + | "IDEMPOTENCY_KEY_RULE_MISMATCH"; + const IDEMPOTENCY_REFUSALS: Readonly< - Record> + Record> > = Object.freeze({ // The same key went out with another body. IDEMPOTENT_REQUEST_MISMATCH: Object.freeze({ @@ -74,7 +78,7 @@ const IDEMPOTENCY_REFUSALS: Readonly< export function idempotencyRefusalReason( code: string, status: number | undefined, -): string | undefined { +): IdempotencyRefusalReason | undefined { const refusal = Object.hasOwn(IDEMPOTENCY_REFUSALS, code) ? IDEMPOTENCY_REFUSALS[code] : undefined; diff --git a/src/adapters/http/http-execution-v3.ts b/src/adapters/http/http-execution-v3.ts index 84959475..f6cc4451 100644 --- a/src/adapters/http/http-execution-v3.ts +++ b/src/adapters/http/http-execution-v3.ts @@ -47,8 +47,10 @@ import { import { parseRetryAfter } from "./retry-policy.ts"; import { envelopeFailureEffect, + idempotencyRefusalReason, readFailureEnvelope, readSuccessEnvelope, + type IdempotencyRefusalReason, } from "./backend-envelope.ts"; import { createExecutionContext, @@ -336,10 +338,14 @@ export type HttpExecutionObservation = Readonly<{ * `MAYBE_APPLIED` (03-05). * - 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. */ export type HttpDiagnosticReason = | "CLASSIFIER_FAILED" - | HttpRequestRejectionReason; + | HttpRequestRejectionReason + | IdempotencyRefusalReason; /** * The outcome is the single authority for the observed error kind. The terminal @@ -1669,14 +1675,16 @@ async function admitProblem( // A body that is not a failure Envelope is an unreadable problem. let validated: ValidatorInvocation; let backendEffect: "NOT_APPLIED" | "MAYBE_APPLIED" | undefined; + let refusalReason: IdempotencyRefusalReason | undefined; if (enveloped) { const framed = readFailureEnvelope(decoded.value); validated = framed.ok ? invokeValidator(contract.problemValidator, framed.value) : UNFRAMED_PROBLEM; - backendEffect = framed.ok - ? envelopeFailureEffect(status, framed.value) - : undefined; + if (framed.ok) { + backendEffect = envelopeFailureEffect(status, framed.value); + refusalReason = idempotencyRefusalReason(framed.value.code, status); + } } else { validated = invokeValidator(contract.problemValidator, decoded.value); } @@ -1724,7 +1732,9 @@ async function admitProblem( retryAfterMs: metadata.retryAfterMs ?? null, ...(isCommand && classification.contractRuntimeFailure ? { diagnosticReason: "CLASSIFIER_FAILED" as const } - : {}), + : refusalReason === undefined + ? {} + : { diagnosticReason: refusalReason }), }); } diff --git a/tests/integration/http-execution-v3-envelope.test.ts b/tests/integration/http-execution-v3-envelope.test.ts index 77a656ee..99c9b5c0 100644 --- a/tests/integration/http-execution-v3-envelope.test.ts +++ b/tests/integration/http-execution-v3-envelope.test.ts @@ -8,8 +8,11 @@ import { createContractHttpExecutor, createFeatureHttpBinding, defineFeatureHttpOperation, + type HttpExecutionObservation, type InstalledHttpOperationExecutor, } from "../../src/adapters/http/index.ts"; +import { createHttpObservationProjector } from "../../src/bootstrap/runtime-adapters.ts"; +import type { DiagnosticRecordInput } from "../../src/contracts/diagnostics.ts"; import { mappingSuccess } from "../../src/contracts/boundary-mapper.ts"; import type { AppFailure } from "../../src/contracts/errors.ts"; import { @@ -253,10 +256,14 @@ function scope() { }); } -function v3Executor(fetcher?: typeof fetch): InstalledHttpOperationExecutor { +function v3Executor( + fetcher?: typeof fetch, + observe?: (observation: HttpExecutionObservation) => void, +): InstalledHttpOperationExecutor { const executor = createContractHttpExecutor({ baseUrl: BASE_URL, ...(fetcher === undefined ? {} : { fetcher }), + ...(observe === undefined ? {} : { observe }), maxRetryAttempts: 0, attachCredentials: () => ({ kind: "READY" as const, headers: {} }), random: () => 0, @@ -325,10 +332,14 @@ const V2_PAYLOADS: Readonly> = Object.freeze({ EnvelopeTestItem: itemSchema, }); -function v2(fetcher?: typeof fetch) { +function v2( + fetcher?: typeof fetch, + diagnostics?: Readonly<{ record(input: DiagnosticRecordInput): void }>, +) { return createHttpClient({ baseUrl: BASE_URL, ...(fetcher === undefined ? {} : { fetcher }), + ...(diagnostics === undefined ? {} : { diagnostics }), maxRetryAttempts: 0, clock: { now: () => 0, sleep: async () => {} }, authSession: createDemoSessionAdapter("authenticated"), @@ -614,6 +625,39 @@ describe("V3 Envelope verdicts equal the V2 client's for the same answer", () => }); }); +// 1101 README 14.4. V2 names an idempotency refusal in diagnostics (`reason`, +// a closed taxonomy). An Envelope operation's executor now knows the backend +// code and names the same ones; any other code stays out of diagnostics. +describe("V3 Envelope diagnostics name what V2 names", () => { + it.each([ + ["422 IDEMPOTENT_REQUEST_MISMATCH", 422, "IDEMPOTENT_REQUEST_MISMATCH", "IDEMPOTENT_REQUEST_MISMATCH"], + ["400 IDEMPOTENCY_KEY_INVALID", 400, "IDEMPOTENCY_KEY_INVALID", "IDEMPOTENCY_KEY_RULE_MISMATCH"], + ["409 IDEMPOTENT_IN_FLIGHT", 409, "IDEMPOTENT_IN_FLIGHT", undefined], + ["409 domain conflict", 409, "RESOURCE_CONFLICT", undefined], + ] as const)("%s", async (_label, status, code, reason) => { + answer("post", "/api/envelope-items", failure(code, "VALIDATION", false), { status }); + const v2Records: DiagnosticRecordInput[] = []; + const v3Records: DiagnosticRecordInput[] = []; + const project = createHttpObservationProjector({ + diagnostics: { record: (input) => v3Records.push(input) }, + telemetry: { emit: () => {} }, + }); + + await v2(undefined, { record: (input) => v2Records.push(input) }).execute( + "ENVELOPE_CREATE_ITEM", + { body: {}, idempotencyKey: KEY }, + ); + await v3CreateFailure( + createFeatureHttpBinding(v3Executor(undefined, project), OPERATIONS), + ); + + expect(v2Records).toHaveLength(1); + expect(v3Records).toHaveLength(1); + expect(v3Records[0]?.context?.reason).toBe(reason); + expect(v3Records[0]?.context?.reason).toBe(v2Records[0]?.context?.reason); + }); +}); + describe("shared MSW scenarios for an Envelope operation", () => { it.each([ ["success", { ok: true, value: [{ id: "item-1", name: "First" }] }],