Open History to see the last commit
1import { observe } from './observer.js'
2import { createRealtime, rawSql } from '@neon/realtime/server'
3import type { RawSqlQuery, RealtimeDirectServer } from '@neon/realtime/server'
4import type { MaterializedLiveQuerySubscription, RawLiveQuerySubscription } from '@neon/realtime/client'
5import { validateSchema } from './path.js'
6import type { AppendUpdate, RealtimeAppend } from './live-payload.js'
7import type { InstallationIdentity } from './installation.js'
8export type { AppendUpdate, RealtimeAppend } from './live-payload.js'
9
10export interface StreamHead {
11 readonly streamId: string
12 readonly offset: string
13 readonly version: string
14 readonly closed: boolean
15 readonly deleted: boolean
16}
17export interface HeadWatch {
18 /** Resolves only when an initial authoritative result is available. */
19 readonly ready: Promise<void>
20 readonly close: () => void
21}
22export interface StreamNotifier {
23 readonly watch: (input: { readonly schema: string; readonly tenantId: string; readonly streamId: string },
24 listener: (head: StreamHead | null) => void) => HeadWatch
25 /** Stable UUIDs must already be authorized by the server. No path/tenant join. */
26 readonly watchAppends?: (input: { readonly schema: string; readonly tenantId: string; readonly streamId: string; readonly after: string; readonly installation: InstallationIdentity },
27 listener: (update: AppendUpdate) => void) => HeadWatch
28}
29export interface NeonRealtimeOptions {
30 readonly url: string
31 readonly secret: string
32 readonly database: string
33 readonly maxWatches?: number
34 readonly readyTimeoutMs?: number
35 readonly onError?: (error: unknown) => void
36}
37interface Row { id: string; tail_offset: string; change_version: string; closed: boolean; deleted_at: Date | null }
38interface Entry {
39 listeners: Set<(head: StreamHead | null) => void>
40 subscription?: MaterializedLiveQuerySubscription<Row>
41 ready: Promise<void>
42 fingerprint?: string
43 head?: StreamHead | null
44 disposed: boolean
45}
46interface AppendDbRow { stream_id: string; start_offset: string; end_offset: string; payload: Uint8Array | null; message_ends: readonly number[] | null }
47interface IdentityWatch extends HeadWatch { readonly isCurrent: () => boolean }
48interface AppendEntry {
49 readonly listeners: Set<(update: AppendUpdate) => void>
50 subscription?: RawLiveQuerySubscription<AppendDbRow>
51 ready: Promise<void>
52 disposed: boolean
53 identityWatch?: IdentityWatch
54}
55interface IdentityEntry {
56 listeners: Set<(valid: boolean) => void>
57 subscription?: MaterializedLiveQuerySubscription<InstallationIdentity>
58 ready: Promise<void>
59 valid: boolean
60 disposed: boolean
61}
62
63/** Direct server-side subscriptions; secrets and query parameters stay on the backend. */
64export function createNeonRealtimeNotifier(options: NeonRealtimeOptions): StreamNotifier & { close(): void } {
65 const maximum = options.maxWatches ?? 1000
66 if (!Number.isSafeInteger(maximum) || maximum < 1) throw new RangeError('Invalid maxWatches')
67 let client: RealtimeDirectServer<RawSqlQuery<unknown>> | undefined
68 const entries = new Map<string, Entry>()
69 const appendEntries = new Map<string, AppendEntry>()
70 const identities = new Map<string, IdentityEntry>()
71 let closed = false
72 const report = (error: unknown) => observe(options.onError, error)
73 const retire = (key: string, entry: Entry) => {
74 entry.disposed = true
75 entry.subscription?.unsubscribe()
76 entries.delete(key)
77 if (!entries.size && !appendEntries.size && !identities.size) { client?.close(); client = undefined }
78 }
79 const retireAppends = (key: string, entry: AppendEntry) => {
80 entry.disposed = true; entry.subscription?.unsubscribe(); entry.identityWatch?.close(); appendEntries.delete(key)
81 if (!entries.size && !appendEntries.size && !identities.size) { client?.close(); client = undefined }
82 }
83 const watchIdentity = (schema: string, expected: InstallationIdentity, listener: (valid: boolean) => void): IdentityWatch => {
84 const key = JSON.stringify([schema, expected.id, expected.serving_epoch, expected.environment_id, expected.storage_identity])
85 let entry = identities.get(key)
86 if (!entry) {
87 if (entries.size + appendEntries.size + identities.size >= maximum) throw new Error('Realtime watch limit reached')
88 const current: IdentityEntry = { listeners: new Set(), ready: Promise.resolve(), valid: false, disposed: false }
89 identities.set(key, current)
90 client ??= createRealtime({ url: options.url, secret: options.secret, db: options.database })
91 const active = client
92 current.ready = (async () => {
93 const subscription = await active.subscribe(rawSql<InstallationIdentity>(`SELECT id, serving_epoch, serving_state, environment_id, storage_identity
94 FROM ${schema}.installation WHERE singleton = true`))
95 if (current.disposed) { subscription.unsubscribe(); return }
96 current.subscription = subscription
97 let everValid = false
98 const publish = () => {
99 if (current.disposed) return
100 const snapshot = subscription.getSnapshot(), row = snapshot.data?.[0]
101 current.valid = subscription.getState().status === 'live' && snapshot.status === 'live' && snapshot.data?.length === 1 && !!row && row.id === expected.id
102 && row.serving_epoch === expected.serving_epoch && row.serving_state === 'active'
103 && row.environment_id === expected.environment_id && row.storage_identity === expected.storage_identity
104 if (current.valid) everValid = true
105 if (!everValid) return
106 for (const callback of current.listeners) observe(callback, current.valid, report)
107 }
108 subscription.onChange(publish)
109 subscription.onStateChange((state) => { if (state.status !== 'live') publish() })
110 await subscription.awaitRows(() => true, options.readyTimeoutMs ?? 20_000)
111 publish()
112 if (!current.valid) throw new Error('Realtime installation identity differs from the serving database')
113 })().catch((error: unknown) => { if (!current.disposed) throw error })
114 void current.ready.catch(report)
115 entry = current
116 }
117 const watched = entry
118 watched.listeners.add(listener)
119 return { isCurrent: () => watched.valid && !watched.disposed, ready: watched.ready.then(() => { if (!watched.valid && !watched.disposed) throw new Error('Realtime installation identity is not current') }), close() {
120 watched.listeners.delete(listener)
121 if (!watched.listeners.size && !watched.disposed) {
122 watched.disposed = true; watched.subscription?.unsubscribe(); identities.delete(key)
123 }
124 } }
125 }
126 return {
127 watchAppends(input, listener) {
128 if (closed) throw new Error('Realtime notifier is closed')
129 const schema = validateSchema(input.schema)
130 const key = JSON.stringify([schema, input.tenantId, input.streamId, input.after, input.installation])
131 let entry = appendEntries.get(key)
132 if (!entry) {
133 if (entries.size + appendEntries.size + identities.size >= maximum) throw new Error('Realtime watch limit reached')
134 const current: AppendEntry = { listeners: new Set(), ready: Promise.resolve(), disposed: false }
135 client ??= createRealtime({ url: options.url, secret: options.secret, db: options.database })
136 appendEntries.set(key, current)
137 const active = client
138 current.ready = (async () => {
139 current.identityWatch = watchIdentity(schema, input.installation, (valid) => {
140 if (!valid && !current.disposed) for (const callback of current.listeners) observe(callback, { type: 'invalidate' }, report)
141 })
142 await current.identityWatch.ready
143 if (current.disposed) return
144 const subscription = await active.subscribe(rawSql<AppendDbRow>(`SELECT stream_id, start_offset, end_offset, payload, message_ends
145 FROM ${schema}.appends WHERE stream_id = $1::uuid AND end_offset > $2`, [input.streamId, input.after]), { materialize: false })
146 if (current.disposed) { subscription.unsubscribe(); return }
147 current.subscription = subscription
148 const publish = (update: AppendUpdate) => { if (!current.disposed) for (const callback of current.listeners) observe(callback, update, report) }
149 const row = (rowId: string, value: AppendDbRow): RealtimeAppend => ({ rowId, streamId: value.stream_id, start: value.start_offset, end: value.end_offset, payload: value.payload, messageEnds: value.message_ends })
150 subscription.onUpdate((update) => {
151 if (!current.identityWatch?.isCurrent()) { publish({ type: 'invalidate' }); return }
152 if ((update.type === 'rows' ? update.rows.length : update.changes.length) > 4096) { publish({ type: 'invalidate' }); return }
153 if (update.type === 'rows') publish({ type: 'replace', rows: update.rows.map((value) => row(value.rowId, value.row)), removed: [] })
154 else publish({ type: 'changes', rows: update.changes.flatMap((change) => change.type === 'upsert' ? [row(change.rowId, change.row)] : []),
155 removed: update.changes.flatMap((change) => change.type === 'remove' ? [change.rowId] : []) })
156 })
157 let wasLive = false
158 await new Promise<void>((resolve, reject) => {
159 const timer = setTimeout(() => reject(new Error('Realtime append snapshot deadline exceeded')), options.readyTimeoutMs ?? 20_000)
160 const state = (value: ReturnType<typeof subscription.getState>) => {
161 if (current.disposed) { clearTimeout(timer); resolve(); return }
162 if (value.status === 'live') { wasLive = true; clearTimeout(timer); resolve() }
163 else if (value.status === 'error') { clearTimeout(timer); publish({ type: 'invalidate' }); reject(value.error); report(value.error) }
164 else if (wasLive) publish({ type: 'invalidate' })
165 }
166 subscription.onStateChange(state); state(subscription.getState())
167 })
168 })().catch((error: unknown) => { if (!current.disposed) throw error })
169 void current.ready.catch(report)
170 entry = current
171 }
172 const watched = entry
173 watched.listeners.add(listener)
174 let disposed = false
175 return { ready: watched.ready, close() {
176 if (disposed) return
177 disposed = true; watched.listeners.delete(listener)
178 if (!watched.listeners.size) retireAppends(key, watched)
179 } }
180 },
181 watch(input, listener) {
182 if (closed) throw new Error('Realtime notifier is closed')
183 const schema = validateSchema(input.schema)
184 const key = JSON.stringify([schema, input.tenantId, input.streamId])
185 let entry = entries.get(key)
186 if (!entry) {
187 if (entries.size + appendEntries.size + identities.size >= maximum) throw new Error('Realtime watch limit reached')
188 const current: Entry = { listeners: new Set(), ready: Promise.resolve(), disposed: false }
189 client ??= createRealtime({ url: options.url, secret: options.secret, db: options.database })
190 entries.set(key, current)
191 const active = client
192 current.ready = (async () => {
193 const subscription = await active.subscribe(rawSql<Row>(`SELECT id, tail_offset, change_version, closed, deleted_at
194 FROM ${schema}.streams WHERE tenant_id = $1 AND id = $2::uuid`, [input.tenantId, input.streamId]))
195 if (current.disposed) { subscription.unsubscribe(); return }
196 current.subscription = subscription
197 const publish = () => {
198 if (current.disposed) return
199 const snapshot = subscription.getSnapshot()
200 if (snapshot.data === undefined || snapshot.status !== 'live') return
201 const row = snapshot.data[0]
202 const head = row ? { streamId: row.id, offset: row.tail_offset, version: String(row.change_version), closed: row.closed, deleted: row.deleted_at !== null } : null
203 const fingerprint = JSON.stringify(head)
204 if (current.fingerprint === fingerprint) return
205 current.fingerprint = fingerprint
206 current.head = head
207 for (const callback of current.listeners) observe(callback, head, report)
208 }
209 subscription.onChange(publish)
210 subscription.onStateChange((state) => { if (!current.disposed && state.status === 'error') report(state.error) })
211 await subscription.awaitRows(() => true, options.readyTimeoutMs ?? 20_000)
212 publish()
213 })().catch((error: unknown) => { if (!current.disposed) throw error })
214 void current.ready.catch(report)
215 entry = current
216 }
217 const watched = entry
218 watched.listeners.add(listener)
219 if (watched.head !== undefined) queueMicrotask(() => {
220 if (!watched.disposed && watched.listeners.has(listener)) observe(listener, watched.head ?? null, report)
221 })
222 let disposed = false
223 return { ready: watched.ready, close() {
224 if (disposed) return
225 disposed = true
226 watched.listeners.delete(listener)
227 if (!watched.listeners.size) retire(key, watched)
228 } }
229 },
230 close() {
231 closed = true
232 for (const [key, entry] of entries) retire(key, entry)
233 for (const [key, entry] of appendEntries) retireAppends(key, entry)
234 },
235 }
236}