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

91.24% Statements 125/137
82.5% Branches 33/40
90.47% Functions 19/21
91.72% Lines 122/133

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                                                                                                            18x 18x 18x 18x 18x     18x 18x       17x 1x     16x 16x 80x 80x         80x     16x 16x       29x 1x     71x 28x 25x 25x 125x   25x     3x   3x 1x 1x 1x   1x             3x 3x 3x             16x 12x 1x 1x     11x 1x 1x     10x   10x 10x 10x 50x     10x 1x 1x 1x 1x 1x 1x               9x 72x 61x     11x 11x 9x     2x 2x           9x   9x 9x 9x 9x 9x   9x 9x 9x   9x                 10x 10x 2x     9x   9x     9x       9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x   9x         9x                 9x 2x 2x   1x       9x       9x   1x         14x   70x 70x                     1x   1x 1x 1x   1x   1x 5x 5x 1x             1x       18x     20x 20x       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";
 
interface PooledRunner {
  runner: SandboxRunner;
  inUse: boolean;
  lastReleasedTime: number;
}
 
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;
};
 
class SandboxRunnerPool {
  private readonly numRunners: number;
  private readonly runners: PooledRunner[] = [];
  private readonly queue: QueueEntry[] = [];
  private readonly logger = new Logger("SandboxRunnerPool");
  private readonly acquireTimeoutMs = 60000;
  private initialized = false;
 
  constructor(numRunners: number = 5) {
    this.numRunners = numRunners;
    this.logger.info(`[SandboxRunnerPool] Initialized with target pool size: ${this.numRunners}`);
  }
 
  async initialize(): Promise<void> {
    if (this.initialized) {
      return;
    }
 
    this.logger.info(`[SandboxRunnerPool] Initializing ${this.numRunners} runner instances...`);
    for (let i = 0; i < this.numRunners; i++) {
      const runner = new SandboxRunner();
      this.runners.push({
        runner,
        inUse: false,
        lastReleasedTime: Date.now(),
      });
      this.logger.debug(`[SandboxRunnerPool] Created runner [${i}]`);
    }
 
    this.initialized = true;
    this.logger.info(`[SandboxRunnerPool] Pool ready with ${this.numRunners} runners`);
  }
 
  async acquireRunner(): Promise<SandboxRunner> {
    if (!this.initialized) {
      throw new Error("SandboxRunnerPool not initialized. Call initialize() first.");
    }
 
    const available = this.runners.find((p) => !p.inUse);
    if (available) {
      available.inUse = true;
      this.logger.debug(
        `[SandboxRunnerPool] Runner acquired (available: ${this.runners.filter((p) => !p.inUse).length}/${this.numRunners})`,
      );
      return available.runner;
    }
 
    return new Promise<SandboxRunner>((resolve, reject) => {
      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);
 
      entry = { resolve, reject, timeout };
      this.queue.push(entry);
      this.logger.debug(
        `[SandboxRunnerPool] Runner queued (queue length: ${this.queue.length}/${this.numRunners})`,
      );
    });
  }
 
  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;
    }
 
    await this.resetRunnerState(runner);
 
    pooledRunner.inUse = false;
    pooledRunner.lastReleasedTime = Date.now();
    this.logger.debug(
      `[SandboxRunnerPool] Runner released and reset (available: ${this.runners.filter((p) => !p.inUse).length}/${this.numRunners})`,
    );
 
    if (this.queue.length > 0) {
      const entry = this.queue.shift();
      Eif (entry) {
        clearTimeout(entry.timeout);
        pooledRunner.inUse = true;
        entry.resolve(runner);
        this.logger.debug(
          `[SandboxRunnerPool] Queued request granted (queue: ${this.queue.length} remaining)`,
        );
      }
    }
  }
 
  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() {
    return {
      totalRunners: this.numRunners,
      availableRunners: this.runners.filter((p) => !p.inUse).length,
      inUseRunners: this.runners.filter((p) => p.inUse).length,
      queuedRequests: this.queue.length,
      initialized: this.initialized,
    };
  }
 
  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;
 
    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(5);
  return poolInstance;
}
 
export async function initializeSandboxRunnerPool(): Promise<void> {
  const pool = getSandboxRunnerPool();
  await pool.initialize();
}