fix(http): let the package classify command 401/403/429 and keep re-login first (03-02)
These statuses skipped the package classifier and always became MAYBE_APPLIED, so an expired session ended in "contact support" or the unknown-result screen. The descriptor gains optional classifyStatus, the reference create declares NOT_APPLIED, and AUTH_REQUIRED keeps reauth. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
dfb1b9e0ee
commit
2afee67150
+3
@@ -635,6 +635,7 @@ export interface CommandEffectDescriptor<Problem> {
|
||||
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<Problem> {
|
||||
- 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
|
||||
|
||||
@@ -128,6 +128,28 @@ export function classifyProblemEffect<Problem>(
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<Problem>(
|
||||
descriptor: CommandEffectDescriptor<Problem> | 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,
|
||||
|
||||
@@ -36,6 +36,7 @@ import {
|
||||
import {
|
||||
certaintyForAbandonedAttempt,
|
||||
classifyProblemEffect,
|
||||
classifyStatusEffect,
|
||||
joinMutationEffectCertainty,
|
||||
type MutationEffectCertainty,
|
||||
type PhysicalAttemptState,
|
||||
@@ -1142,25 +1143,24 @@ async function admitResponse<Input, WireOutput, Problem>(
|
||||
}
|
||||
|
||||
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<Input, WireOutput, Problem>(
|
||||
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,
|
||||
|
||||
+10
-2
@@ -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 }
|
||||
: {}),
|
||||
|
||||
@@ -123,6 +123,12 @@ export interface CommandEffectDescriptor<Problem> {
|
||||
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`);
|
||||
}
|
||||
|
||||
@@ -44,6 +44,11 @@ const CREATE_EFFECT: CommandEffectDescriptor<ReferenceProblem> = 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({
|
||||
|
||||
@@ -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(<RuntimeApplication composition={composition} />);
|
||||
|
||||
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();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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<unknown, unknown, unknown> {
|
||||
return {
|
||||
...createInstalled,
|
||||
contract: {
|
||||
...createInstalled.contract,
|
||||
commandEffect: {
|
||||
...createInstalled.contract.commandEffect!,
|
||||
...(classifyStatus === undefined ? {} : { classifyStatus }),
|
||||
} as NonNullable<typeof createInstalled.contract.commandEffect>,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function effectFor(
|
||||
status: number,
|
||||
contract: InstalledHttpContract<unknown, unknown, unknown>,
|
||||
) {
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user