Open History to see the last commit
1import { admitLive } from './admission.js'
2import { randomInt } from 'node:crypto'
3import { StreamError } from './errors.js'
4import type { HeadWatch, StreamNotifier, StreamHead } from './neon.js'
5import { mediaType, formatPayloads } from './payload.js'
6import type { PostgresStreamStore, ReadResult } from './store.js'
7import { PayloadWindow } from './live-payload.js'
8import { ownedResponseBody } from './response-body.js'
9import { encodeSsePage } from './sse.js'
10
11export interface LiveOptions {
12 /** Consumer-owned notifier. Production Neon servers use createNeonRealtimeNotifier. */
13 readonly notifier: StreamNotifier
14 readonly longPollTimeoutMs?: number
15 readonly fallbackIntervalMs?: number
16 readonly heartbeatMs?: number
17 readonly maxSseDurationMs?: number
18 /** Per instance, additionally bounded by installation-wide database admission. */
19 readonly maxReaders?: number
20 readonly maxBufferedBytes?: number
21 readonly maxBufferedFrames?: number
22 readonly payloadWindowMs?: number
23 readonly validationIntervalMs?: number
24}
25
26export function responseCursor(previous: string | null, now = Date.now()): string {
27 const current = BigInt(Math.max(0, Math.floor((now - Date.UTC(2024, 9, 9)) / 20_000)))
28 // Bound untrusted BigInt input while preserving monotonicity for valid cursors.
29 if (previous && /^\d{1,128}$/.test(previous) && BigInt(previous) >= current) {
30 return String(BigInt(previous) + BigInt(Math.ceil(randomInt(1, 3601) / 20)))
31 }
32 return String(current)
33}
34
35interface Channel {
36 version: string | null
37 revision: number
38 references: number
39 disposed: boolean
40 watch?: HeadWatch
41 timer?: ReturnType<typeof setTimeout>
42 waiters: Set<() => void>
43 head: StreamHead | null | undefined
44 validation: Pick<ReadResult, 'stream' | 'validatedAt' | 'validUntil'>
45 validating?: Promise<Pick<ReadResult, 'stream' | 'validatedAt' | 'validUntil'>>
46}
47
48/** Authorized durable replay plus bounded, contiguous committed Realtime payloads. */
49export class LiveReads {
50 private readonly channels = new Map<string, Channel>()
51 private readonly active = new Set<AbortController>()
52 private readonly releases = new Set<Promise<void>>()
53 private readonly timeout: number
54 private readonly fallback: number
55 private readonly heartbeat: number
56 private readonly duration: number
57 private readonly maximum: number
58 private readonly bufferBytes: number
59 private readonly bufferFrames: number
60 private readonly windowMs: number
61 private readonly validationMs: number
62 private closed = false
63
64 constructor(private readonly store: PostgresStreamStore, private readonly schema: string,
65 private readonly options: LiveOptions, private readonly report: (error: unknown) => void) {
66 this.timeout = options.longPollTimeoutMs ?? 25_000
67 this.fallback = options.fallbackIntervalMs ?? 5000
68 this.heartbeat = options.heartbeatMs ?? 15_000
69 this.duration = options.maxSseDurationMs ?? 60_000
70 this.maximum = options.maxReaders ?? 80
71 this.bufferBytes = options.maxBufferedBytes ?? 2 * 1024 * 1024
72 this.bufferFrames = options.maxBufferedFrames ?? 256
73 this.windowMs = options.payloadWindowMs ?? 10_000
74 this.validationMs = options.validationIntervalMs ?? 1000
75 for (const [value, min, max] of [[this.timeout, 1, 300_000], [this.fallback, 100, 60_000],
76 [this.heartbeat, 100, 60_000], [this.duration, 100, 300_000], [this.maximum, 1, 100_000],
77 [this.bufferBytes, 1, 64 * 1024 * 1024], [this.bufferFrames, 1, 4096], [this.windowMs, 100, 60_000], [this.validationMs, 100, 60_000]]) {
78 if (!Number.isSafeInteger(value) || value! < min! || value! > max!) throw new RangeError('Invalid live read limits')
79 }
80 if (typeof options.notifier?.watch !== 'function') throw new TypeError('Live reads require a notifier')
81 }
82
83 private channel(tenant: string, id: string, initial: ReadResult) {
84 const key = JSON.stringify([tenant, id])
85 let channel = this.channels.get(key)
86 if (!channel) {
87 const current: Channel = { version: initial.stream.change_version, revision: 0, references: 0, disposed: false, waiters: new Set(), head: undefined, validation: { stream: initial.stream, validatedAt: initial.validatedAt, validUntil: initial.validUntil } }
88 this.channels.set(key, current)
89 const update = (next: string | null) => {
90 if (current.disposed || next === current.version) return
91 // Delayed authoritative snapshots can trail a more recent SQL recheck.
92 if (next !== null && current.version !== null && BigInt(next) < BigInt(current.version)) return
93 current.version = next
94 current.revision++
95 for (const wake of [...current.waiters]) wake()
96 }
97 try {
98 current.watch = this.options.notifier.watch({ schema: this.schema, tenantId: tenant, streamId: id },
99 (head) => {
100 if (head && current.version !== null && BigInt(head.version) < BigInt(current.version)) return
101 current.head = head
102 update(head && !head.deleted ? head.version : null)
103 })
104 void current.watch.ready.catch(this.report)
105 } catch (error) { this.report(error) }
106 const poll = async () => {
107 try { update(await this.store.headVersion(tenant, id)) } catch (error) {
108 if (error instanceof StreamError && error.code === 'INSTALLATION_FENCED') update(null)
109 else this.report(error)
110 }
111 finally { if (!current.disposed) current.timer = setTimeout(() => { void poll() }, this.fallback).unref() }
112 }
113 current.timer = setTimeout(() => { void poll() }, this.fallback).unref()
114 channel = current
115 }
116 const watched = channel
117 watched.references++
118 return {
119 revision: () => watched.revision,
120 head: () => watched.head,
121 wake: () => { if (!watched.disposed) { watched.revision++; for (const wake of [...watched.waiters]) wake() } },
122 observe: (value: Pick<ReadResult, 'stream' | 'validatedAt' | 'validUntil'>) => {
123 if (value.validatedAt >= watched.validation.validatedAt) watched.validation = { stream: value.stream, validatedAt: value.validatedAt, validUntil: value.validUntil }
124 },
125 validate: async () => {
126 const previous = watched.validation
127 if (performance.now() - previous.validatedAt < this.validationMs && performance.now() < previous.validUntil) return previous
128 watched.validating ??= this.store.validateGeneration(tenant, id).then((value) => { watched.validation = value; return value })
129 .finally(() => { delete watched.validating })
130 return watched.validating
131 },
132 wait: (revision: number, timeoutMs: number, signal: AbortSignal) => new Promise<void>((resolve, reject) => {
133 if (signal.aborted) { reject(signal.reason); return }
134 if (watched.revision !== revision || watched.disposed) { resolve(); return }
135 const cleanup = () => { clearTimeout(timer); signal.removeEventListener('abort', abort); watched.waiters.delete(wake) }
136 const wake = () => { cleanup(); resolve() }
137 const abort = () => { cleanup(); reject(signal.reason) }
138 const timer = setTimeout(wake, Math.max(0, timeoutMs))
139 watched.waiters.add(wake)
140 signal.addEventListener('abort', abort, { once: true })
141 }),
142 release: () => {
143 if (--watched.references) return
144 watched.disposed = true
145 clearTimeout(watched.timer)
146 watched.watch?.close()
147 for (const wake of [...watched.waiters]) wake()
148 this.channels.delete(key)
149 },
150 }
151 }
152
153 async serve(request: Request, tenant: string, path: string, offset: string, expiresAt?: number): Promise<Response> {
154 if (this.closed) throw new StreamError(503, 'SERVER_CLOSED', 'Server is shutting down')
155 if (this.active.size >= this.maximum) throw new StreamError(429, 'LIVE_LIMIT', 'Live reader capacity reached', { 'Retry-After': '1' })
156 const abort = new AbortController()
157 this.active.add(abort)
158 const canceled = () => abort.abort(new StreamError(408, 'REQUEST_ABORTED', 'Request aborted'))
159 request.signal.addEventListener('abort', canceled, { once: true })
160 if (request.signal.aborted) canceled()
161 const expiry = expiresAt === undefined ? undefined : setTimeout(() => abort.abort(new StreamError(401, 'AUTH_EXPIRED', 'Authentication expired')), Math.max(0, Math.min(2_147_483_647, expiresAt - Date.now())))
162 // The hard local deadline precedes the database lease expiry. A suspended
163 // runtime must observe abort before replaying after the deadline.
164 const lifetime = Math.max(this.timeout, this.duration) + 15_000
165 const hardDeadline = performance.now() + lifetime
166 const deadlineTimer = setTimeout(() => abort.abort(), lifetime).unref()
167 const assertActive = () => {
168 // Timer callbacks can run after promise continuations when a suspended
169 // isolate resumes. Check monotonic elapsed time before any new emission.
170 if (expiresAt !== undefined && Date.now() >= expiresAt) abort.abort(new StreamError(401, 'AUTH_EXPIRED', 'Authentication expired'))
171 if (performance.now() >= hardDeadline) abort.abort()
172 abort.signal.throwIfAborted()
173 }
174 let releaseAdmission: (() => Promise<void>) | undefined
175 let subscription: ReturnType<LiveReads['channel']> | undefined
176 let payload: PayloadWindow | undefined
177 let released = false
178 const pageLeases = new Set<() => void>()
179 const inFlight = new Set<Promise<unknown>>()
180 const track = <T>(work: Promise<T>): Promise<T> => {
181 const pending = work.finally(() => { inFlight.delete(pending) })
182 inFlight.add(pending)
183 return pending
184 }
185 const budgeted = async (work: () => Promise<ReadResult>): Promise<ReadResult> => {
186 let give = this.store.reserveRead()
187 let returned = false
188 const release = () => {
189 if (returned) return
190 returned = true
191 pageLeases.delete(release)
192 give()
193 }
194 pageLeases.add(release)
195 try {
196 const result = await work()
197 give()
198 if (!result.hasData) { release(); return result }
199 give = this.store.reserveBody(result.body.byteLength + 65536)
200 return { ...result, release }
201 } catch (error) { release(); throw error }
202 }
203 const release = () => {
204 if (released) return
205 released = true
206 clearTimeout(expiry)
207 clearTimeout(deadlineTimer)
208 // Stop notifications immediately, but retain capacity while an already
209 // issued SQL/object read settles. Cancellation storms must not admit an
210 // unbounded number of detached replay operations.
211 request.signal.removeEventListener('abort', canceled)
212 payload?.close()
213 subscription?.release()
214 const work = (async () => {
215 await Promise.allSettled([...inFlight])
216 for (const give of [...pageLeases]) give()
217 await releaseAdmission?.()
218 })().catch((error: unknown) => {
219 if (!(error instanceof StreamError && error.code === 'INSTALLATION_FENCED')) this.report(error)
220 }).finally(() => { this.active.delete(abort) })
221 this.releases.add(work)
222 void work.finally(() => this.releases.delete(work))
223 }
224 try {
225 assertActive()
226 releaseAdmission = await admitLive(this.store.guard, this.schema, lifetime + 5000)
227 assertActive()
228 const initial = await track(budgeted(() => this.store.read(tenant, path, offset, undefined, abort.signal)))
229 assertActive()
230 const id = initial.stream.id
231 const isSse = new URL(request.url).searchParams.get('live') === 'sse'
232 let cursor = new URL(request.url).searchParams.get('cursor')
233 const headers = new Headers({ 'Stream-Next-Offset': initial.next, 'Content-Type': initial.stream.content_type, 'Cache-Control': 'no-store' })
234 if (initial.upToDate) headers.set('Stream-Up-To-Date', 'true')
235 if (initial.stream.closed && initial.upToDate) headers.set('Stream-Closed', 'true')
236 if (initial.stream.ttl_seconds !== null) headers.set('Stream-TTL', String(initial.stream.ttl_seconds))
237 if (initial.stream.expires_at) headers.set('Stream-Expires-At', initial.stream.expires_at.toISOString())
238 if (!isSse && (initial.hasData || initial.stream.closed)) {
239 headers.set('Stream-Cursor', responseCursor(cursor))
240 if (initial.release) pageLeases.delete(initial.release)
241 release()
242 return new Response(initial.hasData ? ownedResponseBody(initial.body, { signal: request.signal, release: initial.release!,
243 timeoutMs: Math.max(1, hardDeadline - performance.now()), ...(expiresAt === undefined ? {} : { expiresAt }) }) : null,
244 { status: initial.hasData ? 200 : 204, headers })
245 }
246 subscription = this.channel(tenant, id, initial)
247 const channel = subscription
248 channel.observe(initial)
249 if (this.options.notifier.watchAppends) payload = new PayloadWindow({ notifier: this.options.notifier, schema: this.schema, tenantId: tenant, streamId: id,
250 installation: await this.store.guard.snapshot(), maxBytes: this.bufferBytes, maxFrames: this.bufferFrames, windowMs: this.windowMs, wake: channel.wake, report: this.report }, initial)
251 const replay = async (at: string) => {
252 const revision = payload?.revision ?? -1
253 const result = await this.store.readGeneration(tenant, id, at, abort.signal)
254 channel.observe(result); payload?.reconcile(result, revision)
255 return result
256 }
257 const page = (at: string): Promise<ReadResult> => budgeted(async () => {
258 if (!payload || payload.needsReplay || !payload.verified) return replay(at)
259 const head = channel.head()
260 if (head === null || head?.deleted) return replay(at)
261 const validation = await channel.validate()
262 const metadata = head && BigInt(head.version) >= BigInt(validation.stream.change_version)
263 ? { ...validation.stream, tail_offset: head.offset, change_version: head.version, closed: head.closed } : validation.stream
264 const overhead = mediaType(metadata.content_type) === 'application/json' ? 1 : 0
265 const batch = payload.take(at, this.store.replayLimits.maxBytes - overhead, this.store.replayLimits.maxFrames, metadata.tail_offset)
266 if (!batch && payload.needsReplay) return replay(at)
267 const next = batch?.next ?? at
268 if (metadata.closed && next < metadata.tail_offset && !batch?.frames.length) return replay(at)
269 return { stream: metadata, body: formatPayloads((batch?.frames ?? []).map((frame) => frame.payload), metadata.content_type),
270 next, upToDate: !batch?.ahead && next >= metadata.tail_offset, hasData: Boolean(batch?.frames.length), validatedAt: validation.validatedAt, validUntil: validation.validUntil }
271 })
272 const waitForPage = async (at: string, deadline: number): Promise<ReadResult> => {
273 let awaitingPayload: number | undefined
274 for (;;) {
275 assertActive()
276 const revision = channel.revision()
277 const result = await track(page(at))
278 assertActive()
279 if (result.hasData || result.stream.closed || Date.now() >= deadline) return result
280 if (!result.upToDate) {
281 awaitingPayload ??= performance.now()
282 if (performance.now() - awaitingPayload >= 50) return track(budgeted(() => replay(at)))
283 } else awaitingPayload = undefined
284 const wait = Math.min(deadline - Date.now(), payload ? this.validationMs : Infinity, Math.max(1, result.validUntil - performance.now()),
285 awaitingPayload === undefined ? Infinity : Math.max(1, 50 - (performance.now() - awaitingPayload)))
286 await channel.wait(revision, wait, abort.signal)
287 }
288 }
289 if (!isSse) {
290 const deadline = Date.now() + this.timeout
291 const result = await waitForPage(initial.next, deadline)
292 assertActive()
293 headers.set('Stream-Next-Offset', result.next)
294 headers.set('Stream-Cursor', responseCursor(cursor))
295 if (result.upToDate) headers.set('Stream-Up-To-Date', 'true')
296 else headers.delete('Stream-Up-To-Date')
297 if (result.stream.closed && result.upToDate) headers.set('Stream-Closed', 'true')
298 if (result.release) pageLeases.delete(result.release)
299 release()
300 return new Response(result.hasData ? ownedResponseBody(result.body, { signal: request.signal, release: result.release!,
301 timeoutMs: Math.max(1, hardDeadline - performance.now()), ...(expiresAt === undefined ? {} : { expiresAt }) }) : null,
302 { status: result.hasData ? 200 : 204, headers })
303 }
304
305 const binary = !mediaType(initial.stream.content_type).startsWith('text/') && mediaType(initial.stream.content_type) !== 'application/json'
306 headers.set('Content-Type', 'text/event-stream')
307 headers.set('Cache-Control', 'no-cache, no-store, no-transform')
308 headers.set('X-Accel-Buffering', 'no')
309 if (binary) headers.set('Stream-SSE-Data-Encoding', 'base64')
310 let next = initial.next
311 let first: ReadResult | undefined = initial
312 let ending = false
313 let output: Generator<Uint8Array> | undefined
314 let releaseOutput: (() => void) | undefined
315 let eofPending = false
316 let rotation: ReturnType<typeof setTimeout>
317 const thisDuration = this.duration
318 const body = new ReadableStream<Uint8Array>({
319 start(controller) {
320 const end = () => {
321 if (ending) return
322 ending = true
323 clearTimeout(rotation)
324 abort.signal.removeEventListener('abort', end)
325 const complete = output === undefined
326 first = undefined
327 output?.return(undefined)
328 output = undefined
329 if (complete) controller.close()
330 else controller.error(abort.signal.reason)
331 release()
332 }
333 abort.signal.addEventListener('abort', end, { once: true })
334 rotation = setTimeout(() => abort.abort(), thisDuration)
335 if (abort.signal.aborted) end()
336 },
337 pull: async (controller) => {
338 try {
339 assertActive()
340 if (output) {
341 const part = output.next()
342 if (!part.done) { controller.enqueue(part.value); return }
343 output = undefined
344 releaseOutput?.()
345 releaseOutput = undefined
346 if (eofPending) { abort.abort(); return }
347 }
348 let result = first
349 first = undefined
350 if (!result) {
351 result = await waitForPage(next, Date.now() + this.heartbeat)
352 if (ending) return
353 assertActive()
354 if (!result.hasData && !result.stream.closed) { controller.enqueue(Buffer.from(': heartbeat\n\n')); return }
355 }
356 if (ending) return
357 assertActive()
358 next = result.next
359 const eof = result.stream.closed && result.upToDate
360 cursor = responseCursor(cursor)
361 output = encodeSsePage(result.body, result.hasData, binary,
362 { streamNextOffset: next, ...(eof ? { streamClosed: true } : { streamCursor: cursor }), ...(result.upToDate ? { upToDate: true } : {}) })
363 releaseOutput = result.release
364 eofPending = eof
365 controller.enqueue(output.next().value!)
366 } catch (error) {
367 if (!ending) { if (!(error instanceof StreamError)) this.report(error); abort.abort(error) }
368 }
369 },
370 cancel() {
371 // The stream is already canceled before this callback runs. Prevent
372 // the abort listener from trying to close its controller a second time.
373 ending = true
374 first = undefined
375 output?.return(undefined)
376 output = undefined
377 clearTimeout(rotation)
378 abort.abort()
379 release()
380 },
381 }, { highWaterMark: 1 })
382 return new Response(body, { status: 200, headers })
383 } catch (error) { release(); throw error }
384 }
385
386 close(): void {
387 this.closed = true
388 for (const abort of this.active) abort.abort(new StreamError(503, 'SERVER_CLOSED', 'Server is shutting down'))
389 }
390
391 async drain(): Promise<void> { await Promise.allSettled([...this.releases]) }
392}