chore(review): 1106 realtime 조치 브랜치를 합친다
This commit is contained in:
@@ -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,8 +1992,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`)도 이 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 |
|
||||
| `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 |
|
||||
| `EVENT_CONFLICT` | 같은 ID/sequence가 다른 event를 가리킴 | terminal protocol conflict + resync/rollback |
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -99,9 +99,14 @@ export type RealtimeReconnectCloseClassification =
|
||||
export type RealtimeReconnectSession<
|
||||
ClosedReceipt = RealtimeReconnectOutcome<void>,
|
||||
> = Readonly<{
|
||||
/**
|
||||
* 1106/04-01. A throw or rejection reads like a lost connection:
|
||||
* PROVIDER_UNAVAILABLE on RECEIVE, `retryable: true`, retried with backoff.
|
||||
*/
|
||||
waitClosed():
|
||||
| ClosedReceipt
|
||||
| Promise<ClosedReceipt>;
|
||||
/** A throw ends the run with PROTOCOL_MISMATCH and no retry. */
|
||||
classifyClosed(
|
||||
receipt: ClosedReceipt,
|
||||
): RealtimeReconnectCloseClassification;
|
||||
@@ -164,6 +169,18 @@ export type RealtimeReconnectCoordinatorDependencies<
|
||||
> = Readonly<{
|
||||
policy: ReconnectPolicy;
|
||||
environment: RealtimeReconnectEnvironment;
|
||||
/**
|
||||
* 1106/04-01. Return every connect failure as a result. A throw or
|
||||
* rejection is read as a transport failure, not a defect: the attempt ends
|
||||
* PROVIDER_UNAVAILABLE on CONNECT, `retryable: true`, and is retried with
|
||||
* backoff, so a transport around a library that throws on a failed connect
|
||||
* still recovers. The poll coordinator reads a throwing `execute` the other
|
||||
* way (PROTOCOL_MISMATCH, no retry): the V3 executor it wraps never throws.
|
||||
* Check the transport's settings outside `attempt`, when composition builds
|
||||
* it. `createFetchSseConnection` and `createWebSocketConnection` throw a
|
||||
* TypeError on a wrong endpoint; inside `attempt` that TypeError would be
|
||||
* retried until the budget ends and look like a server outage.
|
||||
*/
|
||||
attempt(
|
||||
context: RealtimeReconnectAttemptContext,
|
||||
):
|
||||
@@ -175,7 +192,10 @@ export type RealtimeReconnectCoordinatorDependencies<
|
||||
RealtimeReconnectAttemptSuccess<ClosedReceipt>
|
||||
>
|
||||
>;
|
||||
/** Build the result with `realtimeSuccess`/`realtimeFailure`. */
|
||||
/**
|
||||
* Build the result with `realtimeSuccess`/`realtimeFailure`. A throw ends
|
||||
* the run with PROTOCOL_MISMATCH on RECOVER and no retry.
|
||||
*/
|
||||
confirmTransportBarrier(
|
||||
recovery: RealtimeCommittedRecovery,
|
||||
): RealtimeResult<void>;
|
||||
|
||||
@@ -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(() =>
|
||||
|
||||
@@ -1758,16 +1758,29 @@ class FakeWebSocket implements WebSocketFacade {
|
||||
/**
|
||||
* The smallest SSE bridge design 6.3 leaves to composition: the attempt ends
|
||||
* at `onOpen` and the rest of the read is the session.
|
||||
*
|
||||
* 1106/04-01. The coordinator retries a throwing attempt as
|
||||
* PROVIDER_UNAVAILABLE, so the bridge checks its connection settings here,
|
||||
* when it is built: a wrong endpoint throws before any run. Each attempt
|
||||
* still makes its own connection, because the session's `close` ends that
|
||||
* connection for good.
|
||||
*/
|
||||
function sseAttempt(fetcher: typeof fetch, clock: ManualClock) {
|
||||
function sseAttempt(
|
||||
fetcher: typeof fetch,
|
||||
clock: ManualClock,
|
||||
endpoint = "https://app.example.test/events",
|
||||
) {
|
||||
const settings = Object.freeze({
|
||||
endpoint,
|
||||
applicationOrigin: "https://app.example.test",
|
||||
recoveryMode: "CURSOR" as const,
|
||||
fetcher,
|
||||
clock,
|
||||
});
|
||||
// Creating a connection checks the settings and sends nothing.
|
||||
createFetchSseConnection(settings).close();
|
||||
return async (context: RealtimeReconnectAttemptContext) => {
|
||||
const connection = createFetchSseConnection({
|
||||
endpoint: "https://app.example.test/events",
|
||||
applicationOrigin: "https://app.example.test",
|
||||
recoveryMode: "CURSOR",
|
||||
fetcher,
|
||||
clock,
|
||||
});
|
||||
const connection = createFetchSseConnection(settings);
|
||||
const open = deferred<"OPEN">();
|
||||
const reading = readSseForReconnect(connection, {
|
||||
resumeCursor: null,
|
||||
@@ -2435,4 +2448,106 @@ describe("results that composition code hands the reconnect coordinator", () =>
|
||||
);
|
||||
expect(clock.sleepCalls).toEqual([]);
|
||||
});
|
||||
|
||||
// 1106/04-01. The rule the attempt and session types state. A throwing
|
||||
// attempt or waitClosed is a transport failure and is retried; poll reads a
|
||||
// throwing execute the other way (1105/04-02).
|
||||
it.each([
|
||||
["attempt", "CONNECT"],
|
||||
["waitClosed", "RECEIVE"],
|
||||
] as const)(
|
||||
"retries a throwing %s as PROVIDER_UNAVAILABLE on %s",
|
||||
async (thrower, operation) => {
|
||||
const clock = new ManualClock();
|
||||
const observed: string[] = [];
|
||||
let attempts = 0;
|
||||
const coordinator = createRealtimeReconnectCoordinator({
|
||||
policy: policy(),
|
||||
environment: new MutableOnlineEnvironment(true),
|
||||
clock,
|
||||
random: () => 0.5,
|
||||
confirmTransportBarrier: confirmationSucceeded,
|
||||
attempt: () => {
|
||||
attempts += 1;
|
||||
if (thrower === "attempt") throw new TypeError("composer defect");
|
||||
return opened<RealtimeReconnectOutcome<void>>(
|
||||
Object.freeze({
|
||||
classifyClosed: (
|
||||
receipt: RealtimeReconnectOutcome<void>,
|
||||
) => receipt,
|
||||
close: vi.fn(),
|
||||
waitClosed: () => {
|
||||
throw new TypeError("composer defect");
|
||||
},
|
||||
}),
|
||||
);
|
||||
},
|
||||
observe: (observation) => observed.push(observationLabel(observation)),
|
||||
});
|
||||
|
||||
let result: RealtimeResult<void> | null = null;
|
||||
void coordinator.run().then((value) => {
|
||||
result = value;
|
||||
});
|
||||
await advanceUntil(clock, () => result !== null);
|
||||
|
||||
expect(attempts).toBe(3);
|
||||
expect(clock.sleepCalls).toEqual([50, 100]);
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
error: { kind: "PROVIDER_UNAVAILABLE", operation, retryable: true },
|
||||
});
|
||||
expect(
|
||||
observed.filter((label) => label.startsWith("RETRY_SCHEDULED")),
|
||||
).toEqual([
|
||||
"RETRY_SCHEDULED:PROVIDER_UNAVAILABLE",
|
||||
"RETRY_SCHEDULED:PROVIDER_UNAVAILABLE",
|
||||
]);
|
||||
expect(observed.at(-1)).toBe(
|
||||
"RUN_ENDED:PROVIDER_UNAVAILABLE:EXHAUSTED",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("ends the run without a retry when classifyClosed throws", async () => {
|
||||
const clock = new ManualClock();
|
||||
let attempts = 0;
|
||||
const coordinator = createRealtimeReconnectCoordinator({
|
||||
policy: policy(),
|
||||
environment: new MutableOnlineEnvironment(true),
|
||||
clock,
|
||||
confirmTransportBarrier: confirmationSucceeded,
|
||||
attempt: () => {
|
||||
attempts += 1;
|
||||
return opened<RealtimeReconnectOutcome<void>>(
|
||||
Object.freeze({
|
||||
classifyClosed: () => {
|
||||
throw new TypeError("composer defect");
|
||||
},
|
||||
close: vi.fn(),
|
||||
waitClosed: closedSuccessfully,
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
await expect(coordinator.run()).resolves.toEqual(
|
||||
realtimeFailure("PROTOCOL_MISMATCH", "CONNECT", false),
|
||||
);
|
||||
expect(attempts).toBe(1);
|
||||
expect(clock.sleepCalls).toEqual([]);
|
||||
});
|
||||
|
||||
// Review 04-R2 built this endpoint's connection inside the attempt: no
|
||||
// request, three attempts, then PROVIDER_UNAVAILABLE (EXHAUSTED). The bridge
|
||||
// now checks its settings when it is built, so the run never starts.
|
||||
it("refuses a wrong SSE endpoint when the bridge is built", () => {
|
||||
const fetcher = vi.fn<typeof fetch>();
|
||||
const build = () =>
|
||||
sseAttempt(fetcher, new ManualClock(), "http://app.example.test/events");
|
||||
|
||||
expect(build).toThrow(TypeError);
|
||||
expect(build).toThrow("SSE endpoint must be fixed same-origin HTTPS.");
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user