All files / server/services sandbox-runner-pool.ts

93.2% Statements 192/206
80.39% Branches 82/102
96.87% Functions 31/32
93.53% Lines 188/201

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 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540                                                                                                                                                            35x 35x 35x     35x     35x 35x 35x 35x 35x 35x 35x           33x 1x     32x     32x 122x 122x             122x     32x 32x           629x 1x         1110x 628x 68x   68x 1x 1x   68x 279x   68x       560x 35x 35x             35x     35x     525x 2x         523x 523x                   523x 1x 1x 1x   1x             523x 500x 500x 500x   500x 500x     500x           523x 514x     523x 523x 523x             528x 105x 1x     1x     104x 1x     1x       103x 103x 103x       103x 103x     103x 2x         101x   2x       2x 2x 2x 2x             2x         103x 103x         103x 530x     103x   2x   105x 1023x     105x 21x 21x 21x 21x 21x 21x       82x 82x                   82x 82x 46x       36x       36x 2x 2x 2x 2x 2x 2x               100x 800x 698x     102x 102x 100x     2x 2x               100x   100x 100x 100x 100x       100x         100x 100x 100x   100x                 103x 103x 4x     100x   100x     100x       100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x   100x         100x                 100x 2x 2x   1x           100x       100x       1x             97x 353x       97x         97x         353x   353x 353x               47x       14x   14x 1x 1x   14x     14x 69x 33x 33x       14x 69x 69x 1x                 14x       47x     34x             34x       2x 2x         2x 1x 1x      
import { SandboxRunner } from "./sandbox-runner";
import { Logger } from "@shared/logger";
import type { IOPinRecord } from "@shared/schema";
import type {
  ExecutionState,
  TelemetryMetrics,
} from "./sandbox/execution-manager";
import { config } from "../config";
 
interface PooledRunner {
  runner: SandboxRunner;
  inUse: boolean;
  resetting: boolean;
  lastReleasedTime: number;
  idleTimer: ReturnType<typeof setTimeout> | null;
}
 
interface QueueEntry {
  resolve: (runner: SandboxRunner) => void;
  reject: (error: Error) => void;
  timeout: NodeJS.Timeout;
}
 
// Useful internal type for accessing private runner fields safely
type SandboxRunnerInternal = {
  state: string;
  processKilled: boolean;
  executionState: ExecutionState;
  processController?: {
    proc?: {
      stdout?: unknown;
      stderr?: unknown;
    };
    stdoutListeners?: unknown[];
    stderrListeners?: unknown[];
    closeListeners?: unknown[];
    errorListeners?: unknown[];
    removeAllListeners?: () => void;
  } | null;
  pinStateBatcher?: { pause: () => void; resume: () => void } | null;
  serialOutputBatcher?: { pause: () => void; resume: () => void } | null;
  registryManager?: { destroy: () => void; reset: () => void } | null;
  flushMessageQueue?: () => void;
  onOutputCallback?: ((line: string, isComplete?: boolean) => void) | null;
  outputCallback?: ((line: string, isComplete?: boolean) => void) | null;
  errorCallback?: ((line: string) => void) | null;
  telemetryCallback?: ((metrics: TelemetryMetrics) => void) | null;
  pinStateCallback?:
    | ((pin: number, type: string, value: number) => void)
    | null;
  ioRegistryCallback?:
    | ((
        registry: IOPinRecord[],
        baudrate: number | undefined,
        reason?: string,
      ) => void)
    | null;
  timeoutManager?: { clear: () => void };
  fileBuilder?: { reset: () => void };
  flushTimer?: NodeJS.Timeout | null;
  // keep object extensible as we access other internal fields in reset logic
  [key: string]: unknown;
};
 
export interface SandboxRunnerPoolOptions {
  minRunners?: number;
  maxRunners?: number;
  maxQueueSize?: number;
  idleTimeoutMs?: number;
  acquireTimeoutMs?: number;
  resetTimeoutMs?: number;
}
 
export class SandboxRunnerPool {
  private readonly minRunners: number;
  private readonly maxRunners: number;
  private readonly maxQueueSize: number;
  private readonly idleTimeoutMs: number;
  private readonly runners: PooledRunner[] = [];
  private readonly queue: QueueEntry[] = [];
  private readonly logger = new Logger("SandboxRunnerPool");
  private readonly acquireTimeoutMs: number;
  private readonly resetTimeoutMs: number;
  private initialized = false;
 
  constructor(options: SandboxRunnerPoolOptions = {}) {
    this.minRunners = options.minRunners ?? config.sandbox.pool.minRunners;
    this.maxRunners = options.maxRunners ?? config.sandbox.pool.maxRunners;
    this.maxQueueSize = options.maxQueueSize ?? config.sandbox.pool.maxQueueSize;
    this.idleTimeoutMs = options.idleTimeoutMs ?? config.sandbox.pool.idleTimeoutMs;
    this.acquireTimeoutMs = options.acquireTimeoutMs ?? config.sandbox.pool.acquireTimeoutMs;
    this.resetTimeoutMs = options.resetTimeoutMs ?? config.sandbox.pool.resetTimeoutMs;
    this.logger.info(
      `[SandboxRunnerPool] Pool config: min=${this.minRunners}, max=${this.maxRunners}, idleTimeout=${this.idleTimeoutMs}ms`,
    );
  }
 
  async initialize(): Promise<void> {
    if (this.initialized) {
      return;
    }
 
    this.logger.info(
      `[SandboxRunnerPool] Initializing ${this.minRunners} warm runner instances...`,
    );
    for (let i = 0; i < this.minRunners; i++) {
      const runner = new SandboxRunner();
      this.runners.push({
        runner,
        inUse: false,
        resetting: false,
        lastReleasedTime: Date.now(),
        idleTimer: null,
      });
      this.logger.debug(`[SandboxRunnerPool] Created warm runner [${i}]`);
    }
 
    this.initialized = true;
    this.logger.info(
      `[SandboxRunnerPool] Pool ready with ${this.minRunners} warm runners (max: ${this.maxRunners})`,
    );
  }
 
  async acquireRunner(signal?: AbortSignal): Promise<SandboxRunner> {
    if (!this.initialized) {
      throw new Error(
        "SandboxRunnerPool not initialized. Call initialize() first.",
      );
    }
 
    const available = this.runners.find((p) => !p.inUse && !p.resetting);
    if (available) {
      available.inUse = true;
      // Cancel any pending idle-cleanup timer for this runner
      if (available.idleTimer !== null) {
        clearTimeout(available.idleTimer);
        available.idleTimer = null;
      }
      this.logger.debug(
        `[SandboxRunnerPool] Runner acquired (available: ${this.runners.filter((p) => !p.inUse).length}/${this.runners.length})`,
      );
      return available.runner;
    }
 
    // On-demand creation: create a new runner if below maxRunners
    if (this.runners.length < this.maxRunners) {
      const runner = new SandboxRunner();
      this.runners.push({
        runner,
        inUse: true,
        resetting: false,
        lastReleasedTime: Date.now(),
        idleTimer: null,
      });
      this.logger.debug(
        `[SandboxRunnerPool] On-demand runner created (total: ${this.runners.length}/${this.maxRunners})`,
      );
      return runner;
    }
 
    if (this.queue.length >= this.maxQueueSize) {
      throw new Error(
        `SandboxRunnerPool queue full (${this.maxQueueSize} pending). Try again later.`,
      );
    }
 
    return new Promise<SandboxRunner>((resolve, reject) => {
      Iif (signal?.aborted) {
        reject(
          new Error(
            "SandboxRunnerPool: acquire cancelled (client disconnected)",
          ),
        );
        return;
      }
 
      let entry: QueueEntry;
      const timeout = setTimeout(() => {
        const index = this.queue.indexOf(entry);
        Eif (index !== -1) {
          this.queue.splice(index, 1);
        }
        reject(
          new Error(
            `SandboxRunnerPool: acquire timeout after ${this.acquireTimeoutMs}ms (queue: ${this.queue.length})`,
          ),
        );
      }, this.acquireTimeoutMs);
 
      const onAbort = () => {
        const index = this.queue.indexOf(entry);
        Eif (index !== -1) {
          this.queue.splice(index, 1);
        }
        clearTimeout(timeout);
        this.logger.debug(
          `[SandboxRunnerPool] Queued request cancelled by AbortSignal (queue: ${this.queue.length} remaining)`,
        );
        reject(
          new Error(
            "SandboxRunnerPool: acquire cancelled (client disconnected)",
          ),
        );
      };
      if (signal) {
        signal.addEventListener("abort", onAbort, { once: true });
      }
 
      entry = { resolve, reject, timeout };
      this.queue.push(entry);
      this.logger.debug(
        `[SandboxRunnerPool] Runner queued (queue length: ${this.queue.length}, at maxRunners: ${this.maxRunners})`,
      );
    });
  }
 
  async releaseRunner(runner: SandboxRunner): Promise<void> {
    const pooledRunner = this.runners.find((p) => p.runner === runner);
    if (!pooledRunner) {
      this.logger.warn(
        "[SandboxRunnerPool] Attempt to release unknown runner (ignored)",
      );
      return;
    }
 
    if (!pooledRunner.inUse) {
      this.logger.warn(
        "[SandboxRunnerPool] Attempt to release already-released runner (ignored)",
      );
      return;
    }
 
    // Always mark as free FIRST, even if reset hangs — prevents permanent pool deadlock
    pooledRunner.inUse = false;
    pooledRunner.resetting = true;
    pooledRunner.lastReleasedTime = Date.now();
 
    // Reset with a timeout guard so a stuck runner.stop() cannot block forever
    let resetTimer: ReturnType<typeof setTimeout> | undefined;
    try {
      await Promise.race([
        this.resetRunnerState(runner),
        new Promise<void>((_, reject) => {
          resetTimer = setTimeout(
            () => reject(new Error("Runner reset timed out")),
            this.resetTimeoutMs,
          );
        }),
      ]);
      pooledRunner.resetting = false;
    } catch (error) {
      this.logger.error(
        `[SandboxRunnerPool] Runner reset failed or timed out: ${error}. Force-replacing runner.`,
      );
      // Replace the stuck runner with a fresh one
      const index = this.runners.indexOf(pooledRunner);
      Eif (index !== -1) {
        const freshRunner = new SandboxRunner();
        this.runners[index] = {
          runner: freshRunner,
          inUse: false,
          resetting: false,
          lastReleasedTime: Date.now(),
          idleTimer: null,
        };
        this.logger.info(
          `[SandboxRunnerPool] Replaced stuck runner at index ${index} with fresh instance`,
        );
      }
    } finally {
      Eif (resetTimer !== undefined) {
        clearTimeout(resetTimer);
      }
    }
 
    // Find the (possibly replaced) pooled runner for queue dispatch
    const currentPooled = this.runners.find(
      (p) => p.runner === (pooledRunner.runner ?? runner) || p === pooledRunner,
    );
    const freeRunner =
      currentPooled && !currentPooled.inUse && !currentPooled.resetting
        ? currentPooled
        : this.runners.find((p) => !p.inUse && !p.resetting);
 
    this.logger.debug(
      `[SandboxRunnerPool] Runner released and reset (available: ${this.runners.filter((p) => !p.inUse).length}/${this.runners.length})`,
    );
 
    if (this.queue.length > 0 && freeRunner) {
      const entry = this.queue.shift();
      Eif (entry) {
        clearTimeout(entry.timeout);
        freeRunner.inUse = true;
        entry.resolve(freeRunner.runner);
        this.logger.debug(
          `[SandboxRunnerPool] Queued request granted (queue: ${this.queue.length} remaining)`,
        );
      }
    E} else if (freeRunner) {
      this.scheduleIdleCleanup(freeRunner);
    }
  }
 
  /**
   * Schedule idle cleanup for runners above the minRunners floor.
   * If the runner is re-acquired before the timer fires, the timer is cancelled.
   */
  private scheduleIdleCleanup(pooledRunner: PooledRunner): void {
    // Only schedule cleanup for runners above the warm floor
    const warmRunners = this.runners.slice(0, this.minRunners);
    if (warmRunners.includes(pooledRunner)) {
      return; // This is a warm runner – never clean it up
    }
 
    // Cancel existing timer if any
    Iif (pooledRunner.idleTimer !== null) {
      clearTimeout(pooledRunner.idleTimer);
    }
 
    pooledRunner.idleTimer = setTimeout(() => {
      pooledRunner.idleTimer = null;
      Iif (pooledRunner.inUse) return; // Reacquired before timer fired
      const idx = this.runners.indexOf(pooledRunner);
      Eif (idx !== -1) {
        this.runners.splice(idx, 1);
        this.logger.debug(
          `[SandboxRunnerPool] Idle runner removed (total: ${this.runners.length}/${this.maxRunners})`,
        );
      }
    }, this.idleTimeoutMs);
  }
 
  private clearRunnerListeners(runner: SandboxRunnerInternal): void {
    const safeRemoveAll = (target: unknown, label: string) => {
      if (!target || typeof target !== "object" || target === null) {
        return;
      }
 
      const maybe = target as { removeAllListeners?: unknown };
      if (typeof maybe.removeAllListeners !== "function") {
        return;
      }
 
      try {
        (maybe.removeAllListeners as () => void)();
      } catch (error) {
        this.logger.debug(
          `[SandboxRunnerPool] Failed removeAllListeners on ${label}: ${error}`,
        );
      }
    };
 
    safeRemoveAll(runner, "runner");
 
    const processController = runner.processController;
    safeRemoveAll(processController, "processController");
    safeRemoveAll(processController?.proc, "processController.proc");
    safeRemoveAll(
      processController?.proc?.stdout,
      "processController.proc.stdout",
    );
    safeRemoveAll(
      processController?.proc?.stderr,
      "processController.proc.stderr",
    );
 
    safeRemoveAll(runner.registryManager, "registryManager");
    safeRemoveAll(runner.serialOutputBatcher, "serialOutputBatcher");
    safeRemoveAll(runner.pinStateBatcher, "pinStateBatcher");
 
    Iif (processController) {
      processController.stdoutListeners = [];
      processController.stderrListeners = [];
      processController.closeListeners = [];
      processController.errorListeners = [];
    }
  }
 
  private async resetRunnerState(runner: SandboxRunner): Promise<void> {
    try {
      if (runner.isRunning) {
        await runner.stop();
      }
 
      const r = runner as unknown as SandboxRunnerInternal;
 
      this.clearRunnerListeners(r);
 
      // Use the state setter (delegates to executionState.state)
      r.state = "stopped";
 
      // Reset executionState fields directly to avoid creating ad-hoc properties
      // on the runner instance that shadow the real executionState fields.
      const es = r.executionState;
      es.processKilled = false;
      es.pauseStartTime = null;
      es.totalPausedTime = 0;
      es.pinStateBatcher = null;
      es.serialOutputBatcher = null;
      es.onOutputCallback = null;
      es.errorCallback = null;
      es.telemetryCallback = null;
      es.pinStateCallback = null;
      es.ioRegistryCallback = undefined;
      es.outputBuffer = "";
      es.outputBufferIndex = 0;
      es.totalOutputBytes = 0;
      es.isSendingOutput = false;
      es.pendingCleanup = false;
      es.messageQueue = [];
      es.stderrFallbackBuffer = "";
      es.backpressurePaused = false;
 
      Iif (es.flushTimer) {
        clearTimeout(es.flushTimer);
        es.flushTimer = null;
      }
 
      Iif (r.fileBuilder && typeof r.fileBuilder.reset === "function") {
        r.fileBuilder.reset();
      }
 
      // Reset the existing RegistryManager rather than destroying and recreating it.
      // Destroying makes the object permanently unusable (destroyed=true), which breaks
      // the ExecutionManager that holds a reference to the same instance.
      // The original onUpdate callback uses executionState.ioRegistryCallback dynamically,
      // so it picks up the correct callback for each new run automatically.
      if (r.registryManager) {
        try {
          r.registryManager.reset();
        } catch (error) {
          this.logger.debug(
            `[SandboxRunnerPool] RegistryManager reset failed: ${error}`,
          );
        }
      }
 
      Iif (r.timeoutManager) {
        r.timeoutManager.clear();
      }
 
      this.logger.debug(
        "[SandboxRunnerPool] Runner state reset complete (isolation verified)",
      );
    } catch (error) {
      this.logger.error(
        `[SandboxRunnerPool] Error during runner reset: ${error}`,
      );
    }
  }
 
  getStats() {
    const sandboxStatuses = this.runners.map((entry) =>
      (entry.runner as SandboxRunner & {
        getSandboxStatus?: () => { dockerAvailable: boolean; dockerImageBuilt: boolean };
      }).getSandboxStatus?.(),
    );
    const sandboxReady = config.serverMode !== "docker" ||
      (sandboxStatuses.length > 0 && sandboxStatuses.every(
        (status) => status?.dockerAvailable && status.dockerImageBuilt,
      ));
 
    return {
      totalRunners: this.runners.length,
      minRunners: this.minRunners,
      maxRunners: this.maxRunners,
      maxQueueSize: this.maxQueueSize,
      availableRunners: this.runners.filter((p) => !p.inUse && !p.resetting)
        .length,
      inUseRunners: this.runners.filter((p) => p.inUse).length,
      resettingRunners: this.runners.filter((p) => p.resetting).length,
      queuedRequests: this.queue.length,
      initialized: this.initialized,
      sandboxReady,
    };
  }
 
  getRunnerIndex(runner: SandboxRunner): number {
    return this.runners.findIndex((p) => p.runner === runner);
  }
 
  async shutdown(): Promise<void> {
    this.logger.info("[SandboxRunnerPool] Shutting down...");
 
    for (const entry of this.queue) {
      clearTimeout(entry.timeout);
      entry.reject(new Error("SandboxRunnerPool shutting down"));
    }
    this.queue.length = 0;
 
    // Cancel all idle timers
    for (const pooledRunner of this.runners) {
      if (pooledRunner.idleTimer !== null) {
        clearTimeout(pooledRunner.idleTimer);
        pooledRunner.idleTimer = null;
      }
    }
 
    for (const { runner } of this.runners) {
      try {
        if (runner.isRunning) {
          await runner.stop();
        }
      } catch (error) {
        this.logger.warn(
          `[SandboxRunnerPool] Error stopping runner during shutdown: ${error}`,
        );
      }
    }
 
    this.logger.info("[SandboxRunnerPool] Shutdown complete");
  }
}
 
let poolInstance: SandboxRunnerPool | null = null;
 
export function getSandboxRunnerPool(): SandboxRunnerPool {
  poolInstance ??= new SandboxRunnerPool({
    minRunners: config.sandbox.pool.minRunners,
    maxRunners: config.sandbox.pool.maxRunners,
    idleTimeoutMs: config.sandbox.pool.idleTimeoutMs,
    acquireTimeoutMs: config.sandbox.pool.acquireTimeoutMs,
    resetTimeoutMs: config.sandbox.pool.resetTimeoutMs,
  });
  return poolInstance;
}
 
export async function initializeSandboxRunnerPool(): Promise<void> {
  const pool = getSandboxRunnerPool();
  await pool.initialize();
}
 
/** Reset the singleton — test-only, allows re-initialization with new env vars. */
export function _resetPoolSingleton(): void {
  if (poolInstance) {
    poolInstance.shutdown().catch(() => {});
    poolInstance = null;
  }
}