Files
clean-architecture-frontend…/src/adapters/realtime/polling/bounded-poll-coordinator.ts
T
DongHyeonka 06ffafa25e docs: 살아 있는 문서의 낡은 문장을 지금 코드와 정본에 맞춘다
2026-11-07~08의 정리(문서 이동, 참조 기능 삭제, CI 재편) 뒤 살아 있는
문서가 지금 코드와 다른 말을 한다.

- 현재 계약 문서 둘과 스타터 문서가 기록(docs/design/)을 정본으로
  가리킨다. 정본을 frontend-application-foundation.md·src/bootstrap/,
  패턴 표·계층 규칙으로 바꾸고 설계서는 배경으로 둔다(1112/02-06).
- 실시간 대응표 둘(짝 백엔드 출구, poll attempt 결과)이 기록에만 있었다.
  optional-adapter-recipes.md로 옮기고 코드 주석·매뉴얼 03·설계서 머리
  블록이 옮긴 곳을 가리킨다(1112/09-02).
- 실행 격리 변수 목록을 설계 기록이 아니라 scripts/lib/run-isolation.ts로
  가리킨다(1112/08-17).
- 계약 소유 절 이름(「판단 규칙」), pin 대조 시험의 게이트(005·007),
  drift 검사 범위(1112/02-07). INVENTORY 머리의 손 숫자와 지킬 수 없는
  꼬리 문장(1112/02-08).
- 검증 안내: 검사기를 바꾸면 FE-GATE-029, 문서면 desktop
  verify:documentation(1112/08-05, 08-04). FE-GATE-012는 merge 단계다
  (08-16). N6이 알리는 파일을 좁혀 적는다(08-10). 한 파일 시험은
  verify.sh exec(08-11). 문서 검사 범위의 손 사본을 정본 한 곳으로(08-07).
- create:feature 참조의 Next: 3과 되돌리기(08-08), 손으로 옮긴 숫자
  (08-19), 라운드 없는 리뷰 ID 17곳에 0925를 붙인다(08-15).
- secret scan 범위 설명(1112/07-03), lab이 기능 라우트를 읽는 문장
  (1103/16-06), README 동기화 기준점·제품 소유 파일·선택 기능 결함 몫
  (0929/14-02, 14-03, 13-10), 커밋을 다시 지은 모든 통합의 해시 대조
  (1106/14-02).

고른 방법: 문장을 코드에 맞춘다. 표는 옮기고 숫자는 정본을 가리킨다.
버린 대안: 기록 문서 본문 고치기(기록은 머리 블록만 고친다).

위험·한계: 문서 검사 범위 목록을 지운 ci-quality-gates.md는 이제
docs/README.md 5절과 gates.md 7절을 읽어야 한다. 매뉴얼 02 7절 업로드
예의 declare module 문제(1112/09-01)는 고치는 방향이 check:architecture
규칙과 부딪쳐 결정 대기로 남긴다.

검증: scripts/verify.sh docs(노트북) 통과. desktop verify:documentation과
FE-GATE-005(문서를 읽는 시험)는 PR 본문에 적는다.

Refs: 1112/02-06, 1112/02-07, 1112/02-08, 1112/07-03, 1112/08-04,
 1112/08-05, 1112/08-07, 1112/08-08, 1112/08-10, 1112/08-11, 1112/08-15,
 1112/08-16, 1112/08-17, 1112/08-19, 1112/09-02, 1103/16-06, 0929/14-02,
 0929/14-03, 0929/13-10, 1106/14-02
2026-11-12 23:36:14 +09:00

880 lines
25 KiB
TypeScript

import {
assertBoundedPollOperation,
definePollLeasePolicy,
type BoundedPollOperation,
type PollLeasePolicy,
} from "../../../application/policies/bounded-polling.ts";
import type { ClockPort } from "../../../application/ports/clock-port.ts";
import {
REALTIME_FAILURE_KINDS,
type RealtimeFailure,
type RealtimeFailureKind,
type RealtimeResult,
} from "../../../application/ports/realtime/shared.ts";
import { systemClock } from "../../platform/system-clock.ts";
import {
captureRealtimeDataSnapshot,
hasExactSnapshotKeys,
observeRealtime,
raceRealtimeTask,
realtimeFailure,
realtimeSuccess,
type RealtimeRace,
} from "../result.ts";
/**
* Provider-private Retry-After metadata is consumed by this adapter and is
* deliberately stripped before a failure crosses the realtime boundary.
*/
export type BoundedPollAttemptFailure = RealtimeFailure & Readonly<{
retryAfterMs?: number;
}>;
type BoundedPollAttemptSuccess<Value> =
| Readonly<{
kind: "UNCHANGED";
responseBytes: 0;
}>
| Readonly<{
kind: "VALUE";
value: Value;
responseBytes: number;
state?: string;
}>;
export type BoundedPollAttemptResult<Value> =
| Extract<
RealtimeResult<BoundedPollAttemptSuccess<Value>>,
{ ok: true }
>
| Readonly<{ ok: false; error: BoundedPollAttemptFailure }>;
export type BoundedPollResult<Value> =
RealtimeResult<
Readonly<{
kind: "TERMINAL";
attempts: number;
state: string;
value: Value;
}>
>;
export type BoundedPollEnvironment = Readonly<{
visibility(): "HIDDEN" | "VISIBLE";
online(): boolean;
subscribeVisibility?(
listener: (visibility: "HIDDEN" | "VISIBLE") => void,
): () => void;
subscribeOnline?(listener: (online: boolean) => void): () => void;
}>;
export type BoundedPollRunInput<Value> = Readonly<{
signal?: AbortSignal;
onValue?: (
value: Value,
context: Readonly<{ signal: AbortSignal; isCurrent(): boolean }>,
) => void | Promise<void>;
}>;
export type BoundedPollCoordinator<Value> = Readonly<{
run(input?: BoundedPollRunInput<Value>): Promise<
BoundedPollResult<Value>
>;
getState(): "CLOSED" | "DRAINING" | "IDLE" | "RUNNING";
close(): void;
}>;
/**
* Closed diagnostics for design 14.1 `bounded_poll_*`. `outcome` is VALUE,
* UNCHANGED or the failure kind for ATTEMPT_FINISHED, and TERMINAL or the
* failure kind for LEASE_STOPPED.
*/
export type BoundedPollObservation = Readonly<{
kind: "LEASE_STARTED" | "ATTEMPT_FINISHED" | "LEASE_STOPPED";
outcome?: "VALUE" | "UNCHANGED" | "TERMINAL" | RealtimeFailureKind;
}>;
/**
* 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: 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.
* docs/architecture/optional-adapter-recipes.md 「poll attempt 결과 대응」
* maps each V3 executor outcome to a result.
*/
execute(input: Readonly<{
operationId: string;
/**
* 1103/04-01. The `operation` this coordinator was created with, the
* object creation checked. Run this one on the executor, not another row
* for the same path: a descriptor with `retryBudget: 2` sends up to three
* requests per attempt.
*/
operation: Operation;
attempt: number;
/**
* Hard response-body ceiling that must be enforced before decoding.
*/
maxResponseBytes: number;
signal: AbortSignal;
}>): Promise<BoundedPollAttemptResult<Value>>;
environment: BoundedPollEnvironment;
isCurrent?: () => boolean;
clock?: ClockPort;
random?: () => number;
observe?(observation: BoundedPollObservation): void;
}>;
const SAFE_STATE = /^[A-Z][A-Z0-9_]{0,63}$/u;
const POLL_RETRYABLE_FAILURE_KINDS = Object.freeze([
"CONNECT_TIMEOUT",
"RATE_LIMITED",
"PROVIDER_UNAVAILABLE",
] as const satisfies readonly RealtimeFailureKind[]);
const POLL_RETRY_AFTER_FAILURE_KINDS = Object.freeze([
"RATE_LIMITED",
"PROVIDER_UNAVAILABLE",
] as const satisfies readonly RealtimeFailureKind[]);
export function createBoundedPollCoordinator<
Value,
Operation extends BoundedPollOperation = BoundedPollOperation,
>(
dependencies: BoundedPollCoordinatorDependencies<Value, Operation>,
): BoundedPollCoordinator<Value> {
const policy = definePollLeasePolicy(dependencies.policy);
const operation = dependencies.operation;
assertBoundedPollOperation(policy, operation);
const maxResponseBytes = Math.min(
policy.maxResponseBytes,
operation.frontend.responseByteLimit,
);
const clock = dependencies.clock ?? systemClock;
const random = dependencies.random ?? Math.random;
const isCurrent = dependencies.isCurrent ?? (() => true);
let state: "CLOSED" | "DRAINING" | "IDLE" | "RUNNING" = "IDLE";
let activeController: AbortController | null = null;
let generation = 0;
let pendingWork = 0;
const observe = (observation: BoundedPollObservation) =>
observeRealtime(dependencies.observe, observation);
async function run(
input?: BoundedPollRunInput<Value>,
): Promise<BoundedPollResult<Value>> {
const startedGeneration = generation;
const result = await runLease(input);
// A call rejected before starting leaves the generation unchanged.
if (generation !== startedGeneration) {
observe({
kind: "LEASE_STOPPED",
outcome: result.ok ? "TERMINAL" : result.error.kind,
});
}
return result;
}
async function runLease(
input: BoundedPollRunInput<Value> = {},
): Promise<BoundedPollResult<Value>> {
if (state === "CLOSED") return pollFailure("CLOSED");
if (state !== "IDLE") {
return pollFailure("PROTOCOL_MISMATCH");
}
if (input.signal?.aborted) return pollFailure("ABORTED");
if (safeVisibility(dependencies.environment) !== "VISIBLE") {
return pollFailure("ABORTED");
}
if (safeOnline(dependencies.environment) !== true) {
return pollFailure("OFFLINE", true);
}
if (!safeIsCurrent(isCurrent)) {
return pollFailure("SCOPE_FENCED");
}
state = "RUNNING";
const runGeneration = ++generation;
observe({ kind: "LEASE_STARTED" });
const controller = new AbortController();
activeController = controller;
let stopKind: RealtimeFailureKind | null = null;
let attempts = 0;
let consecutiveFailures = 0;
let nextDelayMs = policy.minimumIntervalMs;
const startedAtMs = safeNow(clock);
const stop = (kind: RealtimeFailureKind) => {
if (stopKind !== null) return;
stopKind = kind;
controller.abort();
};
const onCallerAbort = () => stop("ABORTED");
input.signal?.addEventListener("abort", onCallerAbort, {
once: true,
});
let unsubscribeVisibility: (() => void) | undefined;
let unsubscribeOnline: (() => void) | undefined;
try {
unsubscribeVisibility =
dependencies.environment.subscribeVisibility?.((visibility) => {
if (visibility !== "VISIBLE") stop("ABORTED");
});
} catch {
stop("ABORTED");
}
try {
unsubscribeOnline =
dependencies.environment.subscribeOnline?.((online) => {
if (!online) stop("OFFLINE");
});
} catch {
stop("OFFLINE");
}
try {
if (startedAtMs === null) {
return pollFailure("PROVIDER_UNAVAILABLE");
}
while (true) {
const lifecycleFailure = currentFailure(
stopKind,
state,
runGeneration,
generation,
isCurrent,
dependencies.environment,
);
if (lifecycleFailure) {
return pollFailure(
lifecycleFailure,
lifecycleFailure === "OFFLINE",
);
}
if (attempts >= policy.maxAttempts) {
return pollFailure("POLL_BUDGET_EXHAUSTED");
}
const nowBeforeSleep = safeNow(clock);
if (
nowBeforeSleep === null ||
nowBeforeSleep < startedAtMs
) {
return pollFailure("PROVIDER_UNAVAILABLE");
}
if (
nowBeforeSleep - startedAtMs + nextDelayMs >=
policy.maxElapsedMs
) {
return pollFailure("POLL_BUDGET_EXHAUSTED");
}
const cadenceOutcome = await raceRealtimeTask(
() => clock.sleep(nextDelayMs, controller.signal),
controller.signal,
);
if (cadenceOutcome.kind !== "VALUE") {
const afterSleepFailure = currentFailure(
stopKind,
state,
runGeneration,
generation,
isCurrent,
dependencies.environment,
);
return pollFailure(
afterSleepFailure ??
(cadenceOutcome.kind === "REJECTED"
? "PROVIDER_UNAVAILABLE"
: "ABORTED"),
afterSleepFailure === "OFFLINE",
);
}
const beforeAttemptFailure = currentFailure(
stopKind,
state,
runGeneration,
generation,
isCurrent,
dependencies.environment,
);
if (beforeAttemptFailure) {
return pollFailure(
beforeAttemptFailure,
beforeAttemptFailure === "OFFLINE",
);
}
const attemptStartedAt = safeNow(clock);
if (
attemptStartedAt === null ||
attemptStartedAt < startedAtMs ||
attemptStartedAt - startedAtMs >= policy.maxElapsedMs
) {
return pollFailure("POLL_BUDGET_EXHAUSTED");
}
attempts += 1;
let result: BoundedPollAttemptResult<Value> | null;
const attemptOutcome = await awaitWithinLease(
() =>
trackWork(
dependencies.execute({
operationId: policy.operationId,
operation,
attempt: attempts,
maxResponseBytes,
signal: controller.signal,
}),
runGeneration,
),
policy.maxElapsedMs - (attemptStartedAt - startedAtMs),
clock,
controller.signal,
() => stop("POLL_BUDGET_EXHAUSTED"),
);
if (attemptOutcome.kind === "VALUE") {
result = attemptOutcome.value;
} else if (attemptOutcome.kind === "REJECTED") {
// 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();
}
const interruptedFailure = currentFailure(
stopKind,
state,
runGeneration,
generation,
isCurrent,
dependencies.environment,
);
return pollFailure(
interruptedFailure ??
(attemptOutcome.kind === "CLOCK_FAILED"
? "PROVIDER_UNAVAILABLE"
: "ABORTED"),
interruptedFailure === "OFFLINE",
);
}
const afterAttemptFailure = currentFailure(
stopKind,
state,
runGeneration,
generation,
isCurrent,
dependencies.environment,
);
if (afterAttemptFailure) {
return pollFailure(
afterAttemptFailure,
afterAttemptFailure === "OFFLINE",
);
}
const attemptFinishedAt = safeNow(clock);
if (
attemptFinishedAt === null ||
attemptFinishedAt < attemptStartedAt
) {
return pollFailure("PROVIDER_UNAVAILABLE");
}
if (
attemptFinishedAt - startedAtMs >= policy.maxElapsedMs
) {
return pollFailure("POLL_BUDGET_EXHAUSTED");
}
const parsedResult =
result === null ? null : parseAttemptResult<Value>(result);
if (!parsedResult) {
return pollFailure("PROTOCOL_MISMATCH");
}
result = parsedResult;
observe({
kind: "ATTEMPT_FINISHED",
outcome: result.ok ? result.value.kind : result.error.kind,
});
if (!result.ok) {
// A missing server hint falls back to policy backoff; an executor
// that requires one reports `retryable: false` instead.
if (
!result.error.retryable ||
!isPollRetryableFailureKind(result.error.kind)
) {
// OFFLINE ends this lease but stays retryable, like every other
// OFFLINE here.
return pollFailure(
result.error.kind,
result.error.kind === "OFFLINE" && result.error.retryable,
);
}
consecutiveFailures += 1;
const failureDelay = retryDelay(
policy,
consecutiveFailures,
isPollRetryAfterFailureKind(result.error.kind)
? result.error.retryAfterMs
: undefined,
random,
);
if (failureDelay === null) {
return pollFailure("POLL_BUDGET_EXHAUSTED");
}
nextDelayMs = failureDelay;
continue;
}
consecutiveFailures = 0;
if (
result.value.responseBytes > maxResponseBytes
) {
return pollFailure("PROTOCOL_MISMATCH");
}
if (result.value.kind === "UNCHANGED") {
const delay = successDelay(policy, random);
if (delay === null) {
return pollFailure("PROTOCOL_MISMATCH");
}
nextDelayMs = delay;
continue;
}
const valueResult = result.value;
if (input.onValue) {
const beforeApplyAt = safeNow(clock);
if (
beforeApplyAt === null ||
beforeApplyAt < attemptFinishedAt ||
beforeApplyAt - startedAtMs >= policy.maxElapsedMs
) {
return pollFailure("POLL_BUDGET_EXHAUSTED");
}
const applyOutcome = await awaitWithinLease(
() =>
trackWork(
Promise.resolve(
input.onValue!(valueResult.value, {
signal: controller.signal,
isCurrent: () =>
state === "RUNNING" &&
generation === runGeneration &&
stopKind === null &&
!controller.signal.aborted &&
safeIsCurrent(isCurrent),
}),
),
runGeneration,
),
policy.maxElapsedMs - (beforeApplyAt - startedAtMs),
clock,
controller.signal,
() => stop("POLL_BUDGET_EXHAUSTED"),
);
if (applyOutcome.kind === "REJECTED") {
return applyFailure();
}
if (applyOutcome.kind !== "VALUE") {
if (applyOutcome.kind === "CLOCK_FAILED") {
controller.abort();
}
const interruptedFailure = currentFailure(
stopKind,
state,
runGeneration,
generation,
isCurrent,
dependencies.environment,
);
return pollFailure(
interruptedFailure ??
(applyOutcome.kind === "CLOCK_FAILED"
? "PROVIDER_UNAVAILABLE"
: "ABORTED"),
interruptedFailure === "OFFLINE",
);
}
}
const afterApplyFailure = currentFailure(
stopKind,
state,
runGeneration,
generation,
isCurrent,
dependencies.environment,
);
if (afterApplyFailure) {
return pollFailure(
afterApplyFailure,
afterApplyFailure === "OFFLINE",
);
}
const applyFinishedAt = safeNow(clock);
if (
applyFinishedAt === null ||
applyFinishedAt < attemptFinishedAt
) {
return pollFailure("PROVIDER_UNAVAILABLE");
}
if (applyFinishedAt - startedAtMs >= policy.maxElapsedMs) {
return pollFailure("POLL_BUDGET_EXHAUSTED");
}
if (
valueResult.state &&
policy.terminalStates.includes(valueResult.state)
) {
return realtimeSuccess(
Object.freeze({
kind: "TERMINAL" as const,
attempts,
state: valueResult.state,
value: valueResult.value,
}),
);
}
const delay = successDelay(policy, random);
if (delay === null) {
return pollFailure("PROTOCOL_MISMATCH");
}
nextDelayMs = delay;
}
} finally {
input.signal?.removeEventListener("abort", onCallerAbort);
safelyUnsubscribe(unsubscribeVisibility);
safelyUnsubscribe(unsubscribeOnline);
if (activeController === controller) {
activeController = null;
}
if (generation === runGeneration) {
state = pendingWork === 0 ? "IDLE" : "DRAINING";
}
}
}
function trackWork<WorkValue>(
work: Promise<WorkValue>,
workGeneration: number,
): Promise<WorkValue> {
pendingWork += 1;
void work.then(
() => releaseWork(workGeneration),
() => releaseWork(workGeneration),
);
return work;
}
function releaseWork(workGeneration: number): void {
pendingWork = Math.max(0, pendingWork - 1);
if (
pendingWork === 0 &&
state === "DRAINING" &&
generation === workGeneration
) {
state = "IDLE";
}
}
function close(): void {
if (state === "CLOSED") return;
state = "CLOSED";
generation += 1;
activeController?.abort();
}
return Object.freeze({
run,
getState: () => state,
close,
});
}
function currentFailure(
requested: RealtimeFailureKind | null,
state: "CLOSED" | "DRAINING" | "IDLE" | "RUNNING",
runGeneration: number,
currentGeneration: number,
isCurrent: () => boolean,
environment: BoundedPollEnvironment,
): RealtimeFailureKind | null {
if (requested) return requested;
if (
state === "CLOSED" ||
state === "DRAINING" ||
runGeneration !== currentGeneration
) {
return "CLOSED";
}
if (!safeIsCurrent(isCurrent)) return "SCOPE_FENCED";
if (safeVisibility(environment) !== "VISIBLE") return "ABORTED";
if (safeOnline(environment) !== true) return "OFFLINE";
return null;
}
const LEASE_EXPIRED = Object.freeze({ kind: "TIMEOUT" as const });
/** Bounds work by the lease's remaining time; expiry stops the whole run. */
async function awaitWithinLease<Value>(
task: () => Promise<Value>,
remainingMs: number,
clock: ClockPort,
signal: AbortSignal,
onLeaseExpired: () => void,
): Promise<RealtimeRace<Value>> {
const outcome =
Number.isFinite(remainingMs) && remainingMs > 0
? await raceRealtimeTask(task, signal, (lease) =>
clock.sleep(remainingMs, lease),
)
: LEASE_EXPIRED;
if (outcome.kind === "TIMEOUT") onLeaseExpired();
return outcome;
}
function parseAttemptResult<Value>(
result: unknown,
): BoundedPollAttemptResult<Value> | null {
const outer = snapshotDataRecord(result, [
["error", "ok"],
["ok", "value"],
]);
if (!outer) return null;
if (outer.ok === false) {
const error = snapshotDataRecord(outer.error, [
["kind", "operation", "retryable"],
["kind", "operation", "retryable", "retryAfterMs"],
]);
if (
!error ||
!REALTIME_FAILURE_KINDS.includes(
error.kind as RealtimeFailureKind,
) ||
error.operation !== "POLL" ||
typeof error.retryable !== "boolean" ||
(Object.hasOwn(error, "retryAfterMs") &&
(!Number.isSafeInteger(error.retryAfterMs) ||
(error.retryAfterMs as number) < 0))
) {
return null;
}
const canonicalError = Object.freeze({
kind: error.kind as RealtimeFailureKind,
operation: "POLL" as const,
retryable: error.retryable,
...(Object.hasOwn(error, "retryAfterMs")
? { retryAfterMs: error.retryAfterMs as number }
: {}),
});
return Object.freeze({
ok: false as const,
error: canonicalError,
});
}
if (outer.ok !== true) return null;
const value = snapshotDataRecord(outer.value, [
["kind", "responseBytes"],
["kind", "responseBytes", "state", "value"],
["kind", "responseBytes", "value"],
]);
if (
!value ||
!Number.isSafeInteger(value.responseBytes) ||
(value.responseBytes as number) < 0
) {
return null;
}
if (value.kind === "UNCHANGED") {
return value.responseBytes === 0
? Object.freeze({
ok: true as const,
value: Object.freeze({
kind: "UNCHANGED" as const,
responseBytes: 0 as const,
}),
})
: null;
}
if (
value.kind !== "VALUE" ||
(Object.hasOwn(value, "state") &&
(typeof value.state !== "string" ||
!SAFE_STATE.test(value.state)))
) {
return null;
}
return Object.freeze({
ok: true as const,
value: Object.freeze({
kind: "VALUE" as const,
value: value.value as Value,
responseBytes: value.responseBytes as number,
...(Object.hasOwn(value, "state")
? { state: value.state as string }
: {}),
}),
});
}
function snapshotDataRecord(
value: unknown,
allowedKeySets: readonly (readonly string[])[],
): Readonly<Record<string, unknown>> | null {
const snapshot = captureRealtimeDataSnapshot(value);
return snapshot && hasExactSnapshotKeys(snapshot, ...allowedKeySets)
? snapshot.values
: null;
}
function retryDelay(
policy: PollLeasePolicy,
consecutiveFailures: number,
retryAfterMs: number | undefined,
random: () => number,
): number | null {
const sample = safeRandom(random);
if (sample === null) return null;
if (
retryAfterMs !== undefined &&
(!Number.isSafeInteger(retryAfterMs) ||
retryAfterMs < 0 ||
retryAfterMs > policy.maxIntervalMs)
) {
return null;
}
const ceiling = Math.min(
policy.maxIntervalMs,
policy.minimumIntervalMs * 2 ** Math.max(0, consecutiveFailures - 1),
);
return Math.max(
policy.minimumIntervalMs,
Math.floor(ceiling * sample),
retryAfterMs ?? 0,
);
}
function isPollRetryableFailureKind(
kind: RealtimeFailureKind,
): boolean {
return POLL_RETRYABLE_FAILURE_KINDS.includes(
kind as (typeof POLL_RETRYABLE_FAILURE_KINDS)[number],
);
}
function isPollRetryAfterFailureKind(
kind: RealtimeFailureKind,
): boolean {
return POLL_RETRY_AFTER_FAILURE_KINDS.includes(
kind as (typeof POLL_RETRY_AFTER_FAILURE_KINDS)[number],
);
}
function successDelay(
policy: PollLeasePolicy,
random: () => number,
): number | null {
const sample = safeRandom(random);
if (sample === null) return null;
const spread = Math.floor(policy.successIntervalMs * 0.1);
return Math.min(
policy.maxIntervalMs,
Math.max(
policy.minimumIntervalMs,
policy.successIntervalMs -
spread +
Math.floor(2 * spread * sample),
),
);
}
function safeRandom(random: () => number): number | null {
try {
const value = random();
return Number.isFinite(value) && value >= 0 && value < 1
? value
: null;
} catch {
return null;
}
}
function safeNow(clock: ClockPort): number | null {
try {
const value = clock.now();
return Number.isFinite(value) ? value : null;
} catch {
return null;
}
}
function safeIsCurrent(isCurrent: () => boolean): boolean {
try {
return isCurrent() === true;
} catch {
return false;
}
}
function safeVisibility(
environment: BoundedPollEnvironment,
): "HIDDEN" | "VISIBLE" | null {
try {
const value = environment.visibility();
return value === "HIDDEN" || value === "VISIBLE" ? value : null;
} catch {
return null;
}
}
function safeOnline(
environment: BoundedPollEnvironment,
): boolean | null {
try {
const value = environment.online();
return typeof value === "boolean" ? value : null;
} catch {
return null;
}
}
function safelyUnsubscribe(
unsubscribe: (() => void) | undefined,
): void {
try {
unsubscribe?.();
} catch {
// Lifecycle cleanup remains terminal even for a throwing host.
}
}
function pollFailure(
kind: RealtimeFailureKind,
retryable = false,
): BoundedPollResult<never> {
return realtimeFailure(kind, "POLL", retryable);
}
function applyFailure(): BoundedPollResult<never> {
return realtimeFailure("APPLY_FAILED", "APPLY", false);
}