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

electron-main.mjs

485 lines12.4 KB

1import { dirname, join } from 'node:path'
2import { execFile } from 'node:child_process'
3import { promisify } from 'node:util'
4import { AsyncLocalStorage } from 'node:async_hooks'
5import { copyFileSync, existsSync, mkdtempSync, rmSync } from 'node:fs'
6import { tmpdir } from 'node:os'
7import { fileURLToPath } from 'node:url'
8import { serialize } from 'node:v8'
9import { BrowserWindow, app, ipcMain } from 'electron'
10import { createSQLiteCorePersistenceAdapter } from '@tanstack/db-sqlite-persistence-core'
11import { exposeElectronSQLitePersistence } from '../../../dist/esm/main.js'
12​
13const E2E_RESULT_PREFIX = `__TANSTACK_DB_E2E_RESULT__:`
14const E2E_RESULT_BASE64_PREFIX = `__TANSTACK_DB_E2E_RESULT_BASE64__:`
15const E2E_INPUT_ENV_VAR = `TANSTACK_DB_E2E_INPUT`
16const E2E_TRANSPORT_TYPE_TAG = `__tanstack_db_e2e_transport_type__`
17const E2E_TRANSPORT_VALUE_TAG = `value`
18const execFileAsync = promisify(execFile)
19​
20function toSqlLiteral(value) {
21 if (value === null || value === undefined) {
22 return `NULL`
23 }
24​
25 if (typeof value === `number`) {
26 return Number.isFinite(value) ? String(value) : `NULL`
27 }
28​
29 if (typeof value === `boolean`) {
30 return value ? `1` : `0`
31 }
32​
33 if (typeof value === `bigint`) {
34 return value.toString()
35 }
36​
37 const textValue = typeof value === `string` ? value : String(value)
38 return `'${textValue.replace(/'/g, `''`)}'`
40​
41function interpolateSql(sql, params) {
42 let parameterIndex = 0
43 const renderedSql = sql.replace(/\?/g, () => {
44 const currentParam = params[parameterIndex]
45 parameterIndex++
46 return toSqlLiteral(currentParam)
47 })
48​
49 if (parameterIndex !== params.length) {
50 throw new Error(
51 `SQL interpolation mismatch: used ${parameterIndex} params, received ${params.length}`,
52 )
53 }
54​
55 return renderedSql
57​
58class SqliteCliDriver {
59 transactionDbPath = new AsyncLocalStorage()
60 queue = Promise.resolve()
61​
62 constructor(dbPath) {
63 this.dbPath = dbPath
64 }
65​
66 async exec(sql) {
67 const activeDbPath = this.transactionDbPath.getStore()
68 if (activeDbPath) {
69 await execFileAsync(`sqlite3`, [activeDbPath, sql])
70 return
71 }
72​
73 await this.enqueue(async () => {
74 await execFileAsync(`sqlite3`, [this.dbPath, sql])
75 })
76 }
77​
78 async query(sql, params = []) {
79 const activeDbPath = this.transactionDbPath.getStore()
80 const renderedSql = interpolateSql(sql, params)
81 const queryDbPath = activeDbPath ?? this.dbPath
82​
83 const runQuery = async () => {
84 const { stdout } = await execFileAsync(`sqlite3`, [
85 `-json`,
86 queryDbPath,
87 renderedSql,
88 ])
89 const trimmedOutput = stdout.trim()
90 if (!trimmedOutput) {
91 return []
92 }
93​
94 return JSON.parse(trimmedOutput)
95 }
96​
97 if (activeDbPath) {
98 return runQuery()
99 }
100​
101 return this.enqueue(async () => runQuery())
102 }
103​
104 async run(sql, params = []) {
105 const activeDbPath = this.transactionDbPath.getStore()
106 const renderedSql = interpolateSql(sql, params)
107 const runDbPath = activeDbPath ?? this.dbPath
108​
109 if (activeDbPath) {
110 await execFileAsync(`sqlite3`, [runDbPath, renderedSql])
111 return
112 }
113​
114 await this.enqueue(async () => {
115 await execFileAsync(`sqlite3`, [runDbPath, renderedSql])
116 })
117 }
118​
119 async transaction(fn) {
120 const activeDbPath = this.transactionDbPath.getStore()
121 if (activeDbPath) {
122 return fn(this)
123 }
124​
125 return this.enqueue(async () => {
126 const txDirectory = mkdtempSync(join(tmpdir(), `db-electron-e2e-tx-`))
127 const txDbPath = join(txDirectory, `state.sqlite`)
128​
129 if (existsSync(this.dbPath)) {
130 copyFileSync(this.dbPath, txDbPath)
131 }
132​
133 try {
134 const txResult = await this.transactionDbPath.run(txDbPath, async () =>
135 fn(this),
136 )
137 if (existsSync(txDbPath)) {
138 copyFileSync(txDbPath, this.dbPath)
139 }
140 return txResult
141 } finally {
142 rmSync(txDirectory, { recursive: true, force: true })
143 }
144 })
145 }
146​
147 enqueue(operation) {
148 const queuedOperation = this.queue.then(operation, operation)
149 this.queue = queuedOperation.then(
150 () => undefined,
151 () => undefined,
152 )
153 return queuedOperation
154 }
156​
157function parseInputFromEnv() {
158 const rawInput = process.env[E2E_INPUT_ENV_VAR]
159 if (!rawInput) {
160 throw new Error(`Missing ${E2E_INPUT_ENV_VAR}`)
161 }
162​
163 const parsed = JSON.parse(rawInput)
164 const decoded = decodeTransportValue(parsed)
165 if (!decoded || typeof decoded !== `object`) {
166 throw new Error(`Invalid ${E2E_INPUT_ENV_VAR} payload`)
167 }
168​
169 return decoded
171​
172function isEncodedTransportValue(value) {
173 return (
174 value &&
175 typeof value === `object` &&
176 typeof value[E2E_TRANSPORT_TYPE_TAG] === `string`
177 )
179​
180function decodeTransportValue(value) {
181 if (value === null) {
182 return null
183 }
184​
185 if (
186 typeof value === `string` ||
187 typeof value === `number` ||
188 typeof value === `boolean`
189 ) {
190 return value
191 }
192​
193 if (Array.isArray(value)) {
194 return value.map((item) => decodeTransportValue(item))
195 }
196​
197 if (isEncodedTransportValue(value)) {
198 switch (value[E2E_TRANSPORT_TYPE_TAG]) {
199 case `bigint`:
200 return BigInt(value[E2E_TRANSPORT_VALUE_TAG])
201 case `date`:
202 return new Date(value[E2E_TRANSPORT_VALUE_TAG])
203 case `date_invalid`:
204 return new Date(Number.NaN)
205 case `nan`:
206 return Number.NaN
207 case `infinity`:
208 return Number.POSITIVE_INFINITY
209 case `-infinity`:
210 return Number.NEGATIVE_INFINITY
211 default:
212 break
213 }
214 }
215​
216 if (typeof value === `object`) {
217 const decodedObject = {}
218 for (const [key, objectValue] of Object.entries(value)) {
219 decodedObject[key] = decodeTransportValue(objectValue)
220 }
221 return decodedObject
222 }
223​
224 return value
226​
227function printProcessResult(result) {
228 try {
229 const serializedResult = Buffer.from(serialize(result)).toString(`base64`)
230 process.stdout.write(`${E2E_RESULT_BASE64_PREFIX}${serializedResult}\n`)
231 } catch {
232 process.stdout.write(`${E2E_RESULT_PREFIX}${JSON.stringify(result)}\n`)
233 }
235​
236function getPreloadPath() {
237 const currentFile = fileURLToPath(import.meta.url)
238 return join(dirname(currentFile), `renderer-preload.cjs`)
240​
241function getRendererPagePath() {
242 const currentFile = fileURLToPath(import.meta.url)
243 return join(dirname(currentFile), `renderer-page.html`)
245​
246function serializeError(error) {
247 if (error instanceof Error) {
248 return {
249 name: error.name,
250 message: error.message,
251 stack: error.stack,
252 }
253 }
254​
255 return {
256 name: `Error`,
257 message: `Unknown runtime error`,
258 }
260​
261function createUnknownCollectionError(collectionId) {
262 const error = new Error(
263 `Unknown electron persistence collection "${collectionId}"`,
264 )
265 error.name = `UnknownElectronPersistenceCollectionError`
266 error.code = `UNKNOWN_COLLECTION`
267 return error
269​
270function requireAllowedTarget(target, collectionId) {
271 const addressedId =
272 target?.kind === `managed`
273 ? target.storageCollectionId
274 : target?.kind === `eager`
275 ? target.collectionId
276 : undefined
277 if (addressedId !== collectionId) {
278 throw createUnknownCollectionError(addressedId)
279 }
280 return target
282​
283function createMainPersistence(input, driver) {
284 const adapter = createSQLiteCorePersistenceAdapter({
285 driver,
286 ...(input.adapterOptions ?? {}),
287 })
288​
289 if (input.allowAnyCollectionId) {
290 return {
291 persistence: {
292 adapter,
293 },
294 cleanup: () => {},
295 }
296 }
297​
298 return {
299 persistence: {
300 adapter: {
301 loadSubset: (target, options, ctx) => {
302 return adapter.loadSubset(
303 requireAllowedTarget(target, input.collectionId),
304 options,
305 ctx,
306 )
307 },
308 loadResumeSnapshot: (target, ctx) => {
309 return adapter.loadResumeSnapshot(
310 requireAllowedTarget(target, input.collectionId),
311 ctx,
312 )
313 },
314 loadCollectionMetadata: (target, ctx) => {
315 return adapter.loadCollectionMetadata(
316 requireAllowedTarget(target, input.collectionId),
317 ctx,
318 )
319 },
320 scanRows: (target, options, ctx) => {
321 return adapter.scanRows(
322 requireAllowedTarget(target, input.collectionId),
323 options,
324 ctx,
325 )
326 },
327 applyCommittedTx: (target, tx) => {
328 return adapter.applyCommittedTx(
329 requireAllowedTarget(target, input.collectionId),
330 tx,
331 )
332 },
333 reconcileCommittedTx: (target, tx, anchor) => {
334 return adapter.reconcileCommittedTx(
335 requireAllowedTarget(target, input.collectionId),
336 tx,
337 anchor,
338 )
339 },
340 ensureIndex: (target, signature, spec, ctx) => {
341 return adapter.ensureIndex(
342 requireAllowedTarget(target, input.collectionId),
343 signature,
344 spec,
345 ctx,
346 )
347 },
348 markIndexRemoved: (target, signature, ctx) => {
349 return adapter.markIndexRemoved?.(
350 requireAllowedTarget(target, input.collectionId),
351 signature,
352 ctx,
353 )
354 },
355 pullSince: (target, fromRowVersion, ctx) => {
356 return adapter.pullSince?.(
357 requireAllowedTarget(target, input.collectionId),
358 fromRowVersion,
359 ctx,
360 )
361 },
362 getStreamPosition: (target, ctx) => {
363 return adapter.getStreamPosition(
364 requireAllowedTarget(target, input.collectionId),
365 ctx,
366 )
367 },
368 reserveLeadershipTerm: (target, observedTerm, ctx) => {
369 return adapter.reserveLeadershipTerm(
370 requireAllowedTarget(target, input.collectionId),
371 observedTerm,
372 ctx,
373 )
374 },
375 },
376 },
377 cleanup: () => {},
378 }
380​
381async function run() {
382 app.commandLine.appendSwitch(`disable-gpu`)
383 app.commandLine.appendSwitch(`disable-dev-shm-usage`)
384 app.commandLine.appendSwitch(`no-sandbox`)
385​
386 const input = parseInputFromEnv()
387 const driver = new SqliteCliDriver(input.dbPath)
388 const mainRuntime = createMainPersistence(input, driver)
389 const disposeIpc = exposeElectronSQLitePersistence({
390 ipcMain,
391 persistence: mainRuntime.persistence,
392 channel: input.channel,
393 })
394​
395 let window
396 try {
397 await app.whenReady()
398 window = new BrowserWindow({
399 show: false,
400 webPreferences: {
401 contextIsolation: true,
402 nodeIntegration: false,
403 sandbox: false,
404 preload: getPreloadPath(),
405 },
406 })
407​
408 const rendererDiagnostics = []
409 window.webContents.on(
410 `console-message`,
411 (_event, level, message, line, sourceId) => {
412 rendererDiagnostics.push(
413 `[console:${String(level)}] ${sourceId}:${String(line)} ${message}`,
414 )
415 },
416 )
417 window.webContents.on(`preload-error`, (_event, path, error) => {
418 rendererDiagnostics.push(
419 `[preload-error] ${path}: ${error?.message ?? `unknown preload error`}`,
420 )
421 })
422​
423 await window.loadFile(getRendererPagePath())
424​
425 const scenarioInputBase64 = Buffer.from(
426 serialize({
427 collectionId: input.collectionId,
428 allowAnyCollectionId: input.allowAnyCollectionId,
429 hostKind: input.hostKind,
430 adapterOptions: input.adapterOptions,
431 channel: input.channel,
432 timeoutMs: input.timeoutMs,
433 scenario: input.scenario,
434 }),
435 ).toString(`base64`)
436​
437 const hasBridgeApi = await window.webContents.executeJavaScript(
438 `typeof window.__tanstackDbRuntimeBridge__ === 'object'`,
439 true,
440 )
441 if (!hasBridgeApi) {
442 throw new Error(
443 `Renderer preload bridge is unavailable.\n${rendererDiagnostics.join(`\n`)}`,
444 )
445 }
446​
447 let result
448 try {
449 result = await window.webContents.executeJavaScript(
450 `window.__tanstackDbRuntimeBridge__.runScenarioFromBase64('${scenarioInputBase64}')`,
451 true,
452 )
453 } catch (error) {
454 const message = error instanceof Error ? error.message : `Unknown error`
455 throw new Error(
456 `Renderer scenario execution failed: ${message}\n${rendererDiagnostics.join(`\n`)}`,
457 )
458 }
459​
460 return {
461 ok: true,
462 result,
463 }
464 } finally {
465 if (window) {
466 window.destroy()
467 }
468 disposeIpc()
469 mainRuntime.cleanup()
470 await app.quit()
471 }
473​
474void run()
475 .then((result) => {
476 printProcessResult(result)
477 process.exitCode = 0
478 })
479 .catch((error) => {
480 printProcessResult({
481 ok: false,
482 error: serializeError(error),
483 })
484 process.exitCode = 1
485 })