Open History to see the last commit
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
27}
28
29type BrowserPersistedCollectionTestConfig = E2ETestConfig
30type PersistedCollectionHarness<T extends PersistableRow> = {
31 collection: Collection<T, string | number>
32 seedPersisted: (rows: Array<T>) => Promise<void>
33}
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(id, {
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 const collection = createCollection(
65 persistedCollectionOptions<T, string | number>({
66 id,
67 syncMode,
68 getKey: (item) => item.id,
69 persistence,
70 autoIndex: `eager`,
71 defaultIndexType: BTreeIndex,
72 }),
73 )
74
75 return {
76 collection,
77 seedPersisted,
78 }
79}
80
81type PersistedTransactionHandle = {
82 isPersisted: {
83 promise: Promise<unknown>
84 }
85}
86
87async function waitForPersisted(
88 transaction: PersistedTransactionHandle,
89): Promise<void> {
90 await transaction.isPersisted.promise
91}
92
93async function seedCollection<T extends PersistableRow>(
94 collection: Collection<T, string | number>,
95 rows: Array<T>,
96): Promise<void> {
97 const tx = collection.insert(rows)
98 await waitForPersisted(tx)
99}
100
101async function insertRowIntoCollections<T extends PersistableRow>(
102 collections: ReadonlyArray<Collection<T, string | number>>,
103 row: T,
104): Promise<void> {
105 for (const collection of collections) {
106 const tx = collection.insert(row)
107 await waitForPersisted(tx)
108 }
109}
110
111async function updateRowAcrossCollections<T extends PersistableRow>(
112 collections: ReadonlyArray<Collection<T, string | number>>,
113 id: string,
114 updates: Partial<T>,
115): Promise<void> {
116 for (const collection of collections) {
117 if (!collection.has(id)) {
118 continue
119 }
120 const tx = collection.update(id, (draft) => {
121 Object.assign(draft, updates)
122 })
123 await waitForPersisted(tx)
124 }
125}
126
127async function deleteRowAcrossCollections<T extends PersistableRow>(
128 collections: ReadonlyArray<Collection<T, string | number>>,
129 id: string,
130): Promise<void> {
131 for (const collection of collections) {
132 if (!collection.has(id)) {
133 continue
134 }
135 const tx = collection.delete(id)
136 await waitForPersisted(tx)
137 }
138}
139
140beforeAll(async () => {
141 const tempDirectory = mkdtempSync(join(tmpdir(), `db-browser-persisted-e2e-`))
142 const dbPath = join(tempDirectory, `state.sqlite`)
143 const suiteId = Date.now().toString(36)
144 const database = createWASQLiteTestDatabase({
145 filename: dbPath,
146 })
147 const seedData = generateSeedData()
148 const fixture = captureSeedData(seedData, {
149 registration:
150 'packages/browser-db-sqlite-persistence/e2e/browser-single-tab-persisted-collection.e2e.test.ts',
151 provider: 'WASQLite test database fixture',
152 })
153
154 const eagerUsers = createPersistedCollection<User>(
155 database,
156 `browser-persisted-users-eager-${suiteId}`,
157 `eager`,
158 )
159 const eagerPosts = createPersistedCollection<Post>(
160 database,
161 `browser-persisted-posts-eager-${suiteId}`,
162 `eager`,
163 )
164 const eagerComments = createPersistedCollection<Comment>(
165 database,
166 `browser-persisted-comments-eager-${suiteId}`,
167 `eager`,
168 )
169
170 const onDemandUsers = createPersistedCollection<User>(
171 database,
172 `browser-persisted-users-ondemand-${suiteId}`,
173 `on-demand`,
174 )
175 const onDemandPosts = createPersistedCollection<Post>(
176 database,
177 `browser-persisted-posts-ondemand-${suiteId}`,
178 `on-demand`,
179 )
180 const onDemandComments = createPersistedCollection<Comment>(
181 database,
182 `browser-persisted-comments-ondemand-${suiteId}`,
183 `on-demand`,
184 )
185
186 await Promise.all([
187 eagerUsers.collection.preload(),
188 eagerPosts.collection.preload(),
189 eagerComments.collection.preload(),
190 ])
191
192 await seedCollection(eagerUsers.collection, seedData.users)
193 await seedCollection(eagerPosts.collection, seedData.posts)
194 await seedCollection(eagerComments.collection, seedData.comments)
195 await onDemandUsers.seedPersisted(seedData.users)
196 await onDemandPosts.seedPersisted(seedData.posts)
197 await onDemandComments.seedPersisted(seedData.comments)
198
199 config = {
200 fixture,
201 collections: {
202 eager: {
203 users: eagerUsers.collection,
204 posts: eagerPosts.collection,
205 comments: eagerComments.collection,
206 },
207 onDemand: {
208 users: onDemandUsers.collection,
209 posts: onDemandPosts.collection,
210 comments: onDemandComments.collection,
211 },
212 },
213 mutations: {
214 insertUser: async (user) =>
215 insertRowIntoCollections(
216 [eagerUsers.collection, onDemandUsers.collection],
217 user,
218 ),
219 updateUser: async (id, updates) =>
220 updateRowAcrossCollections(
221 [eagerUsers.collection, onDemandUsers.collection],
222 id,
223 updates,
224 ),
225 deleteUser: async (id) =>
226 deleteRowAcrossCollections(
227 [eagerUsers.collection, onDemandUsers.collection],
228 id,
229 ),
230 insertPost: async (post) =>
231 insertRowIntoCollections(
232 [eagerPosts.collection, onDemandPosts.collection],
233 post,
234 ),
235 deletePost: async (id) =>
236 deleteRowAcrossCollections(
237 [eagerPosts.collection, onDemandPosts.collection],
238 id,
239 ),
240 },
241 setup: async () => {},
242 afterEach: async () => {
243 await Promise.all([
244 onDemandUsers.collection.cleanup(),
245 onDemandPosts.collection.cleanup(),
246 onDemandComments.collection.cleanup(),
247 ])
248
249 onDemandUsers.collection.startSyncImmediate()
250 onDemandPosts.collection.startSyncImmediate()
251 onDemandComments.collection.startSyncImmediate()
252 },
253 teardown: async () => {
254 await Promise.all([
255 eagerUsers.collection.cleanup(),
256 eagerPosts.collection.cleanup(),
257 eagerComments.collection.cleanup(),
258 onDemandUsers.collection.cleanup(),
259 onDemandPosts.collection.cleanup(),
260 onDemandComments.collection.cleanup(),
261 ])
262 await Promise.resolve(database.close?.())
263 rmSync(tempDirectory, { recursive: true, force: true })
264 },
265 }
266})
267
268afterEach(async () => {
269 if (config.afterEach) {
270 await config.afterEach()
271 }
272})
273
274afterAll(async () => {
275 await config.teardown()
276})
277
278function getConfig(): Promise<BrowserPersistedCollectionTestConfig> {
279 return Promise.resolve(config)
280}
281
282runPersistedCollectionConformanceSuite(
283 `browser single-tab persisted collection conformance`,
284 getConfig,
285)