fix(realtime): 배럴에서 결과 생성 함수를 내보내고 동결 규칙을 적는다 (04-01)

문제: 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절
This commit is contained in:
DongHyeonka
2026-11-01 22:49:38 +09:00
parent eaa5b63571
commit 3fe28dec2e
8 changed files with 157 additions and 1 deletions
+1
View File
@@ -35,6 +35,7 @@ export {
type RealtimeReconnectSession,
type RealtimeRecoveryReconnectDirective,
} from "./reconnect-coordinator.ts";
export { realtimeFailure, realtimeSuccess } from "./result.ts";
export {
createLivePollHandoffCoordinator,
LIVE_POLL_HANDOFF_CEILINGS,
@@ -97,6 +97,11 @@ export type LivePollHandoffCoordinatorDependencies<Value> = Readonly<{
authoritativeCheckpointEstablished: true;
}>;
limits: LivePollHandoffLimits;
/**
* `apply` and `establishAuthoritativeCheckpoint` build their results with
* `realtimeSuccess`/`realtimeFailure`; a result that is not frozen fails
* with MAPPING_CONTRACT_VIOLATION.
*/
apply(input: Readonly<{
writer: LivePollWriterKind;
generation: number;
@@ -41,6 +41,10 @@ export type RealtimeCommittedRecovery = Extract<
/**
* The hint is coordinator-private metadata. A terminal RealtimeResult can
* therefore be returned without rewriting its failure.
*
* Build `result` with `realtimeSuccess`/`realtimeFailure`. The coordinator
* returns the exact object it validated, so a result that is not frozen ends
* the run with PROTOCOL_MISMATCH and no retry.
*/
export type RealtimeReconnectOutcome<Value> =
| Readonly<{
@@ -89,7 +93,8 @@ export type RealtimeReconnectCloseClassification =
/**
* The receipt stays strongly typed until `classifyClosed`. `close` must be
* terminal and idempotent.
* terminal and idempotent. `classifyClosed` builds its results as
* RealtimeReconnectOutcome says.
*/
export type RealtimeReconnectSession<
ClosedReceipt = RealtimeReconnectOutcome<void>,
@@ -170,6 +175,7 @@ export type RealtimeReconnectCoordinatorDependencies<
RealtimeReconnectAttemptSuccess<ClosedReceipt>
>
>;
/** Build the result with `realtimeSuccess`/`realtimeFailure`. */
confirmTransportBarrier(
recovery: RealtimeCommittedRecovery,
): RealtimeResult<void>;
+8
View File
@@ -43,6 +43,14 @@ export type RealtimeDataSnapshot = Readonly<{
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 }> {
@@ -59,6 +59,10 @@ export type FetchSseReadInput = Readonly<{
* Runs after the response and stream contract are validated but before any
* event bytes are consumed. A reconnect bridge can hold this gate until the
* exact recovery checkpoint's replay barrier is confirmed.
*
* `onOpen` and `onEvent` build their results with
* `realtimeSuccess`/`realtimeFailure`; a result that is not frozen fails
* closed.
*/
onOpen?(
signal: AbortSignal,
@@ -158,6 +158,11 @@ export type WebSocketConnectionDependencies = Readonly<{
endpoint: string,
protocol: typeof REALTIME_WEBSOCKET_PROTOCOL,
): WebSocketFacade;
/**
* `onEvent` and `onSubscribed` build their results with
* `realtimeSuccess`/`realtimeFailure`; a result that is not frozen fails
* closed.
*/
onEvent(
frame: WebSocketEventFrame,
signal: AbortSignal,