Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import {
3 Shape,
4 ShapeStream,
5 createReactNativeRuntimeVisibilityAdapter,
6} from '../../packages/client/src/index.js'
7import { createShapeHandler } from '../../packages/server/src/handler.js'
8import { ObjectShapeLog } from '../../packages/server/src/object-log.js'
9import { FixtureObjectStore } from './support/object-store.js'
10import type {
11 RealtimeSource,
12 SourceObserver,
13} from '../../packages/server/src/realtime-source.js'
14
15type Visibility = 'active' | 'background' | 'inactive'
16const flush = () => new Promise<void>((resolve) => setImmediate(resolve))
17
18function fixture(object: boolean, electricOnly: boolean) {
19 const store = new FixtureObjectStore()
20 const subscriptions: { observer: SourceObserver; signal: AbortSignal }[] = []
21 let label = 'before'
22 const source: RealtimeSource = {
23 async subscribe(_, observer, signal) {
24 subscriptions.push({ observer, signal })
25 observer.event({
26 type: 'schema',
27 columns: [
28 { name: 'id', type_oid: 23, typmod: -1, codec: 'pg_text' },
29 { name: 'label', type_oid: 25, typmod: -1, codec: 'pg_text' },
30 ],
31 })
32 observer.event({
33 type: 'baseline',
34 rows: [{ row_key: 'a'.repeat(64), values: ['1', label] }],
35 mvcc: { xmin: '10', xmax: '11', xip: [] },
36 })
37 return { close() {} }
38 },
39 close() {},
40 }
41 let authorized = 0
42 const handler = createShapeHandler({
43 source,
44 longPollMs: 5_000,
45 createLog: object
46 ? ({ handle }) =>
47 new ObjectShapeLog({ store, prefix: handle, sealBytes: 1 })
48 : undefined,
49 async authorize() {
50 authorized++
51 return {
52 authorizationKey: 'mobile-user',
53 definition: {
54 namespace: 'public',
55 table: 'items',
56 primaryKey: ['id'],
57 projection: ['id', 'label'],
58 query: { sql: 'select id,label from public.items' },
59 schema: { id: { type: 'int4' }, label: { type: 'text' } },
60 },
61 }
62 },
63 })
64 const requests: { url: URL; signal: AbortSignal }[] = []
65 const fetchClient: typeof fetch = async (input, init) => {
66 const request = new Request(input, init)
67 requests.push({ url: new URL(request.url), signal: request.signal })
68 const response = await handler.fetch(request)
69 if (!electricOnly) return response
70 const headers = new Headers(response.headers)
71 for (const key of [...headers.keys()])
72 if (key.toLowerCase().startsWith('stream-')) headers.delete(key)
73 return new Response(response.body, { status: response.status, headers })
74 }
75 return {
76 handler,
77 requests,
78 fetchClient,
79 subscriptions,
80 store,
81 authorized: () => authorized,
82 publish(value: string) {
83 label = value
84 subscriptions.at(-1)!.observer.event({
85 type: 'publication',
86 changes: [
87 { op: 'upsert', row_key: 'a'.repeat(64), values: ['1', label] },
88 ],
89 txids: ['11'],
90 frontier: { lsn: '0/20' },
91 })
92 },
93 }
94}
95
96for (const object of [false, true])
97 for (const electricOnly of [false, true])
98 describe(`${object ? 'object' : 'memory'} log / ${electricOnly ? 'Electric' : 'native'} headers`, () => {
99 it.each([false, true])(
100 'pauses on AppState background, catches up at the same handle, and refetches after owner loss (SSE=%s)',
101 async (liveSse) => {
102 const f = fixture(object, electricOnly)
103 const abort = new AbortController()
104 const errors: unknown[] = []
105 let state: Visibility = 'active'
106 let listener: ((state: Visibility) => void) | undefined
107 const appState = {
108 get currentState() {
109 return state
110 },
111 addEventListener(
112 _: 'change',
113 callback: (state: Visibility) => void
114 ) {
115 listener = callback
116 return {
117 remove() {
118 listener = undefined
119 },
120 }
121 },
122 }
123 const setState = (next: Visibility) => {
124 state = next
125 listener?.(next)
126 }
127 const stream = new ShapeStream<{ id: number; label: string }>({
128 url: 'http://local/api/shapes',
129 params: { table: 'items' },
130 liveSse,
131 fetchClient: f.fetchClient,
132 signal: abort.signal,
133 runtimeVisibility:
134 createReactNativeRuntimeVisibilityAdapter(appState),
135 onError(error) {
136 errors.push(error)
137 },
138 })
139 const shape = new Shape(stream)
140 try {
141 expect(await shape.rows).toEqual([{ id: 1, label: 'before' }])
142 await expect
143 .poll(() => f.requests.at(-1)?.url.searchParams.get('live'))
144 .toBe('true')
145 const handle = stream.shapeHandle
146 const active = f.requests.at(-1)!
147 setState('background')
148 await expect.poll(() => active.signal.aborted).toBe(true)
149 await flush()
150 const pausedCount = f.requests.length
151 f.publish('while hidden')
152 await flush()
153 expect(f.requests).toHaveLength(pausedCount)
154 expect(shape.currentRows).toEqual([{ id: 1, label: 'before' }])
155 setState('active')
156 await expect
157 .poll(() => shape.currentRows)
158 .toEqual([{ id: 1, label: 'while hidden' }])
159 expect(stream.shapeHandle).toBe(handle)
160 const catchup = f.requests[pausedCount]
161 expect(catchup.url.searchParams.get('handle')).toBe(handle)
162 expect(catchup.url.searchParams.has('live')).toBe(false)
163 expect(f.subscriptions).toHaveLength(1)
164
165 setState('inactive')
166 await flush()
167 f.subscriptions[0].observer.error(
168 new Error('Owner continuity lost while backgrounded')
169 )
170 setState('active')
171 await expect.poll(() => stream.shapeHandle).not.toBe(handle)
172 await expect.poll(() => shape.isUpToDate).toBe(true)
173 expect(shape.currentRows).toEqual([
174 { id: 1, label: 'while hidden' },
175 ])
176 expect(f.subscriptions).toHaveLength(2)
177 expect(f.subscriptions[0].signal.aborted).toBe(true)
178 expect(
179 f.requests.every((r) => r.url.pathname === '/api/shapes')
180 ).toBe(true)
181 expect(f.authorized()).toBe(f.requests.length)
182 expect(errors).toEqual([])
183 if (object) expect(f.store.gets.length).toBeGreaterThan(0)
184 } finally {
185 abort.abort()
186 stream.unsubscribeAll()
187 f.handler.close()
188 await f.handler.drain()
189 expect(listener).toBeUndefined()
190 expect(f.subscriptions.every((s) => s.signal.aborted)).toBe(true)
191 expect(f.store.objects.size).toBe(0)
192 }
193 }
194 )
195
196 it.each([false, true])(
197 'recovers a hung native read after a clock gap with reason-less AbortController=%s',
198 async (dropReason) => {
199 // Only the wake detector clock/intervals are fake. HTTP bodies, log
200 // persistence, promise delivery and long-poll deadlines stay real.
201 vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'] })
202 const originalAbort = AbortController.prototype.abort
203 if (dropReason)
204 vi.spyOn(AbortController.prototype, 'abort').mockImplementation(
205 function (this: AbortController) {
206 originalAbort.call(this)
207 }
208 )
209 const f = fixture(object, electricOnly)
210 const abort = new AbortController()
211 const errors: unknown[] = []
212 const stream = new ShapeStream<{ id: number; label: string }>({
213 url: 'http://local/api/shapes',
214 params: { table: 'items' },
215 fetchClient: f.fetchClient,
216 signal: abort.signal,
217 onError(error) {
218 errors.push(error)
219 },
220 })
221 const shape = new Shape(stream)
222 try {
223 await shape.rows
224 await expect
225 .poll(() => f.requests.at(-1)?.url.searchParams.get('live'))
226 .toBe('true')
227 const handle = stream.shapeHandle
228 const hung = f.requests.at(-1)!
229 const start = f.requests.length
230 vi.setSystemTime(Date.now() + 10_000)
231 await vi.advanceTimersByTimeAsync(2_001)
232 await expect.poll(() => hung.signal.aborted).toBe(true)
233 await expect.poll(() => f.requests.length).toBeGreaterThan(start)
234 expect(f.requests[start].url.searchParams.has('live')).toBe(false)
235 f.publish('after wake')
236 await expect
237 .poll(() => shape.currentRows)
238 .toEqual([{ id: 1, label: 'after wake' }])
239 expect(stream.shapeHandle).toBe(handle)
240 expect(f.subscriptions).toHaveLength(1)
241 expect(errors).toEqual([])
242 } finally {
243 abort.abort()
244 stream.unsubscribeAll()
245 f.handler.close()
246 await f.handler.drain()
247 expect(vi.getTimerCount()).toBe(0)
248 vi.useRealTimers()
249 vi.restoreAllMocks()
250 }
251 }
252 )
253 })