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

browser-single-tab-persisted-collection.e2e.test.ts

286 lines7.8 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 {
7 createBrowserWASQLitePersistence,
8 persistedCollectionOptions,
9} from '../src'
10import {
11 captureSeedData,
12 generateSeedData,
13} from '../../db-collection-e2e/src/fixtures/seed-data'
14import { runPersistedCollectionConformanceSuite } from '../../db-sqlite-persistence-core/tests/contracts/persisted-collection-conformance-contract'
15import { createWASQLiteTestDatabase } from '../tests/helpers/wa-sqlite-test-db'
16import type { Collection } from '@tanstack/db'
17import type { BrowserWASQLiteDatabase } from '../src'
18import type {
19 Comment,
20 E2ETestConfig,
21 Post,
22 User,
23} from '../../db-collection-e2e/src/types'
24​
25type PersistableRow = {
26 id: string
28​
29type BrowserPersistedCollectionTestConfig = E2ETestConfig
30type PersistedCollectionHarness<T extends PersistableRow> = {
31 collection: Collection<T, string | number>
32 seedPersisted: (rows: Array<T>) => Promise<void>
34​
35let config: BrowserPersistedCollectionTestConfig
36​
37function createPersistedCollection<T extends PersistableRow>(
38 database: BrowserWASQLiteDatabase,
39 id: string,
40 syncMode: `eager` | `on-demand`,
41): PersistedCollectionHarness<T> {
42 const persistence = createBrowserWASQLitePersistence({
43 database,
44 })
45 let seedTxSequence = 0
46 const seedPersisted = async (rows: Array<T>): Promise<void> => {
47 if (rows.length === 0) {
48 return
49 }
50 seedTxSequence++
51 await persistence.adapter.applyCommittedTx(
52 { kind: `eager`, collectionId: id },
53 {
54 txId: `seed-${id}-${seedTxSequence}`,
55 term: 1,
56 seq: seedTxSequence,
57 rowVersion: seedTxSequence,
58 mutations: rows.map((row) => ({
59 type: `insert` as const,
60 key: row.id,
61 value: row,
62 })),
63 },
64 )
65 }
66​
67 const collection = createCollection(
68 persistedCollectionOptions<T, string | number>({
69 id,
70 syncMode,
71 getKey: (item) => item.id,
72 persistence,
73 autoIndex: `eager`,
74 defaultIndexType: BTreeIndex,
75 }),
76 )
77​
78 return {
79 collection,
80 seedPersisted,
81 }
83​
84type PersistedTransactionHandle = {
85 when: (state: 'settled') => Promise<unknown>
87​
88async function waitForPersisted(
89 transaction: PersistedTransactionHandle,
90): Promise<void> {
91 await transaction.when(`settled`)
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​
141beforeAll(async () => {
142 const tempDirectory = mkdtempSync(join(tmpdir(), `db-browser-persisted-e2e-`))
143 const dbPath = join(tempDirectory, `state.sqlite`)
144 const suiteId = Date.now().toString(36)
145 const database = createWASQLiteTestDatabase({
146 filename: dbPath,
147 })
148 const seedData = generateSeedData()
149 const fixture = captureSeedData(seedData, {
150 registration:
151 'packages/browser-db-sqlite-persistence/e2e/browser-single-tab-persisted-collection.e2e.test.ts',
152 provider: 'WASQLite test database fixture',
153 })
154​
155 const eagerUsers = createPersistedCollection<User>(
156 database,
157 `browser-persisted-users-eager-${suiteId}`,
158 `eager`,
159 )
160 const eagerPosts = createPersistedCollection<Post>(
161 database,
162 `browser-persisted-posts-eager-${suiteId}`,
163 `eager`,
164 )
165 const eagerComments = createPersistedCollection<Comment>(
166 database,
167 `browser-persisted-comments-eager-${suiteId}`,
168 `eager`,
169 )
170​
171 const onDemandUsers = createPersistedCollection<User>(
172 database,
173 `browser-persisted-users-ondemand-${suiteId}`,
174 `on-demand`,
175 )
176 const onDemandPosts = createPersistedCollection<Post>(
177 database,
178 `browser-persisted-posts-ondemand-${suiteId}`,
179 `on-demand`,
180 )
181 const onDemandComments = createPersistedCollection<Comment>(
182 database,
183 `browser-persisted-comments-ondemand-${suiteId}`,
184 `on-demand`,
185 )
186​
187 await Promise.all([
188 eagerUsers.collection.preload(),
189 eagerPosts.collection.preload(),
190 eagerComments.collection.preload(),
191 ])
192​
193 await seedCollection(eagerUsers.collection, seedData.users)
194 await seedCollection(eagerPosts.collection, seedData.posts)
195 await seedCollection(eagerComments.collection, seedData.comments)
196 await onDemandUsers.seedPersisted(seedData.users)
197 await onDemandPosts.seedPersisted(seedData.posts)
198 await onDemandComments.seedPersisted(seedData.comments)
199​
200 config = {
201 fixture,
202 collections: {
203 eager: {
204 users: eagerUsers.collection,
205 posts: eagerPosts.collection,
206 comments: eagerComments.collection,
207 },
208 onDemand: {
209 users: onDemandUsers.collection,
210 posts: onDemandPosts.collection,
211 comments: onDemandComments.collection,
212 },
213 },
214 mutations: {
215 insertUser: async (user) =>
216 insertRowIntoCollections(
217 [eagerUsers.collection, onDemandUsers.collection],
218 user,
219 ),
220 updateUser: async (id, updates) =>
221 updateRowAcrossCollections(
222 [eagerUsers.collection, onDemandUsers.collection],
223 id,
224 updates,
225 ),
226 deleteUser: async (id) =>
227 deleteRowAcrossCollections(
228 [eagerUsers.collection, onDemandUsers.collection],
229 id,
230 ),
231 insertPost: async (post) =>
232 insertRowIntoCollections(
233 [eagerPosts.collection, onDemandPosts.collection],
234 post,
235 ),
236 deletePost: async (id) =>
237 deleteRowAcrossCollections(
238 [eagerPosts.collection, onDemandPosts.collection],
239 id,
240 ),
241 },
242 setup: async () => {},
243 afterEach: async () => {
244 await Promise.all([
245 onDemandUsers.collection.cleanup(),
246 onDemandPosts.collection.cleanup(),
247 onDemandComments.collection.cleanup(),
248 ])
249​
250 onDemandUsers.collection.startSyncImmediate()
251 onDemandPosts.collection.startSyncImmediate()
252 onDemandComments.collection.startSyncImmediate()
253 },
254 teardown: async () => {
255 await Promise.all([
256 eagerUsers.collection.cleanup(),
257 eagerPosts.collection.cleanup(),
258 eagerComments.collection.cleanup(),
259 onDemandUsers.collection.cleanup(),
260 onDemandPosts.collection.cleanup(),
261 onDemandComments.collection.cleanup(),
262 ])
263 await Promise.resolve(database.close?.())
264 rmSync(tempDirectory, { recursive: true, force: true })
265 },
266 }
267})
268​
269afterEach(async () => {
270 if (config.afterEach) {
271 await config.afterEach()
272 }
273})
274​
275afterAll(async () => {
276 await config.teardown()
277})
278​
279function getConfig(): Promise<BrowserPersistedCollectionTestConfig> {
280 return Promise.resolve(config)
282​
283runPersistedCollectionConformanceSuite(
284 `browser single-tab persisted collection conformance`,
285 getConfig,