Open History to see the last commit
1import { DatabaseSync } from 'node:sqlite'
2import { afterEach, describe, expect, it, vi } from 'vitest'
3import { IR, createCollection, getLoadSubsetDemandKey } from '@tanstack/db'
4import {
5 SQLiteCorePersistenceAdapter,
6 persistedCollectionOptions,
7} from '../src/index.js'
8import { createSerializedNodeSqliteDriver as createDriver } from './helpers/node-sqlite-driver.js'
9import {
10 drain,
11 filterQuery,
12 onDemandSource,
13 quietConsole,
14 untilUpstreamCalled,
15 useFakeClock,
16 withCleanup,
17} from './helpers/demand-coverage-driver.js'
18import type { Row } from './helpers/demand-coverage-driver.js'
19import type { SQLiteDriver } from '../src/index.js'
20
21/**
22 * Supplemental checks beside the persisted demand coverage oracle
23 * (`persisted-demand-coverage-oracle.test.ts`). These pin two behaviors that
24 * the opt-in must leave as they were, and whose laws other owners hold, so
25 * they are ordinary examples rather than inputs to the coverage judgment
26 * (ORC-016):
27 *
28 * - An optimistic write on a demand settled from SQLite follows the
29 * optimistic overlay rules (`packages/db/tests/optimistic-history-oracle.ts`
30 * owns them): the row shows while its handler runs and leaves when it
31 * rejects, and the query stays ready throughout.
32 * - Opting in keeps a synchronous answer synchronous: a second request for a
33 * demand already hydrated in this sync run reports `true` to core, as it
34 * did before the opt-in existed.
35 */
36
37const A1: Row = { id: `a1`, group: `a`, rank: 1, value: `v1` }
38const A2: Row = { id: `a2`, group: `a`, rank: 2, value: `v1` }
39
40async function coverD(
41 driver: SQLiteDriver,
42 rows: ReadonlyArray<Row> = [A1, A2],
43): Promise<ReturnType<typeof getLoadSubsetDemandKey>> {
44 const { collection, upstream } = onDemandSource(
45 new SQLiteCorePersistenceAdapter({ driver }),
46 0,
47 )
48 const query = filterQuery(collection, `a`)
49 return withCleanup(async () => {
50 const preload = query.preload()
51 await vi.waitFor(() => expect(upstream.pendingCount()).toBe(1))
52 await upstream.answer(rows)
53 await preload
54 return getLoadSubsetDemandKey(upstream.calls[0]!)
55 }, [() => query.cleanup(), () => collection.cleanup()])
56}
57
58type OptimisticObservation = {
59 settledBeforeWrite: Array<string>
60 duringWrite: Array<string>
61 afterRollback: Array<string>
62 readyThroughout: boolean
63}
64
65async function runOptimisticWrite(): Promise<OptimisticObservation> {
66 const driver = createDriver(new DatabaseSync(`:memory:`))
67 await coverD(driver)
68 useFakeClock()
69 let rejectWrite!: (error: unknown) => void
70 const { collection, upstream } = onDemandSource(
71 new SQLiteCorePersistenceAdapter({ driver }),
72 0,
73 {
74 onInsert: () =>
75 new Promise<void>((_resolve, reject) => {
76 rejectWrite = reject
77 }),
78 },
79 )
80 const query = filterQuery(collection, `a`)
81 return withCleanup(async () => {
82 void query.preload().catch(() => undefined)
83 await untilUpstreamCalled(upstream, 1)
84 await drain()
85 await vi.advanceTimersByTimeAsync(1)
86 await drain()
87 const ids = () => query.toArray.map((row) => row.id).sort()
88 let readyThroughout = query.status === `ready`
89 const settledBeforeWrite = ids()
90 const transaction = collection.insert({
91 id: `a9`,
92 group: `a`,
93 rank: 9,
94 value: `local`,
95 })
96 void transaction.when('settled').catch(() => undefined)
97 await drain()
98 readyThroughout &&= query.status === `ready`
99 const duringWrite = ids()
100 rejectWrite(new Error(`offline write`))
101 await drain()
102 readyThroughout &&= query.status === `ready`
103 return {
104 settledBeforeWrite,
105 duringWrite,
106 afterRollback: ids(),
107 readyThroughout,
108 }
109 }, [
110 () => vi.useRealTimers(),
111 () => query.cleanup(),
112 () => collection.cleanup(),
113 ])
114}
115
116async function runSynchronousAnswer(): Promise<{
117 sourceCalls: number
118 secondResult: `true` | `promise` | `none`
119}> {
120 const driver = createDriver(new DatabaseSync(`:memory:`))
121 let sourceCalls = 0
122 const collection = createCollection(
123 persistedCollectionOptions<Row, string>({
124 id: `demand-coverage-synchronous`,
125 getKey: (row) => row.id,
126 syncMode: `on-demand`,
127 initialRender: { strategy: `network-first`, networkTimeoutMs: 0 },
128 persistence: { adapter: new SQLiteCorePersistenceAdapter({ driver }) },
129 sync: {
130 sync: ({ begin, write, commit }) => ({
131 loadSubset: () => {
132 sourceCalls++
133 begin()
134 for (const value of [A1, A2]) write({ type: `insert`, value })
135 commit()
136 return true
137 },
138 }),
139 },
140 }),
141 )
142 const first = filterQuery(collection, `a`)
143 let subscription: { unsubscribe: () => void } | undefined
144 return withCleanup(async () => {
145 await first.preload()
146 await new Promise((resolve) => setTimeout(resolve, 50))
147 const callsBefore = sourceCalls
148 const second = { result: `none` as `true` | `promise` | `none` }
149 const changes = collection.subscribeChanges(() => {}, {
150 includeInitialState: false,
151 })
152 subscription = changes
153 ;(
154 changes as unknown as { requestSnapshot: (options: object) => unknown }
155 ).requestSnapshot({
156 where: new IR.Func(`eq`, [new IR.PropRef([`group`]), new IR.Value(`a`)]),
157 onLoadSubsetResult: (result: true | Promise<void>) => {
158 second.result = result === true ? `true` : `promise`
159 },
160 })
161 return {
162 sourceCalls: sourceCalls - callsBefore,
163 secondResult: second.result,
164 }
165 }, [
166 () => subscription?.unsubscribe(),
167 () => first.cleanup(),
168 () => collection.cleanup(),
169 ])
170}
171
172afterEach(() => {
173 vi.useRealTimers()
174 vi.restoreAllMocks()
175})
176
177describe(`persisted demand coverage beside other owners' laws`, () => {
178 it(`keeps an optimistic write's overlay rules on a demand settled from SQLite`, async () => {
179 quietConsole()
180 expect(await runOptimisticWrite()).toEqual({
181 settledBeforeWrite: [`a1`, `a2`],
182 duringWrite: [`a1`, `a2`, `a9`],
183 afterRollback: [`a1`, `a2`],
184 readyThroughout: true,
185 })
186 })
187
188 it(`keeps a synchronous answer for an already hydrated demand synchronous`, async () => {
189 quietConsole()
190 // Positive witness: the second request reached the source.
191 expect(await runSynchronousAnswer()).toEqual({
192 sourceCalls: 1,
193 secondResult: `true`,
194 })
195 })
196})
197
198describe(`demand coverage test driver`, () => {
199 // The harness keeps an oracle mismatch as the primary failure even when
200 // cleanup fails too (ORC-010).
201 it(`preserves a primary failure when cleanup also fails`, async () => {
202 const mismatch = new Error(`wrong rows`)
203 const cleanupFailure = new Error(`cleanup failed`)
204 await expect(
205 withCleanup(
206 () => Promise.reject(mismatch),
207 [
208 () => {
209 throw cleanupFailure
210 },
211 ],
212 ),
213 ).rejects.toMatchObject({
214 cause: mismatch,
215 errors: [mismatch, cleanupFailure],
216 })
217 })
218})