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

main.ts

306 lines8.3 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 `loadCollectionMetadata`: {
124 if (!adapter.loadCollectionMetadata) {
125 throw new InvalidPersistedCollectionConfigError(
126 `loadCollectionMetadata is not supported by the configured electron persistence adapter`,
127 )
128 }
129 const result = await adapter.loadCollectionMetadata(request.collectionId)
130 return {
131 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
132 requestId: request.requestId,
133 method: request.method,
134 ok: true,
135 result,
136 }
137 }
138​
139 case `scanRows`: {
140 if (!adapter.scanRows) {
141 throw new InvalidPersistedCollectionConfigError(
142 `scanRows is not supported by the configured electron persistence adapter`,
143 )
144 }
145 const result = await adapter.scanRows(
146 request.collectionId,
147 request.payload.options,
148 )
149 return {
150 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
151 requestId: request.requestId,
152 method: request.method,
153 ok: true,
154 result,
155 }
156 }
157​
158 case `applyCommittedTx`: {
159 await adapter.applyCommittedTx(request.collectionId, request.payload.tx)
160 return {
161 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
162 requestId: request.requestId,
163 method: request.method,
164 ok: true,
165 result: null,
166 }
167 }
168​
169 case `ensureIndex`: {
170 await adapter.ensureIndex(
171 request.collectionId,
172 request.payload.signature,
173 request.payload.spec,
174 )
175 return {
176 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
177 requestId: request.requestId,
178 method: request.method,
179 ok: true,
180 result: null,
181 }
182 }
183​
184 case `markIndexRemoved`: {
185 if (!adapter.markIndexRemoved) {
186 throw new InvalidPersistedCollectionConfigError(
187 `markIndexRemoved is not supported by the configured electron persistence adapter`,
188 )
189 }
190 await adapter.markIndexRemoved(
191 request.collectionId,
192 request.payload.signature,
193 )
194 return {
195 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
196 requestId: request.requestId,
197 method: request.method,
198 ok: true,
199 result: null,
200 }
201 }
202​
203 case `pullSince`: {
204 if (!adapter.pullSince) {
205 throw new InvalidPersistedCollectionConfigError(
206 `pullSince is not supported by the configured electron persistence adapter`,
207 )
208 }
209 const result = await adapter.pullSince(
210 request.collectionId,
211 request.payload.fromRowVersion,
212 )
213 return {
214 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
215 requestId: request.requestId,
216 method: request.method,
217 ok: true,
218 result,
219 }
220 }
221​
222 case `getStreamPosition`: {
223 if (!adapter.getStreamPosition) {
224 throw new InvalidPersistedCollectionConfigError(
225 `getStreamPosition is not supported by the configured electron persistence adapter`,
226 )
227 }
228 const position = await adapter.getStreamPosition(request.collectionId)
229 return {
230 v: ELECTRON_PERSISTENCE_PROTOCOL_VERSION,
231 requestId: request.requestId,
232 method: request.method,
233 ok: true,
234 result: position,
235 }
236 }
237 }
239​
240function resolveModeAwarePersistence(
241 persistence: PersistedCollectionPersistence,
242 request: ElectronPersistenceRequestEnvelope,
243): PersistedCollectionPersistence {
244 const mode = request.resolution?.mode ?? `sync-absent`
245 const schemaVersion = request.resolution?.schemaVersion
246 const collectionAwarePersistence =
247 persistence.resolvePersistenceForCollection?.({
248 collectionId: request.collectionId,
249 mode,
250 schemaVersion,
251 })
252 if (collectionAwarePersistence) {
253 return collectionAwarePersistence
254 }
255​
256 const modeAwarePersistence = persistence.resolvePersistenceForMode?.(mode)
257 return modeAwarePersistence ?? persistence
259​
260export type ElectronIpcMainLike = {
261 handle: (
262 channel: string,
263 listener: (
264 event: unknown,
265 request: ElectronPersistenceRequestEnvelope,
266 ) => Promise<ElectronPersistenceResponseEnvelope>,
267 ) => void
268 removeHandler?: (channel: string) => void
270​
271export type ElectronSQLiteMainProcessOptions = {
272 persistence: PersistedCollectionPersistence
273 ipcMain: ElectronIpcMainLike
274 channel?: string
276​
277export function exposeElectronSQLitePersistence(
278 options: ElectronSQLiteMainProcessOptions,
279): () => void {
280 const channel = options.channel ?? DEFAULT_ELECTRON_PERSISTENCE_CHANNEL
281 options.ipcMain.handle(
282 channel,
283 async (
284 _event,
285 request: ElectronPersistenceRequestEnvelope,
286 ): Promise<ElectronPersistenceResponseEnvelope> => {
287 try {
288 assertValidRequest(request)
289 const modeAwarePersistence = resolveModeAwarePersistence(
290 options.persistence,
291 request,
292 )
293 return await executeRequestAgainstAdapter(
294 request,
295 modeAwarePersistence.adapter,
296 )
297 } catch (error) {
298 return createErrorResponse(request, error)
299 }
300 },
301 )
302​
303 return () => {
304 options.ipcMain.removeHandler?.(channel)
305 }