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

mobile-persisted-collection-conformance-suite.ts

304 lines8.7 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 isPersisted: {
84 promise: Promise<unknown>
85 }
87​
88async function waitForPersisted(
89 transaction: PersistedTransactionHandle,
90): Promise<void> {
91 await transaction.isPersisted.promise
93​
94async function seedCollection<T extends PersistableRow>(
95 collection: Collection<T, string | number>,
96 rows: Array<T>,
97): Promise<void> {
98 const tx = collection.insert(rows)
99 await waitForPersisted(tx)
101​
102async function insertRowIntoCollections<T extends PersistableRow>(
103 collections: ReadonlyArray<Collection<T, string | number>>,
104 row: T,
105): Promise<void> {
106 for (const collection of collections) {
107 const tx = collection.insert(row)
108 await waitForPersisted(tx)
109 }
111​
112async function updateRowAcrossCollections<T extends PersistableRow>(
113 collections: ReadonlyArray<Collection<T, string | number>>,
114 id: string,
115 updates: Partial<T>,
116): Promise<void> {
117 for (const collection of collections) {
118 if (!collection.has(id)) {
119 continue
120 }
121 const tx = collection.update(id, (draft) => {
122 Object.assign(draft, updates)
123 })
124 await waitForPersisted(tx)
125 }
127​
128async function deleteRowAcrossCollections<T extends PersistableRow>(
129 collections: ReadonlyArray<Collection<T, string | number>>,
130 id: string,
131): Promise<void> {
132 for (const collection of collections) {
133 if (!collection.has(id)) {
134 continue
135 }
136 const tx = collection.delete(id)
137 await waitForPersisted(tx)
138 }
140​
141export function runMobilePersistedCollectionConformanceSuite(
142 suiteName: string,
143 createPersistence: MobilePersistenceFactory,
144): void {
145 let config: MobilePersistedCollectionTestConfig | undefined
146​
147 beforeAll(async () => {
148 const tempDirectory = mkdtempSync(
149 join(tmpdir(), `db-rn-persisted-conformance-`),
150 )
151 const dbPath = join(tempDirectory, `state.sqlite`)
152 const suiteId = Date.now().toString(36)
153 const database = createOpSQLiteTestDatabase({
154 filename: dbPath,
155 resultShape: `statement-array`,
156 })
157 const seedData = generateSeedData()
158 const fixture = captureSeedData(seedData, {
159 registration:
160 'packages/react-native-db-sqlite-persistence/e2e/mobile-persisted-collection-conformance-suite.ts',
161 provider: 'React Native test database and supplied persistence factory',
162 })
163​
164 const eagerUsers = createPersistedCollection<User>(
165 database,
166 `mobile-persisted-users-eager-${suiteId}`,
167 `eager`,
168 createPersistence,
169 )
170 const eagerPosts = createPersistedCollection<Post>(
171 database,
172 `mobile-persisted-posts-eager-${suiteId}`,
173 `eager`,
174 createPersistence,
175 )
176 const eagerComments = createPersistedCollection<Comment>(
177 database,
178 `mobile-persisted-comments-eager-${suiteId}`,
179 `eager`,
180 createPersistence,
181 )
182​
183 const onDemandUsers = createPersistedCollection<User>(
184 database,
185 `mobile-persisted-users-ondemand-${suiteId}`,
186 `on-demand`,
187 createPersistence,
188 )
189 const onDemandPosts = createPersistedCollection<Post>(
190 database,
191 `mobile-persisted-posts-ondemand-${suiteId}`,
192 `on-demand`,
193 createPersistence,
194 )
195 const onDemandComments = createPersistedCollection<Comment>(
196 database,
197 `mobile-persisted-comments-ondemand-${suiteId}`,
198 `on-demand`,
199 createPersistence,
200 )
201​
202 await Promise.all([
203 eagerUsers.collection.preload(),
204 eagerPosts.collection.preload(),
205 eagerComments.collection.preload(),
206 ])
207​
208 await seedCollection(eagerUsers.collection, seedData.users)
209 await seedCollection(eagerPosts.collection, seedData.posts)
210 await seedCollection(eagerComments.collection, seedData.comments)
211 await onDemandUsers.seedPersisted(seedData.users)
212 await onDemandPosts.seedPersisted(seedData.posts)
213 await onDemandComments.seedPersisted(seedData.comments)
214​
215 config = {
216 fixture,
217 collections: {
218 eager: {
219 users: eagerUsers.collection,
220 posts: eagerPosts.collection,
221 comments: eagerComments.collection,
222 },
223 onDemand: {
224 users: onDemandUsers.collection,
225 posts: onDemandPosts.collection,
226 comments: onDemandComments.collection,
227 },
228 },
229 mutations: {
230 insertUser: async (user) =>
231 insertRowIntoCollections(
232 [eagerUsers.collection, onDemandUsers.collection],
233 user,
234 ),
235 updateUser: async (id, updates) =>
236 updateRowAcrossCollections(
237 [eagerUsers.collection, onDemandUsers.collection],
238 id,
239 updates,
240 ),
241 deleteUser: async (id) =>
242 deleteRowAcrossCollections(
243 [eagerUsers.collection, onDemandUsers.collection],
244 id,
245 ),
246 insertPost: async (post) =>
247 insertRowIntoCollections(
248 [eagerPosts.collection, onDemandPosts.collection],
249 post,
250 ),
251 deletePost: async (id) =>
252 deleteRowAcrossCollections(
253 [eagerPosts.collection, onDemandPosts.collection],
254 id,
255 ),
256 },
257 setup: async () => {},
258 afterEach: async () => {
259 await Promise.all([
260 onDemandUsers.collection.cleanup(),
261 onDemandPosts.collection.cleanup(),
262 onDemandComments.collection.cleanup(),
263 ])
264​
265 onDemandUsers.collection.startSyncImmediate()
266 onDemandPosts.collection.startSyncImmediate()
267 onDemandComments.collection.startSyncImmediate()
268 },
269 teardown: async () => {
270 await Promise.all([
271 eagerUsers.collection.cleanup(),
272 eagerPosts.collection.cleanup(),
273 eagerComments.collection.cleanup(),
274 onDemandUsers.collection.cleanup(),
275 onDemandPosts.collection.cleanup(),
276 onDemandComments.collection.cleanup(),
277 ])
278 await Promise.resolve(database.close())
279 rmSync(tempDirectory, { recursive: true, force: true })
280 },
281 }
282 })
283​
284 afterEach(async () => {
285 if (config?.afterEach) {
286 await config.afterEach()
287 }
288 })
289​
290 afterAll(async () => {
291 if (config) {
292 await config.teardown()
293 }
294 })
295​
296 function getConfig(): Promise<MobilePersistedCollectionTestConfig> {
297 if (!config) {
298 throw new Error(`${suiteName} config is not initialized`)
299 }
300 return Promise.resolve(config)
301 }
302​
303 runPersistedCollectionConformanceSuite(suiteName, getConfig)