Open History to see the last commit
1import { randomUUID } from 'node:crypto'
2import type { PoolClient } from 'pg'
3import type { StoredFrame } from './replay-plan.js'
4import { StreamError } from './errors.js'
5import type { InstallationGuard } from './installation.js'
6
7export const REPLAY_PIN_MS = 315_000
8export interface ReplayLease { readonly id: string; readonly chunks: number }
9export function assertReplayDeadline(deadline: number): void {
10 if (performance.now() >= deadline) throw new StreamError(503, 'REPLAY_DEADLINE', 'Replay deadline exceeded; retry from the durable checkpoint', { 'Retry-After': '1' })
11}
12
13/** Keeps at most the current read and one following read in flight. */
14export async function replayPipeline<T, R>(values: readonly T[], load: (value: T, signal: AbortSignal) => Promise<R>, readAhead: 0 | 1, signal?: AbortSignal): Promise<readonly R[]> {
15 const stopped = new AbortController()
16 const combined = signal ? AbortSignal.any([signal, stopped.signal]) : stopped.signal
17 const pending = new Map<number, Promise<R>>()
18 const results: R[] = []
19 const start = (index: number) => {
20 if (index >= values.length) return
21 const work = Promise.resolve().then(() => { combined.throwIfAborted(); return load(values[index]!, combined) })
22 pending.set(index, work)
23 void work.catch(() => {})
24 }
25 start(0)
26 if (readAhead) start(1)
27 try {
28 for (let index = 0; index < values.length; index++) {
29 const result = await pending.get(index)!
30 combined.throwIfAborted()
31 pending.delete(index)
32 results.push(result)
33 start(index + 1 + readAhead)
34 }
35 return results
36 } catch (error) {
37 stopped.abort(error)
38 await Promise.allSettled(pending.values())
39 throw error
40 }
41}
42
43/** Acquire under the replay snapshot; object I/O never holds its SQL locks. */
44export class ReplayPins {
45 constructor(private readonly schema: string, private readonly guard: InstallationGuard) {}
46 async acquire(client: PoolClient, frames: readonly StoredFrame[]): Promise<ReplayLease | undefined> {
47 const chunks = [...new Set(frames.flatMap((frame) => frame.storage === 'object' ? [frame.manifest.id] : []))].sort()
48 if (!chunks.length) return undefined
49 const lease = { id: randomUUID(), chunks: chunks.length }, installation = await this.guard.snapshot()
50 const pinned = await client.query(`WITH locked AS MATERIALIZED (
51 SELECT id,retired_at FROM ${this.schema}.chunks WHERE id=ANY($4::uuid[]) ORDER BY id FOR SHARE
52 ) INSERT INTO ${this.schema}.replay_pins (id, chunk_id, serving_epoch, expires_at)
53 SELECT $1, id, $2, clock_timestamp() + $3 * interval '1 millisecond' FROM locked
54 WHERE retired_at IS NULL AND (SELECT count(*) FROM locked WHERE retired_at IS NULL)=$5`,
55 [lease.id, installation.serving_epoch, REPLAY_PIN_MS, chunks, chunks.length])
56 if (pinned.rowCount !== chunks.length) {
57 throw new StreamError(503, 'REPLAY_RETIRED', 'Replay snapshot retired; retry from the durable checkpoint', { 'Retry-After': '1' })
58 }
59 return lease
60 }
61 /** Validate and release in one transaction after the bytes are owned locally. */
62 async complete(lease: ReplayLease | undefined): Promise<void> {
63 if (!lease) return
64 await this.guard.run({}, async (client) => {
65 const released = await client.query<{ valid: boolean }>(`DELETE FROM ${this.schema}.replay_pins WHERE id=$1
66 RETURNING expires_at>clock_timestamp() AS valid`, [lease.id])
67 if (released.rows.length !== lease.chunks || released.rows.some((row) => !row.valid)) {
68 throw new StreamError(503, 'REPLAY_EXPIRED', 'Replay lease expired; retry from the durable checkpoint', { 'Retry-After': '1' })
69 }
70 })
71 }
72 async release(lease: ReplayLease | undefined): Promise<void> {
73 if (lease) await this.guard.releaseReplayPins(lease.id)
74 }
75}