Open History to see the last commit
1import {
2 InvalidPersistedCollectionConfigError,
3 SingleProcessCoordinator,
4} from '@tanstack/db-sqlite-persistence-core'
5import { ElectronCollectionCoordinator } from './electron-coordinator'
6import {
7 DEFAULT_ELECTRON_PERSISTENCE_CHANNEL,
8 ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
9} from './protocol'
10import type {
11 CommittedTxAnchor,
12 PersistedCollectionCoordinator,
13 PersistedCollectionMode,
14 PersistedCollectionPersistence,
15 PersistedIndexSpec,
16 PersistedTx,
17 ReconciledCommittedTx,
18 SQLitePullSinceResult,
19} from '@tanstack/db-sqlite-persistence-core'
20import type {
21 ElectronPersistedKey,
22 ElectronPersistedRow,
23 ElectronPersistenceInvoke,
24 ElectronPersistenceMethod,
25 ElectronPersistencePayloadMap,
26 ElectronPersistenceRequest,
27 ElectronPersistenceRequestEnvelope,
28 ElectronPersistenceResolution,
29 ElectronPersistenceResponseEnvelope,
30 ElectronPersistenceResultMap,
31} from './protocol'
32import type { LoadSubsetOptions } from '@tanstack/db'
33
34const DEFAULT_REQUEST_TIMEOUT_MS = 5_000
35let nextRequestId = 1
36
37function createRequestId(): string {
38 const requestId = nextRequestId
39 nextRequestId++
40 return `electron-persistence-${requestId}`
41}
42
43function withTimeout<T>(
44 promise: Promise<T>,
45 timeoutMs: number,
46 timeoutMessage: string,
47): Promise<T> {
48 if (timeoutMs <= 0) {
49 return promise
50 }
51
52 return new Promise<T>((resolve, reject) => {
53 const timer = setTimeout(() => {
54 reject(new InvalidPersistedCollectionConfigError(timeoutMessage))
55 }, timeoutMs)
56
57 promise.then(
58 (value) => {
59 clearTimeout(timer)
60 resolve(value)
61 },
62 (error: unknown) => {
63 clearTimeout(timer)
64 reject(error)
65 },
66 )
67 })
68}
69
70function assertValidResponse(
71 response: ElectronPersistenceResponseEnvelope,
72 request: ElectronPersistenceRequestEnvelope,
73): void {
74 if (response.v !== ELECTRON_PERSISTENCE_PROTOCOL_VERSION) {
75 throw new InvalidPersistedCollectionConfigError(
76 `Unexpected electron persistence protocol version "${response.v}" in response`,
77 )
78 }
79
80 if (response.requestId !== request.requestId) {
81 throw new InvalidPersistedCollectionConfigError(
82 `Mismatched electron persistence response request id. Expected "${request.requestId}", received "${response.requestId}"`,
83 )
84 }
85
86 if (response.method !== request.method) {
87 throw new InvalidPersistedCollectionConfigError(
88 `Mismatched electron persistence response method. Expected "${request.method}", received "${response.method}"`,
89 )
90 }
91}
92
93function createSerializableLoadSubsetOptions(
94 subsetOptions: LoadSubsetOptions,
95): LoadSubsetOptions {
96 const { subscription: _subscription, ...serializableOptions } = subsetOptions
97 return serializableOptions
98}
99
100type RendererRequestExecutor = <TMethod extends ElectronPersistenceMethod>(
101 method: TMethod,
102 collectionId: string,
103 payload: ElectronPersistencePayloadMap[TMethod],
104 resolution?: ElectronPersistenceResolution,
105) => Promise<ElectronPersistenceResultMap[TMethod]>
106
107function createRendererRequestExecutor(options: {
108 invoke: ElectronPersistenceInvoke
109 channel?: string
110 timeoutMs?: number
111}): RendererRequestExecutor {
112 const channel = options.channel ?? DEFAULT_ELECTRON_PERSISTENCE_CHANNEL
113 const timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS
114
115 return async <TMethod extends ElectronPersistenceMethod>(
116 method: TMethod,
117 collectionId: string,
118 payload: ElectronPersistencePayloadMap[TMethod],
119 resolution?: ElectronPersistenceResolution,
120 ) => {
121 const request = {
122 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
123 requestId: createRequestId(),
124 collectionId,
125 method,
126 resolution,
127 payload,
128 } as ElectronPersistenceRequest
129
130 const response = await withTimeout(
131 options.invoke(channel, request),
132 timeoutMs,
133 `Electron persistence request timed out (method=${method}, collection=${collectionId}, timeoutMs=${timeoutMs})`,
134 )
135 assertValidResponse(response, request)
136
137 if (!response.ok) {
138 const remoteError = new InvalidPersistedCollectionConfigError(
139 `${response.error.name}: ${response.error.message}`,
140 )
141 if (typeof response.error.stack === `string`) {
142 remoteError.stack = response.error.stack
143 }
144 if (
145 typeof response.error.code === `string` ||
146 typeof response.error.code === `number`
147 ) {
148 ;(remoteError as Error & { code?: string | number }).code =
149 response.error.code
150 }
151 if (response.error.path !== undefined) {
152 ;(
153 remoteError as Error & {
154 path?: string | ReadonlyArray<string | number>
155 }
156 ).path = response.error.path
157 }
158 throw remoteError
159 }
160
161 return response.result as ElectronPersistenceResultMap[TMethod]
162 }
163}
164
165type ElectronRendererResolvedAdapter =
166 PersistedCollectionPersistence[`adapter`] & {
167 loadCollectionMetadata: (
168 collectionId: string,
169 ) => Promise<Array<{ key: string; value: unknown }>>
170 scanRows: (
171 collectionId: string,
172 options?: { metadataOnly?: boolean },
173 ) => Promise<
174 Array<{
175 key: string | number
176 value: Record<string, unknown>
177 metadata?: unknown
178 }>
179 >
180 pullSince: (
181 collectionId: string,
182 fromRowVersion: number,
183 ) => Promise<SQLitePullSinceResult<string | number>>
184 getStreamPosition: (collectionId: string) => Promise<{
185 latestTerm: number
186 latestSeq: number
187 latestRowVersion: number
188 }>
189 reserveLeadershipTerm: (
190 collectionId: string,
191 observedTerm: number,
192 ) => Promise<{
193 latestTerm: number
194 latestSeq: number
195 latestRowVersion: number
196 }>
197 }
198
199function createResolvedRendererAdapter(
200 executeRequest: RendererRequestExecutor,
201 resolution?: ElectronPersistenceResolution,
202): ElectronRendererResolvedAdapter {
203 return {
204 loadSubset: async (
205 collectionId: string,
206 subsetOptions: LoadSubsetOptions,
207 ctx?: { requiredIndexSignatures?: ReadonlyArray<string> },
208 ) => {
209 const result = await executeRequest(
210 `loadSubset`,
211 collectionId,
212 {
213 options: createSerializableLoadSubsetOptions(subsetOptions),
214 ctx,
215 },
216 resolution,
217 )
218
219 return result as Array<{
220 key: string | number
221 value: Record<string, unknown>
222 }>
223 },
224 loadResumeSnapshot: async (
225 collectionId: string,
226 ctx?: {
227 requiredIndexSignatures?: ReadonlyArray<string>
228 includeRows?: boolean
229 },
230 ) => {
231 return executeRequest(
232 `loadResumeSnapshot`,
233 collectionId,
234 { ctx },
235 resolution,
236 )
237 },
238 applyCommittedTx: async (
239 collectionId: string,
240 tx: PersistedTx<Record<string, unknown>, string | number>,
241 ): Promise<void> => {
242 await executeRequest(
243 `applyCommittedTx`,
244 collectionId,
245 {
246 tx: tx as PersistedTx<ElectronPersistedRow, ElectronPersistedKey>,
247 },
248 resolution,
249 )
250 },
251 reconcileCommittedTx: async (
252 collectionId: string,
253 tx: PersistedTx<Record<string, unknown>, string | number>,
254 anchor: CommittedTxAnchor,
255 ): Promise<ReconciledCommittedTx> => {
256 return executeRequest(
257 `reconcileCommittedTx`,
258 collectionId,
259 { tx, anchor },
260 resolution,
261 )
262 },
263 loadCollectionMetadata: async (
264 collectionId: string,
265 ): Promise<Array<{ key: string; value: unknown }>> => {
266 return executeRequest(
267 `loadCollectionMetadata`,
268 collectionId,
269 {},
270 resolution,
271 )
272 },
273 scanRows: async (
274 collectionId: string,
275 options?: { metadataOnly?: boolean },
276 ): Promise<
277 Array<{
278 key: string | number
279 value: Record<string, unknown>
280 metadata?: unknown
281 }>
282 > => {
283 const result = await executeRequest(
284 `scanRows`,
285 collectionId,
286 { options },
287 resolution,
288 )
289 return result as Array<{
290 key: string | number
291 value: Record<string, unknown>
292 metadata?: unknown
293 }>
294 },
295 ensureIndex: async (
296 collectionId: string,
297 signature: string,
298 spec: PersistedIndexSpec,
299 ): Promise<void> => {
300 await executeRequest(
301 `ensureIndex`,
302 collectionId,
303 {
304 signature,
305 spec,
306 },
307 resolution,
308 )
309 },
310 markIndexRemoved: async (
311 collectionId: string,
312 signature: string,
313 ): Promise<void> => {
314 await executeRequest(
315 `markIndexRemoved`,
316 collectionId,
317 {
318 signature,
319 },
320 resolution,
321 )
322 },
323 pullSince: async (
324 collectionId: string,
325 fromRowVersion: number,
326 ): Promise<SQLitePullSinceResult<string | number>> => {
327 const result = await executeRequest(
328 `pullSince`,
329 collectionId,
330 {
331 fromRowVersion,
332 },
333 resolution,
334 )
335 return result as SQLitePullSinceResult<string | number>
336 },
337 getStreamPosition: async (
338 collectionId: string,
339 ): Promise<{
340 latestTerm: number
341 latestSeq: number
342 latestRowVersion: number
343 }> => {
344 return executeRequest(`getStreamPosition`, collectionId, {}, resolution)
345 },
346 reserveLeadershipTerm: async (collectionId, observedTerm) =>
347 executeRequest(
348 `reserveLeadershipTerm`,
349 collectionId,
350 { observedTerm },
351 resolution,
352 ),
353 }
354}
355
356export type ElectronIpcRendererLike = {
357 invoke: (
358 channel: string,
359 request: ElectronPersistenceRequestEnvelope,
360 ) => Promise<ElectronPersistenceResponseEnvelope>
361}
362
363export type ElectronSQLitePersistenceOptions = {
364 invoke?: ElectronPersistenceInvoke
365 ipcRenderer?: ElectronIpcRendererLike
366 channel?: string
367 timeoutMs?: number
368 coordinator?: PersistedCollectionCoordinator
369}
370
371function resolveInvoke(
372 options: ElectronSQLitePersistenceOptions,
373): ElectronPersistenceInvoke {
374 if (options.invoke) {
375 return options.invoke
376 }
377
378 if (options.ipcRenderer) {
379 return (channel, request) => options.ipcRenderer!.invoke(channel, request)
380 }
381
382 throw new InvalidPersistedCollectionConfigError(
383 `Electron renderer persistence requires either invoke or ipcRenderer`,
384 )
385}
386
387export function createElectronSQLitePersistence(
388 options: ElectronSQLitePersistenceOptions,
389): PersistedCollectionPersistence {
390 const invoke = resolveInvoke(options)
391 const coordinator = options.coordinator ?? new SingleProcessCoordinator()
392 const executeRequest = createRendererRequestExecutor({
393 invoke,
394 channel: options.channel,
395 timeoutMs: options.timeoutMs,
396 })
397 const adapterCache = new Map<string, ElectronRendererResolvedAdapter>()
398
399 const getAdapterForCollection = (
400 mode: PersistedCollectionMode,
401 schemaVersion: number | undefined,
402 ) => {
403 const schemaVersionKey =
404 schemaVersion === undefined ? `schema:default` : `schema:${schemaVersion}`
405 const cacheKey = `mode:${mode}|${schemaVersionKey}`
406 const cachedAdapter = adapterCache.get(cacheKey)
407 if (cachedAdapter) {
408 return cachedAdapter
409 }
410
411 const adapter = createResolvedRendererAdapter(executeRequest, {
412 mode,
413 schemaVersion,
414 })
415 adapterCache.set(cacheKey, adapter)
416 return adapter
417 }
418
419 const createCollectionPersistence = (
420 collectionId: string | undefined,
421 mode: PersistedCollectionMode,
422 schemaVersion: number | undefined,
423 ): PersistedCollectionPersistence => {
424 const adapter = getAdapterForCollection(mode, schemaVersion)
425 if (coordinator instanceof ElectronCollectionCoordinator) {
426 if (collectionId === undefined) {
427 coordinator.setAdapter(adapter)
428 } else {
429 coordinator.setAdapterForCollection(collectionId, adapter)
430 }
431 }
432 return { adapter, coordinator }
433 }
434
435 const defaultPersistence = createCollectionPersistence(
436 undefined,
437 `sync-absent`,
438 undefined,
439 )
440 if (coordinator instanceof ElectronCollectionCoordinator) {
441 coordinator.setAdapter(defaultPersistence.adapter)
442 }
443
444 return {
445 ...defaultPersistence,
446 resolvePersistenceForCollection: ({ collectionId, mode, schemaVersion }) =>
447 createCollectionPersistence(collectionId, mode, schemaVersion),
448 // Backward compatible fallback for older callers.
449 resolvePersistenceForMode: (mode) =>
450 createCollectionPersistence(undefined, mode, undefined),
451 }
452}