feat(http): Envelope 목록의 meta.page를 mapSuccess에 넘긴다

문제
짝 백엔드는 페이지 목록의 전체 수·페이지 번호를 meta.page(number·size·
total·sort)에 싣는다(http-contract.md §1). 프론트 Envelope 읽기는 meta에서
id 셋만 남기고 data만 꺼낸다. 그래서 목록 기능은 첫 페이지(기본 20개)만 받고
전체 수를 모른다. 생성된 목록 화면의 "총 N개 항목"은 배열 길이라 페이지
크기를 전체 수처럼 보인다(리뷰 실험 X-G). 우회하려면 responseEnvelope를 빼야
하고, 그러면 Envelope 실패 판정을 함께 잃는다.

고른 방법
- backend-envelope.ts: meta에 page 스키마(정수, number·total 0 이상,
  size 1~100, sort 문자열 또는 null). 범위 밖이면 page만 버리고 응답은 읽는다.
  readSuccessEnvelope가 data와 함께 page를 돌려준다.
- 실행기의 SUCCESS 결과에 선택 칸 page. outputValidator는 지금처럼 data만
  본다.
- 바인딩: mapSuccess(value, context)의 두 번째 인자 FeatureHttpSuccessContext
  { page? }. 한 인자짜리 기존 mapSuccess는 그대로 맞는다.
- 배럴에서 EnvelopePage·FeatureHttpSuccessContext 타입을 낸다.
- 계약 문서 4.1절에 meta.page 경로와 "bulk results는 지원하지 않는다", 7절에
  "짝 백엔드는 offset meta.page"를 적었다.

버린 대안
- outputValidator에 { data, page }를 넘기기: 기존 기능 스키마가 모두 깨진다.
- 기능 스키마가 Envelope 전체를 읽기: 실패 판정을 잃는다.
- page가 범위 밖이면 응답 전체를 거절: meta의 모르는 키는 무시한다는 백엔드
  §1 규칙과 어긋난다.

위험·한계
- 생성기(create-feature.ts)의 목록 화면은 아직 배열 길이를 보인다. 생성기
  담당 작업이 page.total을 쓰도록 이어 받는다.
- bulk는 지원하지 않고 문서로만 알린다.

검증
- RED: envelope 통합 3건 실패(mapSuccess가 page를 받지 못함, 정렬 없는
  page 2건).
- GREEN: 같은 파일 51건 통과. 범위 밖 page 3건(size 500, number -1, total
  1.5)은 page 없이 SUCCESS. tests/unit·integration·component·features·
  contract·runtime-schema 253파일 3,209건 통과.
- check:types, lint, check:architecture, verify:documentation 통과.

Refs: docs/reviews/2026-11-03-maturity-review/03-adapters-http-state.md 03-02
This commit is contained in:
DongHyeonka
2026-11-04 20:46:38 +09:00
parent 2017ef76ff
commit 49a09868ad
6 changed files with 174 additions and 11 deletions
@@ -173,6 +173,14 @@ Envelope의 모양과 키 존재 규칙은 짝 백엔드 템플릿 문서가 정
`create:feature`가 만든 기능은 이 값을 선언한다. 참조 기능은 선언하지 않고
DTO와 problem details를 검증한다.
- 실패 Envelope의 `error.code`가 "적용 안 됨"인지는 6.1절이 정한다.
- 페이지 목록의 `meta.page`(`number`·`size`·`total`·`sort`)는 기능의
`mapSuccess(value, { page })` 두 번째 인자로 간다(`FeatureHttpSuccessContext`).
`outputValidator`는 지금처럼 `data`만 본다. 백엔드 범위(정수, `size` 1~100) 밖의
`page`는 버리고 응답은 그대로 읽는다. 목록 화면의 전체 수는 `page.total`이다.
배열 길이는 첫 페이지 크기(기본 20)일 뿐이다.
- bulk 응답(`results`, `BATCH_PARTIAL_FAILURE`)은 지원하지 않는다. 성공 status의
`results` Envelope는 `ENVELOPE_MISMATCH`다. bulk 엔드포인트를 붙이려면
`responseEnvelope`를 빼고 기능 스키마가 본문 전체를 읽는다.
### 4.2 Status와 error
@@ -339,6 +347,11 @@ application bean에 `@Validated`를 달거나 JPA entity에 Bean Validation 제
## 7. Cursor pagination과 snapshot
짝 백엔드 템플릿의 페이지 목록은 이 절의 cursor가 아니라 offset이다(`PageParams`,
`meta.page`, 4.1절). 프론트는 그 `meta.page`를 읽어 기능에 넘길 뿐이고, 아래
`CursorPage` 계약은 cursor를 고른 백엔드를 위한 것이다. 백엔드가 cursor로 바꾸면
이 절로 합친다.
Backend가 pagination을 선택할 때 새 response schema/operation version으로 다음
contract를 제공한다.
+49 -6
View File
@@ -12,16 +12,41 @@ import { z } from "../../contracts/zod.ts";
* for a V3 operation that declares `responseEnvelope: "ENVELOPE_V1"`.
*/
/**
* 1103/03-02. A page list's `meta.page` (§1): the 0-based page `number`, the
* `size` the backend applied (it caps it at 1..100), the `total` across all
* pages, and the applied `sort` in Spring form (`field,direction`), null or
* absent when unsorted.
*/
const pageSchema = z
.object({
number: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
size: z.number().int().min(1).max(100),
total: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
sort: z.string().min(1).max(256).nullable().optional(),
})
.strip();
export type EnvelopePage = Readonly<{
number: number;
size: number;
total: number;
sort?: string;
}>;
/**
* 백엔드 1101/02-02. The paired backend drops a null field together with its
* key (§1). The id keys are absent on an answer written before its request id
* filter, so they are optional here too.
* filter, so they are optional here too. A `page` outside the backend's own
* bounds is dropped rather than failing the answer, like any `meta` key this
* client does not read.
*/
const metaSchema = z
.object({
requestId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(),
traceId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(),
correlationId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(),
page: pageSchema.optional().catch(undefined),
})
.strip();
@@ -64,12 +89,30 @@ export type EnvelopeRead<Value> =
const ENVELOPE_INVALID: EnvelopeRead<never> = Object.freeze({ ok: false });
/** The success `data`. A missing key is the null the backend dropped. */
export function readSuccessEnvelope(value: unknown): EnvelopeRead<unknown> {
/**
* The success `data`. A missing key is the null the backend dropped.
* 1103/03-02. A page list's `meta.page` comes with it.
*/
export function readSuccessEnvelope(
value: unknown,
): Readonly<{ ok: true; value: unknown; page?: EnvelopePage }> | Readonly<{ ok: false }> {
const parsed = successEnvelopeSchema.safeParse(value);
return parsed.success
? Object.freeze({ ok: true as const, value: parsed.data.data })
: ENVELOPE_INVALID;
if (!parsed.success) return ENVELOPE_INVALID;
const page = parsed.data.meta.page;
return Object.freeze({
ok: true as const,
value: parsed.data.data,
...(page === undefined
? {}
: {
page: Object.freeze({
number: page.number,
size: page.size,
total: page.total,
...(typeof page.sort === "string" ? { sort: page.sort } : {}),
}),
}),
});
}
/** The failure `error` object, as the backend sent it. */
+36 -5
View File
@@ -13,7 +13,10 @@ import {
} from "../../contracts/errors.ts";
import type { MutationIntent } from "../../contracts/mutation-intent.ts";
import type { ExecutionContext } from "../../platform/execution/execution-context.ts";
import { envelopeFailureReading } from "./backend-envelope.ts";
import {
envelopeFailureReading,
type EnvelopePage,
} from "./backend-envelope.ts";
import type {
HttpContractViolation,
HttpExecutionOutcome,
@@ -84,6 +87,19 @@ export type FeatureHttpProblemMapping = Readonly<{
validationIssues?: readonly ValidationIssue[];
}>;
/**
* 1103/03-02. What a success answer carries besides its validated value.
*/
export type FeatureHttpSuccessContext = Readonly<{
/**
* An Envelope page list's `meta.page` (the paired backend's offset page:
* `number`, `size`, `total`, `sort`). Absent on every other answer.
*/
page?: EnvelopePage;
}>;
const NO_SUCCESS_CONTEXT: FeatureHttpSuccessContext = Object.freeze({});
type FeatureHttpOperationSpec<
Contract,
Value,
@@ -93,6 +109,7 @@ type FeatureHttpOperationSpec<
routeId: RouteId;
mapSuccess(
value: HttpContractWireOutput<Contract>,
context: FeatureHttpSuccessContext,
): BoundaryMappingResult<Value>;
mapProblem?(
problem: HttpContractProblem<Contract>,
@@ -280,7 +297,10 @@ export function createFeatureHttpBinding<
});
return projectExecutionOutcome(
operation.operationId,
operation.mapSuccess as (value: WireOutput) => BoundaryMappingResult<Value>,
operation.mapSuccess as (
value: WireOutput,
context: FeatureHttpSuccessContext,
) => BoundaryMappingResult<Value>,
problemMapper(
operation.mapProblem as
| ((
@@ -340,7 +360,10 @@ function envelopeProblemMapping(
*/
function projectExecutionOutcome<WireOutput, Problem, Value>(
operationId: string,
mapSuccess: (value: WireOutput) => BoundaryMappingResult<Value>,
mapSuccess: (
value: WireOutput,
context: FeatureHttpSuccessContext,
) => BoundaryMappingResult<Value>,
mapProblem:
| ((
problem: Problem,
@@ -364,7 +387,10 @@ function projectExecutionOutcome<WireOutput, Problem, Value>(
function projectOutcome<WireOutput, Problem, Value>(
operationId: string,
mapSuccess: (value: WireOutput) => BoundaryMappingResult<Value>,
mapSuccess: (
value: WireOutput,
context: FeatureHttpSuccessContext,
) => BoundaryMappingResult<Value>,
mapProblem:
| ((
problem: Problem,
@@ -389,7 +415,12 @@ function projectOutcome<WireOutput, Problem, Value>(
case "SUCCESS": {
let mapped: BoundaryMappingResult<Value>;
try {
mapped = mapSuccess(outcome.value);
mapped = mapSuccess(
outcome.value,
outcome.page === undefined
? NO_SUCCESS_CONTEXT
: Object.freeze({ page: outcome.page }),
);
} catch {
return mapperThrew(outcome.effect, outcome.metadata.status);
}
+9
View File
@@ -51,6 +51,7 @@ import {
invitesKeyedResend,
readFailureEnvelope,
readSuccessEnvelope,
type EnvelopePage,
type IdempotencyRefusalReason,
} from "./backend-envelope.ts";
import {
@@ -160,6 +161,11 @@ export type HttpExecutionOutcome<Value, Problem> = (
value: Value;
metadata: SafeResponseMetadata;
effect: "NOT_APPLICABLE" | "APPLIED_CONFIRMED";
/**
* 1103/03-02. An Envelope page list's `meta.page`, when it is within
* the backend's bounds. The validated value stays `data` alone.
*/
page?: EnvelopePage;
}>
| Readonly<{
kind: "PROBLEM";
@@ -1435,6 +1441,7 @@ async function admitResponse<Input, WireOutput, Problem>(
// 1101 README 14.3. The frame is checked after the byte and structure
// bounds, which count the whole Envelope.
let wireValue = decoded.value;
let page: EnvelopePage | undefined;
if (contract.responseEnvelope === "ENVELOPE_V1") {
const framed = readSuccessEnvelope(decoded.value);
if (!framed.ok) {
@@ -1448,6 +1455,7 @@ async function admitResponse<Input, WireOutput, Problem>(
);
}
wireValue = framed.value;
page = framed.page;
}
const validated = invokeValidator(contract.outputValidator, wireValue);
@@ -1488,6 +1496,7 @@ async function admitResponse<Input, WireOutput, Problem>(
effect: (isCommand
? "APPLIED_CONFIRMED"
: "NOT_APPLICABLE") as "NOT_APPLICABLE" | "APPLIED_CONFIRMED",
...(page === undefined ? {} : { page }),
}),
isCommand ? "APPLIED_CONFIRMED" : "NOT_APPLICABLE",
);
+3
View File
@@ -29,11 +29,14 @@ export {
type FeatureHttpBinding,
type FeatureHttpOperation,
type FeatureHttpProblemMapping,
type FeatureHttpSuccessContext,
type HttpContractInput,
type HttpContractOperationId,
type HttpContractProblem,
type HttpContractWireOutput,
type InstalledHttpOperationExecutor,
} from "./feature-http-binding.ts";
/** 1103/03-02. 짝 백엔드 페이지 목록의 `meta.page` (`FeatureHttpSuccessContext.page`). */
export type { EnvelopePage } from "./backend-envelope.ts";
/** V3 `attachCredentials` 콜백이 반환해야 하는 결과 타입. */
export type { CredentialPatchOutcome } from "./http-contract-bridge.ts";
@@ -338,6 +338,70 @@ describe("V3 operation that reads the paired backend's Envelope", () => {
});
});
// 1103/03-02. The paired backend's page list carries the total and the
// page under meta.page (http-contract.md §1); the binding hands it to
// mapSuccess next to the data.
it("hands the backend's meta.page to mapSuccess", async () => {
answer(
"get",
"/api/envelope-items",
success([{ id: "item-1", name: "First" }], {
...META,
page: { number: 2, size: 20, total: 137, sort: "createdAt,desc" },
}),
);
const seen: unknown[] = [];
const binding = createFeatureHttpBinding(
v3Executor(),
Object.freeze({
ENVELOPE_LIST_ITEMS: defineFeatureHttpOperation({
contract: LIST_CONTRACT,
routeId: "ENVELOPE_ROUTE",
mapSuccess: (value, context) => {
seen.push(context);
return mappingSuccess({ items: value, total: context.page?.total });
},
}),
}),
);
await expect(
binding.execute("ENVELOPE_LIST_ITEMS", Object.freeze({})),
).resolves.toEqual({
ok: true,
value: { items: [{ id: "item-1", name: "First" }], total: 137 },
});
expect(seen).toEqual([
{ page: { number: 2, size: 20, total: 137, sort: "createdAt,desc" } },
]);
});
it.each([
["an unsorted page", { number: 0, size: 20, total: 0, sort: null }, { number: 0, size: 20, total: 0 }],
["a page without sort", { number: 0, size: 100, total: 3 }, { number: 0, size: 100, total: 3 }],
["a size over the backend cap", { number: 0, size: 500, total: 3 }, undefined],
["a negative page number", { number: -1, size: 20, total: 3 }, undefined],
["a fractional total", { number: 0, size: 20, total: 1.5 }, undefined],
] as const)("reads %s", async (_label, page, expected) => {
const fetcher = (async () =>
Response.json(success([], { ...META, page }))) as typeof fetch;
const executor = createContractHttpExecutor({
baseUrl: BASE_URL,
fetcher,
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
});
const outcome = await executor.execute(LIST_CONTRACT, Object.freeze({}), {
routeId: "ENVELOPE_ROUTE",
scope: scope(),
});
// A page the backend could not have sent is dropped, not the answer.
expect(outcome).toMatchObject({ kind: "SUCCESS", value: [] });
expect(outcome.kind === "SUCCESS" ? outcome.page : "not a success").toEqual(expected);
});
it("reads keys the backend dropped as null: a DTO field, the meta ids and the data", async () => {
answer("get", "/api/envelope-items", success([{ id: "item-1", name: "First" }], {}));
await expect(