Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

tauri-persistence.test.ts

402 lines10.8 KB

1import { mkdtempSync, rmSync } from 'node:fs'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { afterEach, expect, it } from 'vitest'
5import { createCollection } from '@tanstack/db'
6import {
7 createTauriSQLitePersistence as createIndexPersistence,
8 persistedCollectionOptions,
9} from '../src'
10import { createTauriSQLitePersistence as createTauriPersistence } from '../src/tauri'
11import { createTauriSQLiteTestDatabase } from './helpers/tauri-sql-test-db'
12import type { TauriSQLiteDatabaseLike } from '../src/tauri'
13​
14type Todo = {
15 id: string
16 title: string
17 score: number
19​
20const activeCleanupFns: Array<() => void | Promise<void>> = []
21​
22afterEach(async () => {
23 while (activeCleanupFns.length > 0) {
24 const cleanupFn = activeCleanupFns.pop()
25 await Promise.resolve(cleanupFn?.())
26 }
27})
28​
29function createTempSqlitePath(): string {
30 const tempDirectory = mkdtempSync(
31 join(tmpdir(), `db-tauri-persistence-test-`),
32 )
33 const dbPath = join(tempDirectory, `state.sqlite`)
34 activeCleanupFns.push(() => {
35 rmSync(tempDirectory, { recursive: true, force: true })
36 })
37 return dbPath
39​
40it(`uses the configured cache-claim lifetime and clock`, async () => {
41 const database = createTauriSQLiteTestDatabase({
42 filename: createTempSqlitePath(),
43 })
44 registerDatabaseCleanup(database)
45 let now = 1_000
46 const persistence = createTauriPersistence({
47 database,
48 cacheGenerationClaimTtlMs: 1_234,
49 now: () => now,
50 })
51 const adapter = persistence.resolvePersistenceForCollection!({
52 collectionId: `claim-options`,
53 mode: `sync-present`,
54 schemaVersion: undefined,
55 }).adapter
56 const claim = await adapter.claimCacheGeneration!(`claim-options`)
57 expect(claim.expiresAtMs).toBe(2_234)
58 now = 2_234
59 expect(
60 await adapter.renewCacheGenerationClaim!(
61 claim.storageCollectionId,
62 claim.claimId,
63 ),
64 ).toBeUndefined()
65})
66​
67function rethrowDatabaseErrorsAsStrings(
68 database: TauriSQLiteDatabaseLike,
69): TauriSQLiteDatabaseLike {
70 return {
71 ...database,
72 execute: async (...args) => {
73 try {
74 return await database.execute(...args)
75 } catch (error) {
76 throw error instanceof Error ? error.message : String(error)
77 }
78 },
79 }
81​
82function registerDatabaseCleanup(
83 database: TauriSQLiteDatabaseLike,
84): () => Promise<void> {
85 let closed = false
86 const close = async () => {
87 if (closed) {
88 return
89 }
90 await database.close()
91 closed = true
92 }
93 activeCleanupFns.push(close)
94 return close
96​
97/**
98 * Migration law (#1711): adding an already-present migration column is an
99 * idempotent no-op even when the Tauri bridge rejects with a string. Seed a
100 * real legacy SQLite table, drive migration through the Tauri driver and core
101 * adapter, then close and reopen once both migration columns exist. PRAGMA,
102 * exact legacy bytes, and public rows are the checkpoints. The unrelated-error
103 * control proves the classifier does not turn arbitrary string failures into
104 * success. This Better SQLite fixture reproduces Tauri's error boundary but is
105 * not a native Tauri runtime receipt.
106 */
107it(`migrates and reopens a legacy database when Tauri reports duplicate columns as strings`, async () => {
108 const dbPath = createTempSqlitePath()
109 const collectionId = `todos-string-migration`
110​
111 const seedDatabase = createTauriSQLiteTestDatabase({ filename: dbPath })
112 const closeSeedDatabase = registerDatabaseCleanup(seedDatabase)
113 await seedDatabase.execute(
114 `CREATE TABLE applied_tx (
115 collection_id TEXT NOT NULL,
116 term INTEGER NOT NULL,
117 seq INTEGER NOT NULL,
118 tx_id TEXT NOT NULL,
119 row_version INTEGER NOT NULL,
120 replay_json TEXT,
121 applied_at INTEGER NOT NULL,
122 PRIMARY KEY (collection_id, term, seq)
123 )`,
124 )
125 await seedDatabase.execute(
126 `INSERT INTO applied_tx (
127 collection_id,
128 term,
129 seq,
130 tx_id,
131 row_version,
132 replay_json,
133 applied_at
134 ) VALUES ($1, $2, $3, $4, $5, $6, $7)`,
135 [
136 collectionId,
137 1,
138 1,
139 `legacy-tx`,
140 1,
141 `{"mutations":[]}`,
142 Math.floor(Date.now() / 1000),
143 ],
144 )
145 await closeSeedDatabase()
146​
147 const migrationDatabase = rethrowDatabaseErrorsAsStrings(
148 createTauriSQLiteTestDatabase({ filename: dbPath }),
149 )
150 const closeMigrationDatabase = registerDatabaseCleanup(migrationDatabase)
151 const migrationPersistence = createTauriPersistence({
152 database: migrationDatabase,
153 })
154​
155 await migrationPersistence.adapter.applyCommittedTx(
156 { kind: `eager`, collectionId: collectionId },
157 {
158 txId: `post-migration-tx`,
159 term: 1,
160 seq: 2,
161 rowVersion: 2,
162 mutations: [
163 {
164 type: `insert`,
165 key: `1`,
166 value: {
167 id: `1`,
168 title: `Survives migration`,
169 score: 1,
170 },
171 },
172 ],
173 },
174 )
175​
176 const migratedColumns = await migrationDatabase.select<
177 Array<{ name: string }>
178 >(`PRAGMA table_info(applied_tx)`)
179 expect(migratedColumns.map((column) => column.name)).toEqual(
180 expect.arrayContaining([`replay_json`, `replay_requires_full_reload`]),
181 )
182 expect(
183 await migrationDatabase.select<
184 Array<{ tx_id: string; replay_json: string | null }>
185 >(
186 `SELECT tx_id, replay_json
187 FROM applied_tx
188 WHERE tx_id = 'legacy-tx'`,
189 ),
190 ).toEqual([{ tx_id: `legacy-tx`, replay_json: `{"mutations":[]}` }])
191 await closeMigrationDatabase()
192​
193 const reopenedDatabase = rethrowDatabaseErrorsAsStrings(
194 createTauriSQLiteTestDatabase({ filename: dbPath }),
195 )
196 registerDatabaseCleanup(reopenedDatabase)
197 const reopenedPersistence = createTauriPersistence({
198 database: reopenedDatabase,
199 })
200​
201 await expect(
202 reopenedPersistence.adapter.loadSubset(
203 { kind: `eager`, collectionId: collectionId },
204 {},
205 ),
206 ).resolves.toEqual([
207 {
208 key: `1`,
209 value: {
210 id: `1`,
211 title: `Survives migration`,
212 score: 1,
213 },
214 },
215 ])
216 expect(
217 await reopenedDatabase.select<
218 Array<{ tx_id: string; replay_json: string | null }>
219 >(
220 `SELECT tx_id, replay_json
221 FROM applied_tx
222 WHERE tx_id = 'legacy-tx'`,
223 ),
224 ).toEqual([{ tx_id: `legacy-tx`, replay_json: `{"mutations":[]}` }])
225})
226​
227it(`propagates unrelated string failures from a Tauri migration`, async () => {
228 const dbPath = createTempSqlitePath()
229 const database = createTauriSQLiteTestDatabase({ filename: dbPath })
230 registerDatabaseCleanup(database)
231 const failingDatabase: TauriSQLiteDatabaseLike = {
232 ...database,
233 execute: async (sql, bindValues) => {
234 if (sql.includes(`ALTER TABLE applied_tx ADD COLUMN replay_json`)) {
235 throw `database is locked`
236 }
237 return database.execute(sql, bindValues)
238 },
239 }
240 const persistence = createTauriPersistence({ database: failingDatabase })
241​
242 await expect(
243 persistence.adapter.loadSubset(
244 { kind: `eager`, collectionId: `todos-unrelated-migration-error` },
245 {},
246 ),
247 ).rejects.toBe(`database is locked`)
248})
249​
250it(`persists data across app restart (close and reopen)`, async () => {
251 const dbPath = createTempSqlitePath()
252 const collectionId = `todos-restart`
253​
254 const firstDatabase = createTauriSQLiteTestDatabase({ filename: dbPath })
255 const firstPersistence = createTauriPersistence({
256 database: firstDatabase,
257 })
258 const firstAdapter = firstPersistence.adapter
259​
260 await firstAdapter.applyCommittedTx(
261 { kind: `eager`, collectionId: collectionId },
262 {
263 txId: `tx-restart-1`,
264 term: 1,
265 seq: 1,
266 rowVersion: 1,
267 mutations: [
268 {
269 type: `insert`,
270 key: `1`,
271 value: {
272 id: `1`,
273 title: `Survives restart`,
274 score: 10,
275 },
276 },
277 ],
278 },
279 )
280 await Promise.resolve(firstDatabase.close())
281​
282 const secondDatabase = createTauriSQLiteTestDatabase({ filename: dbPath })
283 activeCleanupFns.push(async () => {
284 await Promise.resolve(secondDatabase.close())
285 })
286 const secondPersistence = createTauriPersistence({
287 database: secondDatabase,
288 })
289 const secondAdapter = secondPersistence.adapter
290​
291 const rows = await secondAdapter.loadSubset(
292 { kind: `eager`, collectionId: collectionId },
293 {},
294 )
295 expect(rows).toEqual([
296 {
297 key: `1`,
298 value: {
299 id: `1`,
300 title: `Survives restart`,
301 score: 10,
302 },
303 },
304 ])
305})
306​
307it(`shares the same runtime behavior through index and tauri entrypoints`, async () => {
308 const dbPath = createTempSqlitePath()
309 const collectionId = `todos-entrypoints`
310 const database = createTauriSQLiteTestDatabase({ filename: dbPath })
311 activeCleanupFns.push(async () => {
312 await Promise.resolve(database.close())
313 })
314​
315 const indexPersistence = createIndexPersistence({ database })
316 const tauriPersistence = createTauriPersistence({ database })
317​
318 await indexPersistence.adapter.applyCommittedTx(
319 { kind: `eager`, collectionId: collectionId },
320 {
321 txId: `tx-entrypoint-1`,
322 term: 1,
323 seq: 1,
324 rowVersion: 1,
325 mutations: [
326 {
327 type: `insert`,
328 key: `1`,
329 value: {
330 id: `1`,
331 title: `Entry point parity`,
332 score: 1,
333 },
334 },
335 ],
336 },
337 )
338​
339 const rows = await tauriPersistence.adapter.loadSubset(
340 { kind: `eager`, collectionId: collectionId },
341 {},
342 )
343 expect(rows[0]?.value.title).toBe(`Entry point parity`)
344})
345​
346it(`resumes persisted sync after cleanup and restart`, async () => {
347 const dbPath = createTempSqlitePath()
348 const collectionId = `todos-lifecycle`
349 const database = createTauriSQLiteTestDatabase({ filename: dbPath })
350 activeCleanupFns.push(async () => {
351 await Promise.resolve(database.close())
352 })
353​
354 const persistence = createTauriPersistence({
355 database,
356 })
357 const collection = createCollection(
358 persistedCollectionOptions<Todo, string>({
359 id: collectionId,
360 getKey: (todo) => todo.id,
361 persistence,
362 syncMode: `eager`,
363 }),
364 )
365 activeCleanupFns.push(() => collection.cleanup())
366​
367 await collection.stateWhenReady()
368 const initialInsert = collection.insert({
369 id: `1`,
370 title: `Before cleanup`,
371 score: 1,
372 })
373 await initialInsert.isPersisted.promise
374 expect(collection.get(`1`)?.title).toBe(`Before cleanup`)
375​
376 await collection.cleanup()
377 collection.startSyncImmediate()
378 await collection.stateWhenReady()
379​
380 const resumedInsert = collection.insert({
381 id: `2`,
382 title: `After restart`,
383 score: 2,
384 })
385 await resumedInsert.isPersisted.promise
386 expect(collection.get(`2`)?.title).toBe(`After restart`)
387​
388 const persistedRows = await persistence.adapter.loadSubset(
389 { kind: `eager`, collectionId: collectionId },
390 {},
391 )
392 expect(persistedRows).toEqual(
393 expect.arrayContaining([
394 expect.objectContaining({
395 key: `1`,
396 }),
397 expect.objectContaining({
398 key: `2`,
399 }),
400 ]),
401 )
402})