All files / src/process manager.ts

77.41% Statements 72/93
83.78% Branches 31/37
60% Functions 12/20
76.92% Lines 70/91

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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317                            10x                             25x               25x 25x                   21x     21x 21x 1x       20x               21x 21x 1x       19x                   19x     19x     19x 3x                 3x       19x 7x 7x 7x     7x 2x 1x                 1x   1x                   1x             19x         19x   19x                   7x 7x   7x 1x     6x   1x 1x     5x                           5x     5x   5x             5x 5x             3x 3x                   2x 2x   2x 1x         1x 1x                     1x 1x       1x     1x                 4x 4x 2x       2x 2x 2x     1x 1x 1x                 5x 5x         5x   5x 5x                                                                      
/**
 * Process Manager
 *
 * Manages spawning, stopping, and lifecycle of child processes.
 * Uses execa for process spawning with detached mode support.
 * Emits domain events via optional EventBus for coordination.
 */
 
import { execa, type ResultPromise } from 'execa';
import type { ProcessInfo, SpawnOptions } from './types.js';
import type { ProcessRegistry } from './registry.js';
import type { EventBus, ProcessSpawnedEvent, ProcessStoppedEvent, ProcessCrashedEvent } from '../events/index.js';
 
/** Stop timeout in milliseconds before sending SIGKILL */
const STOP_TIMEOUT_MS = 5000;
 
/**
 * Internal tracking for spawned process handles.
 * Maps process ID to execa subprocess for control operations.
 */
interface ProcessHandle {
  subprocess: ResultPromise;
  options: SpawnOptions;
}
 
/**
 * Manager for spawning, tracking, and controlling child processes.
 */
export class ProcessManager {
  private handles: Map<string, ProcessHandle> = new Map();
 
  /**
   * Create a new ProcessManager.
   * @param registry - Registry for tracking process metadata
   * @param eventBus - Optional event bus for emitting domain events
   */
  constructor(
    private registry: ProcessRegistry,
    private eventBus?: EventBus
  ) {}
 
  /**
   * Spawn a new child process.
   * @param options - Spawn configuration
   * @returns Process info for the spawned process
   * @throws If process fails to start
   */
  async spawn(options: SpawnOptions): Promise<ProcessInfo> {
    const { id, command, args = [], cwd, env } = options;
 
    // Check if process with this ID already exists
    const existing = this.registry.get(id);
    if (existing && existing.status === 'running') {
      throw new Error(`Process with id '${id}' is already running`);
    }
 
    // Spawn the process in detached mode
    const subprocess = execa(command, args, {
      cwd,
      env: env ? { ...process.env, ...env } : undefined,
      detached: true,
      stdio: 'ignore', // Don't inherit stdio for background processes
    });
 
    // Ensure we have a PID
    const pid = subprocess.pid;
    if (pid === undefined) {
      throw new Error(`Failed to get PID for process '${id}'`);
    }
 
    // Create process info
    const info: ProcessInfo = {
      id,
      pid,
      command,
      args,
      startedAt: new Date(),
      status: 'running',
    };
 
    // Store handle for later control
    this.handles.set(id, { subprocess, options });
 
    // Register in registry
    this.registry.register(info);
 
    // Emit ProcessSpawned event
    if (this.eventBus) {
      const event: ProcessSpawnedEvent = {
        type: 'process:spawned',
        timestamp: new Date(),
        payload: {
          processId: id,
          pid,
          command,
        },
      };
      this.eventBus.emit(event);
    }
 
    // Set up exit handler to update status and emit events
    subprocess.on('exit', (code, signal) => {
      const status = code === 0 ? 'stopped' : 'crashed';
      this.registry.updateStatus(id, status);
      this.handles.delete(id);
 
      // Emit appropriate event based on exit status
      if (this.eventBus) {
        if (status === 'stopped') {
          const event: ProcessStoppedEvent = {
            type: 'process:stopped',
            timestamp: new Date(),
            payload: {
              processId: id,
              pid,
              exitCode: code,
            },
          };
          this.eventBus.emit(event);
        } else {
          const event: ProcessCrashedEvent = {
            type: 'process:crashed',
            timestamp: new Date(),
            payload: {
              processId: id,
              pid,
              exitCode: code,
              signal,
            },
          };
          this.eventBus.emit(event);
        }
      }
    });
 
    // Suppress unhandled rejection when process is killed
    // This is expected behavior - we're intentionally killing processes
    subprocess.catch(() => {
      // Intentionally ignored - we handle exit via the 'exit' event
    });
 
    // Unref the subprocess so it doesn't keep the parent alive
    subprocess.unref();
 
    return info;
  }
 
  /**
   * Stop a running process.
   * Sends SIGTERM first, then SIGKILL after timeout if needed.
   * @param id - Process ID to stop
   * @throws If process not found
   */
  async stop(id: string): Promise<void> {
    const handle = this.handles.get(id);
    const info = this.registry.get(id);
 
    if (!info) {
      throw new Error(`Process with id '${id}' not found`);
    }
 
    if (info.status !== 'running') {
      // Already stopped, just clean up
      this.handles.delete(id);
      return;
    }
 
    Iif (!handle) {
      // Process exists in registry but we don't have a handle
      // Try to kill by PID directly
      try {
        process.kill(info.pid, 'SIGTERM');
        await this.waitForExit(info.pid, STOP_TIMEOUT_MS);
      } catch {
        // Process might already be dead
      }
      this.registry.updateStatus(id, 'stopped');
      return;
    }
 
    // Send SIGTERM
    handle.subprocess.kill('SIGTERM');
 
    // Wait for graceful shutdown
    const exited = await this.waitForProcessExit(handle.subprocess, STOP_TIMEOUT_MS);
 
    Iif (!exited) {
      // Force kill with SIGKILL
      handle.subprocess.kill('SIGKILL');
      await this.waitForProcessExit(handle.subprocess, 1000).catch(() => {});
    }
 
    // Update status (exit handler should have done this, but ensure it)
    this.registry.updateStatus(id, 'stopped');
    this.handles.delete(id);
  }
 
  /**
   * Stop all running processes.
   */
  async stopAll(): Promise<void> {
    const processes = this.registry.getAll().filter(p => p.status === 'running');
    await Promise.all(processes.map(p => this.stop(p.id).catch(() => {})));
  }
 
  /**
   * Restart a process with the same configuration.
   * @param id - Process ID to restart
   * @returns New process info
   * @throws If process not found or original config unavailable
   */
  async restart(id: string): Promise<ProcessInfo> {
    const handle = this.handles.get(id);
    const info = this.registry.get(id);
 
    if (!info) {
      throw new Error(`Process with id '${id}' not found`);
    }
 
    // Get original spawn options
    let options: SpawnOptions;
    if (handle) {
      options = handle.options;
    } else E{
      // Reconstruct options from process info
      options = {
        id,
        command: info.command,
        args: info.args,
      };
    }
 
    // Stop if running
    Eif (info.status === 'running') {
      await this.stop(id);
    }
 
    // Unregister old process
    this.registry.unregister(id);
 
    // Spawn with same options
    return this.spawn(options);
  }
 
  /**
   * Check if a process is currently running.
   * @param id - Process ID to check
   * @returns true if process exists and is running
   */
  isRunning(id: string): boolean {
    const info = this.registry.get(id);
    if (!info || info.status !== 'running') {
      return false;
    }
 
    // Double-check by probing the actual process
    try {
      process.kill(info.pid, 0);
      return true;
    } catch {
      // Process is dead, update registry
      this.registry.updateStatus(id, 'crashed');
      this.handles.delete(id);
      return false;
    }
  }
 
  /**
   * Wait for a subprocess to exit within a timeout.
   * @returns true if process exited, false if timeout
   */
  private waitForProcessExit(subprocess: ResultPromise, timeoutMs: number): Promise<boolean> {
    return new Promise(resolve => {
      const timeout = setTimeout(() => {
        resolve(false);
      }, timeoutMs);
 
      // Use both then and catch to handle success and kill scenarios
      subprocess
        .then(() => {
          clearTimeout(timeout);
          resolve(true);
        })
        .catch(() => {
          // Process was killed (expected) - this is success for our purposes
          clearTimeout(timeout);
          resolve(true);
        });
    });
  }
 
  /**
   * Wait for a PID to exit within a timeout.
   * @returns true if process exited, false if timeout
   */
  private waitForExit(pid: number, timeoutMs: number): Promise<boolean> {
    return new Promise(resolve => {
      const start = Date.now();
      const check = () => {
        try {
          process.kill(pid, 0);
          // Still alive
          if (Date.now() - start >= timeoutMs) {
            resolve(false);
          } else {
            setTimeout(check, 100);
          }
        } catch {
          // Dead
          resolve(true);
        }
      };
      check();
    });
  }
}