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

95.4% Statements 166/174
83.5% Branches 81/97
94.73% Functions 36/38
96.36% Lines 159/165

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                                                                        37x 37x 37x         37x 37x     37x 37x 37x 37x 37x 37x 37x 37x 37x           34x 1x     33x     33x 116x 116x             116x     116x   33x 33x           634x 1x         1123x 633x 75x   75x 1x 1x   75x 288x   75x       558x 33x 33x             33x     33x     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 103x     77x 2x         72x   31x     31x   103x 77x         101x 563x     101x   45x   105x 1005x     105x 21x 21x 21x 21x 21x 21x       80x 80x         31x 2x 2x     29x 29x 29x 29x             29x       29x           2x 2x 2x 1x 1x   2x                 80x 80x 46x       34x       34x 2x 2x 2x 2x 2x 2x               103x 351x       103x         103x         351x   351x 351x               48x       18x 18x   18x 1x 1x   18x     18x 76x 32x 32x             18x 76x 76x 18x 6x     6x   18x 18x 1x         18x       51x     32x             32x       2x 2x         2x 1x 1x      
import { SandboxRunner } from "./sandbox-runner";
import { Logger } from "@shared/logger";
import { config } from "../config";
import { mapWithConcurrency, settleWithin } from "./concurrency";
 
interface PooledRunner {
  runner: SandboxRunner;
  inUse: boolean;
  resetting: boolean;
  quarantined?: boolean;
  lastReleasedTime: number;
  idleTimer: ReturnType<typeof setTimeout> | null;
}
 
interface QueueEntry {
  resolve: (runner: SandboxRunner) => void;
  reject: (error: Error) => void;
  timeout: NodeJS.Timeout;
}
 
export interface SandboxRunnerPoolOptions {
  minRunners?: number;
  maxRunners?: number;
  maxQueueSize?: number;
  idleTimeoutMs?: number;
  acquireTimeoutMs?: number;
  resetTimeoutMs?: number;
  shutdownConcurrency?: number;
  shutdownStopTimeoutMs?: 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 readonly shutdownConcurrency: number;
  private readonly shutdownStopTimeoutMs: number;
  private initialized = false;
  private shuttingDown = 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.shutdownConcurrency = options.shutdownConcurrency ?? config.sandbox.pool.shutdownConcurrency;
    this.shutdownStopTimeoutMs = options.shutdownStopTimeoutMs ?? config.sandbox.pool.shutdownStopTimeoutMs;
    this.logger.info(
      `[SandboxRunnerPool] Logical simulation capacity: activeMax=${this.maxRunners}, warmFloor=${this.minRunners}, idleTimeout=${this.idleTimeoutMs}ms`,
    );
  }
 
  async initialize(): Promise<void> {
    if (this.initialized) {
      return;
    }
 
    this.logger.info(
      `[SandboxRunnerPool] Initializing ${this.minRunners} logical 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}]`);
    }
 
    await Promise.all(this.runners.map(({ runner }) => runner.initialize()));
 
    this.initialized = true;
    this.logger.info(
      `[SandboxRunnerPool] Pool ready with ${this.minRunners} logical runners (simulation 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 && !pooledRunner.quarantined) {
      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
    Iif (pooledRunner.idleTimer !== null) {
      clearTimeout(pooledRunner.idleTimer);
      pooledRunner.idleTimer = null;
    }
    pooledRunner.inUse = false;
    pooledRunner.quarantined = 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([
        runner.resetForReuse(),
        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}.`,
      );
      if (this.recoverFailedReset(pooledRunner)) return;
    } finally {
      if (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)`,
        );
      }
    } else Eif (freeRunner) {
      this.scheduleIdleCleanup(freeRunner);
    }
  }
 
  private recoverFailedReset(pooledRunner: PooledRunner): boolean {
    if (pooledRunner.runner.hasPendingContainerCleanup) {
      this.quarantineForCleanup(pooledRunner);
      return true;
    }
    // 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`,
      );
    }
    return false;
  }
 
  private quarantineForCleanup(pooledRunner: PooledRunner): void {
    // Retain ownership in this bounded slot and retry using the existing
    // idle-maintenance interval. Never offer it until reset confirms cleanup.
    pooledRunner.quarantined = true;
    Iif (this.shuttingDown) return;
    pooledRunner.idleTimer = setTimeout(() => {
      pooledRunner.idleTimer = null;
      void this.releaseRunner(pooledRunner.runner);
    }, this.idleTimeoutMs);
    pooledRunner.idleTimer.unref();
  }
 
  /**
   * Schedule idle cleanup for logical runners above the derived warm 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);
  }
 
  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.shuttingDown = true;
    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;
      }
    }
 
    // Parallel and bounded per runner: sequential docker removals of many
    // active simulations would exceed the shutdown deadline, and one hanging
    // stop must not hold back the others.
    const active = this.runners
      .map(({ runner }) => runner)
      .filter((runner) => runner.isRunning || runner.hasPendingContainerCleanup);
    const settled = await mapWithConcurrency(active, this.shutdownConcurrency, async (runner) => {
      const stop = runner.stop().catch((error: unknown) => {
        this.logger.warn(`[SandboxRunnerPool] Error stopping runner during shutdown: ${error}`);
      });
      return settleWithin(stop, this.shutdownStopTimeoutMs);
    });
    const unfinished = settled.filter((done) => !done).length;
    if (unfinished > 0) {
      this.logger.warn(
        `[SandboxRunnerPool] ${unfinished} runner(s) did not stop within ${this.shutdownStopTimeoutMs}ms during shutdown`,
      );
    }
 
    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;
  }
}