Open History to see the last commit
1import { isSuccessor, parseOffset } from './offset.js'
2import type { HeadWatch, StreamNotifier } from './neon.js'
3import type { ReadResult } from './store.js'
4import type { InstallationIdentity } from './installation.js'
5
6export interface RealtimeAppend {
7 readonly rowId: string
8 readonly streamId: string
9 readonly start: string
10 readonly end: string
11 readonly payload: Uint8Array | null
12 readonly messageEnds: readonly number[] | null
13}
14export type AppendUpdate =
15 | { readonly type: 'replace' | 'changes'; readonly rows: readonly RealtimeAppend[]; readonly removed: readonly string[] }
16 | { readonly type: 'invalidate' }
17export interface BufferedAppend { readonly start: string; readonly end: string; readonly payload: Buffer; readonly messageEnds: readonly number[] | null }
18
19/** Unordered committed rows become only a contiguous, bounded byte prefix. */
20export class AppendBuffer {
21 private readonly frames = new Map<string, BufferedAppend & { rowId: string }>()
22 private readonly rowIds = new Map<string, string>()
23 private bytes = 0
24 private generation = 0
25 private dirty = true
26 constructor(private readonly streamId: string, private readonly maxBytes: number, private readonly maxFrames: number) {}
27 get revision(): number { return this.generation }
28 get needsReplay(): boolean { return this.dirty }
29 get size(): number { return this.frames.size }
30 requireReplay(): void { this.dirty = true; this.generation++ }
31 invalidate(): void {
32 this.frames.clear(); this.rowIds.clear(); this.bytes = 0; this.dirty = true; this.generation++
33 }
34 reconcile(cursor: string, revision: number): boolean {
35 if (revision !== this.generation) return false
36 for (const [start, frame] of this.frames) if (frame.end <= cursor) this.remove(start)
37 this.dirty = false
38 return true
39 }
40 ingest(update: AppendUpdate, cursor: string): boolean {
41 if (update.type === 'invalidate') { this.invalidate(); return false }
42 if (update.type === 'replace') this.invalidate()
43 if (update.removed.length) { this.invalidate(); return false }
44 for (const row of update.rows) {
45 try {
46 parseOffset(row.start); parseOffset(row.end)
47 if (row.streamId !== this.streamId || row.start >= row.end) throw new Error('Invalid Realtime frame identity')
48 if (row.end <= cursor) continue
49 if (!row.payload || row.start < cursor || !isSuccessor(row.start, row.end)) throw new Error('Realtime frame needs durable replay')
50 if (row.messageEnds) {
51 let previous = 0
52 for (const end of row.messageEnds) {
53 if (!Number.isSafeInteger(end) || end <= previous || end > row.payload.byteLength || row.payload[end - 1] !== 44) throw new Error('Invalid JSON frame index')
54 previous = end
55 }
56 if (previous !== row.payload.byteLength) throw new Error('Incomplete JSON frame index')
57 }
58 const previous = this.frames.get(row.start)
59 if (previous) {
60 if (previous.end !== row.end || !previous.payload.equals(row.payload)
61 || JSON.stringify(previous.messageEnds) !== JSON.stringify(row.messageEnds)) throw new Error('Conflicting Realtime frame')
62 continue
63 }
64 if (this.frames.size >= this.maxFrames || this.bytes + row.payload.byteLength > this.maxBytes) throw new Error('Realtime buffer capacity reached')
65 const oldStart = this.rowIds.get(row.rowId)
66 if (oldStart && oldStart !== row.start) throw new Error('Realtime row identity changed')
67 for (const frame of this.frames.values()) if (row.start < frame.end && row.end > frame.start) throw new Error('Overlapping Realtime frames')
68 const payload = Buffer.from(row.payload)
69 this.frames.set(row.start, { rowId: row.rowId, start: row.start, end: row.end, payload, messageEnds: row.messageEnds ? [...row.messageEnds] : null })
70 this.rowIds.set(row.rowId, row.start); this.bytes += payload.length
71 } catch { this.invalidate(); return false }
72 }
73 return true
74 }
75 private remove(start: string): void {
76 const frame = this.frames.get(start)
77 if (!frame) return
78 this.frames.delete(start); this.rowIds.delete(frame.rowId); this.bytes -= frame.payload.length
79 }
80 take(cursor: string, maxBytes: number, maxFrames: number, through?: string): { frames: readonly BufferedAppend[]; next: string; ahead: boolean } | undefined {
81 if (this.dirty) return undefined
82 const frames: BufferedAppend[] = []
83 let next = cursor, bytes = 0
84 for (;;) {
85 const frame = this.frames.get(next)
86 if (!frame || (through !== undefined && frame.end > through) || frames.length >= maxFrames || bytes + frame.payload.length > maxBytes) break
87 frames.push(frame); bytes += frame.payload.length; next = frame.end
88 this.remove(frame.start)
89 }
90 const ahead = this.frames.size > 0
91 if (!frames.length && ahead && !this.frames.has(cursor)) { this.invalidate(); return undefined }
92 return { frames, next, ahead }
93 }
94}
95
96export interface PayloadWindowOptions {
97 readonly notifier: StreamNotifier
98 readonly schema: string
99 readonly tenantId: string
100 readonly streamId: string
101 readonly installation: InstallationIdentity
102 readonly maxBytes: number
103 readonly maxFrames: number
104 readonly windowMs: number
105 readonly wake: () => void
106 readonly report: (error: unknown) => void
107}
108type WindowReplay = Pick<ReadResult, 'next' | 'upToDate'> & { readonly stream: { readonly closed: boolean } }
109
110interface WindowSession {
111 watch?: HeadWatch
112 timer?: ReturnType<typeof setTimeout>
113 sawSnapshot: boolean
114}
115type WindowState =
116 | { readonly phase: 'catching-up' }
117 | { readonly phase: 'backoff'; readonly retryAt: number }
118 | { readonly phase: 'subscribing' | 'reconciling' | 'forwarding'; readonly session: WindowSession }
119 | { readonly phase: 'closed' }
120
121/** Owns exactly one bounded live view. Closing is terminal, including for late
122 * replay results, readiness callbacks, and synchronous notifier callbacks. */
123export class PayloadWindow {
124 private readonly buffer: AppendBuffer
125 private state: WindowState = { phase: 'catching-up' }
126 private cursor: string
127 constructor(private readonly options: PayloadWindowOptions, initial: WindowReplay) {
128 this.cursor = initial.next
129 this.buffer = new AppendBuffer(options.streamId, options.maxBytes, options.maxFrames)
130 if (initial.upToDate && !initial.stream.closed) this.start(initial.next)
131 }
132 get revision(): number { return this.buffer.revision }
133 get needsReplay(): boolean { return this.state.phase !== 'closed' && this.state.phase !== 'subscribing' && (this.state.phase !== 'forwarding' || this.buffer.needsReplay) }
134 get starting(): boolean { return this.state.phase === 'subscribing' }
135 get verified(): boolean { return this.state.phase === 'forwarding' }
136 private current(session: WindowSession): boolean { return 'session' in this.state && this.state.session === session }
137 private transition(next: WindowState): void {
138 const previous = this.state
139 if (previous.phase === 'closed') return
140 // Revoke ownership before cleanup, which may synchronously call listeners.
141 this.state = next
142 if ('session' in previous && (!('session' in next) || previous.session !== next.session)) {
143 clearTimeout(previous.session.timer)
144 previous.session.watch?.close()
145 }
146 }
147 invalidate(): void {
148 if (this.state.phase === 'closed') return
149 // Preserve an established retry deadline across redundant invalidations.
150 if (this.state.phase !== 'backoff') this.transition({ phase: 'catching-up' })
151 this.buffer.invalidate(); this.options.wake()
152 }
153 private failed(session: WindowSession, error: unknown): void {
154 if (!this.current(session)) return
155 this.transition({ phase: 'backoff', retryAt: performance.now() + 1000 })
156 this.buffer.invalidate(); this.options.report(error); this.options.wake()
157 }
158 private start(cursor: string): void {
159 if (this.state.phase === 'closed' || (this.state.phase === 'backoff' && performance.now() < this.state.retryAt)) return
160 const session: WindowSession = { sawSnapshot: false }
161 this.transition({ phase: 'subscribing', session })
162 this.cursor = cursor; this.buffer.invalidate()
163 try {
164 const watch = this.options.notifier.watchAppends!({ schema: this.options.schema, tenantId: this.options.tenantId, streamId: this.options.streamId, after: cursor, installation: this.options.installation }, (update) => {
165 if (!this.current(session)) return
166 if (update.type === 'invalidate' || (update.type === 'replace' && session.sawSnapshot)) { this.invalidate(); return }
167 if (update.type === 'replace') session.sawSnapshot = true
168 if (!this.buffer.ingest(update, this.cursor)) { this.invalidate(); return }
169 this.options.wake()
170 })
171 // A notifier may invalidate synchronously before returning its handle.
172 if (!this.current(session)) { watch.close(); void watch.ready.catch(() => {}); return }
173 session.watch = watch
174 void watch.ready.then(() => {
175 if (!this.current(session)) return
176 this.transition({ phase: 'reconciling', session })
177 this.buffer.requireReplay(); this.options.wake()
178 }, (error: unknown) => this.failed(session, error))
179 session.timer = setTimeout(() => { if (this.current(session)) this.invalidate() }, this.options.windowMs).unref()
180 } catch (error) { this.failed(session, error) }
181 }
182 reconcile(result: WindowReplay, revision: number): void {
183 if (this.state.phase === 'closed') return
184 this.cursor = result.next
185 if (!result.upToDate || result.stream.closed) { this.transition({ phase: 'catching-up' }); this.buffer.invalidate(); return }
186 if (!('session' in this.state)) { this.start(result.next); return }
187 const { session, phase } = this.state
188 if (this.buffer.reconcile(result.next, revision) && phase !== 'subscribing') this.transition({ phase: 'forwarding', session })
189 }
190 take(cursor: string, maxBytes: number, maxFrames: number, through: string): ReturnType<AppendBuffer['take']> {
191 if (this.state.phase !== 'forwarding') return undefined
192 this.cursor = cursor
193 const result = this.buffer.take(cursor, maxBytes, maxFrames, through)
194 if (this.buffer.needsReplay && !result) this.invalidate()
195 if (result) this.cursor = result.next
196 return result
197 }
198 close(): void {
199 if (this.state.phase === 'closed') return
200 this.transition({ phase: 'closed' }); this.buffer.invalidate()
201 }
202}