Open History to see the last commit
1import { spawn } from 'node:child_process'
2import { existsSync } from 'node:fs'
3import { createRequire } from 'node:module'
4import { dirname, join } from 'node:path'
5import { fileURLToPath } from 'node:url'
6import { deserialize } from 'node:v8'
7import { DEFAULT_ELECTRON_PERSISTENCE_CHANNEL } from '../../src/protocol'
8import {
9 E2E_RESULT_BASE64_PREFIX,
10 E2E_RESULT_PREFIX,
11} from './fixtures/runtime-bridge-types'
12import type { ElectronPersistenceInvoke } from '../../src/protocol'
13import type {
14 ElectronRuntimeBridgeAdapterOptions,
15 ElectronRuntimeBridgeHostKind,
16 ElectronRuntimeBridgeInput,
17 ElectronRuntimeBridgeProcessResult,
18 ElectronRuntimeBridgeScenarioResult,
19} from './fixtures/runtime-bridge-types'
20
21const ELECTRON_SCENARIO_TIMEOUT_MS = 20_000
22const require = createRequire(import.meta.url)
23const currentFilePath = fileURLToPath(import.meta.url)
24const e2eDirectory = dirname(currentFilePath)
25const testsDirectory = dirname(e2eDirectory)
26const packageRoot = dirname(testsDirectory)
27const electronRunnerPath = join(e2eDirectory, `fixtures`, `electron-main.mjs`)
28const E2E_INPUT_ENV_VAR = `TANSTACK_DB_E2E_INPUT`
29const E2E_TRANSPORT_TYPE_TAG = `__tanstack_db_e2e_transport_type__`
30const E2E_TRANSPORT_VALUE_TAG = `value`
31
32export const ELECTRON_FULL_E2E_ENV_VAR = `TANSTACK_DB_ELECTRON_E2E_ALL`
33
34export function isElectronFullE2EEnabled(): boolean {
35 return process.env[ELECTRON_FULL_E2E_ENV_VAR] === `1`
36}
37
38type CreateElectronRuntimeBridgeInvokeOptions = {
39 dbPath: string
40 collectionId: string
41 allowAnyCollectionId?: boolean
42 timeoutMs?: number
43 hostKind?: ElectronRuntimeBridgeHostKind
44 adapterOptions?: ElectronRuntimeBridgeAdapterOptions
45}
46
47function createElectronScenarioEnv(
48 input: ElectronRuntimeBridgeInput,
49): NodeJS.ProcessEnv {
50 const childEnv: NodeJS.ProcessEnv = { ...process.env }
51
52 delete childEnv.NODE_V8_COVERAGE
53
54 for (const envKey of Object.keys(childEnv)) {
55 if (
56 envKey.startsWith(`VITEST_`) ||
57 envKey.startsWith(`__VITEST_`) ||
58 envKey.startsWith(`NYC_`)
59 ) {
60 delete childEnv[envKey]
61 }
62 }
63
64 childEnv[E2E_INPUT_ENV_VAR] = encodeInputForEnv(input)
65 childEnv.ELECTRON_DISABLE_SECURITY_WARNINGS = `true`
66
67 return childEnv
68}
69
70function resolveElectronBinaryPath(): string {
71 const electronModuleValue: unknown = require(`electron`)
72 if (
73 typeof electronModuleValue !== `string` ||
74 electronModuleValue.length === 0
75 ) {
76 throw new Error(`Failed to resolve electron binary path`)
77 }
78 return electronModuleValue
79}
80
81function parseScenarioResult(
82 stdoutBuffer: string,
83 stderrBuffer: string,
84 exitCode: number | null,
85): ElectronRuntimeBridgeProcessResult {
86 const outputLines = stdoutBuffer.split(/\r?\n/u)
87 const base64ResultLine = outputLines.find((line) =>
88 line.startsWith(E2E_RESULT_BASE64_PREFIX),
89 )
90 if (base64ResultLine) {
91 const rawResult = base64ResultLine.slice(E2E_RESULT_BASE64_PREFIX.length)
92 const serializedResult = Buffer.from(rawResult, `base64`)
93 return deserialize(serializedResult) as ElectronRuntimeBridgeProcessResult
94 }
95
96 const jsonResultLine = outputLines.find((line) =>
97 line.startsWith(E2E_RESULT_PREFIX),
98 )
99
100 if (!jsonResultLine) {
101 throw new Error(
102 [
103 `Electron e2e runner did not emit a result line`,
104 `exitCode=${String(exitCode)}`,
105 `stderr=${stderrBuffer}`,
106 `stdout=${stdoutBuffer}`,
107 ].join(`\n`),
108 )
109 }
110
111 const rawResult = jsonResultLine.slice(E2E_RESULT_PREFIX.length)
112 return JSON.parse(rawResult) as ElectronRuntimeBridgeProcessResult
113}
114
115function encodeTransportValue(
116 value: unknown,
117 ancestors: WeakSet<object> = new WeakSet<object>(),
118): unknown {
119 if (value === null) {
120 return null
121 }
122
123 if (
124 typeof value === `string` ||
125 typeof value === `boolean` ||
126 (typeof value === `number` && Number.isFinite(value))
127 ) {
128 return value
129 }
130
131 if (typeof value === `number`) {
132 if (Number.isNaN(value)) {
133 return {
134 [E2E_TRANSPORT_TYPE_TAG]: `nan`,
135 }
136 }
137 if (value === Number.POSITIVE_INFINITY) {
138 return {
139 [E2E_TRANSPORT_TYPE_TAG]: `infinity`,
140 }
141 }
142 if (value === Number.NEGATIVE_INFINITY) {
143 return {
144 [E2E_TRANSPORT_TYPE_TAG]: `-infinity`,
145 }
146 }
147 }
148
149 if (typeof value === `bigint`) {
150 return {
151 [E2E_TRANSPORT_TYPE_TAG]: `bigint`,
152 [E2E_TRANSPORT_VALUE_TAG]: value.toString(),
153 }
154 }
155
156 if (value instanceof Date) {
157 const timestamp = value.getTime()
158 if (Number.isNaN(timestamp)) {
159 return {
160 [E2E_TRANSPORT_TYPE_TAG]: `date_invalid`,
161 }
162 }
163 return {
164 [E2E_TRANSPORT_TYPE_TAG]: `date`,
165 [E2E_TRANSPORT_VALUE_TAG]: value.toISOString(),
166 }
167 }
168
169 if (Array.isArray(value)) {
170 if (ancestors.has(value)) {
171 return undefined
172 }
173 ancestors.add(value)
174 try {
175 return value.map((item) => {
176 const encodedItem = encodeTransportValue(item, ancestors)
177 return encodedItem === undefined ? null : encodedItem
178 })
179 } finally {
180 ancestors.delete(value)
181 }
182 }
183
184 if (
185 typeof value === `undefined` ||
186 typeof value === `function` ||
187 typeof value === `symbol`
188 ) {
189 return undefined
190 }
191
192 if (typeof value === `object`) {
193 if (ancestors.has(value)) {
194 return undefined
195 }
196 ancestors.add(value)
197 try {
198 const encodedObject: Record<string, unknown> = {}
199 for (const [key, objectValue] of Object.entries(
200 value as Record<string, unknown>,
201 )) {
202 const encodedObjectValue = encodeTransportValue(objectValue, ancestors)
203 if (encodedObjectValue !== undefined) {
204 encodedObject[key] = encodedObjectValue
205 }
206 }
207 return encodedObject
208 } finally {
209 ancestors.delete(value)
210 }
211 }
212
213 return undefined
214}
215
216function encodeInputForEnv(input: ElectronRuntimeBridgeInput): string {
217 const encodedInput = encodeTransportValue(input)
218 if (!encodedInput || typeof encodedInput !== `object`) {
219 throw new Error(`Failed to encode e2e runtime input`)
220 }
221 return JSON.stringify(encodedInput)
222}
223
224export async function runElectronRuntimeBridgeScenario(
225 input: ElectronRuntimeBridgeInput,
226): Promise<ElectronRuntimeBridgeScenarioResult> {
227 const scenarioTimeoutMs = Math.max(
228 ELECTRON_SCENARIO_TIMEOUT_MS,
229 (input.timeoutMs ?? 0) + 8_000,
230 )
231 const electronBinaryPath = resolveElectronBinaryPath()
232 const xvfbRunPath = `/usr/bin/xvfb-run`
233 const hasXvfbRun = existsSync(xvfbRunPath)
234 const electronArgs = [
235 `--disable-gpu`,
236 `--disable-dev-shm-usage`,
237 `--no-sandbox`,
238 electronRunnerPath,
239 ]
240 const command = hasXvfbRun ? xvfbRunPath : electronBinaryPath
241 const args = hasXvfbRun
242 ? [
243 `-a`,
244 `--server-args=-screen 0 1280x720x24`,
245 electronBinaryPath,
246 ...electronArgs,
247 ]
248 : electronArgs
249
250 const processResult = await new Promise<ElectronRuntimeBridgeProcessResult>(
251 (resolve, reject) => {
252 const child = spawn(command, args, {
253 cwd: packageRoot,
254 env: createElectronScenarioEnv(input),
255 stdio: [`ignore`, `pipe`, `pipe`],
256 })
257 let stdoutBuffer = ``
258 let stderrBuffer = ``
259 let isSettled = false
260 let resultFromStdout: ElectronRuntimeBridgeProcessResult | undefined
261 let gracefulCloseTimeout: ReturnType<typeof setTimeout> | undefined
262
263 const settle = (
264 callback: (result: ElectronRuntimeBridgeProcessResult) => void,
265 result: ElectronRuntimeBridgeProcessResult,
266 ) => {
267 if (isSettled) {
268 return
269 }
270 isSettled = true
271 clearTimeout(timeout)
272 if (gracefulCloseTimeout) {
273 clearTimeout(gracefulCloseTimeout)
274 }
275 callback(result)
276
277 if (!child.killed) {
278 child.kill(`SIGKILL`)
279 }
280 }
281
282 const rejectOnce = (error: unknown) => {
283 if (isSettled) {
284 return
285 }
286 isSettled = true
287 clearTimeout(timeout)
288 if (gracefulCloseTimeout) {
289 clearTimeout(gracefulCloseTimeout)
290 }
291 reject(error)
292 if (!child.killed) {
293 child.kill(`SIGKILL`)
294 }
295 }
296
297 const timeout = setTimeout(() => {
298 rejectOnce(
299 new Error(
300 [
301 `Electron e2e scenario timed out after ${String(scenarioTimeoutMs)}ms`,
302 `stderr=${stderrBuffer}`,
303 `stdout=${stdoutBuffer}`,
304 ].join(`\n`),
305 ),
306 )
307 }, scenarioTimeoutMs)
308
309 child.on(`error`, (error) => {
310 rejectOnce(error)
311 })
312
313 child.stdout.on(`data`, (chunk: Buffer) => {
314 stdoutBuffer += chunk.toString()
315
316 try {
317 const parsedResult = parseScenarioResult(
318 stdoutBuffer,
319 stderrBuffer,
320 null,
321 )
322 if (!resultFromStdout) {
323 resultFromStdout = parsedResult
324 gracefulCloseTimeout = setTimeout(() => {
325 settle(resolve, parsedResult)
326 }, 1_000)
327 }
328 } catch {
329 // Result line might not be complete yet.
330 }
331 })
332 child.stderr.on(`data`, (chunk: Buffer) => {
333 stderrBuffer += chunk.toString()
334 })
335
336 child.on(`close`, (exitCode) => {
337 if (isSettled) {
338 return
339 }
340
341 try {
342 if (resultFromStdout) {
343 settle(resolve, resultFromStdout)
344 return
345 }
346
347 const parsedResult = parseScenarioResult(
348 stdoutBuffer,
349 stderrBuffer,
350 exitCode,
351 )
352 settle(resolve, parsedResult)
353 } catch (error) {
354 rejectOnce(error)
355 }
356 })
357 },
358 )
359
360 if (!processResult.ok) {
361 throw new Error(
362 `Electron e2e runner failed: ${processResult.error.name}: ${processResult.error.message}`,
363 )
364 }
365
366 return processResult.result
367}
368
369export function createElectronRuntimeBridgeInvoke(
370 options: CreateElectronRuntimeBridgeInvokeOptions,
371): ElectronPersistenceInvoke {
372 let queue: Promise<void> = Promise.resolve()
373
374 return async (channel, request) => {
375 const queuedInvoke = queue.then(
376 () =>
377 runElectronRuntimeBridgeScenario({
378 dbPath: options.dbPath,
379 collectionId: options.collectionId,
380 allowAnyCollectionId: options.allowAnyCollectionId,
381 hostKind: options.hostKind,
382 adapterOptions: options.adapterOptions,
383 channel,
384 timeoutMs: options.timeoutMs ?? 4_000,
385 scenario: {
386 type: `invokeRequest`,
387 request,
388 },
389 }),
390 () =>
391 runElectronRuntimeBridgeScenario({
392 dbPath: options.dbPath,
393 collectionId: options.collectionId,
394 allowAnyCollectionId: options.allowAnyCollectionId,
395 hostKind: options.hostKind,
396 adapterOptions: options.adapterOptions,
397 channel,
398 timeoutMs: options.timeoutMs ?? 4_000,
399 scenario: {
400 type: `invokeRequest`,
401 request,
402 },
403 }),
404 )
405 queue = queuedInvoke.then(
406 () => undefined,
407 () => undefined,
408 )
409
410 const result = await queuedInvoke
411
412 if (result.type !== `invokeRequest`) {
413 throw new Error(`Unexpected invokeRequest result: ${result.type}`)
414 }
415
416 return result.response
417 }
418}
419
420export function withDefaultElectronChannel(
421 invoke: ElectronPersistenceInvoke,
422): ElectronPersistenceInvoke {
423 return (channel, request) =>
424 invoke(channel || DEFAULT_ELECTRON_PERSISTENCE_CHANNEL, request)
425}