diff --git a/docs/architecture/2026-07-30-frontend-runtime-capability-repository-aligned-implementation-closed-deep-design.md b/docs/architecture/2026-07-30-frontend-runtime-capability-repository-aligned-implementation-closed-deep-design.md index a7bec984..2112ff41 100644 --- a/docs/architecture/2026-07-30-frontend-runtime-capability-repository-aligned-implementation-closed-deep-design.md +++ b/docs/architecture/2026-07-30-frontend-runtime-capability-repository-aligned-implementation-closed-deep-design.md @@ -635,6 +635,7 @@ export interface CommandEffectDescriptor { status: number; problem: Problem; }>): "NOT_APPLIED" | "APPLIED_CONFIRMED" | "MAYBE_APPLIED"; + classifyStatus?(status: 401 | 403 | 429): "NOT_APPLIED" | "MAYBE_APPLIED"; } ``` @@ -647,6 +648,8 @@ export interface CommandEffectDescriptor { - frontend는 inspect request/response wire shape나 problem effect meaning을 작성하지 않는다; - `classifyProblem`은 package가 제공한 pure bounded classifier다; - classifier가 throw/unknown을 반환하면 effect는 fail-safe `MAYBE_APPLIED`이고 contract runtime failure를 기록한다; +- 401·403·429는 본문을 읽기 전에 판정하므로 `classifyProblem`을 거치지 않는다. package가 `classifyStatus`를 주면 그 판정을 쓰고, 없거나 `NOT_APPLIED` 외 값·throw면 전송 뒤 `MAYBE_APPLIED`다(`src/adapters/http/http-effect-certainty.ts` `classifyStatusEffect`); +- `AUTH_REQUIRED`는 effect가 `MAYBE_APPLIED`여도 action이 `reauth`다(`src/contracts/errors.ts` `unknownEffectAction`); - feature gateway가 package의 inspect operation을 application-safe outcome으로 mapping한다. ### 4.5 event contribution diff --git a/src/adapters/http/http-effect-certainty.ts b/src/adapters/http/http-effect-certainty.ts index d008b707..0ad44c28 100644 --- a/src/adapters/http/http-effect-certainty.ts +++ b/src/adapters/http/http-effect-certainty.ts @@ -128,6 +128,28 @@ export function classifyProblemEffect( }); } +/** + * D-2. A dispatched command answered 401, 403 or 429 is `MAYBE_APPLIED` unless + * the package classifies that status as `NOT_APPLIED`. Any other answer, or a + * throw, fails safe to `MAYBE_APPLIED`. + */ +export function classifyStatusEffect( + descriptor: CommandEffectDescriptor | null, + status: 401 | 403 | 429, + abandoned: MutationEffectCertainty, +): MutationEffectCertainty { + if (abandoned !== "MAYBE_APPLIED" || !descriptor?.classifyStatus) { + return abandoned; + } + try { + return descriptor.classifyStatus(status) === "NOT_APPLIED" + ? "NOT_APPLIED" + : "MAYBE_APPLIED"; + } catch { + return "MAYBE_APPLIED"; + } +} + /** §8.10. Certainty to UI intent. The copy itself is owned by the i18n catalog. */ export function projectCertaintyToUi( certainty: MutationEffectCertainty, diff --git a/src/adapters/http/http-execution-v3.ts b/src/adapters/http/http-execution-v3.ts index 47138898..42d8b5ae 100644 --- a/src/adapters/http/http-execution-v3.ts +++ b/src/adapters/http/http-execution-v3.ts @@ -36,6 +36,7 @@ import { import { certaintyForAbandonedAttempt, classifyProblemEffect, + classifyStatusEffect, joinMutationEffectCertainty, type MutationEffectCertainty, type PhysicalAttemptState, @@ -1142,25 +1143,24 @@ async function admitResponse( } const metadata = safeMetadata(response, retryAfterMs); + const statusEffect = (classified: 401 | 403 | 429) => + classifyStatusEffect( + contract.commandEffect, + classified, + certaintyForAbandonedAttempt(attemptState, isCommand), + ); if (!contract.acceptedStatuses.includes(status)) { if (status === 401) { await response.body?.cancel().catch(() => {}); return settled( - unauthenticated( - certaintyForAbandonedAttempt(attemptState, isCommand), - isCommand, - metadata, - ), + unauthenticated(statusEffect(401), isCommand, metadata), "UNAUTHENTICATED", ); } if (status === 403) { await response.body?.cancel().catch(() => {}); - return settled( - forbidden(certaintyForAbandonedAttempt(attemptState, isCommand), isCommand), - "FORBIDDEN", - ); + return settled(forbidden(statusEffect(403), isCommand), "FORBIDDEN"); } if (status === 429) { await response.body?.cancel().catch(() => {}); @@ -1168,10 +1168,7 @@ async function admitResponse( result: Object.freeze({ kind: "RATE_LIMITED" as const, ...(retryAfterMs === null ? {} : { retryAfterMs }), - effect: normalizeOptionalEffect( - certaintyForAbandonedAttempt(attemptState, isCommand), - isCommand, - ), + effect: normalizeOptionalEffect(statusEffect(429), isCommand), }), certainty: "RATE_LIMITED", retryHint: true, diff --git a/src/contracts/errors.ts b/src/contracts/errors.ts index 3fc3e571..86873b98 100644 --- a/src/contracts/errors.ts +++ b/src/contracts/errors.ts @@ -314,13 +314,21 @@ export function createFailure( userMessageKey: definition.userMessageKey, action: details.effect === "MAYBE_APPLIED" - ? "contact-support" + ? unknownEffectAction(definition.action) : details.effect === "APPLIED_CONFIRMED" ? "none" : definition.action, }); } +/** + * D-2. An unknown effect sends the user to support, except when the session + * itself is the problem: signing in again comes first either way. + */ +function unknownEffectAction(action: ErrorAction): ErrorAction { + return action === "reauth" ? "reauth" : "contact-support"; +} + /** * Adds controller-owned mutation effect knowledge without weakening the * fail-safe handling required for an unknown server-side outcome. @@ -333,7 +341,7 @@ export function withFailureEffect( ...failure, effect, ...(effect === "MAYBE_APPLIED" - ? { retryable: false as const, action: "contact-support" as const } + ? { retryable: false as const, action: unknownEffectAction(failure.action) } : effect === "APPLIED_CONFIRMED" ? { retryable: false as const, action: "none" as const } : {}), diff --git a/src/contracts/external-contract-runtime.ts b/src/contracts/external-contract-runtime.ts index 671eaa7b..ca930d11 100644 --- a/src/contracts/external-contract-runtime.ts +++ b/src/contracts/external-contract-runtime.ts @@ -123,6 +123,12 @@ export interface CommandEffectDescriptor { classifyProblem( input: Readonly<{ status: number; problem: Problem }>, ): CommandEffectClassification; + /** + * D-2. 401, 403 and 429 are admitted by status before any problem body is + * read. Declare `NOT_APPLIED` only when the server contract guarantees the + * command was rejected untouched. Without this, they stay `MAYBE_APPLIED`. + */ + classifyStatus?(status: 401 | 403 | 429): "NOT_APPLIED" | "MAYBE_APPLIED"; } export type HttpMethod = @@ -470,6 +476,12 @@ function assertHttpContract( if (typeof contract.commandEffect.classifyProblem !== "function") { fail(`${label}: command effect classifier is required`); } + if ( + contract.commandEffect.classifyStatus !== undefined && + typeof contract.commandEffect.classifyStatus !== "function" + ) { + fail(`${label}: command status classifier must be a function`); + } if (contract.retrySemantics === "KEYED" && !contract.commandRecovery) { fail(`${label}: KEYED commands require a recovery descriptor`); } diff --git a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts index 48985218..0f38d803 100644 --- a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts +++ b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts @@ -44,6 +44,11 @@ const CREATE_EFFECT: CommandEffectDescriptor = Object.freeze({ } return "MAYBE_APPLIED"; }, + /** + * D-2. The reference backend rejects an unauthenticated, forbidden or + * rate-limited create before touching state. + */ + classifyStatus: () => "NOT_APPLIED" as const, }); export const LIST_REFERENCE_RESOURCES_CONTRACT = Object.freeze({ diff --git a/tests/features/reference-feature/reference-production-vertical.test.tsx b/tests/features/reference-feature/reference-production-vertical.test.tsx index 47a35f7b..e1a14a16 100644 --- a/tests/features/reference-feature/reference-production-vertical.test.tsx +++ b/tests/features/reference-feature/reference-production-vertical.test.tsx @@ -165,4 +165,46 @@ describe("reference feature production vertical path", () => { expect(idempotencyKeys[0]).toMatch(/^[\x21-\x7e]+$/u); expect(idempotencyKeys[1]).toBe(idempotencyKeys[0]); }); + + it.each([ + // The demo session treats a server 401 as signed out; the route guard + // then asks for sign-in and the form is gone. + [401, "세션이 필요합니다."], + [403, "저장하지 못했습니다. 잠시 후 다시 시도해 주세요."], + [429, "저장하지 못했습니다. 잠시 후 다시 시도해 주세요."], + ])( + "treats a create rejected with %i as not applied, not unknown", + async (status, guidance) => { + const user = userEvent.setup(); + mockApi.server.use( + http.post( + "https://api.test/api/reference-resources", + () => new HttpResponse(null, { status }), + ), + ); + const composition = await createRuntimeComposition({ + fetcher: absoluteFetch, + host: {}, + }); + window.history.pushState({}, "", "/examples/reference-resources/new"); + render(); + + await user.click( + await screen.findByRole("button", { name: "로그인 시작" }), + ); + await user.type( + await screen.findByRole("textbox", { name: /새 항목 이름/ }), + "Rejected", + ); + await user.click(screen.getByRole("button", { name: "저장" })); + + expect(await screen.findByText(guidance)).toBeVisible(); + expect( + screen.queryByText("변경 결과를 확인할 수 없습니다."), + ).not.toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: "같은 요청으로 다시 보내기" }), + ).not.toBeInTheDocument(); + }, + ); }); diff --git a/tests/mocks/scenarios/catalog.ts b/tests/mocks/scenarios/catalog.ts index 3e8abaad..8ab7ba87 100644 --- a/tests/mocks/scenarios/catalog.ts +++ b/tests/mocks/scenarios/catalog.ts @@ -232,14 +232,14 @@ function expectationFor( case "unauthenticated-401": statuses = [401]; kind = "UNAUTHENTICATED"; - outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_APPLICABLE"; + outcomeEffect = command ? "NOT_APPLIED" : "NOT_APPLICABLE"; observer = "UNAUTHENTICATED"; bodies = [attemptBody("CANCELLED_WITHOUT_READ", 0, 0)]; break; case "forbidden-403": statuses = [403]; kind = "FORBIDDEN"; - outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_APPLICABLE"; + outcomeEffect = command ? "NOT_APPLIED" : "NOT_APPLICABLE"; observer = "FORBIDDEN"; bodies = [attemptBody("CANCELLED_WITHOUT_READ", 0, 0)]; break; @@ -289,7 +289,7 @@ function expectationFor( const attemptCount = command ? 1 : 3; statuses = Array.from({ length: attemptCount }, () => 429); kind = "RATE_LIMITED"; - outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_APPLICABLE"; + outcomeEffect = command ? "NOT_APPLIED" : "NOT_APPLICABLE"; observer = "RATE_LIMITED"; retryReasons = command ? [] : ["HTTP_429", "HTTP_429"]; media = Array.from({ length: attemptCount }, () => "application/json"); diff --git a/tests/unit/error-classification.test.ts b/tests/unit/error-classification.test.ts index e13c2661..90ad93f0 100644 --- a/tests/unit/error-classification.test.ts +++ b/tests/unit/error-classification.test.ts @@ -5,6 +5,7 @@ import { createFailure, kindForStatus, normalizeUnknownFailure, + withFailureEffect, } from "../../src/contracts/errors.ts"; import { DIAGNOSTIC_EVENT_REGISTRY } from "../../src/contracts/diagnostics.ts"; import { TELEMETRY_REGISTRY } from "../../src/contracts/telemetry.ts"; @@ -51,6 +52,19 @@ describe("frontend failure classification", () => { expect(kindForStatus(status)).toBe(kind); }); + it("keeps re-login first for an auth failure whose effect is unknown (D-2)", () => { + expect( + createFailure("AUTH_REQUIRED", "CREATE", 0, { effect: "MAYBE_APPLIED" }), + ).toMatchObject({ action: "reauth", retryable: false }); + expect( + withFailureEffect(createFailure("AUTH_REQUIRED", "CREATE", 0), "MAYBE_APPLIED"), + ).toMatchObject({ action: "reauth", retryable: false }); + // Every other kind still sends an unknown effect to support. + expect( + createFailure("FORBIDDEN", "CREATE", 0, { effect: "MAYBE_APPLIED" }), + ).toMatchObject({ action: "contact-support" }); + }); + it("projects only allowlisted safe fields", () => { const untrustedDetails = { code: "TEMPORARY", diff --git a/tests/unit/http-execution-v3.test.ts b/tests/unit/http-execution-v3.test.ts index 660e68c0..44ba0012 100644 --- a/tests/unit/http-execution-v3.test.ts +++ b/tests/unit/http-execution-v3.test.ts @@ -992,6 +992,75 @@ describe("terminal owner classification at every wait", () => { ); }); +/** + * D-2 (03-02). 401, 403 and 429 are admitted before any problem body is read. + * The package may classify them by status; without a classifier, or when it + * misbehaves, a dispatched command stays MAYBE_APPLIED. + */ +describe("command status classification", () => { + function withStatusClassifier( + classifyStatus: ((status: 401 | 403 | 429) => unknown) | undefined, + ): InstalledHttpContract { + return { + ...createInstalled, + contract: { + ...createInstalled.contract, + commandEffect: { + ...createInstalled.contract.commandEffect!, + ...(classifyStatus === undefined ? {} : { classifyStatus }), + } as NonNullable, + }, + }; + } + + async function effectFor( + status: number, + contract: InstalledHttpContract, + ) { + const executor = createContractHttpExecutor({ + baseUrl: "https://api.example/", + maxRetryAttempts: 0, + attachCredentials: () => ({ kind: "READY", headers: {} }), + fetcher: vi.fn(async () => new Response(null, { status })), + }); + const outcome = await executor.execute( + contract, + { name: "created" }, + { routeId: ROUTE_ID, scope, intent: mutationIntent() }, + ); + return { kind: outcome.kind, effect: outcome.effect }; + } + + it.each([ + [401, "UNAUTHENTICATED"], + [403, "FORBIDDEN"], + [429, "RATE_LIMITED"], + ] as const)("uses the package classifier for %i", async (status, kind) => { + const classifyStatus = vi.fn(() => "NOT_APPLIED"); + await expect( + effectFor(status, withStatusClassifier(classifyStatus)), + ).resolves.toEqual({ kind, effect: "NOT_APPLIED" }); + expect(classifyStatus).toHaveBeenCalledWith(status); + }); + + const throwingClassifier = (): unknown => { + throw new Error("package defect"); + }; + const unknownAnswer = (): unknown => "APPLIED_CONFIRMED"; + + it.each([ + ["no classifier", undefined], + ["a throwing classifier", throwingClassifier], + ["an unknown answer", unknownAnswer], + ] as const)("keeps MAYBE_APPLIED for %s", async (_label, classifyStatus) => { + for (const status of [401, 403, 429]) { + await expect( + effectFor(status, withStatusClassifier(classifyStatus)), + ).resolves.toMatchObject({ effect: "MAYBE_APPLIED" }); + } + }); +}); + /** * Q-6.3-7. A retried command's final effect joins what earlier attempts already * established, and an answer that says the command may already be applied is