fix(realtime): poll execute에 descriptor 타입을 싣고 V3 결과 대응표를 둔다

문제: poll `execute`가 받는 `input.operation`은 `BoundedPollOperation`
(`InstalledHttpContract<unknown, unknown, unknown>`)이다. 권하는 대로
`executor.execute(input.operation, x, …)`를 부르면 `Input`이 `unknown`이
되어 `x`는 아무 값이나 통과하고 `outcome.value`도 `unknown`이다. 입력이
틀리면 런타임 `CONTRACT_VIOLATION`(INPUT_INVALID)으로만 드러난다. 타입을
지키려면 클로저 descriptor를 써야 해서 1103/04-01의 잔여 위험(다른 행을
실행) 쪽이 유리해진다. 또 V3 결과 9종을 poll 결과로 바꾸는 대응표가 없다.
repo의 유일한 V3 조합 예(테스트)는 SUCCESS 외 전부를 retryable
PROVIDER_UNAVAILABLE로 바꿔, 옮기면 401·403·입력 거절도 maxAttempts번
다시 요청된다.

고른 방법: 리뷰 선택지 (b) + (c).
- `createBoundedPollCoordinator`와 `BoundedPollCoordinatorDependencies`에
  `Operation extends BoundedPollOperation = BoundedPollOperation`을 더하고
  `operation`·`input.operation`을 `Operation`으로 둔다. `operation`에서
  추론되므로 실행기 호출이 기능 descriptor의 입력·출력 타입으로 검사된다.
  런타임 코드는 바뀌지 않는다.
- 설계 9.2에 V3 결과 kind마다 poll 결과(kind, retryable, retryAfterMs)를
  적은 표를 두고, 13.1 PROVIDER_UNAVAILABLE 행에서 그 표를 가리킨다.
  9.2 "auth에서 lease 종료", 9.3 "401은 attempt를 끝낸다", 9.4, 13.1과
  맞췄다. `retryAfterMs`는 값이 있을 때만 둔다(빈 칸은 모양 오류).
- 테스트 조합 예를 표대로 바꿨다(`pollAttemptResult`). 503 재시도
  테스트는 같은 결과다(503 PROBLEM → retryable PROVIDER_UNAVAILABLE).
- 테스트: 틀린 입력에 `@ts-expect-error`, 출력을 기능 타입으로 받는 타입
  테스트 1건. 401·403이 요청 1번으로 lease를 끝내는 테스트 2건.
버린 대안:
- (d) 대응 함수를 bootstrap이나 recipe에 두기. realtime 어댑터는
  adapters/http 타입을 import할 수 없고, 레시피 번들과 제거 드릴 범위가
  바뀐다.
- `BoundedPollOperation` 자체를 제네릭으로 바꾸기. application 정책의
  공개 이름이 바뀐다. 제약으로만 두면 기존 이름이 그대로다.

위험·한계:
- 기존 호출은 그대로 컴파일된다. `Value`를 직접 적은 호출은 `Operation`이
  기본값이라 예전처럼 `unknown`이다. 타입을 원하면 둘 다 적거나 추론에
  맡긴다(타입 주석과 9.2에 적음). 그래서 `!`를 붙이지 않았다. 단, 추론에
  맡긴 호출이 descriptor 타입과 다른 입력을 실행기에 넘기고 있었다면 이제
  check:types가 실패한다. 이 커밋이 잡으려는 결함이다.
- 표는 조합 코드가 따를 규칙이고 강제 수단은 없다. 템플릿은 poll
  `execute` 기본 구현을 주지 않는다(리뷰 재검토 조건).
- 409·410의 `CURSOR_EXPIRED` 행은 reset 계약이 있는 기능만 해당한다.
  테스트 계약에는 없어 테스트 예는 그 갈래가 없다.
- CHANGELOG 행은 이 커밋에 없다. CHANGELOG 담당이 더한다.

검증: desktop batch에서 확인.
- corepack pnpm check:types:test
- node scripts/run-vitest.ts run tests/unit/realtime/bounded-poll-coordinator.test.ts
- RED: 부모 커밋의 src에서 check:types:test가 실패한다.
  bounded-poll-coordinator.test.ts의 `@ts-expect-error` 줄이 TS2578(쓰이지
  않은 지시문, 입력이 `unknown`이라 `{ size: 20 }`이 통과), 그 아래
  `pollAttemptResult<…>(outcome)`이 TS2345(`outcome.value`가 `unknown`).
  vitest 테스트는 양쪽에서 통과한다.
- lint, check:architecture, verify:documentation

Refs: 1106/04-02
This commit is contained in:
DongHyeonka
2026-11-06 05:32:47 +09:00
parent 0438c3f248
commit 6f06e7702f
4 changed files with 203 additions and 30 deletions
@@ -1677,6 +1677,35 @@ attempt마다 요청이 최대 3번이다. `execute`는 서버·네트워크 실
command/mutation, GraphQL subscription, Connect/gRPC-Web server stream과 arbitrary
status URL은 poll하지 않는다. TanStack Query retry도 `false`여야 한다.
coordinator는 받은 descriptor의 타입도 `input.operation`에 그대로 싣는다
(`createBoundedPollCoordinator<Value, Operation>`, `Operation`은 `operation`에서
추론, 1106/04-02). 그래서 `execute` 안의 `executor.execute(input.operation, …)`는
기능 descriptor의 입력·출력 타입으로 검사된다. `Value`만 직접 적으면 `Operation`이
`BoundedPollOperation`으로 돌아가 입력과 출력이 `unknown`이 된다. 둘 다 적거나
추론에 맡긴다.
`execute`는 실행기 결과를 아래 표대로 poll attempt 결과로 바꾼다(1106/04-02).
poll이 재시도하는 kind는 `retryable: true`인 `CONNECT_TIMEOUT`·`RATE_LIMITED`·
`PROVIDER_UNAVAILABLE`뿐이고, `retryAfterMs`는 뒤 둘만 읽는다.
| V3 결과 `kind` | poll attempt 결과 |
| --- | --- |
| `SUCCESS` | `ok: true`, `kind: "VALUE"`, `value`, terminal 판정에 쓸 `state`. 결과에 본문 크기가 없으므로 `responseBytes`는 `0`을 둔다. 본문 상한은 실행기가 `frontend.responseByteLimit`으로 지킨다(넘으면 `CONTRACT_VIOLATION`). 그래서 poll descriptor의 `responseByteLimit`을 lease `maxResponseBytes` 이하로 둔다 |
| `PROBLEM` | `metadata.status`가 5xx·`408`·`425`이면 `PROVIDER_UNAVAILABLE`, `retryable: true`, `retryAfterMs`는 `metadata.retryAfterMs`. 그 밖의 status는 다시 보내도 같은 답이라 `PROTOCOL_MISMATCH`, `retryable: false`. 9.4의 reset 계약이 있는 `409`·`410`만 `CURSOR_EXPIRED`, `retryable: false` |
| `UNAUTHENTICATED` | `AUTH_REQUIRED`, `retryable: false`. lease가 끝나고, session owner가 회복한 뒤 새 lease를 연다(9.3) |
| `FORBIDDEN` | `FORBIDDEN`, `retryable: false` |
| `RATE_LIMITED` | `RATE_LIMITED`, `retryable: true`, `retryAfterMs`는 결과의 `retryAfterMs` |
| `CONTRACT_VIOLATION` | `metadata.status`가 5xx·`408`·`425`이면 쓸 수 있는 problem 본문 없이 온 서버 장애라 `PROBLEM`의 장애 행과 같다. 그 밖(입력 거절 `INPUT_INVALID`, 응답 schema·크기 위반)은 `PROTOCOL_MISMATCH`, `retryable: false` |
| `TRANSPORT_FAILURE` | `failure.kind`가 `TIMEOUT`이면 `CONNECT_TIMEOUT`, `retryable: true`. `ABORTED_BY_CALLER`면 `ABORTED`, `ABORTED_BY_SCOPE`면 `SCOPE_FENCED`, 둘 다 `retryable: false`. 나머지(`NETWORK_FAILURE` 등)는 `PROVIDER_UNAVAILABLE`, `retryable: true`. 실행기가 끝낸 transport 실패의 `failure.retryable`은 모두 `false`라 옮기지 않는다 |
| `CANCELLED` | `ABORTED`, `retryable: false` |
| `AUTH_INTEGRATION_FAILURE` | `reason`이 `CREDENTIAL_OWNER_UNAVAILABLE`이면 `PROVIDER_UNAVAILABLE`, `retryable: true`. 그 밖은 구성 결함이라 `PROTOCOL_MISMATCH`, `retryable: false`. 어느 쪽도 로그아웃 경로로 보내지 않는다 |
실패 결과의 `operation`은 모두 `"POLL"`이다. `retryAfterMs`는 값이 있을 때만
칸을 둔다. 값이 `undefined`인 칸은 모양이 틀린 결과라 lease가 `PROTOCOL_MISMATCH`로
끝난다. lease 상태 검사가 결과 해석보다 먼저라, 그사이 hidden·offline·scope
변경·close가 있었으면 표와 상관없이 그 kind로 끝난다. 이 표를 따르는 조합 예는
`tests/unit/realtime/bounded-poll-coordinator.test.ts`의 `pollAttemptResult`다.
한 lease는 다음 조건 중 먼저 발생하는 시점에 종료한다.
- terminal state
@@ -1963,7 +1992,7 @@ credential을 보호할 수 있다고 주장하지 않는다.
| `AUTH_REQUIRED` | session expired/recovery 실패 | sign-in UX |
| `FORBIDDEN` | stream/resource 거절 | retry 없음 |
| `RATE_LIMITED` | connection/request/provider limit | bounded server hint |
| `PROVIDER_UNAVAILABLE` | backend/push/hosting unavailable. 환경은 online인데 서버·프록시에 닿지 않은 것(SSE fetch·reader 거절, WebSocket `error`)도 이 kind다(1103/04-04, `retryable: true`). poll은 `execute`가 돌려준 결과의 kind를 쓴다. V3 실행기는 fetch 거절을 던지지 않고 `NETWORK_FAILURE` 결과로 돌려주므로, `execute`가 그 결과를 이 kind로 바꾼다. reconnect coordinator는 조합 코드의 `attempt`·`waitClosed`가 던지거나 거절해도 이 kind로 보고 backoff로 재시도한다(operation `CONNECT`·`RECEIVE`, `retryable: true`, 1106/04-01). 연결 실패를 던지는 라이브러리를 감싼 transport도 회복하게 하려는 규칙이다. 그래서 endpoint 같은 설정 검사는 `attempt` 밖, 조합 코드가 bridge를 만들 때 한다. SSE·WebSocket 연결 생성은 틀린 endpoint에 `TypeError`를 던지고, `attempt` 안이면 그 오류가 서버 장애처럼 예산 끝까지 재시도된다. stream coordinator의 recovery deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: false`). live↔Poll handoff coordinator의 checkpoint deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: true`) | bounded retry 또는 degraded. stream coordinator 마감은 재연결로 풀리지 않는다: task가 settle할 때까지 `DRAINING`을 유지한다. settle 뒤 recovery 마감은 다음 event가 recovery부터 하고, close 마감은 `CLOSED`가 된다. handoff checkpoint 마감은 그 전환을 fail-close하므로 새 handoff만 돌 수 있다. handoff close 마감 뒤에는 writer·checkpoint task가 settle하면 다시 부른 `close()`가 성공한다 |
| `PROVIDER_UNAVAILABLE` | backend/push/hosting unavailable. 환경은 online인데 서버·프록시에 닿지 않은 것(SSE fetch·reader 거절, WebSocket `error`)도 이 kind다(1103/04-04, `retryable: true`). poll은 `execute`가 돌려준 결과의 kind를 쓴다. V3 실행기는 fetch 거절을 던지지 않고 `NETWORK_FAILURE` 결과로 돌려주므로, `execute`가 그 결과를 이 kind로 바꾼다(V3 결과별 대응은 9.2 표). reconnect coordinator는 조합 코드의 `attempt`·`waitClosed`가 던지거나 거절해도 이 kind로 보고 backoff로 재시도한다(operation `CONNECT`·`RECEIVE`, `retryable: true`, 1106/04-01). 연결 실패를 던지는 라이브러리를 감싼 transport도 회복하게 하려는 규칙이다. 그래서 endpoint 같은 설정 검사는 `attempt` 밖, 조합 코드가 bridge를 만들 때 한다. SSE·WebSocket 연결 생성은 틀린 endpoint에 `TypeError`를 던지고, `attempt` 안이면 그 오류가 서버 장애처럼 예산 끝까지 재시도된다. stream coordinator의 recovery deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: false`). live↔Poll handoff coordinator의 checkpoint deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: true`) | bounded retry 또는 degraded. stream coordinator 마감은 재연결로 풀리지 않는다: task가 settle할 때까지 `DRAINING`을 유지한다. settle 뒤 recovery 마감은 다음 event가 recovery부터 하고, close 마감은 `CLOSED`가 된다. handoff checkpoint 마감은 그 전환을 fail-close하므로 새 handoff만 돌 수 있다. handoff close 마감 뒤에는 writer·checkpoint task가 settle하면 다시 부른 `close()`가 성공한다 |
| `PROTOCOL_MISMATCH` | version/subprotocol/content type. poll `execute`가 던지거나 모양이 틀린 결과를 돌려준 것도 이 kind다. 조합 코드 결함이라 서버 장애로 재시도하지 않는다(1105/04-02, `retryable: false`). reconnect coordinator에서는 `classifyClosed`(operation `CONNECT`)나 `confirmTransportBarrier`(operation `RECOVER`)가 던진 것이 이 kind다. reconnect `attempt`·`waitClosed`의 던짐은 `PROVIDER_UNAVAILABLE`이다(1106/04-01). poll `execute`는 던지지 않는 V3 실행기를 감싸고, `attempt`는 던질 수 있는 연결 API를 감싸기 때문이다 | terminal/rollout rollback |
| `MALFORMED_EVENT` | state-bearing syntax/schema/exact-key 실패 | cursor 미진행, freshness `UNKNOWN`, close + registered recovery |
| `MAPPING_CONTRACT_VIOLATION` | validated DTO의 registered mapper 실패 | effect/cache/cursor write 0, close + registered recovery |
@@ -94,19 +94,30 @@ export type BoundedPollObservation = Readonly<{
outcome?: "VALUE" | "UNCHANGED" | "TERMINAL" | RealtimeFailureKind;
}>;
export type BoundedPollCoordinatorDependencies<Value> = Readonly<{
/**
* 1106/04-02. `Operation` is the descriptor's own type, so the executor call
* in `execute` checks the feature's input and output types. It is inferred
* from `operation`; a caller that writes `Value` writes both
* (`createBoundedPollCoordinator<Value, typeof operation>`), or `Operation`
* falls back to `BoundedPollOperation` and the executor sees `unknown`.
*/
export type BoundedPollCoordinatorDependencies<
Value,
Operation extends BoundedPollOperation = BoundedPollOperation,
> = Readonly<{
policy: PollLeasePolicy;
/**
* The V3 descriptor `execute` runs (`BoundedPollOperation`). Creation
* refuses one whose `frontend.retryBudget` is not 0, and every `execute`
* call receives this same object as `input.operation`.
*/
operation: BoundedPollOperation;
operation: Operation;
/**
* Returns every outcome as a result, server and network failures included
* (the V3 executor returns a rejected fetch as NETWORK_FAILURE). A throw,
* like a result of the wrong shape, ends the lease with PROTOCOL_MISMATCH
* and is not retried: it is a composition defect, not a server outage.
* Design 9.2 maps each V3 executor outcome to a result.
*/
execute(input: Readonly<{
operationId: string;
@@ -116,7 +127,7 @@ export type BoundedPollCoordinatorDependencies<Value> = Readonly<{
* for the same path: a descriptor with `retryBudget: 2` sends up to three
* requests per attempt.
*/
operation: BoundedPollOperation;
operation: Operation;
attempt: number;
/**
* Hard response-body ceiling that must be enforced before decoding.
@@ -142,8 +153,11 @@ const POLL_RETRY_AFTER_FAILURE_KINDS = Object.freeze([
"PROVIDER_UNAVAILABLE",
] as const satisfies readonly RealtimeFailureKind[]);
export function createBoundedPollCoordinator<Value>(
dependencies: BoundedPollCoordinatorDependencies<Value>,
export function createBoundedPollCoordinator<
Value,
Operation extends BoundedPollOperation = BoundedPollOperation,
>(
dependencies: BoundedPollCoordinatorDependencies<Value, Operation>,
): BoundedPollCoordinator<Value> {
const policy = definePollLeasePolicy(dependencies.policy);
const operation = dependencies.operation;
+2 -1
View File
@@ -36,7 +36,8 @@ export type PollLeasePolicy = Readonly<{
* pass it to the executor (`createContractHttpExecutor().execute`). The
* executor reads its retry ceiling from `frontend.retryBudget`, so a budget of
* 0 is what makes one poll attempt one physical request; the poll coordinator
* owns every retry between attempts.
* owns every retry between attempts. This type is the bound: the coordinator
* keeps the descriptor's own input and output types (1106/04-02).
*/
export type BoundedPollOperation = InstalledHttpContract<
unknown,
@@ -1,11 +1,15 @@
import { describe, expect, it, vi } from "vitest";
import type { ClockPort } from "../../../src/application/ports/clock-port.ts";
import type { RealtimeFailureKind } from "../../../src/application/ports/realtime/shared.ts";
import {
definePollLeasePolicy,
type BoundedPollOperation,
} from "../../../src/application/policies/bounded-polling.ts";
import { createContractHttpExecutor } from "../../../src/adapters/http/index.ts";
import {
createContractHttpExecutor,
type HttpExecutionOutcome,
} from "../../../src/adapters/http/index.ts";
import {
createBoundedPollCoordinator,
type BoundedPollAttemptResult,
@@ -1090,6 +1094,71 @@ describe("bounded poll coordinator", () => {
});
});
/**
* Design 9.2's table (1106/04-02): every V3 executor outcome as a poll attempt
* result. `retryAfterMs` is present only with a value; an empty key is a
* malformed result.
*/
function pollAttemptResult<Value>(
outcome: HttpExecutionOutcome<Value, unknown>,
): BoundedPollAttemptResult<Value> {
const failed = (
kind: RealtimeFailureKind,
retryable: boolean,
retryAfterMs?: number,
): BoundedPollAttemptResult<Value> => ({
ok: false,
error: {
kind,
operation: "POLL",
retryable,
...(retryAfterMs === undefined ? {} : { retryAfterMs }),
},
});
const outage = (status: number | undefined) =>
status !== undefined &&
(status >= 500 || status === 408 || status === 425);
switch (outcome.kind) {
case "SUCCESS":
return {
ok: true,
value: { kind: "VALUE", value: outcome.value, responseBytes: 0 },
};
case "PROBLEM":
case "CONTRACT_VIOLATION":
return outage(outcome.metadata?.status)
? failed(
"PROVIDER_UNAVAILABLE",
true,
outcome.metadata?.retryAfterMs,
)
: failed("PROTOCOL_MISMATCH", false);
case "UNAUTHENTICATED":
return failed("AUTH_REQUIRED", false);
case "FORBIDDEN":
return failed("FORBIDDEN", false);
case "RATE_LIMITED":
return failed("RATE_LIMITED", true, outcome.retryAfterMs);
case "TRANSPORT_FAILURE":
if (outcome.failure.kind === "TIMEOUT") {
return failed("CONNECT_TIMEOUT", true);
}
if (outcome.failure.kind === "ABORTED_BY_CALLER") {
return failed("ABORTED", false);
}
if (outcome.failure.kind === "ABORTED_BY_SCOPE") {
return failed("SCOPE_FENCED", false);
}
return failed("PROVIDER_UNAVAILABLE", true);
case "CANCELLED":
return failed("ABORTED", false);
case "AUTH_INTEGRATION_FAILURE":
return outcome.reason === "CREDENTIAL_OWNER_UNAVAILABLE"
? failed("PROVIDER_UNAVAILABLE", true)
: failed("PROTOCOL_MISMATCH", false);
}
}
// 1103/04-01. The natural composition: `execute` runs the poll's descriptor on
// the app's V3 executor. The executor's own retries would turn one poll attempt
// into up to three requests, hidden from the poll's budget and observations.
@@ -1115,7 +1184,27 @@ describe("a poll attempt on the V3 executor", () => {
isCurrent: () => true,
});
function pollOn(descriptor: BoundedPollOperation, clock: ManualClock) {
// 1106/04-02. Typed by the feature's own descriptor, with no cast.
const typedPollOnly = Object.freeze({
...TEST_LIST_HTTP_CONTRACT,
frontend: Object.freeze({
...TEST_LIST_HTTP_CONTRACT.frontend,
retryBudget: 0 as const,
}),
});
function pollOn(
descriptor: BoundedPollOperation,
clock: ManualClock,
respond: () => Response = () =>
new Response(
JSON.stringify({ type: "about:blank", title: "down", status: 503 }),
{
status: 503,
headers: { "content-type": "application/problem+json" },
},
),
) {
const requests: string[] = [];
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",
@@ -1124,13 +1213,7 @@ describe("a poll attempt on the V3 executor", () => {
attachCredentials: () => ({ kind: "READY", headers: {} }),
fetcher: async (request) => {
requests.push(String(request));
return new Response(
JSON.stringify({ type: "about:blank", title: "down", status: 503 }),
{
status: 503,
headers: { "content-type": "application/problem+json" },
},
);
return respond();
},
sleep: async () => undefined,
random: () => 0.5,
@@ -1143,31 +1226,77 @@ describe("a poll attempt on the V3 executor", () => {
clock,
random: () => 0.5,
// 1103/04-01. Runs the descriptor the coordinator hands back, never a
// closed-over one.
// closed-over one, and maps its outcome by the 9.2 table (1106/04-02).
execute: async ({ operation: polled, signal }) => {
const outcome = await executor.execute(
polled,
{ limit: 20 },
{ routeId: "TEST_ROUTE", scope, signal },
);
return outcome.kind === "SUCCESS"
? {
ok: true,
value: { kind: "VALUE", value: outcome.value, responseBytes: 1 },
}
: {
ok: false,
error: {
kind: "PROVIDER_UNAVAILABLE",
operation: "POLL",
retryable: true,
},
};
return pollAttemptResult(outcome);
},
});
return { coordinator, requests };
}
// 1106/04-02. `input.operation` keeps the descriptor's own type, so the
// executor call in `execute` is checked against the feature's input and
// output types. check:types is the assertion; the body never runs.
it("types the executor call in execute by the poll descriptor", () => {
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 2,
attachCredentials: () => ({ kind: "READY", headers: {} }),
fetcher: async () => new Response(null, { status: 503 }),
});
const coordinator = createBoundedPollCoordinator({
policy: pollPolicy,
operation: typedPollOnly,
environment: new MutableEnvironment(),
execute: async ({ operation: polled, signal }) => {
const context = { routeId: "TEST_ROUTE", scope, signal };
// @ts-expect-error 1106/04-02: the list descriptor takes `limit`, not `size`.
await executor.execute(polled, { size: 20 }, context);
const outcome = await executor.execute(polled, { limit: 20 }, context);
return pollAttemptResult<readonly Readonly<{ id: string; name: string }>[]>(outcome);
},
});
expect(coordinator.getState()).toBe("IDLE");
});
// 1106/04-02. The 9.2 table ends the lease on an auth answer. The old
// example here retried every non-SUCCESS outcome as a server outage.
it.each([
[401, "AUTH_REQUIRED"],
[403, "FORBIDDEN"],
] as const)(
"ends the lease on the first %i through the 9.2 table",
async (status, kind) => {
const clock = new ManualClock();
const { coordinator, requests } = pollOn(
typedPollOnly,
clock,
() => new Response(null, { status }),
);
let result: unknown = null;
void coordinator.run().then((value) => {
result = value;
});
for (let turn = 0; turn < 400 && result === null; turn += 1) {
clock.advance(1_000);
await flush();
}
expect(result).toEqual({
ok: false,
error: { kind, operation: "POLL", retryable: false },
});
expect(requests).toHaveLength(1);
},
);
it("refuses the default read descriptor, whose executor retries", () => {
expect(TEST_LIST_HTTP_CONTRACT.frontend.retryBudget).toBe(2);
expect(() =>