Files
clean-architecture-frontend…/tests/unit/external-contract-runtime.test.ts
T
DongHyeonka 8b7c6ebf6c perf(contracts): 검증 생략 목록을 부팅 경로 밖에서 만든다 (1101/07-03)
문제
- 93180f6(합친 커밋 d3ddc89)이 초기 JS를 늘렸다. 기능 모양 측정
  (scripts/scale/measure-feature-shape-growth.ts) 기준으로 기능 0개가
  202,376 → 202,526 B(+150)로, 기능 1개 추가분이 960 → 1,029 B로 늘었다.
  tests/unit/feature-shape-growth.test.ts의 1 KiB 상한을 넘는다.
- 원인은 두 가지다.
  - 부팅 때 도는 composeContractContributions가 검증기마다 생략 표시를
    읽고 목록을 만들었다(feature-platform 청크 +164 B). 이 목록을 쓰는
    곳은 플랫폼 개요 화면(lazy 라우트)뿐이다.
  - 공유 zod-validator.ts가 기능이 두 개가 되면 lazy 청크 하나로 따로
    나왔다. 모든 context-routes·feature-runtime import의 preload 목록에
    파일 이름이 하나 늘어 boot·feature-declarations 청크가 각각 약 25 B
    커졌다.

고른 방법
- 목록 계산을 src/contracts/unvalidated-payload.ts의
  listUnvalidatedPayloads(composed)로 옮긴다. 플랫폼 개요 화면만 이것을
  import한다. 결정의 뜻(생략한 operation이 조립 결과에서 목록으로
  나온다)은 그대로다. 계산 시점만 화면이 열릴 때로 미룬다.
  ComposedContractContributions.unvalidatedPayloads 필드는 뺀다.
- unvalidatedPayload 팩토리도 같은 모듈로 옮긴다.
- 조립기의 표시 검사도 뺀다. 이유가 빈 생략은 unvalidatedPayload가 만들
  때 거부한다(TypeError). 손으로 붙인 표시는 값이 "NONE"이 아니거나 이유가
  없어도 목록에 나온다(화면에는 "이유 없음"). 그래서 생략이 숨지 않는다.
  external-contract-runtime.ts에는 RuntimeValidator의 선택 타입 필드
  2개만 남는다.
- vite.config.ts에서 zod-validator.ts를 schema-registry.ts와 같은 lazy
  청크로 묶는다. 어댑터를 import하는 곳은 이미 schema-registry 청크를
  preload한다. includeDependenciesRecursively: false라서 다른 모듈은
  끌려오지 않고, 두 모듈 모두 부팅 그래프 밖이다.

버린 대안
- 조립기에 "NONE + 이유" 검사만 남기기: feature-platform 청크 +57 B gzip.
  검사를 팩토리와 목록으로 옮기면 0 B다. 손으로 붙인 잘못된 표시를
  부팅 때 거부하지 못하지만, 목록에는 나온다.
- zodValidator를 schema-registry.ts 안에 정의: 빌드 설정 없이 같은 결과가
  나오지만 결정한 위치(src/contracts/zod-validator.ts)와 다르고, 다음 단계의
  기능 생성 명령이 그 경로를 쓴다.
- 어댑터를 zod.ts에 두기: zod 입구는 초기 청크라 기능 0개 초기 JS가 는다.

위험·한계
- 조립 결과 타입에서 unvalidatedPayloads 필드가 빠진다. 93180f6 뒤 이
  필드를 쓴 코드는 listUnvalidatedPayloads로 바꿔야 한다. repo 안에서는
  화면과 테스트만 썼다.
- 손으로 만든 잘못된 표시(예: validation: "PARTIAL")는 더 이상 조립에서
  거부되지 않는다. 목록에만 나온다. 테스트 2건을 이 동작으로 바꿨다.
- 청크 묶음은 빌드 설정에 두 파일 경로를 적는다. 파일 이름을 바꾸면
  정규식도 함께 바꿔야 한다. 놓치면 바이트만 늘고 동작은 같다.
- 플랫폼 개요 화면을 열면 schema-registry 청크에 어댑터(351 B raw)가 같이
  온다.

검증
- 기능 모양 측정(0개 / 1개 추가분, gzip B):
  - ee81c44(07-03 전): 202,376 / 960
  - d3ddc89(07-03 합친 뒤): 202,526 / 1,029
  - 목록만 부팅 밖으로: 202,407 / 1,035
  - 청크 묶음 추가: 202,424 / 983
  - 조립기 검사 제거(이 커밋): 202,371 / 958
- feature-shape-growth.test.ts 6건 통과.
- 07-03 테스트 3파일 33건 통과(zod-validator, external-contract-runtime,
  starter-platform-overview-page).
- 회귀: tests/unit·contract·component·runtime-schema·features·platform
  270파일 3,203건, tests/integration 12파일 158건(pnpm을 띄우는
  security-followup-archive 제외), tests/architecture 7파일 33건 통과.
- tsc app·node·test·recipes·web-worker·service-worker 오류 0. 바꾼 파일
  eslint 0. 아키텍처 그래프 검사(pnpm 대신 exec stub) 413 모듈 PASS.
  check-registries PASS(compatibility=none).
- 본 빌드 초기 JS gzip 202,371 B(26파일). raw 644,782 B로 ee81c44 측정과
  같다.

Refs: docs/reviews/2026-11-01-maturity-review/07-contracts.md 07-03
2026-11-03 01:58:38 +09:00

271 lines
9.1 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
ContractContributionError,
composeContractContributions,
invokeValidator,
type InstalledContractContribution,
type RuntimeValidator,
} from "../../src/contracts/external-contract-runtime.ts";
import {
listUnvalidatedPayloads,
unvalidatedPayload,
} from "../../src/contracts/unvalidated-payload.ts";
import {
TEST_CONTRACT_CONTRIBUTION,
TEST_EVENT_CONTRACT,
} from "../helpers/external-contract-fixture.ts";
function contribution(
contributionId: string,
http: InstalledContractContribution["http"],
): InstalledContractContribution & Readonly<{ contributionId: string }> {
return Object.freeze({
...TEST_CONTRACT_CONTRIBUTION,
contributionId,
http: Object.freeze([...http]),
});
}
function captureContributionError(operation: () => unknown): ContractContributionError {
try {
operation();
} catch (error) {
expect(error).toBeInstanceOf(ContractContributionError);
return error as ContractContributionError;
}
throw new Error("Expected contract composition to fail.");
}
describe("external contract contribution composition", () => {
it("allows one feature to install multiple uniquely identified contributions", () => {
const operations = TEST_CONTRACT_CONTRIBUTION.http;
const composed = composeContractContributions([
contribution("test-read-contracts", operations.slice(0, 2)),
contribution("test-command-contracts", operations.slice(2)),
]);
expect(composed.contributions).toHaveLength(2);
expect(composed.httpByOperationId.size).toBe(3);
});
it("rejects duplicate contribution identities even across different feature entries", () => {
const first = contribution(
"test-contracts",
TEST_CONTRACT_CONTRIBUTION.http.slice(0, 1),
);
const second = contribution(
"test-contracts",
TEST_CONTRACT_CONTRIBUTION.http.slice(1),
);
const error = captureContributionError(() =>
composeContractContributions([first, second]),
);
expect(error.reason).toContain("duplicate contributionId");
});
it("maps malformed source values to the closed composition error", () => {
const malformed = {
...contribution("malformed-source", []),
source: null,
} as unknown as InstalledContractContribution;
const error = captureContributionError(() =>
composeContractContributions([malformed]),
);
expect(error.reason).toContain("source");
});
it("rejects method and body vocabulary outside the runtime protocol", () => {
const installed = TEST_CONTRACT_CONTRIBUTION.http[0]!;
const malformedOperation = {
...installed,
contract: { ...installed.contract, method: "TRACE" },
} as unknown as InstalledContractContribution["http"][number];
const error = captureContributionError(() =>
composeContractContributions([
contribution("invalid-http-vocabulary", [malformedOperation]),
]),
);
expect(error.reason).toContain("method");
});
});
// 07-06 (MX1, MX9, MX6). The write-API rules the composer teaches through its
// error messages. TEST_CONTRACT_CONTRIBUTION composing in the first block is
// the valid control.
describe("write operation rules", () => {
const [listRow, , createRow] = TEST_CONTRACT_CONTRIBUTION.http as readonly [
InstalledContractContribution["http"][number],
InstalledContractContribution["http"][number],
InstalledContractContribution["http"][number],
];
function reasonFor(row: object): string {
return captureContributionError(() =>
composeContractContributions([
contribution("write-rule", [
row as InstalledContractContribution["http"][number],
]),
]),
).reason;
}
// The executor decides "write" by `commandEffect !== null`, not by method,
// so this rule is the only thing keeping a GET from running as a command.
it("rejects command descriptors on a read operation", () => {
expect(
reasonFor({
...listRow,
contract: { ...listRow.contract, commandEffect: createRow.contract.commandEffect },
}),
).toBe("test-feature/TEST_LIST_ENTITIES: read operations carry no command descriptors");
});
it("requires a recovery descriptor on a KEYED command", () => {
expect(
reasonFor({
...createRow,
contract: { ...createRow.contract, commandRecovery: null },
}),
).toBe("test-feature/TEST_CREATE_ENTITY: KEYED commands require a recovery descriptor");
});
it("rejects a retry budget on a NEVER-retry operation", () => {
expect(
reasonFor({
...createRow,
contract: { ...createRow.contract, retrySemantics: "NEVER" },
frontend: { ...createRow.frontend, retryBudget: 1 },
}),
).toBe("test-feature/TEST_CREATE_ENTITY: retry budget contradicts NEVER retry semantics");
});
});
// The sample feature's own cases (its fixture composes, a second one does not)
// live in tests/features so they leave with the sample.
describe("template fixture provenance (07-04, §4.8)", () => {
it("rejects a fixture copied into a product feature, which would leave the contract set silently", () => {
const copied = Object.freeze({
...contribution("order-http-v1", TEST_CONTRACT_CONTRIBUTION.http),
featureId: "order",
source: Object.freeze({
kind: "TEMPLATE_FIXTURE" as const,
fixtureId: "REFERENCE_FEATURE_V1" as const,
revision: 1 as const,
}),
});
const error = captureContributionError(() =>
composeContractContributions([copied]),
);
expect(error.reason).toMatch(
/^order: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to .+ only; pin an EXTERNAL_PACKAGE$/u,
);
});
});
// 1101/07-03. Skipping runtime validation stays possible, but only a skip
// made through `unvalidatedPayload` is named, so the composed result lists 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<unknown>) {
return contribution("skip-test", [
{ ...listRow, contract: { ...listRow.contract, outputValidator: validator } },
]);
}
it("lists nothing when every validator checks its input", () => {
expect(
listUnvalidatedPayloads(composeContractContributions([TEST_CONTRACT_CONTRIBUTION])),
).toEqual([]);
});
it("lists an operation whose output skips validation, with its reason", () => {
expect(
listUnvalidatedPayloads(composeContractContributions([withOutput(skipped)])),
).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(listUnvalidatedPayloads(composed)).toEqual([
expect.objectContaining({
contractId: "test.entity.changed",
validator: "payload",
reason: "trusted feed",
}),
]);
});
it("refuses to name a skip without a reason", () => {
expect(() => unvalidatedPayload("TestEntity", " ")).toThrow(
"TestEntity: an unvalidated payload needs a reason",
);
});
// Composition (boot path) does not read the marker, so a hand-built one is
// not refused there; the list still shows it instead of passing it as checked.
it("lists a hand-built marker that is not NONE or has no reason", () => {
const handBuilt = { ...skipped, validation: "PARTIAL", unvalidatedReason: undefined };
expect(
listUnvalidatedPayloads(
composeContractContributions([withOutput(handBuilt as unknown as RuntimeValidator<unknown>)]),
),
).toEqual([expect.objectContaining({ validator: "output", reason: "" })]);
});
});
describe("validator invocation (07-06)", () => {
const returning = (result: unknown): RuntimeValidator<unknown> => ({
schemaId: "Malformed",
safeParse: () => result as never,
});
it.each([
["non-array issues", { success: false, issues: 5 }],
["object issues", { success: false, issues: {} }],
["non-boolean success", { success: "no", data: "unchecked" }],
["throwing issues getter", {
success: false,
get issues(): never {
throw new Error("hostile");
},
}],
])("reports THROWN for a result with %s", (_label, result) => {
expect(invokeValidator(returning(result), {})).toEqual({ outcome: "THROWN" });
});
it("keeps well-formed results", () => {
expect(invokeValidator(returning({ success: true, data: 1 }), {})).toEqual({
outcome: "VALID",
value: 1,
});
expect(
invokeValidator(returning({ success: false, issues: [{ path: [], code: "X" }] }), {}),
).toEqual({ outcome: "INVALID", issues: [{ path: [], code: "X" }] });
});
});