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

mobile-persisted-collection-conformance-suite.ts

302 lines8.6 KB

1import { mkdtempSync, rmSync } from 'node:fs'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { afterAll, afterEach, beforeAll } from 'vitest'
5import { BTreeIndex, createCollection } from '@tanstack/db'
6import { persistedCollectionOptions } from '../src'
7import {
8 captureSeedData,
9 generateSeedData,
10} from '../../db-collection-e2e/src/fixtures/seed-data'
11import { runPersistedCollectionConformanceSuite } from '../../db-sqlite-persistence-core/tests/contracts/persisted-collection-conformance-contract'
12import { createOpSQLiteTestDatabase } from '../tests/helpers/op-sqlite-test-db'
13import type { Collection } from '@tanstack/db'
14import type { PersistedCollectionPersistence } from '@tanstack/db-sqlite-persistence-core'
15import type {
16 Comment,
17 E2ETestConfig,
18 Post,
19 User,
20} from '../../db-collection-e2e/src/types'
21​
22type PersistableRow = {
23 id: string
25​
26type MobilePersistedCollectionTestConfig = E2ETestConfig
27type PersistedCollectionHarness<T extends PersistableRow> = {
28 collection: Collection<T, string | number>
29 seedPersisted: (rows: Array<T>) => Promise<void>
31​
32type MobilePersistenceFactory = (
33 database: ReturnType<typeof createOpSQLiteTestDatabase>,
34) => PersistedCollectionPersistence
35​
36function createPersistedCollection<T extends PersistableRow>(
37 database: ReturnType<typeof createOpSQLiteTestDatabase>,
38 id: string,
39 syncMode: `eager` | `on-demand`,
40 createPersistence: MobilePersistenceFactory,
41): PersistedCollectionHarness<T> {
42 const persistence = createPersistence(database)
43 let seedTxSequence = 0
44 const seedPersisted = async (rows: Array<T>): Promise<void> => {
45 if (rows.length === 0) {
46 return
47 }
48 seedTxSequence++
49 await persistence.adapter.applyCommittedTx(
50 { kind: `eager`, collectionId: id },
51 {
52 txId: `seed-${id}-${seedTxSequence}`,
53 term: 1,
54 seq: seedTxSequence,
55 rowVersion: seedTxSequence,
56 mutations: rows.map((row) => ({
57 type: `insert` as const,
58 key: row.id,
59 value: row,
60 })),
61 },
62 )
63 }
64​
65 const collection = createCollection(
66 persistedCollectionOptions<T, string | number>({
67 id,
68 syncMode,
69 getKey: (item) => item.id,
70 persistence,
71 autoIndex: `eager`,
72 defaultIndexType: BTreeIndex,
73 }),
74 )
75​
76 return {
77 collection,
78 seedPersisted,
79 }
81​
82type PersistedTransactionHandle = {
83 when: (state: 'settled') => Promise<unknown>
85​
86async function waitForPersisted(
87 transaction: PersistedTransactionHandle,
88): Promise<void> {
89 await transaction.when(`settled`)
91​
92async function seedCollection<T extends PersistableRow>(
93 collection: Collection<T, string | number>,
94 rows: Array<T>,
95): Promise<void> {
96 const tx = collection.insert(rows)
97 await waitForPersisted(tx)
99​
100async function insertRowIntoCollections<T extends PersistableRow>(
101 collections: ReadonlyArray<Collection<T, string | number>>,
102 row: T,
103): Promise<void> {
104 for (const collection of collections) {
105 const tx = collection.insert(row)
106 await waitForPersisted(tx)
107 }
109​
110async function updateRowAcrossCollections<T extends PersistableRow>(
111 collections: ReadonlyArray<Collection<T, string | number>>,
112 id: string,
113 updates: Partial<T>,
114): Promise<void> {
115 for (const collection of collections) {
116 if (!collection.has(id)) {
117 continue
118 }
119 const tx = collection.update(id, (draft) => {
120 Object.assign(draft, updates)
121 })
122 await waitForPersisted(tx)
123 }
125​
126async function deleteRowAcrossCollections<T extends PersistableRow>(
127 collections: ReadonlyArray<Collection<T, string | number>>,
128 id: string,
129): Promise<void> {
130 for (const collection of collections) {
131 if (!collection.has(id)) {
132 continue
133 }
134 const tx = collection.delete(id)
135 await waitForPersisted(tx)
136 }
138​
139export function runMobilePersistedCollectionConformanceSuite(
140 suiteName: string,
141 createPersistence: MobilePersistenceFactory,
142): void {
143 let config: MobilePersistedCollectionTestConfig | undefined
144​
145 beforeAll(async () => {
146 const tempDirectory = mkdtempSync(
147 join(tmpdir(), `db-rn-persisted-conformance-`),
148 )
149 const dbPath = join(tempDirectory, `state.sqlite`)
150 const suiteId = Date.now().toString(36)
151 const database = createOpSQLiteTestDatabase({
152 filename: dbPath,
153 resultShape: `statement-array`,
154 })
155 const seedData = generateSeedData()
156 const fixture = captureSeedData(seedData, {
157 registration:
158 'packages/react-native-db-sqlite-persistence/e2e/mobile-persisted-collection-conformance-suite.ts',
159 provider: 'React Native test database and supplied persistence factory',
160 })
161​
162 const eagerUsers = createPersistedCollection<User>(
163 database,
164 `mobile-persisted-users-eager-${suiteId}`,
165 `eager`,
166 createPersistence,
167 )
168 const eagerPosts = createPersistedCollection<Post>(
169 database,
170 `mobile-persisted-posts-eager-${suiteId}`,
171 `eager`,
172 createPersistence,
173 )
174 const eagerComments = createPersistedCollection<Comment>(
175 database,
176 `mobile-persisted-comments-eager-${suiteId}`,
177 `eager`,
178 createPersistence,
179 )
180​
181 const onDemandUsers = createPersistedCollection<User>(
182 database,
183 `mobile-persisted-users-ondemand-${suiteId}`,
184 `on-demand`,
185 createPersistence,
186 )
187 const onDemandPosts = createPersistedCollection<Post>(
188 database,
189 `mobile-persisted-posts-ondemand-${suiteId}`,
190 `on-demand`,
191 createPersistence,
192 )
193 const onDemandComments = createPersistedCollection<Comment>(
194 database,
195 `mobile-persisted-comments-ondemand-${suiteId}`,
196 `on-demand`,
197 createPersistence,
198 )
199​
200 await Promise.all([
201 eagerUsers.collection.preload(),
202 eagerPosts.collection.preload(),
203 eagerComments.collection.preload(),
204 ])
205​
206 await seedCollection(eagerUsers.collection, seedData.users)
207 await seedCollection(eagerPosts.collection, seedData.posts)
208 await seedCollection(eagerComments.collection, seedData.comments)
209 await onDemandUsers.seedPersisted(seedData.users)
210 await onDemandPosts.seedPersisted(seedData.posts)
211 await onDemandComments.seedPersisted(seedData.comments)
212​
213 config = {
214 fixture,
215 collections: {
216 eager: {
217 users: eagerUsers.collection,
218 posts: eagerPosts.collection,
219 comments: eagerComments.collection,
220 },
221 onDemand: {
222 users: onDemandUsers.collection,
223 posts: onDemandPosts.collection,
224 comments: onDemandComments.collection,
225 },
226 },
227 mutations: {
228 insertUser: async (user) =>
229 insertRowIntoCollections(
230 [eagerUsers.collection, onDemandUsers.collection],
231 user,
232 ),
233 updateUser: async (id, updates) =>
234 updateRowAcrossCollections(
235 [eagerUsers.collection, onDemandUsers.collection],
236 id,
237 updates,
238 ),
239 deleteUser: async (id) =>
240 deleteRowAcrossCollections(
241 [eagerUsers.collection, onDemandUsers.collection],
242 id,
243 ),
244 insertPost: async (post) =>
245 insertRowIntoCollections(
246 [eagerPosts.collection, onDemandPosts.collection],
247 post,
248 ),
249 deletePost: async (id) =>
250 deleteRowAcrossCollections(
251 [eagerPosts.collection, onDemandPosts.collection],
252 id,
253 ),
254 },
255 setup: async () => {},
256 afterEach: async () => {
257 await Promise.all([
258 onDemandUsers.collection.cleanup(),
259 onDemandPosts.collection.cleanup(),
260 onDemandComments.collection.cleanup(),
261 ])
262​
263 onDemandUsers.collection.startSyncImmediate()
264 onDemandPosts.collection.startSyncImmediate()
265 onDemandComments.collection.startSyncImmediate()
266 },
267 teardown: async () => {
268 await Promise.all([
269 eagerUsers.collection.cleanup(),
270 eagerPosts.collection.cleanup(),
271 eagerComments.collection.cleanup(),
272 onDemandUsers.collection.cleanup(),
273 onDemandPosts.collection.cleanup(),
274 onDemandComments.collection.cleanup(),
275 ])
276 await Promise.resolve(database.close())
277 rmSync(tempDirectory, { recursive: true, force: true })
278 },
279 }
280 })
281​
282 afterEach(async () => {
283 if (config?.afterEach) {
284 await config.afterEach()
285 }
286 })
287​
288 afterAll(async () => {
289 if (config) {
290 await config.teardown()
291 }
292 })
293​
294 function getConfig(): Promise<MobilePersistedCollectionTestConfig> {
295 if (!config) {
296 throw new Error(`${suiteName} config is not initialized`)
297 }
298 return Promise.resolve(config)
299 }
300​
301 runPersistedCollectionConformanceSuite(suiteName, getConfig)