Open History to see the last commit
1import { randomUUID } from 'node:crypto'
2import { tmpdir } from 'node:os'
3import { LogLevels } from '@powersync/common'
4import { PowerSyncDatabase, Schema, Table, column } from '@powersync/node'
5import { createCollection, createLiveQueryCollection, eq } from '@tanstack/db'
6import pDefer from 'p-defer'
7import { describe, expect, it, onTestFinished, vi } from 'vitest'
8import { powerSyncCollectionOptions } from '../src'
9import { withTestCleanup } from './with-test-cleanup'
10
11const APP_SCHEMA = new Schema({
12 products: new Table({
13 name: column.text,
14 price: column.integer,
15 category: column.text,
16 }),
17})
18
19it.each([new Error(`primary mismatch`), undefined])(
20 `preserves a primary failure and attempts every resource cleanup (%s)`,
21 async (primary) => {
22 const secondary = new Error(`cleanup failure`)
23 const attempted: Array<string> = []
24 const outcome = await withTestCleanup(() => {
25 throw primary
26 }, [
27 () => {
28 attempted.push(`first`)
29 throw secondary
30 },
31 async () => {
32 attempted.push(`second`)
33 await Promise.reject(secondary)
34 },
35 () => {
36 attempted.push(`last`)
37 },
38 ]).then(
39 () => undefined,
40 (error: unknown) => error,
41 )
42 expect(attempted).toEqual([`first`, `second`, `last`])
43 expect(outcome).toBeInstanceOf(AggregateError)
44 expect((outcome as AggregateError).cause).toBe(primary)
45 expect((outcome as AggregateError).errors).toEqual([
46 primary,
47 secondary,
48 secondary,
49 ])
50 },
51)
52
53it(`preserves a lone failure and permits successful teardown`, async () => {
54 const sentinel = new Error(`only failure`)
55 await expect(
56 withTestCleanup(() => {
57 throw sentinel
58 }, [() => {}]),
59 ).rejects.toBe(sentinel)
60 await expect(
61 withTestCleanup(() => {}, [
62 () => {
63 throw sentinel
64 },
65 ]),
66 ).rejects.toBe(sentinel)
67 await expect(withTestCleanup(() => {}, [() => {}])).resolves.toBeUndefined()
68})
69
70describe(`Sync Streams`, () => {
71 async function createDatabase() {
72 const db = new PowerSyncDatabase({
73 database: {
74 dbFilename: `test-sync-streams-${randomUUID()}.sqlite`,
75 dbLocation: tmpdir(),
76 implementation: { type: `node:sqlite` },
77 },
78 schema: APP_SCHEMA,
79 })
80 onTestFinished(async () => {
81 await db.disconnectAndClear()
82 await new Promise((resolve) => setTimeout(resolve, 100))
83 await db.close()
84 })
85 await db.disconnectAndClear()
86 return db
87 }
88
89 async function createTestProducts(db: PowerSyncDatabase) {
90 await db.execute(`
91 INSERT INTO products (id, name, price, category)
92 VALUES
93 (uuid(), 'Product A', 50, 'electronics'),
94 (uuid(), 'Product B', 150, 'electronics'),
95 (uuid(), 'Product C', 25, 'clothing'),
96 (uuid(), 'Product D', 200, 'electronics'),
97 (uuid(), 'Product E', 75, 'clothing')
98 `)
99 }
100
101 it(`eager mode: should call onLoad on sync start and onUnload on cleanup`, async () => {
102 const db = await createDatabase()
103 await createTestProducts(db)
104
105 const onLoadMock = vi.fn()
106 const onUnloadMock = vi.fn()
107 const unloaded: Array<string> = []
108
109 const collection = createCollection(
110 powerSyncCollectionOptions({
111 database: db,
112 table: APP_SCHEMA.props.products,
113 onLoad: async () => {
114 await onLoadMock()
115
116 return () => {
117 onUnloadMock()
118 return unloaded.push(`done`)
119 }
120 },
121 }),
122 )
123
124 try {
125 await collection.stateWhenReady()
126 expect(onLoadMock).toHaveBeenCalledOnce()
127 expect(onUnloadMock).not.toHaveBeenCalled()
128 await collection.cleanup()
129 expect(onUnloadMock).toHaveBeenCalledOnce()
130 expect(unloaded).toEqual([`done`])
131 } finally {
132 await collection.cleanup()
133 }
134 })
135
136 it.each([`fulfill`, `reject`] as const)(
137 `eager mode: awaits asynchronous hook cleanup: %s`,
138 async (outcome) => {
139 const db = await createDatabase()
140 const cleanupGate = pDefer<void>()
141 const cleanupError = new Error(`eager hook cleanup failed`)
142 const cleanupHook = vi.fn(() =>
143 cleanupGate.promise.then(() => {
144 if (outcome === `reject`) throw cleanupError
145 }),
146 )
147 const collection = createCollection(
148 powerSyncCollectionOptions({
149 database: db,
150 table: APP_SCHEMA.props.products,
151 onLoad: () => cleanupHook,
152 }),
153 )
154
155 try {
156 await collection.stateWhenReady()
157 let cleanupSettled = false
158 const cleanupOutcome = collection.cleanup().then(
159 () => {
160 cleanupSettled = true
161 return { status: `fulfilled` as const }
162 },
163 (error: unknown) => {
164 cleanupSettled = true
165 return { status: `rejected` as const, error }
166 },
167 )
168 await Promise.resolve()
169
170 expect(cleanupHook).toHaveBeenCalledOnce()
171 expect(cleanupSettled).toBe(false)
172 expect(collection.status).toBe(`ready`)
173
174 cleanupGate.resolve()
175 const cleanupResult = await cleanupOutcome
176 if (outcome === `reject`) {
177 expect(cleanupResult).toMatchObject({
178 status: `rejected`,
179 error: { name: `SyncCleanupError`, cause: cleanupError },
180 })
181 } else {
182 expect(cleanupResult).toEqual({ status: `fulfilled` })
183 }
184 expect(collection.status).toBe(`cleaned-up`)
185 } finally {
186 cleanupGate.resolve()
187 await collection.cleanup()
188 }
189 },
190 )
191
192 it.each([`fulfill`, `reject`] as const)(
193 `eager mode: awaits asynchronous trigger disposal: %s`,
194 async (outcome) => {
195 const db = await createDatabase()
196 const disposeGate = pDefer<void>()
197 const disposeError = new Error(`eager trigger disposal failed`)
198 const disposeTracking = vi.fn(() =>
199 disposeGate.promise.then(() => {
200 if (outcome === `reject`) throw disposeError
201 }),
202 )
203 vi.spyOn(db.triggers, `createDiffTrigger`).mockResolvedValue(
204 disposeTracking,
205 )
206 const collection = createCollection(
207 powerSyncCollectionOptions({
208 database: db,
209 table: APP_SCHEMA.props.products,
210 }),
211 )
212 const unhandled: Array<unknown> = []
213 const onUnhandled = (error: unknown) => unhandled.push(error)
214 process.on(`unhandledRejection`, onUnhandled)
215
216 try {
217 await collection.stateWhenReady()
218 let cleanupSettled = false
219 const cleanupOutcome = collection.cleanup().then(
220 () => {
221 cleanupSettled = true
222 return { status: `fulfilled` as const }
223 },
224 (error: unknown) => {
225 cleanupSettled = true
226 return { status: `rejected` as const, error }
227 },
228 )
229
230 // Abort and local disposer ownership transfer remain same-stack.
231 expect(disposeTracking).toHaveBeenCalledOnce()
232 await new Promise((resolve) => setImmediate(resolve))
233 expect(cleanupSettled).toBe(false)
234 expect(collection.status).toBe(`ready`)
235
236 disposeGate.resolve()
237 const cleanupResult = await cleanupOutcome
238 if (outcome === `reject`) {
239 expect(cleanupResult).toMatchObject({
240 status: `rejected`,
241 error: { name: `SyncCleanupError`, cause: disposeError },
242 })
243 } else {
244 expect(cleanupResult).toEqual({ status: `fulfilled` })
245 }
246 await new Promise((resolve) => setImmediate(resolve))
247 expect(unhandled).toEqual([])
248 expect(collection.status).toBe(`cleaned-up`)
249 expect(disposeTracking).toHaveBeenCalledOnce()
250 } finally {
251 disposeGate.resolve()
252 process.removeListener(`unhandledRejection`, onUnhandled)
253 await collection.cleanup()
254 }
255 },
256 )
257
258 it.each([`hook-first`, `disposal-first`] as const)(
259 `eager mode: preserves hook and trigger cleanup failures: %s`,
260 async (firstFailure) => {
261 const db = await createDatabase()
262 const hookGate = pDefer<void>()
263 const disposalGate = pDefer<void>()
264 const hookFailureReached = pDefer<void>()
265 const disposalFailureReached = pDefer<void>()
266 const hookError = new Error(`eager hook cleanup failed exactly`)
267 const disposalError = new Error(`eager trigger disposal failed exactly`)
268 const disposeTracking = vi.fn(async () => {
269 await disposalGate.promise
270 disposalFailureReached.resolve()
271 throw disposalError
272 })
273 vi.spyOn(db.triggers, `createDiffTrigger`).mockResolvedValue(
274 disposeTracking,
275 )
276 const cleanupHook = vi.fn(async () => {
277 await hookGate.promise
278 hookFailureReached.resolve()
279 throw hookError
280 })
281 const collection = createCollection(
282 powerSyncCollectionOptions({
283 database: db,
284 table: APP_SCHEMA.props.products,
285 onLoad: () => cleanupHook,
286 }),
287 )
288
289 try {
290 await collection.stateWhenReady()
291 const cleanupOutcome = collection.cleanup().then(
292 () => ({ status: `fulfilled` as const }),
293 (error: unknown) => ({ status: `rejected` as const, error }),
294 )
295
296 if (firstFailure === `hook-first`) {
297 hookGate.resolve()
298 await hookFailureReached.promise
299 disposalGate.resolve()
300 } else {
301 disposalGate.resolve()
302 await disposalFailureReached.promise
303 hookGate.resolve()
304 }
305
306 const outcome = await cleanupOutcome
307 expect(outcome.status).toBe(`rejected`)
308 if (outcome.status !== `rejected`) {
309 throw new Error(`expected eager cleanup to reject`)
310 }
311 expect(outcome.error).toMatchObject({ name: `SyncCleanupError` })
312 const syncCleanupError = outcome.error as { cause?: unknown }
313 expect(syncCleanupError.cause).toBeInstanceOf(AggregateError)
314 const aggregate = syncCleanupError.cause as AggregateError
315 expect(aggregate.cause).toBe(disposalError)
316 expect(aggregate.errors).toEqual([disposalError, hookError])
317 expect(disposeTracking).toHaveBeenCalledOnce()
318 expect(cleanupHook).toHaveBeenCalledOnce()
319 } finally {
320 hookGate.resolve()
321 disposalGate.resolve()
322 await collection.cleanup()
323 }
324 },
325 )
326
327 it(`eager mode: reports an initial load failure`, async () => {
328 const db = await createDatabase()
329 const initialError = new Error(`initial PowerSync load failed`)
330 const collection = createCollection(
331 powerSyncCollectionOptions({
332 database: db,
333 table: APP_SCHEMA.props.products,
334 onLoad: () => Promise.reject(initialError),
335 }),
336 )
337 try {
338 await expect(collection.preload()).rejects.toBe(initialError)
339 expect(collection.status).toBe(`error`)
340 } finally {
341 await collection.cleanup()
342 }
343 })
344
345 it(`eager mode: releases a load hook that resolves after cleanup`, async () => {
346 const db = await createDatabase()
347 const releaseLoad = pDefer<void>()
348 const releaseCleanup = pDefer<void>()
349 const loadStarted = pDefer<void>()
350 const cleanupLoad = vi.fn(() => releaseCleanup.promise)
351 const createDiffTrigger = vi
352 .spyOn(db.triggers, `createDiffTrigger`)
353 .mockResolvedValue(async () => {})
354 const collection = createCollection(
355 powerSyncCollectionOptions({
356 database: db,
357 table: APP_SCHEMA.props.products,
358 onLoad: async () => {
359 loadStarted.resolve()
360 await releaseLoad.promise
361 return cleanupLoad
362 },
363 }),
364 )
365
366 const outcome = collection.preload().then(
367 () => ({ status: `fulfilled` as const }),
368 (error: unknown) => ({ status: `rejected` as const, error }),
369 )
370 let cleanupSettled = false
371 try {
372 await loadStarted.promise
373 const cleanup = collection.cleanup().then(() => {
374 cleanupSettled = true
375 })
376 await Promise.resolve()
377 expect(cleanupSettled).toBe(false)
378 expect(await outcome).toMatchObject({
379 status: `rejected`,
380 error: { name: `AbortError` },
381 })
382 releaseLoad.resolve()
383 await vi.waitFor(() => expect(cleanupLoad).toHaveBeenCalledOnce())
384 expect(cleanupSettled).toBe(false)
385 expect(createDiffTrigger).not.toHaveBeenCalled()
386 releaseCleanup.resolve()
387 await cleanup
388 expect(cleanupSettled).toBe(true)
389 } finally {
390 releaseLoad.resolve()
391 releaseCleanup.resolve()
392 await collection.cleanup()
393 await outcome
394 await vi.waitFor(() => expect(cleanupLoad).toHaveBeenCalledOnce())
395 createDiffTrigger.mockRestore()
396 }
397 })
398
399 it(`on-demand mode: should call onLoadSubset/onUnloadSubset for each live query`, async () => {
400 const db = await createDatabase()
401 await createTestProducts(db)
402
403 const onLoadSubsetMock = vi.fn()
404 const onUnloadSubsetMock = vi.fn()
405 const unloadedRequests: Array<number> = []
406 let nextRequest = 0
407
408 const collection = createCollection(
409 powerSyncCollectionOptions({
410 database: db,
411 table: APP_SCHEMA.props.products,
412 syncMode: `on-demand`,
413 onLoadSubset: () => {
414 onLoadSubsetMock()
415 nextRequest += 1
416 const request = nextRequest
417
418 return () => {
419 onUnloadSubsetMock()
420 unloadedRequests.push(request)
421 }
422 },
423 }),
424 )
425 const cleanups: Array<() => Promise<void>> = []
426 try {
427 await collection.stateWhenReady()
428
429 // LQ1: electronics
430 const electronicsQuery = createLiveQueryCollection({
431 query: (q) =>
432 q
433 .from({ product: collection })
434 .where(({ product }) => eq(product.category, `electronics`))
435 .select(({ product }) => ({
436 id: product.id,
437 name: product.name,
438 price: product.price,
439 category: product.category,
440 })),
441 })
442 cleanups.push(() => electronicsQuery.cleanup())
443
444 await electronicsQuery.preload()
445
446 await vi.waitFor(
447 () => {
448 expect(electronicsQuery.size).toBe(3)
449 },
450 { timeout: 2000 },
451 )
452
453 expect(onLoadSubsetMock).toHaveBeenCalledTimes(1)
454 expect(onUnloadSubsetMock).not.toHaveBeenCalled()
455 expect(
456 electronicsQuery.toArray
457 .map(({ name, price, category }) => ({ name, price, category }))
458 .sort((a, b) => a.name!.localeCompare(b.name!)),
459 ).toEqual([
460 { name: `Product A`, price: 50, category: `electronics` },
461 { name: `Product B`, price: 150, category: `electronics` },
462 { name: `Product D`, price: 200, category: `electronics` },
463 ])
464
465 // LQ2: clothing
466 const clothingQuery = createLiveQueryCollection({
467 query: (q) =>
468 q
469 .from({ product: collection })
470 .where(({ product }) => eq(product.category, `clothing`))
471 .select(({ product }) => ({
472 id: product.id,
473 name: product.name,
474 price: product.price,
475 category: product.category,
476 })),
477 })
478 cleanups.push(() => clothingQuery.cleanup())
479
480 await clothingQuery.preload()
481
482 await vi.waitFor(
483 () => {
484 expect(clothingQuery.size).toBe(2)
485 },
486 { timeout: 2000 },
487 )
488
489 expect(onLoadSubsetMock).toHaveBeenCalledTimes(2)
490 expect(onUnloadSubsetMock).not.toHaveBeenCalled()
491 expect(
492 clothingQuery.toArray
493 .map(({ name, price, category }) => ({ name, price, category }))
494 .sort((a, b) => a.name!.localeCompare(b.name!)),
495 ).toEqual([
496 { name: `Product C`, price: 25, category: `clothing` },
497 { name: `Product E`, price: 75, category: `clothing` },
498 ])
499
500 // Cleanup LQ1 — should trigger first unload
501 await electronicsQuery.cleanup()
502
503 await vi.waitFor(
504 () => {
505 expect(onUnloadSubsetMock).toHaveBeenCalledTimes(1)
506 expect(unloadedRequests).toEqual([1])
507 },
508 { timeout: 2000 },
509 )
510
511 // Cleanup LQ2 — should trigger second unload
512 await clothingQuery.cleanup()
513
514 await vi.waitFor(
515 () => {
516 expect(onUnloadSubsetMock).toHaveBeenCalledTimes(2)
517 expect(unloadedRequests).toEqual([1, 2])
518 },
519 { timeout: 2000 },
520 )
521 } finally {
522 for (const cleanup of cleanups.reverse()) await cleanup()
523 await collection.cleanup()
524 }
525 })
526
527 it.each([`fulfill`, `reject`, `throw`] as const)(
528 `on-demand mode: settles acquired hook cleanup with collection cleanup: %s`,
529 async (outcome) => {
530 const db = await createDatabase()
531 await createTestProducts(db)
532 const cleanupGate = pDefer<void>()
533 const cleanupError = new Error(`on-demand hook cleanup failed`)
534 const cleanupHook = vi.fn(() => {
535 if (outcome === `throw`) throw cleanupError
536 return cleanupGate.promise.then(() => {
537 if (outcome === `reject`) throw cleanupError
538 })
539 })
540 const collection = createCollection(
541 powerSyncCollectionOptions({
542 database: db,
543 table: APP_SCHEMA.props.products,
544 syncMode: `on-demand`,
545 onLoadSubset: () => cleanupHook,
546 }),
547 )
548 const query = createLiveQueryCollection({
549 query: (q) =>
550 q
551 .from({ product: collection })
552 .where(({ product }) => eq(product.category, `electronics`)),
553 })
554 const unhandled: Array<unknown> = []
555 const onUnhandled = (error: unknown) => unhandled.push(error)
556 process.on(`unhandledRejection`, onUnhandled)
557
558 try {
559 await query.preload()
560 let cleanupSettled = false
561 const cleanupOutcome = collection.cleanup().then(
562 () => {
563 cleanupSettled = true
564 return { status: `fulfilled` as const }
565 },
566 (error: unknown) => {
567 cleanupSettled = true
568 return { status: `rejected` as const, error }
569 },
570 )
571
572 expect(cleanupHook).toHaveBeenCalledOnce()
573 if (outcome !== `throw`) {
574 await new Promise((resolve) => setImmediate(resolve))
575 const settledBeforeRelease = cleanupSettled
576 cleanupGate.resolve()
577 const cleanupResult = await cleanupOutcome
578 expect(settledBeforeRelease).toBe(false)
579 if (outcome === `reject`) {
580 expect(cleanupResult).toMatchObject({
581 status: `rejected`,
582 error: { name: `SyncCleanupError`, cause: cleanupError },
583 })
584 } else {
585 expect(cleanupResult).toEqual({ status: `fulfilled` })
586 }
587 } else {
588 expect(await cleanupOutcome).toMatchObject({
589 status: `rejected`,
590 error: { name: `SyncCleanupError`, cause: cleanupError },
591 })
592 }
593 await new Promise((resolve) => setImmediate(resolve))
594 expect(unhandled).toEqual([])
595 expect(collection.status).toBe(`cleaned-up`)
596 expect(cleanupHook).toHaveBeenCalledOnce()
597 } finally {
598 cleanupGate.resolve()
599 process.removeListener(`unhandledRejection`, onUnhandled)
600 await query.cleanup()
601 await collection.cleanup()
602 }
603 },
604 )
605
606 it.each([`fulfill`, `reject`] as const)(
607 `on-demand mode: waits for hook cleanup started by subset release: %s`,
608 async (outcome) => {
609 const db = await createDatabase()
610 await createTestProducts(db)
611 const cleanupGate = pDefer<void>()
612 const cleanupError = new Error(`released subset cleanup failed`)
613 const cleanupHook = vi.fn(() =>
614 cleanupGate.promise.then(() => {
615 if (outcome === `reject`) throw cleanupError
616 }),
617 )
618 const collection = createCollection(
619 powerSyncCollectionOptions({
620 database: db,
621 table: APP_SCHEMA.props.products,
622 syncMode: `on-demand`,
623 onLoadSubset: () => cleanupHook,
624 }),
625 )
626 const query = createLiveQueryCollection({
627 query: (q) =>
628 q
629 .from({ product: collection })
630 .where(({ product }) => eq(product.category, `electronics`)),
631 })
632
633 try {
634 await query.preload()
635 await query.cleanup()
636 expect(cleanupHook).toHaveBeenCalledOnce()
637
638 let cleanupSettled = false
639 const cleanupOutcome = collection.cleanup().then(
640 () => {
641 cleanupSettled = true
642 return { status: `fulfilled` as const }
643 },
644 (error: unknown) => {
645 cleanupSettled = true
646 return { status: `rejected` as const, error }
647 },
648 )
649 await new Promise((resolve) => setImmediate(resolve))
650 expect(cleanupSettled).toBe(false)
651
652 cleanupGate.resolve()
653 const cleanupResult = await cleanupOutcome
654 if (outcome === `reject`) {
655 expect(cleanupResult).toMatchObject({
656 status: `rejected`,
657 error: { name: `SyncCleanupError`, cause: cleanupError },
658 })
659 } else {
660 expect(cleanupResult).toEqual({ status: `fulfilled` })
661 }
662 } finally {
663 cleanupGate.resolve()
664 await query.cleanup()
665 await collection.cleanup()
666 }
667 },
668 )
669
670 it(`on-demand mode: classifies acquired cleanup by its runtime promise shape`, async () => {
671 const db = await createDatabase()
672 await createTestProducts(db)
673 const hiddenPromiseGate = pDefer<void>()
674 const calls: Array<string> = []
675 const incidentalCleanup = () => calls.push(`incidental`)
676 const hiddenPromiseCleanup: () => void = async () => {
677 calls.push(`hidden-promise`)
678 await hiddenPromiseGate.promise
679 }
680 let acquisition = 0
681 const collection = createCollection(
682 powerSyncCollectionOptions({
683 database: db,
684 table: APP_SCHEMA.props.products,
685 syncMode: `on-demand`,
686 onLoadSubset: () =>
687 acquisition++ === 0 ? incidentalCleanup : hiddenPromiseCleanup,
688 }),
689 )
690 const categoryQuery = (category: string) =>
691 createLiveQueryCollection({
692 query: (q) =>
693 q
694 .from({ product: collection })
695 .where(({ product }) => eq(product.category, category)),
696 })
697 const firstQuery = categoryQuery(`electronics`)
698 const secondQuery = categoryQuery(`clothing`)
699
700 try {
701 await firstQuery.preload()
702 await secondQuery.preload()
703 let settled = false
704 const cleanup = collection.cleanup().then(() => {
705 settled = true
706 })
707
708 expect(calls).toEqual([`incidental`, `hidden-promise`])
709 await new Promise((resolve) => setImmediate(resolve))
710 expect(settled).toBe(false)
711
712 hiddenPromiseGate.resolve()
713 await cleanup
714 expect(settled).toBe(true)
715 } finally {
716 hiddenPromiseGate.resolve()
717 await firstQuery.cleanup()
718 await secondQuery.cleanup()
719 await collection.cleanup()
720 }
721 })
722
723 it(`on-demand mode: awaits every acquired hook once during reentrant cleanup`, async () => {
724 const db = await createDatabase()
725 await createTestProducts(db)
726 const firstGate = pDefer<void>()
727 const secondGate = pDefer<void>()
728 let nestedCleanup: Promise<void> | undefined
729 const firstCleanup = vi.fn(() => {
730 nestedCleanup = collection.cleanup()
731 return firstGate.promise
732 })
733 const secondCleanup = vi.fn(() => secondGate.promise)
734 let acquisition = 0
735 const collection = createCollection(
736 powerSyncCollectionOptions({
737 database: db,
738 table: APP_SCHEMA.props.products,
739 syncMode: `on-demand`,
740 onLoadSubset: () =>
741 acquisition++ === 0 ? firstCleanup : secondCleanup,
742 }),
743 )
744 const categoryQuery = (category: string) =>
745 createLiveQueryCollection({
746 query: (q) =>
747 q
748 .from({ product: collection })
749 .where(({ product }) => eq(product.category, category)),
750 })
751 const firstQuery = categoryQuery(`electronics`)
752 const secondQuery = categoryQuery(`clothing`)
753
754 try {
755 await firstQuery.preload()
756 await secondQuery.preload()
757 const cleanup = collection.cleanup()
758
759 expect(nestedCleanup).toBe(cleanup)
760 expect(firstCleanup).toHaveBeenCalledOnce()
761 expect(secondCleanup).toHaveBeenCalledOnce()
762 let settled = false
763 void cleanup.then(() => {
764 settled = true
765 })
766 secondGate.resolve()
767 await new Promise((resolve) => setImmediate(resolve))
768 expect(settled).toBe(false)
769
770 firstGate.resolve()
771 await cleanup
772 expect(settled).toBe(true)
773 expect(firstCleanup).toHaveBeenCalledOnce()
774 expect(secondCleanup).toHaveBeenCalledOnce()
775 } finally {
776 firstGate.resolve()
777 secondGate.resolve()
778 await firstQuery.cleanup()
779 await secondQuery.cleanup()
780 await collection.cleanup()
781 }
782 })
783
784 it.each([`first-hook-first`, `second-hook-first`] as const)(
785 `on-demand mode: preserves every acquired hook cleanup failure: %s`,
786 async (settlementOrder) => {
787 const db = await createDatabase()
788 await createTestProducts(db)
789 const firstGate = pDefer<void>()
790 const secondGate = pDefer<void>()
791 const firstFailureReached = pDefer<void>()
792 const secondFailureReached = pDefer<void>()
793 const firstError = new Error(`first acquired hook cleanup failed`)
794 const secondError = new Error(`second acquired hook cleanup failed`)
795 const firstCleanup = vi.fn(async () => {
796 await firstGate.promise
797 firstFailureReached.resolve()
798 throw firstError
799 })
800 const secondCleanup = vi.fn(async () => {
801 await secondGate.promise
802 secondFailureReached.resolve()
803 throw secondError
804 })
805 let acquisition = 0
806 const collection = createCollection(
807 powerSyncCollectionOptions({
808 database: db,
809 table: APP_SCHEMA.props.products,
810 syncMode: `on-demand`,
811 onLoadSubset: () =>
812 acquisition++ === 0 ? firstCleanup : secondCleanup,
813 }),
814 )
815 const categoryQuery = (category: string) =>
816 createLiveQueryCollection({
817 query: (q) =>
818 q
819 .from({ product: collection })
820 .where(({ product }) => eq(product.category, category)),
821 })
822 const firstQuery = categoryQuery(`electronics`)
823 const secondQuery = categoryQuery(`clothing`)
824
825 try {
826 await firstQuery.preload()
827 await secondQuery.preload()
828 const cleanupOutcome = collection.cleanup().then(
829 () => ({ status: `fulfilled` as const }),
830 (error: unknown) => ({ status: `rejected` as const, error }),
831 )
832
833 if (settlementOrder === `first-hook-first`) {
834 firstGate.resolve()
835 await firstFailureReached.promise
836 secondGate.resolve()
837 } else {
838 secondGate.resolve()
839 await secondFailureReached.promise
840 firstGate.resolve()
841 }
842
843 const outcome = await cleanupOutcome
844 expect(outcome.status).toBe(`rejected`)
845 if (outcome.status !== `rejected`) {
846 throw new Error(`expected on-demand cleanup to reject`)
847 }
848 expect(outcome.error).toMatchObject({ name: `SyncCleanupError` })
849 const syncCleanupError = outcome.error as { cause?: unknown }
850 expect(syncCleanupError.cause).toBeInstanceOf(AggregateError)
851 const aggregate = syncCleanupError.cause as AggregateError
852 expect(aggregate.cause).toBe(firstError)
853 expect(aggregate.errors).toEqual([firstError, secondError])
854 expect(firstCleanup).toHaveBeenCalledOnce()
855 expect(secondCleanup).toHaveBeenCalledOnce()
856 } finally {
857 firstGate.resolve()
858 secondGate.resolve()
859 await firstQuery.cleanup()
860 await secondQuery.cleanup()
861 await collection.cleanup()
862 }
863 },
864 )
865
866 it.each([`fulfill`, `reject`, `throw`] as const)(
867 `disposes a subset hook that resolves after collection cleanup: %s`,
868 async (outcome) => {
869 const db = await createDatabase()
870 await createTestProducts(db)
871 const hook = pDefer<() => void>()
872 const hookEntered = pDefer<void>()
873 const cleanupFailure = new Error(`late subset cleanup failed`)
874 const cleanupHook = vi.fn(() => {
875 if (outcome === `throw`) throw cleanupFailure
876 if (outcome === `reject`) return Promise.reject(cleanupFailure)
877 return undefined
878 })
879 const createDiffTrigger = vi.spyOn(db.triggers, `createDiffTrigger`)
880 const cleanupReports = vi.spyOn(db.logger, `log`)
881
882 const collection = createCollection(
883 powerSyncCollectionOptions({
884 database: db,
885 table: APP_SCHEMA.props.products,
886 syncMode: `on-demand`,
887 onLoadSubset: () => {
888 hookEntered.resolve()
889 return hook.promise
890 },
891 }),
892 )
893 await collection.stateWhenReady().catch(async (error: unknown) => {
894 await collection.cleanup()
895 createDiffTrigger.mockRestore()
896 throw error
897 })
898 const query = createLiveQueryCollection({
899 query: (q) =>
900 q
901 .from({ product: collection })
902 .where(({ product }) => eq(product.category, `electronics`))
903 .select(({ product }) => ({
904 id: product.id,
905 name: product.name,
906 price: product.price,
907 category: product.category,
908 })),
909 })
910 const publications: Array<unknown> = []
911 const subscription = query.subscribeChanges((changes) => {
912 publications.push(
913 changes.map(({ type, key, value }) => ({
914 type,
915 key,
916 value: { ...value },
917 })),
918 )
919 })
920 const preload = query.preload().then(
921 () => ({ status: `fulfilled` as const }),
922 (error: unknown) => ({ status: `rejected` as const, error }),
923 )
924 const reports = vi.spyOn(console, `error`).mockImplementation(() => {})
925 const unexpected: Array<unknown> = []
926 const recordUnhandled = (error: unknown) => unexpected.push(error)
927 process.on(`unhandledRejection`, recordUnhandled)
928 const message =
929 `Source collection '${collection.id}' was manually cleaned up while live query '${query.id}' depends on it. ` +
930 `Live queries prevent automatic GC, so this was likely a manual cleanup() call.`
931 const expectedReports: Array<Array<unknown>> = [
932 [`[Live Query Error] ${message}`],
933 ]
934 if (outcome !== `fulfill`) {
935 expectedReports.push([
936 `[PowerSync]: Could not clean up subset hook for products`,
937 cleanupFailure,
938 ])
939 }
940 await withTestCleanup(async () => {
941 await hookEntered.promise
942 expect(cleanupHook).not.toHaveBeenCalled()
943 expect(createDiffTrigger).not.toHaveBeenCalled()
944 expect(query.status).toBe(`loading`)
945 await collection.cleanup()
946 const expected = { status: `rejected`, error: new Error(message) }
947 expect(await preload).toEqual(expected)
948 hook.resolve(cleanupHook)
949 await vi.waitFor(() => expect(cleanupHook).toHaveBeenCalledOnce())
950 await new Promise((resolve) => setImmediate(resolve))
951 if (outcome === `fulfill`) {
952 expect(cleanupReports).not.toHaveBeenCalledWith(
953 expect.objectContaining({ error: cleanupFailure }),
954 )
955 } else {
956 expect(cleanupReports).toHaveBeenCalledWith({
957 level: LogLevels.error,
958 message: expect.stringContaining(`Could not clean up subset hook`),
959 error: cleanupFailure,
960 })
961 }
962 expect(createDiffTrigger).not.toHaveBeenCalled()
963 expect(collection.status).toBe(`cleaned-up`)
964 expect(query.status).toBe(`error`)
965 expect(query.toArray).toEqual([])
966 expect(collection.size).toBe(0)
967 expect(publications.flat()).toEqual([])
968 expect(reports.mock.calls).toEqual(expectedReports)
969 }, [
970 () => hook.resolve(cleanupHook),
971 () => subscription.unsubscribe(),
972 () => query.cleanup(),
973 () => collection.cleanup(),
974 () => preload,
975 () => vi.waitFor(() => expect(cleanupHook).toHaveBeenCalledOnce()),
976 () => new Promise((resolve) => setTimeout(resolve, 0)),
977 () => expect(reports.mock.calls).toEqual(expectedReports),
978 () => expect(unexpected).toEqual([]),
979 () => process.off(`unhandledRejection`, recordUnhandled),
980 () => reports.mockRestore(),
981 () => cleanupReports.mockRestore(),
982 () => createDiffTrigger.mockRestore(),
983 ])
984 },
985 )
986})