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

electron-persisted-collection.e2e.test.ts

364 lines9.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 { 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 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 isPersisted: {
158 promise: Promise<unknown>
159 }
161​
162async function waitForPersisted(
163 transaction: PersistedTransactionHandle,
164): Promise<void> {
165 await transaction.isPersisted.promise
167​
168async function seedCollection<T extends PersistableRow>(
169 collection: Collection<T, string | number>,
170 rows: Array<T>,
171): Promise<void> {
172 const tx = collection.insert(rows)
173 await waitForPersisted(tx)
175​
176async function insertRowIntoCollections<T extends PersistableRow>(
177 collections: ReadonlyArray<Collection<T, string | number>>,
178 row: T,
179): Promise<void> {
180 for (const collection of collections) {
181 const tx = collection.insert(row)
182 await waitForPersisted(tx)
183 }
185​
186async function updateRowAcrossCollections<T extends PersistableRow>(
187 collections: ReadonlyArray<Collection<T, string | number>>,
188 id: string,
189 updates: Partial<T>,
190): Promise<void> {
191 for (const collection of collections) {
192 if (!collection.has(id)) {
193 continue
194 }
195 const tx = collection.update(id, (draft) => {
196 Object.assign(draft, updates)
197 })
198 await waitForPersisted(tx)
199 }
201​
202async function deleteRowAcrossCollections<T extends PersistableRow>(
203 collections: ReadonlyArray<Collection<T, string | number>>,
204 id: string,
205): Promise<void> {
206 for (const collection of collections) {
207 if (!collection.has(id)) {
208 continue
209 }
210 const tx = collection.delete(id)
211 await waitForPersisted(tx)
212 }
214​
215beforeAll(async () => {
216 const tempDirectory = mkdtempSync(
217 join(tmpdir(), `db-electron-persisted-e2e-`),
218 )
219 const dbPath = join(tempDirectory, `state.sqlite`)
220 const suiteId = Date.now().toString(36)
221 const invokeHarness = createInvokeHarness(dbPath)
222 const seedData = generateSeedData()
223 const fixture = captureSeedData(seedData, {
224 registration:
225 'packages/electron-db-sqlite-persistence/tests/electron-persisted-collection.e2e.test.ts',
226 provider: 'Electron invoke test harness',
227 })
228​
229 const eagerUsers = createPersistedCollection<User>(
230 invokeHarness.invoke,
231 `electron-persisted-users-eager-${suiteId}`,
232 `eager`,
233 )
234 const eagerPosts = createPersistedCollection<Post>(
235 invokeHarness.invoke,
236 `electron-persisted-posts-eager-${suiteId}`,
237 `eager`,
238 )
239 const eagerComments = createPersistedCollection<Comment>(
240 invokeHarness.invoke,
241 `electron-persisted-comments-eager-${suiteId}`,
242 `eager`,
243 )
244 const onDemandUsers = createPersistedCollection<User>(
245 invokeHarness.invoke,
246 `electron-persisted-users-ondemand-${suiteId}`,
247 `on-demand`,
248 )
249 const onDemandPosts = createPersistedCollection<Post>(
250 invokeHarness.invoke,
251 `electron-persisted-posts-ondemand-${suiteId}`,
252 `on-demand`,
253 )
254 const onDemandComments = createPersistedCollection<Comment>(
255 invokeHarness.invoke,
256 `electron-persisted-comments-ondemand-${suiteId}`,
257 `on-demand`,
258 )
259​
260 await eagerUsers.collection.preload()
261 await eagerPosts.collection.preload()
262 await eagerComments.collection.preload()
263​
264 await seedCollection(eagerUsers.collection, seedData.users)
265 await seedCollection(eagerPosts.collection, seedData.posts)
266 await seedCollection(eagerComments.collection, seedData.comments)
267 await onDemandUsers.seedPersisted(seedData.users)
268 await onDemandPosts.seedPersisted(seedData.posts)
269 await onDemandComments.seedPersisted(seedData.comments)
270​
271 config = {
272 fixture,
273 collections: {
274 eager: {
275 users: eagerUsers.collection,
276 posts: eagerPosts.collection,
277 comments: eagerComments.collection,
278 },
279 onDemand: {
280 users: onDemandUsers.collection,
281 posts: onDemandPosts.collection,
282 comments: onDemandComments.collection,
283 },
284 },
285 mutations: {
286 insertUser: async (user) =>
287 insertRowIntoCollections(
288 [eagerUsers.collection, onDemandUsers.collection],
289 user,
290 ),
291 updateUser: async (id, updates) =>
292 updateRowAcrossCollections(
293 [eagerUsers.collection, onDemandUsers.collection],
294 id,
295 updates,
296 ),
297 deleteUser: async (id) =>
298 deleteRowAcrossCollections(
299 [eagerUsers.collection, onDemandUsers.collection],
300 id,
301 ),
302 insertPost: async (post) =>
303 insertRowIntoCollections(
304 [eagerPosts.collection, onDemandPosts.collection],
305 post,
306 ),
307 deletePost: async (id) =>
308 deleteRowAcrossCollections(
309 [eagerPosts.collection, onDemandPosts.collection],
310 id,
311 ),
312 },
313 setup: async () => {},
314 afterEach: async () => {
315 await onDemandUsers.collection.cleanup()
316 await onDemandPosts.collection.cleanup()
317 await onDemandComments.collection.cleanup()
318​
319 onDemandUsers.collection.startSyncImmediate()
320 onDemandPosts.collection.startSyncImmediate()
321 onDemandComments.collection.startSyncImmediate()
322 },
323 teardown: async () => {
324 await eagerUsers.collection.cleanup()
325 await eagerPosts.collection.cleanup()
326 await eagerComments.collection.cleanup()
327 await onDemandUsers.collection.cleanup()
328 await onDemandPosts.collection.cleanup()
329 await onDemandComments.collection.cleanup()
330 invokeHarness.close()
331 rmSync(tempDirectory, { recursive: true, force: true })
332 },
333 }
334})
335​
336afterEach(async () => {
337 if (config?.afterEach) {
338 await config.afterEach()
339 }
340})
341​
342afterAll(async () => {
343 if (config) {
344 await config.teardown()
345 }
346})
347​
348function getConfig(): Promise<ElectronPersistedCollectionTestConfig> {
349 if (!config) {
350 throw new Error(
351 `Electron persisted collection conformance is not initialized`,
352 )
353 }
354 return Promise.resolve(config)
356​
357const conformanceMode = isElectronFullE2EEnabled()
358 ? `real electron ipc`
359 : `in-process invoke`
360​
361runPersistedCollectionConformanceSuite(
362 `electron persisted collection conformance (${conformanceMode})`,
363 getConfig,