diff --git a/src/contracts/external-contract-runtime.ts b/src/contracts/external-contract-runtime.ts index 96131dd9..0da310d6 100644 --- a/src/contracts/external-contract-runtime.ts +++ b/src/contracts/external-contract-runtime.ts @@ -58,9 +58,42 @@ export type RuntimeValidationResult = export interface RuntimeValidator { readonly schemaId: string; + /** + * 1101/07-03. Absent on a validator that checks its input. `"NONE"` marks + * one made by `unvalidatedPayload`, which accepts any value as `T`; + * composition lists it in `unvalidatedPayloads`. A hand-written validator + * that checks nothing and omits the marker is not detected. + */ + readonly validation?: "NONE"; + /** Why validation is skipped. Required with `validation: "NONE"`. */ + readonly unvalidatedReason?: string; safeParse(value: unknown): RuntimeValidationResult; } +/** + * 1101/07-03. The named way to skip runtime validation, for a payload whose + * shape the feature decides to trust (for example generated client types). + * The value reaches the mapper as `T` unchecked: a server that sends another + * shape produces no `SCHEMA_MISMATCH`. The skip and its reason stay visible in + * `ComposedContractContributions.unvalidatedPayloads`. + */ +export function unvalidatedPayload( + schemaId: string, + reason: string, +): RuntimeValidator { + return Object.freeze({ + schemaId, + validation: "NONE" as const, + unvalidatedReason: reason, + safeParse(value: unknown) { + return Object.freeze({ + success: true as const, + data: structuredClone(value) as T, + }); + }, + }); +} + /** * A validator invocation never escapes as a native throw. `THROWN` is the * `CONTRACT_RUNTIME_FAILURE` signal; `false` success is the ordinary @@ -306,18 +339,58 @@ function assertPackageIdentity( } } -function assertValidator( - validator: RuntimeValidator, - label: string, -): void { - if ( - !validator || - typeof validator.safeParse !== "function" || - typeof validator.schemaId !== "string" || - validator.schemaId.length === 0 - ) { - fail(`${label}: runtime validator with non-empty schemaId is required`); +/** 1101/07-03. A validator slot whose validation is skipped by name. */ +export type UnvalidatedPayloadEntry = Readonly<{ + featureId: string; + /** The HTTP operationId, or the event type of an event contract. */ + contractId: string; + validator: "input" | "output" | "problem" | "envelope" | "payload"; + schemaId: string; + reason: string; +}>; + +/** Checks each validator and returns the ones that skip validation by name. */ +function assertValidators( + featureId: string, + contractId: string, + validators: Partial< + Record> + >, +): UnvalidatedPayloadEntry[] { + const unvalidated: UnvalidatedPayloadEntry[] = []; + for (const [role, validator] of Object.entries(validators) as [ + UnvalidatedPayloadEntry["validator"], + RuntimeValidator, + ][]) { + const label = `${featureId}/${contractId}.${role}`; + if ( + !validator || + typeof validator.safeParse !== "function" || + typeof validator.schemaId !== "string" || + validator.schemaId.length === 0 + ) { + fail(`${label}: runtime validator with non-empty schemaId is required`); + } + if (validator.validation === undefined) continue; + const reason = validator.unvalidatedReason; + if ( + validator.validation !== "NONE" || + typeof reason !== "string" || + reason.trim().length === 0 + ) { + fail(`${label}: an unvalidated payload needs validation "NONE" and a reason`); + } + unvalidated.push( + Object.freeze({ + featureId, + contractId, + validator: role, + schemaId: validator.schemaId, + reason, + }), + ); } + return unvalidated; } function assertStatuses( @@ -405,7 +478,7 @@ function assertHttpContract( installed: InstalledHttpContract, featureId: string, authProfiles: InstalledRestAuthProfiles, -): void { +): UnvalidatedPayloadEntry[] { const contract = installed?.contract; if (!contract || typeof contract !== "object") { fail(`${featureId}: http contract descriptor missing`); @@ -434,9 +507,11 @@ function assertHttpContract( ) { fail(`${label}: pathTemplate`); } - assertValidator(contract.inputValidator, `${label}.input`); - assertValidator(contract.outputValidator, `${label}.output`); - assertValidator(contract.problemValidator, `${label}.problem`); + const unvalidated = assertValidators(featureId, String(contract.operationId), { + input: contract.inputValidator, + output: contract.outputValidator, + problem: contract.problemValidator, + }); if (typeof contract.projectRequest !== "function") { fail(`${label}: descriptor request projection is required`); } @@ -514,12 +589,13 @@ function assertHttpContract( ) { fail(`${label}: retry budget contradicts NEVER retry semantics`); } + return unvalidated; } function assertEventContract( event: InstalledEventContract, featureId: string, -): void { +): UnvalidatedPayloadEntry[] { const label = `${featureId}/${String(event?.eventType)}`; if ( typeof event?.eventType !== "string" || @@ -529,8 +605,10 @@ function assertEventContract( ) { fail(`${label}: eventType`); } - assertValidator(event.envelopeValidator, `${label}.envelope`); - assertValidator(event.payloadValidator, `${label}.payload`); + return assertValidators(featureId, event.eventType, { + envelope: event.envelopeValidator, + payload: event.payloadValidator, + }); } export type ComposedContractContributions = Readonly<{ @@ -549,6 +627,8 @@ export type ComposedContractContributions = Readonly<{ InstalledEventContract >; externalPackages: readonly InstalledContractPackageIdentity[]; + /** 1101/07-03. Every validator made by `unvalidatedPayload`, in install order. */ + unvalidatedPayloads: readonly UnvalidatedPayloadEntry[]; }>; const EXECUTION_POLICY_KEYS = [ @@ -698,6 +778,7 @@ export function composeContractContributions( const packagesById = new Map(); const contributionIds = new Set(); const installedContributions: InstalledContractContribution[] = []; + const unvalidatedPayloads: UnvalidatedPayloadEntry[] = []; let fixtureInstalled = false; for (const raw of rows) { @@ -833,7 +914,9 @@ export function composeContractContributions( installed as InstalledHttpContract, featureId, ); - assertHttpContract(snapshot, featureId, authProfiles); + unvalidatedPayloads.push( + ...assertHttpContract(snapshot, featureId, authProfiles), + ); const operationId = snapshot.contract.operationId; const previous = httpByOperationId.get(operationId); if (previous) fail(`duplicate operation: ${operationId}`); @@ -847,7 +930,7 @@ export function composeContractContributions( event as InstalledEventContract, featureId, ); - assertEventContract(snapshot, featureId); + unvalidatedPayloads.push(...assertEventContract(snapshot, featureId)); if (eventByType.has(snapshot.eventType)) { fail(`duplicate event type: ${snapshot.eventType}`); } @@ -877,5 +960,6 @@ export function composeContractContributions( httpByOperationId: createReadOnlyRegistry(httpByOperationId), eventByType: createReadOnlyRegistry(eventByType), externalPackages: Object.freeze(externalPackages), + unvalidatedPayloads: Object.freeze(unvalidatedPayloads), }); } diff --git a/src/contracts/zod-validator.ts b/src/contracts/zod-validator.ts new file mode 100644 index 00000000..47b5b026 --- /dev/null +++ b/src/contracts/zod-validator.ts @@ -0,0 +1,47 @@ +import type { RuntimeValidator } from "./external-contract-runtime.ts"; +import type { ZodType } from "./zod.ts"; + +/** + * 1101/07-03. The one adapter from a zod schema to the `RuntimeValidator` + * protocol (`external-contract-runtime.ts`). Features import it from here + * rather than keeping a copy, so its rules cannot drift between features: + * - a success value is a `structuredClone` copy, so the caller's object never + * reaches the executor; + * - an issue path stays an array of numbers and strings (symbol keys become + * strings); an issue code is zod's code as a string. + * A package that ships its own validators keeps implementing the protocol + * directly. To skip validation on purpose, use `unvalidatedPayload`, which + * composition lists. + */ +export function zodValidator( + schemaId: string, + schema: ZodType, +): RuntimeValidator { + return Object.freeze({ + schemaId, + safeParse(value: unknown) { + const result = schema.safeParse(value); + if (result.success) { + return Object.freeze({ + success: true as const, + data: structuredClone(result.data), + }); + } + return Object.freeze({ + success: false as const, + issues: Object.freeze( + result.error.issues.map((issue) => + Object.freeze({ + path: Object.freeze( + issue.path.map((segment): string | number => + typeof segment === "number" ? segment : String(segment), + ), + ), + code: String(issue.code), + }), + ), + ), + }); + }, + }); +} diff --git a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts index fb5daae5..b01ee5ba 100644 --- a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts +++ b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts @@ -5,6 +5,7 @@ import type { InstalledContractContribution, InstalledHttpContract, } from "../../../contracts/external-contract-runtime.ts"; +import { zodValidator } from "../../../contracts/zod-validator.ts"; import { REFERENCE_FEATURE_ID } from "./reference-feature-contract.ts"; import { createReferenceResourceCommandSchema, @@ -13,7 +14,6 @@ import { referenceResourceListQuerySchema, referenceResourceParamsSchema, type ReferenceProblem, - zodValidator, } from "./reference-schemas.ts"; export type { ReferenceProblem } from "./reference-schemas.ts"; diff --git a/src/features/reference-feature/contracts/reference-schemas.ts b/src/features/reference-feature/contracts/reference-schemas.ts index 276cee25..619cd866 100644 --- a/src/features/reference-feature/contracts/reference-schemas.ts +++ b/src/features/reference-feature/contracts/reference-schemas.ts @@ -1,6 +1,6 @@ import { z } from "../../../contracts/zod.ts"; -import type { RuntimeValidator } from "../../../contracts/external-contract-runtime.ts"; import { runtimeSchemaCodecFromValidator } from "../../../contracts/schema-registry.ts"; +import { zodValidator } from "../../../contracts/zod-validator.ts"; export const referenceResourceListQuerySchema = z .object({ @@ -80,44 +80,6 @@ const requestSchemas = { CreateReferenceResourceCommand: createReferenceResourceCommandSchema, } satisfies Record; -/** - * D-15. The one zod wrapper: every reference schema is exposed through the - * canonical `RuntimeValidator`, and the registry codecs below are adapters - * over it. - */ -export function zodValidator( - schemaId: string, - schema: z.ZodType, -): RuntimeValidator { - return Object.freeze({ - schemaId, - safeParse(value: unknown) { - const result = schema.safeParse(value); - if (result.success) { - return Object.freeze({ - success: true as const, - data: structuredClone(result.data), - }); - } - return Object.freeze({ - success: false as const, - issues: Object.freeze( - result.error.issues.map((issue) => - Object.freeze({ - path: Object.freeze( - issue.path.map((segment): string | number => - typeof segment === "number" ? segment : String(segment), - ), - ), - code: String(issue.code), - }), - ), - ), - }); - }, - }); -} - const codec = (schemaId: string, schema: z.ZodType) => runtimeSchemaCodecFromValidator(zodValidator(schemaId, schema)); diff --git a/src/presentation/examples/platform-overview-page.tsx b/src/presentation/examples/platform-overview-page.tsx index 4768fba7..9435c29e 100644 --- a/src/presentation/examples/platform-overview-page.tsx +++ b/src/presentation/examples/platform-overview-page.tsx @@ -3,6 +3,7 @@ import { type ComponentType, useEffect, useState } from "react"; import { HTTP_EXECUTION_CEILINGS, type ComposedContractContributions, + type UnvalidatedPayloadEntry, } from "../../contracts/external-contract-runtime.ts"; import { SERVER_STATE_PROFILES } from "../../contracts/server-state.ts"; import { EXPECTED_CONTRACT_SET_PACKAGES } from "../../features/installed-contract-contributions.ts"; @@ -155,6 +156,26 @@ const OPERATION_COLUMNS: readonly DataTableColumn[] = }, ]); +const UNVALIDATED_COLUMNS: readonly DataTableColumn[] = + Object.freeze([ + { + id: "contractId", + header: "계약", + cell: (row) => {row.contractId}, + }, + { + id: "validator", + header: "검증기", + cell: (row) => ( + <> + {row.validator} + {row.schemaId} + + ), + }, + { id: "reason", header: "생략 이유", cell: (row) => row.reason }, + ]); + type ProfileRow = (typeof SERVER_STATE_PROFILES)[keyof typeof SERVER_STATE_PROFILES]; const PROFILE_COLUMNS: readonly DataTableColumn[] = Object.freeze([ @@ -448,6 +469,14 @@ export function PlatformOverviewPage({ /> } /> + {/* 1101/07-03. Drawn only when a contract skips validation by name. */} + `${row.contractId}.${row.validator}`} + empty={null} + />
{ } }); + // 1101/07-03. A skipped validation is shown, not just composed. + it("lists the operations that skip runtime validation, with the reason", () => { + const [listRow, ...rest] = TEST_CONTRACT_CONTRIBUTION.http; + const contracts = composeContractContributions([ + Object.freeze({ + ...TEST_CONTRACT_CONTRIBUTION, + http: Object.freeze([ + { + ...listRow!, + contract: { + ...listRow!.contract, + outputValidator: unvalidatedPayload( + "TestEntityListPayload", + "typed by the package", + ), + }, + }, + ...rest, + ]), + }), + ]); + render( + + + + + , + ); + + const table = tableByCaption("런타임 검증을 생략한 계약"); + const [row, ...others] = within(table).getAllByRole("row").slice(1); + expect(others).toHaveLength(0); + expect(within(row!).getByText("TEST_LIST_ENTITIES")).toBeVisible(); + expect(within(row!).getByText("typed by the package")).toBeVisible(); + }); + + it("shows no skipped-validation list when every operation validates", () => { + renderPage(); + + expect( + screen.queryByRole("table", { name: "런타임 검증을 생략한 계약" }), + ).toBeNull(); + }); + it("renders every fixed server-state profile with its own budget", () => { renderPage(); diff --git a/tests/helpers/external-contract-fixture.ts b/tests/helpers/external-contract-fixture.ts index 4960a2cc..a65e5f74 100644 --- a/tests/helpers/external-contract-fixture.ts +++ b/tests/helpers/external-contract-fixture.ts @@ -5,38 +5,8 @@ import type { InstalledContractContribution, InstalledEventContract, InstalledHttpContract, - RuntimeValidator, } from "../../src/contracts/external-contract-runtime.ts"; - -function zodValidator( - schemaId: string, - schema: z.ZodType, -): RuntimeValidator { - return Object.freeze({ - schemaId, - safeParse(value: unknown) { - const result = schema.safeParse(value); - if (result.success) { - return Object.freeze({ success: true as const, data: result.data }); - } - return Object.freeze({ - success: false as const, - issues: Object.freeze( - result.error.issues.map((issue) => - Object.freeze({ - path: Object.freeze( - issue.path.map((segment) => - typeof segment === "number" ? segment : String(segment), - ), - ), - code: String(issue.code), - }), - ), - ), - }); - }, - }); -} +import { zodValidator } from "../../src/contracts/zod-validator.ts"; const entitySchema = z .object({ diff --git a/tests/unit/external-contract-runtime.test.ts b/tests/unit/external-contract-runtime.test.ts index cf0495a1..52020384 100644 --- a/tests/unit/external-contract-runtime.test.ts +++ b/tests/unit/external-contract-runtime.test.ts @@ -4,10 +4,14 @@ import { ContractContributionError, composeContractContributions, invokeValidator, + unvalidatedPayload, type InstalledContractContribution, type RuntimeValidator, } from "../../src/contracts/external-contract-runtime.ts"; -import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts"; +import { + TEST_CONTRACT_CONTRIBUTION, + TEST_EVENT_CONTRACT, +} from "../helpers/external-contract-fixture.ts"; function contribution( contributionId: string, @@ -159,6 +163,73 @@ describe("template fixture provenance (07-04, §4.8)", () => { }); }); +// 1101/07-03. Skipping runtime validation stays possible, but only a skip +// made through `unvalidatedPayload` is named, so composition can list it. +describe("validation skipped by name (1101/07-03)", () => { + const [listRow] = TEST_CONTRACT_CONTRIBUTION.http as readonly [ + InstalledContractContribution["http"][number], + ]; + const skipped = unvalidatedPayload("TestEntityListPayload", "typed by the package"); + + function withOutput(validator: RuntimeValidator) { + return contribution("skip-test", [ + { ...listRow, contract: { ...listRow.contract, outputValidator: validator } }, + ]); + } + + it("lists nothing when every validator checks its input", () => { + expect( + composeContractContributions([TEST_CONTRACT_CONTRIBUTION]).unvalidatedPayloads, + ).toEqual([]); + }); + + it("lists an operation whose output skips validation, with its reason", () => { + expect( + composeContractContributions([withOutput(skipped)]).unvalidatedPayloads, + ).toEqual([ + { + featureId: "test-feature", + contractId: "TEST_LIST_ENTITIES", + validator: "output", + schemaId: "TestEntityListPayload", + reason: "typed by the package", + }, + ]); + }); + + it("lists an event whose payload skips validation", () => { + const composed = composeContractContributions([ + Object.freeze({ + ...contribution("skip-event", []), + events: Object.freeze([ + { ...TEST_EVENT_CONTRACT, payloadValidator: unvalidatedPayload("TestEntity", "trusted feed") }, + ]), + }), + ]); + + expect(composed.unvalidatedPayloads).toEqual([ + expect.objectContaining({ + contractId: "test.entity.changed", + validator: "payload", + reason: "trusted feed", + }), + ]); + }); + + it.each([ + ["no reason", { ...skipped, unvalidatedReason: " " }], + ["an unknown marker", { ...skipped, validation: "PARTIAL" }], + ])("rejects a skip marker with %s", (_label, validator) => { + expect( + captureContributionError(() => + composeContractContributions([withOutput(validator as RuntimeValidator)]), + ).reason, + ).toBe( + 'test-feature/TEST_LIST_ENTITIES.output: an unvalidated payload needs validation "NONE" and a reason', + ); + }); +}); + describe("validator invocation (07-06)", () => { const returning = (result: unknown): RuntimeValidator => ({ schemaId: "Malformed", diff --git a/tests/unit/zod-validator.test.ts b/tests/unit/zod-validator.test.ts new file mode 100644 index 00000000..d9d3868a --- /dev/null +++ b/tests/unit/zod-validator.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from "vitest"; + +import { + invokeValidator, + unvalidatedPayload, +} from "../../src/contracts/external-contract-runtime.ts"; +import { z } from "../../src/contracts/zod.ts"; +import { zodValidator } from "../../src/contracts/zod-validator.ts"; + +/** + * 1101/07-03. The one zod adapter lives in src/contracts, so every feature + * imports it instead of copying it, and it outlives the sample feature. + */ +describe("zodValidator", () => { + const validator = zodValidator( + "Entity", + z.object({ id: z.string().min(1), tags: z.array(z.string()) }).strip(), + ); + + it("returns a copy of the parsed value, not the caller's object", () => { + const source = { id: "a", tags: ["x"] }; + const result = validator.safeParse(source); + + expect(result).toEqual({ success: true, data: source }); + if (!result.success) throw new Error("expected success"); + expect(result.data.tags).not.toBe(source.tags); + expect(Object.isFrozen(result)).toBe(true); + }); + + it("reports issues with array paths and string codes", () => { + expect(validator.safeParse({ id: "", tags: [1] })).toEqual({ + success: false, + issues: [ + { path: ["id"], code: "too_small" }, + { path: ["tags", 0], code: "invalid_type" }, + ], + }); + }); + + it("checks its input, so it carries no skip marker", () => { + expect(validator.schemaId).toBe("Entity"); + expect(validator.validation).toBeUndefined(); + }); +}); + +describe("unvalidatedPayload", () => { + const skipped = unvalidatedPayload<{ id: string }>( + "EntityPayload", + "generated client types are trusted", + ); + + it("names the skip on the validator itself", () => { + expect(skipped).toMatchObject({ + schemaId: "EntityPayload", + validation: "NONE", + unvalidatedReason: "generated client types are trusted", + }); + }); + + it("accepts any value as a copy", () => { + const source = { anything: [1] }; + const invocation = invokeValidator(skipped, source); + + expect(invocation).toEqual({ outcome: "VALID", value: source }); + if (invocation.outcome !== "VALID") throw new Error("expected VALID"); + expect(invocation.value).not.toBe(source); + }); +});