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

electron-persisted-collection.e2e.test.ts

362 lines9.9 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 '@tanstack/db-sqlite-persistence-core'
7import { createNodeSQLitePersistence } from '@tanstack/node-db-sqlite-persistence'
8import { BetterSqlite3SQLiteDriver } from '../../node-db-sqlite-persistence/src/node-driver'
9import {
10 createElectronSQLitePersistence,
11 exposeElectronSQLitePersistence,
12} from '../src'
13import {
14 captureSeedData,
15 generateSeedData,
16} from '../../db-collection-e2e/src/fixtures/seed-data'
17import { runPersistedCollectionConformanceSuite } from '../../db-sqlite-persistence-core/tests/contracts/persisted-collection-conformance-contract'
18import {
19 createElectronRuntimeBridgeInvoke,
20 isElectronFullE2EEnabled,
21} from './e2e/electron-process-client'
22import type { PersistedTx } from '@tanstack/db-sqlite-persistence-core'
23import type { Collection } from '@tanstack/db'
24import type {
25 ElectronPersistenceInvoke,
26 ElectronPersistenceRequestEnvelope,
27 ElectronPersistenceResponseEnvelope,
28} from '../src/protocol'
29import type {
30 Comment,
31 E2ETestConfig,
32 Post,
33 User,
34} from '../../db-collection-e2e/src/types'
35​
36type PersistableRow = {
37 id: string
39​
40type ElectronPersistedCollectionTestConfig = E2ETestConfig
41type PersistedCollectionHarness<T extends PersistableRow> = {
42 collection: Collection<T, string | number>
43 seedPersisted: (rows: Array<T>) => Promise<void>
45​
46type InvokeHarness = {
47 invoke: ElectronPersistenceInvoke
48 close: () => void
50​
51let config: ElectronPersistedCollectionTestConfig | undefined
52​
53function createInvokeHarness(dbPath: string): InvokeHarness {
54 if (isElectronFullE2EEnabled()) {
55 return {
56 invoke: createElectronRuntimeBridgeInvoke({
57 dbPath,
58 collectionId: `seed`,
59 allowAnyCollectionId: true,
60 timeoutMs: 12_000,
61 }),
62 close: () => {},
63 }
64 }
65​
66 const driver = new BetterSqlite3SQLiteDriver({ filename: dbPath })
67 const persistence = createNodeSQLitePersistence({
68 database: driver.getDatabase(),
69 })
70 let handler:
71 | ((
72 event: unknown,
73 request: ElectronPersistenceRequestEnvelope,
74 ) => Promise<ElectronPersistenceResponseEnvelope>)
75 | undefined
76 const dispose = exposeElectronSQLitePersistence({
77 ipcMain: {
78 handle: (_channel, listener) => {
79 handler = listener
80 },
81 removeHandler: () => {},
82 },
83 persistence,
84 })
85​
86 return {
87 invoke: async (_channel, request) => {
88 if (!handler) {
89 throw new Error(`Electron IPC handler not registered`)
90 }
91 return handler(undefined, request)
92 },
93 close: () => {
94 dispose()
95 driver.close()
96 },
97 }
99​
100function createSeedTx<T extends PersistableRow>(
101 collectionId: string,
102 seedSequence: number,
103 rows: Array<T>,
104): PersistedTx<T, string | number> {
105 return {
106 txId: `seed-${collectionId}-${seedSequence}`,
107 term: 1,
108 seq: seedSequence,
109 rowVersion: seedSequence,
110 mutations: rows.map((row) => ({
111 type: `insert` as const,
112 key: row.id,
113 value: row,
114 })),
115 }
117​
118function createPersistedCollection<T extends PersistableRow>(
119 invoke: ElectronPersistenceInvoke,
120 id: string,
121 syncMode: `eager` | `on-demand`,
122): PersistedCollectionHarness<T> {
123 const persistence = createElectronSQLitePersistence({
124 invoke,
125 timeoutMs: isElectronFullE2EEnabled() ? 90_000 : undefined,
126 })
127 let seedSequence = 0
128 const seedPersisted = async (rows: Array<T>): Promise<void> => {
129 if (rows.length === 0) {
130 return
131 }
132 seedSequence++
133 await persistence.adapter.applyCommittedTx(
134 { kind: `eager`, collectionId: id },
135 createSeedTx(id, seedSequence, rows),
136 )
137 }
138​
139 const collection = createCollection(
140 persistedCollectionOptions<T, string | number>({
141 id,
142 syncMode,
143 getKey: (item) => item.id,
144 persistence,
145 autoIndex: `eager`,
146 defaultIndexType: BTreeIndex,
147 }),
148 )
149​
150 return {
151 collection,
152 seedPersisted,
153 }
155​
156type PersistedTransactionHandle = {
157 when: (state: 'settled') => Promise<unknown>
159​
160async function waitForPersisted(
161 transaction: PersistedTransactionHandle,
162): Promise<void> {
163 await transaction.when(`settled`)
165​
166async function seedCollection<T extends PersistableRow>(
167 collection: Collection<T, string | number>,
168 rows: Array<T>,
169): Promise<void> {
170 const tx = collection.insert(rows)
171 await waitForPersisted(tx)
173​
174async function insertRowIntoCollections<T extends PersistableRow>(
175 collections: ReadonlyArray<Collection<T, string | number>>,
176 row: T,
177): Promise<void> {
178 for (const collection of collections) {
179 const tx = collection.insert(row)
180 await waitForPersisted(tx)
181 }
183​
184async function updateRowAcrossCollections<T extends PersistableRow>(
185 collections: ReadonlyArray<Collection<T, string | number>>,
186 id: string,
187 updates: Partial<T>,
188): Promise<void> {
189 for (const collection of collections) {
190 if (!collection.has(id)) {
191 continue
192 }
193 const tx = collection.update(id, (draft) => {
194 Object.assign(draft, updates)
195 })
196 await waitForPersisted(tx)
197 }
199​
200async function deleteRowAcrossCollections<T extends PersistableRow>(
201 collections: ReadonlyArray<Collection<T, string | number>>,
202 id: string,
203): Promise<void> {
204 for (const collection of collections) {
205 if (!collection.has(id)) {
206 continue
207 }
208 const tx = collection.delete(id)
209 await waitForPersisted(tx)
210 }
212​
213beforeAll(async () => {
214 const tempDirectory = mkdtempSync(
215 join(tmpdir(), `db-electron-persisted-e2e-`),
216 )
217 const dbPath = join(tempDirectory, `state.sqlite`)
218 const suiteId = Date.now().toString(36)
219 const invokeHarness = createInvokeHarness(dbPath)
220 const seedData = generateSeedData()
221 const fixture = captureSeedData(seedData, {
222 registration:
223 'packages/electron-db-sqlite-persistence/tests/electron-persisted-collection.e2e.test.ts',
224 provider: 'Electron invoke test harness',
225 })
226​
227 const eagerUsers = createPersistedCollection<User>(
228 invokeHarness.invoke,
229 `electron-persisted-users-eager-${suiteId}`,
230 `eager`,
231 )
232 const eagerPosts = createPersistedCollection<Post>(
233 invokeHarness.invoke,
234 `electron-persisted-posts-eager-${suiteId}`,
235 `eager`,
236 )
237 const eagerComments = createPersistedCollection<Comment>(
238 invokeHarness.invoke,
239 `electron-persisted-comments-eager-${suiteId}`,
240 `eager`,
241 )
242 const onDemandUsers = createPersistedCollection<User>(
243 invokeHarness.invoke,
244 `electron-persisted-users-ondemand-${suiteId}`,
245 `on-demand`,
246 )
247 const onDemandPosts = createPersistedCollection<Post>(
248 invokeHarness.invoke,
249 `electron-persisted-posts-ondemand-${suiteId}`,
250 `on-demand`,
251 )
252 const onDemandComments = createPersistedCollection<Comment>(
253 invokeHarness.invoke,
254 `electron-persisted-comments-ondemand-${suiteId}`,
255 `on-demand`,
256 )
257​
258 await eagerUsers.collection.preload()
259 await eagerPosts.collection.preload()
260 await eagerComments.collection.preload()
261​
262 await seedCollection(eagerUsers.collection, seedData.users)
263 await seedCollection(eagerPosts.collection, seedData.posts)
264 await seedCollection(eagerComments.collection, seedData.comments)
265 await onDemandUsers.seedPersisted(seedData.users)
266 await onDemandPosts.seedPersisted(seedData.posts)
267 await onDemandComments.seedPersisted(seedData.comments)
268​
269 config = {
270 fixture,
271 collections: {
272 eager: {
273 users: eagerUsers.collection,
274 posts: eagerPosts.collection,
275 comments: eagerComments.collection,
276 },
277 onDemand: {
278 users: onDemandUsers.collection,
279 posts: onDemandPosts.collection,
280 comments: onDemandComments.collection,
281 },
282 },
283 mutations: {
284 insertUser: async (user) =>
285 insertRowIntoCollections(
286 [eagerUsers.collection, onDemandUsers.collection],
287 user,
288 ),
289 updateUser: async (id, updates) =>
290 updateRowAcrossCollections(
291 [eagerUsers.collection, onDemandUsers.collection],
292 id,
293 updates,
294 ),
295 deleteUser: async (id) =>
296 deleteRowAcrossCollections(
297 [eagerUsers.collection, onDemandUsers.collection],
298 id,
299 ),
300 insertPost: async (post) =>
301 insertRowIntoCollections(
302 [eagerPosts.collection, onDemandPosts.collection],
303 post,
304 ),
305 deletePost: async (id) =>
306 deleteRowAcrossCollections(
307 [eagerPosts.collection, onDemandPosts.collection],
308 id,
309 ),
310 },
311 setup: async () => {},
312 afterEach: async () => {
313 await onDemandUsers.collection.cleanup()
314 await onDemandPosts.collection.cleanup()
315 await onDemandComments.collection.cleanup()
316​
317 onDemandUsers.collection.startSyncImmediate()
318 onDemandPosts.collection.startSyncImmediate()
319 onDemandComments.collection.startSyncImmediate()
320 },
321 teardown: async () => {
322 await eagerUsers.collection.cleanup()
323 await eagerPosts.collection.cleanup()
324 await eagerComments.collection.cleanup()
325 await onDemandUsers.collection.cleanup()
326 await onDemandPosts.collection.cleanup()
327 await onDemandComments.collection.cleanup()
328 invokeHarness.close()
329 rmSync(tempDirectory, { recursive: true, force: true })
330 },
331 }
332})
333​
334afterEach(async () => {
335 if (config?.afterEach) {
336 await config.afterEach()
337 }
338})
339​
340afterAll(async () => {
341 if (config) {
342 await config.teardown()
343 }
344})
345​
346function getConfig(): Promise<ElectronPersistedCollectionTestConfig> {
347 if (!config) {
348 throw new Error(
349 `Electron persisted collection conformance is not initialized`,
350 )
351 }
352 return Promise.resolve(config)
354​
355const conformanceMode = isElectronFullE2EEnabled()
356 ? `real electron ipc`
357 : `in-process invoke`
358​
359runPersistedCollectionConformanceSuite(
360 `electron persisted collection conformance (${conformanceMode})`,
361 getConfig,