문제: reconnect coordinator, live/poll handoff, SSE onOpen·onEvent, WS onSubscribed·onEvent는 받은 RealtimeResult를 2단계로 동결된 객체만 받는다. 타입은 Readonly일 뿐이라 같은 모양의 평범한 객체도 컴파일된다. 그런데 동결된 결과를 만드는 realtimeSuccess / realtimeFailure는 result.ts에만 있고 배럴에 없다. 조합 코드는 배럴만 import할 수 있으므로 결과를 손으로 만들게 되고, 그러면 첫 실패나 첫 종료에서 PROTOCOL_MISMATCH·MAPPING_CONTRACT_VIOLATION으로 재시도 없이 끝난다. 이 규칙은 주석에도 없었고, reconnect 경계의 동결 검사 3곳을 지워도(MU4) 테스트가 모두 통과했다. 고른 방법: 리뷰 6.2절의 (b). 배럴 src/adapters/realtime/index.ts에서 두 함수를 export하고(추가만, 기존 시그니처 변화 없음), 엄격한 경계의 타입 주석(RealtimeReconnectOutcome, RealtimeReconnectSession, confirmTransportBarrier, handoff apply·establishAuthoritativeCheckpoint, SSE onOpen·onEvent, WS onEvent·onSubscribed)과 생성 함수 주석에 규칙을 적었다. 동결 규칙 자체와 DEFAULT_RETRYABLE 기본값은 그대로다. 버린 대안: - (c) 엄격한 경계도 stream coordinator처럼 한 번 복사하기. 규칙이 하나가 되지만 "검증한 실패 객체를 그대로 돌려준다"(toBe) 계약을 깬다. - (d) 생성 함수를 application port(shared.ts)에 두기. feature 코드도 쓸 수 있게 되지만 application 계층에 런타임 헬퍼가 는다. handoff apply를 feature가 구현한다고 정해지면 그때 옮긴다. - 런타임 오류 이름을 따로 두기(예: RESULT_NOT_FROZEN). failure kind 어휘가 바뀌는 계약 변경이라 이번 범위 밖이다. 위험·한계: - 동결하지 않은 결과는 여전히 컴파일된다. 타입으로 막으려면 brand가 필요하고, 그건 공개 타입을 깨는 변경이다. 주석과 테스트로만 알린다. - realtime 레시피 번들 40,863 -> 40,879 / 40,900 gzip B(+16 B, 여유 21 B). 예산은 그대로다. 검증: - RED: 새 테스트 "retries a failure built with the barrel's realtimeFailure"가 수정 전 `TypeError: realtimeFailure is not a function`으로 실패(1 failed | 43 passed). - 새 테스트 4건(시도의 평범한 실패, 동결된 실패 안의 평범한 error, classifyClosed의 평범한 성공 -> PROTOCOL_MISMATCH, 재시도 없음)과 handoff apply의 평범한 성공 -> MAPPING_CONTRACT_VIOLATION 1건. - MU4(reconnect 동결 검사 3곳 제거)를 다시 넣으면 새 테스트 3건이 실패한다(수정 전에는 생존). - GREEN: `node scripts/run-vitest.ts run tests/unit/realtime/` -> 14파일 230건 통과. - `npx tsc --project tsconfig.app.json --noEmit`, `npx tsc --project tsconfig.test.json --noEmit` -> 오류 0. - `npx eslint <바꾼 파일 8개> --max-warnings=0` -> 통과. - `node scripts/check-realtime-boundaries.ts` -> PASS, `node scripts/check-adapter-inventory.ts` -> PASS, `node scripts/check-optional-recipes.ts` -> PASS(realtime 40879/40900). Refs: docs/reviews/2026-11-01-maturity-review/04-adapters-realtime.md 04-01, 6.2절
403 lines
12 KiB
TypeScript
403 lines
12 KiB
TypeScript
import type {
|
|
RealtimeTransportEventOutcome,
|
|
} from "../../application/ports/realtime/event-authority.ts";
|
|
import type {
|
|
RealtimeFailure,
|
|
RealtimeFailureKind,
|
|
RealtimeOperation,
|
|
RealtimeResult,
|
|
} from "../../application/ports/realtime/shared.ts";
|
|
import {
|
|
REALTIME_FAILURE_KINDS,
|
|
REALTIME_OPERATIONS,
|
|
} from "../../application/ports/realtime/shared.ts";
|
|
import {
|
|
isCanonicalRealtimeSequence,
|
|
isRealtimeOpaqueIdentifier,
|
|
isRealtimeResumeCursor,
|
|
} from "../../contracts/realtime-events.ts";
|
|
import { createAbortableOperation } from "../platform/abortable-operation.ts";
|
|
|
|
export type {
|
|
RealtimeFailure,
|
|
RealtimeFailureKind,
|
|
RealtimeOperation,
|
|
RealtimeResult,
|
|
} from "../../application/ports/realtime/shared.ts";
|
|
|
|
const DEFAULT_RETRYABLE = new Set<RealtimeFailureKind>([
|
|
"OFFLINE",
|
|
"CONNECT_TIMEOUT",
|
|
"IDLE_TIMEOUT",
|
|
"RATE_LIMITED",
|
|
"PROVIDER_UNAVAILABLE",
|
|
]);
|
|
const FAILURE_KINDS = new Set<unknown>(REALTIME_FAILURE_KINDS);
|
|
const OPERATIONS = new Set<unknown>(REALTIME_OPERATIONS);
|
|
|
|
export type RealtimeDataSnapshot = Readonly<{
|
|
/** The object that was read; never read its properties again. */
|
|
source: object;
|
|
keys: readonly string[];
|
|
values: Readonly<Record<string, unknown>>;
|
|
frozen: boolean;
|
|
}>;
|
|
|
|
/**
|
|
* Build every result handed to the reconnect coordinator, the live/poll
|
|
* handoff, or an SSE or WebSocket callback with these two functions. Those
|
|
* boundaries keep using the object they validated, so they accept only a
|
|
* result frozen two levels deep and fail closed on a plain object of the same
|
|
* type. The stream coordinator and polling copy the result once and accept
|
|
* either.
|
|
*/
|
|
export function realtimeSuccess<Value>(
|
|
value: Value,
|
|
): Extract<RealtimeResult<Value>, { ok: true }> {
|
|
return Object.freeze({ ok: true, value });
|
|
}
|
|
|
|
export function realtimeFailure(
|
|
kind: RealtimeFailureKind,
|
|
operation: RealtimeOperation,
|
|
retryable = DEFAULT_RETRYABLE.has(kind),
|
|
): Extract<RealtimeResult<never>, { ok: false }> {
|
|
return Object.freeze({
|
|
ok: false,
|
|
error: Object.freeze({
|
|
kind,
|
|
operation,
|
|
retryable,
|
|
} satisfies RealtimeFailure),
|
|
});
|
|
}
|
|
|
|
export function isRealtimeFailure(
|
|
value: unknown,
|
|
): value is RealtimeFailure {
|
|
return parseRealtimeFailure(value, true) !== null;
|
|
}
|
|
|
|
export type RealtimeRace<Value> =
|
|
| Readonly<{ kind: "VALUE"; value: Value }>
|
|
| Readonly<{ kind: "REJECTED" }>
|
|
| Readonly<{ kind: "ABORTED" }>
|
|
| Readonly<{ kind: "TIMEOUT" }>
|
|
| Readonly<{ kind: "CLOCK_FAILED" }>;
|
|
|
|
const REJECTED = Object.freeze({ kind: "REJECTED" as const });
|
|
const ABORTED = Object.freeze({ kind: "ABORTED" as const });
|
|
const TIMEOUT = Object.freeze({ kind: "TIMEOUT" as const });
|
|
const CLOCK_FAILED = Object.freeze({ kind: "CLOCK_FAILED" as const });
|
|
|
|
/**
|
|
* Realtime's one abort/deadline race, on the kernel abortable operation.
|
|
* Settles with whichever comes first: the task's value or rejection (a
|
|
* synchronous throw counts as one), `signal` aborting, or `deadline`
|
|
* resolving. A deadline that throws or rejects on its own is CLOCK_FAILED.
|
|
* Nothing starts when `signal` is already aborted.
|
|
*
|
|
* The task gets the operation signal, which aborts with `signal`, at the
|
|
* deadline and once the race is over. The deadline is armed before the task
|
|
* starts, so it wins a tie, but the task always starts (a cancel must not be
|
|
* skipped because the clock broke).
|
|
*/
|
|
export function raceRealtimeTask<Value>(
|
|
task: (signal: AbortSignal) => Value | PromiseLike<Value>,
|
|
signal?: AbortSignal,
|
|
deadline?: (signal: AbortSignal) => PromiseLike<unknown>,
|
|
): Promise<RealtimeRace<Value>> {
|
|
if (signal?.aborted) return Promise.resolve(ABORTED);
|
|
const timer = new AbortController();
|
|
const operation = createAbortableOperation({
|
|
signal,
|
|
...(deadline && {
|
|
timeoutMs: 0,
|
|
setTimer: (fire: () => void) =>
|
|
Promise.resolve(deadline(timer.signal)).then(fire, () =>
|
|
operation.close(),
|
|
),
|
|
clearTimer: () => timer.abort(),
|
|
}),
|
|
});
|
|
let running: Promise<Value>;
|
|
try {
|
|
running = Promise.resolve(task(operation.signal));
|
|
} catch (error) {
|
|
running = Promise.reject(error);
|
|
}
|
|
const raced = operation.race(running);
|
|
// Registered after the race, so the outcome is claimed first.
|
|
void running.then(operation.close, operation.close);
|
|
return raced.then((outcome) =>
|
|
outcome.kind === "VALUE"
|
|
? outcome
|
|
: outcome.kind === "REJECTED"
|
|
? REJECTED
|
|
: outcome.terminal === "CALLER_ABORT"
|
|
? ABORTED
|
|
: outcome.terminal === "DEADLINE"
|
|
? TIMEOUT
|
|
: CLOCK_FAILED,
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Best-effort delivery to an optional observation sink. A throwing sink never
|
|
* changes realtime control flow.
|
|
*/
|
|
export function observeRealtime<Observation extends object>(
|
|
sink: ((observation: Observation) => void) | undefined,
|
|
observation: Observation,
|
|
): void {
|
|
try {
|
|
sink?.(Object.freeze(observation));
|
|
} catch {
|
|
// Diagnostics never control realtime behavior.
|
|
}
|
|
}
|
|
|
|
/**
|
|
* A `raceRealtimeTask` deadline on a host timer instead of the injected
|
|
* clock, for bounds that must hold even when the clock itself hangs.
|
|
*/
|
|
export function timerDeadline(
|
|
delayMs: number,
|
|
schedule: (callback: () => void, delayMs: number) => unknown = (
|
|
callback,
|
|
delay,
|
|
) => setTimeout(callback, delay),
|
|
cancel: (handle: unknown) => void = (handle) =>
|
|
clearTimeout(handle as ReturnType<typeof setTimeout>),
|
|
): (signal: AbortSignal) => Promise<void> {
|
|
return (signal) =>
|
|
new Promise((resolve) => {
|
|
const handle = schedule(resolve, delayMs);
|
|
signal.addEventListener(
|
|
"abort",
|
|
() => {
|
|
try {
|
|
cancel(handle);
|
|
} catch {
|
|
// A broken scheduler cannot change the race outcome.
|
|
}
|
|
},
|
|
{ once: true },
|
|
);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Captures an external result through own data descriptors exactly once and
|
|
* returns a new canonical value. Callers that need to use the validated fields
|
|
* must use this returned snapshot rather than reading the source again.
|
|
*/
|
|
export function snapshotRealtimeResult<Value>(
|
|
value: unknown,
|
|
isValue: (candidate: unknown) => candidate is Value,
|
|
): RealtimeResult<Value> | null {
|
|
return parseRealtimeResult(value, isValue, false);
|
|
}
|
|
|
|
export function isRealtimeResult<Value>(
|
|
value: unknown,
|
|
isValue: (candidate: unknown) => candidate is Value,
|
|
): value is RealtimeResult<Value> {
|
|
return parseRealtimeResult(value, isValue, true) !== null;
|
|
}
|
|
|
|
export function isRealtimeTransportEventOutcome(
|
|
value: unknown,
|
|
): value is RealtimeTransportEventOutcome {
|
|
const snapshot = captureRealtimeDataSnapshot(value);
|
|
if (!snapshot || !snapshot.frozen) {
|
|
return false;
|
|
}
|
|
if (snapshot.values.kind === "CONTINUE") {
|
|
return hasExactSnapshotKeys(snapshot, ["kind"]);
|
|
}
|
|
if (
|
|
snapshot.values.kind !== "RECOVERY_COMMITTED" ||
|
|
!hasExactSnapshotKeys(snapshot, [
|
|
"checkpoint",
|
|
"kind",
|
|
"streamId",
|
|
]) ||
|
|
typeof snapshot.values.streamId !== "string"
|
|
) {
|
|
return false;
|
|
}
|
|
const checkpoint = captureRealtimeDataSnapshot(
|
|
snapshot.values.checkpoint,
|
|
);
|
|
return (
|
|
checkpoint !== null &&
|
|
checkpoint.frozen &&
|
|
hasExactSnapshotKeys(checkpoint, [
|
|
"lastAppliedSequence",
|
|
"recoveryMode",
|
|
"resumeCursor",
|
|
"streamEpoch",
|
|
]) &&
|
|
isRealtimeOpaqueIdentifier(snapshot.values.streamId) &&
|
|
isRealtimeOpaqueIdentifier(checkpoint.values.streamEpoch) &&
|
|
isCanonicalRealtimeSequence(
|
|
checkpoint.values.lastAppliedSequence,
|
|
) &&
|
|
(checkpoint.values.recoveryMode === "CURSOR"
|
|
? isRealtimeResumeCursor(checkpoint.values.resumeCursor)
|
|
: (checkpoint.values.recoveryMode === "SNAPSHOT_ONLY" ||
|
|
checkpoint.values.recoveryMode === "SESSION_REBUILD") &&
|
|
checkpoint.values.resumeCursor === null)
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Reads a plain record without invoking property accessors. Symbol keys,
|
|
* inherited shapes, non-enumerable fields and accessors are rejected. The
|
|
* returned null-prototype value map is immutable and detached from later
|
|
* property reads on the source object.
|
|
*/
|
|
export function captureRealtimeDataSnapshot(
|
|
value: unknown,
|
|
): RealtimeDataSnapshot | null {
|
|
try {
|
|
if (
|
|
!value ||
|
|
typeof value !== "object" ||
|
|
Array.isArray(value)
|
|
) {
|
|
return null;
|
|
}
|
|
const prototype = Object.getPrototypeOf(value);
|
|
if (
|
|
prototype !== Object.prototype &&
|
|
prototype !== null
|
|
) {
|
|
return null;
|
|
}
|
|
const extensible = Object.isExtensible(value);
|
|
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
const ownKeys = Reflect.ownKeys(descriptors);
|
|
if (ownKeys.some((key) => typeof key !== "string")) {
|
|
return null;
|
|
}
|
|
const keys = (ownKeys as string[]).sort();
|
|
const values = Object.create(null) as Record<string, unknown>;
|
|
let frozen = !extensible;
|
|
for (const key of keys) {
|
|
const descriptor = descriptors[key];
|
|
if (
|
|
!descriptor ||
|
|
!Object.hasOwn(descriptor, "value") ||
|
|
descriptor.enumerable !== true
|
|
) {
|
|
return null;
|
|
}
|
|
Object.defineProperty(values, key, {
|
|
configurable: false,
|
|
enumerable: true,
|
|
value: descriptor.value,
|
|
writable: false,
|
|
});
|
|
frozen =
|
|
frozen &&
|
|
descriptor.configurable === false &&
|
|
descriptor.writable === false;
|
|
}
|
|
return Object.freeze({
|
|
source: value,
|
|
keys: Object.freeze(keys),
|
|
values: Object.freeze(values),
|
|
frozen,
|
|
});
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function parseRealtimeResult<Value>(
|
|
value: unknown,
|
|
isValue: (candidate: unknown) => candidate is Value,
|
|
requireFrozenSource: boolean,
|
|
): RealtimeResult<Value> | null {
|
|
const snapshot = captureRealtimeDataSnapshot(value);
|
|
if (
|
|
!snapshot ||
|
|
(requireFrozenSource && !snapshot.frozen)
|
|
) {
|
|
return null;
|
|
}
|
|
if (
|
|
snapshot.values.ok === true &&
|
|
hasExactSnapshotKeys(snapshot, ["ok", "value"])
|
|
) {
|
|
let accepted: boolean;
|
|
try {
|
|
accepted = isValue(snapshot.values.value);
|
|
} catch {
|
|
return null;
|
|
}
|
|
return accepted
|
|
? realtimeSuccess(snapshot.values.value as Value)
|
|
: null;
|
|
}
|
|
if (
|
|
snapshot.values.ok !== false ||
|
|
!hasExactSnapshotKeys(snapshot, ["error", "ok"])
|
|
) {
|
|
return null;
|
|
}
|
|
const failure = parseRealtimeFailure(
|
|
snapshot.values.error,
|
|
requireFrozenSource,
|
|
);
|
|
return failure
|
|
? realtimeFailure(
|
|
failure.kind,
|
|
failure.operation,
|
|
failure.retryable,
|
|
)
|
|
: null;
|
|
}
|
|
|
|
function parseRealtimeFailure(
|
|
value: unknown,
|
|
requireFrozenSource: boolean,
|
|
): RealtimeFailure | null {
|
|
const snapshot = captureRealtimeDataSnapshot(value);
|
|
if (
|
|
!snapshot ||
|
|
(requireFrozenSource && !snapshot.frozen) ||
|
|
!hasExactSnapshotKeys(snapshot, [
|
|
"kind",
|
|
"operation",
|
|
"retryable",
|
|
]) ||
|
|
!FAILURE_KINDS.has(snapshot.values.kind) ||
|
|
!OPERATIONS.has(snapshot.values.operation) ||
|
|
typeof snapshot.values.retryable !== "boolean"
|
|
) {
|
|
return null;
|
|
}
|
|
return Object.freeze({
|
|
kind: snapshot.values.kind as RealtimeFailureKind,
|
|
operation: snapshot.values.operation as RealtimeOperation,
|
|
retryable: snapshot.values.retryable,
|
|
});
|
|
}
|
|
|
|
/** True when the snapshot's keys are exactly one of the given key sets. */
|
|
export function hasExactSnapshotKeys(
|
|
snapshot: RealtimeDataSnapshot,
|
|
...keySets: readonly (readonly string[])[]
|
|
): boolean {
|
|
return keySets.some((keySet) => {
|
|
const expected = [...keySet].sort();
|
|
return (
|
|
snapshot.keys.length === expected.length &&
|
|
snapshot.keys.every((key, index) => key === expected[index])
|
|
);
|
|
});
|
|
}
|