Files
clean-architecture-frontend…/tests/unit/realtime/bounded-poll-coordinator.test.ts
T
DongHyeonka 6f06e7702f 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
2026-11-06 05:32:47 +09:00

1379 lines
38 KiB
TypeScript

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,
type HttpExecutionOutcome,
} from "../../../src/adapters/http/index.ts";
import {
createBoundedPollCoordinator,
type BoundedPollAttemptResult,
type BoundedPollEnvironment,
type BoundedPollObservation,
} from "../../../src/adapters/realtime/polling/bounded-poll-coordinator.ts";
import { TEST_LIST_HTTP_CONTRACT } from "../../helpers/external-contract-fixture.ts";
type Sleeper = {
dueAt: number;
resolve(): void;
reject(): void;
signal?: AbortSignal;
onAbort?: () => void;
};
class ManualClock implements ClockPort {
current = 0;
readonly sleepers: Sleeper[] = [];
now(): number {
return this.current;
}
sleep(milliseconds: number, signal?: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(new DOMException("Aborted", "AbortError"));
return;
}
const sleeper: Sleeper = {
dueAt: this.current + milliseconds,
resolve: () => {
signal?.removeEventListener("abort", sleeper.onAbort!);
resolve();
},
reject: () => {
signal?.removeEventListener("abort", sleeper.onAbort!);
reject(new DOMException("Aborted", "AbortError"));
},
signal,
};
sleeper.onAbort = () => {
this.remove(sleeper);
sleeper.reject();
};
signal?.addEventListener("abort", sleeper.onAbort, {
once: true,
});
this.sleepers.push(sleeper);
});
}
advance(milliseconds: number): void {
this.current += milliseconds;
const ready = this.sleepers
.filter((sleeper) => sleeper.dueAt <= this.current)
.sort((left, right) => left.dueAt - right.dueAt);
for (const sleeper of ready) {
this.remove(sleeper);
sleeper.resolve();
}
}
private remove(target: Sleeper): void {
const index = this.sleepers.indexOf(target);
if (index >= 0) this.sleepers.splice(index, 1);
}
}
class MutableEnvironment implements BoundedPollEnvironment {
visible = true;
connected = true;
readonly visibilityListeners = new Set<
(visibility: "HIDDEN" | "VISIBLE") => void
>();
readonly onlineListeners = new Set<(online: boolean) => void>();
visibility(): "HIDDEN" | "VISIBLE" {
return this.visible ? "VISIBLE" : "HIDDEN";
}
online(): boolean {
return this.connected;
}
subscribeVisibility(
listener: (visibility: "HIDDEN" | "VISIBLE") => void,
): () => void {
this.visibilityListeners.add(listener);
return () => this.visibilityListeners.delete(listener);
}
subscribeOnline(listener: (online: boolean) => void): () => void {
this.onlineListeners.add(listener);
return () => this.onlineListeners.delete(listener);
}
hide(): void {
this.visible = false;
for (const listener of this.visibilityListeners) listener("HIDDEN");
}
}
const policy = definePollLeasePolicy({
operationId: "GET_JOB_STATUS",
owner: "reference-job",
minimumIntervalMs: 5_000,
successIntervalMs: 5_000,
maxIntervalMs: 60_000,
maxAttempts: 3,
maxElapsedMs: 60_000,
maxResponseBytes: 1_024,
visibility: "VISIBLE_ONLY",
fallbackReason: "CONVERGENCE",
terminalStates: ["COMPLETED", "FAILED"],
});
const operation: BoundedPollOperation = Object.freeze({
contract: Object.freeze({
...TEST_LIST_HTTP_CONTRACT.contract,
operationId: "GET_JOB_STATUS",
}),
frontend: Object.freeze({
...TEST_LIST_HTTP_CONTRACT.frontend,
responseByteLimit: 1_024,
retryBudget: 0 as const,
}),
}) as BoundedPollOperation;
function withResponseByteLimit(
responseByteLimit: number,
): BoundedPollOperation {
return {
...operation,
frontend: { ...operation.frontend, responseByteLimit },
};
}
async function flush(): Promise<void> {
for (let turn = 0; turn < 12; turn += 1) {
await Promise.resolve();
}
}
describe("bounded poll coordinator", () => {
it("observes lease start, each attempt and the stop reason", async () => {
const clock = new ManualClock();
const results: BoundedPollAttemptResult<string>[] = [
{ ok: true, value: { kind: "UNCHANGED", responseBytes: 0 } },
{
ok: false,
error: {
kind: "RATE_LIMITED",
operation: "POLL",
retryable: true,
},
},
{
ok: true,
value: {
kind: "VALUE",
value: "done",
responseBytes: 8,
state: "COMPLETED",
},
},
];
const observations: unknown[] = [];
const coordinator = createBoundedPollCoordinator({
policy,
operation,
execute: async () => results.shift()!,
environment: new MutableEnvironment(),
clock,
random: () => 0.5,
observe: (observation) => {
observations.push(observation);
throw new Error("sink failure must not change the lease");
},
});
let settled = false;
const running = coordinator.run();
void running.then(() => {
settled = true;
});
for (let step = 0; step < 50 && !settled; step += 1) {
clock.advance(1_000);
await flush();
}
await expect(running).resolves.toMatchObject({
ok: true,
value: { kind: "TERMINAL", attempts: 3 },
});
expect(observations).toEqual([
{ kind: "LEASE_STARTED" },
{ kind: "ATTEMPT_FINISHED", outcome: "UNCHANGED" },
{ kind: "ATTEMPT_FINISHED", outcome: "RATE_LIMITED" },
{ kind: "ATTEMPT_FINISHED", outcome: "VALUE" },
{ kind: "LEASE_STOPPED", outcome: "TERMINAL" },
]);
});
it("chains completed attempts without overlap and stops at a terminal state", async () => {
const clock = new ManualClock();
const environment = new MutableEnvironment();
let active = 0;
let highWatermark = 0;
const execute = vi
.fn<
(
input: Readonly<{
operationId: string;
attempt: number;
maxResponseBytes: number;
signal: AbortSignal;
}>,
) => Promise<BoundedPollAttemptResult<string>>
>()
.mockImplementation(async ({ attempt }) => {
active += 1;
highWatermark = Math.max(highWatermark, active);
await Promise.resolve();
active -= 1;
return {
ok: true,
value: {
kind: "VALUE",
value: attempt === 1 ? "working" : "done",
responseBytes: 32,
state: attempt === 1 ? "RUNNING" : "COMPLETED",
},
};
});
const onValue = vi.fn();
const coordinator = createBoundedPollCoordinator({
policy,
operation,
execute,
environment,
clock,
random: () => 0.5,
});
const result = coordinator.run({ onValue });
expect(execute).not.toHaveBeenCalled();
clock.advance(5_000);
await flush();
expect(execute).toHaveBeenCalledTimes(1);
expect(clock.sleepers).toHaveLength(1);
clock.advance(5_000);
await flush();
await expect(result).resolves.toEqual({
ok: true,
value: {
kind: "TERMINAL",
attempts: 2,
state: "COMPLETED",
value: "done",
},
});
expect(onValue.mock.calls.map(([value]) => value)).toEqual([
"working",
"done",
]);
expect(highWatermark).toBe(1);
expect(coordinator.getState()).toBe("IDLE");
expect(environment.visibilityListeners.size).toBe(0);
expect(environment.onlineListeners.size).toBe(0);
});
it("passes the strictest response ceiling to the executor before decode", async () => {
const clock = new ManualClock();
const execute = vi.fn(
async ({
maxResponseBytes,
}: Readonly<{ maxResponseBytes: number }>) => ({
ok: true as const,
value: {
kind: "VALUE" as const,
value: "done",
responseBytes: maxResponseBytes,
state: "COMPLETED",
},
}),
);
const coordinator = createBoundedPollCoordinator<string>({
policy,
operation: withResponseByteLimit(4_096),
execute,
environment: new MutableEnvironment(),
clock,
});
const pending = coordinator.run();
clock.advance(5_000);
await expect(pending).resolves.toMatchObject({
ok: true,
value: { state: "COMPLETED" },
});
expect(execute).toHaveBeenCalledWith(
expect.objectContaining({ maxResponseBytes: 1_024 }),
);
});
it("does not start another attempt while a request is unresolved", async () => {
const clock = new ManualClock();
const environment = new MutableEnvironment();
let resolveFirst:
| ((result: BoundedPollAttemptResult<string>) => void)
| undefined;
const execute = vi
.fn()
.mockImplementationOnce(
() =>
new Promise<BoundedPollAttemptResult<string>>((resolve) => {
resolveFirst = resolve;
}),
)
.mockResolvedValue({
ok: true,
value: {
kind: "VALUE",
value: "done",
responseBytes: 10,
state: "COMPLETED",
},
});
const coordinator = createBoundedPollCoordinator<string>({
policy,
operation,
execute,
environment,
clock,
random: () => 0.5,
});
const pending = coordinator.run();
clock.advance(5_000);
await flush();
expect(execute).toHaveBeenCalledTimes(1);
clock.advance(30_000);
await flush();
expect(execute).toHaveBeenCalledTimes(1);
resolveFirst?.({
ok: true,
value: { kind: "UNCHANGED", responseBytes: 0 },
});
await flush();
clock.advance(5_000);
await flush();
expect(execute).toHaveBeenCalledTimes(2);
await expect(pending).resolves.toMatchObject({
ok: true,
value: { attempts: 2, state: "COMPLETED" },
});
});
it("ends the lease when an in-flight executor ignores abort and exceeds max elapsed", async () => {
const clock = new ManualClock();
let attemptSignal: AbortSignal | undefined;
let settleAttempt:
| ((result: BoundedPollAttemptResult<string>) => void)
| undefined;
const execute = vi.fn(
({ signal }: Readonly<{ signal: AbortSignal }>) => {
attemptSignal = signal;
return new Promise<BoundedPollAttemptResult<string>>(
(resolve) => {
settleAttempt = resolve;
},
);
},
);
const coordinator = createBoundedPollCoordinator<string>({
policy,
operation,
execute,
environment: new MutableEnvironment(),
clock,
});
const pending = coordinator.run();
clock.advance(5_000);
await flush();
expect(execute).toHaveBeenCalledTimes(1);
expect(attemptSignal?.aborted).toBe(false);
clock.advance(54_999);
await flush();
expect(coordinator.getState()).toBe("RUNNING");
clock.advance(1);
await flush();
await expect(pending).resolves.toEqual({
ok: false,
error: {
kind: "POLL_BUDGET_EXHAUSTED",
operation: "POLL",
retryable: false,
},
});
expect(attemptSignal?.aborted).toBe(true);
expect(coordinator.getState()).toBe("DRAINING");
await expect(coordinator.run()).resolves.toMatchObject({
ok: false,
error: { kind: "PROTOCOL_MISMATCH" },
});
settleAttempt?.({
ok: false,
error: {
kind: "ABORTED",
operation: "POLL",
retryable: false,
},
});
await flush();
expect(coordinator.getState()).toBe("IDLE");
});
it("returns promptly when a caller aborts an executor that ignores its signal", async () => {
const clock = new ManualClock();
const caller = new AbortController();
let settleAttempt:
| ((result: BoundedPollAttemptResult<string>) => void)
| undefined;
const execute = vi.fn(
() =>
new Promise<BoundedPollAttemptResult<string>>(
(resolve) => {
settleAttempt = resolve;
},
),
);
const coordinator = createBoundedPollCoordinator<string>({
policy,
operation,
execute,
environment: new MutableEnvironment(),
clock,
});
const pending = coordinator.run({ signal: caller.signal });
clock.advance(5_000);
await flush();
expect(execute).toHaveBeenCalledTimes(1);
caller.abort();
await expect(pending).resolves.toEqual({
ok: false,
error: {
kind: "ABORTED",
operation: "POLL",
retryable: false,
},
});
expect(coordinator.getState()).toBe("DRAINING");
settleAttempt?.({
ok: false,
error: {
kind: "ABORTED",
operation: "POLL",
retryable: false,
},
});
await flush();
expect(coordinator.getState()).toBe("IDLE");
});
it("fails closed and aborts the attempt when the lease deadline clock is unavailable", async () => {
let current = 0;
let sleeps = 0;
const clock: ClockPort = {
now: () => current,
sleep: async (milliseconds) => {
sleeps += 1;
if (sleeps > 1) throw new Error("deadline unavailable");
current += milliseconds;
},
};
let attemptSignal: AbortSignal | undefined;
const execute = vi.fn(
async ({ signal }: Readonly<{ signal: AbortSignal }>) => {
attemptSignal = signal;
return {
ok: true as const,
value: {
kind: "UNCHANGED" as const,
responseBytes: 0 as const,
},
};
},
);
const coordinator = createBoundedPollCoordinator<string>({
policy,
operation,
execute,
environment: new MutableEnvironment(),
clock,
});
await expect(coordinator.run()).resolves.toEqual({
ok: false,
error: {
kind: "PROVIDER_UNAVAILABLE",
operation: "POLL",
retryable: false,
},
});
expect(execute).toHaveBeenCalledOnce();
expect(attemptSignal?.aborted).toBe(true);
});
it("fences a non-cooperative apply callback at the lease deadline", async () => {
const clock = new ManualClock();
let applyContext:
| Readonly<{
signal: AbortSignal;
isCurrent(): boolean;
}>
| undefined;
let releaseApply: (() => void) | undefined;
const coordinator = createBoundedPollCoordinator<string>({
policy,
operation,
execute: async () => ({
ok: true,
value: {
kind: "VALUE",
value: "working",
responseBytes: 10,
state: "RUNNING",
},
}),
environment: new MutableEnvironment(),
clock,
});
const pending = coordinator.run({
onValue: (_value, context) => {
applyContext = context;
return new Promise<void>((resolve) => {
releaseApply = resolve;
});
},
});
clock.advance(5_000);
await flush();
expect(applyContext?.isCurrent()).toBe(true);
clock.advance(55_000);
await flush();
await expect(pending).resolves.toEqual({
ok: false,
error: {
kind: "POLL_BUDGET_EXHAUSTED",
operation: "POLL",
retryable: false,
},
});
expect(applyContext?.signal.aborted).toBe(true);
expect(applyContext?.isCurrent()).toBe(false);
expect(coordinator.getState()).toBe("DRAINING");
releaseApply?.();
await flush();
expect(coordinator.getState()).toBe("IDLE");
});
it("honors Retry-After as a floor and exhausts finite attempts", async () => {
const clock = new ManualClock();
const execute = vi
.fn()
.mockResolvedValueOnce({
ok: false,
error: {
kind: "RATE_LIMITED",
operation: "POLL",
retryable: true,
retryAfterMs: 10_000,
},
})
.mockResolvedValue({
ok: true,
value: { kind: "UNCHANGED", responseBytes: 0 },
});
const coordinator = createBoundedPollCoordinator<string>({
policy: definePollLeasePolicy({
...policy,
maxAttempts: 2,
}),
operation,
execute,
environment: new MutableEnvironment(),
clock,
random: () => 0,
});
const pending = coordinator.run();
clock.advance(5_000);
await flush();
expect(execute).toHaveBeenCalledTimes(1);
clock.advance(9_999);
await flush();
expect(execute).toHaveBeenCalledTimes(1);
clock.advance(1);
await flush();
await expect(pending).resolves.toEqual({
ok: false,
error: {
kind: "POLL_BUDGET_EXHAUSTED",
operation: "POLL",
retryable: false,
},
});
expect(execute).toHaveBeenCalledTimes(2);
});
it.each(["RATE_LIMITED", "PROVIDER_UNAVAILABLE"] as const)(
"retries retryable %s without a server hint on policy backoff",
async (kind) => {
const clock = new ManualClock();
const execute = vi
.fn()
.mockResolvedValueOnce({
ok: false,
error: {
kind,
operation: "POLL",
retryable: true,
},
})
.mockResolvedValue({
ok: false,
error: {
kind,
operation: "POLL",
retryable: false,
},
});
const coordinator = createBoundedPollCoordinator<string>({
policy,
operation,
execute,
environment: new MutableEnvironment(),
clock,
random: () => 0,
});
const pending = coordinator.run();
clock.advance(5_000);
await flush();
expect(execute).toHaveBeenCalledTimes(1);
clock.advance(5_000);
await flush();
await expect(pending).resolves.toEqual({
ok: false,
error: {
kind,
operation: "POLL",
retryable: false,
},
});
expect(execute).toHaveBeenCalledTimes(2);
},
);
it("ignores Retry-After for retryable failure kinds that cannot carry the hint", async () => {
const clock = new ManualClock();
const execute = vi
.fn()
.mockResolvedValueOnce({
ok: false,
error: {
kind: "CONNECT_TIMEOUT",
operation: "POLL",
retryable: true,
retryAfterMs: 10_000,
},
})
.mockResolvedValue({
ok: true,
value: {
kind: "VALUE",
value: "done",
responseBytes: 10,
state: "COMPLETED",
},
});
const coordinator = createBoundedPollCoordinator<string>({
policy,
operation,
execute,
environment: new MutableEnvironment(),
clock,
random: () => 0,
});
const pending = coordinator.run();
clock.advance(5_000);
await flush();
expect(execute).toHaveBeenCalledTimes(1);
clock.advance(4_999);
await flush();
expect(execute).toHaveBeenCalledTimes(1);
clock.advance(1);
await expect(pending).resolves.toMatchObject({
ok: true,
value: { attempts: 2, state: "COMPLETED" },
});
expect(execute).toHaveBeenCalledTimes(2);
});
it.each(["AUTH_REQUIRED", "FORBIDDEN"] as const)(
"never retries terminal %s failures even when the executor marks them retryable",
async (kind) => {
const clock = new ManualClock();
const execute = vi.fn().mockResolvedValue({
ok: false,
error: {
kind,
operation: "POLL",
retryable: true,
retryAfterMs: 10_000,
},
});
const coordinator = createBoundedPollCoordinator<string>({
policy,
operation,
execute,
environment: new MutableEnvironment(),
clock,
});
const pending = coordinator.run();
clock.advance(5_000);
await expect(pending).resolves.toEqual({
ok: false,
error: {
kind,
operation: "POLL",
retryable: false,
},
});
expect(execute).toHaveBeenCalledOnce();
},
);
it("aborts in-flight work on hidden lifecycle and rejects late scope results", async () => {
const hiddenClock = new ManualClock();
const hiddenEnvironment = new MutableEnvironment();
const hiddenCoordinator = createBoundedPollCoordinator<string>({
policy,
operation,
environment: hiddenEnvironment,
clock: hiddenClock,
execute: ({ signal }) =>
new Promise((resolve) => {
signal.addEventListener(
"abort",
() =>
resolve({
ok: false,
error: {
kind: "ABORTED",
operation: "POLL",
retryable: false,
},
}),
{ once: true },
);
}),
});
const hidden = hiddenCoordinator.run();
hiddenClock.advance(5_000);
await flush();
hiddenEnvironment.hide();
await expect(hidden).resolves.toEqual({
ok: false,
error: {
kind: "ABORTED",
operation: "POLL",
retryable: false,
},
});
const scopeClock = new ManualClock();
let current = true;
let resolveAttempt:
| ((result: BoundedPollAttemptResult<string>) => void)
| undefined;
const onValue = vi.fn();
const scopeCoordinator = createBoundedPollCoordinator<string>({
policy,
operation,
environment: new MutableEnvironment(),
clock: scopeClock,
isCurrent: () => current,
execute: () =>
new Promise((resolve) => {
resolveAttempt = resolve;
}),
});
const fenced = scopeCoordinator.run({ onValue });
scopeClock.advance(5_000);
await flush();
current = false;
resolveAttempt?.({
ok: true,
value: {
kind: "VALUE",
value: "late",
responseBytes: 10,
state: "COMPLETED",
},
});
await expect(fenced).resolves.toEqual({
ok: false,
error: {
kind: "SCOPE_FENCED",
operation: "POLL",
retryable: false,
},
});
expect(onValue).not.toHaveBeenCalled();
});
it("rejects accessor and extra-key attempt results without re-reading them", async () => {
const accessorClock = new ManualClock();
const readOk = vi.fn(() => true);
const accessorResult = Object.defineProperties(
{},
{
ok: {
enumerable: true,
get: readOk,
},
value: {
enumerable: true,
value: {
kind: "VALUE",
value: "unsafe",
responseBytes: 1,
state: "COMPLETED",
},
},
},
) as BoundedPollAttemptResult<string>;
const accessorCoordinator = createBoundedPollCoordinator<string>({
policy,
operation,
environment: new MutableEnvironment(),
clock: accessorClock,
execute: async () => accessorResult,
});
const accessorRun = accessorCoordinator.run();
accessorClock.advance(5_000);
await expect(accessorRun).resolves.toMatchObject({
ok: false,
error: { kind: "PROTOCOL_MISMATCH" },
});
expect(readOk).not.toHaveBeenCalled();
const extraClock = new ManualClock();
const extraCoordinator = createBoundedPollCoordinator<string>({
policy,
operation,
environment: new MutableEnvironment(),
clock: extraClock,
execute: async () =>
({
ok: true,
value: {
kind: "VALUE",
value: "unsafe",
responseBytes: 1,
state: "COMPLETED",
},
extra: true,
}) as BoundedPollAttemptResult<string>,
});
const extraRun = extraCoordinator.run();
extraClock.advance(5_000);
await expect(extraRun).resolves.toMatchObject({
ok: false,
error: { kind: "PROTOCOL_MISMATCH" },
});
});
// 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<BoundedPollAttemptResult<string>>,
);
const coordinator = createBoundedPollCoordinator<string>({
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 caller = new AbortController();
const coordinator = createBoundedPollCoordinator<string>({
policy,
operation,
environment: new MutableEnvironment(),
clock,
execute: ({ signal }) =>
new Promise<BoundedPollAttemptResult<string>>((_resolve, reject) => {
signal.addEventListener(
"abort",
() => reject(new DOMException("Aborted", "AbortError")),
{ once: true },
);
caller.abort();
}),
});
const running = coordinator.run({ signal: caller.signal });
clock.advance(5_000);
await expect(running).resolves.toEqual({
ok: false,
error: { kind: "ABORTED", operation: "POLL", retryable: false },
});
});
it("reads attempt results with the shared realtime snapshot rules", async () => {
const runWith = async (result: unknown) => {
const clock = new ManualClock();
const coordinator = createBoundedPollCoordinator<string>({
policy,
operation,
environment: new MutableEnvironment(),
clock,
execute: async () => result as BoundedPollAttemptResult<string>,
});
const running = coordinator.run();
clock.advance(5_000);
return running;
};
const terminalValue = () => ({
kind: "VALUE",
value: "done",
responseBytes: 1,
state: "COMPLETED",
});
// A hidden (non-enumerable) field is not plain data: rejected.
await expect(
runWith(
Object.defineProperties(
{},
{
ok: { enumerable: false, value: true },
value: { enumerable: true, value: terminalValue() },
},
),
),
).resolves.toMatchObject({
ok: false,
error: { kind: "PROTOCOL_MISMATCH" },
});
// A null-prototype record is plain data: accepted.
await expect(
runWith(
Object.assign(Object.create(null) as object, {
ok: true,
value: Object.assign(
Object.create(null) as object,
terminalValue(),
),
}),
),
).resolves.toMatchObject({
ok: true,
value: { kind: "TERMINAL", value: "done" },
});
});
it("fails closed on response ceilings, concurrent runs and close", async () => {
const clock = new ManualClock();
const coordinator = createBoundedPollCoordinator<string>({
policy,
operation: withResponseByteLimit(512),
environment: new MutableEnvironment(),
clock,
execute: async () => ({
ok: true,
value: {
kind: "VALUE",
value: "oversized",
responseBytes: 513,
state: "RUNNING",
},
}),
});
const first = coordinator.run();
await expect(coordinator.run()).resolves.toEqual({
ok: false,
error: {
kind: "PROTOCOL_MISMATCH",
operation: "POLL",
retryable: false,
},
});
clock.advance(5_000);
await expect(first).resolves.toEqual({
ok: false,
error: {
kind: "PROTOCOL_MISMATCH",
operation: "POLL",
retryable: false,
},
});
const pending = coordinator.run();
coordinator.close();
coordinator.close();
await expect(pending).resolves.toEqual({
ok: false,
error: {
kind: "CLOSED",
operation: "POLL",
retryable: false,
},
});
expect(coordinator.getState()).toBe("CLOSED");
});
});
/**
* 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.
describe("a poll attempt on the V3 executor", () => {
const pollPolicy = definePollLeasePolicy({
operationId: TEST_LIST_HTTP_CONTRACT.contract.operationId,
owner: "reference-job",
minimumIntervalMs: 5_000,
successIntervalMs: 5_000,
maxIntervalMs: 60_000,
maxAttempts: 3,
maxElapsedMs: 600_000,
maxResponseBytes: 32_768,
visibility: "VISIBLE_ONLY",
fallbackReason: "STREAM_UNAVAILABLE",
terminalStates: [],
});
const scope = Object.freeze({
generation: 1,
fingerprint: "scope-1",
identities: Object.freeze({}) as never,
signal: new AbortController().signal,
isCurrent: () => true,
});
// 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/",
// The app default (`MAX_RETRY_ATTEMPTS`).
maxRetryAttempts: 2,
attachCredentials: () => ({ kind: "READY", headers: {} }),
fetcher: async (request) => {
requests.push(String(request));
return respond();
},
sleep: async () => undefined,
random: () => 0.5,
createRequestId: () => "req-1",
});
const coordinator = createBoundedPollCoordinator<unknown>({
policy: pollPolicy,
operation: descriptor,
environment: new MutableEnvironment(),
clock,
random: () => 0.5,
// 1103/04-01. Runs the descriptor the coordinator hands back, never a
// 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 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(() =>
pollOn(TEST_LIST_HTTP_CONTRACT as BoundedPollOperation, new ManualClock()),
).toThrow(TypeError);
});
it("sends one request per poll attempt with a poll descriptor", async () => {
const clock = new ManualClock();
const pollOnly = Object.freeze({
...TEST_LIST_HTTP_CONTRACT,
frontend: Object.freeze({
...TEST_LIST_HTTP_CONTRACT.frontend,
retryBudget: 0 as const,
}),
}) as BoundedPollOperation;
const { coordinator, requests } = pollOn(pollOnly, clock);
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).toMatchObject({
ok: false,
error: { kind: "POLL_BUDGET_EXHAUSTED" },
});
expect(requests).toHaveLength(pollPolicy.maxAttempts);
});
// 1103/04-01's remaining gap: `execute` had no descriptor, so composition
// code chose one itself and could run the default row (three requests per
// attempt, review 04-R1 P5).
it("hands every execute call the descriptor it checked at creation", async () => {
const clock = new ManualClock();
const pollOnly = Object.freeze({
...TEST_LIST_HTTP_CONTRACT,
frontend: Object.freeze({
...TEST_LIST_HTTP_CONTRACT.frontend,
retryBudget: 0 as const,
}),
}) as BoundedPollOperation;
const received: unknown[] = [];
const coordinator = createBoundedPollCoordinator<unknown>({
policy: pollPolicy,
operation: pollOnly,
environment: new MutableEnvironment(),
clock,
random: () => 0.5,
execute: async ({ operation: polled }) => {
received.push(polled);
return {
ok: false,
error: {
kind: "PROVIDER_UNAVAILABLE",
operation: "POLL",
retryable: true,
},
};
},
});
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(received).toHaveLength(pollPolicy.maxAttempts);
for (const polled of received) expect(polled).toBe(pollOnly);
});
});