refactor(realtime): merge snapshot and race helpers, move shared parsers to kernel (Q-6.4-8)

Realtime kept three DataSnapshot readers and about ten hand-written
abort/timeout races, and two parsers had drifted copies in other adapters.

Snapshot: reconnect-coordinator and bounded-poll now use result.ts
captureRealtimeDataSnapshot (+ `source`, variadic hasExactSnapshotKeys).
Kept the result.ts rules, the stricter ones: Object.hasOwn instead of
`"value" in` (prototype pollution), enumerable fields only, keys read from
one descriptor snapshot, frozen computed at snapshot time instead of a
later Object.isFrozen. Poll therefore now rejects non-enumerable fields;
it also accepts null-prototype records, which the other two copies
already did (pure data, no inherited accessors). Characterization test
added for both in bounded-poll-coordinator.test.ts.

Race: one raceRealtimeTask(task, signal, deadline) in result.ts, built on
kernel createAbortableOperation, replaces fetch-sse timed/cancelReader,
reconnect race/drain (the drain keeps a host timer via timerDeadline,
since the clock itself may hang), poll awaitTaskOrAbort/awaitWithinLease,
live-poll checkpoint + two quiescence races (now one), stream-coordinator
deadline/recovery-wait/close-drain, and the two WS inline races. Kept
semantics: deadline armed first and wins a tie (poll lease), task still
starts when the clock throws (reader cancel), collaborator rejections
still reach stream-coordinator callers, scheduler install failure still
fails closed as a timeout. Small change: nothing starts once the signal is
already aborted (WS apply / SSE onEvent / reader.read could run just
before being reported ABORTED). The mapping adds one microtask per race,
so the reconnect test flush() helper gets 16 turns instead of 8.

Kernel: parseRetryAfterDelay moves to platform/retry-after.ts (realtime
re-exports it; http retry-policy parseRetryAfter now delegates, so it
rejects "", "  ", "1e3", "1.5", "0x10" and non-IMF dates it used to
accept). json-member-scanner moves to platform/; web-push push-codec uses
it instead of its top-level-only duplicate-key check, so nested
duplicates are rejected too. INVENTORY 136 -> 137, detail tables updated.

Tests: RED for http strict Retry-After, web-push nested duplicate, poll
snapshot rules; new direct raceRealtimeTask tests. Gates: architecture,
types app/test (+ service-worker/web-worker), lint, adapter-inventory
(abort ratchet 21/21), test:unit, test:component, realtime-boundaries,
integration/platform all pass. Realtime bundle 40346 -> 39433 gzip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-24 13:54:42 +09:00
co-authored by Claude Opus 5.5
parent 54e6bce9d2
commit ae2f006b6d
22 changed files with 674 additions and 1071 deletions
+3 -10
View File
@@ -1,3 +1,5 @@
import { parseRetryAfterDelay } from "../platform/retry-after.ts";
const retryKinds: ReadonlySet<string> = new Set([
"NETWORK_UNREACHABLE",
"REQUEST_TIMEOUT",
@@ -18,16 +20,7 @@ export function parseRetryAfter(
value: string | null | undefined,
now = Date.now(),
): number | null {
if (!value) return null;
const seconds = Number(value);
if (Number.isFinite(seconds)) {
return seconds < 0 ? null : seconds * 1_000;
}
const timestamp = Date.parse(value);
if (!Number.isFinite(timestamp)) return null;
return Math.max(0, timestamp - now);
return parseRetryAfterDelay(value, now);
}
export type RetryOperation = Readonly<{
+38
View File
@@ -0,0 +1,38 @@
/**
* Parses an HTTP Retry-After value: delta-seconds (digits only, surrounding
* whitespace allowed) or an IMF-fixdate. Anything else — decimals, exponents,
* blank text, other date spellings — is `null`, never a guessed delay.
* No runtime ceiling is applied; callers reject a value above their budget.
*/
export function parseRetryAfterDelay(
value: string | null | undefined,
nowEpochMs: number,
): number | null {
if (
typeof value !== "string" ||
value.length === 0 ||
value.length > 128 ||
!Number.isFinite(nowEpochMs)
) {
return null;
}
const normalized = value.trim();
if (/^\d+$/u.test(normalized)) {
const seconds = Number(normalized);
return Number.isSafeInteger(seconds) &&
seconds <= Math.floor(Number.MAX_SAFE_INTEGER / 1_000)
? seconds * 1_000
: null;
}
if (
!/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/u.test(
normalized,
)
) {
return null;
}
const timestamp = Date.parse(normalized);
return Number.isFinite(timestamp)
? Math.max(0, timestamp - nowEpochMs)
: null;
}
+1 -1
View File
@@ -24,7 +24,7 @@ import {
} from "../../contracts/schema-registry.ts";
import {
hasDuplicateJsonMembers,
} from "./json-member-scanner.ts";
} from "../platform/json-member-scanner.ts";
export type ValidatedRealtimeEventDto = Readonly<{
envelope: RealtimeEventEnvelope;
@@ -7,6 +7,7 @@ import {
import { systemClock } from "../platform/system-clock.ts";
import {
isRealtimeResult,
raceRealtimeTask,
realtimeFailure,
realtimeSuccess,
} from "./result.ts";
@@ -555,24 +556,6 @@ export function createLivePollHandoffCoordinator<Value>(
from: LivePollWriterKind,
candidate: InternalWriterLease<Value>,
): Promise<RealtimeResult<void>> {
const timer = new AbortController();
let releaseAbortGate = (): void => undefined;
const aborted = new Promise<
Readonly<{ kind: "ABORTED" }>
>((resolve) => {
const onAbort = () => resolve({ kind: "ABORTED" });
candidate.controller.signal.addEventListener(
"abort",
onAbort,
{ once: true },
);
releaseAbortGate = () =>
candidate.controller.signal.removeEventListener(
"abort",
onAbort,
);
if (candidate.controller.signal.aborted) onAbort();
});
const operation = Promise.resolve()
.then(() =>
dependencies.establishAuthoritativeCheckpoint(
@@ -585,59 +568,30 @@ export function createLivePollHandoffCoordinator<Value>(
isCheckpointCandidateCurrent(candidate),
}),
),
)
.then(
(value) => ({ kind: "VALUE" as const, value }),
() => ({ kind: "REJECTED" as const }),
);
// RT-RR-04. Registered at the moment the authority is called, and removed
// only when it settles, so `close()` cannot report quiescence over it.
checkpointTasks.add(operation);
void operation.finally(() => {
checkpointTasks.delete(operation);
const settled = operation.then(
() => undefined,
() => undefined,
);
checkpointTasks.add(settled);
void settled.then(() => {
checkpointTasks.delete(settled);
});
const timeout = Promise.resolve()
.then(async () => {
await clock.sleep(
limits.quiescenceTimeoutMs,
timer.signal,
);
return { kind: "TIMED_OUT" as const };
})
.catch(() => ({
kind: timer.signal.aborted
? ("CANCELED" as const)
: ("TIMER_FAILED" as const),
}));
const selected = await Promise.race([
operation,
timeout,
aborted,
]);
timer.abort();
releaseAbortGate();
const selected = await raceRealtimeTask(
() => operation,
candidate.controller.signal,
(signal) => clock.sleep(limits.quiescenceTimeoutMs, signal),
);
if (selected.kind === "ABORTED") {
return handoffFailure("ABORTED", "RECOVER");
}
if (selected.kind === "TIMED_OUT") {
if (selected.kind === "TIMEOUT") {
candidate.controller.abort();
return handoffFailure("IDLE_TIMEOUT", "RECOVER");
}
if (
selected.kind === "TIMER_FAILED" ||
selected.kind === "REJECTED"
) {
candidate.controller.abort();
return handoffFailure(
"PROVIDER_UNAVAILABLE",
"RECOVER",
true,
);
}
if (selected.kind === "CANCELED") {
return handoffFailure("ABORTED", "RECOVER");
}
if (selected.kind !== "VALUE") {
candidate.controller.abort();
return handoffFailure(
@@ -673,50 +627,22 @@ export function createLivePollHandoffCoordinator<Value>(
async function awaitTaskQuiescence(
task: Promise<unknown>,
): Promise<QuiescenceOutcome> {
const timer = new AbortController();
const settled = task.then(
() => "QUIESCED" as const,
() => "QUIESCED" as const,
const outcome = await raceRealtimeTask(
() => task,
undefined,
(signal) => clock.sleep(limits.quiescenceTimeoutMs, signal),
);
const timeout = Promise.resolve()
.then(async () => {
await clock.sleep(limits.quiescenceTimeoutMs, timer.signal);
return "TIMED_OUT" as const;
})
.catch(() =>
timer.signal.aborted
? ("QUIESCED" as const)
: ("TIMER_FAILED" as const),
);
const outcome = await Promise.race([settled, timeout]);
timer.abort();
return outcome;
return outcome.kind === "TIMEOUT"
? "TIMED_OUT"
: outcome.kind === "CLOCK_FAILED"
? "TIMER_FAILED"
: "QUIESCED";
}
async function awaitQuiescence(
function awaitQuiescence(
lease: InternalWriterLease<Value>,
): Promise<QuiescenceOutcome> {
const timer = new AbortController();
const settled = lease.tail.then(
() => "QUIESCED" as const,
() => "QUIESCED" as const,
);
const timeout = Promise.resolve()
.then(async () => {
await clock.sleep(
limits.quiescenceTimeoutMs,
timer.signal,
);
return "TIMED_OUT" as const;
})
.catch(() =>
timer.signal.aborted
? ("QUIESCED" as const)
: ("TIMER_FAILED" as const),
);
const outcome = await Promise.race([settled, timeout]);
timer.abort();
return outcome;
return awaitTaskQuiescence(lease.tail);
}
function close(): Promise<RealtimeResult<void>> {
@@ -13,8 +13,12 @@ import {
} from "../../../application/ports/realtime/shared.ts";
import { systemClock } from "../../platform/system-clock.ts";
import {
captureRealtimeDataSnapshot,
hasExactSnapshotKeys,
raceRealtimeTask,
realtimeFailure,
realtimeSuccess,
type RealtimeRace,
} from "../result.ts";
/**
@@ -216,7 +220,7 @@ export function createBoundedPollCoordinator<Value>(
) {
return pollFailure("POLL_BUDGET_EXHAUSTED");
}
const cadenceOutcome = await awaitTaskOrAbort(
const cadenceOutcome = await raceRealtimeTask(
() => clock.sleep(nextDelayMs, controller.signal),
controller.signal,
);
@@ -231,7 +235,7 @@ export function createBoundedPollCoordinator<Value>(
);
return pollFailure(
afterSleepFailure ??
(cadenceOutcome.kind === "THREW"
(cadenceOutcome.kind === "REJECTED"
? "PROVIDER_UNAVAILABLE"
: "ABORTED"),
afterSleepFailure === "OFFLINE",
@@ -281,7 +285,7 @@ export function createBoundedPollCoordinator<Value>(
);
if (attemptOutcome.kind === "VALUE") {
result = attemptOutcome.value;
} else if (attemptOutcome.kind === "THREW") {
} else if (attemptOutcome.kind === "REJECTED") {
result = realtimeFailure(
controller.signal.aborted ? "ABORTED" : "OFFLINE",
"POLL",
@@ -411,7 +415,7 @@ export function createBoundedPollCoordinator<Value>(
controller.signal,
() => stop("POLL_BUDGET_EXHAUSTED"),
);
if (applyOutcome.kind === "THREW") {
if (applyOutcome.kind === "REJECTED") {
return applyFailure();
}
if (applyOutcome.kind !== "VALUE") {
@@ -550,156 +554,24 @@ function currentFailure(
return null;
}
type TaskOutcome<Value> =
| Readonly<{ kind: "VALUE"; value: Value }>
| Readonly<{ kind: "THREW" }>
| Readonly<{ kind: "ABORTED" }>;
type LeaseTaskOutcome<Value> =
| TaskOutcome<Value>
| Readonly<{ kind: "LEASE_EXPIRED" }>
| Readonly<{ kind: "CLOCK_FAILED" }>;
async function awaitTaskOrAbort<Value>(
task: () => Promise<Value>,
signal: AbortSignal,
): Promise<TaskOutcome<Value>> {
if (signal.aborted) return Object.freeze({ kind: "ABORTED" });
let removeAbortListener: () => void = () => undefined;
const aborted = new Promise<Readonly<{ kind: "ABORTED" }>>(
(resolve) => {
const onAbort = () => resolve(Object.freeze({ kind: "ABORTED" }));
signal.addEventListener("abort", onAbort, { once: true });
removeAbortListener = () =>
signal.removeEventListener("abort", onAbort);
if (signal.aborted) onAbort();
},
);
if (signal.aborted) {
removeAbortListener();
return Object.freeze({ kind: "ABORTED" });
}
let taskPromise: Promise<Value>;
try {
taskPromise = task();
} catch {
removeAbortListener();
return Object.freeze({ kind: "THREW" });
}
const completed = taskPromise.then<
TaskOutcome<Value>,
TaskOutcome<Value>
>(
(value) => Object.freeze({ kind: "VALUE", value }),
() => Object.freeze({ kind: "THREW" }),
);
try {
return await Promise.race([completed, aborted]);
} finally {
removeAbortListener();
}
}
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<LeaseTaskOutcome<Value>> {
if (!Number.isFinite(remainingMs) || remainingMs <= 0) {
onLeaseExpired();
return Object.freeze({ kind: "LEASE_EXPIRED" });
}
if (signal.aborted) return Object.freeze({ kind: "ABORTED" });
const deadlineController = new AbortController();
let resolveInterruption:
| ((outcome: LeaseTaskOutcome<Value>) => void)
| undefined;
let removeAbortListener: () => void = () => undefined;
let interruptionSettled = false;
const finishInterruption = (
outcome: LeaseTaskOutcome<Value>,
): boolean => {
if (interruptionSettled) return false;
interruptionSettled = true;
resolveInterruption?.(outcome);
return true;
};
const interrupted = new Promise<LeaseTaskOutcome<Value>>((resolve) => {
resolveInterruption = resolve;
const onAbort = () =>
finishInterruption(Object.freeze({ kind: "ABORTED" }));
signal.addEventListener("abort", onAbort, { once: true });
removeAbortListener = () =>
signal.removeEventListener("abort", onAbort);
if (signal.aborted) onAbort();
});
if (signal.aborted) {
removeAbortListener();
return Object.freeze({ kind: "ABORTED" });
}
let deadlineSleep: Promise<void>;
try {
deadlineSleep = clock.sleep(
remainingMs,
deadlineController.signal,
);
} catch {
removeAbortListener();
deadlineController.abort();
return Object.freeze({ kind: "CLOCK_FAILED" });
}
const deadline = deadlineSleep.then(
() => {
if (deadlineController.signal.aborted) return;
if (
finishInterruption(
Object.freeze({ kind: "LEASE_EXPIRED" }),
): Promise<RealtimeRace<Value>> {
const outcome =
Number.isFinite(remainingMs) && remainingMs > 0
? await raceRealtimeTask(task, signal, (lease) =>
clock.sleep(remainingMs, lease),
)
) {
onLeaseExpired();
}
},
() => {
if (!deadlineController.signal.aborted) {
finishInterruption(
Object.freeze({ kind: "CLOCK_FAILED" }),
);
}
},
);
if (signal.aborted) {
removeAbortListener();
deadlineController.abort();
void deadline;
return Object.freeze({ kind: "ABORTED" });
}
let taskPromise: Promise<Value>;
try {
taskPromise = task();
} catch {
taskPromise = Promise.reject(new Error("Task failed."));
}
const completed = taskPromise.then<
LeaseTaskOutcome<Value>,
LeaseTaskOutcome<Value>
>(
(value) => Object.freeze({ kind: "VALUE", value }),
() => Object.freeze({ kind: "THREW" }),
);
try {
const outcome = await Promise.race([completed, interrupted]);
void deadline;
return outcome;
} finally {
removeAbortListener();
deadlineController.abort();
}
: LEASE_EXPIRED;
if (outcome.kind === "TIMEOUT") onLeaseExpired();
return outcome;
}
function parseAttemptResult<Value>(
@@ -790,42 +662,10 @@ function snapshotDataRecord(
value: unknown,
allowedKeySets: readonly (readonly string[])[],
): Readonly<Record<string, unknown>> | null {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return null;
}
try {
if (Object.getPrototypeOf(value) !== Object.prototype) {
return null;
}
const keys = Reflect.ownKeys(value);
if (keys.some((key) => typeof key !== "string")) return null;
const sortedKeys = (keys as string[]).sort();
if (
!allowedKeySets.some((allowed) => {
const sortedAllowed = [...allowed].sort();
return (
sortedKeys.length === sortedAllowed.length &&
sortedKeys.every(
(key, index) => key === sortedAllowed[index],
)
);
})
) {
return null;
}
const descriptors = Object.getOwnPropertyDescriptors(value);
const snapshot: Record<string, unknown> = {};
for (const key of sortedKeys) {
const descriptor = descriptors[key];
if (!descriptor || !Object.hasOwn(descriptor, "value")) {
return null;
}
snapshot[key] = descriptor.value;
}
return Object.freeze(snapshot);
} catch {
return null;
}
const snapshot = captureRealtimeDataSnapshot(value);
return snapshot && hasExactSnapshotKeys(snapshot, ...allowedKeySets)
? snapshot.values
: null;
}
function retryDelay(
+61 -163
View File
@@ -16,9 +16,14 @@ import {
type ReconnectPolicy,
} from "./reconnect-policy.ts";
import {
captureRealtimeDataSnapshot,
hasExactSnapshotKeys,
isRealtimeResult,
isRealtimeTransportEventOutcome,
raceRealtimeTask,
realtimeFailure,
timerDeadline,
type RealtimeDataSnapshot,
} from "./result.ts";
type FailureResult = Extract<RealtimeResult<never>, { ok: false }>;
@@ -226,12 +231,6 @@ type ParsedCloseClassification =
directive: ParsedRecoveryDirective;
}>;
type DataSnapshot = Readonly<{
source: object;
keys: readonly string[];
values: Readonly<Record<string, unknown>>;
}>;
type ParsedRunInput = Readonly<{
signal: AbortSignal | undefined;
initialRecovery: ParsedRecoveryDirective | null;
@@ -1023,65 +1022,31 @@ export function createRealtimeReconnectCoordinator<ClosedReceipt>(
});
}
const INTERRUPTED = Object.freeze({ kind: "INTERRUPTED" as const });
async function race<Value>(
task: Promise<Settled<Value>>,
signal: AbortSignal,
): Promise<AwaitedTask<Value>> {
if (signal.aborted) return Object.freeze({ kind: "INTERRUPTED" });
let cleanup: () => void = () => undefined;
const interrupted = new Promise<
Readonly<{ kind: "INTERRUPTED" }>
>((resolve) => {
const abort = () =>
resolve(Object.freeze({ kind: "INTERRUPTED" }));
signal.addEventListener("abort", abort, { once: true });
cleanup = () => signal.removeEventListener("abort", abort);
if (signal.aborted) abort();
});
try {
return await Promise.race([task, interrupted]);
} finally {
cleanup();
}
const raced = await raceRealtimeTask(() => task, signal);
return raced.kind === "VALUE" ? raced.value : INTERRUPTED;
}
async function drainWithinCeiling<Value>(
task: Promise<Settled<Value>>,
signal: AbortSignal,
): Promise<DrainedTask<Value>> {
if (signal.aborted) return Object.freeze({ kind: "INTERRUPTED" });
let timer: ReturnType<typeof setTimeout> | undefined;
let cleanup: () => void = () => undefined;
const boundary = new Promise<
| Readonly<{ kind: "INTERRUPTED" }>
| Readonly<{ kind: "TIMED_OUT" }>
>((resolve) => {
const abort = () =>
resolve(Object.freeze({ kind: "INTERRUPTED" }));
cleanup = () => safelyRemoveAbortListener(signal, abort);
try {
signal.addEventListener("abort", abort, { once: true });
timer = setTimeout(
() => resolve(Object.freeze({ kind: "TIMED_OUT" })),
REALTIME_RECONNECT_CEILINGS.drainTimeoutMs,
);
} catch {
resolve(Object.freeze({ kind: "TIMED_OUT" }));
}
if (signal.aborted) abort();
});
try {
return await Promise.race([task, boundary]);
} finally {
cleanup();
if (timer !== undefined) {
try {
clearTimeout(timer);
} catch {
// The generation remains fenced if host timer cleanup fails.
}
}
}
// A host timer, not the clock: a non-cooperative clock is one of the things
// this drain has to bound.
const raced = await raceRealtimeTask(
() => task,
signal,
timerDeadline(REALTIME_RECONNECT_CEILINGS.drainTimeoutMs),
);
if (raced.kind === "VALUE") return raced.value;
return raced.kind === "ABORTED"
? INTERRUPTED
: Object.freeze({ kind: "TIMED_OUT" });
}
function createBarrierGate(): BarrierGate {
@@ -1104,15 +1069,16 @@ function createBarrierGate(): BarrierGate {
}
function parseRunInput(value: unknown): ParsedRunInput | null {
const snapshot = captureDataSnapshot(value);
const snapshot = captureRealtimeDataSnapshot(value);
if (
!snapshot ||
!hasOneExactKeySet(snapshot, [
!hasExactSnapshotKeys(
snapshot,
[],
["signal"],
["initialRecovery"],
["initialRecovery", "signal"],
])
)
) {
return null;
}
@@ -1130,7 +1096,7 @@ function parseRunInput(value: unknown): ParsedRunInput | null {
initialValue === undefined
? null
: parseRecoveryDirectiveSnapshot(
captureDataSnapshot(initialValue),
captureRealtimeDataSnapshot(initialValue),
);
if (initialValue !== undefined && !initialRecovery) return null;
return Object.freeze({
@@ -1143,28 +1109,29 @@ function parseAttemptOutcome<ClosedReceipt>(
value: unknown,
): ParsedOutcome<ParsedAttemptSuccess<ClosedReceipt>> | null {
return parseOutcomeSnapshot(
captureDataSnapshot(value),
captureRealtimeDataSnapshot(value),
(candidate) =>
parseAttemptSuccess<ClosedReceipt>(
captureDataSnapshot(candidate),
captureRealtimeDataSnapshot(candidate),
),
);
}
function parseAttemptSuccess<ClosedReceipt>(
snapshot: DataSnapshot | null,
snapshot: RealtimeDataSnapshot | null,
): ParsedValue<ParsedAttemptSuccess<ClosedReceipt>> | null {
if (
!snapshot ||
!hasOneExactKeySet(snapshot, [
!hasExactSnapshotKeys(
snapshot,
["session"],
["establishedRecoveryBarrier", "session"],
])
)
) {
return null;
}
const session = parseSession<ClosedReceipt>(
captureDataSnapshot(snapshot.values.session),
captureRealtimeDataSnapshot(snapshot.values.session),
);
if (!session) return null;
const hasRecoveryBarrier = snapshot.keys.includes(
@@ -1181,11 +1148,11 @@ function parseAttemptSuccess<ClosedReceipt>(
}
function parseSession<ClosedReceipt>(
snapshot: DataSnapshot | null,
snapshot: RealtimeDataSnapshot | null,
): RealtimeReconnectSession<ClosedReceipt> | null {
if (
!snapshot ||
!hasExactKeys(snapshot, [
!hasExactSnapshotKeys(snapshot, [
"classifyClosed",
"close",
"waitClosed",
@@ -1221,7 +1188,7 @@ function parseSession<ClosedReceipt>(
function parseCloseClassification(
value: unknown,
): ParsedCloseClassification | null {
const snapshot = captureDataSnapshot(value);
const snapshot = captureRealtimeDataSnapshot(value);
if (!snapshot) return null;
if (snapshot.values.kind === "RECOVERY_RECONNECT") {
const directive = parseRecoveryDirectiveSnapshot(snapshot);
@@ -1245,11 +1212,12 @@ function parseCloseClassification(
}
function parseRecoveryDirectiveSnapshot(
snapshot: DataSnapshot | null,
snapshot: RealtimeDataSnapshot | null,
): ParsedRecoveryDirective | null {
if (
!snapshot ||
!hasOneExactKeySet(snapshot, [
!hasExactSnapshotKeys(
snapshot,
["kind", "recovery", "terminalResult"],
[
"kind",
@@ -1257,13 +1225,13 @@ function parseRecoveryDirectiveSnapshot(
"serverNotBeforeMs",
"terminalResult",
],
]) ||
) ||
snapshot.values.kind !== "RECOVERY_RECONNECT"
) {
return null;
}
const recovery = parseCommittedRecovery(
captureDataSnapshot(snapshot.values.recovery),
captureRealtimeDataSnapshot(snapshot.values.recovery),
);
const terminalFailure = parseFailureResult(
snapshot.values.terminalResult,
@@ -1286,32 +1254,32 @@ function parseRecoveryDirectiveSnapshot(
}
function parseCommittedRecovery(
snapshot: DataSnapshot | null,
snapshot: RealtimeDataSnapshot | null,
): RealtimeCommittedRecovery | null {
if (
!snapshot ||
!hasExactKeys(snapshot, [
!hasExactSnapshotKeys(snapshot, [
"checkpoint",
"kind",
"streamId",
]) ||
snapshot.values.kind !== "RECOVERY_COMMITTED" ||
!safeFrozen(snapshot.source)
!snapshot.frozen
) {
return null;
}
const checkpoint = captureDataSnapshot(
const checkpoint = captureRealtimeDataSnapshot(
snapshot.values.checkpoint,
);
if (
!checkpoint ||
!hasExactKeys(checkpoint, [
!hasExactSnapshotKeys(checkpoint, [
"lastAppliedSequence",
"recoveryMode",
"resumeCursor",
"streamEpoch",
]) ||
!safeFrozen(checkpoint.source)
!checkpoint.frozen
) {
return null;
}
@@ -1347,22 +1315,23 @@ function parseVoidResult(
}
function parseOutcomeSnapshot<Value>(
snapshot: DataSnapshot | null,
snapshot: RealtimeDataSnapshot | null,
parseValue: (candidate: unknown) => ParsedValue<Value> | null,
): ParsedOutcome<Value> | null {
if (
!snapshot ||
!hasOneExactKeySet(snapshot, [
!hasExactSnapshotKeys(
snapshot,
["result"],
["result", "serverNotBeforeMs"],
])
)
) {
return null;
}
const result = parseResult(snapshot.values.result, parseValue);
if (!result) return null;
if (result.ok) {
return hasExactKeys(snapshot, ["result"])
return hasExactSnapshotKeys(snapshot, ["result"])
? Object.freeze({
ok: true,
result: result.result,
@@ -1385,11 +1354,11 @@ function parseResult<Value>(
value: unknown,
parseValue: (candidate: unknown) => ParsedValue<Value> | null,
): ParsedResult<Value> | null {
const snapshot = captureDataSnapshot(value);
if (!snapshot || !safeFrozen(snapshot.source)) return null;
const snapshot = captureRealtimeDataSnapshot(value);
if (!snapshot || !snapshot.frozen) return null;
if (snapshot.values.ok === true) {
if (!hasExactKeys(snapshot, ["ok", "value"])) return null;
if (!hasExactSnapshotKeys(snapshot, ["ok", "value"])) return null;
const parsedValue = parseValue(snapshot.values.value);
const canonical = Object.freeze({
ok: true,
@@ -1420,29 +1389,29 @@ function parseResult<Value>(
function parseFailureResult(
value: unknown,
): FailureSnapshot | null {
return parseFailureResultSnapshot(captureDataSnapshot(value));
return parseFailureResultSnapshot(captureRealtimeDataSnapshot(value));
}
function parseFailureResultSnapshot(
snapshot: DataSnapshot | null,
snapshot: RealtimeDataSnapshot | null,
): FailureSnapshot | null {
if (
!snapshot ||
!hasExactKeys(snapshot, ["error", "ok"]) ||
!hasExactSnapshotKeys(snapshot, ["error", "ok"]) ||
snapshot.values.ok !== false ||
!safeFrozen(snapshot.source)
!snapshot.frozen
) {
return null;
}
const error = captureDataSnapshot(snapshot.values.error);
const error = captureRealtimeDataSnapshot(snapshot.values.error);
if (
!error ||
!hasExactKeys(error, [
!hasExactSnapshotKeys(error, [
"kind",
"operation",
"retryable",
]) ||
!safeFrozen(error.source)
!error.frozen
) {
return null;
}
@@ -1472,69 +1441,6 @@ function parseFailureResultSnapshot(
});
}
function captureDataSnapshot(value: unknown): DataSnapshot | null {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return null;
}
try {
const prototype = Object.getPrototypeOf(value);
if (
prototype !== Object.prototype &&
prototype !== null
) {
return null;
}
const descriptors = Object.getOwnPropertyDescriptors(value);
const ownKeys = Reflect.ownKeys(descriptors);
if (ownKeys.some((key) => typeof key !== "string")) {
return null;
}
const keys = (ownKeys as string[]).sort();
const values = Object.create(null) as Record<string, unknown>;
for (const key of keys) {
const descriptor = descriptors[key];
if (
!descriptor ||
!("value" in descriptor) ||
descriptor.enumerable !== true
) {
return null;
}
Object.defineProperty(values, key, {
configurable: false,
enumerable: true,
value: descriptor.value,
writable: false,
});
}
return Object.freeze({
source: value,
keys: Object.freeze(keys),
values: Object.freeze(values),
});
} catch {
return null;
}
}
function hasOneExactKeySet(
snapshot: DataSnapshot,
expected: readonly (readonly string[])[],
): boolean {
return expected.some((keys) => hasExactKeys(snapshot, keys));
}
function hasExactKeys(
snapshot: DataSnapshot,
expected: readonly string[],
): boolean {
const sorted = [...expected].sort();
return (
snapshot.keys.length === sorted.length &&
snapshot.keys.every((key, index) => key === sorted[index])
);
}
function parseNotBefore(
value: unknown,
): number | null | undefined {
@@ -1709,14 +1615,6 @@ function safeSignalAborted(
}
}
function safeFrozen(value: object): boolean {
try {
return Object.isFrozen(value);
} catch {
return false;
}
}
function safelyAddAbortListener(
signal: AbortSignal | undefined,
listener: () => void,
+2 -37
View File
@@ -1,3 +1,5 @@
export { parseRetryAfterDelay } from "../platform/retry-after.ts";
export const REALTIME_RECONNECT_CEILINGS = Object.freeze({
drainTimeoutMs: 2_000,
maxAttempts: 10,
@@ -146,43 +148,6 @@ export function isReconnectAttemptResetEligible(input: Readonly<{
);
}
/**
* Parses the HTTP Retry-After delay without applying a runtime ceiling.
* Callers must reject a value that exceeds their remaining/max-delay budget.
*/
export function parseRetryAfterDelay(
value: string | null | undefined,
nowEpochMs: number,
): number | null {
if (
typeof value !== "string" ||
value.length === 0 ||
value.length > 128 ||
!Number.isFinite(nowEpochMs)
) {
return null;
}
const normalized = value.trim();
if (/^\d+$/u.test(normalized)) {
const seconds = Number(normalized);
return Number.isSafeInteger(seconds) &&
seconds <= Math.floor(Number.MAX_SAFE_INTEGER / 1_000)
? seconds * 1_000
: null;
}
if (
!/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/u.test(
normalized,
)
) {
return null;
}
const timestamp = Date.parse(normalized);
return Number.isFinite(timestamp)
? Math.max(0, timestamp - nowEpochMs)
: null;
}
function positiveInteger(value: number): boolean {
return Number.isSafeInteger(value) && value > 0;
}
+108 -7
View File
@@ -16,6 +16,7 @@ import {
isRealtimeOpaqueIdentifier,
isRealtimeResumeCursor,
} from "../../contracts/realtime-events.ts";
import { createAbortableOperation } from "../platform/abortable-operation.ts";
export type {
RealtimeFailure,
@@ -35,6 +36,8 @@ const FAILURE_KINDS = new Set<unknown>(REALTIME_FAILURE_KINDS);
const OPERATIONS = new Set<unknown>(REALTIME_OPERATIONS);
export type RealtimeDataSnapshot = Readonly<{
/** The object that was read; never read its properties again. */
source: object;
keys: readonly string[];
values: Readonly<Record<string, unknown>>;
frozen: boolean;
@@ -67,6 +70,100 @@ export function isRealtimeFailure(
return parseRealtimeFailure(value, true) !== null;
}
export type RealtimeRace<Value> =
| Readonly<{ kind: "VALUE"; value: Value }>
| Readonly<{ kind: "REJECTED" }>
| Readonly<{ kind: "ABORTED" }>
| Readonly<{ kind: "TIMEOUT" }>
| Readonly<{ kind: "CLOCK_FAILED" }>;
const REJECTED = Object.freeze({ kind: "REJECTED" as const });
const ABORTED = Object.freeze({ kind: "ABORTED" as const });
const TIMEOUT = Object.freeze({ kind: "TIMEOUT" as const });
const CLOCK_FAILED = Object.freeze({ kind: "CLOCK_FAILED" as const });
/**
* Realtime's one abort/deadline race, on the kernel abortable operation.
* Settles with whichever comes first: the task's value or rejection (a
* synchronous throw counts as one), `signal` aborting, or `deadline`
* resolving. A deadline that throws or rejects on its own is CLOCK_FAILED.
* Nothing starts when `signal` is already aborted.
*
* The task gets the operation signal, which aborts with `signal`, at the
* deadline and once the race is over. The deadline is armed before the task
* starts, so it wins a tie, but the task always starts (a cancel must not be
* skipped because the clock broke).
*/
export function raceRealtimeTask<Value>(
task: (signal: AbortSignal) => Value | PromiseLike<Value>,
signal?: AbortSignal,
deadline?: (signal: AbortSignal) => PromiseLike<unknown>,
): Promise<RealtimeRace<Value>> {
if (signal?.aborted) return Promise.resolve(ABORTED);
const timer = new AbortController();
const operation = createAbortableOperation({
signal,
...(deadline && {
timeoutMs: 0,
setTimer: (fire: () => void) =>
Promise.resolve(deadline(timer.signal)).then(fire, () =>
operation.close(),
),
clearTimer: () => timer.abort(),
}),
});
let running: Promise<Value>;
try {
running = Promise.resolve(task(operation.signal));
} catch (error) {
running = Promise.reject(error);
}
const raced = operation.race(running);
// Registered after the race, so the outcome is claimed first.
void running.then(operation.close, operation.close);
return raced.then((outcome) =>
outcome.kind === "VALUE"
? outcome
: outcome.kind === "REJECTED"
? REJECTED
: outcome.terminal === "CALLER_ABORT"
? ABORTED
: outcome.terminal === "DEADLINE"
? TIMEOUT
: CLOCK_FAILED,
);
}
/**
* A `raceRealtimeTask` deadline on a host timer instead of the injected
* clock, for bounds that must hold even when the clock itself hangs.
*/
export function timerDeadline(
delayMs: number,
schedule: (callback: () => void, delayMs: number) => unknown = (
callback,
delay,
) => setTimeout(callback, delay),
cancel: (handle: unknown) => void = (handle) =>
clearTimeout(handle as ReturnType<typeof setTimeout>),
): (signal: AbortSignal) => Promise<void> {
return (signal) =>
new Promise((resolve) => {
const handle = schedule(resolve, delayMs);
signal.addEventListener(
"abort",
() => {
try {
cancel(handle);
} catch {
// A broken scheduler cannot change the race outcome.
}
},
{ once: true },
);
});
}
/**
* Captures an external result through own data descriptors exactly once and
* returns a new canonical value. Callers that need to use the validated fields
@@ -186,6 +283,7 @@ export function captureRealtimeDataSnapshot(
descriptor.writable === false;
}
return Object.freeze({
source: value,
keys: Object.freeze(keys),
values: Object.freeze(values),
frozen,
@@ -266,13 +364,16 @@ function parseRealtimeFailure(
});
}
function hasExactSnapshotKeys(
/** True when the snapshot's keys are exactly one of the given key sets. */
export function hasExactSnapshotKeys(
snapshot: RealtimeDataSnapshot,
expectedKeys: readonly string[],
...keySets: readonly (readonly string[])[]
): boolean {
const expected = [...expectedKeys].sort();
return (
snapshot.keys.length === expected.length &&
snapshot.keys.every((key, index) => key === expected[index])
);
return keySets.some((keySet) => {
const expected = [...keySet].sort();
return (
snapshot.keys.length === expected.length &&
snapshot.keys.every((key, index) => key === expected[index])
);
});
}
+37 -135
View File
@@ -16,6 +16,7 @@ import { parseRetryAfterDelay } from "../reconnect-policy.ts";
import {
isRealtimeResult,
isRealtimeTransportEventOutcome,
raceRealtimeTask,
realtimeFailure,
realtimeSuccess,
} from "../result.ts";
@@ -162,30 +163,36 @@ export function createFetchSseConnection(
once: true,
});
if (input.signal?.aborted) onCallerAbort();
const timed = <Value>(
task: () => Value | PromiseLike<Value>,
timeoutMs: number,
) =>
raceRealtimeTask(task, controller.signal, (signal) =>
clock.sleep(timeoutMs, signal),
);
try {
const request = timed(
Promise.resolve().then(() =>
fetcher(endpoint.href, {
method: "GET",
credentials: "same-origin",
redirect: "error",
cache: "no-store",
referrerPolicy: "no-referrer",
headers: {
Accept: "text/event-stream",
...(input.resumeCursor === null
? {}
: { "Last-Event-ID": input.resumeCursor }),
},
signal: controller.signal,
}),
),
const responseResult = await timed(
// The fetcher starts on the next microtask, like other collaborators.
() =>
Promise.resolve().then(() =>
fetcher(endpoint.href, {
method: "GET",
credentials: "same-origin",
redirect: "error",
cache: "no-store",
referrerPolicy: "no-referrer",
headers: {
Accept: "text/event-stream",
...(input.resumeCursor === null
? {}
: { "Last-Event-ID": input.resumeCursor }),
},
signal: controller.signal,
}),
),
connectTimeoutMs,
clock,
controller.signal,
);
const responseResult = await request;
if (responseResult.kind === "CLOCK_FAILED") {
controller.abort();
return failed("PROVIDER_UNAVAILABLE", "CONNECT", true);
@@ -241,23 +248,11 @@ export function createFetchSseConnection(
const reader = response.body.getReader();
activeReader = reader;
let retryHintMs: number | null = null;
if (input.onOpen) {
let opening: Promise<RealtimeResult<void>>;
try {
opening = Promise.resolve(input.onOpen(controller.signal));
} catch {
await cancelReader(reader, clock, controller);
return failed(
"PROVIDER_UNAVAILABLE",
"CONNECT",
false,
);
}
const onOpen = input.onOpen;
if (onOpen) {
const opened = await timed(
opening,
() => onOpen(controller.signal),
connectTimeoutMs,
clock,
controller.signal,
);
if (opened.kind !== "VALUE") {
await cancelReader(reader, clock, controller);
@@ -318,22 +313,9 @@ export function createFetchSseConnection(
await cancelReader(reader, clock, controller);
return failed("PROTOCOL_MISMATCH", "DECODE", false);
}
let handler: Promise<
RealtimeResult<SseInboundEventOutcome>
>;
try {
handler = Promise.resolve(
input.onEvent(item, controller.signal),
);
} catch {
await cancelReader(reader, clock, controller);
return failed("APPLY_FAILED", "APPLY", false);
}
const handled = await timed(
handler,
() => input.onEvent(item, controller.signal),
idleTimeoutMs,
clock,
controller.signal,
);
if (handled.kind === "ABORTED") {
await cancelReader(reader, clock, controller);
@@ -384,10 +366,8 @@ export function createFetchSseConnection(
while (true) {
const readResult = await timed(
reader.read(),
() => reader.read(),
idleTimeoutMs,
clock,
controller.signal,
);
if (readResult.kind === "ABORTED") {
await cancelReader(reader, clock, controller);
@@ -598,66 +578,6 @@ function responseFailure(
return failed("PROTOCOL_MISMATCH", "CONNECT", false);
}
type TimedResult<Value> =
| Readonly<{ kind: "VALUE"; value: Value }>
| Readonly<{ kind: "REJECTED" }>
| Readonly<{ kind: "ABORTED" }>
| Readonly<{ kind: "CLOCK_FAILED" }>
| Readonly<{ kind: "TIMEOUT" }>;
async function timed<Value>(
operation: Promise<Value>,
timeoutMs: number,
clock: ClockPort,
signal: AbortSignal,
): Promise<TimedResult<Value>> {
if (signal.aborted) {
return Object.freeze({ kind: "ABORTED" });
}
const timer = new AbortController();
let abortListener: (() => void) | undefined;
const operationResult = operation.then<
TimedResult<Value>,
TimedResult<Value>
>(
(value) => Object.freeze({ kind: "VALUE", value }),
() => Object.freeze({ kind: "REJECTED" }),
);
let timeoutResult: Promise<TimedResult<Value>>;
try {
timeoutResult = clock.sleep(timeoutMs, timer.signal).then<
TimedResult<Value>,
TimedResult<Value>
>(
() => Object.freeze({ kind: "TIMEOUT" }),
() =>
Object.freeze({
kind: timer.signal.aborted
? ("ABORTED" as const)
: ("CLOCK_FAILED" as const),
}),
);
} catch {
return Object.freeze({ kind: "CLOCK_FAILED" });
}
const abortedResult = new Promise<TimedResult<Value>>((resolve) => {
abortListener = () =>
resolve(Object.freeze({ kind: "ABORTED" }));
signal.addEventListener("abort", abortListener, { once: true });
if (signal.aborted) abortListener();
});
const result = await Promise.race([
operationResult,
timeoutResult,
abortedResult,
]);
timer.abort();
if (abortListener) {
signal.removeEventListener("abort", abortListener);
}
return result;
}
function readClockNow(clock: ClockPort): number | null {
try {
const value = clock.now();
@@ -673,29 +593,11 @@ async function cancelReader(
generation?: AbortController,
): Promise<void> {
generation?.abort();
let cancellation: Promise<void>;
try {
cancellation = Promise.resolve(reader.cancel()).then(
() => undefined,
() => undefined,
);
} catch {
return;
}
const timeout = new AbortController();
let timeoutPromise: Promise<void>;
try {
timeoutPromise = clock
.sleep(READER_CANCEL_TIMEOUT_MS, timeout.signal)
.then(
() => undefined,
() => undefined,
);
} catch {
timeoutPromise = Promise.resolve();
}
await Promise.race([cancellation, timeoutPromise]);
timeout.abort();
await raceRealtimeTask(
() => reader.cancel(),
undefined,
(signal) => clock.sleep(READER_CANCEL_TIMEOUT_MS, signal),
);
}
function safelyNotify(
+29 -83
View File
@@ -35,6 +35,9 @@ import {
} from "./event-codec.ts";
import {
captureRealtimeDataSnapshot,
hasExactSnapshotKeys,
raceRealtimeTask,
timerDeadline,
realtimeFailure,
realtimeSuccess,
snapshotRealtimeResult,
@@ -184,15 +187,8 @@ export function createRealtimeStreamCoordinator(
});
const states = new Map<StreamRegistrationId, StreamState>();
let closed = false;
/** RT-02. Releasing a timer is best effort and never a public failure. */
const clearTimerSafely = (handle: unknown): void => {
try {
clearScheduledTimeout(handle);
} catch {
// A broken scheduler cannot change an already classified outcome.
}
};
const deadline = (delayMs: number) =>
timerDeadline(delayMs, scheduleTimeout, clearScheduledTimeout);
const TASK_TIMED_OUT = Symbol("REALTIME_TASK_TIMED_OUT");
@@ -227,26 +223,18 @@ export function createRealtimeStreamCoordinator(
if (!state.closed) state.freshness = "STALE";
}
});
// RT-02. A scheduler that cannot install the deadline leaves the wait
// unbounded. Letting the exception escape turned a typed realtime result
// into a native rejection and — through the caller's own catch — started a
// recovery that overlapped the effect still running, so an install failure
// fails closed as an expired deadline instead.
let handle: unknown;
let installed = false;
const timeout = new Promise<typeof TASK_TIMED_OUT>((resolve) => {
try {
handle = scheduleTimeout(() => resolve(TASK_TIMED_OUT), timeoutMs);
installed = true;
} catch {
resolve(TASK_TIMED_OUT);
}
});
const outcome = await Promise.race([task, timeout]);
if (installed) clearTimerSafely(handle);
if (outcome !== TASK_TIMED_OUT) return outcome;
// The commit capability is revoked immediately; the work itself is not.
const outcome = await raceRealtimeTask(
() => task,
undefined,
deadline(timeoutMs),
);
if (outcome.kind === "VALUE") return outcome.value;
// The collaborator's own rejection reaches the caller unchanged.
if (outcome.kind === "REJECTED") return await task;
// Expired, or (RT-02) a scheduler that could not install the deadline and
// left the wait unbounded: both fail closed as an expired deadline, not a
// native rejection that would start an overlapping recovery. The commit
// capability is revoked immediately; the work itself is not.
revokeAndAbort();
state.lifecycle = "DRAINING";
state.timedOutTasks.add(task);
@@ -920,32 +908,13 @@ export function createRealtimeStreamCoordinator(
const active = state.recoveryPromise;
const reason = state.activeRecoveryReason ?? "INITIALIZE";
if (!active) return dropped("RECOVERY_IN_PROGRESS");
if (signal?.aborted) {
return realtimeFailure("ABORTED", "RECEIVE");
}
let removeAbortListener: () => void = () => undefined;
const aborted = new Promise<Readonly<{ kind: "ABORTED" }>>(
(resolve) => {
if (!signal) return;
const onAbort = () => resolve({ kind: "ABORTED" });
signal.addEventListener("abort", onAbort, { once: true });
removeAbortListener = () =>
signal.removeEventListener("abort", onAbort);
if (signal.aborted) onAbort();
},
);
const settled = await Promise.race([
active.then((result) => ({
kind: "RESULT" as const,
result,
})),
aborted,
]);
removeAbortListener();
const settled = await raceRealtimeTask(() => active, signal);
if (settled.kind === "ABORTED") {
return realtimeFailure("ABORTED", "RECEIVE");
}
const result = settled.result;
// Only VALUE or REJECTED remain; a rejection propagates as before.
const result =
settled.kind === "VALUE" ? settled.value : await active;
if (!result.ok) return result;
return realtimeSuccess(
Object.freeze({
@@ -1040,26 +1009,14 @@ export function createRealtimeStreamCoordinator(
for (const state of states.values()) state.lifecycle = "CLOSED";
return realtimeSuccess(undefined);
}
let handle: unknown;
let installed = false;
const drained = await Promise.race([
Promise.allSettled(retained).then(() => true),
new Promise<false>((resolve) => {
try {
handle = scheduleTimeout(
() => resolve(false),
limits.drainTimeoutMs,
);
installed = true;
} catch {
// RT-02. Without a drain bound this call cannot prove quiescence, so
// it reports the honest failure rather than rejecting natively.
resolve(false);
}
}),
]);
if (installed) clearTimerSafely(handle);
if (!drained) {
// RT-02. Without a drain bound (CLOCK_FAILED) this call cannot prove
// quiescence, so it reports the honest failure rather than rejecting.
const drained = await raceRealtimeTask(
() => Promise.allSettled(retained),
undefined,
deadline(limits.drainTimeoutMs),
);
if (drained.kind !== "VALUE") {
// Still DRAINING: the caller must not treat this as quiescence.
return realtimeFailure("IDLE_TIMEOUT", "CLOSE", false);
}
@@ -1414,14 +1371,3 @@ function captureSnapshotCheckpoint(
? checkpoint
: null;
}
function hasExactSnapshotKeys(
snapshot: RealtimeDataSnapshot,
expected: readonly string[],
): boolean {
const selected = [...expected].sort();
return (
snapshot.keys.length === selected.length &&
snapshot.keys.every((key, index) => key === selected[index])
);
}
@@ -11,6 +11,7 @@ import type {
import {
isRealtimeResult,
isRealtimeTransportEventOutcome,
raceRealtimeTask,
realtimeFailure,
realtimeSuccess,
} from "../result.ts";
@@ -882,91 +883,64 @@ export function createWebSocketConnection(
terminateProtocol();
return;
}
if (dependencies.onSubscribed) {
const barrierController = new AbortController();
const abortBarrier = () => barrierController.abort();
generation.signal.addEventListener("abort", abortBarrier, {
once: true,
});
if (generation.signal.aborted) abortBarrier();
try {
const outcome = await Promise.race([
Promise.resolve()
.then(() =>
dependencies.onSubscribed!(
Object.freeze({
subscriptionId: frame.subscriptionId,
streamId: subscription.request.streamId,
streamEpoch: frame.streamEpoch,
acceptedCursor: frame.acceptedCursor,
nextExpectedSequence: frame.nextExpectedSequence,
}),
barrierController.signal,
),
)
.then((value) =>
const onSubscribed = dependencies.onSubscribed;
if (onSubscribed) {
const outcome = await raceRealtimeTask(
(signal) =>
Promise.resolve().then(() =>
onSubscribed(
Object.freeze({
kind: "HANDLED" as const,
value,
subscriptionId: frame.subscriptionId,
streamId: subscription.request.streamId,
streamEpoch: frame.streamEpoch,
acceptedCursor: frame.acceptedCursor,
nextExpectedSequence: frame.nextExpectedSequence,
}),
signal,
),
dependencies.clock
.sleep(
ceilings.maxApplyMs,
barrierController.signal,
)
.then(() =>
Object.freeze({ kind: "TIMED_OUT" as const }),
),
]);
if (
outcome.kind === "TIMED_OUT" &&
status !== "CLOSED"
) {
requestRecovery({
subscriptionId: frame.subscriptionId,
reason: "APPLY_FAILED",
});
terminate(
failure(
"APPLY_FAILED",
),
generation.signal,
(signal) => dependencies.clock.sleep(ceilings.maxApplyMs, signal),
);
if (outcome.kind === "TIMEOUT" && status !== "CLOSED") {
requestRecovery({
subscriptionId: frame.subscriptionId,
reason: "APPLY_FAILED",
});
terminate(
failure(
"APPLY_FAILED",
"RECOVER",
false,
"SNAPSHOT",
),
"CURSOR_RESET",
undefined,
);
return;
}
if (outcome.kind === "VALUE" && status !== "CLOSED") {
if (!isRealtimeResult(outcome.value, isUndefined)) {
terminateInboundFailure(
realtimeFailure(
"PROTOCOL_MISMATCH",
"RECOVER",
false,
"SNAPSHOT",
),
"CURSOR_RESET",
undefined,
).error,
frame.subscriptionId,
);
return;
}
if (
outcome.kind === "HANDLED" &&
status !== "CLOSED"
) {
if (!isRealtimeResult(outcome.value, isUndefined)) {
terminateInboundFailure(
realtimeFailure(
"PROTOCOL_MISMATCH",
"RECOVER",
false,
).error,
frame.subscriptionId,
);
return;
}
if (!outcome.value.ok) {
terminateInboundFailure(
outcome.value.error,
frame.subscriptionId,
);
return;
}
if (!outcome.value.ok) {
terminateInboundFailure(
outcome.value.error,
frame.subscriptionId,
);
return;
}
} catch {
if (
status !== "CLOSED" &&
!generation.signal.aborted
) {
}
if (outcome.kind !== "TIMEOUT" && outcome.kind !== "VALUE") {
if (status !== "CLOSED" && !generation.signal.aborted) {
terminateInboundFailure(
realtimeFailure(
"PROVIDER_UNAVAILABLE",
@@ -977,12 +951,6 @@ export function createWebSocketConnection(
);
}
return;
} finally {
generation.signal.removeEventListener(
"abort",
abortBarrier,
);
barrierController.abort();
}
}
if (
@@ -1057,87 +1025,24 @@ export function createWebSocketConnection(
return;
}
const applyController = new AbortController();
const abortApply = () => applyController.abort();
generation.signal.addEventListener("abort", abortApply, {
once: true,
});
try {
const outcome = await Promise.race([
dependencies
.onEvent(frame, applyController.signal)
.then((value) =>
Object.freeze({
kind: "HANDLED" as const,
value,
}),
),
dependencies.clock
.sleep(ceilings.maxApplyMs, applyController.signal)
.then(() =>
Object.freeze({ kind: "TIMED_OUT" as const }),
),
]);
if (outcome.kind === "TIMED_OUT" && status !== "CLOSED") {
requestRecovery({
subscriptionId: frame.subscriptionId,
reason: "APPLY_FAILED",
});
terminate(
failure(
"APPLY_FAILED",
"RECEIVE",
false,
"SNAPSHOT",
),
"CURSOR_RESET",
undefined,
);
} else if (outcome.kind === "HANDLED" && status !== "CLOSED") {
if (
!isRealtimeResult(
outcome.value,
isRealtimeTransportEventOutcome,
)
) {
requestRecovery({
subscriptionId: frame.subscriptionId,
reason: "APPLY_FAILED",
});
terminate(
failure(
"APPLY_FAILED",
"RECEIVE",
false,
"SNAPSHOT",
),
"CURSOR_RESET",
undefined,
);
} else if (!outcome.value.ok) {
terminateInboundFailure(
outcome.value.error,
frame.subscriptionId,
);
} else if (
outcome.value.value.kind === "RECOVERY_COMMITTED"
) {
terminate(
failure(
"CURSOR_EXPIRED",
"RECEIVE",
false,
"SNAPSHOT",
),
"CURSOR_RESET",
undefined,
true,
outcome.value.value,
);
}
}
} catch {
if (status !== "CLOSED" && !generation.signal.aborted) {
const outcome = await raceRealtimeTask(
(signal) => dependencies.onEvent(frame, signal),
generation.signal,
(signal) => dependencies.clock.sleep(ceilings.maxApplyMs, signal),
);
const handled =
outcome.kind === "VALUE" &&
isRealtimeResult(outcome.value, isRealtimeTransportEventOutcome)
? outcome.value
: null;
if (!handled) {
// Timed out, returned no valid result, or failed while still current.
if (
status !== "CLOSED" &&
(outcome.kind === "TIMEOUT" ||
outcome.kind === "VALUE" ||
!generation.signal.aborted)
) {
requestRecovery({
subscriptionId: frame.subscriptionId,
reason: "APPLY_FAILED",
@@ -1153,9 +1058,23 @@ export function createWebSocketConnection(
undefined,
);
}
} finally {
generation.signal.removeEventListener("abort", abortApply);
applyController.abort();
} else if (status !== "CLOSED") {
if (!handled.ok) {
terminateInboundFailure(handled.error, frame.subscriptionId);
} else if (handled.value.kind === "RECOVERY_COMMITTED") {
terminate(
failure(
"CURSOR_EXPIRED",
"RECEIVE",
false,
"SNAPSHOT",
),
"CURSOR_RESET",
undefined,
true,
handled.value,
);
}
}
}
@@ -1,6 +1,6 @@
import {
hasDuplicateJsonMembers,
} from "../json-member-scanner.ts";
} from "../../platform/json-member-scanner.ts";
export const REALTIME_WEBSOCKET_PROTOCOL = "realtime.v1" as const;
+8 -99
View File
@@ -8,6 +8,7 @@ import {
type WebPushResult,
} from "../../contracts/web-push.ts";
import { hasExactKeys, isRecord, validOpaqueId } from "./codec-primitives.ts";
import { hasDuplicateJsonMembers } from "../platform/json-member-scanner.ts";
const REGISTRY_ID = /^[A-Z][A-Z0-9_]{0,63}$/u;
const ISO_INSTANT =
@@ -71,7 +72,13 @@ export function decodeWebPushHint(
} catch {
return webPushFailure("CONTRACT_REJECTED", "PUSH_DECODE");
}
if (hasDuplicateTopLevelJsonKeys(decoded)) {
// The byte cap already bounds the scan, so the budget never trips first.
if (
hasDuplicateJsonMembers(decoded, {
maxDepth: WEB_PUSH_LIMITS.decodedHintBytes,
maxMembers: WEB_PUSH_LIMITS.decodedHintBytes,
})
) {
return webPushFailure("CONTRACT_REJECTED", "PUSH_DECODE");
}
if (isRecord(value) && Object.hasOwn(value, "web_push")) {
@@ -189,101 +196,3 @@ export function clickDataFromHint(
expiresAt: hint.expiresAt,
});
}
function hasDuplicateTopLevelJsonKeys(source: string): boolean {
let cursor = skipWhitespace(source, 0);
if (source[cursor] !== "{") return false;
cursor = skipWhitespace(source, cursor + 1);
const keys = new Set<string>();
while (cursor < source.length && source[cursor] !== "}") {
if (source[cursor] !== "\"") return false;
const keyEnd = jsonStringEnd(source, cursor);
if (keyEnd === null) return false;
let key: unknown;
try {
key = JSON.parse(source.slice(cursor, keyEnd));
} catch {
return false;
}
if (typeof key !== "string") return false;
if (keys.has(key)) return true;
keys.add(key);
cursor = skipWhitespace(source, keyEnd);
if (source[cursor] !== ":") return false;
const valueEnd = jsonValueEnd(source, cursor + 1);
if (valueEnd === null) return false;
cursor = skipWhitespace(source, valueEnd);
if (source[cursor] === ",") {
cursor = skipWhitespace(source, cursor + 1);
continue;
}
if (source[cursor] !== "}") return false;
}
return false;
}
function jsonStringEnd(
source: string,
start: number,
): number | null {
let escaped = false;
for (let cursor = start + 1; cursor < source.length; cursor += 1) {
const character = source[cursor];
if (escaped) {
escaped = false;
} else if (character === "\\") {
escaped = true;
} else if (character === "\"") {
return cursor + 1;
}
}
return null;
}
function jsonValueEnd(
source: string,
start: number,
): number | null {
let cursor = skipWhitespace(source, start);
let depth = 0;
let inString = false;
let escaped = false;
for (; cursor < source.length; cursor += 1) {
const character = source[cursor];
if (inString) {
if (escaped) {
escaped = false;
} else if (character === "\\") {
escaped = true;
} else if (character === "\"") {
inString = false;
}
continue;
}
if (character === "\"") {
inString = true;
} else if (character === "{" || character === "[") {
depth += 1;
} else if (character === "}" || character === "]") {
if (depth === 0) return cursor;
depth -= 1;
} else if (character === "," && depth === 0) {
return cursor;
}
}
return inString || depth !== 0 ? null : cursor;
}
function skipWhitespace(source: string, start: number): number {
let cursor = start;
while (
cursor < source.length &&
(source[cursor] === " " ||
source[cursor] === "\n" ||
source[cursor] === "\r" ||
source[cursor] === "\t")
) {
cursor += 1;
}
return cursor;
}