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