All files / server/services sandbox-runner.ts

71.69% Statements 152/212
60.78% Branches 62/102
72.41% Functions 21/29
74.86% Lines 134/179

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 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422        14x 14x 14x                                   14x   69x                           69x 69x 69x 69x   2910x 33x     69x 69x 69x 69x 69x 69x 69x   69x               615x 1x             69x           1x 1x               1x 1x       69x 69x     69x                     69x                                                           69x         69x             6x               1x       2813x               45x 45x 45x 45x 45x       120x 114x         114x 114x         101x         114x 114x 2x 2x 2x 2x         112x         112x 31x 31x 31x     81x 114x             81x         69x 2x 2x 2x     67x     67x 67x         66x       114x 114x 112x     2x       2x 2x       2x 1x     1x 1x           45x 40x 40x       26x   2x 2x       1x   1x         11x 11x       11x 11x 11x                 11x 11x     11x 11x           11x 11x 11x 11x                   1x 1x 1x                                                           57x 57x 26x 26x 26x 26x 26x   57x 57x 57x 57x 57x 57x 57x 57x 57x 57x   57x         57x 57x 57x 57x 57x   57x 21x 15x 15x           26x 26x 26x 26x   26x         8x              
// Lean orchestrator for Arduino sketch simulation
// Delegates execution flow to ExecutionManager, manages state transitions and process control
 
import { ProcessController, type IProcessController } from "./process-controller";
import { mkdir } from "node:fs/promises";
import { existsSync } from "node:fs";
import { join } from "node:path";
import { Logger } from "@shared/logger";
import { getFastTmpBaseDir } from "@shared/utils/temp-paths";
import { ArduinoOutputParser as StderrParser } from "./arduino-output-parser";
import { RegistryManager } from "./registry-manager";
import { SimulationTimeoutManager } from "./simulation-timeout-manager";
import { SketchFileBuilder } from "./sketch-file-builder";
import { LocalCompiler } from "./local-compiler";
import type { RunSketchOptions } from "./run-sketch-types";
import { ProcessExecutor } from "./process-executor";
 
// Manager delegation imports
import { DockerManager } from "./sandbox/docker-manager";
import { StreamHandler } from "./sandbox/stream-handler";
import { FilesystemHelper } from "./sandbox/filesystem-helper";
import { ExecutionManager, type ExecutionState, SimulationState, SANDBOX_CONFIG } from "./sandbox/execution-manager";
 
export class SandboxRunner {
  private static missingDockerSocketLogEmitted = false;
 
  private readonly logger = new Logger("SandboxRunner");
  private readonly tempDir: string;
  private readonly processController: IProcessController;
  private readonly registryManager: RegistryManager;
  private readonly timeoutManager: SimulationTimeoutManager;
  private readonly fileBuilder: SketchFileBuilder;
  private readonly localCompiler: LocalCompiler;
  private readonly dockerManager: DockerManager;
  private readonly streamHandler: StreamHandler;
  private readonly filesystemHelper: FilesystemHelper;
  private readonly executionManager: ExecutionManager;
  private readonly executionState: ExecutionState;
  private readonly processExecutor: ProcessExecutor;
 
  private dockerAvailable = false;
  private dockerImageBuilt = false;
  private dockerChecked = false;
  private tempDirCreated = false;
 
  private get state(): SimulationState { return this.executionState?.state ?? SimulationState.STOPPED; }
  private set state(v: SimulationState | string) { this.executionState.state = v as SimulationState; }
 
  constructor(options?: { tempDir?: string; processController?: IProcessController }) {
    this.processController = options?.processController ?? new ProcessController();
    this.tempDir = options?.tempDir ?? join(getFastTmpBaseDir(), "unosim-temp");
    this.timeoutManager = new SimulationTimeoutManager();
    this.fileBuilder = new SketchFileBuilder(this.tempDir);
    this.localCompiler = new LocalCompiler();
    this.processExecutor = new ProcessExecutor();
    const stderrParser = new StderrParser();
    
    this.registryManager = new RegistryManager({
      onUpdate: (registry, baudrate, reason) => {
        if (this.executionState?.ioRegistryCallback) {
          this.executionState.ioRegistryCallback(registry, baudrate, reason);
        }
        this.executionManager.flushMessageQueue(this.executionState);
      },
      onTelemetry: (metrics) => {
        if (this.executionState?.telemetryCallback) {
          this.executionState.telemetryCallback(metrics);
        }
      },
      enableTelemetry: true,
    });
 
    // Initialize managers with dependencies
    this.dockerManager = new DockerManager(
      this.processController,
      stderrParser,
      this.timeoutManager,
      (parsed, callbacks) => {
        // Delegate parsed line to stream handler
        Eif (this.executionState) {
          const streamState = {
            pinStateBatcher: this.executionState.pinStateBatcher,
            serialOutputBatcher: this.executionState.serialOutputBatcher,
            backpressurePaused: this.executionState.backpressurePaused,
            isPaused: this.executionState.state === SimulationState.PAUSED,
            baudrate: this.executionState.baudrate,
            registryManager: this.registryManager,
          };
          this.streamHandler.handleParsedLine(parsed, streamState, callbacks);
          this.executionState.backpressurePaused = streamState.backpressurePaused;
        }
      },
    );
    this.streamHandler = new StreamHandler(this.processController);
    this.filesystemHelper = new FilesystemHelper(this.fileBuilder, this.localCompiler);
 
    // Initialize execution manager with dependencies
    this.executionManager = new ExecutionManager(
      this.registryManager,
      this.timeoutManager,
      this.fileBuilder,
      this.localCompiler,
      this.dockerManager,
      this.streamHandler,
      this.filesystemHelper,
    );
 
    // Initialize execution state
    this.executionState = {
      outputBuffer: "",
      outputBufferIndex: 0,
      isSendingOutput: false,
      totalOutputBytes: 0,
      messageQueue: [],
      pauseStartTime: null,
      totalPausedTime: 0,
      isCompiling: false,
      currentSketchDir: null,
      currentRegistryFile: null,
      processStartTime: null,
      onOutputCallback: null,
      pinStateCallback: null,
      errorCallback: null,
      telemetryCallback: null,
      ioRegistryCallback: undefined,
      pinStateBatcher: null,
      serialOutputBatcher: null,
      backpressurePaused: false,
      baudrate: 9600,
      stderrFallbackBuffer: "",
      flushTimer: null,
      state: SimulationState.STOPPED,
      processKilled: false,
      pendingCleanup: false,
      processController: this.processController,
    };
 
    // Start docker check eagerly so getSandboxStatus() has cached results (S7059: moved to private method)
    this._scheduleEagerDockerCheck();
  }
 
  /** Schedule docker availability check immediately after construction. (S7059: move async-op out of constructor) */
  private _scheduleEagerDockerCheck(): void {
    this.ensureDockerChecked().catch(() => {
      // Docker check failed, but we already have defaults set
      // (dockerAvailable=false, dockerImageBuilt=false)
    });
  }
 
  get isRunning(): boolean {
    return (
      this.state === SimulationState.STARTING ||
      this.state === SimulationState.RUNNING ||
      this.state === SimulationState.PAUSED
    );
  }
 
  get isPaused(): boolean {
    return this.state === SimulationState.PAUSED;
  }
 
  get simulationState(): SimulationState {
    return this.state;
  }
 
  private get pauseStartTime(): number | null { return this.executionState.pauseStartTime; }
 
 
 
  async runSketch(options: RunSketchOptions): Promise<void> {
    await this.ensureDockerChecked();
    await this.ensureTempDir();
    this.executionState.dockerAvailable = this.dockerAvailable;
    this.executionState.dockerImageBuilt = this.dockerImageBuilt;
    await this.executionManager.runSketch(options, this.executionState);
  }
 
  private async ensureDockerChecked(): Promise<void> {
    if (this.dockerChecked) return;
    Iif (process.env.FORCE_DOCKER === "1") {
      this.dockerAvailable = true; this.dockerImageBuilt = true; this.dockerChecked = true; return;
    }
    
    // Always use async path; ProcessExecutor handles test mocking internally
    try {
      await this.checkDockerAsync();
    } catch {
      this.dockerAvailable = false;
      this.dockerImageBuilt = false;
    } finally {
      this.dockerChecked = true;
    }
  }
 
  private async checkDockerAsync(): Promise<void> {
    const dockerSocketPath = this.getDockerSocketPath();
    if (dockerSocketPath && !existsSync(dockerSocketPath)) {
      this.dockerAvailable = false;
      this.dockerImageBuilt = false;
      this.logMissingDockerSocketOnce(dockerSocketPath);
      return;
    }
 
    // Use ProcessExecutor for all Docker checks
    // docker --version
    const versionResult = await this.processExecutor.execute("docker", ["--version"], {
      timeout: 2000,
      stdio: "pipe",
    });
 
    if (versionResult.error || versionResult.code !== 0) {
      this.dockerAvailable = false;
      this.dockerImageBuilt = false;
      return;
    }
 
    const versionOutput = versionResult.stdout || "";
    Iif (!versionOutput.includes("Docker")) {
      this.dockerAvailable = false;
      this.dockerImageBuilt = false;
      return;
    }
 
    // docker info
    const infoResult = await this.processExecutor.execute("docker", ["info"], {
      timeout: 2000,
      stdio: "pipe",
    });
 
    if (infoResult.error || infoResult.code !== 0) {
      this.dockerAvailable = false;
      this.dockerImageBuilt = false;
      return;
    }
 
    this.dockerAvailable = true;
 
    // docker image inspect <image>
    const imageName = SANDBOX_CONFIG.dockerImage;
    const inspectResult = await this.processExecutor.execute("docker", ["image", "inspect", imageName], {
      timeout: 2000,
      stdio: "pipe",
    });
 
    this.dockerImageBuilt = inspectResult.code === 0;
  }
 
  private getDockerSocketPath(): string | null {
    const dockerHost = process.env.DOCKER_HOST?.trim();
    if (!dockerHost) {
      return "/var/run/docker.sock";
    }
 
    Iif (!dockerHost.startsWith("unix://")) {
      return null;
    }
 
    const socketPath = dockerHost.slice("unix://".length).trim();
    return socketPath || "/var/run/docker.sock";
  }
 
  private logMissingDockerSocketOnce(socketPath: string): void {
    if (SandboxRunner.missingDockerSocketLogEmitted) {
      return;
    }
 
    SandboxRunner.missingDockerSocketLogEmitted = true;
    this.logger.info(
      `Docker socket not available at ${socketPath}; sandbox mode disabled, using local-limited execution`,
    );
  }
 
  private async ensureTempDir(): Promise<void> {
    if (this.tempDirCreated) return;
    this.tempDirCreated = true;
    try { await mkdir(this.tempDir, { recursive: true }); } catch { /* ignore */ }
  }
 
  private async cleanupDockerContainer(containerName?: string): Promise<void> {
    if (!containerName) return;
 
    try {
      const result = await this.processExecutor.execute("docker", ["rm", "-f", containerName], {
        timeout: 5000,
        stdio: "pipe",
      });
      this.logger.info(`Docker cleanup for ${containerName} finished (code ${result.code})`);
    } catch (error) {
      this.logger.debug(`Docker cleanup for ${containerName} failed: ${error}`);
    }
  }
 
  pause(): boolean {
    const s = this.executionState;
    Eif (this.state !== SimulationState.RUNNING || !this.processController.hasProcess()) return false;
    this.state = SimulationState.PAUSED;
    this.timeoutManager.pause();
    s.pinStateBatcher?.pause();
    s.serialOutputBatcher?.pause();
    this.registryManager.pauseTelemetry();
    Iif (!s.processKilled) this.processController.writeStdin("[[PAUSE_TIME]]\n");
    s.pauseStartTime = Date.now();
    this.registryManager.markPauseTime(s.pauseStartTime);
    this.processController.kill("SIGSTOP");
    this.logger.info("Simulation paused (SIGSTOP)");
    return true;
  }
 
  resume(): boolean {
    const s = this.executionState;
    Eif (this.state !== SimulationState.PAUSED || !this.processController.hasProcess()) return false;
    this.processController.kill("SIGCONT");
    const pauseDuration = Date.now() - (this.pauseStartTime ?? Date.now());
    s.totalPausedTime += pauseDuration;
    Iif (!s.processKilled) this.processController.writeStdin(`[[RESUME_TIME:${pauseDuration}]]\n`);
    s.pauseStartTime = null;
    this.registryManager.markPauseTime(null);
    this.state = SimulationState.RUNNING;
    this.timeoutManager.resume();
    s.pinStateBatcher?.resume();
    s.serialOutputBatcher?.resume();
    this.registryManager.resumeTelemetry();
    this.logger.info(`Simulation resumed after ${pauseDuration}ms (SIGCONT)`);
    Iif (!s.processKilled) this.processController.writeStdin("\n");
    if (s.outputBuffer.length > 0 && s.onOutputCallback && !s.isSendingOutput) {
      this.sendOutputWithDelay(s.onOutputCallback);
    }
    return true;
  }
 
 
 
  sendSerialInput(input: string): void {
    const s = this.executionState;
    if (this.isRunning && !this.isPaused && this.processController.hasProcess() && !s.processKilled) {
      this.processController.writeStdin(input + "\n");
    } else E{
      this.logger.warn("Simulator is not running or is paused — serial input ignored");
    }
  }
 
  setRegistryFile(filePath: string): void { this.executionState.currentRegistryFile = filePath; }
  getSketchDir(): string | null { return this.executionState.currentSketchDir; }
 
  setPinValue(pin: number, value: number): void {
    const s = this.executionState;
    if ((this.isRunning || this.isPaused) && this.processController.hasProcess() && !s.processKilled) {
      this.processController.writeStdin(`[[SET_PIN:${pin}:${value}]]\n`);
    }
  }
 
  // Send output character by character with baudrate delay
  private sendOutputWithDelay(onOutput: (line: string, isComplete?: boolean) => void): void {
    const s = this.executionState;
    if (!this.isRunning || this.isPaused) { s.isSendingOutput = false; return; }
    if (s.outputBufferIndex >= s.outputBuffer.length) { s.isSendingOutput = false; return; }
    s.isSendingOutput = true;
    const char = s.outputBuffer[s.outputBufferIndex++];
    s.totalOutputBytes++;
    if (s.totalOutputBytes > SANDBOX_CONFIG.maxOutputBytes) { void this.stop(); return; }
    onOutput(char, char === "\n");
    setTimeout(() => this.sendOutputWithDelay(onOutput), Math.max(1, 10_000 / s.baudrate));
  }
 
  async stop(): Promise<void> {
    const s = this.executionState;
    if (this.state === SimulationState.STOPPED || s.processKilled) return;
    this.state = SimulationState.STOPPED;
    s.processKilled = true;
    s.pendingCleanup = true;
    s.pauseStartTime = null;
    s.totalPausedTime = 0;
 
    s.pinStateBatcher?.stop(); s.pinStateBatcher?.destroy(); s.pinStateBatcher = null;
    s.serialOutputBatcher?.stop(); s.serialOutputBatcher?.destroy(); s.serialOutputBatcher = null;
    this.registryManager.pauseTelemetry();
    s.onOutputCallback = null; s.errorCallback = null;
    s.telemetryCallback = null; s.pinStateCallback = null; s.ioRegistryCallback = undefined;
    this.registryManager.reset();
    this.timeoutManager.clear();
    this.localCompiler.kill();
    this.processController.kill("SIGKILL");
    this.processController.destroySockets();
 
    const fsState = {
      currentSketchDir: s.currentSketchDir, isCompiling: s.isCompiling,
      pendingCleanup: s.pendingCleanup, cleanupRetries: new Map<string, number>(),
      currentRegistryFile: s.currentRegistryFile,
    };
    this.filesystemHelper.markRegistryForCleanup(fsState);
    this.filesystemHelper.markTempDirForCleanup(fsState);
    s.currentSketchDir = fsState.currentSketchDir;
    s.currentRegistryFile = fsState.currentRegistryFile;
    s.pendingCleanup = fsState.pendingCleanup;
 
    for (const dir of this.fileBuilder.getCreatedSketchDirs()) {
      if (!existsSync(dir)) { this.fileBuilder.clearCreatedSketchDir(dir); continue; }
      if (this.filesystemHelper.attemptCleanupDir(dir)) {
        this.fileBuilder.clearCreatedSketchDir(dir);
      } else E{
        this.filesystemHelper.scheduleCleanupRetry(fsState, dir);
      }
    }
 
    s.outputBuffer = ""; s.outputBufferIndex = 0; s.isSendingOutput = false;
    const containerName = s.currentContainerName;
    s.currentContainerName = undefined;
    Iif (s.flushTimer) { clearTimeout(s.flushTimer); s.flushTimer = null; }
 
    await this.cleanupDockerContainer(containerName);
  }
 
  getSandboxStatus(): { dockerAvailable: boolean; dockerImageBuilt: boolean; mode: "docker-sandbox" | "local-limited" } {
    // Docker check is started in constructor, so just return cached values
    return {
      dockerAvailable: this.dockerAvailable,
      dockerImageBuilt: this.dockerImageBuilt,
      mode: this.dockerAvailable && this.dockerImageBuilt ? "docker-sandbox" : "local-limited",
    };
  }
}