fix(http): V2 검증 거절을 적용 안 됨으로 보고 고친 값을 다시 저장하게 한다 (백엔드 1101/02-01)
문제
V2 클라이언트(client.ts)는 필드 검증 거절(422, 짝 백엔드의 400
VALIDATION_FAILED + 필드 목록)에 effect를 붙이지 않는다. mutation
코디네이터(application-query.ts mutationFailureWithEffect)는 effect가 없으면
MAYBE_APPLIED로 보고 admission을 UNKNOWN으로 붙든다. 폼은 VALIDATION_
REJECTED를 필드 오류로 보여 주지만, 참조 폼 페이지는 코디네이터가 결과 불명을
들고 있으면 저장 버튼을 끈다(reference-resource-form-page.tsx
mutationBlocked). 사용자가 필드를 고쳐도 다시 저장할 수 없다. use-app-form
자체는 VALIDATION_REJECTED에서 unknownSubmissionRef를 비우므로 막지 않는다.
막는 것은 코디네이터 상태다.
V3 참조 기능은 재현되지 않는다. 생성 분류기가 400·422를 NOT_APPLIED로
본다(reference-feature-contract-contribution.ts classifyProblem).
고른 방법
V2에서 필드 검증 거절(fieldValidation: 422, 또는 400 VALIDATION_FAILED +
배열 details)에 effect NOT_APPLIED를 붙인다. 멱등성 거절(IDEMPOTENCY_
REFUSALS)과 같은 자리에서 붙이고, 진단 reason은 멱등성 거절에만 남긴다.
근거(백엔드 계약)
- docs/web/http-contract.md 4절과 web adapter README 예외 표가 VALIDATION_
FAILED의 출처를 적는다: 요청 본문 바인딩(MethodArgumentNotValid
Exception), 컨트롤러 파라미터 제약(HandlerMethodValidationException),
Bean Validation(ConstraintViolationException), 페이지 파라미터, 읽을 수
없는 본문. 모두 요청을 묶는 단계에서 컨트롤러·use case보다 먼저 거절한다.
- 4절에 "상태를 바꾸지 않는다"는 문장은 없다. 이 판정은 위 출처에서
끌어낸 것이다.
버린 대안
- 코디네이터가 effect 없는 VALIDATION_REJECTED를 모두 NOT_APPLIED로 보기:
거절을 판정하는 곳은 응답을 읽는 클라이언트다. 코디네이터의 "모르면
MAYBE_APPLIED" 규칙은 그대로 둔다.
- 폼 페이지가 VALIDATION_REJECTED 뒤 결과 불명을 무시하기: 키가 붙은 채
남아 같은 입력을 다시 저장하면 같은 키가 나간다.
위험·한계
- application 층에서 쓰기 뒤에 VALIDATION_FAILED를 던지는 백엔드 코드가
있다면 이 판정은 틀린다. 짝 백엔드 IdempotencyExecutor는 실행 중 예외를
EFFECT_UNKNOWN_ABANDONED로 기록한다. 이 경우 같은 키 재전송은 500
IDEMPOTENCY_RECOVERY_REQUIRED를 받는다. NOT_APPLIED면 다음 저장이 새 키를
쓰므로 그 경로를 타지 않는다.
- 필드 목록 없는 400 VALIDATION_FAILED({cause}, 본문 파싱 실패)와 그 밖의
400·409는 effect 없이 둔다(결과 불명으로 붙듦). 이번 범위 밖이다.
- 422 IDEMPOTENT_REQUEST_MISMATCH는 원래 NOT_APPLIED였고 그대로다.
검증
- RED: tests/component/form-foundation.test.tsx "saves the corrected value
after a $status field error" 2행(422, 400 VALIDATION_FAILED) 실패. 필드
오류 뒤 저장 버튼이 disabled다.
- V3: tests/features/reference-feature/reference-production-vertical.test.tsx
"saves the corrected value after a server 422 field error"는 수정 전에도
통과한다(재현 안 됨, 동작 고정).
- GREEN: 위 행 통과. tests/integration/http-diagnostics.test.ts의 "unrelated
422" 행은 effect가 없다고 기대하던 것을 NOT_APPLIED로 바꾸고, 409 행을
더해 다른 거절은 effect가 없음을 고정했다. tests/integration/http-client.
test.ts에 400 VALIDATION_FAILED effect 단언을 더했다.
tests/unit·contract·runtime-schema·integration·component·features·platform
3398 tests 통과, 1개 실패(tests/unit/second-api-feature-registries.test.ts,
기준 3b7d73a에서도 같은 메시지로 실패). tsc app·test, 바꾼 파일 eslint
통과.
Refs: clean-architecture-backend-template docs/web/http-contract.md 4절, src/adapter/inbound/web/README.md 예외 표
This commit is contained in:
@@ -1013,6 +1013,9 @@ async function parseResponse(
|
||||
// the same failure as a 422, so it gets the same kind and issues and a form
|
||||
// maps it with the same allowed fields. A 400 VALIDATION_FAILED whose body
|
||||
// did not parse carries `{cause}`, not a list, and keeps its reading.
|
||||
// Field validation is checked when the request is bound, before the
|
||||
// command runs, so it is NOT_APPLIED: the coordinator must not hold it as an
|
||||
// unknown effect, or the form cannot save the corrected value.
|
||||
const fieldValidation =
|
||||
response.status === 422 ||
|
||||
(response.status === 400 &&
|
||||
@@ -1027,9 +1030,12 @@ async function parseResponse(
|
||||
ok: false,
|
||||
error: failure(kind, operation.operationId, attempt, {
|
||||
code,
|
||||
...(idempotencyRefusalReason(code, response.status) === undefined
|
||||
? {}
|
||||
: { effect: "NOT_APPLIED" as const }),
|
||||
// A refusal the server made before running the command: not applied,
|
||||
// so the mutation coordinator does not hold it as an unknown effect.
|
||||
...(fieldValidation ||
|
||||
idempotencyRefusalReason(code, response.status) !== undefined
|
||||
? { effect: "NOT_APPLIED" as const }
|
||||
: {}),
|
||||
httpStatus: response.status,
|
||||
requestId: safeMeta(envelopeRecord.meta).requestId,
|
||||
traceId: safeMeta(envelopeRecord.meta).traceId,
|
||||
|
||||
@@ -9,7 +9,10 @@ import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createHttpClient } from "../../src/adapters/http/client.ts";
|
||||
import { createFailure } from "../../src/contracts/errors.ts";
|
||||
import { createRuntimeIdentityRegistry } from "../../src/contracts/query-keys.ts";
|
||||
import { useApplicationMutation } from "../../src/presentation/adapters/query/application-query.ts";
|
||||
import { TEST_HTTP_CONTRACT } from "../helpers/http-contract-fixture.ts";
|
||||
import { queryClient, scopeSnapshot, wrapper } from "./application-query-fixture.tsx";
|
||||
import { Button } from "../../src/presentation/components/ui/button.ts";
|
||||
import {
|
||||
DirtyNavigationDialog,
|
||||
@@ -578,3 +581,112 @@ describe("submission timing", () => {
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* A server validation refusal through the V2 client and the mutation
|
||||
* coordinator, with the reference form page's gate: the save button is off
|
||||
* while the coordinator holds an unknown effect.
|
||||
*/
|
||||
describe("correcting a field after a V2 validation refusal", () => {
|
||||
let token = 0;
|
||||
const scope = {
|
||||
...scopeSnapshot(),
|
||||
identities: createRuntimeIdentityRegistry({
|
||||
tokenFactory: () => `form-identity-token-${String(++token).padStart(4, "0")}`,
|
||||
}),
|
||||
};
|
||||
|
||||
function CoordinatedForm(props: Readonly<{ fetcher: typeof fetch }>) {
|
||||
const [client] = useState(() =>
|
||||
createHttpClient({
|
||||
...TEST_HTTP_CONTRACT,
|
||||
baseUrl: "https://api.test",
|
||||
fetcher: props.fetcher,
|
||||
}),
|
||||
);
|
||||
const mutation = useApplicationMutation<
|
||||
Readonly<{ name: string; note?: string }>,
|
||||
unknown
|
||||
>({
|
||||
definitionId: "v2-create-v1",
|
||||
definitionVersion: 1,
|
||||
operationId: "CREATE_ENTITY",
|
||||
requiresIdempotencyKey: true,
|
||||
owner: "platform-test",
|
||||
duplicatePolicy: "REJECT_WHILE_ACTIVE",
|
||||
scope,
|
||||
invalidate: [],
|
||||
execute: (command, { intent }) =>
|
||||
client.execute("CREATE_ENTITY", {
|
||||
body: { name: command.name },
|
||||
idempotencyKey: intent.idempotencyKey,
|
||||
}),
|
||||
});
|
||||
const form = useAppForm({
|
||||
schema,
|
||||
defaultValues: defaults,
|
||||
allowedServerFields: ["name", "note"],
|
||||
mapToCommand: (values) => ({ name: values.name }),
|
||||
submit: mutation.submit,
|
||||
});
|
||||
const blocked =
|
||||
mutation.state.indicator === "mutation-effect-unknown" ||
|
||||
mutation.state.indicator === "mutation-pending";
|
||||
return (
|
||||
<Form pending={form.pending} onSubmit={(event) => void form.submitForm(event)}>
|
||||
<FormField {...form.field("name")} label="Name" required />
|
||||
<Button type="submit" disabled={form.pending || blocked}>
|
||||
Submit
|
||||
</Button>
|
||||
<output data-testid="result">{form.result}</output>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
const meta = { requestId: "request-1", traceId: "trace-1" };
|
||||
|
||||
// 백엔드 1101/02-01 후속. A 422 in the frontend contract's shape, and the
|
||||
// paired backend's 400 VALIDATION_FAILED (its docs/web/http-contract.md §4).
|
||||
it.each([
|
||||
{ status: 422, error: { code: "INVALID_INPUT", details: { issues: [{ path: "name", code: "REQUIRED" }] } } },
|
||||
{
|
||||
status: 400,
|
||||
error: {
|
||||
code: "VALIDATION_FAILED",
|
||||
details: [{ field: "name", code: "NOT_BLANK", message: "필수 값이 없습니다." }],
|
||||
},
|
||||
},
|
||||
])("saves the corrected value after a $status field error", async ({ status, error }) => {
|
||||
const user = userEvent.setup();
|
||||
const fetcher = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(
|
||||
Response.json({ success: false, error, meta }, { status }),
|
||||
)
|
||||
.mockImplementation(async () =>
|
||||
Response.json({
|
||||
success: true,
|
||||
data: { id: "entity-1", name: "Fixed" },
|
||||
meta,
|
||||
}),
|
||||
);
|
||||
render(<CoordinatedForm fetcher={fetcher} />, {
|
||||
wrapper: wrapper(queryClient()),
|
||||
});
|
||||
const name = screen.getByRole("textbox", { name: /Name/ });
|
||||
|
||||
await user.type(name, "Rejected");
|
||||
await user.click(screen.getByRole("button", { name: "Submit" }));
|
||||
await waitFor(() => expect(name).toHaveAttribute("aria-invalid", "true"));
|
||||
|
||||
await user.clear(name);
|
||||
await user.type(name, "Fixed");
|
||||
expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled();
|
||||
await user.click(screen.getByRole("button", { name: "Submit" }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId("result")).toHaveTextContent("success"),
|
||||
);
|
||||
expect(fetcher).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -388,4 +388,55 @@ describe("reference feature production vertical path", () => {
|
||||
expect(name).toHaveAttribute("aria-invalid", "true");
|
||||
expect(document.body).not.toHaveTextContent("backend copy");
|
||||
});
|
||||
|
||||
// A validation refusal is not an unknown effect: the corrected value can
|
||||
// be saved (the create classifier answers 422 NOT_APPLIED).
|
||||
it("saves the corrected value after a server 422 field error", async () => {
|
||||
const user = userEvent.setup();
|
||||
let sent = 0;
|
||||
mockApi.server.use(
|
||||
http.post("https://api.test/api/reference-resources", async ({ request }) => {
|
||||
sent += 1;
|
||||
if (sent === 1) {
|
||||
return HttpResponse.json(
|
||||
{
|
||||
type: "https://api.test/problems/validation_rejected",
|
||||
title: "VALIDATION_REJECTED",
|
||||
status: 422,
|
||||
code: "VALIDATION_REJECTED",
|
||||
issues: [{ path: "name", code: "too_big" }],
|
||||
},
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
const body = (await request.json()) as { name: string };
|
||||
return HttpResponse.json(
|
||||
{ id: "reference-created-1", name: body.name },
|
||||
{ status: 201 },
|
||||
);
|
||||
}),
|
||||
);
|
||||
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: "로그인 시작" }),
|
||||
);
|
||||
const name = await screen.findByRole("textbox", { name: /새 항목 이름/ });
|
||||
await user.type(name, "Too long for the server");
|
||||
await user.click(screen.getByRole("button", { name: "저장" }));
|
||||
await waitFor(() => expect(name).toHaveAttribute("aria-invalid", "true"));
|
||||
|
||||
await user.clear(name);
|
||||
await user.type(name, "Short");
|
||||
expect(screen.getByRole("button", { name: "저장" })).toBeEnabled();
|
||||
await user.click(screen.getByRole("button", { name: "저장" }));
|
||||
|
||||
expect(await screen.findByText("저장했습니다.")).toBeVisible();
|
||||
expect(sent).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -663,6 +663,7 @@ describe("paired backend 400 VALIDATION_FAILED", () => {
|
||||
code: "VALIDATION_FAILED",
|
||||
httpStatus: 400,
|
||||
retryable: false,
|
||||
effect: "NOT_APPLIED",
|
||||
validationIssues: [
|
||||
{ path: "name", code: "NOT_BLANK" },
|
||||
{ path: "items.name", code: "SIZE" },
|
||||
@@ -686,5 +687,6 @@ describe("paired backend 400 VALIDATION_FAILED", () => {
|
||||
error: { kind: "UNKNOWN_CLIENT_FAILURE", code, httpStatus: 400 },
|
||||
});
|
||||
expect(result.ok ? null : result.error.validationIssues).toBeUndefined();
|
||||
expect(result.ok ? null : result.error.effect).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -255,15 +255,20 @@ describe("HTTP diagnostics and terminal telemetry", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps an unrelated 422 effect-free and reason-free", async () => {
|
||||
it.each([
|
||||
// A field validation refusal is not applied, but names no idempotency cause.
|
||||
{ status: 422, code: "INVALID_INPUT", effect: "NOT_APPLIED" },
|
||||
// Any other refusal keeps no effect: the coordinator holds it as unknown.
|
||||
{ status: 409, code: "SOMETHING_NEW", effect: undefined },
|
||||
])("gives an unrelated $status $code no reason", async ({ status, code, effect }) => {
|
||||
const fetcher = vi.fn(async () =>
|
||||
Response.json(
|
||||
{
|
||||
success: false,
|
||||
error: { code: "INVALID_INPUT" },
|
||||
error: { code },
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
},
|
||||
{ status: 422 },
|
||||
{ status },
|
||||
),
|
||||
);
|
||||
const { client, records } = harness(fetcher);
|
||||
@@ -274,7 +279,7 @@ describe("HTTP diagnostics and terminal telemetry", () => {
|
||||
body: { name: "n" },
|
||||
});
|
||||
|
||||
expect(result.ok ? undefined : result.error.effect).toBeUndefined();
|
||||
expect(result.ok ? undefined : result.error.effect).toBe(effect);
|
||||
expect(records[0]?.context).not.toHaveProperty("reason");
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user