All files / cli/src/commands daemon-spawn.ts

0% Statements 0/17
0% Branches 0/4
0% Functions 0/2
0% Lines 0/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49                                                                                                 
import { spawn } from 'node:child_process';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
 
import { pingDaemon } from './daemon-client.ts';
 
const POLL_INTERVAL_MS = 100;
const MAX_POLLS = 300; // 30 seconds
 
/**
 * Ensure the daemon is running. If it is not, spawn it as a detached process
 * and wait until the socket becomes responsive.
 *
 * @param socketPath - The UNIX socket path.
 */
export async function ensureDaemon(socketPath: string): Promise<void> {
  if (await pingDaemon(socketPath)) {
    return;
  }
 
  process.stderr.write('Starting daemon...\n');
 
  const currentDir = dirname(fileURLToPath(import.meta.url));
  const entryPath = join(currentDir, 'daemon-entry.mjs');
 
  const child = spawn(process.execPath, [entryPath], {
    detached: true,
    stdio: 'ignore',
    env: {
      ...process.env,
      OCAP_SOCKET_PATH: socketPath,
    },
  });
  child.unref();
 
  // Poll until daemon responds
  for (let i = 0; i < MAX_POLLS; i++) {
    await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
    if (await pingDaemon(socketPath)) {
      process.stderr.write('Daemon ready.\n');
      return;
    }
  }
 
  throw new Error(
    `Daemon did not start within ${(MAX_POLLS * POLL_INTERVAL_MS) / 1000}s`,
  );
}