Open History to see the last commit
1import { randomUUID } from 'node:crypto'
2import type {
3 Envelope,
4 RawChange,
5 RawRow,
6 Sequence,
7 SnapshotEvidence,
8} from '@neon/realtime-electric-protocol'
9import type {
10 RealtimeSource,
11 SourceEvent,
12 SourceQuery,
13} from './realtime-source.js'
14import type { ShapeLog } from './shape-log.js'
15import { MemoryShapeLog } from './memory-log.js'
16
17export interface OwnerDefinition {
18 /** Prepared by the authorized query-definition layer, never interpolated here. */
19 query: SourceQuery
20 namespace: string
21 table: string
22 primaryKey: readonly string[]
23 /** Public projection. The source query also includes hidden primary-key columns. */
24 projection: readonly string[]
25 schema: Record<string, { type: string; [key: string]: unknown }>
26 logMode?: 'full' | 'changes_only'
27 replica?: 'default' | 'full'
28}
29
30export interface ShapeOwnerOptions {
31 source: RealtimeSource
32 definition: OwnerDefinition
33 now?: () => number
34 ttlMs?: number
35 includeBaseline?: boolean
36 onClose?: (event: { handle: string; error: Error }) => void
37 createLog?: (context: { handle: string; expiresAt: number }) => ShapeLog
38}
39
40/** A handle has exactly one source epoch and an absolute, bounded lifetime. */
41export class ShapeOwner {
42 readonly handle = randomUUID()
43 readonly log: ShapeLog
44 readonly expiresAt: number
45 readonly definition: OwnerDefinition
46 readonly #abort = new AbortController()
47 readonly #now: () => number
48 readonly #expiry: ReturnType<typeof setTimeout>
49 readonly #rows = new Map<string, RawRow>()
50 #columns?: Extract<SourceEvent, { type: 'schema' }>['columns']
51 #baselineComplete = false
52 #error?: Error
53 #seq = 0n
54 #queue: Promise<void> = Promise.resolve()
55 #start?: Promise<void>
56
57 constructor(private readonly options: ShapeOwnerOptions) {
58 this.definition = options.definition
59 this.#now = options.now ?? Date.now
60 const ttl = options.ttlMs ?? 900_000
61 if (!Number.isFinite(ttl) || ttl <= 0 || ttl > 900_000)
62 throw new Error('Shape TTL must be positive and at most 15 minutes')
63 this.expiresAt = this.#now() + ttl
64 this.log =
65 options.createLog?.({ handle: this.handle, expiresAt: this.expiresAt }) ??
66 new MemoryShapeLog()
67 this.#append({
68 kind: 'initializing',
69 handle: this.handle,
70 expiresAt: new Date(this.expiresAt).toISOString(),
71 })
72 this.#expiry = setTimeout(() => this.close(new Error('Shape expired')), ttl)
73 this.#expiry.unref?.()
74 }
75
76 /** Does not wait for a baseline; first HTTP response can return immediately. */
77 start(): Promise<void> {
78 return (this.#start ??= this.options.source
79 .subscribe(
80 this.definition.query,
81 {
82 event: (event) => {
83 const next = this.#queue.then(() => {
84 this.assertValid()
85 this.#accept(event)
86 })
87 // Register failure immediately. Readers always observe a terminal
88 // handle rather than an unhandled rejection or an incomplete log.
89 this.#queue = next.catch((error) => this.close(asError(error)))
90 },
91 error: (error) => this.close(error),
92 },
93 this.#abort.signal
94 )
95 .then(() => {})
96 .catch((error) => this.close(asError(error))))
97 }
98
99 async settled(): Promise<void> {
100 await this.#queue
101 this.assertValid()
102 }
103
104 get schema(): Record<string, unknown> | undefined {
105 return this.#columns ? this.definition.schema : undefined
106 }
107
108 /** Diagnostic count only; retained source rows remain private to the owner. */
109 get retainedRowCount(): number {
110 return this.#rows.size
111 }
112
113 assertValid(): void {
114 if (this.#now() >= this.expiresAt) this.close(new Error('Shape expired'))
115 if (this.#error) throw this.#error
116 }
117
118 close(error = new Error('Shape owner stopped')): void {
119 if (this.#error) return
120 this.#error = error
121 clearTimeout(this.#expiry)
122 this.#abort.abort(error)
123 this.log.close()
124 this.#rows.clear()
125 this.options.onClose?.({ handle: this.handle, error })
126 }
127
128 #accept(event: SourceEvent): void {
129 switch (event.type) {
130 case 'schema': {
131 if (this.#columns) throw new Error('Shape schema replaced')
132 this.#columns = event.columns
133 const names = new Set(event.columns.map((c) => c.name))
134 if (names.size !== event.columns.length)
135 throw new Error('Duplicate source column name')
136 for (const name of [
137 ...this.definition.primaryKey,
138 ...this.definition.projection,
139 ]) {
140 if (!names.has(name))
141 throw new Error(`Source column missing: ${name}`)
142 }
143 return
144 }
145 case 'baseline': {
146 if (this.#baselineComplete) throw new Error('Replacement baseline')
147 const changes: RawChange[] = []
148 for (const wire of event.rows) {
149 const row = this.#decode(wire.values)
150 this.#rows.set(wire.row_key, row)
151 if (
152 this.options.includeBaseline !== false &&
153 this.definition.logMode !== 'changes_only'
154 )
155 changes.push(this.#change('insert', row))
156 if (changes.length === 128)
157 this.#append({ kind: 'snapshot-chunk', changes: changes.splice(0) })
158 }
159 if (changes.length) this.#append({ kind: 'snapshot-chunk', changes })
160 this.#append({
161 kind: 'snapshot-complete',
162 coveredSeq: String(this.#seq) as Sequence,
163 evidence: { snapshot: snapshot(event.mvcc) },
164 })
165 this.#baselineComplete = true
166 return
167 }
168 case 'publication': {
169 if (!this.#baselineComplete)
170 throw new Error('Publication before baseline')
171 const changes: RawChange[] = []
172 for (const wire of event.changes) {
173 const before = this.#rows.get(wire.row_key)
174 if (wire.op === 'remove') {
175 if (!before) throw new Error('Source removed an unknown row')
176 this.#rows.delete(wire.row_key)
177 changes.push(this.#change('delete', before))
178 } else {
179 const row = this.#decode(wire.values)
180 // A primary-key change can retain the opaque source identity. Emit
181 // remove+insert so Shape materialization never retains the old key.
182 if (before && this.#key(before) !== this.#key(row)) {
183 changes.push(this.#change('delete', before))
184 changes.push(this.#change('insert', row))
185 } else
186 changes.push(
187 this.#change(before ? 'update' : 'insert', row, before)
188 )
189 this.#rows.set(wire.row_key, row)
190 }
191 }
192 this.#append({
193 kind: 'publication',
194 changes,
195 evidence: {
196 txids: event.txids.map(sequence),
197 lsn: lsnToDecimal(event.frontier.lsn),
198 },
199 })
200 return
201 }
202 case 'progress':
203 if (!this.#baselineComplete) throw new Error('Progress before baseline')
204 this.#append({
205 kind: 'progress',
206 coveredSeq: String(this.#seq) as Sequence,
207 evidence: { snapshot: snapshot(event.mvcc) },
208 })
209 return
210 case 'reset':
211 throw new Error('Source reset; refetch required')
212 }
213 }
214
215 #decode(values: readonly (string | null | { base64: string })[]): RawRow {
216 if (!this.#columns || values.length !== this.#columns.length)
217 throw new Error('Invalid source row schema')
218 return Object.fromEntries(
219 this.#columns.map((column, index) => {
220 const value = values[index]
221 if (value !== null && typeof value === 'object') {
222 if (column.type_oid !== 17 || column.codec !== 'bytes')
223 throw new Error('Unsupported binary source value')
224 return [
225 column.name,
226 `\\x${Buffer.from(value.base64, 'base64').toString('hex')}`,
227 ]
228 }
229 return [column.name, value]
230 })
231 )
232 }
233
234 #key(row: RawRow): string {
235 const quote = (part: string) => `"${part.replaceAll('"', '""')}"`
236 return `${quote(this.definition.namespace)}.${quote(this.definition.table)}/${this.definition.primaryKey
237 .map((name) => {
238 const value = row[name]
239 if (value === null || value === undefined || typeof value === 'object')
240 throw new Error('Missing scalar primary key')
241 return quote(String(value))
242 })
243 .join('/')}`
244 }
245
246 #project(row: RawRow): RawRow {
247 return Object.fromEntries(
248 this.definition.projection.map((name) => [name, row[name]])
249 )
250 }
251
252 #change(
253 operation: 'insert' | 'update' | 'delete',
254 row: RawRow,
255 before?: RawRow
256 ): RawChange {
257 const projected = this.#project(row)
258 const keys = new Set(this.definition.primaryKey)
259 const changed = before
260 ? this.definition.projection.filter(
261 (column) => row[column] !== before[column]
262 )
263 : []
264 const full = this.definition.replica === 'full'
265 const value =
266 full || operation === 'insert'
267 ? projected
268 : Object.fromEntries(
269 Object.entries(projected).filter(
270 ([column]) =>
271 keys.has(column) ||
272 (operation === 'update' && changed.includes(column))
273 )
274 )
275 return {
276 key: this.#key(row),
277 value,
278 ...(full && before
279 ? {
280 old_value: Object.fromEntries(
281 changed.map((column) => [column, before[column]])
282 ),
283 }
284 : {}),
285 headers: {
286 operation,
287 relation: [this.definition.namespace, this.definition.table],
288 },
289 }
290 }
291
292 #append(value: EnvelopeInput): void {
293 this.#seq += 1n
294 this.log.append({
295 ...value,
296 version: 1,
297 seq: String(this.#seq) as Sequence,
298 } as Envelope)
299 }
300}
301
302type EnvelopeInput = Envelope extends infer E
303 ? E extends Envelope
304 ? Omit<E, 'version' | 'seq'>
305 : never
306 : never
307function asError(value: unknown): Error {
308 return value instanceof Error ? value : new Error(String(value))
309}
310function sequence(value: string): Sequence {
311 if (!/^(0|[1-9][0-9]*)$/.test(value))
312 throw new Error('Invalid source integer')
313 return value as Sequence
314}
315function snapshot(value: {
316 xmin: string
317 xmax: string
318 xip: readonly string[]
319}): SnapshotEvidence {
320 return {
321 xmin: sequence(value.xmin),
322 xmax: sequence(value.xmax),
323 xip_list: value.xip.map(sequence),
324 }
325}
326export function lsnToDecimal(lsn: string): Sequence {
327 if (!/^[0-9A-F]{1,8}\/[0-9A-F]{1,8}$/.test(lsn))
328 throw new Error('Invalid PostgreSQL LSN')
329 const [high, low] = lsn.split('/').map((part) => BigInt(`0x${part}`))
330 return String((high << 32n) | low) as Sequence
331}