All files / server/services process-controller.ts

78.94% Statements 90/114
69.84% Branches 44/63
84% Functions 21/25
82.52% Lines 85/103

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      15x                                                                                               72x 72x 72x 72x 72x 72x 72x       20x 20x     20x           20x 20x       20x     20x                 20x   20x 20x 3x             20x 5x     20x 20x     20x       20x   20x 35x   34x 34x     35x       20x   20x         20x 16x       16x 19x           20x   20x 26x   20x       22x             17x         17x         21x       24x         8x         3x 3x             31x 31x 25x 25x   6x 6x 4x   4x 4x           4x     2x           2x 31x                   2x 2x 2x                               42x 42x 1x 1x           42x 42x 1x     1x           1x 1x 1x   1x           1x 1x 1x   1x                               17x 17x 17x 17x 17x      
import type { ChildProcess, SpawnOptions } from "node:child_process";
import { Logger } from "@shared/logger";
 
const logger = new Logger("ProcessController");
 
/**
 * ProcessController
 *
 * Encapsulates child_process lifecycle and stream forwarding for SandboxRunner.
 *
 * Important concurrency note:
 * - Callbacks (stdout/stderr/close/error) are captured and iterated by the
 *   single wrapper attached to the ChildProcess streams. Consumers should
 *   capture stable callback references before passing them to async code.
 *   This avoids a race where a caller clears or replaces a callback while
 *   an interval/timer (e.g. SerialOutputBatcher) is still invoking it — the
 *   capture-and-check pattern prevents `TypeError: callback is not a function`.
 */
 
export type StdDataCb = (data: Buffer) => void;
export type StdLineCb = (line: string) => void;
export type CloseCb = (code: number | null) => void;
export type ErrorCb = (err: Error) => void;
 
export interface IProcessController {
  /**
   * Spawn a child process and return the underlying `ChildProcess` object
   * (or null if spawn failed). Uses dynamic import so mocking works in tests.
   */
  spawn(command: string, args?: string[] | undefined, options?: SpawnOptions | undefined): Promise<import("node:child_process").ChildProcess | null>;
  onStdout(cb: StdDataCb): void;
  onStderr(cb: StdDataCb): void;
  onStderrLine(cb: StdLineCb): void;
  supportsStderrLineStreaming(): boolean;
  onClose(cb: CloseCb): void;
  onError(cb: ErrorCb): void;
  writeStdin(data: string): boolean;
  kill(signal?: NodeJS.Signals | number): void;
  destroySockets(): void;
  hasProcess(): boolean;
  clearListeners(): void;
  /** Returns the PID of the currently active child process, or null. */
  getPid(): number | null;
}
 
/**
 * ProcessController — encapsulates low-level child_process handling.
 * - centralizes spawn(), signal delivery and stream/event wiring
 * - keeps SandboxRunner free from direct spawn/kill calls
 */
export class ProcessController implements IProcessController {
  private proc: ChildProcess | null = null;
  private stdoutListeners: StdDataCb[] = [];
  private stderrListeners: StdDataCb[] = [];
  private stderrLineListeners: StdLineCb[] = [];
  private closeListeners: CloseCb[] = [];
  private errorListeners: ErrorCb[] = [];
  private stderrReadline: import("node:readline").Interface | null = null;
 
  async spawn(command: string, args: string[] = [], options?: SpawnOptions): Promise<import("node:child_process").ChildProcess | null> {
    // dynamic import ensures test mocks of child_process are applied
    const { spawn } = await import("node:child_process");
    const { createInterface } = await import("node:readline");
 
    // Ensure we always use pipes so we can drain output and prevent backpressure.
    const spawnOptions: SpawnOptions = {
      stdio: ["pipe", "pipe", "pipe"],
      ...options,
    };
 
    // debug logging of spawn attempts goes through policy logger
    logger.debug(`ProcessController.spawn called: ${command} ${args ? args.join(" ") : ""}`);
    logger.debug(`ProcessController.spawn options: ${JSON.stringify(spawnOptions)}`);
 
    // Destroy any previous process reference
    // spawn with or without options depending on caller
    this.proc = spawn(command, args, spawnOptions);
 
    // Cleanup stale readline interface from previous process, if any.
    Iif (this.stderrReadline) {
      try {
        this.stderrReadline.close();
      } catch {
        // ignore
      }
      this.stderrReadline = null;
    }
    // if tests have registered a global spawnInstances array, record it
    try {
      // TypeScript guard: check that globalThis.spawnInstances exists and is an array
      const gs = (globalThis as Record<string, unknown>).spawnInstances;
      if (Array.isArray(gs) && this.proc) {
        gs.push(this.proc);
      }
    } catch {
      /* ignore */
    }
 
    // attach existing listeners (guard for nullability)
    this.proc?.stdout?.on("data", (d: Buffer) => {
      this.stdoutListeners.forEach((cb) => cb(d));
    });
 
    this._setupStderrHandling(createInterface);
    this._setupProcessEventListeners();
 
    // return the underlying ChildProcess so callers can inspect it
    return this.proc;
  }
 
  private _setupStderrHandling(createInterface: (options: any) => import("node:readline").Interface): void {
    Iif (!this.proc?.stderr) return;
 
    this.proc.stderr.on("data", (d: Buffer) => {
      if (process.env.NODE_ENV === "test") {
        // convert low-level wrapper events into buffered debug logs
        try {
          logger.debug(`wrapper stderr handler invoked with: ${d.toString()}`);
        } catch {}
      }
      this.stderrListeners.forEach((cb) => cb(d));
    });
 
    // Type-safe stream handling: verify the stream has our expected methods
    const stderrStream = this.proc.stderr as unknown;
    const canUseReadline =
      stderrStream !== null && 
      typeof stderrStream === 'object' &&
      typeof (stderrStream as Record<string, unknown>).on === "function" &&
      typeof (stderrStream as Record<string, unknown>).resume === "function";
 
    if (canUseReadline) {
      this.stderrReadline = createInterface({
        input: this.proc.stderr,
        crlfDelay: Infinity,
      });
      this.stderrReadline.on("line", (line: string) => {
        this.stderrLineListeners.forEach((cb) => cb(line));
      });
    }
  }
 
  private _setupProcessEventListeners(): void {
    Iif (!this.proc) return;
 
    this.proc.on("close", (code: number | null) => {
      this.closeListeners.forEach((cb) => cb(code));
    });
    this.proc.on("error", (err: Error) => this.errorListeners.forEach((cb) => cb(err)));
  }
 
  onStdout(cb: StdDataCb) {
    this.stdoutListeners.push(cb);
    // The active process (if any) has a single wrapper attached in spawn()
    // which iterates over `stdoutListeners`. Do not attach `cb` directly to
    // `proc.stdout` here — that caused duplicate invocations.
  }
 
  onStderr(cb: StdDataCb) {
    this.stderrListeners.push(cb);
    // Handled by the single stderr wrapper installed in spawn().
  }
 
  onStderrLine(cb: StdLineCb) {
    this.stderrLineListeners.push(cb);
    // Handled by readline interface installed in spawn().
  }
 
  supportsStderrLineStreaming(): boolean {
    return this.stderrReadline !== null;
  }
 
  onClose(cb: CloseCb) {
    this.closeListeners.push(cb);
    // `spawn()` wires a single 'close' handler that will call listeners.
  }
 
  onError(cb: ErrorCb) {
    this.errorListeners.push(cb);
    // `spawn()` wires a single 'error' handler that will call listeners.
  }
 
  writeStdin(data: string): boolean {
    try {
      return this.proc?.stdin?.write(data) ?? false;
    } catch {
      return false;
    }
  }
 
  kill(signal?: NodeJS.Signals | number): void {
    try {
      if (!this.proc) {
        logger.debug(`ProcessController.kill called but proc is null (signal=${signal})`);
        return;
      }
      const pid = this.proc.pid;
      if (pid == null) {
        logger.debug(`ProcessController.kill: pid is null, sending ${signal}`);
        // Safe cast: signal is known to be NodeJS.Signals | number, which is what kill accepts
        if (typeof signal === 'string') {
          this.proc.kill(signal);
        E} else if (typeof signal === 'number') {
          this.proc.kill(signal);
        } else {
          this.proc.kill();
        }
        return;
      }
 
      logger.debug(`ProcessController.kill: sending ${signal} to pid=${pid}`);
 
      // For SIGSTOP / SIGCONT send to the entire process group (-pid).
      // This ensures all children of the process (e.g. sub-shells, avr-gcc)
      // receive the signal, not just the direct child.
      // On non-POSIX systems (Windows) fall back to the plain kill.
      const isGroupSignal = signal === "SIGSTOP" || signal === "SIGCONT";
      Iif (isGroupSignal && typeof signal === 'string') {
        try {
          process.kill(-pid, signal);
          return;
        } catch (err) {
          logger.debug(`ProcessController.kill group signal failed: ${err}`);
          // group kill failed (e.g. process not a group leader) — fall through
        }
      }
 
      try {
        if (typeof signal === 'string') {
          this.proc.kill(signal);
        E} else if (typeof signal === 'number') {
          this.proc.kill(signal);
        } else {
          this.proc.kill();
        }
      } catch (err) {
        logger.debug(`ProcessController.kill direct kill failed: ${err}`);
      }
    } catch (err) {
      logger.debug(`ProcessController.kill outer error: ${err}`);
      // swallow errors — caller should handle state
    }
  }
 
  destroySockets(): void {
    try {
      if (this.stderrReadline) {
        this.stderrReadline.close();
        this.stderrReadline = null;
      }
    } catch {
      /* ignore */
    }
 
    try {
      if (!this.proc) return;
      Eif (this.proc.stdin && !this.proc.stdin.destroyed) {
         
        // @ts-ignore - Node typings: destroy may exist
        this.proc.stdin.destroy();
      }
    } catch {
      /* ignore */
    }
 
    try {
      Iif (!this.proc) return;
      Eif (this.proc.stdout && !this.proc.stdout.destroyed) {
        // @ts-ignore
        this.proc.stdout.destroy();
      }
    } catch {
      /* ignore */
    }
 
    try {
      Iif (!this.proc) return;
      Eif (this.proc.stderr && !this.proc.stderr.destroyed) {
        // @ts-ignore
        this.proc.stderr.destroy();
      }
    } catch {
      /* ignore */
    }
  }
 
  hasProcess(): boolean {
    return !!this.proc;
  }
 
  getPid(): number | null {
    return this.proc?.pid ?? null;
  }
 
  clearListeners(): void {
    this.stdoutListeners = [];
    this.stderrListeners = [];
    this.stderrLineListeners = [];
    this.closeListeners = [];
    this.errorListeners = [];
  }
}