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

client-lifecycle.test.ts

491 lines18.1 KB

1import { describe, expect, it } from 'vitest'
2import {
3 FetchError,
4 Shape,
5 ShapeStream,
6 isChangeMessage,
7} from '../../packages/client/src/index.js'
8import { createShapeHandler } from '../../packages/server/src/handler.js'
9import { ObjectShapeLog } from '../../packages/server/src/object-log.js'
10import { FixtureObjectStore } from './support/object-store.js'
11import type { SourceObserver } from '../../packages/server/src/realtime-source.js'
12​
13function deferred<T>() {
14 let resolve!: (value: T) => void
15 const promise = new Promise<T>((done) => {
16 resolve = done
17 })
18 return { promise, resolve }
20function fixture(
21 objects: boolean,
22 electricOnly: boolean,
23 connectionMs = 5_000
24) {
25 const observers: SourceObserver[] = []
26 const requests: Request[] = []
27 const store = new FixtureObjectStore()
28 let txid = 10
29 const handler = createShapeHandler({
30 longPollMs: connectionMs,
31 sseConnectionMs: connectionMs,
32 source: {
33 async subscribe(_, observer) {
34 observers.push(observer)
35 observer.event({
36 type: 'schema',
37 columns: [
38 { name: 'id', type_oid: 23, typmod: -1, codec: 'pg_text' },
39 { name: 'label', type_oid: 25, typmod: -1, codec: 'pg_text' },
40 ],
41 })
42 observer.event({
43 type: 'baseline',
44 rows: [{ row_key: 'a'.repeat(64), values: ['1', 'initial'] }],
45 mvcc: { xmin: '10', xmax: '10', xip: [] },
46 })
47 return { close() {} }
48 },
49 close() {},
50 },
51 createLog: objects
52 ? ({ handle }) =>
53 new ObjectShapeLog({ store, prefix: handle, sealBytes: 1 })
54 : undefined,
55 async authorize(request) {
56 return {
57 authorizationKey: 'client-lifecycle',
58 definition: {
59 namespace: 'public',
60 logMode:
61 new URL(request.url).searchParams.get('log') === 'changes_only'
62 ? 'changes_only'
63 : 'full',
64 table: 'items',
65 primaryKey: ['id'],
66 projection: ['id', 'label'],
67 schema: { id: { type: 'int4' }, label: { type: 'text' } },
68 query: { sql: 'select id,label from public.items' },
69 },
70 }
71 },
72 })
73 const fetchClient: typeof fetch = async (input, init) => {
74 const request = new Request(input, init)
75 requests.push(request)
76 const response = await handler.fetch(request)
77 if (!electricOnly) return response
78 const headers = new Headers(response.headers)
79 for (const name of [...headers.keys()])
80 if (name.startsWith('stream-')) headers.delete(name)
81 return new Response(response.body, { status: response.status, headers })
82 }
83 return {
84 handler,
85 observers,
86 requests,
87 fetchClient,
88 publish(label: string, operation: 'upsert' | 'remove' = 'upsert') {
89 txid++
90 observers[0].event({
91 type: 'publication',
92 changes: [
93 operation === 'remove'
94 ? { op: 'remove', row_key: 'a'.repeat(64) }
95 : { op: 'upsert', row_key: 'a'.repeat(64), values: ['1', label] },
96 ],
97 txids: [String(txid)],
98 frontier: { lsn: `0/${txid.toString(16).toUpperCase()}` },
99 })
100 return txid
101 },
102 }
104​
105for (const objects of [false, true])
106 for (const electricOnly of [false, true])
107 for (const liveSse of [false, true])
108 describe(`client lifecycle (objects=${objects}, Electric headers=${electricOnly}, SSE=${liveSse})`, () => {
109 it('removes one stream and shape subscriber while the remaining subscribers keep receiving updates', async () => {
110 const f = fixture(objects, electricOnly)
111 const abort = new AbortController()
112 const stream = new ShapeStream<{ id: number; label: string }>({
113 url: 'http://local/application/shapes',
114 liveSse,
115 signal: abort.signal,
116 fetchClient: f.fetchClient,
117 })
118 const shape = new Shape(stream)
119 let removedStream = 0,
120 keptStream = 0,
121 removedShape = 0,
122 keptShape = 0
123 const unsubscribeStream = stream.subscribe(() => {
124 removedStream++
125 })
126 stream.subscribe(() => {
127 keptStream++
128 })
129 const unsubscribeShape = shape.subscribe(() => {
130 removedShape++
131 })
132 shape.subscribe(() => {
133 keptShape++
134 })
135 try {
136 expect(await shape.rows).toEqual([{ id: 1, label: 'initial' }])
137 const handle = stream.shapeHandle
138 const counts = {
139 removedStream,
140 keptStream,
141 removedShape,
142 keptShape,
143 }
144 unsubscribeStream()
145 unsubscribeShape()
146 expect(shape.numSubscribers).toBe(1)
147 f.publish('next')
148 await expect
149 .poll(() => shape.currentRows)
150 .toEqual([{ id: 1, label: 'next' }])
151 expect(removedStream).toBe(counts.removedStream)
152 expect(removedShape).toBe(counts.removedShape)
153 expect(keptStream).toBeGreaterThan(counts.keptStream)
154 expect(keptShape).toBeGreaterThan(counts.keptShape)
155 expect(stream.shapeHandle).toBe(handle)
156 expect(f.observers).toHaveLength(1)
157 } finally {
158 abort.abort()
159 stream.unsubscribeAll()
160 f.handler.close()
161 await f.handler.drain()
162 }
163 })
164​
165 it('finishes subscribe:false with a ready snapshot and a disconnected public status', async () => {
166 const f = fixture(objects, electricOnly)
167 const abort = new AbortController()
168 const stream = new ShapeStream({
169 url: 'http://local/application/shapes',
170 liveSse,
171 subscribe: false,
172 signal: abort.signal,
173 fetchClient: f.fetchClient,
174 })
175 const shape = new Shape(stream)
176 try {
177 expect(await shape.rows).toEqual([{ id: 1, label: 'initial' }])
178 await expect.poll(() => stream.isConnected()).toBe(false)
179 expect(stream.isLoading()).toBe(false)
180 expect(stream.isUpToDate).toBe(true)
181 expect(shape.isUpToDate).toBe(true)
182 expect(stream.lastSyncedAt()).toEqual(expect.any(Number))
183 expect(stream.shapeHandle).toBeTruthy()
184 expect(stream.lastOffset).not.toBe('-1')
185 expect(
186 f.requests.every((r) => !new URL(r.url).searchParams.has('live'))
187 ).toBe(true)
188 } finally {
189 abort.abort()
190 stream.unsubscribeAll()
191 f.handler.close()
192 await f.handler.drain()
193 }
194 })
195​
196 it('disconnects on a live auth error and resumes the same history after asynchronous repair', async () => {
197 const f = fixture(objects, electricOnly)
198 const abort = new AbortController()
199 const entered = deferred<Error>()
200 const repaired = deferred<void>()
201 let rejectNext = false
202 const headers: string[] = []
203 const stream = new ShapeStream<{ id: number; label: string }>({
204 url: 'http://local/application/shapes?tenant=a%2Bb',
205 params: { table: 'items' },
206 liveSse,
207 signal: abort.signal,
208 headers: { authorization: 'Bearer before' },
209 fetchClient: async (input, init) => {
210 const request = new Request(input, init)
211 headers.push(request.headers.get('authorization')!)
212 if (rejectNext) {
213 rejectNext = false
214 return new Response('expired', { status: 401 })
215 }
216 return f.fetchClient(input, init)
217 },
218 onError: async (error) => {
219 entered.resolve(error)
220 await repaired.promise
221 return { headers: { authorization: 'Bearer after' } }
222 },
223 })
224 const shape = new Shape(stream)
225 let refresh: Promise<void> | undefined
226 try {
227 expect(await shape.rows).toEqual([{ id: 1, label: 'initial' }])
228 expect(stream.isConnected()).toBe(true)
229 const handle = stream.shapeHandle
230 rejectNext = true
231 refresh = stream.forceDisconnectAndRefresh()
232 const error = await entered.promise
233 expect(error).toBeInstanceOf(FetchError)
234 expect((error as FetchError).status).toBe(401)
235 expect(stream.isConnected()).toBe(false)
236 expect(stream.error).toBe(error)
237 expect(shape.currentRows).toEqual([{ id: 1, label: 'initial' }])
238 f.publish('written during auth repair')
239 repaired.resolve()
240 await refresh
241 await expect
242 .poll(() => shape.currentRows)
243 .toEqual([{ id: 1, label: 'written during auth repair' }])
244 expect(stream.isConnected()).toBe(true)
245 expect(stream.error).toBeNull()
246 expect(stream.shapeHandle).toBe(handle)
247 expect(f.observers).toHaveLength(1)
248 expect(headers.at(-1)).toBe('Bearer after')
249 for (const request of f.requests) {
250 const url = new URL(request.url)
251 expect(url.pathname).toBe('/application/shapes')
252 expect(url.searchParams.get('tenant')).toBe('a+b')
253 if (url.searchParams.has('handle'))
254 expect(url.searchParams.get('handle')).toBe(handle)
255 }
256 } finally {
257 repaired.resolve()
258 abort.abort()
259 await refresh?.catch(() => {})
260 stream.unsubscribeAll()
261 f.handler.close()
262 await f.handler.drain()
263 }
264 })
265​
266 it.each(['network', 'fetch-error', 'http-500', 'http-429'] as const)(
267 'disconnects during native %s backoff and resumes the same history without the public error handler',
268 async (failure) => {
269 const f = fixture(objects, electricOnly, 100)
270 const abort = new AbortController()
271 const failed = deferred<void>()
272 const errors: Error[] = []
273 let failing = false
274 let failedAttempts = 0
275 const stream = new ShapeStream<{ id: number; label: string }>({
276 url: 'http://local/application/shapes',
277 liveSse,
278 signal: abort.signal,
279 backoffOptions: {
280 initialDelay: 1,
281 maxDelay: 5,
282 multiplier: 1,
283 onFailedAttempt() {
284 failedAttempts++
285 failed.resolve()
286 },
287 },
288 fetchClient: async (input, init) => {
289 if (failing) {
290 if (failure === 'network') throw new TypeError('Offline')
291 if (failure === 'fetch-error')
292 throw new FetchError(
293 500,
294 'Transient custom fetch failure',
295 undefined,
296 {},
297 String(input)
298 )
299 return new Response('Transient failure', {
300 status: failure === 'http-500' ? 500 : 429,
301 })
302 }
303 return f.fetchClient(input, init)
304 },
305 onError(error) {
306 errors.push(error)
307 },
308 })
309 const shape = new Shape(stream)
310 try {
311 expect(await shape.rows).toEqual([{ id: 1, label: 'initial' }])
312 expect(stream.isConnected()).toBe(true)
313 const handle = stream.shapeHandle
314 // Let the ongoing poll/SSE connection complete naturally. A forced
315 // refresh would itself disconnect and could mask a broken failure hook.
316 failing = true
317 await failed.promise
318 expect(stream.isConnected()).toBe(false)
319 expect(stream.error).toBeNull()
320 f.publish('queued during backoff')
321 failing = false
322 await expect
323 .poll(() => shape.currentRows)
324 .toEqual([{ id: 1, label: 'queued during backoff' }])
325 expect(stream.isConnected()).toBe(true)
326 expect(stream.error).toBeNull()
327 expect(failedAttempts).toBeGreaterThan(0)
328 expect(errors).toEqual([])
329 expect(stream.shapeHandle).toBe(handle)
330 expect(f.observers).toHaveLength(1)
331 } finally {
332 abort.abort()
333 stream.unsubscribeAll()
334 f.handler.close()
335 await f.handler.drain()
336 }
337 }
338 )
339​
340 it('advances lastSyncedAt on unchanged live tails without rotating or publishing row changes', async () => {
341 const f = fixture(objects, electricOnly, 100)
342 const abort = new AbortController()
343 const stream = new ShapeStream({
344 url: 'http://local/application/shapes',
345 liveSse,
346 signal: abort.signal,
347 fetchClient: f.fetchClient,
348 })
349 const shape = new Shape(stream)
350 let changes = 0
351 stream.subscribe((messages) => {
352 changes += messages.filter(isChangeMessage).length
353 })
354 try {
355 await shape.rows
356 const handle = stream.shapeHandle
357 const offset = stream.lastOffset
358 const synced = stream.lastSyncedAt()!
359 const before = changes
360 await expect.poll(() => stream.lastSyncedAt()! > synced).toBe(true)
361 expect(stream.isConnected()).toBe(true)
362 expect(stream.lastOffset).toBe(offset)
363 expect(stream.shapeHandle).toBe(handle)
364 expect(changes).toBe(before)
365 expect(shape.currentRows).toEqual([{ id: 1, label: 'initial' }])
366 expect(f.observers).toHaveLength(1)
367 } finally {
368 abort.abort()
369 stream.unsubscribeAll()
370 f.handler.close()
371 await f.handler.drain()
372 }
373 })
374​
375 it.each(['consumed', 'locked'] as const)(
376 'reports a %s custom-fetch response as a terminal public FetchError without retrying',
377 async (state) => {
378 const f = fixture(objects, electricOnly)
379 const abort = new AbortController()
380 const handled: Error[] = []
381 let attempts = 0
382 let reader: ReadableStreamDefaultReader<Uint8Array> | undefined
383 const stream = new ShapeStream({
384 url: 'http://local/application/shapes',
385 liveSse,
386 signal: abort.signal,
387 fetchClient: async (input, init) => {
388 attempts++
389 const response = await f.fetchClient(input, init)
390 if (state === 'consumed') await response.text()
391 else reader = response.body!.getReader()
392 return response
393 },
394 onError(error) {
395 handled.push(error)
396 },
397 })
398 try {
399 const failure = await new Promise<Error>((resolve) =>
400 stream.subscribe(() => {}, resolve)
401 )
402 expect(failure).toBeInstanceOf(FetchError)
403 expect(failure.message).toMatch(/body|Response/i)
404 expect(stream.error).toBe(failure)
405 expect(stream.isConnected()).toBe(false)
406 expect(handled).toEqual([failure])
407 expect(attempts).toBe(1)
408 } finally {
409 await reader?.cancel()
410 reader?.releaseLock()
411 abort.abort()
412 stream.unsubscribeAll()
413 f.handler.close()
414 await f.handler.drain()
415 }
416 }
417 )
418​
419 it('ignores unseen-key updates/deletes until an insert is observed in changes-only mode', async () => {
420 const f = fixture(objects, electricOnly)
421 const abort = new AbortController()
422 const stream = new ShapeStream<{ id: number; label: string }>({
423 url: 'http://local/application/shapes',
424 log: 'changes_only',
425 liveSse,
426 signal: abort.signal,
427 fetchClient: f.fetchClient,
428 })
429 const shape = new Shape(stream)
430 const operations: string[] = []
431 stream.subscribe((messages) => {
432 for (const message of messages)
433 if (isChangeMessage(message))
434 operations.push(message.headers.operation)
435 })
436 const deliver = async (
437 label: string,
438 operation: 'upsert' | 'remove' = 'upsert'
439 ) => {
440 const delivered = deferred<void>()
441 let txid: number
442 const unsubscribe = stream.subscribe((messages) => {
443 if (
444 messages.some(
445 (message) =>
446 isChangeMessage(message) &&
447 message.headers.txids?.includes(txid)
448 )
449 )
450 delivered.resolve()
451 })
452 try {
453 txid = f.publish(label, operation)
454 await delivered.promise
455 await expect.poll(() => shape.isUpToDate).toBe(true)
456 } finally {
457 unsubscribe()
458 }
459 }
460 try {
461 expect(await shape.rows).toEqual([])
462 await deliver('unseen update')
463 expect(shape.currentRows).toEqual([])
464 await deliver('', 'remove')
465 expect(shape.currentRows).toEqual([])
466 await deliver('observed insertion')
467 expect(shape.currentRows).toEqual([
468 { id: 1, label: 'observed insertion' },
469 ])
470 await deliver('observed update')
471 expect(shape.currentRows).toEqual([
472 { id: 1, label: 'observed update' },
473 ])
474 await deliver('', 'remove')
475 expect(shape.currentRows).toEqual([])
476 expect(operations).toEqual([
477 'update',
478 'delete',
479 'insert',
480 'update',
481 'delete',
482 ])
483 expect(f.observers).toHaveLength(1)
484 } finally {
485 abort.abort()
486 stream.unsubscribeAll()
487 f.handler.close()
488 await f.handler.drain()
489 }
490 })
491 })