Open History to see the last commit
1import { randomUUID } from 'node:crypto'
2import { tmpdir } from 'node:os'
3import { PowerSyncDatabase, Schema, Table, column } from '@powersync/node'
4import { createCollection, createLiveQueryCollection, eq } from '@tanstack/db'
5import pDefer from 'p-defer'
6import { describe, expect, it, onTestFinished, vi } from 'vitest'
7import { powerSyncCollectionOptions } from '../src'
8import { withTestCleanup } from './with-test-cleanup'
9
10const APP_SCHEMA = new Schema({
11 products: new Table({
12 name: column.text,
13 price: column.integer,
14 category: column.text,
15 }),
16})
17
18it.each([new Error(`primary mismatch`), undefined])(
19 `preserves a primary failure and attempts every resource cleanup (%s)`,
20 async (primary) => {
21 const secondary = new Error(`cleanup failure`)
22 const attempted: Array<string> = []
23 const outcome = await withTestCleanup(() => {
24 throw primary
25 }, [
26 () => {
27 attempted.push(`first`)
28 throw secondary
29 },
30 async () => {
31 attempted.push(`second`)
32 await Promise.reject(secondary)
33 },
34 () => {
35 attempted.push(`last`)
36 },
37 ]).then(
38 () => undefined,
39 (error: unknown) => error,
40 )
41 expect(attempted).toEqual([`first`, `second`, `last`])
42 expect(outcome).toBeInstanceOf(AggregateError)
43 expect((outcome as AggregateError).cause).toBe(primary)
44 expect((outcome as AggregateError).errors).toEqual([
45 primary,
46 secondary,
47 secondary,
48 ])
49 },
50)
51
52it(`preserves a lone failure and permits successful teardown`, async () => {
53 const sentinel = new Error(`only failure`)
54 await expect(
55 withTestCleanup(() => {
56 throw sentinel
57 }, [() => {}]),
58 ).rejects.toBe(sentinel)
59 await expect(
60 withTestCleanup(() => {}, [
61 () => {
62 throw sentinel
63 },
64 ]),
65 ).rejects.toBe(sentinel)
66 await expect(withTestCleanup(() => {}, [() => {}])).resolves.toBeUndefined()
67})
68
69describe(`Sync Streams`, () => {
70 async function createDatabase() {
71 const db = new PowerSyncDatabase({
72 database: {
73 dbFilename: `test-sync-streams-${randomUUID()}.sqlite`,
74 dbLocation: tmpdir(),
75 implementation: { type: `node:sqlite` },
76 },
77 schema: APP_SCHEMA,
78 })
79 onTestFinished(async () => {
80 await db.disconnectAndClear()
81 await new Promise((resolve) => setTimeout(resolve, 100))
82 await db.close()
83 })
84 await db.disconnectAndClear()
85 return db
86 }
87
88 async function createTestProducts(db: PowerSyncDatabase) {
89 await db.execute(`
90 INSERT INTO products (id, name, price, category)
91 VALUES
92 (uuid(), 'Product A', 50, 'electronics'),
93 (uuid(), 'Product B', 150, 'electronics'),
94 (uuid(), 'Product C', 25, 'clothing'),
95 (uuid(), 'Product D', 200, 'electronics'),
96 (uuid(), 'Product E', 75, 'clothing')
97 `)
98 }
99
100 it(`eager mode: should call onLoad on sync start and onUnload on cleanup`, async () => {
101 const db = await createDatabase()
102 await createTestProducts(db)
103
104 const onLoadMock = vi.fn()
105 const onUnloadMock = vi.fn()
106
107 const collection = createCollection(
108 powerSyncCollectionOptions({
109 database: db,
110 table: APP_SCHEMA.props.products,
111 onLoad: async () => {
112 await onLoadMock()
113
114 return () => {
115 onUnloadMock()
116 }
117 },
118 }),
119 )
120
121 try {
122 await collection.stateWhenReady()
123 expect(onLoadMock).toHaveBeenCalledOnce()
124 expect(onUnloadMock).not.toHaveBeenCalled()
125 await collection.cleanup()
126 expect(onUnloadMock).toHaveBeenCalledOnce()
127 } finally {
128 await collection.cleanup()
129 }
130 })
131
132 it(`eager mode: reports an initial load failure`, async () => {
133 const db = await createDatabase()
134 const initialError = new Error(`initial PowerSync load failed`)
135 const collection = createCollection(
136 powerSyncCollectionOptions({
137 database: db,
138 table: APP_SCHEMA.props.products,
139 onLoad: () => Promise.reject(initialError),
140 }),
141 )
142 try {
143 await expect(collection.preload()).rejects.toBe(initialError)
144 expect(collection.status).toBe(`error`)
145 } finally {
146 await collection.cleanup()
147 }
148 })
149
150 it(`eager mode: releases a load hook that resolves after cleanup`, async () => {
151 const db = await createDatabase()
152 const releaseLoad = pDefer<void>()
153 const loadStarted = pDefer<void>()
154 const cleanupLoad = vi.fn()
155 const createDiffTrigger = vi
156 .spyOn(db.triggers, `createDiffTrigger`)
157 .mockResolvedValue(async () => {})
158 const collection = createCollection(
159 powerSyncCollectionOptions({
160 database: db,
161 table: APP_SCHEMA.props.products,
162 onLoad: async () => {
163 loadStarted.resolve()
164 await releaseLoad.promise
165 return cleanupLoad
166 },
167 }),
168 )
169
170 const outcome = collection.preload().then(
171 () => ({ status: `fulfilled` as const }),
172 (error: unknown) => ({ status: `rejected` as const, error }),
173 )
174 try {
175 await loadStarted.promise
176 await collection.cleanup()
177 expect(await outcome).toMatchObject({
178 status: `rejected`,
179 error: { name: `AbortError` },
180 })
181 releaseLoad.resolve()
182 await vi.waitFor(() => expect(cleanupLoad).toHaveBeenCalledOnce())
183 expect(createDiffTrigger).not.toHaveBeenCalled()
184 } finally {
185 releaseLoad.resolve()
186 await collection.cleanup()
187 await outcome
188 await vi.waitFor(() => expect(cleanupLoad).toHaveBeenCalledOnce())
189 createDiffTrigger.mockRestore()
190 }
191 })
192
193 it(`on-demand mode: should call onLoadSubset/onUnloadSubset for each live query`, async () => {
194 const db = await createDatabase()
195 await createTestProducts(db)
196
197 const onLoadSubsetMock = vi.fn()
198 const onUnloadSubsetMock = vi.fn()
199 const unloadedRequests: Array<number> = []
200 let nextRequest = 0
201
202 const collection = createCollection(
203 powerSyncCollectionOptions({
204 database: db,
205 table: APP_SCHEMA.props.products,
206 syncMode: `on-demand`,
207 onLoadSubset: () => {
208 onLoadSubsetMock()
209 nextRequest += 1
210 const request = nextRequest
211
212 return () => {
213 onUnloadSubsetMock()
214 unloadedRequests.push(request)
215 }
216 },
217 }),
218 )
219 const cleanups: Array<() => Promise<void>> = []
220 try {
221 await collection.stateWhenReady()
222
223 // LQ1: electronics
224 const electronicsQuery = createLiveQueryCollection({
225 query: (q) =>
226 q
227 .from({ product: collection })
228 .where(({ product }) => eq(product.category, `electronics`))
229 .select(({ product }) => ({
230 id: product.id,
231 name: product.name,
232 price: product.price,
233 category: product.category,
234 })),
235 })
236 cleanups.push(() => electronicsQuery.cleanup())
237
238 await electronicsQuery.preload()
239
240 await vi.waitFor(
241 () => {
242 expect(electronicsQuery.size).toBe(3)
243 },
244 { timeout: 2000 },
245 )
246
247 expect(onLoadSubsetMock).toHaveBeenCalledTimes(1)
248 expect(onUnloadSubsetMock).not.toHaveBeenCalled()
249 expect(
250 electronicsQuery.toArray
251 .map(({ name, price, category }) => ({ name, price, category }))
252 .sort((a, b) => a.name!.localeCompare(b.name!)),
253 ).toEqual([
254 { name: `Product A`, price: 50, category: `electronics` },
255 { name: `Product B`, price: 150, category: `electronics` },
256 { name: `Product D`, price: 200, category: `electronics` },
257 ])
258
259 // LQ2: clothing
260 const clothingQuery = createLiveQueryCollection({
261 query: (q) =>
262 q
263 .from({ product: collection })
264 .where(({ product }) => eq(product.category, `clothing`))
265 .select(({ product }) => ({
266 id: product.id,
267 name: product.name,
268 price: product.price,
269 category: product.category,
270 })),
271 })
272 cleanups.push(() => clothingQuery.cleanup())
273
274 await clothingQuery.preload()
275
276 await vi.waitFor(
277 () => {
278 expect(clothingQuery.size).toBe(2)
279 },
280 { timeout: 2000 },
281 )
282
283 expect(onLoadSubsetMock).toHaveBeenCalledTimes(2)
284 expect(onUnloadSubsetMock).not.toHaveBeenCalled()
285 expect(
286 clothingQuery.toArray
287 .map(({ name, price, category }) => ({ name, price, category }))
288 .sort((a, b) => a.name!.localeCompare(b.name!)),
289 ).toEqual([
290 { name: `Product C`, price: 25, category: `clothing` },
291 { name: `Product E`, price: 75, category: `clothing` },
292 ])
293
294 // Cleanup LQ1 — should trigger first unload
295 await electronicsQuery.cleanup()
296
297 await vi.waitFor(
298 () => {
299 expect(onUnloadSubsetMock).toHaveBeenCalledTimes(1)
300 expect(unloadedRequests).toEqual([1])
301 },
302 { timeout: 2000 },
303 )
304
305 // Cleanup LQ2 — should trigger second unload
306 await clothingQuery.cleanup()
307
308 await vi.waitFor(
309 () => {
310 expect(onUnloadSubsetMock).toHaveBeenCalledTimes(2)
311 expect(unloadedRequests).toEqual([1, 2])
312 },
313 { timeout: 2000 },
314 )
315 } finally {
316 for (const cleanup of cleanups.reverse()) await cleanup()
317 await collection.cleanup()
318 }
319 })
320
321 it(`disposes a subset hook that resolves after collection cleanup`, async () => {
322 const db = await createDatabase()
323 await createTestProducts(db)
324 const hook = pDefer<() => void>()
325 const hookEntered = pDefer<void>()
326 const cleanupHook = vi.fn()
327 const createDiffTrigger = vi.spyOn(db.triggers, `createDiffTrigger`)
328
329 const collection = createCollection(
330 powerSyncCollectionOptions({
331 database: db,
332 table: APP_SCHEMA.props.products,
333 syncMode: `on-demand`,
334 onLoadSubset: () => {
335 hookEntered.resolve()
336 return hook.promise
337 },
338 }),
339 )
340 await collection.stateWhenReady().catch(async (error: unknown) => {
341 await collection.cleanup()
342 createDiffTrigger.mockRestore()
343 throw error
344 })
345 const query = createLiveQueryCollection({
346 query: (q) =>
347 q
348 .from({ product: collection })
349 .where(({ product }) => eq(product.category, `electronics`))
350 .select(({ product }) => ({
351 id: product.id,
352 name: product.name,
353 price: product.price,
354 category: product.category,
355 })),
356 })
357 const publications: Array<unknown> = []
358 const subscription = query.subscribeChanges((changes) => {
359 publications.push(
360 changes.map(({ type, key, value }) => ({
361 type,
362 key,
363 value: { ...value },
364 })),
365 )
366 })
367 const preload = query.preload().then(
368 () => ({ status: `fulfilled` as const }),
369 (error: unknown) => ({ status: `rejected` as const, error }),
370 )
371 const reports = vi.spyOn(console, `error`).mockImplementation(() => {})
372 const unexpected: Array<unknown> = []
373 const recordUnhandled = (error: unknown) => unexpected.push(error)
374 process.on(`unhandledRejection`, recordUnhandled)
375 const message =
376 `Source collection '${collection.id}' was manually cleaned up while live query '${query.id}' depends on it. ` +
377 `Live queries prevent automatic GC, so this was likely a manual cleanup() call.`
378 await withTestCleanup(async () => {
379 await hookEntered.promise
380 expect(cleanupHook).not.toHaveBeenCalled()
381 expect(createDiffTrigger).not.toHaveBeenCalled()
382 expect(query.status).toBe(`loading`)
383 await collection.cleanup()
384 const expected = { status: `rejected`, error: new Error(message) }
385 expect(await preload).toEqual(expected)
386 hook.resolve(cleanupHook)
387 await vi.waitFor(() => expect(cleanupHook).toHaveBeenCalledOnce())
388 expect(createDiffTrigger).not.toHaveBeenCalled()
389 expect(collection.status).toBe(`cleaned-up`)
390 expect(query.status).toBe(`error`)
391 expect(query.toArray).toEqual([])
392 expect(collection.size).toBe(0)
393 expect(publications.flat()).toEqual([])
394 expect(reports.mock.calls).toEqual([[`[Live Query Error] ${message}`]])
395 }, [
396 () => hook.resolve(cleanupHook),
397 () => subscription.unsubscribe(),
398 () => query.cleanup(),
399 () => collection.cleanup(),
400 () => preload,
401 () => vi.waitFor(() => expect(cleanupHook).toHaveBeenCalledOnce()),
402 () => new Promise((resolve) => setTimeout(resolve, 0)),
403 () =>
404 expect(reports.mock.calls).toEqual([[`[Live Query Error] ${message}`]]),
405 () => expect(unexpected).toEqual([]),
406 () => process.off(`unhandledRejection`, recordUnhandled),
407 () => reports.mockRestore(),
408 () => createDiffTrigger.mockRestore(),
409 ])
410 })
411})