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

main.ts

370 lines10.1 KB

1import { InvalidPersistedCollectionConfigError } from '@tanstack/db-sqlite-persistence-core'
2import {
3 DEFAULT_ELECTRON_PERSISTENCE_CHANNEL,
4 ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
5} from './protocol'
6import type {
7 PersistedCollectionPersistence,
8 PersistenceAdapter,
9 SQLitePullSinceResult,
10} from '@tanstack/db-sqlite-persistence-core'
11import type {
12 ElectronPersistedKey,
13 ElectronPersistedRow,
14 ElectronPersistenceRequestEnvelope,
15 ElectronPersistenceResponseEnvelope,
16 ElectronSerializedError,
17} from './protocol'
18​
19type ElectronMainPersistenceAdapter = PersistenceAdapter & {
20 loadCollectionMetadata?: (
21 collectionId: string,
22 ) => Promise<Array<{ key: string; value: unknown }>>
23 scanRows?: (
24 collectionId: string,
25 options?: { metadataOnly?: boolean },
26 ) => Promise<
27 Array<{
28 key: ElectronPersistedKey
29 value: ElectronPersistedRow
30 metadata?: unknown
31 }>
32 >
33 pullSince?: (
34 collectionId: string,
35 fromRowVersion: number,
36 ) => Promise<SQLitePullSinceResult<ElectronPersistedKey>>
37 getStreamPosition?: (collectionId: string) => Promise<{
38 latestTerm: number
39 latestSeq: number
40 latestRowVersion: number
41 }>
43​
44function serializeError(error: unknown): ElectronSerializedError {
45 const fallbackMessage = `Unknown electron persistence error`
46​
47 if (!(error instanceof Error)) {
48 return {
49 name: `Error`,
50 message: fallbackMessage,
51 code: undefined,
52 }
53 }
54​
55 const detailedError = error as Error & { code?: unknown; path?: unknown }
56 const path = detailedError.path
57 return {
58 name: error.name || `Error`,
59 message: error.message || fallbackMessage,
60 stack: error.stack,
61 code:
62 typeof detailedError.code === `string` ||
63 typeof detailedError.code === `number`
64 ? detailedError.code
65 : undefined,
66 path:
67 typeof path === `string` ||
68 (Array.isArray(path) &&
69 path.every(
70 (segment: unknown) =>
71 typeof segment === `string` || typeof segment === `number`,
72 ))
73 ? (path as string | ReadonlyArray<string | number>)
74 : undefined,
75 }
77​
78function createErrorResponse(
79 request: ElectronPersistenceRequestEnvelope,
80 error: unknown,
81): ElectronPersistenceResponseEnvelope {
82 return {
83 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
84 requestId: request.requestId,
85 method: request.method,
86 ok: false,
87 error: serializeError(error),
88 }
90​
91function assertValidRequest(request: ElectronPersistenceRequestEnvelope): void {
92 if (request.v !== ELECTRON_PERSISTENCE_PROTOCOL_VERSION) {
93 throw new InvalidPersistedCollectionConfigError(
94 `Unsupported electron persistence protocol version "${request.v}"`,
95 )
96 }
97​
98 if (
99 typeof request.requestId !== `string` ||
100 request.requestId.trim().length === 0
101 ) {
102 throw new InvalidPersistedCollectionConfigError(
103 `Electron persistence requestId cannot be empty`,
104 )
105 }
106​
107 if (
108 typeof request.collectionId !== `string` ||
109 request.collectionId.trim().length === 0
110 ) {
111 throw new InvalidPersistedCollectionConfigError(
112 `Electron persistence collectionId cannot be empty`,
113 )
114 }
116​
117async function executeRequestAgainstAdapter(
118 request: ElectronPersistenceRequestEnvelope,
119 adapter: ElectronMainPersistenceAdapter,
120): Promise<ElectronPersistenceResponseEnvelope> {
121 switch (request.method) {
122 case `loadSubset`: {
123 const result = await adapter.loadSubset(
124 request.collectionId,
125 request.payload.options,
126 request.payload.ctx,
127 )
128 return {
129 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
130 requestId: request.requestId,
131 method: request.method,
132 ok: true,
133 result,
134 }
135 }
136​
137 case `loadResumeSnapshot`: {
138 const result = await adapter.loadResumeSnapshot(
139 request.collectionId,
140 request.payload.ctx,
141 )
142 return {
143 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
144 requestId: request.requestId,
145 method: request.method,
146 ok: true,
147 result,
148 }
149 }
150​
151 case `loadCollectionMetadata`: {
152 if (!adapter.loadCollectionMetadata) {
153 throw new InvalidPersistedCollectionConfigError(
154 `loadCollectionMetadata is not supported by the configured electron persistence adapter`,
155 )
156 }
157 const result = await adapter.loadCollectionMetadata(request.collectionId)
158 return {
159 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
160 requestId: request.requestId,
161 method: request.method,
162 ok: true,
163 result,
164 }
165 }
166​
167 case `scanRows`: {
168 if (!adapter.scanRows) {
169 throw new InvalidPersistedCollectionConfigError(
170 `scanRows is not supported by the configured electron persistence adapter`,
171 )
172 }
173 const result = await adapter.scanRows(
174 request.collectionId,
175 request.payload.options,
176 )
177 return {
178 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
179 requestId: request.requestId,
180 method: request.method,
181 ok: true,
182 result,
183 }
184 }
185​
186 case `applyCommittedTx`: {
187 await adapter.applyCommittedTx(request.collectionId, request.payload.tx)
188 return {
189 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
190 requestId: request.requestId,
191 method: request.method,
192 ok: true,
193 result: null,
194 }
195 }
196​
197 case `reconcileCommittedTx`: {
198 const result = adapter.reconcileCommittedTx
199 ? await adapter.reconcileCommittedTx(
200 request.collectionId,
201 request.payload.tx,
202 request.payload.anchor,
203 )
204 : { kind: `unknown` as const }
205 return {
206 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
207 requestId: request.requestId,
208 method: request.method,
209 ok: true,
210 result,
211 }
212 }
213​
214 case `ensureIndex`: {
215 await adapter.ensureIndex(
216 request.collectionId,
217 request.payload.signature,
218 request.payload.spec,
219 )
220 return {
221 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
222 requestId: request.requestId,
223 method: request.method,
224 ok: true,
225 result: null,
226 }
227 }
228​
229 case `markIndexRemoved`: {
230 if (!adapter.markIndexRemoved) {
231 throw new InvalidPersistedCollectionConfigError(
232 `markIndexRemoved is not supported by the configured electron persistence adapter`,
233 )
234 }
235 await adapter.markIndexRemoved(
236 request.collectionId,
237 request.payload.signature,
238 )
239 return {
240 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
241 requestId: request.requestId,
242 method: request.method,
243 ok: true,
244 result: null,
245 }
246 }
247​
248 case `pullSince`: {
249 if (!adapter.pullSince) {
250 throw new InvalidPersistedCollectionConfigError(
251 `pullSince is not supported by the configured electron persistence adapter`,
252 )
253 }
254 const result = await adapter.pullSince(
255 request.collectionId,
256 request.payload.fromRowVersion,
257 )
258 return {
259 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
260 requestId: request.requestId,
261 method: request.method,
262 ok: true,
263 result,
264 }
265 }
266​
267 case `reserveLeadershipTerm`: {
268 if (!adapter.reserveLeadershipTerm) {
269 throw new InvalidPersistedCollectionConfigError(
270 `reserveLeadershipTerm is not supported by the configured electron persistence adapter`,
271 )
272 }
273 const position = await adapter.reserveLeadershipTerm(
274 request.collectionId,
275 request.payload.observedTerm,
276 )
277 return {
278 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
279 requestId: request.requestId,
280 method: request.method,
281 ok: true,
282 result: position,
283 }
284 }
285​
286 case `getStreamPosition`: {
287 if (!adapter.getStreamPosition) {
288 throw new InvalidPersistedCollectionConfigError(
289 `getStreamPosition is not supported by the configured electron persistence adapter`,
290 )
291 }
292 const position = await adapter.getStreamPosition(request.collectionId)
293 return {
294 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
295 requestId: request.requestId,
296 method: request.method,
297 ok: true,
298 result: position,
299 }
300 }
301 }
303​
304function resolveModeAwarePersistence(
305 persistence: PersistedCollectionPersistence,
306 request: ElectronPersistenceRequestEnvelope,
307): PersistedCollectionPersistence {
308 const mode = request.resolution?.mode ?? `sync-absent`
309 const schemaVersion = request.resolution?.schemaVersion
310 const collectionAwarePersistence =
311 persistence.resolvePersistenceForCollection?.({
312 collectionId: request.collectionId,
313 mode,
314 schemaVersion,
315 })
316 if (collectionAwarePersistence) {
317 return collectionAwarePersistence
318 }
319​
320 const modeAwarePersistence = persistence.resolvePersistenceForMode?.(mode)
321 return modeAwarePersistence ?? persistence
323​
324export type ElectronIpcMainLike = {
325 handle: (
326 channel: string,
327 listener: (
328 event: unknown,
329 request: ElectronPersistenceRequestEnvelope,
330 ) => Promise<ElectronPersistenceResponseEnvelope>,
331 ) => void
332 removeHandler?: (channel: string) => void
334​
335export type ElectronSQLiteMainProcessOptions = {
336 persistence: PersistedCollectionPersistence
337 ipcMain: ElectronIpcMainLike
338 channel?: string
340​
341export function exposeElectronSQLitePersistence(
342 options: ElectronSQLiteMainProcessOptions,
343): () => void {
344 const channel = options.channel ?? DEFAULT_ELECTRON_PERSISTENCE_CHANNEL
345 options.ipcMain.handle(
346 channel,
347 async (
348 _event,
349 request: ElectronPersistenceRequestEnvelope,
350 ): Promise<ElectronPersistenceResponseEnvelope> => {
351 try {
352 assertValidRequest(request)
353 const modeAwarePersistence = resolveModeAwarePersistence(
354 options.persistence,
355 request,
356 )
357 return await executeRequestAgainstAdapter(
358 request,
359 modeAwarePersistence.adapter,
360 )
361 } catch (error) {
362 return createErrorResponse(request, error)
363 }
364 },
365 )
366​
367 return () => {
368 options.ipcMain.removeHandler?.(channel)
369 }