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

renderer.ts

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