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

electron-ipc.test.ts

374 lines10.6 KB

1import { mkdtempSync, rmSync } from 'node:fs'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { afterEach, describe, expect, it } from 'vitest'
5import { InvalidPersistedCollectionConfigError } from '@tanstack/db-sqlite-persistence-core'
6import { createNodeSQLitePersistence } from '@tanstack/node-db-sqlite-persistence'
7import { BetterSqlite3SQLiteDriver } from '../../node-db-sqlite-persistence/src/node-driver'
8import {
9 createElectronSQLitePersistence,
10 exposeElectronSQLitePersistence,
11} from '../src'
12import {
13 DEFAULT_ELECTRON_PERSISTENCE_CHANNEL,
14 ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
15} from '../src/protocol'
16import {
17 createElectronRuntimeBridgeInvoke,
18 isElectronFullE2EEnabled,
19} from './e2e/electron-process-client'
20import type { PersistedCollectionPersistence } from '@tanstack/db-sqlite-persistence-core'
21import type {
22 ElectronPersistenceInvoke,
23 ElectronPersistenceRequestEnvelope,
24 ElectronPersistenceResponseEnvelope,
25} from '../src/protocol'
26​
27type InvokeHarness = {
28 invoke: ElectronPersistenceInvoke
29 close: () => void
31​
32type ElectronMainPersistence = PersistedCollectionPersistence
33​
34const electronRuntimeBridgeTimeoutMs = isElectronFullE2EEnabled()
35 ? 45_000
36 : 4_000
37​
38function createFilteredPersistence(
39 collectionId: string,
40 allowAnyCollectionId: boolean,
41 persistence: ElectronMainPersistence,
42): ElectronMainPersistence {
43 if (allowAnyCollectionId) {
44 return persistence
45 }
46​
47 const baseAdapter = persistence.adapter
48 const assertKnownCollection = (requestedCollectionId: string) => {
49 if (requestedCollectionId !== collectionId) {
50 const error = new Error(
51 `Unknown electron persistence collection "${requestedCollectionId}"`,
52 )
53 error.name = `UnknownElectronPersistenceCollectionError`
54 ;(error as Error & { code?: string }).code = `UNKNOWN_COLLECTION`
55 throw error
56 }
57 }
58​
59 const adapter: ElectronMainPersistence[`adapter`] = {
60 loadSubset: (requestedCollectionId, options, ctx) => {
61 assertKnownCollection(requestedCollectionId)
62 return baseAdapter.loadSubset(requestedCollectionId, options, ctx)
63 },
64 applyCommittedTx: (requestedCollectionId, tx) => {
65 assertKnownCollection(requestedCollectionId)
66 return baseAdapter.applyCommittedTx(requestedCollectionId, tx)
67 },
68 ensureIndex: (requestedCollectionId, signature, spec) => {
69 assertKnownCollection(requestedCollectionId)
70 return baseAdapter.ensureIndex(requestedCollectionId, signature, spec)
71 },
72 markIndexRemoved: (requestedCollectionId, signature) => {
73 assertKnownCollection(requestedCollectionId)
74 if (!baseAdapter.markIndexRemoved) {
75 return Promise.resolve()
76 }
77 return baseAdapter.markIndexRemoved(requestedCollectionId, signature)
78 },
79 }
80​
81 return {
82 coordinator: persistence.coordinator,
83 adapter,
84 }
86​
87function createInvokeHarness(
88 dbPath: string,
89 collectionId: string,
90 allowAnyCollectionId: boolean = true,
91): InvokeHarness {
92 if (isElectronFullE2EEnabled()) {
93 return {
94 invoke: createElectronRuntimeBridgeInvoke({
95 dbPath,
96 collectionId,
97 allowAnyCollectionId,
98 timeoutMs: electronRuntimeBridgeTimeoutMs,
99 }),
100 close: () => {},
101 }
102 }
103​
104 const driver = new BetterSqlite3SQLiteDriver({ filename: dbPath })
105 const persistence = createNodeSQLitePersistence({
106 database: driver.getDatabase(),
107 })
108 const filteredPersistence = createFilteredPersistence(
109 collectionId,
110 allowAnyCollectionId,
111 persistence,
112 )
113​
114 let handler:
115 | ((
116 event: unknown,
117 request: ElectronPersistenceRequestEnvelope,
118 ) => Promise<ElectronPersistenceResponseEnvelope>)
119 | undefined
120​
121 const ipcMainLike = {
122 handle: (
123 _channel: string,
124 listener: (
125 event: unknown,
126 request: ElectronPersistenceRequestEnvelope,
127 ) => Promise<ElectronPersistenceResponseEnvelope>,
128 ) => {
129 handler = listener
130 },
131 removeHandler: () => {},
132 }
133 const dispose = exposeElectronSQLitePersistence({
134 ipcMain: ipcMainLike,
135 persistence: filteredPersistence,
136 })
137​
138 return {
139 invoke: async (_channel, request) => {
140 if (!handler) {
141 throw new Error(`Electron IPC handler was not registered`)
142 }
143 return handler(undefined, request)
144 },
145 close: () => {
146 dispose()
147 driver.close()
148 },
149 }
151​
152const activeCleanupFns: Array<() => void> = []
153​
154afterEach(() => {
155 while (activeCleanupFns.length > 0) {
156 const cleanupFn = activeCleanupFns.pop()
157 cleanupFn?.()
158 }
159})
160​
161function createTempDbPath(): string {
162 const tempDirectory = mkdtempSync(join(tmpdir(), `db-electron-ipc-`))
163 const dbPath = join(tempDirectory, `state.sqlite`)
164 activeCleanupFns.push(() => {
165 rmSync(tempDirectory, { recursive: true, force: true })
166 })
167 return dbPath
169​
170describe(`electron sqlite persistence bridge`, () => {
171 it(`round-trips reads and writes through main process`, async () => {
172 const dbPath = createTempDbPath()
173 const invokeHarness = createInvokeHarness(dbPath, `todos`)
174 activeCleanupFns.push(() => invokeHarness.close())
175​
176 const rendererPersistence = createElectronSQLitePersistence({
177 invoke: async (channel, request) => {
178 expect(channel).toBe(DEFAULT_ELECTRON_PERSISTENCE_CHANNEL)
179 return invokeHarness.invoke(channel, request)
180 },
181 timeoutMs: electronRuntimeBridgeTimeoutMs,
182 })
183​
184 await rendererPersistence.adapter.applyCommittedTx(`todos`, {
185 txId: `tx-1`,
186 term: 1,
187 seq: 1,
188 rowVersion: 1,
189 mutations: [
190 {
191 type: `insert`,
192 key: `1`,
193 value: {
194 id: `1`,
195 title: `From renderer`,
196 score: 10,
197 },
198 },
199 ],
200 })
201​
202 const rows = await rendererPersistence.adapter.loadSubset(`todos`, {})
203 expect(rows).toEqual([
204 {
205 key: `1`,
206 value: {
207 id: `1`,
208 title: `From renderer`,
209 score: 10,
210 },
211 },
212 ])
213 })
214​
215 it(`persists data across main process restarts`, async () => {
216 const dbPath = createTempDbPath()
217​
218 if (isElectronFullE2EEnabled()) {
219 const invoke = createElectronRuntimeBridgeInvoke({
220 dbPath,
221 collectionId: `todos`,
222 timeoutMs: electronRuntimeBridgeTimeoutMs,
223 })
224 const rendererPersistence = createElectronSQLitePersistence({
225 invoke,
226 timeoutMs: electronRuntimeBridgeTimeoutMs,
227 })
228​
229 await rendererPersistence.adapter.applyCommittedTx(`todos`, {
230 txId: `tx-restart-1`,
231 term: 1,
232 seq: 1,
233 rowVersion: 1,
234 mutations: [
235 {
236 type: `insert`,
237 key: `persisted`,
238 value: {
239 id: `persisted`,
240 title: `Survives restart`,
241 score: 42,
242 },
243 },
244 ],
245 })
246​
247 const rows = await rendererPersistence.adapter.loadSubset(`todos`, {})
248 expect(rows[0]?.value.title).toBe(`Survives restart`)
249 return
250 }
251​
252 const invokeHarnessA = createInvokeHarness(dbPath, `todos`)
253 const rendererPersistenceA = createElectronSQLitePersistence({
254 invoke: invokeHarnessA.invoke,
255 timeoutMs: electronRuntimeBridgeTimeoutMs,
256 })
257 await rendererPersistenceA.adapter.applyCommittedTx(`todos`, {
258 txId: `tx-restart-1`,
259 term: 1,
260 seq: 1,
261 rowVersion: 1,
262 mutations: [
263 {
264 type: `insert`,
265 key: `persisted`,
266 value: {
267 id: `persisted`,
268 title: `Survives restart`,
269 score: 42,
270 },
271 },
272 ],
273 })
274 invokeHarnessA.close()
275​
276 const invokeHarnessB = createInvokeHarness(dbPath, `todos`)
277 activeCleanupFns.push(() => invokeHarnessB.close())
278 const rendererPersistenceB = createElectronSQLitePersistence({
279 invoke: invokeHarnessB.invoke,
280 timeoutMs: electronRuntimeBridgeTimeoutMs,
281 })
282 const rows = await rendererPersistenceB.adapter.loadSubset(`todos`, {})
283 expect(rows[0]?.value.title).toBe(`Survives restart`)
284 })
285​
286 it(`returns deterministic timeout errors`, async () => {
287 const neverInvoke: ElectronPersistenceInvoke = async () =>
288 await new Promise<ElectronPersistenceResponseEnvelope>(() => {})
289​
290 const rendererPersistence = createElectronSQLitePersistence({
291 invoke: neverInvoke,
292 timeoutMs: 5,
293 })
294​
295 await expect(
296 rendererPersistence.adapter.loadSubset(`todos`, {}),
297 ).rejects.toBeInstanceOf(InvalidPersistedCollectionConfigError)
298 })
299​
300 it(`returns remote errors for unknown collections`, async () => {
301 const dbPath = createTempDbPath()
302 const invokeHarness = createInvokeHarness(dbPath, `known`, false)
303 activeCleanupFns.push(() => invokeHarness.close())
304 const rendererPersistence = createElectronSQLitePersistence({
305 invoke: invokeHarness.invoke,
306 timeoutMs: electronRuntimeBridgeTimeoutMs,
307 })
308​
309 await expect(
310 rendererPersistence.adapter.loadSubset(`missing`, {}),
311 ).rejects.toThrow(`Unknown electron persistence collection`)
312 })
313​
314 it(`registers and unregisters ipc handlers through thin api`, async () => {
315 let registeredChannel: string | undefined
316 let registeredHandler:
317 | ((
318 event: unknown,
319 request: ElectronPersistenceRequestEnvelope,
320 ) => Promise<ElectronPersistenceResponseEnvelope>)
321 | undefined
322 const removedChannels: Array<string> = []
323​
324 const fakeIpcMain = {
325 handle: (
326 channel: string,
327 handler: (
328 event: unknown,
329 request: ElectronPersistenceRequestEnvelope,
330 ) => Promise<ElectronPersistenceResponseEnvelope>,
331 ) => {
332 registeredChannel = channel
333 registeredHandler = handler
334 },
335 removeHandler: (channel: string) => {
336 removedChannels.push(channel)
337 },
338 }
339​
340 const driver = new BetterSqlite3SQLiteDriver({
341 filename: createTempDbPath(),
342 })
343 activeCleanupFns.push(() => driver.close())
344 const persistence = createNodeSQLitePersistence({
345 database: driver.getDatabase(),
346 })
347​
348 const dispose = exposeElectronSQLitePersistence({
349 ipcMain: fakeIpcMain,
350 persistence,
351 })
352​
353 expect(registeredChannel).toBe(DEFAULT_ELECTRON_PERSISTENCE_CHANNEL)
354 expect(registeredHandler).toBeDefined()
355​
356 const response = await registeredHandler?.(undefined, {
357 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
358 requestId: `req-1`,
359 collectionId: `todos`,
360 method: `loadSubset`,
361 payload: {
362 options: {},
363 },
364 })
365 expect(response).toMatchObject({
366 ok: true,
367 requestId: `req-1`,
368 method: `loadSubset`,
369 })
370​
371 dispose()
372 expect(removedChannels).toEqual([DEFAULT_ELECTRON_PERSISTENCE_CHANNEL])
373 })
374})