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 { generateSeedData } from '../../db-collection-e2e/src/fixtures/seed-data'
11import { runPersistedCollectionConformanceSuite } from '../../db-sqlite-persistence-core/tests/contracts/persisted-collection-conformance-contract'
12import { createWASQLiteTestDatabase } from '../tests/helpers/wa-sqlite-test-db'
13import type { Collection } from '@tanstack/db'
14import type { BrowserWASQLiteDatabase } from '../src'
15import type {
16 Comment,
17 E2ETestConfig,
18 Post,
19 User,
20} from '../../db-collection-e2e/src/types'
21
22type PersistableRow = {
23 id: string
24}
25
26type BrowserPersistedCollectionTestConfig = E2ETestConfig
27type PersistedCollectionHarness<T extends PersistableRow> = {
28 collection: Collection<T, string | number>
29 seedPersisted: (rows: Array<T>) => Promise<void>
30}
31
32let config: BrowserPersistedCollectionTestConfig
33
34function createPersistedCollection<T extends PersistableRow>(
35 database: BrowserWASQLiteDatabase,
36 id: string,
37 syncMode: `eager` | `on-demand`,
38): PersistedCollectionHarness<T> {
39 const persistence = createBrowserWASQLitePersistence({
40 database,
41 })
42 let seedTxSequence = 0
43 const seedPersisted = async (rows: Array<T>): Promise<void> => {
44 if (rows.length === 0) {
45 return
46 }
47 seedTxSequence++
48 await persistence.adapter.applyCommittedTx(id, {
49 txId: `seed-${id}-${seedTxSequence}`,
50 term: 1,
51 seq: seedTxSequence,
52 rowVersion: seedTxSequence,
53 mutations: rows.map((row) => ({
54 type: `insert` as const,
55 key: row.id,
56 value: row,
57 })),
58 })
59 }
60
61 const collection = createCollection(
62 persistedCollectionOptions<T, string | number>({
63 id,
64 syncMode,
65 getKey: (item) => item.id,
66 persistence,
67 autoIndex: `eager`,
68 defaultIndexType: BTreeIndex,
69 }),
70 )
71
72 return {
73 collection,
74 seedPersisted,
75 }
76}
77
78type PersistedTransactionHandle = {
79 isPersisted: {
80 promise: Promise<unknown>
81 }
82}
83
84async function waitForPersisted(
85 transaction: PersistedTransactionHandle,
86): Promise<void> {
87 await transaction.isPersisted.promise
88}
89
90async function seedCollection<T extends PersistableRow>(
91 collection: Collection<T, string | number>,
92 rows: Array<T>,
93): Promise<void> {
94 const tx = collection.insert(rows)
95 await waitForPersisted(tx)
96}
97
98async function insertRowIntoCollections<T extends PersistableRow>(
99 collections: ReadonlyArray<Collection<T, string | number>>,
100 row: T,
101): Promise<void> {
102 for (const collection of collections) {
103 const tx = collection.insert(row)
104 await waitForPersisted(tx)
105 }
106}
107
108async function updateRowAcrossCollections<T extends PersistableRow>(
109 collections: ReadonlyArray<Collection<T, string | number>>,
110 id: string,
111 updates: Partial<T>,
112): Promise<void> {
113 for (const collection of collections) {
114 if (!collection.has(id)) {
115 continue
116 }
117 const tx = collection.update(id, (draft) => {
118 Object.assign(draft, updates)
119 })
120 await waitForPersisted(tx)
121 }
122}
123
124async function deleteRowAcrossCollections<T extends PersistableRow>(
125 collections: ReadonlyArray<Collection<T, string | number>>,
126 id: string,
127): Promise<void> {
128 for (const collection of collections) {
129 if (!collection.has(id)) {
130 continue
131 }
132 const tx = collection.delete(id)
133 await waitForPersisted(tx)
134 }
135}
136
137beforeAll(async () => {
138 const tempDirectory = mkdtempSync(join(tmpdir(), `db-browser-persisted-e2e-`))
139 const dbPath = join(tempDirectory, `state.sqlite`)
140 const suiteId = Date.now().toString(36)
141 const database = createWASQLiteTestDatabase({
142 filename: dbPath,
143 })
144 const seedData = generateSeedData()
145
146 const eagerUsers = createPersistedCollection<User>(
147 database,
148 `browser-persisted-users-eager-${suiteId}`,
149 `eager`,
150 )
151 const eagerPosts = createPersistedCollection<Post>(
152 database,
153 `browser-persisted-posts-eager-${suiteId}`,
154 `eager`,
155 )
156 const eagerComments = createPersistedCollection<Comment>(
157 database,
158 `browser-persisted-comments-eager-${suiteId}`,
159 `eager`,
160 )
161
162 const onDemandUsers = createPersistedCollection<User>(
163 database,
164 `browser-persisted-users-ondemand-${suiteId}`,
165 `on-demand`,
166 )
167 const onDemandPosts = createPersistedCollection<Post>(
168 database,
169 `browser-persisted-posts-ondemand-${suiteId}`,
170 `on-demand`,
171 )
172 const onDemandComments = createPersistedCollection<Comment>(
173 database,
174 `browser-persisted-comments-ondemand-${suiteId}`,
175 `on-demand`,
176 )
177
178 await Promise.all([
179 eagerUsers.collection.preload(),
180 eagerPosts.collection.preload(),
181 eagerComments.collection.preload(),
182 ])
183
184 await seedCollection(eagerUsers.collection, seedData.users)
185 await seedCollection(eagerPosts.collection, seedData.posts)
186 await seedCollection(eagerComments.collection, seedData.comments)
187 await onDemandUsers.seedPersisted(seedData.users)
188 await onDemandPosts.seedPersisted(seedData.posts)
189 await onDemandComments.seedPersisted(seedData.comments)
190
191 config = {
192 collections: {
193 eager: {
194 users: eagerUsers.collection,
195 posts: eagerPosts.collection,
196 comments: eagerComments.collection,
197 },
198 onDemand: {
199 users: onDemandUsers.collection,
200 posts: onDemandPosts.collection,
201 comments: onDemandComments.collection,
202 },
203 },
204 mutations: {
205 insertUser: async (user) =>
206 insertRowIntoCollections(
207 [eagerUsers.collection, onDemandUsers.collection],
208 user,
209 ),
210 updateUser: async (id, updates) =>
211 updateRowAcrossCollections(
212 [eagerUsers.collection, onDemandUsers.collection],
213 id,
214 updates,
215 ),
216 deleteUser: async (id) =>
217 deleteRowAcrossCollections(
218 [eagerUsers.collection, onDemandUsers.collection],
219 id,
220 ),
221 insertPost: async (post) =>
222 insertRowIntoCollections(
223 [eagerPosts.collection, onDemandPosts.collection],
224 post,
225 ),
226 },
227 setup: async () => {},
228 afterEach: async () => {
229 await Promise.all([
230 onDemandUsers.collection.cleanup(),
231 onDemandPosts.collection.cleanup(),
232 onDemandComments.collection.cleanup(),
233 ])
234
235 onDemandUsers.collection.startSyncImmediate()
236 onDemandPosts.collection.startSyncImmediate()
237 onDemandComments.collection.startSyncImmediate()
238 },
239 teardown: async () => {
240 await Promise.all([
241 eagerUsers.collection.cleanup(),
242 eagerPosts.collection.cleanup(),
243 eagerComments.collection.cleanup(),
244 onDemandUsers.collection.cleanup(),
245 onDemandPosts.collection.cleanup(),
246 onDemandComments.collection.cleanup(),
247 ])
248 await Promise.resolve(database.close?.())
249 rmSync(tempDirectory, { recursive: true, force: true })
250 },
251 }
252})
253
254afterEach(async () => {
255 if (config.afterEach) {
256 await config.afterEach()
257 }
258})
259
260afterAll(async () => {
261 await config.teardown()
262})
263
264function getConfig(): Promise<BrowserPersistedCollectionTestConfig> {
265 return Promise.resolve(config)
266}
267
268runPersistedCollectionConformanceSuite(
269 `browser single-tab persisted collection conformance`,
270 getConfig,
271)