Files
clean-architecture-frontend…/src/contracts/realtime-streams.ts
T
DongHyeonka 12f3bb7862 refactor(contracts)!: V2 API 행을 지우고 FE-REG-API를 HTTP descriptor에서 뽑는다
문제
기능 하나가 같은 HTTP API를 두 번 적는다. *-api-contract.ts의 V2 행
(defineRestOperation)은 check:registries(FE-REG-API)가 검사하는 선언이고,
contract contribution의 V3 descriptor가 실제로 실행된다. 둘이 어긋나지 않게
http-operation-v2-v3-parity 테스트를 따로 둔다. 048f490으로 V2 클라이언트가
없어져 V2 행을 읽는 실행 코드는 없고, 검사만 남은 두 번째 사본이다. V2 행을
위한 기능별 runtimeSchemas·mappers 레지스트리와 V2 보안 프로필 해석
(resolveRestSecurityProfiles)도 같이 남아 있다. 사용자 지시: 최신 경로 하나만
남기고, 레지스트리 기준선 재승인을 승인했다.

고른 방법
- src/contracts/api-operations.ts를 projectApiOperationRows 하나로 바꿨다.
  조립된 contribution의 descriptor마다 operationId, featureId, method, path,
  authProfileId, retrySemantics, requestBody, responseBody, responseEnvelope,
  request/response/problemSchema(검증기 schemaId) 행을 만든다. FE-REG-API는
  같은 export(API_OPERATIONS)를 읽고, governance 정의를 이 필드로 바꿨다.
  requestSchema·responseSchema는 그대로 FE-REG-SCHEMA를 참조한다.
- FeatureRuntime은 apiContract 대신 schemas(FE-REG-SCHEMA 행)만 받는다.
  installed-feature-runtime-registries는 schemas로 스키마 레지스트리를 만들고
  FE-REG-API 행을 descriptor에서 뽑는다. RUNTIME_SCHEMA_CODECS, MAPPER_REGISTRY,
  REST_PROFILE_BINDINGS_VALID, API_RUNTIME_BINDINGS_VALID를 지웠다.
- realtime snapshot 바인딩은 ApiOperationRow를 받고 method GET과
  retrySemantics SAFE·IDEMPOTENT를 본다(V2의 contractVersion·semantics·
  replayPolicy 대신).
- rest-profiles.ts에서 V2 행용 provider·CSRF 프로필 해석을 지웠다. V3는 조립
  때 auth profile을 검사하고 자격증명 헤더를 프로필로 거른다.
- 참조 기능: reference-api-contract.ts를 reference-schema-metadata.ts로
  바꾸고(스키마 행만), V2 runtime codec·operation mapper·레지스트리 mapper를
  지웠다. V3 descriptor가 쓰지 않는 NoRequest 스키마 행도 지웠다.
- create:feature: <base>-api-contract.ts 대신 <base>-schema-metadata.ts를
  만든다. codec·mapper 레지스트리 행과 그 테스트를 만들지 않는다.
- 레지스트리 기준선을 update:registry-baseline으로 다시 만들고 승인했다
  (digest 16f72742…, 승인자 DongHyeonka, 이유에 사용자 승인을 적음).
- 매뉴얼 01·02·reference, starter-experience, 계약 문서의 V2 설명을 지웠다.

버린 대안
- V2 행을 남기고 V3에서 생성하기: 생성 단계와 생성물이 하나 더 생긴다. 행은
  실행되지 않으므로 메모리에서 뽑아 검사하면 충분하다.
- 스키마 메타데이터(FE-REG-SCHEMA 행)도 검증기에서 뽑기: boundary·
  unknownFieldPolicy·owner는 검증기에 없고, 라우트 스키마도 같은 레지스트리를
  쓴다. 이 행은 V2가 아니라 스키마 레지스트리라 남겼다.

위험·한계
- BREAKING: FeatureRuntime 모양, contracts·rest-profiles·loaded-feature-runtimes
  의 이름이 바뀌거나 없어졌다. memento-frontend의 memento-web이 V2 행을 쓴다.
  옮기는 법은 CHANGELOG에 적는다.
- V2 보안 프로필 일관성 검사(auth "none"과 ANONYMOUS, 쿠키 프로필의 CSRF
  모드)가 사라졌다. V3 descriptor에는 그 칸이 없다.
- BoundedPollOperationContract(realtime polling recipe)는 contractVersion: 2
  필드를 갖지만 자체 계약이라 바꾸지 않았다.

검증
- check:types, lint, check:architecture, check:registries(11 registries PASS,
  compatibility=none), check:ci, check:diagnostics, check:adapter-inventory,
  verify:documentation 통과.
- test:unit 2,566(새 tests/unit/api-operation-rows.test.ts 3건 포함),
  test:integration 114, test:component 245, test:contract 23,
  test:runtime-schema 56, tests/features 99 통과.
- tests/unit/second-api-feature-registries.test.ts: V3 descriptor만 가진 두
  번째 기능을 복사본에 넣으면 기준선을 고치지 않고 check:registries가 통과한다.
- check:bundle 통과. 초기 JS 201,598 → 200,911 B.
- test:feature-scaffold 16개, test:sample-removal 23개 검사 통과.

BREAKING CHANGE: FeatureRuntime이 apiContract 대신 schemas를 받는다.
defineRestOperation, ApiOperation, RestOperationV2, composeApiOperations,
validateApiRuntimeBindings, getApiOperation, contracts의 API_OPERATIONS,
createRestProviderProfile, RestProviderProfile, resolveRestSecurityProfiles,
validateRestProfileBindings, REST_CSRF_PROFILES, RestCsrfProfile,
loaded-feature-runtimes의 RUNTIME_SCHEMA_CODECS, MAPPER_REGISTRY,
REST_PROFILE_BINDINGS_VALID, API_RUNTIME_BINDINGS_VALID가 없어졌다. 기능은
operation을 contract contribution에만 적고, schemas 행을 feature-runtime에
넘긴다.
2026-11-03 21:37:48 +09:00

549 lines
17 KiB
TypeScript

import type { ApiOperationRow } from "./api-operations.ts";
import type { InstalledBoundaryMapper } from "./boundary-mapper.ts";
import type { RuntimeSchemaCodec } from "./schema-registry.ts";
import {
ownDataValue,
snapshotExactArray,
snapshotExactObject,
} from "./exact-snapshot.ts";
declare const streamRegistrationIdBrand: unique symbol;
declare const eventTypeIdBrand: unique symbol;
declare const realtimeEndpointIdBrand: unique symbol;
declare const externalEventEffectProfileIdBrand: unique symbol;
declare const killSwitchIdBrand: unique symbol;
export type StreamRegistrationId = string &
Readonly<{ [streamRegistrationIdBrand]: true }>;
export type EventTypeId = string &
Readonly<{ [eventTypeIdBrand]: true }>;
export type RealtimeEndpointId = string &
Readonly<{ [realtimeEndpointIdBrand]: true }>;
export type ExternalEventEffectProfileId = string &
Readonly<{ [externalEventEffectProfileIdBrand]: true }>;
export type KillSwitchId = string &
Readonly<{ [killSwitchIdBrand]: true }>;
export const REALTIME_EVENT_PROTOCOL = "REALTIME_EVENT_V1" as const;
export const REALTIME_HARD_LIMITS = Object.freeze({
maxEventBytes: 64 * 1024,
maxPayloadDepth: 16,
maxPayloadNodes: 4_096,
maxQueueEvents: 256,
maxQueueBytes: 4 * 1024 * 1024,
maxDedupeEntries: 2_048,
maxDedupeBytes: 4 * 1024 * 1024,
dedupeTtlMs: 10 * 60 * 1_000,
});
export type RealtimeLimits = Readonly<{
maxEventBytes: number;
maxPayloadDepth: number;
maxPayloadNodes: number;
maxQueueEvents: number;
maxQueueBytes: number;
maxDedupeEntries: number;
/**
* Additional implementation memory ceiling for semantic conflict
* fingerprints. Reaching it evicts the oldest entries, the same as
* exhausting the count/time dedupe window.
*/
maxDedupeBytes: number;
dedupeTtlMs: number;
}>;
export type RealtimeRecoveryProfile =
| Readonly<{
mode: "CURSOR";
snapshotOperationId: string;
checkpointCodecId: string;
barrier: "REPLAY";
}>
| Readonly<{
mode: "SNAPSHOT_ONLY";
snapshotOperationId: string;
checkpointCodecId: string;
barrier: "CONNECT_BUFFER" | "SERVER_HOLD" | "NONE";
}>
| Readonly<{
mode: "SESSION_REBUILD";
rebuildInputId: string;
}>;
/**
* `fallback`, `hiddenPolicy` and `killSwitchId` are validated declarations.
* The reference runtime in `src/adapters/realtime/` does not read or enforce
* them: closing on hidden, pagehide and logout, the kill switch and the
* fallback are composition code's responsibility (design 5.4-5.6).
*/
export type RealtimeStreamRegistration = Readonly<{
id: StreamRegistrationId;
protocol: typeof REALTIME_EVENT_PROTOCOL;
owner: string;
scope: "ORIGIN_SHARED" | "ACCOUNT_BOUND" | "SESSION_BOUND";
primaryTransport: "SSE" | "WEBSOCKET" | "NONE";
endpointId: RealtimeEndpointId;
eventTypeIds: readonly EventTypeId[];
delivery: "INVALIDATION_HINT" | "AUTHORITATIVE_DELTA" | "EPHEMERAL";
recovery: RealtimeRecoveryProfile;
fallback: "BOUNDED_POLLING" | "EXPLICITLY_STALE";
hiddenPolicy: "CLOSE" | "BOUNDED_GRACE";
limits: RealtimeLimits;
killSwitchId: KillSwitchId;
}>;
export type RealtimeEventTypeRegistration = Readonly<{
id: EventTypeId;
owner: string;
payloadSchemaId: string;
mapperId: string;
effectProfileId: ExternalEventEffectProfileId;
stateBearing: boolean;
}>;
export type RealtimePolicyRegistryBindings = Readonly<{
schemaCodecs: Readonly<Record<string, RuntimeSchemaCodec>>;
mappers: Readonly<Record<string, InstalledBoundaryMapper>>;
apiOperations: Readonly<Record<string, ApiOperationRow>>;
endpointIds: readonly RealtimeEndpointId[];
effectProfileIds: readonly ExternalEventEffectProfileId[];
killSwitchIds: readonly KillSwitchId[];
rebuildInputIds?: readonly string[];
}>;
export type RealtimePolicyRegistry = Readonly<{
findStream(id: string): RealtimeStreamRegistration | undefined;
findEventType(id: string): RealtimeEventTypeRegistration | undefined;
findStreamEventType(
streamId: string,
eventTypeId: string,
): RealtimeEventTypeRegistration | undefined;
listStreams(): readonly RealtimeStreamRegistration[];
listEventTypes(): readonly RealtimeEventTypeRegistration[];
}>;
export type RealtimePolicyRegistryInput = Readonly<{
streams: readonly RealtimeStreamRegistration[];
eventTypes: readonly RealtimeEventTypeRegistration[];
bindings: RealtimePolicyRegistryBindings;
}>;
const REGISTRY_ID = /^[A-Z][A-Z0-9_]{2,79}$/u;
const OWNED_ID = /^[A-Za-z][A-Za-z0-9._:-]{0,127}$/u;
const OWNER = /^[a-z0-9][a-z0-9._:-]{0,127}$/u;
const STREAM_KEYS = Object.freeze([
"delivery",
"endpointId",
"eventTypeIds",
"fallback",
"hiddenPolicy",
"id",
"killSwitchId",
"limits",
"owner",
"primaryTransport",
"protocol",
"recovery",
"scope",
] as const);
const EVENT_TYPE_KEYS = Object.freeze([
"effectProfileId",
"id",
"mapperId",
"owner",
"payloadSchemaId",
"stateBearing",
] as const);
const LIMIT_KEYS = Object.freeze([
"dedupeTtlMs",
"maxDedupeBytes",
"maxDedupeEntries",
"maxEventBytes",
"maxPayloadDepth",
"maxPayloadNodes",
"maxQueueBytes",
"maxQueueEvents",
] as const);
export function defineStreamRegistrationId(
value: string,
): StreamRegistrationId {
return defineRegistryId(value, "stream") as StreamRegistrationId;
}
export function defineEventTypeId(value: string): EventTypeId {
return defineRegistryId(value, "event type") as EventTypeId;
}
export function defineRealtimeEndpointId(
value: string,
): RealtimeEndpointId {
return defineRegistryId(value, "endpoint") as RealtimeEndpointId;
}
export function defineExternalEventEffectProfileId(
value: string,
): ExternalEventEffectProfileId {
return defineRegistryId(
value,
"effect profile",
) as ExternalEventEffectProfileId;
}
export function defineRealtimeKillSwitchId(value: string): KillSwitchId {
return defineRegistryId(value, "kill switch") as KillSwitchId;
}
/**
* Builds a composition-time registry and retains no caller-owned registration
* object or array.
*/
export function createRealtimePolicyRegistry(
input: RealtimePolicyRegistryInput,
): RealtimePolicyRegistry {
// Q-6.7-6. Arrays are copied by index, so an own `Symbol.iterator` cannot
// hand the loops below more rows than the bounds checked.
const streamInputs = snapshotExactArray(ownDataValue(input, "streams"), 128);
const eventTypeInputs = snapshotExactArray(
ownDataValue(input, "eventTypes"),
512,
);
if (
!streamInputs ||
streamInputs.length < 1 ||
!eventTypeInputs ||
eventTypeInputs.length < 1
) {
throw new TypeError("Realtime policy registry is invalid.");
}
const bindings = input.bindings;
const endpointIds = identifierSet(
bindings.endpointIds,
"endpoint",
);
const effectProfileIds = identifierSet(
bindings.effectProfileIds,
"effect profile",
);
const killSwitchIds = identifierSet(
bindings.killSwitchIds,
"kill switch",
);
const rebuildInputIds = ownedIdentifierSet(
bindings.rebuildInputIds ?? [],
"rebuild input",
);
const eventTypes = new Map<EventTypeId, RealtimeEventTypeRegistration>();
for (const candidate of eventTypeInputs) {
const registration = snapshotEventType(
candidate as RealtimeEventTypeRegistration,
bindings,
effectProfileIds,
);
if (eventTypes.has(registration.id)) {
throw new TypeError("Realtime event type is duplicated.");
}
eventTypes.set(registration.id, registration);
}
const streams = new Map<StreamRegistrationId, RealtimeStreamRegistration>();
const referencedEventTypes = new Set<EventTypeId>();
for (const candidate of streamInputs) {
const registration = snapshotStream(
candidate as RealtimeStreamRegistration,
bindings,
eventTypes,
endpointIds,
killSwitchIds,
rebuildInputIds,
);
if (streams.has(registration.id)) {
throw new TypeError("Realtime stream is duplicated.");
}
streams.set(registration.id, registration);
for (const eventTypeId of registration.eventTypeIds) {
referencedEventTypes.add(eventTypeId);
}
}
if (
[...eventTypes.keys()].some(
(eventTypeId) => !referencedEventTypes.has(eventTypeId),
)
) {
throw new TypeError("Realtime event type is not owned by a stream.");
}
const streamList = Object.freeze([...streams.values()]);
const eventTypeList = Object.freeze([...eventTypes.values()]);
return Object.freeze({
findStream(id: string) {
return streams.get(id as StreamRegistrationId);
},
findEventType(id: string) {
return eventTypes.get(id as EventTypeId);
},
findStreamEventType(streamId: string, eventTypeId: string) {
const stream = streams.get(streamId as StreamRegistrationId);
if (!stream || !stream.eventTypeIds.includes(eventTypeId as EventTypeId)) {
return undefined;
}
return eventTypes.get(eventTypeId as EventTypeId);
},
listStreams: () => streamList,
listEventTypes: () => eventTypeList,
});
}
function snapshotEventType(
source: RealtimeEventTypeRegistration,
bindings: RealtimePolicyRegistryBindings,
effectProfileIds: ReadonlySet<string>,
): RealtimeEventTypeRegistration {
const input = exactRow<RealtimeEventTypeRegistration>(source, EVENT_TYPE_KEYS);
if (
!input ||
!REGISTRY_ID.test(input.id) ||
!OWNER.test(input.owner) ||
!OWNED_ID.test(input.payloadSchemaId) ||
!OWNED_ID.test(input.mapperId) ||
!REGISTRY_ID.test(input.effectProfileId) ||
typeof input.stateBearing !== "boolean" ||
bindings.schemaCodecs[input.payloadSchemaId]?.schemaId !==
input.payloadSchemaId ||
bindings.mappers[input.mapperId]?.mapperId !== input.mapperId ||
bindings.mappers[input.mapperId]?.inputSchemaId !==
input.payloadSchemaId ||
!effectProfileIds.has(input.effectProfileId)
) {
throw new TypeError("Realtime event type registration is invalid.");
}
return input;
}
function snapshotStream(
source: RealtimeStreamRegistration,
bindings: RealtimePolicyRegistryBindings,
eventTypes: ReadonlyMap<EventTypeId, RealtimeEventTypeRegistration>,
endpointIds: ReadonlySet<string>,
killSwitchIds: ReadonlySet<string>,
rebuildInputIds: ReadonlySet<string>,
): RealtimeStreamRegistration {
const input = exactRow<RealtimeStreamRegistration>(source, STREAM_KEYS);
const eventTypeIds = snapshotExactArray(input?.eventTypeIds, 128) as
| readonly EventTypeId[]
| null;
if (
!input ||
!REGISTRY_ID.test(input.id) ||
input.protocol !== REALTIME_EVENT_PROTOCOL ||
!OWNER.test(input.owner) ||
!["ORIGIN_SHARED", "ACCOUNT_BOUND", "SESSION_BOUND"].includes(
input.scope,
) ||
!["SSE", "WEBSOCKET", "NONE"].includes(input.primaryTransport) ||
!REGISTRY_ID.test(input.endpointId) ||
!endpointIds.has(input.endpointId) ||
!eventTypeIds ||
eventTypeIds.length < 1 ||
new Set(eventTypeIds).size !== eventTypeIds.length ||
eventTypeIds.some(
(eventTypeId) =>
!REGISTRY_ID.test(eventTypeId) || !eventTypes.has(eventTypeId),
) ||
!["INVALIDATION_HINT", "AUTHORITATIVE_DELTA", "EPHEMERAL"].includes(
input.delivery,
) ||
!["BOUNDED_POLLING", "EXPLICITLY_STALE"].includes(input.fallback) ||
!["CLOSE", "BOUNDED_GRACE"].includes(input.hiddenPolicy) ||
!REGISTRY_ID.test(input.killSwitchId) ||
!killSwitchIds.has(input.killSwitchId)
) {
throw new TypeError("Realtime stream registration is invalid.");
}
const limits = snapshotLimits(input.limits);
const recovery = snapshotRecovery(
input.recovery,
bindings,
rebuildInputIds,
);
const selectedEventTypes = eventTypeIds.map((eventTypeId) => {
const selected = eventTypes.get(eventTypeId);
if (!selected) {
throw new TypeError("Realtime stream event type is unresolved.");
}
return selected;
});
const hasStateBearingEvent = selectedEventTypes.some(
(eventType) => eventType.stateBearing,
);
const hasNonStateBearingEvent = selectedEventTypes.some(
(eventType) => !eventType.stateBearing,
);
if (
(hasStateBearingEvent && recovery.mode === "SESSION_REBUILD") ||
(hasStateBearingEvent &&
recovery.mode === "SNAPSHOT_ONLY" &&
recovery.barrier === "NONE") ||
(input.delivery === "EPHEMERAL" && hasStateBearingEvent) ||
(input.delivery === "AUTHORITATIVE_DELTA" &&
hasNonStateBearingEvent) ||
(recovery.mode === "SESSION_REBUILD" &&
input.delivery !== "EPHEMERAL") ||
(input.delivery === "EPHEMERAL" &&
input.fallback === "BOUNDED_POLLING")
) {
throw new TypeError("Realtime stream recovery contract is contradictory.");
}
return Object.freeze({ ...input, eventTypeIds, recovery, limits });
}
const SNAPSHOT_RECOVERY_KEYS = Object.freeze([
"barrier",
"checkpointCodecId",
"mode",
"snapshotOperationId",
] as const);
const SESSION_REBUILD_KEYS = Object.freeze(["mode", "rebuildInputId"] as const);
function snapshotRecovery(
source: RealtimeRecoveryProfile,
bindings: RealtimePolicyRegistryBindings,
rebuildInputIds: ReadonlySet<string>,
): RealtimeRecoveryProfile {
// The mode only picks the key set; every check below reads the snapshot.
const input = exactRow<RealtimeRecoveryProfile>(
source,
ownDataValue(source, "mode") === "SESSION_REBUILD"
? SESSION_REBUILD_KEYS
: SNAPSHOT_RECOVERY_KEYS,
);
if (!input) {
throw new TypeError("Realtime recovery profile is invalid.");
}
if (input.mode === "CURSOR") {
if (input.barrier !== "REPLAY" || !validSnapshotBindings(input, bindings)) {
throw new TypeError("Realtime cursor recovery profile is invalid.");
}
return input;
}
if (input.mode === "SNAPSHOT_ONLY") {
if (
!["CONNECT_BUFFER", "SERVER_HOLD", "NONE"].includes(input.barrier) ||
!validSnapshotBindings(input, bindings)
) {
throw new TypeError("Realtime snapshot recovery profile is invalid.");
}
return input;
}
if (
input.mode !== "SESSION_REBUILD" ||
!OWNED_ID.test(input.rebuildInputId) ||
!rebuildInputIds.has(input.rebuildInputId)
) {
throw new TypeError("Realtime session rebuild profile is invalid.");
}
return input;
}
function validSnapshotBindings(
input: Readonly<{
snapshotOperationId: string;
checkpointCodecId: string;
}>,
bindings: RealtimePolicyRegistryBindings,
): boolean {
const operation = bindings.apiOperations[input.snapshotOperationId];
return (
OWNED_ID.test(input.snapshotOperationId) &&
OWNED_ID.test(input.checkpointCodecId) &&
bindings.schemaCodecs[input.checkpointCodecId]?.schemaId ===
input.checkpointCodecId &&
operation?.method === "GET" &&
(operation.retrySemantics === "SAFE" ||
operation.retrySemantics === "IDEMPOTENT")
);
}
function snapshotLimits(source: RealtimeLimits): RealtimeLimits {
const input = exactRow<RealtimeLimits>(source, LIMIT_KEYS);
if (!input) {
throw new TypeError("Realtime limits are invalid.");
}
for (const key of LIMIT_KEYS) {
const value = input[key];
if (
!Number.isSafeInteger(value) ||
value < 1 ||
value > REALTIME_HARD_LIMITS[key]
) {
throw new TypeError("Realtime limits exceed implementation ceilings.");
}
}
if (
input.maxQueueBytes < input.maxEventBytes ||
input.maxDedupeBytes < input.maxEventBytes
) {
throw new TypeError("Realtime memory limits cannot hold one event.");
}
return input;
}
function identifierSet(
source: readonly string[],
label: string,
): ReadonlySet<string> {
const values = snapshotExactArray(source) as readonly string[] | null;
if (!values) {
throw new TypeError(`Realtime ${label} bindings are invalid.`);
}
const result = new Set<string>();
for (const value of values) {
if (!REGISTRY_ID.test(value) || result.has(value)) {
throw new TypeError(`Realtime ${label} bindings are invalid.`);
}
result.add(value);
}
return result;
}
function ownedIdentifierSet(
source: readonly string[],
label: string,
): ReadonlySet<string> {
const values = snapshotExactArray(source) as readonly string[] | null;
if (!values) {
throw new TypeError(`Realtime ${label} bindings are invalid.`);
}
const result = new Set<string>();
for (const value of values) {
if (!OWNED_ID.test(value) || result.has(value)) {
throw new TypeError(`Realtime ${label} bindings are invalid.`);
}
result.add(value);
}
return result;
}
function defineRegistryId(value: string, label: string): string {
if (!REGISTRY_ID.test(value)) {
throw new TypeError(`Realtime ${label} ID is invalid.`);
}
return value;
}
/** Q-6.7-6. One owned read of an exact row; checks run on the copy. */
function exactRow<Row>(source: unknown, keys: readonly string[]): Row | null {
return snapshotExactObject(source, { allowed: keys, required: keys }) as
| Row
| null;
}