Skip to content
Source
Sign inSign up
samwillis/neon-durable-streams
Open History to see the last commit

live.ts

347 lines17.6 KB

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