Open History to see the last commit
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 createReactNativeSQLitePersistence,
8 persistedCollectionOptions,
9} from '../src'
10import { createOpSQLiteTestDatabase } from './helpers/op-sqlite-test-db'
11
12type Todo = {
13 id: string
14 title: string
15 score: number
16}
17
18type Cleanup = () => void | Promise<void>
19
20const activeCleanupFns: Array<Cleanup> = []
21
22async function withFailurePreservingCleanup<T>(
23 run: (cleanups: Array<Cleanup>) => Promise<T>,
24 cleanups: Array<Cleanup>,
25): Promise<T> {
26 let outcome: { ok: true; value: T } | { ok: false; error: unknown }
27 try {
28 outcome = { ok: true, value: await run(cleanups) }
29 } catch (error) {
30 outcome = { ok: false, error }
31 }
32
33 const cleanupErrors: Array<unknown> = []
34 for (const cleanup of cleanups) {
35 try {
36 await cleanup()
37 } catch (error) {
38 cleanupErrors.push(error)
39 }
40 }
41
42 if (!outcome.ok) {
43 if (cleanupErrors.length > 0) {
44 throw new AggregateError(
45 [outcome.error, ...cleanupErrors],
46 `react-native restart oracle and cleanup failed`,
47 { cause: outcome.error },
48 )
49 }
50 throw outcome.error
51 }
52 if (cleanupErrors.length === 1) throw cleanupErrors[0]
53 if (cleanupErrors.length > 1) {
54 throw new AggregateError(
55 cleanupErrors,
56 `react-native restart oracle cleanup failed`,
57 { cause: cleanupErrors[0] },
58 )
59 }
60 return outcome.value
61}
62
63function once(cleanup: Cleanup): Cleanup {
64 let attempted = false
65 return async () => {
66 if (attempted) return
67 attempted = true
68 await cleanup()
69 }
70}
71
72afterEach(async () => {
73 while (activeCleanupFns.length > 0) {
74 const cleanupFn = activeCleanupFns.pop()
75 await Promise.resolve(cleanupFn?.())
76 }
77})
78
79function createTempSqlitePath(): string {
80 const tempDirectory = mkdtempSync(join(tmpdir(), `db-rn-persistence-test-`))
81 const dbPath = join(tempDirectory, `state.sqlite`)
82 activeCleanupFns.push(() => {
83 rmSync(tempDirectory, { recursive: true, force: true })
84 })
85 return dbPath
86}
87
88const collectionRegistryQuery = `SELECT collection_id, table_name, tombstone_table_name, schema_version
89 FROM collection_registry
90 WHERE collection_id = ?`
91
92const restartStreamPosition = {
93 latestTerm: 5,
94 latestSeq: 8,
95 latestRowVersion: 13,
96} as const
97
98/**
99 * Restart law: an existing collection_registry mapping is authoritative after
100 * close/reopen, and its exact stream position and stored rows remain readable.
101 * The first ordinary-row connection seeds the fixed witness; the reopened
102 * executeAsync columnar connection exercises the production adapter boundary.
103 * This better-sqlite3 shim cannot close native op-sqlite device coverage.
104 */
105it(`reuses a pre-populated registry with exact stream and rows after close and reopen`, async () => {
106 const tempDirectory = mkdtempSync(
107 join(tmpdir(), `db-rn-persistence-restart-oracle-`),
108 )
109 const dbPath = join(tempDirectory, `state.sqlite`)
110 const collectionId = `todos-restart`
111
112 await withFailurePreservingCleanup(
113 async (cleanups) => {
114 const firstDatabase = createOpSQLiteTestDatabase({ filename: dbPath })
115 const closeFirstDatabase = once(() =>
116 Promise.resolve(firstDatabase.close()),
117 )
118 cleanups.unshift(closeFirstDatabase)
119 const firstAdapter = createReactNativeSQLitePersistence({
120 database: firstDatabase,
121 }).adapter
122
123 await firstAdapter.applyCommittedTx(collectionId, {
124 txId: `tx-restart-1`,
125 term: 5,
126 seq: 8,
127 rowVersion: 13,
128 mutations: [
129 {
130 type: `insert`,
131 key: `1`,
132 value: {
133 id: `1`,
134 title: `Survives restart`,
135 score: 10,
136 },
137 },
138 ],
139 })
140
141 const firstNativeDatabase = firstDatabase.getNativeDatabase?.()
142 if (!firstNativeDatabase) {
143 throw new Error(`restart oracle requires the local SQLite shim`)
144 }
145 const registryBeforeRestart = firstNativeDatabase
146 .prepare(collectionRegistryQuery)
147 .all(collectionId)
148 expect(registryBeforeRestart).toEqual([
149 {
150 collection_id: collectionId,
151 table_name: expect.stringMatching(/^c_[a-z2-7]+_[0-9a-z]+$/),
152 tombstone_table_name: expect.stringMatching(
153 /^t_[a-z2-7]+_[0-9a-z]+$/,
154 ),
155 schema_version: 1,
156 },
157 ])
158 if (!firstAdapter.getStreamPosition) {
159 throw new Error(`restart oracle requires stream-position support`)
160 }
161 expect(await firstAdapter.getStreamPosition(collectionId)).toEqual(
162 restartStreamPosition,
163 )
164
165 await closeFirstDatabase()
166
167 const secondDatabase = createOpSQLiteTestDatabase({
168 filename: dbPath,
169 resultShape: `execute-async-columnar`,
170 })
171 cleanups.unshift(() => Promise.resolve(secondDatabase.close()))
172 const secondNativeDatabase = secondDatabase.getNativeDatabase?.()
173 if (!secondNativeDatabase) {
174 throw new Error(`restart oracle requires the reopened SQLite shim`)
175 }
176 expect(
177 secondNativeDatabase.prepare(collectionRegistryQuery).all(collectionId),
178 ).toEqual(registryBeforeRestart)
179
180 const secondAdapter = createReactNativeSQLitePersistence({
181 database: secondDatabase,
182 }).adapter
183 if (!secondAdapter.getStreamPosition) {
184 throw new Error(`restart oracle requires stream-position support`)
185 }
186 expect(await secondAdapter.getStreamPosition(collectionId)).toEqual(
187 restartStreamPosition,
188 )
189 await expect(secondAdapter.loadSubset(collectionId, {})).resolves.toEqual(
190 [
191 {
192 key: `1`,
193 value: {
194 id: `1`,
195 title: `Survives restart`,
196 score: 10,
197 },
198 },
199 ],
200 )
201 expect(
202 secondNativeDatabase.prepare(collectionRegistryQuery).all(collectionId),
203 ).toEqual(registryBeforeRestart)
204 },
205 [() => rmSync(tempDirectory, { recursive: true, force: true })],
206 )
207})
208
209it(`shared react-native api persists across expo-style restart`, async () => {
210 const dbPath = createTempSqlitePath()
211 const collectionId = `todos-restart-expo`
212
213 const firstDatabase = createOpSQLiteTestDatabase({ filename: dbPath })
214 const firstPersistence = createReactNativeSQLitePersistence({
215 database: firstDatabase,
216 })
217 const firstAdapter = firstPersistence.adapter
218
219 await firstAdapter.applyCommittedTx(collectionId, {
220 txId: `tx-restart-expo-1`,
221 term: 1,
222 seq: 1,
223 rowVersion: 1,
224 mutations: [
225 {
226 type: `insert`,
227 key: `1`,
228 value: {
229 id: `1`,
230 title: `Expo survives restart`,
231 score: 10,
232 },
233 },
234 ],
235 })
236 await Promise.resolve(firstDatabase.close())
237
238 const secondDatabase = createOpSQLiteTestDatabase({ filename: dbPath })
239 activeCleanupFns.push(() => Promise.resolve(secondDatabase.close()))
240 const secondPersistence = createReactNativeSQLitePersistence({
241 database: secondDatabase,
242 })
243 const secondAdapter = secondPersistence.adapter
244
245 const rows = await secondAdapter.loadSubset(collectionId, {})
246 expect(rows).toEqual([
247 {
248 key: `1`,
249 value: {
250 id: `1`,
251 title: `Expo survives restart`,
252 score: 10,
253 },
254 },
255 ])
256})
257
258it(`keeps all committed rows under rapid mutation bursts`, async () => {
259 const dbPath = createTempSqlitePath()
260 const collectionId = `todos-burst`
261 const database = createOpSQLiteTestDatabase({ filename: dbPath })
262 activeCleanupFns.push(() => Promise.resolve(database.close()))
263
264 const persistence = createReactNativeSQLitePersistence({
265 database,
266 })
267 const adapter = persistence.adapter
268
269 const burstSize = 50
270 for (let index = 0; index < burstSize; index++) {
271 const rowId = String(index + 1)
272 await adapter.applyCommittedTx(collectionId, {
273 txId: `tx-burst-${rowId}`,
274 term: 1,
275 seq: index + 1,
276 rowVersion: index + 1,
277 mutations: [
278 {
279 type: `insert`,
280 key: rowId,
281 value: {
282 id: rowId,
283 title: `Todo ${rowId}`,
284 score: index,
285 },
286 },
287 ],
288 })
289 }
290
291 const rows = await adapter.loadSubset(collectionId, {})
292 expect(rows).toHaveLength(burstSize)
293})
294
295it(`uses a single react-native api across runtime aliases`, async () => {
296 const dbPath = createTempSqlitePath()
297 const collectionId = `todos-entrypoints`
298 const database = createOpSQLiteTestDatabase({ filename: dbPath })
299 activeCleanupFns.push(() => Promise.resolve(database.close()))
300
301 const reactNativePersistence = createReactNativeSQLitePersistence({
302 database,
303 })
304 const sharedApiPersistence = createReactNativeSQLitePersistence({
305 database,
306 })
307
308 await reactNativePersistence.adapter.applyCommittedTx(collectionId, {
309 txId: `tx-entrypoint-1`,
310 term: 1,
311 seq: 1,
312 rowVersion: 1,
313 mutations: [
314 {
315 type: `insert`,
316 key: `1`,
317 value: {
318 id: `1`,
319 title: `Entry point parity`,
320 score: 1,
321 },
322 },
323 ],
324 })
325
326 const rows = await sharedApiPersistence.adapter.loadSubset(collectionId, {})
327 expect(rows[0]?.value.title).toBe(`Entry point parity`)
328})
329
330it(`resumes persisted sync after simulated background/foreground transitions`, async () => {
331 const dbPath = createTempSqlitePath()
332 const collectionId = `todos-lifecycle`
333 const database = createOpSQLiteTestDatabase({ filename: dbPath })
334 activeCleanupFns.push(() => Promise.resolve(database.close()))
335
336 const persistence = createReactNativeSQLitePersistence({
337 database,
338 })
339 const collection = createCollection(
340 persistedCollectionOptions<Todo, string>({
341 id: collectionId,
342 getKey: (todo) => todo.id,
343 persistence,
344 syncMode: `eager`,
345 }),
346 )
347 activeCleanupFns.push(() => collection.cleanup())
348
349 await collection.stateWhenReady()
350
351 const initialInsert = collection.insert({
352 id: `1`,
353 title: `Before background`,
354 score: 1,
355 })
356 await initialInsert.isPersisted.promise
357 expect(collection.get(`1`)?.title).toBe(`Before background`)
358
359 await collection.cleanup()
360 collection.startSyncImmediate()
361 await collection.stateWhenReady()
362
363 const postResumeInsert = collection.insert({
364 id: `2`,
365 title: `Post resume write`,
366 score: 2,
367 })
368 await postResumeInsert.isPersisted.promise
369 expect(collection.get(`2`)?.title).toBe(`Post resume write`)
370
371 const persistedRows = await persistence.adapter.loadSubset(collectionId, {})
372 expect(persistedRows).toEqual(
373 expect.arrayContaining([
374 expect.objectContaining({
375 key: `1`,
376 }),
377 expect.objectContaining({
378 key: `2`,
379 }),
380 ]),
381 )
382})
383
384it(`shared api resumes persisted sync in expo-style lifecycle`, async () => {
385 const dbPath = createTempSqlitePath()
386 const collectionId = `todos-lifecycle-expo`
387 const database = createOpSQLiteTestDatabase({ filename: dbPath })
388 activeCleanupFns.push(() => Promise.resolve(database.close()))
389
390 const persistence = createReactNativeSQLitePersistence({
391 database,
392 })
393 const collection = createCollection(
394 persistedCollectionOptions<Todo, string>({
395 id: collectionId,
396 getKey: (todo) => todo.id,
397 persistence,
398 syncMode: `eager`,
399 }),
400 )
401 activeCleanupFns.push(() => collection.cleanup())
402
403 await collection.stateWhenReady()
404
405 const initialInsert = collection.insert({
406 id: `1`,
407 title: `Before background`,
408 score: 1,
409 })
410 await initialInsert.isPersisted.promise
411 expect(collection.get(`1`)?.title).toBe(`Before background`)
412
413 await collection.cleanup()
414 collection.startSyncImmediate()
415 await collection.stateWhenReady()
416
417 const postResumeInsert = collection.insert({
418 id: `2`,
419 title: `Post resume write`,
420 score: 2,
421 })
422 await postResumeInsert.isPersisted.promise
423 expect(collection.get(`2`)?.title).toBe(`Post resume write`)
424
425 const persistedRows = await persistence.adapter.loadSubset(collectionId, {})
426 expect(persistedRows).toEqual(
427 expect.arrayContaining([
428 expect.objectContaining({
429 key: `1`,
430 }),
431 expect.objectContaining({
432 key: `2`,
433 }),
434 ]),
435 )
436})