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 createCapacitorSQLitePersistence,
8 persistedCollectionOptions,
9} from '../src'
10import { createCapacitorSQLiteTestDatabase } from './helpers/capacitor-sqlite-test-db'
11
12type Todo = {
13 id: string
14 title: string
15 score: number
16}
17
18const activeCleanupFns: Array<() => void | Promise<void>> = []
19
20afterEach(async () => {
21 while (activeCleanupFns.length > 0) {
22 const cleanupFn = activeCleanupFns.pop()
23 await Promise.resolve(cleanupFn?.())
24 }
25})
26
27function createTempSqlitePath(): string {
28 const tempDirectory = mkdtempSync(
29 join(tmpdir(), `db-capacitor-persistence-test-`),
30 )
31 const dbPath = join(tempDirectory, `state.sqlite`)
32 activeCleanupFns.push(() => {
33 rmSync(tempDirectory, { recursive: true, force: true })
34 })
35 return dbPath
36}
37
38it(`uses the configured cache-claim lifetime and clock`, async () => {
39 const database = createCapacitorSQLiteTestDatabase({
40 filename: createTempSqlitePath(),
41 })
42 activeCleanupFns.push(() => database.close())
43 let now = 1_000
44 const persistence = createCapacitorSQLitePersistence({
45 database,
46 cacheGenerationClaimTtlMs: 1_234,
47 now: () => now,
48 })
49 const adapter = persistence.resolvePersistenceForCollection!({
50 collectionId: `claim-options`,
51 mode: `sync-present`,
52 schemaVersion: undefined,
53 }).adapter
54 const claim = await adapter.claimCacheGeneration!(`claim-options`)
55 expect(claim.expiresAtMs).toBe(2_234)
56 now = 2_234
57 expect(
58 await adapter.renewCacheGenerationClaim!(
59 claim.storageCollectionId,
60 claim.claimId,
61 ),
62 ).toBeUndefined()
63})
64
65it(`persists data across app restart (close and reopen)`, async () => {
66 const dbPath = createTempSqlitePath()
67 const collectionId = `todos-restart`
68
69 const firstDatabase = createCapacitorSQLiteTestDatabase({ filename: dbPath })
70 const firstPersistence = createCapacitorSQLitePersistence({
71 database: firstDatabase,
72 })
73 const firstAdapter = firstPersistence.adapter
74
75 await firstAdapter.applyCommittedTx(
76 { kind: `eager`, collectionId: collectionId },
77 {
78 txId: `tx-restart-1`,
79 term: 1,
80 seq: 1,
81 rowVersion: 1,
82 mutations: [
83 {
84 type: `insert`,
85 key: `1`,
86 value: {
87 id: `1`,
88 title: `Survives restart`,
89 score: 10,
90 },
91 },
92 ],
93 },
94 )
95 await firstDatabase.close()
96
97 const secondDatabase = createCapacitorSQLiteTestDatabase({ filename: dbPath })
98 activeCleanupFns.push(() => secondDatabase.close())
99 const secondPersistence = createCapacitorSQLitePersistence({
100 database: secondDatabase,
101 })
102 const secondAdapter = secondPersistence.adapter
103
104 const rows = await secondAdapter.loadSubset(
105 { kind: `eager`, collectionId: collectionId },
106 {},
107 )
108 expect(rows).toEqual([
109 {
110 key: `1`,
111 value: {
112 id: `1`,
113 title: `Survives restart`,
114 score: 10,
115 },
116 },
117 ])
118})
119
120it(`keeps all committed rows under rapid mutation bursts`, async () => {
121 const dbPath = createTempSqlitePath()
122 const collectionId = `todos-burst`
123 const database = createCapacitorSQLiteTestDatabase({ filename: dbPath })
124 activeCleanupFns.push(() => database.close())
125
126 const persistence = createCapacitorSQLitePersistence({
127 database,
128 })
129 const adapter = persistence.adapter
130
131 const burstSize = 50
132 for (let index = 0; index < burstSize; index++) {
133 const rowId = String(index + 1)
134 await adapter.applyCommittedTx(
135 { kind: `eager`, collectionId: collectionId },
136 {
137 txId: `tx-burst-${rowId}`,
138 term: 1,
139 seq: index + 1,
140 rowVersion: index + 1,
141 mutations: [
142 {
143 type: `insert`,
144 key: rowId,
145 value: {
146 id: rowId,
147 title: `Todo ${rowId}`,
148 score: index,
149 },
150 },
151 ],
152 },
153 )
154 }
155
156 const rows = await adapter.loadSubset(
157 { kind: `eager`, collectionId: collectionId },
158 {},
159 )
160 expect(rows).toHaveLength(burstSize)
161})
162
163it(`shares persistence across multiple collections on one database`, async () => {
164 const dbPath = createTempSqlitePath()
165 const database = createCapacitorSQLiteTestDatabase({ filename: dbPath })
166 activeCleanupFns.push(() => database.close())
167
168 const persistence = createCapacitorSQLitePersistence({
169 database,
170 })
171
172 await persistence.adapter.applyCommittedTx(
173 { kind: `eager`, collectionId: `todos-a` },
174 {
175 txId: `tx-a-1`,
176 term: 1,
177 seq: 1,
178 rowVersion: 1,
179 mutations: [
180 {
181 type: `insert`,
182 key: `a1`,
183 value: {
184 id: `a1`,
185 title: `A`,
186 score: 1,
187 },
188 },
189 ],
190 },
191 )
192
193 await persistence.adapter.applyCommittedTx(
194 { kind: `eager`, collectionId: `todos-b` },
195 {
196 txId: `tx-b-1`,
197 term: 1,
198 seq: 1,
199 rowVersion: 1,
200 mutations: [
201 {
202 type: `insert`,
203 key: `b1`,
204 value: {
205 id: `b1`,
206 title: `B`,
207 score: 2,
208 },
209 },
210 ],
211 },
212 )
213
214 const rowsA = await persistence.adapter.loadSubset(
215 { kind: `eager`, collectionId: `todos-a` },
216 {},
217 )
218 const rowsB = await persistence.adapter.loadSubset(
219 { kind: `eager`, collectionId: `todos-b` },
220 {},
221 )
222
223 expect(rowsA.map((row) => row.key)).toEqual([`a1`])
224 expect(rowsB.map((row) => row.key)).toEqual([`b1`])
225})
226
227it(`resumes persisted sync after simulated app lifecycle transitions`, async () => {
228 const dbPath = createTempSqlitePath()
229 const collectionId = `todos-lifecycle`
230 const database = createCapacitorSQLiteTestDatabase({ filename: dbPath })
231 activeCleanupFns.push(() => database.close())
232
233 const persistence = createCapacitorSQLitePersistence({
234 database,
235 })
236 const collection = createCollection(
237 persistedCollectionOptions<Todo, string>({
238 id: collectionId,
239 getKey: (todo) => todo.id,
240 persistence,
241 syncMode: `eager`,
242 }),
243 )
244 activeCleanupFns.push(() => collection.cleanup())
245
246 await collection.stateWhenReady()
247
248 const initialInsert = collection.insert({
249 id: `1`,
250 title: `Before background`,
251 score: 1,
252 })
253 await initialInsert.when(`settled`)
254
255 await collection.cleanup()
256 collection.startSyncImmediate()
257 await collection.stateWhenReady()
258
259 const postResumeInsert = collection.insert({
260 id: `2`,
261 title: `Post resume write`,
262 score: 2,
263 })
264 await postResumeInsert.when(`settled`)
265
266 const persistedRows = await persistence.adapter.loadSubset(
267 { kind: `eager`, collectionId: collectionId },
268 {},
269 )
270 expect(persistedRows).toEqual(
271 expect.arrayContaining([
272 expect.objectContaining({ key: `1` }),
273 expect.objectContaining({ key: `2` }),
274 ]),
275 )
276})