Open History to see the last commit
1import {
2 InvalidPersistedCollectionConfigError,
3 resolvePersistedStorageTarget,
4} from '@tanstack/db-sqlite-persistence-core'
5import {
6 DEFAULT_ELECTRON_PERSISTENCE_CHANNEL,
7 ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
8} from './protocol'
9import type {
10 PersistedCollectionPersistence,
11 PersistedStorageTarget,
12 PersistenceAdapter,
13 SQLitePullSinceResult,
14} from '@tanstack/db-sqlite-persistence-core'
15import type {
16 ElectronPersistedKey,
17 ElectronPersistedRow,
18 ElectronPersistenceRequestEnvelope,
19 ElectronPersistenceResponseEnvelope,
20 ElectronSerializedError,
21} from './protocol'
22
23type ElectronMainPersistenceAdapter = PersistenceAdapter & {
24 loadCollectionMetadata?: (
25 target: PersistedStorageTarget,
26 ctx?: { cacheGenerationClaimId?: string },
27 ) => Promise<Array<{ key: string; value: unknown }>>
28 scanRows?: (
29 target: PersistedStorageTarget,
30 options?: { metadataOnly?: boolean },
31 ctx?: { cacheGenerationClaimId?: string },
32 ) => Promise<
33 Array<{
34 key: ElectronPersistedKey
35 value: ElectronPersistedRow
36 metadata?: unknown
37 }>
38 >
39 pullSince?: (
40 target: PersistedStorageTarget,
41 fromRowVersion: number,
42 ctx?: { cacheGenerationClaimId?: string },
43 ) => Promise<SQLitePullSinceResult<ElectronPersistedKey>>
44 getStreamPosition?: (
45 target: PersistedStorageTarget,
46 ctx?: { cacheGenerationClaimId?: string },
47 ) => Promise<{
48 latestTerm: number
49 latestSeq: number
50 latestRowVersion: number
51 }>
52}
53
54function serializeError(error: unknown): ElectronSerializedError {
55 const fallbackMessage = `Unknown electron persistence error`
56
57 if (!(error instanceof Error)) {
58 return {
59 name: `Error`,
60 message: fallbackMessage,
61 code: undefined,
62 }
63 }
64
65 const detailedError = error as Error & { code?: unknown; path?: unknown }
66 const path = detailedError.path
67 return {
68 name: error.name || `Error`,
69 message: error.message || fallbackMessage,
70 stack: error.stack,
71 code:
72 typeof detailedError.code === `string` ||
73 typeof detailedError.code === `number`
74 ? detailedError.code
75 : undefined,
76 path:
77 typeof path === `string` ||
78 (Array.isArray(path) &&
79 path.every(
80 (segment: unknown) =>
81 typeof segment === `string` || typeof segment === `number`,
82 ))
83 ? (path as string | ReadonlyArray<string | number>)
84 : undefined,
85 }
86}
87
88function createErrorResponse(
89 request: ElectronPersistenceRequestEnvelope,
90 error: unknown,
91): ElectronPersistenceResponseEnvelope {
92 return {
93 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
94 requestId: request.requestId,
95 method: request.method,
96 ok: false,
97 error: serializeError(error),
98 }
99}
100
101function assertValidRequest(request: ElectronPersistenceRequestEnvelope): void {
102 if (request.v !== ELECTRON_PERSISTENCE_PROTOCOL_VERSION) {
103 throw new InvalidPersistedCollectionConfigError(
104 `Unsupported electron persistence protocol version "${request.v}"`,
105 )
106 }
107
108 if (
109 typeof request.requestId !== `string` ||
110 request.requestId.trim().length === 0
111 ) {
112 throw new InvalidPersistedCollectionConfigError(
113 `Electron persistence requestId cannot be empty`,
114 )
115 }
116
117 if (
118 typeof request.collectionId !== `string` ||
119 request.collectionId.trim().length === 0
120 ) {
121 throw new InvalidPersistedCollectionConfigError(
122 `Electron persistence collectionId cannot be empty`,
123 )
124 }
125}
126
127function requireStorageTarget(
128 request: ElectronPersistenceRequestEnvelope,
129): PersistedStorageTarget {
130 const target = request.storageTarget
131 if (!target) {
132 throw new InvalidPersistedCollectionConfigError(
133 `Electron persistence data request requires an explicit storage target`,
134 )
135 }
136 if (
137 resolvePersistedStorageTarget(target).collectionId !== request.collectionId
138 ) {
139 throw new InvalidPersistedCollectionConfigError(
140 `Electron persistence storage target does not match its collectionId`,
141 )
142 }
143 return target
144}
145
146async function executeRequestAgainstAdapter(
147 request: ElectronPersistenceRequestEnvelope,
148 adapter: ElectronMainPersistenceAdapter,
149): Promise<ElectronPersistenceResponseEnvelope> {
150 switch (request.method) {
151 case `loadSubset`: {
152 const result = await adapter.loadSubset(
153 requireStorageTarget(request),
154 request.payload.options,
155 request.payload.ctx,
156 )
157 return {
158 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
159 requestId: request.requestId,
160 method: request.method,
161 ok: true,
162 result,
163 }
164 }
165
166 case `loadResumeSnapshot`: {
167 const result = await adapter.loadResumeSnapshot(
168 requireStorageTarget(request),
169 request.payload.ctx,
170 )
171 return {
172 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
173 requestId: request.requestId,
174 method: request.method,
175 ok: true,
176 result,
177 }
178 }
179
180 case `loadCollectionMetadata`: {
181 if (!adapter.loadCollectionMetadata) {
182 throw new InvalidPersistedCollectionConfigError(
183 `loadCollectionMetadata is not supported by the configured electron persistence adapter`,
184 )
185 }
186 const result = await adapter.loadCollectionMetadata(
187 requireStorageTarget(request),
188 request.payload.ctx,
189 )
190 return {
191 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
192 requestId: request.requestId,
193 method: request.method,
194 ok: true,
195 result,
196 }
197 }
198
199 case `scanRows`: {
200 if (!adapter.scanRows) {
201 throw new InvalidPersistedCollectionConfigError(
202 `scanRows is not supported by the configured electron persistence adapter`,
203 )
204 }
205 const result = await adapter.scanRows(
206 requireStorageTarget(request),
207 request.payload.options,
208 request.payload.ctx,
209 )
210 return {
211 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
212 requestId: request.requestId,
213 method: request.method,
214 ok: true,
215 result,
216 }
217 }
218
219 case `applyCommittedTx`: {
220 await adapter.applyCommittedTx(
221 requireStorageTarget(request),
222 request.payload.tx,
223 )
224 return {
225 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
226 requestId: request.requestId,
227 method: request.method,
228 ok: true,
229 result: null,
230 }
231 }
232
233 case `reconcileCommittedTx`: {
234 const result = adapter.reconcileCommittedTx
235 ? await adapter.reconcileCommittedTx(
236 requireStorageTarget(request),
237 request.payload.tx,
238 request.payload.anchor,
239 )
240 : { kind: `unknown` as const }
241 return {
242 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
243 requestId: request.requestId,
244 method: request.method,
245 ok: true,
246 result,
247 }
248 }
249
250 case `ensureIndex`: {
251 await adapter.ensureIndex(
252 requireStorageTarget(request),
253 request.payload.signature,
254 request.payload.spec,
255 request.payload.ctx,
256 )
257 return {
258 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
259 requestId: request.requestId,
260 method: request.method,
261 ok: true,
262 result: null,
263 }
264 }
265
266 case `markIndexRemoved`: {
267 if (!adapter.markIndexRemoved) {
268 throw new InvalidPersistedCollectionConfigError(
269 `markIndexRemoved is not supported by the configured electron persistence adapter`,
270 )
271 }
272 await adapter.markIndexRemoved(
273 requireStorageTarget(request),
274 request.payload.signature,
275 request.payload.ctx,
276 )
277 return {
278 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
279 requestId: request.requestId,
280 method: request.method,
281 ok: true,
282 result: null,
283 }
284 }
285
286 case `pullSince`: {
287 if (!adapter.pullSince) {
288 throw new InvalidPersistedCollectionConfigError(
289 `pullSince is not supported by the configured electron persistence adapter`,
290 )
291 }
292 const result = await adapter.pullSince(
293 requireStorageTarget(request),
294 request.payload.fromRowVersion,
295 request.payload.ctx,
296 )
297 return {
298 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
299 requestId: request.requestId,
300 method: request.method,
301 ok: true,
302 result,
303 }
304 }
305
306 case `reserveLeadershipTerm`: {
307 if (!adapter.reserveLeadershipTerm) {
308 throw new InvalidPersistedCollectionConfigError(
309 `reserveLeadershipTerm is not supported by the configured electron persistence adapter`,
310 )
311 }
312 const position = await adapter.reserveLeadershipTerm(
313 requireStorageTarget(request),
314 request.payload.observedTerm,
315 request.payload.ctx,
316 )
317 return {
318 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
319 requestId: request.requestId,
320 method: request.method,
321 ok: true,
322 result: position,
323 }
324 }
325
326 case `getStreamPosition`: {
327 if (!adapter.getStreamPosition) {
328 throw new InvalidPersistedCollectionConfigError(
329 `getStreamPosition is not supported by the configured electron persistence adapter`,
330 )
331 }
332 const position = await adapter.getStreamPosition(
333 requireStorageTarget(request),
334 request.payload.ctx,
335 )
336 return {
337 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
338 requestId: request.requestId,
339 method: request.method,
340 ok: true,
341 result: position,
342 }
343 }
344
345 case `claimCacheGeneration`: {
346 if (!adapter.claimCacheGeneration) {
347 throw new InvalidPersistedCollectionConfigError(
348 `claimCacheGeneration is not supported by the configured electron persistence adapter`,
349 )
350 }
351 const result = await adapter.claimCacheGeneration(request.collectionId)
352 return {
353 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
354 requestId: request.requestId,
355 method: request.method,
356 ok: true,
357 result,
358 }
359 }
360
361 case `rotateCacheGeneration`: {
362 if (!adapter.rotateCacheGeneration) {
363 throw new InvalidPersistedCollectionConfigError(
364 `rotateCacheGeneration is not supported by the configured electron persistence adapter`,
365 )
366 }
367 const result = await adapter.rotateCacheGeneration(
368 request.collectionId,
369 request.payload.claimId,
370 request.payload.resetMetadata,
371 request.payload.expectedStorageCollectionId,
372 )
373 return {
374 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
375 requestId: request.requestId,
376 method: request.method,
377 ok: true,
378 result,
379 }
380 }
381
382 case `renewCacheGenerationClaim`: {
383 if (!adapter.renewCacheGenerationClaim) {
384 throw new InvalidPersistedCollectionConfigError(
385 `renewCacheGenerationClaim is not supported by the configured electron persistence adapter`,
386 )
387 }
388 const result = await adapter.renewCacheGenerationClaim(
389 request.payload.storageCollectionId,
390 request.payload.claimId,
391 )
392 return {
393 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
394 requestId: request.requestId,
395 method: request.method,
396 ok: true,
397 result,
398 }
399 }
400
401 case `releaseCacheGenerationClaim`: {
402 if (!adapter.releaseCacheGenerationClaim) {
403 throw new InvalidPersistedCollectionConfigError(
404 `releaseCacheGenerationClaim is not supported by the configured electron persistence adapter`,
405 )
406 }
407 await adapter.releaseCacheGenerationClaim(request.payload.claimId)
408 return {
409 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
410 requestId: request.requestId,
411 method: request.method,
412 ok: true,
413 result: null,
414 }
415 }
416 }
417}
418
419function resolveModeAwarePersistence(
420 persistence: PersistedCollectionPersistence,
421 request: ElectronPersistenceRequestEnvelope,
422): PersistedCollectionPersistence {
423 if (
424 request.storageTarget?.kind === `managed` &&
425 !request.resolution?.logicalCollectionId
426 ) {
427 throw new InvalidPersistedCollectionConfigError(
428 `Electron managed cache request requires a logical Collection ID`,
429 )
430 }
431 const mode = request.resolution?.mode ?? `sync-absent`
432 const schemaVersion = request.resolution?.schemaVersion
433 const collectionAwarePersistence =
434 persistence.resolvePersistenceForCollection?.({
435 collectionId:
436 request.resolution?.logicalCollectionId ?? request.collectionId,
437 mode,
438 schemaVersion,
439 })
440 if (collectionAwarePersistence) {
441 return collectionAwarePersistence
442 }
443
444 const modeAwarePersistence = persistence.resolvePersistenceForMode?.(mode)
445 return modeAwarePersistence ?? persistence
446}
447
448export type ElectronIpcMainLike = {
449 handle: (
450 channel: string,
451 listener: (
452 event: unknown,
453 request: ElectronPersistenceRequestEnvelope,
454 ) => Promise<ElectronPersistenceResponseEnvelope>,
455 ) => void
456 removeHandler?: (channel: string) => void
457}
458
459export type ElectronSQLiteMainProcessOptions = {
460 persistence: PersistedCollectionPersistence
461 ipcMain: ElectronIpcMainLike
462 channel?: string
463}
464
465export function exposeElectronSQLitePersistence(
466 options: ElectronSQLiteMainProcessOptions,
467): () => void {
468 const channel = options.channel ?? DEFAULT_ELECTRON_PERSISTENCE_CHANNEL
469 options.ipcMain.handle(
470 channel,
471 async (
472 _event,
473 request: ElectronPersistenceRequestEnvelope,
474 ): Promise<ElectronPersistenceResponseEnvelope> => {
475 try {
476 assertValidRequest(request)
477 const modeAwarePersistence = resolveModeAwarePersistence(
478 options.persistence,
479 request,
480 )
481 return await executeRequestAgainstAdapter(
482 request,
483 modeAwarePersistence.adapter,
484 )
485 } catch (error) {
486 return createErrorResponse(request, error)
487 }
488 },
489 )
490
491 return () => {
492 options.ipcMain.removeHandler?.(channel)
493 }
494}