diff --git a/docs/architecture/backend-api-and-server-state-contract.md b/docs/architecture/backend-api-and-server-state-contract.md index f018a7cb..4fabc602 100644 --- a/docs/architecture/backend-api-and-server-state-contract.md +++ b/docs/architecture/backend-api-and-server-state-contract.md @@ -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를 제공한다. diff --git a/src/adapters/http/backend-envelope.ts b/src/adapters/http/backend-envelope.ts index 0325f446..894bfaba 100644 --- a/src/adapters/http/backend-envelope.ts +++ b/src/adapters/http/backend-envelope.ts @@ -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 = const ENVELOPE_INVALID: EnvelopeRead = Object.freeze({ ok: false }); -/** The success `data`. A missing key is the null the backend dropped. */ -export function readSuccessEnvelope(value: unknown): EnvelopeRead { +/** + * 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. */ diff --git a/src/adapters/http/feature-http-binding.ts b/src/adapters/http/feature-http-binding.ts index 2643cafb..162c222b 100644 --- a/src/adapters/http/feature-http-binding.ts +++ b/src/adapters/http/feature-http-binding.ts @@ -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, + context: FeatureHttpSuccessContext, ): BoundaryMappingResult; mapProblem?( problem: HttpContractProblem, @@ -280,7 +297,10 @@ export function createFeatureHttpBinding< }); return projectExecutionOutcome( operation.operationId, - operation.mapSuccess as (value: WireOutput) => BoundaryMappingResult, + operation.mapSuccess as ( + value: WireOutput, + context: FeatureHttpSuccessContext, + ) => BoundaryMappingResult, problemMapper( operation.mapProblem as | (( @@ -340,7 +360,10 @@ function envelopeProblemMapping( */ function projectExecutionOutcome( operationId: string, - mapSuccess: (value: WireOutput) => BoundaryMappingResult, + mapSuccess: ( + value: WireOutput, + context: FeatureHttpSuccessContext, + ) => BoundaryMappingResult, mapProblem: | (( problem: Problem, @@ -364,7 +387,10 @@ function projectExecutionOutcome( function projectOutcome( operationId: string, - mapSuccess: (value: WireOutput) => BoundaryMappingResult, + mapSuccess: ( + value: WireOutput, + context: FeatureHttpSuccessContext, + ) => BoundaryMappingResult, mapProblem: | (( problem: Problem, @@ -389,7 +415,12 @@ function projectOutcome( case "SUCCESS": { let mapped: BoundaryMappingResult; 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); } diff --git a/src/adapters/http/http-execution-v3.ts b/src/adapters/http/http-execution-v3.ts index 3f2d06cc..89eccf06 100644 --- a/src/adapters/http/http-execution-v3.ts +++ b/src/adapters/http/http-execution-v3.ts @@ -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: 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( // 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( ); } wireValue = framed.value; + page = framed.page; } const validated = invokeValidator(contract.outputValidator, wireValue); @@ -1488,6 +1496,7 @@ async function admitResponse( effect: (isCommand ? "APPLIED_CONFIRMED" : "NOT_APPLICABLE") as "NOT_APPLICABLE" | "APPLIED_CONFIRMED", + ...(page === undefined ? {} : { page }), }), isCommand ? "APPLIED_CONFIRMED" : "NOT_APPLICABLE", ); diff --git a/src/adapters/http/index.ts b/src/adapters/http/index.ts index c1af125a..d2036449 100644 --- a/src/adapters/http/index.ts +++ b/src/adapters/http/index.ts @@ -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"; diff --git a/tests/integration/http-execution-v3-envelope.test.ts b/tests/integration/http-execution-v3-envelope.test.ts index 48bb1b70..d921c2b6 100644 --- a/tests/integration/http-execution-v3-envelope.test.ts +++ b/tests/integration/http-execution-v3-envelope.test.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(