Open History to see the last commit
1import { describe, expect, it, onTestFinished, vi } from 'vitest'
2import { createCollection, createLiveQueryCollection, eq } from '@tanstack/db'
3import { createDeferred } from '../../db/src/deferred.js'
4import { persistedCollectionOptions } from '../src/index.js'
5import type { Collection, LoadSubsetOptions } from '@tanstack/db'
6import type { PersistenceAdapter } from '../src/index.js'
7
8/**
9 * # Does the persisted wrapper carry initial-query readiness?
10 *
11 * ARCHITECTURE.md law 10 makes a settled `loadSubset` the readiness evidence
12 * for an on-demand source, and law 7 says a successful load settles only after
13 * its rows are visible. The persisted wrapper composes two loads: it hydrates
14 * the subset from local storage, then awaits the upstream source's load. The
15 * upstream here never calls `markReady()`, as a progressive source would not
16 * during its full sync. Each witness records the rows visible at the
17 * query's first-ready transition.
18 */
19
20type Row = { id: string; group: string }
21
22function storageAdapter(local: ReadonlyArray<Row>) {
23 const read = createDeferred<void>()
24 const adapter: PersistenceAdapter = {
25 loadSubset: async () => {
26 await read.promise
27 return local.map((value) => ({ key: value.id, value }))
28 },
29 loadResumeSnapshot: () =>
30 Promise.resolve({
31 rows: [],
32 keySet: { status: `consistent` },
33 collectionMetadata: [],
34 latestTerm: 0,
35 latestSeq: 0,
36 latestRowVersion: 0,
37 resetEpoch: 0,
38 }),
39 applyCommittedTx: async () => {},
40 ensureIndex: async () => {},
41 }
42 return { adapter, read }
43}
44
45type Upstream = {
46 calls: Array<LoadSubsetOptions>
47 respond: (rows: ReadonlyArray<Row>) => void
48 fail: (error: unknown) => void
49}
50
51function persistedOnDemand(
52 adapter: PersistenceAdapter,
53): [Collection<Row, string, any>, Upstream] {
54 let pending = createDeferred<void>()
55 let write!: (rows: ReadonlyArray<Row>) => void
56 const upstream: Upstream = {
57 calls: [],
58 respond: (rows) => {
59 write(rows)
60 pending.resolve()
61 },
62 fail: (error) => pending.reject(error),
63 }
64 const collection = createCollection(
65 persistedCollectionOptions<Row, string>({
66 id: `exposure-${Math.random().toString(36).slice(2)}`,
67 getKey: (row) => row.id,
68 persistence: { adapter },
69 syncMode: `on-demand`,
70 sync: {
71 sync: (params) => {
72 write = (rows) => {
73 params.begin()
74 for (const value of rows) params.write({ type: `insert`, value })
75 params.commit()
76 }
77 return {
78 loadSubset: (options: LoadSubsetOptions) => {
79 upstream.calls.push(options)
80 pending = createDeferred<void>()
81 return pending.promise
82 },
83 }
84 },
85 },
86 }),
87 )
88 onTestFinished(() => collection.cleanup())
89 return [collection, upstream]
90}
91
92function groupA(source: Collection<Row, string, any>) {
93 const query = createLiveQueryCollection((q) =>
94 q.from({ row: source }).where(({ row }) => eq(row.group, `a`)),
95 )
96 onTestFinished(() => query.cleanup())
97 return query
98}
99
100function rowsAtFirstReady(query: Collection<any, any, any>) {
101 const seen: { rows?: Array<unknown> } = {}
102 query.onFirstReady(() => {
103 seen.rows = query.toArray.map((row: Row) => row.id).sort()
104 })
105 return seen
106}
107
108describe(`persisted on-demand initial readiness follows the composed load`, () => {
109 it(`is first ready with local and upstream subset rows visible`, async () => {
110 const storage = storageAdapter([{ id: `local`, group: `a` }])
111 const [source, upstream] = persistedOnDemand(storage.adapter)
112 const query = groupA(source)
113 const seen = rowsAtFirstReady(query)
114 const preload = query.preload()
115
116 storage.read.resolve()
117 await vi.waitFor(() => expect(upstream.calls).toHaveLength(1))
118 expect(query.isReady()).toBe(false)
119 upstream.respond([{ id: `remote`, group: `a` }])
120 await preload
121
122 expect(source.isReady()).toBe(false)
123 expect(seen.rows).toEqual([`local`, `remote`])
124 })
125
126 it(`an upstream load failure errors the query and never readies it`, async () => {
127 const storage = storageAdapter([])
128 const [source, upstream] = persistedOnDemand(storage.adapter)
129 const warned = vi.spyOn(console, `warn`).mockImplementation(() => {})
130 const loggedError = vi.spyOn(console, `error`).mockImplementation(() => {})
131 onTestFinished(() => {
132 warned.mockRestore()
133 loggedError.mockRestore()
134 })
135 const query = groupA(source)
136 const seen = rowsAtFirstReady(query)
137 void query.preload().catch(() => {})
138 storage.read.resolve()
139 await vi.waitFor(() => expect(upstream.calls).toHaveLength(1))
140 upstream.fail(new Error(`upstream failed`))
141 await vi.waitFor(() => expect(query.status).toBe(`error`))
142 expect(seen.rows).toBeUndefined()
143 })
144
145 it(`a demand released during local hydration starts no upstream load`, async () => {
146 const storage = storageAdapter([{ id: `local`, group: `a` }])
147 const [source, upstream] = persistedOnDemand(storage.adapter)
148 const query = groupA(source)
149 void query.preload().catch(() => {})
150 await new Promise((resolve) => setTimeout(resolve, 0))
151 await query.cleanup()
152 storage.read.resolve()
153 await new Promise((resolve) => setTimeout(resolve, 20))
154 expect(upstream.calls.every((options) => options.signal?.aborted)).toBe(
155 true,
156 )
157 expect(source.has(`remote`)).toBe(false)
158 })
159})