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

renderer.ts

412 lines11.2 KB

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