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

main.ts

320 lines8.6 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 codedError = error as Error & { code?: unknown }
56 return {
57 name: error.name || `Error`,
58 message: error.message || fallbackMessage,
59 stack: error.stack,
60 code: typeof codedError.code === `string` ? codedError.code : undefined,
61 }
63​
64function createErrorResponse(
65 request: ElectronPersistenceRequestEnvelope,
66 error: unknown,
67): ElectronPersistenceResponseEnvelope {
68 return {
69 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
70 requestId: request.requestId,
71 method: request.method,
72 ok: false,
73 error: serializeError(error),
74 }
76​
77function assertValidRequest(request: ElectronPersistenceRequestEnvelope): void {
78 if (request.v !== ELECTRON_PERSISTENCE_PROTOCOL_VERSION) {
79 throw new InvalidPersistedCollectionConfigError(
80 `Unsupported electron persistence protocol version "${request.v}"`,
81 )
82 }
83​
84 if (
85 typeof request.requestId !== `string` ||
86 request.requestId.trim().length === 0
87 ) {
88 throw new InvalidPersistedCollectionConfigError(
89 `Electron persistence requestId cannot be empty`,
90 )
91 }
92​
93 if (
94 typeof request.collectionId !== `string` ||
95 request.collectionId.trim().length === 0
96 ) {
97 throw new InvalidPersistedCollectionConfigError(
98 `Electron persistence collectionId cannot be empty`,
99 )
100 }
102​
103async function executeRequestAgainstAdapter(
104 request: ElectronPersistenceRequestEnvelope,
105 adapter: ElectronMainPersistenceAdapter,
106): Promise<ElectronPersistenceResponseEnvelope> {
107 switch (request.method) {
108 case `loadSubset`: {
109 const result = await adapter.loadSubset(
110 request.collectionId,
111 request.payload.options,
112 request.payload.ctx,
113 )
114 return {
115 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
116 requestId: request.requestId,
117 method: request.method,
118 ok: true,
119 result,
120 }
121 }
122​
123 case `loadResumeSnapshot`: {
124 const result = await adapter.loadResumeSnapshot(
125 request.collectionId,
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 `loadCollectionMetadata`: {
138 if (!adapter.loadCollectionMetadata) {
139 throw new InvalidPersistedCollectionConfigError(
140 `loadCollectionMetadata is not supported by the configured electron persistence adapter`,
141 )
142 }
143 const result = await adapter.loadCollectionMetadata(request.collectionId)
144 return {
145 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
146 requestId: request.requestId,
147 method: request.method,
148 ok: true,
149 result,
150 }
151 }
152​
153 case `scanRows`: {
154 if (!adapter.scanRows) {
155 throw new InvalidPersistedCollectionConfigError(
156 `scanRows is not supported by the configured electron persistence adapter`,
157 )
158 }
159 const result = await adapter.scanRows(
160 request.collectionId,
161 request.payload.options,
162 )
163 return {
164 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
165 requestId: request.requestId,
166 method: request.method,
167 ok: true,
168 result,
169 }
170 }
171​
172 case `applyCommittedTx`: {
173 await adapter.applyCommittedTx(request.collectionId, request.payload.tx)
174 return {
175 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
176 requestId: request.requestId,
177 method: request.method,
178 ok: true,
179 result: null,
180 }
181 }
182​
183 case `ensureIndex`: {
184 await adapter.ensureIndex(
185 request.collectionId,
186 request.payload.signature,
187 request.payload.spec,
188 )
189 return {
190 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
191 requestId: request.requestId,
192 method: request.method,
193 ok: true,
194 result: null,
195 }
196 }
197​
198 case `markIndexRemoved`: {
199 if (!adapter.markIndexRemoved) {
200 throw new InvalidPersistedCollectionConfigError(
201 `markIndexRemoved is not supported by the configured electron persistence adapter`,
202 )
203 }
204 await adapter.markIndexRemoved(
205 request.collectionId,
206 request.payload.signature,
207 )
208 return {
209 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
210 requestId: request.requestId,
211 method: request.method,
212 ok: true,
213 result: null,
214 }
215 }
216​
217 case `pullSince`: {
218 if (!adapter.pullSince) {
219 throw new InvalidPersistedCollectionConfigError(
220 `pullSince is not supported by the configured electron persistence adapter`,
221 )
222 }
223 const result = await adapter.pullSince(
224 request.collectionId,
225 request.payload.fromRowVersion,
226 )
227 return {
228 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
229 requestId: request.requestId,
230 method: request.method,
231 ok: true,
232 result,
233 }
234 }
235​
236 case `getStreamPosition`: {
237 if (!adapter.getStreamPosition) {
238 throw new InvalidPersistedCollectionConfigError(
239 `getStreamPosition is not supported by the configured electron persistence adapter`,
240 )
241 }
242 const position = await adapter.getStreamPosition(request.collectionId)
243 return {
244 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
245 requestId: request.requestId,
246 method: request.method,
247 ok: true,
248 result: position,
249 }
250 }
251 }
253​
254function resolveModeAwarePersistence(
255 persistence: PersistedCollectionPersistence,
256 request: ElectronPersistenceRequestEnvelope,
257): PersistedCollectionPersistence {
258 const mode = request.resolution?.mode ?? `sync-absent`
259 const schemaVersion = request.resolution?.schemaVersion
260 const collectionAwarePersistence =
261 persistence.resolvePersistenceForCollection?.({
262 collectionId: request.collectionId,
263 mode,
264 schemaVersion,
265 })
266 if (collectionAwarePersistence) {
267 return collectionAwarePersistence
268 }
269​
270 const modeAwarePersistence = persistence.resolvePersistenceForMode?.(mode)
271 return modeAwarePersistence ?? persistence
273​
274export type ElectronIpcMainLike = {
275 handle: (
276 channel: string,
277 listener: (
278 event: unknown,
279 request: ElectronPersistenceRequestEnvelope,
280 ) => Promise<ElectronPersistenceResponseEnvelope>,
281 ) => void
282 removeHandler?: (channel: string) => void
284​
285export type ElectronSQLiteMainProcessOptions = {
286 persistence: PersistedCollectionPersistence
287 ipcMain: ElectronIpcMainLike
288 channel?: string
290​
291export function exposeElectronSQLitePersistence(
292 options: ElectronSQLiteMainProcessOptions,
293): () => void {
294 const channel = options.channel ?? DEFAULT_ELECTRON_PERSISTENCE_CHANNEL
295 options.ipcMain.handle(
296 channel,
297 async (
298 _event,
299 request: ElectronPersistenceRequestEnvelope,
300 ): Promise<ElectronPersistenceResponseEnvelope> => {
301 try {
302 assertValidRequest(request)
303 const modeAwarePersistence = resolveModeAwarePersistence(
304 options.persistence,
305 request,
306 )
307 return await executeRequestAgainstAdapter(
308 request,
309 modeAwarePersistence.adapter,
310 )
311 } catch (error) {
312 return createErrorResponse(request, error)
313 }
314 },
315 )
316​
317 return () => {
318 options.ipcMain.removeHandler?.(channel)
319 }