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

renderer.ts

632 lines18.6 KB

1import {
2 InvalidPersistedCollectionConfigError,
3 SingleProcessCoordinator,
4 resolvePersistedStorageTarget,
5} from '@tanstack/db-sqlite-persistence-core'
6import { ElectronCollectionCoordinator } from './electron-coordinator'
7import {
8 DEFAULT_ELECTRON_PERSISTENCE_CHANNEL,
9 ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
10} from './protocol'
11import type {
12 CommittedTxAnchor,
13 PersistedCacheGenerationClaim,
14 PersistedCollectionCoordinator,
15 PersistedCollectionMode,
16 PersistedCollectionPersistence,
17 PersistedIndexSpec,
18 PersistedStorageTarget,
19 PersistedTx,
20 ReconciledCommittedTx,
21 SQLitePullSinceResult,
22} from '@tanstack/db-sqlite-persistence-core'
23import type {
24 ElectronPersistedKey,
25 ElectronPersistedRow,
26 ElectronPersistenceInvoke,
27 ElectronPersistenceMethod,
28 ElectronPersistencePayloadMap,
29 ElectronPersistenceRequest,
30 ElectronPersistenceRequestEnvelope,
31 ElectronPersistenceResolution,
32 ElectronPersistenceResponseEnvelope,
33 ElectronPersistenceResultMap,
34} from './protocol'
35import type { LoadSubsetOptions } from '@tanstack/db'
36​
37const DEFAULT_REQUEST_TIMEOUT_MS = 5_000
38let nextRequestId = 1
39​
40function createRequestId(): string {
41 const requestId = nextRequestId
42 nextRequestId++
43 return `electron-persistence-${requestId}`
45​
46function withTimeout<T>(
47 promise: Promise<T>,
48 timeoutMs: number,
49 timeoutMessage: string,
50): Promise<T> {
51 if (timeoutMs <= 0) {
52 return promise
53 }
54​
55 return new Promise<T>((resolve, reject) => {
56 const timer = setTimeout(() => {
57 reject(new InvalidPersistedCollectionConfigError(timeoutMessage))
58 }, timeoutMs)
59​
60 promise.then(
61 (value) => {
62 clearTimeout(timer)
63 resolve(value)
64 },
65 (error: unknown) => {
66 clearTimeout(timer)
67 reject(error)
68 },
69 )
70 })
72​
73function assertValidResponse(
74 response: ElectronPersistenceResponseEnvelope,
75 request: ElectronPersistenceRequestEnvelope,
76): void {
77 if (response.v !== ELECTRON_PERSISTENCE_PROTOCOL_VERSION) {
78 throw new InvalidPersistedCollectionConfigError(
79 `Unexpected electron persistence protocol version "${response.v}" in response`,
80 )
81 }
82​
83 if (response.requestId !== request.requestId) {
84 throw new InvalidPersistedCollectionConfigError(
85 `Mismatched electron persistence response request id. Expected "${request.requestId}", received "${response.requestId}"`,
86 )
87 }
88​
89 if (response.method !== request.method) {
90 throw new InvalidPersistedCollectionConfigError(
91 `Mismatched electron persistence response method. Expected "${request.method}", received "${response.method}"`,
92 )
93 }
95​
96function createSerializableLoadSubsetOptions(
97 subsetOptions: LoadSubsetOptions,
98): LoadSubsetOptions {
99 const { subscription: _subscription, ...serializableOptions } = subsetOptions
100 return serializableOptions
102​
103type RendererRequestExecutor = <TMethod extends ElectronPersistenceMethod>(
104 method: TMethod,
105 target: string | PersistedStorageTarget,
106 payload: ElectronPersistencePayloadMap[TMethod],
107 resolution?: ElectronPersistenceResolution,
108) => Promise<ElectronPersistenceResultMap[TMethod]>
109​
110function createRendererRequestExecutor(options: {
111 invoke: ElectronPersistenceInvoke
112 channel?: string
113 timeoutMs?: number
114 claimCollections: Map<string, string>
115}): RendererRequestExecutor {
116 const channel = options.channel ?? DEFAULT_ELECTRON_PERSISTENCE_CHANNEL
117 const timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS
118​
119 return async <TMethod extends ElectronPersistenceMethod>(
120 method: TMethod,
121 target: string | PersistedStorageTarget,
122 payload: ElectronPersistencePayloadMap[TMethod],
123 resolution?: ElectronPersistenceResolution,
124 ) => {
125 const storageTarget = typeof target === `string` ? undefined : target
126 const collectionId = storageTarget
127 ? resolvePersistedStorageTarget(storageTarget).collectionId
128 : target
129 const isGenerationRequest =
130 method === `claimCacheGeneration` ||
131 method === `rotateCacheGeneration` ||
132 method === `renewCacheGenerationClaim` ||
133 method === `releaseCacheGenerationClaim`
134 const managedTarget = storageTarget?.kind === `managed`
135 const logicalCollectionId =
136 resolution?.logicalCollectionId ??
137 (managedTarget
138 ? options.claimCollections.get(storageTarget.claimId)
139 : isGenerationRequest
140 ? collectionId
141 : undefined)
142 if ((managedTarget || isGenerationRequest) && !logicalCollectionId) {
143 throw new InvalidPersistedCollectionConfigError(
144 `Electron managed cache request requires a known logical Collection ID`,
145 )
146 }
147 const request = {
148 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
149 requestId: createRequestId(),
150 collectionId,
151 storageTarget,
152 method,
153 resolution:
154 managedTarget || isGenerationRequest
155 ? { ...resolution, mode: `sync-present`, logicalCollectionId }
156 : resolution,
157 payload,
158 } as ElectronPersistenceRequest
159​
160 const response = await withTimeout(
161 options.invoke(channel, request),
162 timeoutMs,
163 `Electron persistence request timed out (method=${method}, collection=${collectionId}, timeoutMs=${timeoutMs})`,
164 )
165 assertValidResponse(response, request)
166​
167 if (!response.ok) {
168 const remoteError = new InvalidPersistedCollectionConfigError(
169 `${response.error.name}: ${response.error.message}`,
170 )
171 if (typeof response.error.stack === `string`) {
172 remoteError.stack = response.error.stack
173 }
174 if (
175 typeof response.error.code === `string` ||
176 typeof response.error.code === `number`
177 ) {
178 ;(remoteError as Error & { code?: string | number }).code =
179 response.error.code
180 }
181 if (response.error.path !== undefined) {
182 ;(
183 remoteError as Error & {
184 path?: string | ReadonlyArray<string | number>
185 }
186 ).path = response.error.path
187 }
188 throw remoteError
189 }
190​
191 return response.result as ElectronPersistenceResultMap[TMethod]
192 }
194​
195type ElectronRendererResolvedAdapter =
196 PersistedCollectionPersistence[`adapter`] & {
197 loadCollectionMetadata: (
198 target: PersistedStorageTarget,
199 ctx?: { cacheGenerationClaimId?: string },
200 ) => Promise<Array<{ key: string; value: unknown }>>
201 scanRows: (
202 target: PersistedStorageTarget,
203 options?: { metadataOnly?: boolean },
204 ctx?: { cacheGenerationClaimId?: string },
205 ) => Promise<
206 Array<{
207 key: string | number
208 value: Record<string, unknown>
209 metadata?: unknown
210 }>
211 >
212 pullSince: (
213 target: PersistedStorageTarget,
214 fromRowVersion: number,
215 ctx?: { cacheGenerationClaimId?: string },
216 ) => Promise<SQLitePullSinceResult<string | number>>
217 getStreamPosition: (
218 target: PersistedStorageTarget,
219 ctx?: { cacheGenerationClaimId?: string },
220 ) => Promise<{
221 latestTerm: number
222 latestSeq: number
223 latestRowVersion: number
224 }>
225 reserveLeadershipTerm: (
226 target: PersistedStorageTarget,
227 observedTerm: number,
228 ctx?: { cacheGenerationClaimId?: string },
229 ) => Promise<{
230 latestTerm: number
231 latestSeq: number
232 latestRowVersion: number
233 }>
234 }
235​
236function createResolvedRendererAdapter(
237 executeRequest: RendererRequestExecutor,
238 claimCollections: Map<string, string>,
239 managedCacheGenerations: boolean,
240 resolution?: ElectronPersistenceResolution,
241): ElectronRendererResolvedAdapter {
242 const adapter: ElectronRendererResolvedAdapter = {
243 loadSubset: async (
244 target: PersistedStorageTarget,
245 subsetOptions: LoadSubsetOptions,
246 ctx?: {
247 requiredIndexSignatures?: ReadonlyArray<string>
248 cacheGenerationClaimId?: string
249 },
250 ) => {
251 const access = resolvePersistedStorageTarget(
252 target,
253 ctx?.cacheGenerationClaimId,
254 )
255 const result = await executeRequest(
256 `loadSubset`,
257 target,
258 {
259 options: createSerializableLoadSubsetOptions(subsetOptions),
260 ctx: { ...ctx, cacheGenerationClaimId: access.claimId },
261 },
262 resolution,
263 )
264​
265 return result as Array<{
266 key: string | number
267 value: Record<string, unknown>
268 }>
269 },
270 loadResumeSnapshot: async (
271 target: PersistedStorageTarget,
272 ctx?: {
273 requiredIndexSignatures?: ReadonlyArray<string>
274 includeRows?: boolean
275 cacheGenerationClaimId?: string
276 },
277 ) => {
278 const access = resolvePersistedStorageTarget(
279 target,
280 ctx?.cacheGenerationClaimId,
281 )
282 return executeRequest(
283 `loadResumeSnapshot`,
284 target,
285 { ctx: { ...ctx, cacheGenerationClaimId: access.claimId } },
286 resolution,
287 )
288 },
289 applyCommittedTx: async (
290 target: PersistedStorageTarget,
291 tx: PersistedTx<Record<string, unknown>, string | number>,
292 ): Promise<void> => {
293 const access = resolvePersistedStorageTarget(
294 target,
295 tx.cacheGenerationClaimId,
296 )
297 await executeRequest(
298 `applyCommittedTx`,
299 target,
300 {
301 tx: { ...tx, cacheGenerationClaimId: access.claimId } as PersistedTx<
302 ElectronPersistedRow,
303 ElectronPersistedKey
304 >,
305 },
306 resolution,
307 )
308 },
309 reconcileCommittedTx: async (
310 target: PersistedStorageTarget,
311 tx: PersistedTx<Record<string, unknown>, string | number>,
312 anchor: CommittedTxAnchor,
313 ): Promise<ReconciledCommittedTx> => {
314 const access = resolvePersistedStorageTarget(
315 target,
316 tx.cacheGenerationClaimId,
317 )
318 return executeRequest(
319 `reconcileCommittedTx`,
320 target,
321 { tx: { ...tx, cacheGenerationClaimId: access.claimId }, anchor },
322 resolution,
323 )
324 },
325 loadCollectionMetadata: async (
326 target: PersistedStorageTarget,
327 ctx?: { cacheGenerationClaimId?: string },
328 ): Promise<Array<{ key: string; value: unknown }>> => {
329 const access = resolvePersistedStorageTarget(
330 target,
331 ctx?.cacheGenerationClaimId,
332 )
333 return executeRequest(
334 `loadCollectionMetadata`,
335 target,
336 { ctx: { ...ctx, cacheGenerationClaimId: access.claimId } },
337 resolution,
338 )
339 },
340 scanRows: async (
341 target: PersistedStorageTarget,
342 options?: { metadataOnly?: boolean },
343 ctx?: { cacheGenerationClaimId?: string },
344 ): Promise<
345 Array<{
346 key: string | number
347 value: Record<string, unknown>
348 metadata?: unknown
349 }>
350 > => {
351 const access = resolvePersistedStorageTarget(
352 target,
353 ctx?.cacheGenerationClaimId,
354 )
355 const result = await executeRequest(
356 `scanRows`,
357 target,
358 { options, ctx: { ...ctx, cacheGenerationClaimId: access.claimId } },
359 resolution,
360 )
361 return result as Array<{
362 key: string | number
363 value: Record<string, unknown>
364 metadata?: unknown
365 }>
366 },
367 ensureIndex: async (
368 target: PersistedStorageTarget,
369 signature: string,
370 spec: PersistedIndexSpec,
371 ctx?: { cacheGenerationClaimId?: string },
372 ): Promise<void> => {
373 const access = resolvePersistedStorageTarget(
374 target,
375 ctx?.cacheGenerationClaimId,
376 )
377 await executeRequest(
378 `ensureIndex`,
379 target,
380 {
381 signature,
382 spec,
383 ctx: { ...ctx, cacheGenerationClaimId: access.claimId },
384 },
385 resolution,
386 )
387 },
388 markIndexRemoved: async (
389 target: PersistedStorageTarget,
390 signature: string,
391 ctx?: { cacheGenerationClaimId?: string },
392 ): Promise<void> => {
393 const access = resolvePersistedStorageTarget(
394 target,
395 ctx?.cacheGenerationClaimId,
396 )
397 await executeRequest(
398 `markIndexRemoved`,
399 target,
400 {
401 signature,
402 ctx: { ...ctx, cacheGenerationClaimId: access.claimId },
403 },
404 resolution,
405 )
406 },
407 pullSince: async (
408 target: PersistedStorageTarget,
409 fromRowVersion: number,
410 ctx?: { cacheGenerationClaimId?: string },
411 ): Promise<SQLitePullSinceResult<string | number>> => {
412 const access = resolvePersistedStorageTarget(
413 target,
414 ctx?.cacheGenerationClaimId,
415 )
416 const result = await executeRequest(
417 `pullSince`,
418 target,
419 {
420 fromRowVersion,
421 ctx: { ...ctx, cacheGenerationClaimId: access.claimId },
422 },
423 resolution,
424 )
425 return result as SQLitePullSinceResult<string | number>
426 },
427 getStreamPosition: async (
428 target: PersistedStorageTarget,
429 ctx?: { cacheGenerationClaimId?: string },
430 ): Promise<{
431 latestTerm: number
432 latestSeq: number
433 latestRowVersion: number
434 }> => {
435 const access = resolvePersistedStorageTarget(
436 target,
437 ctx?.cacheGenerationClaimId,
438 )
439 return executeRequest(
440 `getStreamPosition`,
441 target,
442 { ctx: { ...ctx, cacheGenerationClaimId: access.claimId } },
443 resolution,
444 )
445 },
446 claimCacheGeneration: async (
447 collectionId: string,
448 ): Promise<PersistedCacheGenerationClaim> => {
449 const claim = await executeRequest(
450 `claimCacheGeneration`,
451 collectionId,
452 {},
453 resolution,
454 )
455 claimCollections.set(claim.claimId, collectionId)
456 return claim
457 },
458 rotateCacheGeneration: async (
459 collectionId: string,
460 claimId: string,
461 resetMetadata?: { key: string; value: unknown },
462 expectedStorageCollectionId?: string,
463 ): Promise<PersistedCacheGenerationClaim> => {
464 const claim = await executeRequest(
465 `rotateCacheGeneration`,
466 collectionId,
467 { claimId, resetMetadata, expectedStorageCollectionId },
468 resolution,
469 )
470 claimCollections.delete(claimId)
471 claimCollections.set(claim.claimId, collectionId)
472 return claim
473 },
474 renewCacheGenerationClaim: (
475 storageCollectionId: string,
476 claimId: string,
477 ): Promise<number | undefined> => {
478 const collectionId = claimCollections.get(claimId)
479 if (!collectionId) {
480 throw new InvalidPersistedCollectionConfigError(
481 `Unknown electron persisted cache claim "${claimId}"`,
482 )
483 }
484 return executeRequest(
485 `renewCacheGenerationClaim`,
486 collectionId,
487 { storageCollectionId, claimId },
488 resolution,
489 )
490 },
491 releaseCacheGenerationClaim: async (claimId: string): Promise<void> => {
492 const collectionId = claimCollections.get(claimId)
493 if (!collectionId) {
494 throw new InvalidPersistedCollectionConfigError(
495 `Unknown electron persisted cache claim "${claimId}"`,
496 )
497 }
498 await executeRequest(
499 `releaseCacheGenerationClaim`,
500 collectionId,
501 { claimId },
502 resolution,
503 )
504 claimCollections.delete(claimId)
505 },
506 reserveLeadershipTerm: async (target, observedTerm, ctx) => {
507 const access = resolvePersistedStorageTarget(
508 target,
509 ctx?.cacheGenerationClaimId,
510 )
511 return executeRequest(
512 `reserveLeadershipTerm`,
513 target,
514 {
515 observedTerm,
516 ctx: { ...ctx, cacheGenerationClaimId: access.claimId },
517 },
518 resolution,
519 )
520 },
521 }
522 if (!managedCacheGenerations) {
523 adapter.claimCacheGeneration = undefined
524 adapter.rotateCacheGeneration = undefined
525 adapter.renewCacheGenerationClaim = undefined
526 adapter.releaseCacheGenerationClaim = undefined
527 }
528 return adapter
530​
531export type ElectronIpcRendererLike = {
532 invoke: (
533 channel: string,
534 request: ElectronPersistenceRequestEnvelope,
535 ) => Promise<ElectronPersistenceResponseEnvelope>
537​
538export type ElectronSQLitePersistenceOptions = {
539 invoke?: ElectronPersistenceInvoke
540 ipcRenderer?: ElectronIpcRendererLike
541 channel?: string
542 timeoutMs?: number
543 coordinator?: PersistedCollectionCoordinator
544 /** Set false when a custom main-process adapter does not manage cache generations. */
545 managedCacheGenerations?: boolean
547​
548function resolveInvoke(
549 options: ElectronSQLitePersistenceOptions,
550): ElectronPersistenceInvoke {
551 if (options.invoke) {
552 return options.invoke
553 }
554​
555 if (options.ipcRenderer) {
556 return (channel, request) => options.ipcRenderer!.invoke(channel, request)
557 }
558​
559 throw new InvalidPersistedCollectionConfigError(
560 `Electron renderer persistence requires either invoke or ipcRenderer`,
561 )
563​
564export function createElectronSQLitePersistence(
565 options: ElectronSQLitePersistenceOptions,
566): PersistedCollectionPersistence {
567 const invoke = resolveInvoke(options)
568 const coordinator = options.coordinator ?? new SingleProcessCoordinator()
569 const claimCollections = new Map<string, string>()
570 const executeRequest = createRendererRequestExecutor({
571 invoke,
572 channel: options.channel,
573 timeoutMs: options.timeoutMs,
574 claimCollections,
575 })
576 const adapterCache = new Map<string, ElectronRendererResolvedAdapter>()
577​
578 const getAdapterForCollection = (
579 collectionId: string | undefined,
580 mode: PersistedCollectionMode,
581 schemaVersion: number | undefined,
582 ) => {
583 const cacheKey = JSON.stringify([collectionId, mode, schemaVersion])
584 const cachedAdapter = adapterCache.get(cacheKey)
585 if (cachedAdapter) {
586 return cachedAdapter
587 }
588​
589 const adapter = createResolvedRendererAdapter(
590 executeRequest,
591 claimCollections,
592 options.managedCacheGenerations ?? true,
593 { mode, schemaVersion, logicalCollectionId: collectionId },
594 )
595 adapterCache.set(cacheKey, adapter)
596 return adapter
597 }
598​
599 const createCollectionPersistence = (
600 collectionId: string | undefined,
601 mode: PersistedCollectionMode,
602 schemaVersion: number | undefined,
603 ): PersistedCollectionPersistence => {
604 const adapter = getAdapterForCollection(collectionId, mode, schemaVersion)
605 if (coordinator instanceof ElectronCollectionCoordinator) {
606 if (collectionId === undefined) {
607 coordinator.setAdapter(adapter)
608 } else {
609 coordinator.setAdapterForCollection(collectionId, adapter)
610 }
611 }
612 return { adapter, coordinator }
613 }
614​
615 const defaultPersistence = createCollectionPersistence(
616 undefined,
617 `sync-absent`,
618 undefined,
619 )
620 if (coordinator instanceof ElectronCollectionCoordinator) {
621 coordinator.setAdapter(defaultPersistence.adapter)
622 }
623​
624 return {
625 ...defaultPersistence,
626 resolvePersistenceForCollection: ({ collectionId, mode, schemaVersion }) =>
627 createCollectionPersistence(collectionId, mode, schemaVersion),
628 // Backward compatible fallback for older callers.
629 resolvePersistenceForMode: (mode) =>
630 createCollectionPersistence(undefined, mode, undefined),
631 }