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

shape.ts

360 lines10.5 KB

1import { Message, Offset, Row } from './types'
2import {
3 isChangeMessage,
4 isControlMessage,
5 canonicalBigintSafeStringify,
6} from './helpers'
7import { FetchError } from './error'
8import { LogMode, ShapeStreamInterface } from './client'
9​
10export type ShapeData<T extends Row<unknown> = Row> = Map<string, T>
11export type ShapeChangedCallback<T extends Row<unknown> = Row> = (data: {
12 value: ShapeData<T>
13 rows: T[]
14}) => void
15​
16type ShapeStatus = `syncing` | `up-to-date`
17​
18/**
19 * Shape subscriber notification semantics (see SPEC.md → "Shape
20 * notification semantics" for the canonical contract):
21 *
22 * - **N1 (no notify while syncing).** Data messages that arrive while
23 * `status === 'syncing'` apply to `#data` but do NOT call `#notify`.
24 * A notification fires only when the shape transitions from
25 * `syncing` to `up-to-date` via an up-to-date control message. This
26 * guarantees that subscribers observing `rows` always see a
27 * consistent snapshot of the shape AND can read a defined
28 * `stream.lastSyncedAt()`.
29 *
30 * - **N2 (notify on change while up-to-date).** Once
31 * `status === 'up-to-date'`, any data message (insert/update/delete,
32 * subject to `mode === 'changes_only'` filtering) triggers a
33 * notification; the status then transitions back to `syncing` until
34 * the next up-to-date message.
35 *
36 * A `must-refetch` control message clears `#data` and transitions the
37 * status back to `syncing`, which re-engages N1 — subscribers will
38 * receive the post-rotation state on the next `up-to-date` without
39 * ever observing an intermediate empty-rows notification.
40 */
41​
42/**
43 * A Shape is an object that subscribes to a shape log,
44 * keeps a materialised shape `.rows` in memory and
45 * notifies subscribers when the value has changed.
46 *
47 * It can be used without a framework and as a primitive
48 * to simplify developing framework hooks.
49 *
50 * @constructor
51 * @param {ShapeStream<T extends Row>} - the underlying shape stream
52 * @example
53 * ```
54 * const shapeStream = new ShapeStream<{ foo: number }>({
55 * url: `http://localhost:3000/v1/shape`,
56 * params: {
57 * table: `foo`
58 * }
59 * })
60 * const shape = new Shape(shapeStream)
61 * ```
62 *
63 * `rows` returns a promise that resolves the Shape data once the Shape has been
64 * fully loaded (and when resuming from being offline):
65 *
66 * const rows = await shape.rows
67 *
68 * `currentRows` returns the current data synchronously:
69 *
70 * const rows = shape.currentRows
71 *
72 * Subscribe to updates. Called whenever the shape updates in Postgres.
73 *
74 * shape.subscribe(({ rows }) => {
75 * console.log(rows)
76 * })
77 */
78export class Shape<T extends Row<unknown> = Row> {
79 readonly stream: ShapeStreamInterface<T>
80​
81 readonly #data: ShapeData<T> = new Map()
82 readonly #subscribers = new Map<object, ShapeChangedCallback<T>>()
83 readonly #insertedKeys = new Set<string>()
84 readonly #requestedSubSnapshots = new Set<string>()
85 #reexecuteSnapshotsPending = false
86 #status: ShapeStatus = `syncing`
87 #error: FetchError | false = false
88​
89 constructor(stream: ShapeStreamInterface<T>) {
90 this.stream = stream
91 this.stream.subscribe(
92 this.#process.bind(this),
93 this.#handleError.bind(this)
94 )
95 }
96​
97 get isUpToDate(): boolean {
98 return this.#status === `up-to-date`
99 }
100​
101 get lastOffset(): Offset {
102 return this.stream.lastOffset
103 }
104​
105 get handle(): string | undefined {
106 return this.stream.shapeHandle
107 }
108​
109 get rows(): Promise<T[]> {
110 return this.value.then((v) => Array.from(v.values()))
111 }
112​
113 get currentRows(): T[] {
114 return Array.from(this.currentValue.values())
115 }
116​
117 get value(): Promise<ShapeData<T>> {
118 return new Promise((resolve, reject) => {
119 if (this.stream.isUpToDate) {
120 resolve(this.currentValue)
121 } else {
122 const unsubscribe = this.subscribe(({ value }) => {
123 unsubscribe()
124 if (this.#error) reject(this.#error)
125 resolve(value)
126 })
127 }
128 })
129 }
130​
131 get currentValue() {
132 return this.#data
133 }
134​
135 get error() {
136 return this.#error
137 }
138​
139 /** Unix time at which we last synced. Undefined when `isLoading` is true. */
140 lastSyncedAt(): number | undefined {
141 return this.stream.lastSyncedAt()
142 }
143​
144 /** Time elapsed since last sync (in ms). Infinity if we did not yet sync. */
145 lastSynced() {
146 return this.stream.lastSynced()
147 }
148​
149 /** True during initial fetch. False afterwise. */
150 isLoading() {
151 return this.stream.isLoading()
152 }
153​
154 /** Indicates if we are connected to the Electric sync service. */
155 isConnected(): boolean {
156 return this.stream.isConnected()
157 }
158​
159 /** Current log mode of the underlying stream */
160 get mode(): LogMode {
161 return this.stream.mode
162 }
163​
164 /**
165 * Request a snapshot for subset of data. Only available when mode is changes_only.
166 * Returns void; data will be emitted via the stream and processed by this Shape.
167 */
168 async requestSnapshot(
169 params: Parameters<ShapeStreamInterface<T>[`requestSnapshot`]>[0]
170 ): Promise<void> {
171 // Track this snapshot request for future re-execution on shape rotation.
172 // Use canonical stringify so permutation-equivalent params dedup.
173 const key = canonicalBigintSafeStringify(params)
174 this.#requestedSubSnapshots.add(key)
175 // Ensure the stream is up-to-date so schema is available for parsing
176 await this.#awaitUpToDate()
177 await this.stream.requestSnapshot(params)
178 }
179​
180 subscribe(callback: ShapeChangedCallback<T>): () => void {
181 const subscriptionId = {}
182​
183 this.#subscribers.set(subscriptionId, callback)
184​
185 return () => {
186 this.#subscribers.delete(subscriptionId)
187 }
188 }
189​
190 unsubscribeAll(): void {
191 this.#subscribers.clear()
192 }
193​
194 get numSubscribers() {
195 return this.#subscribers.size
196 }
197​
198 #process(messages: Message<T>[]): void {
199 let shouldNotify = false
200​
201 messages.forEach((message) => {
202 if (isChangeMessage(message)) {
203 const wasUpToDate = this.#status === `up-to-date`
204 this.#updateShapeStatus(`syncing`)
205 if (this.mode === `full`) {
206 switch (message.headers.operation) {
207 case `insert`:
208 this.#data.set(message.key, message.value)
209 if (wasUpToDate) shouldNotify = true
210 break
211 case `update`:
212 this.#data.set(message.key, {
213 ...this.#data.get(message.key)!,
214 ...message.value,
215 })
216 if (wasUpToDate) shouldNotify = true
217 break
218 case `delete`:
219 this.#data.delete(message.key)
220 if (wasUpToDate) shouldNotify = true
221 break
222 }
223 } else {
224 // changes_only: only apply updates/deletes for keys for which we observed an insert
225 switch (message.headers.operation) {
226 case `insert`:
227 this.#insertedKeys.add(message.key)
228 this.#data.set(message.key, message.value)
229 if (wasUpToDate) shouldNotify = true
230 break
231 case `update`:
232 if (this.#insertedKeys.has(message.key)) {
233 this.#data.set(message.key, {
234 ...this.#data.get(message.key)!,
235 ...message.value,
236 })
237 if (wasUpToDate) shouldNotify = true
238 }
239 break
240 case `delete`:
241 if (this.#insertedKeys.has(message.key)) {
242 this.#data.delete(message.key)
243 this.#insertedKeys.delete(message.key)
244 if (wasUpToDate) shouldNotify = true
245 }
246 break
247 }
248 }
249 }
250​
251 if (isControlMessage(message)) {
252 switch (message.headers.control) {
253 case `up-to-date`:
254 if (this.#updateShapeStatus(`up-to-date`)) shouldNotify = true
255 if (this.#reexecuteSnapshotsPending) {
256 this.#reexecuteSnapshotsPending = false
257 void this.#reexecuteSnapshots()
258 }
259 break
260 case `must-refetch`:
261 this.#data.clear()
262 this.#insertedKeys.clear()
263 this.#error = false
264 this.#updateShapeStatus(`syncing`)
265 this.#reexecuteSnapshotsPending = true
266 break
267 }
268 }
269 })
270​
271 if (shouldNotify) this.#notify()
272 }
273​
274 async #reexecuteSnapshots(): Promise<void> {
275 try {
276 await this.#awaitUpToDate()
277 } catch (e) {
278 this.#surfaceReexecuteError(e)
279 return
280 }
281​
282 const results = await Promise.all(
283 Array.from(this.#requestedSubSnapshots).map(async (jsonParams) => {
284 try {
285 const snapshot = JSON.parse(jsonParams)
286 await this.stream.requestSnapshot(snapshot)
287 return undefined
288 } catch (e) {
289 return e
290 }
291 })
292 )
293​
294 const firstError = results.find((e) => e !== undefined)
295 if (firstError !== undefined) this.#surfaceReexecuteError(firstError)
296 }
297​
298 #surfaceReexecuteError(e: unknown): void {
299 if (e instanceof FetchError) {
300 this.#error = e
301 } else if (e instanceof Error) {
302 this.#error = new FetchError(0, e.message, undefined, {}, ``, e.message)
303 } else {
304 this.#error = new FetchError(0, String(e), undefined, {}, ``, String(e))
305 }
306 this.#notify()
307 }
308​
309 async #awaitUpToDate(): Promise<void> {
310 if (this.#error) throw this.#error
311 if (this.stream.isUpToDate) return
312 if (this.stream.error) throw this.stream.error as Error
313 await new Promise<void>((resolve, reject) => {
314 let settled = false
315 let interval: ReturnType<typeof setInterval>
316 let unsub: (() => void) | undefined
317 const done = (action: () => void) => {
318 if (settled) return
319 settled = true
320 clearInterval(interval)
321 unsub?.()
322 action()
323 }
324 const check = () => {
325 if (this.stream.isUpToDate) return done(resolve)
326 const streamError = this.stream.error as Error | undefined
327 if (streamError) return done(() => reject(streamError))
328 if (this.#error) {
329 const err = this.#error
330 return done(() => reject(err))
331 }
332 }
333 interval = setInterval(check, 10)
334 unsub = this.stream.subscribe(
335 () => check(),
336 (err) => done(() => reject(err))
337 )
338 check()
339 })
340 }
341​
342 #updateShapeStatus(status: ShapeStatus): boolean {
343 const stateChanged = this.#status !== status
344 this.#status = status
345 return stateChanged && status === `up-to-date`
346 }
347​
348 #handleError(e: Error): void {
349 if (e instanceof FetchError) {
350 this.#error = e
351 this.#notify()
352 }
353 }
354​
355 #notify(): void {
356 this.#subscribers.forEach((callback) => {
357 callback({ value: this.currentValue, rows: this.currentRows })
358 })
359 }