feat(http): operation이 쓰기 전 업무 거절 code를 선언한다

문제
Envelope operation의 400·409·422는 백엔드 표의 세 code만 NOT_APPLIED이고
나머지는 모두 MAYBE_APPLIED다. 기능의 classifyProblem은 이를 바꿀 수 없다.
짝 백엔드 생성 기능의 create는 이름 규칙을 트랜잭션 전에 검사하고 400
<FEATURE>_INVALID를 준다. 그런데 폼은 "변경 결과를 확인할 수 없습니다"를
띄우고 저장 버튼을 끈다. 입력을 고쳐도 다시 저장할 수 없다(리뷰 실험
X-A·X-B). 401·403·429는 classifyStatus로 operation이 정할 수 있는데
400·409·422는 정할 자리가 없다.

고른 방법 (결정 D2 ①)
- CommandEffectDescriptor에 선택 칸 refusedBeforeWrite?: readonly string[].
  표 밖 400·409·422가 이 목록의 code면 NOT_APPLIED다. 함수가 아니라 code
  목록이라 리뷰할 수 있고, status 범위를 통째로 NOT_APPLIED로 만들 수 없다.
- 조립 검사(assertRefusedBeforeWrite): 목록은 Envelope operation에만,
  code는 백엔드 문법, 중복 금지. IDEMPOTENT_*·IDEMPOTENCY_*는 거절한다
  (409 IDEMPOTENT_IN_FLIGHT의 앞선 요청은 적용될 수 있다).
- 실행기도 같은 code와 표의 code(VALIDATION_FAILED 등)를 무시한다. 조립
  없이 실행기를 부르는 경로의 fail-close다.
- 조립이 목록을 얼려 복사한다(LIVE-03). classifier는 지금처럼 참조로
  두고, 설치본이 원본을 prototype으로 물려받아 classifier의 this가 그대로다.
- 매뉴얼 02 4절과 계약 문서 6.1절에 언제 적고 언제 적지 않는지,
  <FEATURE>_INVALID 예와 거부 문구를 적었다.

버린 대안
- 표 밖 400 전체를 NOT_APPLIED: BAD_PARAMETER·MAPPING_FAILED는 쓰기 뒤에도
  나온다.
- 분류기 판정 복원: 3261208이 버린 길. 400 전체를 NOT_APPLIED로 보는
  분류기가 키 보호를 푼다.
- 결과 불명 화면에 "적용되지 않음" 버튼: 사용자가 모르고 누르면 새 키로
  중복이 생긴다.
- 백엔드 단계 신호(error.applied): 두 repo 계약 변경이다(D2 ②).

위험·한계
- 쓰기 뒤에도 나오는 code를 잘못 적으면 결과 불명 요청이 새 키로 나가
  중복이 생길 수 있다. 책임은 선언한 기능 작성자에게 간다. 매뉴얼이 백엔드
  코드에서 던지는 곳을 확인한 code만 적으라고 한다.
- 생성기(scripts/create-feature.ts)는 이 칸을 아직 쓰지 않는다. 다른 작업이
  이어 받는다.
- 결과 불명 화면이 거절 code의 문구를 보이는 것(08-01 (가))은 하지 않았다.

검증
- RED: 새 테스트 17건이 이 변경 전 소스에서 실패(조립 규칙 10, 판정 3,
  envelope 통합 3, form-foundation 1).
- GREEN: tests/unit·integration·component·features·contract·runtime-schema
  253파일 3,199건 통과. 폼: WORKLOG_INVALID를 선언하면 결과 unavailable,
  저장 켜짐, 고친 값 저장 fetch 2회, 키 key-1 → key-2. 선언하지 않으면
  effect-unknown, 저장 꺼짐, fetch 1회.
- 변이: 실행기의 멱등성·표 code 무시 제거, 조립의 멱등성 규칙 제거, 목록
  복사 제거, 실행기가 목록을 넘기지 않음 모두 검출. 보존 조건 M5·M10·M24도
  계속 검출.
- check:types, lint, check:registries, check:architecture,
  verify:documentation 통과.

Refs: docs/reviews/2026-11-03-maturity-review/03-adapters-http-state.md 03-01
Refs: docs/reviews/2026-11-03-maturity-review/08-presentation.md 08-01
This commit is contained in:
DongHyeonka
2026-11-04 20:38:12 +09:00
parent 37615072e9
commit 1e8b3d049f
9 changed files with 481 additions and 17 deletions
+30 -9
View File
@@ -179,10 +179,30 @@ function mayHaveApplied(code: string, status: number): boolean {
}
/**
* The verdict the backend contract gives whatever the operation is, or
* `undefined` when the operation's own classifier decides.
* 1103/03-01. A code the operation declares as refused before its write
* (`commandEffect.refusedBeforeWrite`). Composition already refuses an
* idempotency code in that list; this is the runtime's own fail-close for an
* executor called without composition. The table's own codes keep its status
* rule.
*/
function declaredBeforeWrite(
code: string,
declared: readonly string[] | undefined,
): boolean {
return (
declared !== undefined &&
!Object.hasOwn(REFUSED_BEFORE_WRITE, code) &&
!/^IDEMPOTEN(?:T|CY)_/.test(code) &&
declared.includes(code)
);
}
/**
* The verdict the backend contract gives, or `undefined` when the
* operation's own classifier decides.
*
* - Not applied: a code in the refusal table above.
* - Not applied: a code in the refusal table above, or a 400, 409 or 422
* whose code the operation declared as refused before its write.
* - Maybe applied: every other 400, 409 and 422, including 409
* IDEMPOTENT_IN_FLIGHT (an earlier request with the key still runs); the
* backend can raise them after a write and the code does not say which.
@@ -191,14 +211,15 @@ function mayHaveApplied(code: string, status: number): boolean {
export function envelopeFailureEffect(
status: number,
error: EnvelopeError,
declaredRefusals?: readonly string[],
): "NOT_APPLIED" | "MAYBE_APPLIED" | undefined {
if (refusedBeforeWrite(error.code, status) !== undefined) return "NOT_APPLIED";
return status === 400 ||
status === 409 ||
status === 422 ||
mayHaveApplied(error.code, status)
? "MAYBE_APPLIED"
: undefined;
if (status === 400 || status === 409 || status === 422) {
return declaredBeforeWrite(error.code, declaredRefusals)
? "NOT_APPLIED"
: "MAYBE_APPLIED";
}
return mayHaveApplied(error.code, status) ? "MAYBE_APPLIED" : undefined;
}
/**
+8 -2
View File
@@ -1693,7 +1693,12 @@ async function admitProblem<Input, WireOutput, Problem>(
? invokeValidator(contract.problemValidator, framed.value)
: UNFRAMED_PROBLEM;
if (framed.ok) {
backendEffect = envelopeFailureEffect(status, framed.value);
// 1103/03-01. The operation's own pre-write refusals join the table.
backendEffect = envelopeFailureEffect(
status,
framed.value,
contract.commandEffect?.refusedBeforeWrite,
);
refusalReason = idempotencyRefusalReason(framed.value.code, status);
keyedResend =
isCommand &&
@@ -1720,7 +1725,8 @@ async function admitProblem<Input, WireOutput, Problem>(
}
// The backend's own verdict, when it has one, is the same for every
// operation. The package classifies the rest.
// operation, plus the codes the operation lists as refused before its
// write. The package classifies the rest.
const classification =
isCommand && backendEffect !== undefined
? Object.freeze({ effect: backendEffect, contractRuntimeFailure: false })
@@ -149,6 +149,17 @@ export interface CommandEffectDescriptor<Problem> {
* command was rejected untouched. Without this, they stay `MAYBE_APPLIED`.
*/
classifyStatus?(status: 401 | 403 | 429): "NOT_APPLIED" | "MAYBE_APPLIED";
/**
* 1103/03-01. `responseEnvelope: "ENVELOPE_V1"` only. The backend codes
* this endpoint raises only before it writes, such as the paired backend
* scaffold's `<FEATURE>_INVALID` (its create checks the name before the
* transaction). A 400, 409 or 422 outside the backend's own table that
* carries one of these codes is `NOT_APPLIED`, so the next save takes a new
* key. Every code not listed stays `MAYBE_APPLIED`. Idempotency codes
* (`IDEMPOTENT_*`, `IDEMPOTENCY_*`) are the backend table's to decide, and
* composition refuses them here. Composition installs a copy of the list.
*/
readonly refusedBeforeWrite?: readonly string[];
}
export type HttpMethod =
@@ -524,6 +535,7 @@ function assertHttpContract(
) {
fail(`${label}: command status classifier must be a function`);
}
assertRefusedBeforeWrite(contract, label);
if (contract.retrySemantics === "KEYED" && !contract.commandRecovery) {
fail(`${label}: KEYED commands require a recovery descriptor`);
}
@@ -570,6 +582,46 @@ function assertHttpContract(
}
}
/** The paired backend's `error.code` grammar (its docs/web/http-contract.md §1). */
const BACKEND_ERROR_CODE = /^[A-Z0-9_]{1,64}$/;
/**
* 1103/03-01. Codes no operation may declare as refused before the write:
* the backend's idempotency answers. Its own table decides them, including
* 409 IDEMPOTENT_IN_FLIGHT, whose earlier request may still apply.
*/
const IDEMPOTENCY_CODE = /^IDEMPOTEN(?:T|CY)_/;
function assertRefusedBeforeWrite(
contract: InstalledHttpContract<unknown, unknown, unknown>["contract"],
label: string,
): void {
const declared = contract.commandEffect?.refusedBeforeWrite;
if (declared === undefined) return;
if (!Array.isArray(declared)) {
fail(`${label}: refusedBeforeWrite must be a list of backend codes`);
}
// Without the Envelope the executor never reads a backend code, so the
// list would promise a verdict nothing applies.
if (contract.responseEnvelope !== "ENVELOPE_V1") {
fail(
`${label}: refusedBeforeWrite needs responseEnvelope ENVELOPE_V1; without it classifyProblem decides`,
);
}
const seen = new Set<string>();
for (const code of declared as readonly unknown[]) {
if (typeof code !== "string" || !BACKEND_ERROR_CODE.test(code)) {
fail(`${label}: refusedBeforeWrite code ${String(code)}`);
}
if (IDEMPOTENCY_CODE.test(code)) {
fail(
`${label}: refusedBeforeWrite cannot declare ${code}; the backend's idempotency answers are decided by its own table`,
);
}
if (seen.has(code)) fail(`${label}: refusedBeforeWrite repeats ${code}`);
seen.add(code);
}
}
function assertEventContract(
event: InstalledEventContract<unknown, unknown>,
featureId: string,
@@ -693,6 +745,7 @@ function snapshotHttpContract(
...source,
acceptedStatuses: statusArray(source.acceptedStatuses, reject),
emptyBodyStatuses: statusArray(source.emptyBodyStatuses, reject),
commandEffect: snapshotCommandEffect(source.commandEffect, reject),
commandRecovery:
source.commandRecovery === null
? null
@@ -706,6 +759,44 @@ function snapshotHttpContract(
return Object.freeze({ contract, frontend });
}
/**
* 1103/03-01. The classifiers stay by reference, like validators: behaviour
* the contribution owns. The refusal list is data that lifts the backend's
* table, so the installed effect carries its own frozen copy, read once. The
* copy inherits everything else from the source, so a classifier keeps the
* `this` it was written for, and a list added to the source later is shadowed.
*/
function snapshotCommandEffect(
effect: CommandEffectDescriptor<unknown> | null,
reject: (detail: string) => never,
): CommandEffectDescriptor<unknown> | null {
// Not an object: assertHttpContract names what is wrong.
if (effect === null || typeof effect !== "object") return effect;
let declared: unknown;
try {
const descriptor = Object.getOwnPropertyDescriptor(
effect,
"refusedBeforeWrite",
);
if (descriptor !== undefined && !("value" in descriptor)) {
return reject("refusedBeforeWrite must be a data property");
}
declared = descriptor?.value;
} catch {
return reject("refusedBeforeWrite unreadable");
}
const codes =
declared === undefined
? undefined
: (snapshotExactArray(declared, 64) ??
reject("refusedBeforeWrite must be a list of backend codes"));
return Object.freeze(
Object.create(effect, {
refusedBeforeWrite: { value: codes, enumerable: true },
}) as CommandEffectDescriptor<unknown>,
);
}
/**
* Q-6.7-6. Arrays are copied by index, never through their iterator, so an own
* `Symbol.iterator` cannot hand composition a different list than `length`