From 3fe28dec2e526cc45cf0bfa337e006d2dcce68c1 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 1 Nov 2026 22:04:48 +0900 Subject: [PATCH] =?UTF-8?q?fix(realtime):=20=EB=B0=B0=EB=9F=B4=EC=97=90?= =?UTF-8?q?=EC=84=9C=20=EA=B2=B0=EA=B3=BC=20=EC=83=9D=EC=84=B1=20=ED=95=A8?= =?UTF-8?q?=EC=88=98=EB=A5=BC=20=EB=82=B4=EB=B3=B4=EB=82=B4=EA=B3=A0=20?= =?UTF-8?q?=EB=8F=99=EA=B2=B0=20=EA=B7=9C=EC=B9=99=EC=9D=84=20=EC=A0=81?= =?UTF-8?q?=EB=8A=94=EB=8B=A4=20(04-01)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 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절 --- src/adapters/realtime/index.ts | 1 + .../realtime/live-poll-handoff-coordinator.ts | 5 + .../realtime/reconnect-coordinator.ts | 8 +- src/adapters/realtime/result.ts | 8 ++ .../realtime/sse/fetch-sse-connection.ts | 4 + .../websocket/websocket-connection.ts | 5 + .../live-poll-handoff-coordinator.test.ts | 19 +++ .../realtime-reconnect-coordinator.test.ts | 108 ++++++++++++++++++ 8 files changed, 157 insertions(+), 1 deletion(-) diff --git a/src/adapters/realtime/index.ts b/src/adapters/realtime/index.ts index a219ef49..e0093f31 100644 --- a/src/adapters/realtime/index.ts +++ b/src/adapters/realtime/index.ts @@ -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, diff --git a/src/adapters/realtime/live-poll-handoff-coordinator.ts b/src/adapters/realtime/live-poll-handoff-coordinator.ts index ceb4e769..5ab77f7c 100644 --- a/src/adapters/realtime/live-poll-handoff-coordinator.ts +++ b/src/adapters/realtime/live-poll-handoff-coordinator.ts @@ -97,6 +97,11 @@ export type LivePollHandoffCoordinatorDependencies = 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; diff --git a/src/adapters/realtime/reconnect-coordinator.ts b/src/adapters/realtime/reconnect-coordinator.ts index 4527428c..2e2653a3 100644 --- a/src/adapters/realtime/reconnect-coordinator.ts +++ b/src/adapters/realtime/reconnect-coordinator.ts @@ -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 = | 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, @@ -170,6 +175,7 @@ export type RealtimeReconnectCoordinatorDependencies< RealtimeReconnectAttemptSuccess > >; + /** Build the result with `realtimeSuccess`/`realtimeFailure`. */ confirmTransportBarrier( recovery: RealtimeCommittedRecovery, ): RealtimeResult; diff --git a/src/adapters/realtime/result.ts b/src/adapters/realtime/result.ts index 9bcb900e..3c9880db 100644 --- a/src/adapters/realtime/result.ts +++ b/src/adapters/realtime/result.ts @@ -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, ): Extract, { ok: true }> { diff --git a/src/adapters/realtime/sse/fetch-sse-connection.ts b/src/adapters/realtime/sse/fetch-sse-connection.ts index f1854baf..e7fcd788 100644 --- a/src/adapters/realtime/sse/fetch-sse-connection.ts +++ b/src/adapters/realtime/sse/fetch-sse-connection.ts @@ -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, diff --git a/src/adapters/realtime/websocket/websocket-connection.ts b/src/adapters/realtime/websocket/websocket-connection.ts index 592b328e..0417c313 100644 --- a/src/adapters/realtime/websocket/websocket-connection.ts +++ b/src/adapters/realtime/websocket/websocket-connection.ts @@ -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, diff --git a/tests/unit/realtime/live-poll-handoff-coordinator.test.ts b/tests/unit/realtime/live-poll-handoff-coordinator.test.ts index f3c1f9c5..49a1eacd 100644 --- a/tests/unit/realtime/live-poll-handoff-coordinator.test.ts +++ b/tests/unit/realtime/live-poll-handoff-coordinator.test.ts @@ -163,6 +163,25 @@ describe("live/poll authoritative writer handoff", () => { expect(highWatermark).toBe(1); }); + it("accepts an apply result only when it is frozen like realtimeSuccess builds it", async () => { + // Type-checks as RealtimeResult, but the handoff reuses the value + // it validated, so it requires a frozen result. + const plain: RealtimeResult = { ok: true, value: undefined }; + const results = [plain, realtimeSuccess(undefined)]; + const harness = createHarness({ + apply: vi.fn(async () => results.shift()!), + }); + const writer = harness.coordinator.currentWriter()!; + + await expect(writer.write("plain", 1)).resolves.toEqual( + realtimeFailure("MAPPING_CONTRACT_VIOLATION", "APPLY", false), + ); + await expect(writer.write("frozen", 1)).resolves.toMatchObject({ + ok: true, + value: { kind: "APPLIED", writer: "LIVE" }, + }); + }); + it("fails closed when a non-cooperative active writer fills the bounded tail", async () => { let firstSignal: AbortSignal | undefined; let firstIsCurrent: (() => boolean) | undefined; diff --git a/tests/unit/realtime/realtime-reconnect-coordinator.test.ts b/tests/unit/realtime/realtime-reconnect-coordinator.test.ts index 55826588..7a7b1b63 100644 --- a/tests/unit/realtime/realtime-reconnect-coordinator.test.ts +++ b/tests/unit/realtime/realtime-reconnect-coordinator.test.ts @@ -18,6 +18,8 @@ import { type RealtimeReconnectOutcome, type RealtimeReconnectSession, type RealtimeRecoveryReconnectDirective, + realtimeFailure as publicRealtimeFailure, + realtimeSuccess as publicRealtimeSuccess, } from "../../../src/adapters/realtime/index.ts"; import { defineReconnectPolicy, @@ -2232,3 +2234,109 @@ describe("transport failures through the reconnect coordinator", () => { }, ); }); + +describe("results that composition code hands the reconnect coordinator", () => { + // Composition code may import only the adapter barrel. Each case passes a + // value that type-checks as RealtimeReconnectOutcome. + it("retries a failure built with the barrel's realtimeFailure", async () => { + const clock = new ManualClock(); + const last = publicRealtimeFailure("CONNECT_TIMEOUT", "CONNECT"); + let attempts = 0; + const coordinator = createRealtimeReconnectCoordinator({ + policy: policy({ maxAttempts: 1 }), + environment: new MutableOnlineEnvironment(true), + clock, + random: () => 0.5, + confirmTransportBarrier: () => publicRealtimeSuccess(undefined), + attempt: () => ({ + result: + ++attempts === 1 + ? publicRealtimeFailure("CONNECT_TIMEOUT", "CONNECT") + : last, + }), + }); + + const running = coordinator.run(); + await flush(); + expect(clock.sleepCalls).toEqual([50]); + clock.advance(50); + + await expect(running).resolves.toBe(last); + expect(attempts).toBe(2); + }); + + const unfrozenFailure: RealtimeReconnectOutcome = { + result: { + ok: false, + error: { + kind: "CONNECT_TIMEOUT", + operation: "CONNECT", + retryable: true, + }, + }, + }; + const unfrozenError: RealtimeReconnectOutcome = { + result: Object.freeze({ + ok: false, + error: { + kind: "CONNECT_TIMEOUT", + operation: "CONNECT", + retryable: true, + }, + } as const), + }; + + it.each([ + ["a plain failure object", unfrozenFailure], + ["a frozen failure around a plain error", unfrozenError], + ] as const)( + "ends the run without a retry when an attempt returns %s", + async (_label, outcome) => { + const clock = new ManualClock(); + let attempts = 0; + const coordinator = createRealtimeReconnectCoordinator({ + policy: policy(), + environment: new MutableOnlineEnvironment(true), + clock, + confirmTransportBarrier: confirmationSucceeded, + attempt: () => { + attempts += 1; + return outcome; + }, + }); + + const running = coordinator.run(); + await flush(); + expect(clock.sleepCalls).toEqual([]); + await expect(running).resolves.toEqual( + realtimeFailure("PROTOCOL_MISMATCH", "CONNECT", false), + ); + expect(attempts).toBe(1); + }, + ); + + it("ends the run when classifyClosed returns a plain success object", async () => { + const clock = new ManualClock(); + const coordinator = createRealtimeReconnectCoordinator({ + policy: policy(), + environment: new MutableOnlineEnvironment(true), + clock, + confirmTransportBarrier: confirmationSucceeded, + attempt: () => + opened( + Object.freeze({ + classifyClosed: (): RealtimeReconnectOutcome => ({ + result: { ok: true, value: undefined }, + }), + close: vi.fn(), + waitClosed: closedSuccessfully, + }), + ), + }); + + await expect(coordinator.run()).resolves.toEqual( + realtimeFailure("PROTOCOL_MISMATCH", "CONNECT", false), + ); + expect(clock.sleepCalls).toEqual([]); + }); +});