diff --git a/docs/architecture/realtime-events-web-push-and-bounded-polling.md b/docs/architecture/realtime-events-web-push-and-bounded-polling.md index a0d3a2e7..428776d0 100644 --- a/docs/architecture/realtime-events-web-push-and-bounded-polling.md +++ b/docs/architecture/realtime-events-web-push-and-bounded-polling.md @@ -1667,7 +1667,8 @@ poll coordinator는 실행할 V3 descriptor(`InstalledHttpContract`, 조립된 (`http-execution-v3.ts` `retryCeiling`). 이 값을 descriptor에서 읽으므로, poll에 묶은 descriptor가 0이면 실행기의 `maxRetryAttempts`(`MAX_RETRY_ATTEMPTS`)와 상관없이 poll 한 attempt가 요청 한 번이다. 같은 descriptor를 `execute` 안에서 실행기에 -넘긴다. 기능의 기본 GET descriptor(`create:feature`는 `retryBudget: 2`)는 생성 때 +넘긴다. `execute`는 서버·네트워크 실패도 결과로 돌려준다. 던지면 조합 코드 +결함으로 보고 재시도 없이 `PROTOCOL_MISMATCH`로 lease를 끝낸다(1105/04-02). 기능의 기본 GET descriptor(`create:feature`는 `retryBudget: 2`)는 생성 때 거절된다. poll 전용 operation을 따로 등록한다. V3에는 401 재전송이 없다. command/mutation, GraphQL subscription, Connect/gRPC-Web server stream과 arbitrary status URL은 poll하지 않는다. TanStack Query retry도 `false`여야 한다. @@ -1958,8 +1959,8 @@ 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`, poll `execute` 거절)도 세 transport 모두 이 kind다(1103/04-04, `retryable: true`). 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 | terminal/rollout rollback | +| `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로 바꾼다. 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`) | 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 | | `EVENT_CONFLICT` | 같은 ID/sequence가 다른 event를 가리킴 | terminal protocol conflict + resync/rollback | diff --git a/src/adapters/realtime/polling/bounded-poll-coordinator.ts b/src/adapters/realtime/polling/bounded-poll-coordinator.ts index c92908d3..f2f73202 100644 --- a/src/adapters/realtime/polling/bounded-poll-coordinator.ts +++ b/src/adapters/realtime/polling/bounded-poll-coordinator.ts @@ -101,6 +101,12 @@ export type BoundedPollCoordinatorDependencies = Readonly<{ * refuses one whose `frontend.retryBudget` is not 0. */ operation: BoundedPollOperation; + /** + * 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. + */ execute(input: Readonly<{ operationId: string; attempt: number; @@ -300,7 +306,7 @@ export function createBoundedPollCoordinator( } attempts += 1; - let result: BoundedPollAttemptResult; + let result: BoundedPollAttemptResult | null; const attemptOutcome = await awaitWithinLease( () => trackWork( @@ -320,12 +326,14 @@ export function createBoundedPollCoordinator( if (attemptOutcome.kind === "VALUE") { result = attemptOutcome.value; } else if (attemptOutcome.kind === "REJECTED") { - // 1103/04-04. No server answered; OFFLINE is the environment's. - result = realtimeFailure( - controller.signal.aborted ? "ABORTED" : "PROVIDER_UNAVAILABLE", - "POLL", - !controller.signal.aborted, - ); + // 1105/04-02. `execute` returns every failure as a result; the V3 + // executor already returns a rejected fetch as NETWORK_FAILURE. A + // throw is a composition defect, read below like a malformed + // result, not retried as a server outage. One caused by this + // lease's abort ends with the abort's reason. + result = controller.signal.aborted + ? realtimeFailure("ABORTED", "POLL", false) + : null; } else { if (attemptOutcome.kind === "CLOCK_FAILED") { controller.abort(); @@ -374,7 +382,8 @@ export function createBoundedPollCoordinator( return pollFailure("POLL_BUDGET_EXHAUSTED"); } - const parsedResult = parseAttemptResult(result); + const parsedResult = + result === null ? null : parseAttemptResult(result); if (!parsedResult) { return pollFailure("PROTOCOL_MISMATCH"); } diff --git a/tests/unit/realtime/bounded-poll-coordinator.test.ts b/tests/unit/realtime/bounded-poll-coordinator.test.ts index c2c9cfd3..cbd8e735 100644 --- a/tests/unit/realtime/bounded-poll-coordinator.test.ts +++ b/tests/unit/realtime/bounded-poll-coordinator.test.ts @@ -903,47 +903,86 @@ describe("bounded poll coordinator", () => { }); }); - // 1103/04-04. A rejected executor means the request did not reach a server - // that answered. It is PROVIDER_UNAVAILABLE, retried within the lease like - // one the executor reports; OFFLINE comes only from the environment. - it("retries a throwing executor as PROVIDER_UNAVAILABLE within the lease", async () => { + // 1105/04-02. `execute` returns server and network failures as results (the + // V3 executor returns a rejected fetch as NETWORK_FAILURE). A throw is a + // composition defect, like a malformed result: the lease ends at once with + // PROTOCOL_MISMATCH instead of retrying it as a server outage until the + // budget runs out. + it.each([ + ["an async execute that rejects", async () => { + throw new TypeError("Cannot read properties of undefined"); + }], + ["an execute that throws before returning", () => { + throw new TypeError("Cannot read properties of undefined"); + }], + ] as const)( + "ends the lease with PROTOCOL_MISMATCH for %s", + async (_label, body) => { + const clock = new ManualClock(); + const observations: BoundedPollObservation[] = []; + const execute = vi.fn( + body as () => Promise>, + ); + const coordinator = createBoundedPollCoordinator({ + policy, + operation, + environment: new MutableEnvironment(), + clock, + random: () => 0.5, + execute, + observe: (observation) => observations.push(observation), + }); + + let result: unknown = null; + void coordinator.run().then((value) => { + result = value; + }); + for (let turn = 0; turn < 120 && result === null; turn += 1) { + clock.advance(1_000); + await flush(); + } + + expect(execute).toHaveBeenCalledTimes(1); + expect(result).toEqual({ + ok: false, + error: { + kind: "PROTOCOL_MISMATCH", + operation: "POLL", + retryable: false, + }, + }); + expect(observations).toEqual([ + { kind: "LEASE_STARTED" }, + { kind: "LEASE_STOPPED", outcome: "PROTOCOL_MISMATCH" }, + ]); + expect(coordinator.getState()).toBe("IDLE"); + }, + ); + + it("keeps ABORTED when execute rejects because the caller aborted", async () => { const clock = new ManualClock(); - const observations: BoundedPollObservation[] = []; - const execute = vi.fn(async (): Promise> => { - throw new TypeError("Failed to fetch"); - }); + const caller = new AbortController(); const coordinator = createBoundedPollCoordinator({ policy, operation, environment: new MutableEnvironment(), clock, - random: () => 0.5, - execute, - observe: (observation) => observations.push(observation), + execute: ({ signal }) => + new Promise>((_resolve, reject) => { + signal.addEventListener( + "abort", + () => reject(new DOMException("Aborted", "AbortError")), + { once: true }, + ); + caller.abort(); + }), }); - let result: unknown = null; - void coordinator.run().then((value) => { - result = value; - }); - for (let turn = 0; turn < 120 && result === null; turn += 1) { - clock.advance(1_000); - await flush(); - } - - expect(execute).toHaveBeenCalledTimes(policy.maxAttempts); - expect( - observations - .filter((observation) => observation.kind === "ATTEMPT_FINISHED") - .map((observation) => observation.outcome), - ).toEqual([ - "PROVIDER_UNAVAILABLE", - "PROVIDER_UNAVAILABLE", - "PROVIDER_UNAVAILABLE", - ]); - expect(result).toMatchObject({ + const running = coordinator.run({ signal: caller.signal }); + clock.advance(5_000); + await expect(running).resolves.toEqual({ ok: false, - error: { kind: "POLL_BUDGET_EXHAUSTED", operation: "POLL" }, + error: { kind: "ABORTED", operation: "POLL", retryable: false }, }); });