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:
@@ -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<void>, but the handoff reuses the value
|
||||
// it validated, so it requires a frozen result.
|
||||
const plain: RealtimeResult<void> = { 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;
|
||||
|
||||
@@ -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<never> = {
|
||||
result: {
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "CONNECT_TIMEOUT",
|
||||
operation: "CONNECT",
|
||||
retryable: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
const unfrozenError: RealtimeReconnectOutcome<never> = {
|
||||
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<void> => ({
|
||||
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([]);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user