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

react-native-persistence.test.ts

472 lines12.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 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
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
62​
63function once(cleanup: Cleanup): Cleanup {
64 let attempted = false
65 return async () => {
66 if (attempted) return
67 attempted = true
68 await cleanup()
69 }
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
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(
124 { kind: `eager`, collectionId: collectionId },
125 {
126 txId: `tx-restart-1`,
127 term: 5,
128 seq: 8,
129 rowVersion: 13,
130 mutations: [
131 {
132 type: `insert`,
133 key: `1`,
134 value: {
135 id: `1`,
136 title: `Survives restart`,
137 score: 10,
138 },
139 },
140 ],
141 },
142 )
143​
144 const firstNativeDatabase = firstDatabase.getNativeDatabase?.()
145 if (!firstNativeDatabase) {
146 throw new Error(`restart oracle requires the local SQLite shim`)
147 }
148 const registryBeforeRestart = firstNativeDatabase
149 .prepare(collectionRegistryQuery)
150 .all(collectionId)
151 expect(registryBeforeRestart).toEqual([
152 {
153 collection_id: collectionId,
154 table_name: expect.stringMatching(/^c_[a-z2-7]+_[0-9a-z]+$/),
155 tombstone_table_name: expect.stringMatching(
156 /^t_[a-z2-7]+_[0-9a-z]+$/,
157 ),
158 schema_version: 1,
159 },
160 ])
161 if (!firstAdapter.getStreamPosition) {
162 throw new Error(`restart oracle requires stream-position support`)
163 }
164 expect(
165 await firstAdapter.getStreamPosition({
166 kind: `eager`,
167 collectionId: collectionId,
168 }),
169 ).toEqual(restartStreamPosition)
170​
171 await closeFirstDatabase()
172​
173 const secondDatabase = createOpSQLiteTestDatabase({
174 filename: dbPath,
175 resultShape: `execute-async-columnar`,
176 })
177 cleanups.unshift(() => Promise.resolve(secondDatabase.close()))
178 const secondNativeDatabase = secondDatabase.getNativeDatabase?.()
179 if (!secondNativeDatabase) {
180 throw new Error(`restart oracle requires the reopened SQLite shim`)
181 }
182 expect(
183 secondNativeDatabase.prepare(collectionRegistryQuery).all(collectionId),
184 ).toEqual(registryBeforeRestart)
185​
186 const secondAdapter = createReactNativeSQLitePersistence({
187 database: secondDatabase,
188 }).adapter
189 if (!secondAdapter.getStreamPosition) {
190 throw new Error(`restart oracle requires stream-position support`)
191 }
192 expect(
193 await secondAdapter.getStreamPosition({
194 kind: `eager`,
195 collectionId: collectionId,
196 }),
197 ).toEqual(restartStreamPosition)
198 await expect(
199 secondAdapter.loadSubset(
200 { kind: `eager`, collectionId: collectionId },
201 {},
202 ),
203 ).resolves.toEqual([
204 {
205 key: `1`,
206 value: {
207 id: `1`,
208 title: `Survives restart`,
209 score: 10,
210 },
211 },
212 ])
213 expect(
214 secondNativeDatabase.prepare(collectionRegistryQuery).all(collectionId),
215 ).toEqual(registryBeforeRestart)
216 },
217 [() => rmSync(tempDirectory, { recursive: true, force: true })],
218 )
219})
220​
221it(`shared react-native api persists across expo-style restart`, async () => {
222 const dbPath = createTempSqlitePath()
223 const collectionId = `todos-restart-expo`
224​
225 const firstDatabase = createOpSQLiteTestDatabase({ filename: dbPath })
226 const firstPersistence = createReactNativeSQLitePersistence({
227 database: firstDatabase,
228 })
229 const firstAdapter = firstPersistence.adapter
230​
231 await firstAdapter.applyCommittedTx(
232 { kind: `eager`, collectionId: collectionId },
233 {
234 txId: `tx-restart-expo-1`,
235 term: 1,
236 seq: 1,
237 rowVersion: 1,
238 mutations: [
239 {
240 type: `insert`,
241 key: `1`,
242 value: {
243 id: `1`,
244 title: `Expo survives restart`,
245 score: 10,
246 },
247 },
248 ],
249 },
250 )
251 await Promise.resolve(firstDatabase.close())
252​
253 const secondDatabase = createOpSQLiteTestDatabase({ filename: dbPath })
254 activeCleanupFns.push(() => Promise.resolve(secondDatabase.close()))
255 const secondPersistence = createReactNativeSQLitePersistence({
256 database: secondDatabase,
257 })
258 const secondAdapter = secondPersistence.adapter
259​
260 const rows = await secondAdapter.loadSubset(
261 { kind: `eager`, collectionId: collectionId },
262 {},
263 )
264 expect(rows).toEqual([
265 {
266 key: `1`,
267 value: {
268 id: `1`,
269 title: `Expo survives restart`,
270 score: 10,
271 },
272 },
273 ])
274})
275​
276it(`keeps all committed rows under rapid mutation bursts`, async () => {
277 const dbPath = createTempSqlitePath()
278 const collectionId = `todos-burst`
279 const database = createOpSQLiteTestDatabase({ filename: dbPath })
280 activeCleanupFns.push(() => Promise.resolve(database.close()))
281​
282 const persistence = createReactNativeSQLitePersistence({
283 database,
284 })
285 const adapter = persistence.adapter
286​
287 const burstSize = 50
288 for (let index = 0; index < burstSize; index++) {
289 const rowId = String(index + 1)
290 await adapter.applyCommittedTx(
291 { kind: `eager`, collectionId: collectionId },
292 {
293 txId: `tx-burst-${rowId}`,
294 term: 1,
295 seq: index + 1,
296 rowVersion: index + 1,
297 mutations: [
298 {
299 type: `insert`,
300 key: rowId,
301 value: {
302 id: rowId,
303 title: `Todo ${rowId}`,
304 score: index,
305 },
306 },
307 ],
308 },
309 )
310 }
311​
312 const rows = await adapter.loadSubset(
313 { kind: `eager`, collectionId: collectionId },
314 {},
315 )
316 expect(rows).toHaveLength(burstSize)
317})
318​
319it(`uses a single react-native api across runtime aliases`, async () => {
320 const dbPath = createTempSqlitePath()
321 const collectionId = `todos-entrypoints`
322 const database = createOpSQLiteTestDatabase({ filename: dbPath })
323 activeCleanupFns.push(() => Promise.resolve(database.close()))
324​
325 const reactNativePersistence = createReactNativeSQLitePersistence({
326 database,
327 })
328 const sharedApiPersistence = createReactNativeSQLitePersistence({
329 database,
330 })
331​
332 await reactNativePersistence.adapter.applyCommittedTx(
333 { kind: `eager`, collectionId: collectionId },
334 {
335 txId: `tx-entrypoint-1`,
336 term: 1,
337 seq: 1,
338 rowVersion: 1,
339 mutations: [
340 {
341 type: `insert`,
342 key: `1`,
343 value: {
344 id: `1`,
345 title: `Entry point parity`,
346 score: 1,
347 },
348 },
349 ],
350 },
351 )
352​
353 const rows = await sharedApiPersistence.adapter.loadSubset(
354 { kind: `eager`, collectionId: collectionId },
355 {},
356 )
357 expect(rows[0]?.value.title).toBe(`Entry point parity`)
358})
359​
360it(`resumes persisted sync after simulated background/foreground transitions`, async () => {
361 const dbPath = createTempSqlitePath()
362 const collectionId = `todos-lifecycle`
363 const database = createOpSQLiteTestDatabase({ filename: dbPath })
364 activeCleanupFns.push(() => Promise.resolve(database.close()))
365​
366 const persistence = createReactNativeSQLitePersistence({
367 database,
368 })
369 const collection = createCollection(
370 persistedCollectionOptions<Todo, string>({
371 id: collectionId,
372 getKey: (todo) => todo.id,
373 persistence,
374 syncMode: `eager`,
375 }),
376 )
377 activeCleanupFns.push(() => collection.cleanup())
378​
379 await collection.stateWhenReady()
380​
381 const initialInsert = collection.insert({
382 id: `1`,
383 title: `Before background`,
384 score: 1,
385 })
386 await initialInsert.isPersisted.promise
387 expect(collection.get(`1`)?.title).toBe(`Before background`)
388​
389 await collection.cleanup()
390 collection.startSyncImmediate()
391 await collection.stateWhenReady()
392​
393 const postResumeInsert = collection.insert({
394 id: `2`,
395 title: `Post resume write`,
396 score: 2,
397 })
398 await postResumeInsert.isPersisted.promise
399 expect(collection.get(`2`)?.title).toBe(`Post resume write`)
400​
401 const persistedRows = await persistence.adapter.loadSubset(
402 { kind: `eager`, collectionId: collectionId },
403 {},
404 )
405 expect(persistedRows).toEqual(
406 expect.arrayContaining([
407 expect.objectContaining({
408 key: `1`,
409 }),
410 expect.objectContaining({
411 key: `2`,
412 }),
413 ]),
414 )
415})
416​
417it(`shared api resumes persisted sync in expo-style lifecycle`, async () => {
418 const dbPath = createTempSqlitePath()
419 const collectionId = `todos-lifecycle-expo`
420 const database = createOpSQLiteTestDatabase({ filename: dbPath })
421 activeCleanupFns.push(() => Promise.resolve(database.close()))
422​
423 const persistence = createReactNativeSQLitePersistence({
424 database,
425 })
426 const collection = createCollection(
427 persistedCollectionOptions<Todo, string>({
428 id: collectionId,
429 getKey: (todo) => todo.id,
430 persistence,
431 syncMode: `eager`,
432 }),
433 )
434 activeCleanupFns.push(() => collection.cleanup())
435​
436 await collection.stateWhenReady()
437​
438 const initialInsert = collection.insert({
439 id: `1`,
440 title: `Before background`,
441 score: 1,
442 })
443 await initialInsert.isPersisted.promise
444 expect(collection.get(`1`)?.title).toBe(`Before background`)
445​
446 await collection.cleanup()
447 collection.startSyncImmediate()
448 await collection.stateWhenReady()
449​
450 const postResumeInsert = collection.insert({
451 id: `2`,
452 title: `Post resume write`,
453 score: 2,
454 })
455 await postResumeInsert.isPersisted.promise
456 expect(collection.get(`2`)?.title).toBe(`Post resume write`)
457​
458 const persistedRows = await persistence.adapter.loadSubset(
459 { kind: `eager`, collectionId: collectionId },
460 {},
461 )
462 expect(persistedRows).toEqual(
463 expect.arrayContaining([
464 expect.objectContaining({
465 key: `1`,
466 }),
467 expect.objectContaining({
468 key: `2`,
469 }),
470 ]),
471 )
472})