All files / server/services unified-gatekeeper.ts

84.43% Statements 179/212
75% Branches 60/80
94.59% Functions 35/37
84.92% Lines 169/199

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 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567                                        23x 23x 23x 23x                                                                                             111x 111x     111x     111x 111x 111x     111x   111x     111x               111x     111x     111x   111x 1x 1x 1x         110x 99x   11x     110x 110x 110x             111x               19x                       806x 806x   806x 806x   806x 161x 161x 161x             161x 161x   161x         161x       806x 512x 512x 502x   512x 512x     806x   161x     645x 645x     132x 132x           132x 132x 132x               645x 10x       10x       635x 635x 129776x 3x 3x     635x   635x         635x 502x 502x             635x 635x 132x 132x                           935x 935x                             943x 943x   943x 943x 943x   943x 1745x 1745x     147913x   1745x   147909x 1619x 813x             813x 813x 813x 813x 813x 813x   126x   122x             122x 122x 122x 122x 122x     810x       943x 133x       810x 810x 802x     810x     810x 6x 6x   6x                   286x 132x 132x 132x 132x                                             293x 287x 287x 287x 286x 286x 286x     286x 286x                     935x 933x 933x 148036x 933x 134x   799x   933x     933x                     111x       111x 12x 12x 12x     12x 6x                       12x                                   12x       12x                     105x 101x 101x       105x             83x                                 2x 2x 3x         2x   1x     2x                 3x 3x 3x 3x 3x               3x   3x             23x     75x 75x       118x 118x 4x   118x    
/**
 * Unified Gatekeeper - Concurrency & Cache Management
 * 
 * Centralized system for:
 * 1. Compile slot allocation (semaphore-based)
 * 2. Cache Read-Write locking (multiple readers, single writer)
 * 3. TTL-based deadlock prevention (auto-release after timeout)
 * 4. Priority queuing (system checks prioritized over regular tasks)
 * 5. Event-driven architecture (eliminates polling overhead)
 * 
 * Replaces the previous dual-gatekeeper pattern with atomic, deadlock-safe operations.
 * Performance: O(1) event notification instead of O(n) polling overhead.
 */
 
import { Logger } from "@shared/logger";
import { config, getCompileMaxConcurrent } from "../config";
import { cpus } from "node:os";
import { EventEmitter } from "node:events";
 
// Priority levels for task queuing
export enum TaskPriority {
  HIGH = 0,    // System health checks, cleanup, user interactions
  NORMAL = 1,  // Regular compilations
  LOW = 2,     // Background work
}
 
interface CacheLockEntry {
  key: string;
  lockType: "read" | "write";
  acquiredAt: number;
  expiresAt: number;
  owner: string;
}
 
interface CompileSlotEntry {
  priority: TaskPriority;
  acquiredAt: number;
  expiresAt: number;
  owner: string;
}
 
interface QueuedTask {
  priority: TaskPriority;
  resolver: (release: () => void) => void;
  ownerId: string;
  owner: string;
  createdAt: number;
}
 
/**
 * Calculate adaptive concurrency based on CPU count
 * Formula: max(1, cpuCount - 1)
 * Examples:
 *   2-core (RasPi):  max(1, 2-1) = 1
 *   4-core desktop:  max(1, 4-1) = 3
 *   8-core workstation: max(1, 8-1) = 7
 *   16-core server:  max(1, 16-1) = 15
 */
function calculateOptimalConcurrency(): number {
  try {
    const numCores = cpus().length;
    return Math.max(1, numCores - 1);
  } catch {
    return 4; // Fallback default
  }
}
 
export class UnifiedGatekeeper extends EventEmitter {
  private readonly maxCompileConcurrent: number;
  private availableSlots: number;
  private readonly activeSlots: Map<string, CompileSlotEntry> = new Map();
  private compileQueue: QueuedTask[] = [];
  
  // Cache locks: key -> [lock entries]
  private readonly cacheLocks: Map<string, CacheLockEntry[]> = new Map();
  
  // Lock monitoring
  private lockCheckInterval: NodeJS.Timeout | null = null;
  private readonly lockTTL = config.timeouts.gatekeeperLockTTLMs;
  private readonly checkIntervalMs = config.timeouts.gatekeeperLockCheckIntervalMs;
  
  // Queue size limit to prevent unbounded memory growth under extreme load
  private readonly maxQueueSize = config.compilation.gatekeeperMaxQueueSize;
  
  private readonly logger = new Logger("UnifiedGatekeeper");
  
  // Statistics
  private stats = {
    totalCompileSlotRequests: 0,
    totalCacheLockRequests: 0,
    expiredLocks: 0,
    deadlocksAvoided: 0,
  };
 
  constructor(maxConcurrent?: number) {
    super();
    
    // Allow unlimited event listeners for high-contention scenarios (200+ waiters)
    this.setMaxListeners(0);
    
    // In worker threads, disable gatekeeper since the worker pool controls concurrency
    const isWorkerThread = process.env.COMPILE_GATEKEEPER_DISABLED === "true";
    
    if (isWorkerThread) {
      this.maxCompileConcurrent = Infinity;
      this.availableSlots = Infinity;
      this.logger.info("UnifiedGatekeeper in worker thread (pool-controlled)");
    } else {
      // Priority 1: Explicit env override
      // Priority 2: Constructor parameter
      // Priority 3: CPU-adaptive calculation
      if (maxConcurrent) {
        this.maxCompileConcurrent = maxConcurrent;
      } else {
        this.maxCompileConcurrent = getCompileMaxConcurrent() || calculateOptimalConcurrency();
      }
      
      this.availableSlots = this.maxCompileConcurrent;
      const numCores = cpus().length;
      this.logger.info(
        `UnifiedGatekeeper initialized: max ${this.maxCompileConcurrent} concurrent compiles ` +
        `(${numCores} CPU cores detected, formula: max(1, cores-1))`,
      );
    }
    
    // Start periodic lock expiration check
    this.startLockMonitoring();
  }
 
  /**
   * Acquire a compile slot with HIGH priority (for user-initiated simulations)
   * Ensures interactive tasks get prompt access
   */
  async acquireCompileSlotHighPriority(owner: string = "simulation-start", onQueued?: () => void): Promise<() => void> {
    return this.acquireCompileSlot(TaskPriority.HIGH, config.timeouts.compileGatekeeperAcquireMs, owner, onQueued);
  }
 
  /**
   * Acquire a compile slot (internal method used by all priorities)
   */
  async acquireCompileSlot(
    priority: TaskPriority = TaskPriority.NORMAL,
    timeoutMs: number = config.timeouts.compileGatekeeperAcquireMs,
    owner: string = "unknown",
    onQueued?: () => void,
  ): Promise<() => void> {
    this.stats.totalCompileSlotRequests++;
    const ownerId = `${owner}-${Date.now()}-${crypto.randomUUID()}`;
 
    return new Promise((resolve, reject) => {
      let timeoutHandle: NodeJS.Timeout | null = null;
      
      const grant = () => {
        Eif (timeoutHandle) clearTimeout(timeoutHandle);
        const expiresAt = Date.now() + this.lockTTL;
        const entry: CompileSlotEntry = {
          priority,
          acquiredAt: Date.now(),
          expiresAt,
          owner: ownerId,
        };
        
        this.activeSlots.set(ownerId, entry);
        this.availableSlots--;
        
        this.logger.debug(
          `✓ Compile slot acquired by ${owner} (available: ${this.availableSlots}, active: ${this.activeSlots.size})`,
        );
 
        // Return release function bound to this owner
        resolve(this.createReleaseFunction(ownerId, "compile"));
      };
 
      // Set immediate timeout for this acquire attempt (not just queue timeout)
      timeoutHandle = setTimeout(() => {
        const idx = this.compileQueue.findIndex(t => t.ownerId === ownerId);
        if (idx >= 0) {
          this.compileQueue.splice(idx, 1);
        }
        this.activeSlots.delete(ownerId);
        reject(new Error(`Compile slot acquire timeout after ${timeoutMs}ms for ${owner}`));
      }, timeoutMs);
 
      if (this.availableSlots > 0) {
        // Fast path: slot available
        grant();
      } else {
        // Slow path: queue the request with timeout
        onQueued?.();
        const queuedTask: QueuedTask = {
          priority,
          resolver: (release) => {
            const expiresAt = Date.now() + this.lockTTL;
            const entry: CompileSlotEntry = {
              priority,
              acquiredAt: Date.now(),
              expiresAt,
              owner: ownerId,
            };
            this.activeSlots.set(ownerId, entry);
            this.availableSlots--;
            resolve(release);
          },
          ownerId,
          owner,
          createdAt: Date.now(),
        };
 
        // Reject if queue is full to prevent unbounded memory growth
        if (this.compileQueue.length >= this.maxQueueSize) {
          reject(new Error(
            `Compile queue full (${this.maxQueueSize} pending). ` +
            `Try again later. Active: ${this.activeSlots.size}, Queued: ${this.compileQueue.length}`,
          ));
          return;
        }
 
        // Priority-aware insertion (O(n) instead of O(n log n) full sort)
        let insertIdx = this.compileQueue.length;
        for (let i = 0; i < this.compileQueue.length; i++) {
          if (queuedTask.priority < this.compileQueue[i].priority) {
            insertIdx = i;
            break;
          }
        }
        this.compileQueue.splice(insertIdx, 0, queuedTask);
        
        this.logger.debug(
          `⏳ Compile slot queued for ${owner} (queue: ${this.compileQueue.length}, active: ${this.activeSlots.size})`,
        );
 
        // Timeout handling
        const timeoutHandle = setTimeout(() => {
          const idx = this.compileQueue.indexOf(queuedTask);
          Iif (idx >= 0) {
            this.compileQueue.splice(idx, 1);
            reject(new Error(`Compile slot timeout after ${timeoutMs}ms for ${owner}`));
          }
        }, timeoutMs);
 
        // Wrap resolver to clear timeout on success
        const originalResolver = queuedTask.resolver;
        queuedTask.resolver = (release) => {
          clearTimeout(timeoutHandle);
          originalResolver(release);
        };
      }
    });
  }
 
  /**
   * Clean up timeout and event listener after a cache lock is acquired or timed out.
   */
  private _cleanupLockWaiter(
    key: string,
    timeoutHandle: NodeJS.Timeout | null,
    eventListener: (() => void) | null,
  ): void {
    if (timeoutHandle) clearTimeout(timeoutHandle);
    if (eventListener) this.off(`cache_lock_released:${key}`, eventListener);
  }
 
  /**
   * Acquire a cache lock (read or write)
   * Read locks: multiple readers allowed
   * Write locks: exclusive, no other locks allowed
   * Uses event-driven approach - no polling overhead
   */
  async acquireCacheLock(
    key: string,
    lockType: "read" | "write" = "read",
    timeoutMs: number = config.timeouts.compileGatekeeperAcquireMs,
    owner: string = "unknown",
  ): Promise<() => Promise<void>> {
    this.stats.totalCacheLockRequests++;
    const ownerId = `${owner}-${Date.now()}-${crypto.randomUUID()}`;
 
    return new Promise((resolve, reject) => {
      let timeoutHandle: NodeJS.Timeout | null = null;
      let eventListener: (() => void) | null = null;
 
      const tryAcquire = (): boolean => {
        const locks = this.cacheLocks.get(key) || [];
        const now = Date.now();
 
        // Filter out expired locks
        const activeLocks = locks.filter(l => l.expiresAt > now);
        
        if (lockType === "read") {
          // Read lock: allowed if no write locks exist
          const hasWriteLock = activeLocks.some(l => l.lockType === "write");
          if (!hasWriteLock) {
            const entry: CacheLockEntry = {
              key,
              lockType: "read",
              acquiredAt: now,
              expiresAt: now + this.lockTTL,
              owner: ownerId,
            };
            activeLocks.push(entry);
            this.cacheLocks.set(key, activeLocks);
            this.logger.debug(`✓ Read lock acquired for ${key} by ${owner}`);
            this._cleanupLockWaiter(key, timeoutHandle, eventListener);
            resolve(this.createCacheLockReleaser(key, ownerId));
            return true;
          }
        } else if (activeLocks.length === 0) {
          // Write lock: exclusive, no other locks allowed
          const entry: CacheLockEntry = {
            key,
            lockType: "write",
            acquiredAt: now,
            expiresAt: now + this.lockTTL,
            owner: ownerId,
          };
          this.cacheLocks.set(key, [entry]);
          this.logger.debug(`✓ Write lock acquired for ${key} by ${owner}`);
          this._cleanupLockWaiter(key, timeoutHandle, eventListener);
          resolve(this.createCacheLockReleaser(key, ownerId));
          return true;
        }
 
        return false;
      };
 
      // Try immediate acquisition
      if (tryAcquire()) {
        return;
      }
 
      // Set up event-driven waiting (no polling)
      const eventName = `cache_lock_released:${key}`;
      eventListener = () => {
        tryAcquire(); // Event fires when lock might be available
      };
      
      this.on(eventName, eventListener);
 
      // Timeout handling with cleanup
      timeoutHandle = setTimeout(() => {
        Eif (eventListener) {
          this.off(eventName, eventListener);
        }
        reject(new Error(`Cache lock timeout (${lockType}) for ${key} after ${timeoutMs}ms`));
      }, timeoutMs);
    });
  }
 
  /**
   * Grant the next task from the compile queue a slot.
   * Called after a slot is released to wake up a waiting requester.
   */
  private _grantNextQueuedSlot(): void {
    if (this.compileQueue.length === 0) return;
    const task = this.compileQueue.shift();
    Iif (!task) return;
    try {
      task.resolver(this.createReleaseFunction(task.ownerId, "compile"));
    } catch (err) {
      this.logger.error(
        `Failed to grant queued slot to ${task.owner}: ${err instanceof Error ? err.message : String(err)}`,
      );
      // Slot remains available (already incremented above), try next task
      if (this.compileQueue.length > 0) {
        const next = this.compileQueue.shift();
        if (!next) return;
        try {
          next.resolver(this.createReleaseFunction(next.ownerId, "compile"));
        } catch {
          // Silently drop — slot stays available
        }
      }
    }
  }
 
  /**
   * Release a compile slot
   * Emits event for monitoring and triggers next queued task
   */
  private createReleaseFunction(ownerId: string, type: "compile" | "cache"): () => void {
    return () => {
      Eif (type === "compile") {
        const entry = this.activeSlots.get(ownerId);
        if (entry) {
          this.activeSlots.delete(ownerId);
          this.availableSlots++;
          this.logger.debug(
            `✓ Compile slot released (available: ${this.availableSlots}, active: ${this.activeSlots.size})`,
          );
          this.emit("slot_released");
          this._grantNextQueuedSlot();
        }
      }
    };
  }
 
  /**
   * Create a cache lock releaser function
   * Emits event to wake up waiting tasks (event-driven, no polling)
   */
  private createCacheLockReleaser(key: string, ownerId: string): () => Promise<void> {
    return async () => {
      const locks = this.cacheLocks.get(key);
      Eif (locks) {
        const filteredLocks = locks.filter(l => l.owner !== ownerId);
        if (filteredLocks.length === 0) {
          this.cacheLocks.delete(key);
        } else {
          this.cacheLocks.set(key, filteredLocks);
        }
        this.logger.debug(`✓ Lock released for ${key}`);
        
        // Emit event to wake up waiting tasks (O(1) notification instead of polling)
        this.emit(`cache_lock_released:${key}`);
      }
    };
  }
 
  /**
   * Monitor for expired locks and clean them up automatically
   * Prevents deadlocks caused by crashed processes
   * Emits events to wake up waiting tasks
   */
  private startLockMonitoring(): void {
    Iif (this.lockCheckInterval) {
      return;
    }
 
    this.lockCheckInterval = setInterval(() => {
      const now = Date.now();
      let expiredCount = 0;
      const releasedKeys = new Set<string>();
 
      // Check compile slots
      for (const [ownerId, slot] of this.activeSlots.entries()) {
        Iif (slot.expiresAt < now) {
          this.activeSlots.delete(ownerId);
          this.availableSlots++;
          expiredCount++;
          this.logger.warn(`⚠ Compile slot TTL expired for ${slot.owner}, auto-releasing`);
          
          // Emit event to wake up queued tasks
          this.emit("slot_released");
        }
      }
 
      // Check cache locks
      for (const [key, locks] of this.cacheLocks.entries()) {
        const activeLocks = locks.filter(l => l.expiresAt > now);
        const expiredInKey = locks.length - activeLocks.length;
        expiredCount += expiredInKey;
 
        if (activeLocks.length === 0) {
          this.cacheLocks.delete(key);
        } else {
          this.cacheLocks.set(key, activeLocks);
        }
 
        if (expiredInKey > 0) {
          this.logger.warn(`⚠ ${expiredInKey} cache lock(s) TTL expired for ${key}, auto-releasing`);
          releasedKeys.add(key);
        }
      }
 
      // Emit events for all released cache locks (O(1) per key)
      for (const key of releasedKeys) {
        this.emit(`cache_lock_released:${key}`);
      }
 
      Iif (expiredCount > 0) {
        this.stats.expiredLocks += expiredCount;
        this.stats.deadlocksAvoided++;
      }
    }, this.checkIntervalMs);
  }
 
  /**
   * Gracefully stop lock monitoring and cleanup event listeners
   */
  stopLockMonitoring(): void {
    if (this.lockCheckInterval) {
      clearInterval(this.lockCheckInterval);
      this.lockCheckInterval = null;
    }
    
    // Remove all event listeners to prevent memory leaks
    this.removeAllListeners();
  }
 
  /**
   * Get current gatekeeper statistics for monitoring
   */
  getStats() {
    return {
      maxConcurrentCompiles: this.maxCompileConcurrent,
      availableSlots: this.availableSlots,
      activeCompiles: this.activeSlots.size,
      queuedCompiles: this.compileQueue.length,
      activeCacheLocks: this.cacheLocks.size,
      totalCompileRequests: this.stats.totalCompileSlotRequests,
      totalCacheLockRequests: this.stats.totalCacheLockRequests,
      expiredLocks: this.stats.expiredLocks,
      deadlocksAvoided: this.stats.deadlocksAvoided,
    };
  }
 
  /**
   * Gracefully drain all queues and wait for completion
   */
  async drain(): Promise<void> {
    return new Promise((resolve) => {
      const checkEmpty = () => {
        if (
          this.activeSlots.size === 0 &&
          this.compileQueue.length === 0 &&
          this.cacheLocks.size === 0
        ) {
          resolve();
        } else {
          setTimeout(checkEmpty, 100);
        }
      };
      checkEmpty();
    });
  }
 
  /**
   * Reset gatekeeper state (for testing)
   * Removes all event listeners to prevent memory leaks
   */
  reset(): void {
    this.activeSlots.clear();
    this.compileQueue = [];
    this.cacheLocks.clear();
    this.availableSlots = this.maxCompileConcurrent;
    this.stats = {
      totalCompileSlotRequests: 0,
      totalCacheLockRequests: 0,
      expiredLocks: 0,
      deadlocksAvoided: 0,
    };
    
    // Remove all event listeners to prevent memory leaks
    this.removeAllListeners();
    
    this.logger.info("UnifiedGatekeeper reset");
  }
}
 
/**
 * Global singleton instance
 */
let unifiedGatekeeperInstance: UnifiedGatekeeper | null = null;
 
export function getUnifiedGatekeeper(maxConcurrent?: number): UnifiedGatekeeper {
  unifiedGatekeeperInstance ??= new UnifiedGatekeeper(maxConcurrent);
  return unifiedGatekeeperInstance;
}
 
export function resetUnifiedGatekeeper(): void {
  const instance = unifiedGatekeeperInstance;
  if (instance) {
    instance.stopLockMonitoring();
  }
  unifiedGatekeeperInstance = null;
}