All files / server/services simulation-timeout-manager.ts

89.87% Statements 71/79
78.37% Branches 29/37
100% Functions 11/11
89.87% Lines 71/79

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                                    114x 114x 114x 114x 114x 114x 114x     114x 1x                         70x   70x 2x 2x     68x 68x 68x 68x   68x 11x 11x 11x   11x 11x       68x                   15x 3x 3x     12x           12x 12x 12x 12x     12x 12x 12x     12x 12x               8x 2x 2x     6x                   6x 6x 6x     6x 6x 2x 2x 2x   2x 2x       6x 6x               251x 46x 46x 46x     251x 251x 251x 251x                 7x 5x     2x 1x     1x       1x 1x             9x             6x             1x      
// simulation-timeout-manager.ts
// Manages simulation execution timeout with pause/resume support
 
import { Logger } from "@shared/logger";
 
export interface TimeoutCallback {
  (): void;
}
 
export interface SimulationTimeoutManagerConfig {
  onTimeout?: TimeoutCallback;
}
 
/**
 * SimulationTimeoutManager handles execution timeout logic with pause/resume support.
 * Ensures no zombie timers remain after stop() and correctly calculates remaining time.
 */
export class SimulationTimeoutManager {
  private timeoutHandle: NodeJS.Timeout | null = null;
  private timeoutDeadlineMs: number | null = null;
  private pausedRemainingMs: number | null = null;
  private callback: TimeoutCallback | null = null;
  private isPaused = false;
  private isActive = false;
  private readonly logger = new Logger("TimeoutManager");
 
  constructor(config: SimulationTimeoutManagerConfig = {}) {
    if (config.onTimeout) {
      this.callback = config.onTimeout;
    }
  }
 
  /**
   * Schedule a timeout with the given duration in milliseconds.
   * If timeoutMs is null, no timeout is scheduled (infinite execution).
   *
   * @param timeoutMs - Timeout duration in milliseconds, or null for infinite
   * @param callback - Callback to execute when timeout occurs
   */
  schedule(timeoutMs: number | null, callback: TimeoutCallback): void {
    // Clear any existing timeout first
    this.clear();
 
    if (timeoutMs === null || timeoutMs <= 0) {
      this.logger.debug("No timeout scheduled (infinite execution)");
      return;
    }
 
    this.callback = callback;
    this.timeoutDeadlineMs = Date.now() + timeoutMs;
    this.isActive = true;
    this.isPaused = false;
 
    this.timeoutHandle = setTimeout(() => {
      this.logger.debug("Timeout reached - executing callback");
      this.isActive = false;
      this.timeoutHandle = null;
 
      Eif (this.callback) {
        this.callback();
      }
    }, timeoutMs);
 
    this.logger.debug(
      `Timeout scheduled: ${timeoutMs}ms (deadline: ${this.timeoutDeadlineMs})`,
    );
  }
 
  /**
   * Pause the timeout clock. Calculates and stores remaining time.
   * Returns the remaining time in milliseconds, or null if no timeout is active.
   */
  pause(): number | null {
    if (!this.isActive || this.isPaused) {
      this.logger.debug("Pause ignored - not active or already paused");
      return null;
    }
 
    Iif (!this.timeoutDeadlineMs) {
      this.logger.debug("Pause ignored - no deadline set");
      return null;
    }
 
    // Calculate remaining time before clearing timer
    const now = Date.now();
    const remaining = Math.max(0, this.timeoutDeadlineMs - now);
    this.pausedRemainingMs = remaining;
    this.isPaused = true;
 
    // Clear the active timer to stop it from firing
    Eif (this.timeoutHandle) {
      clearTimeout(this.timeoutHandle);
      this.timeoutHandle = null;
    }
 
    this.logger.debug(`Timeout paused - ${remaining}ms remaining`);
    return remaining;
  }
 
  /**
   * Resume the timeout clock with the remaining time.
   * Returns true if resume was successful, false otherwise.
   */
  resume(): boolean {
    if (!this.isActive || !this.isPaused) {
      this.logger.debug("Resume ignored - not active or not paused");
      return false;
    }
 
    Iif (this.pausedRemainingMs === null || this.pausedRemainingMs <= 0) {
      this.logger.debug("Resume ignored - no remaining time");
      // Timeout already expired
      if (this.callback) {
        this.callback();
      }
      this.clear();
      return false;
    }
 
    const remainingMs = this.pausedRemainingMs;
    this.pausedRemainingMs = null;
    this.isPaused = false;
 
    // Schedule new timeout with remaining time
    this.timeoutDeadlineMs = Date.now() + remainingMs;
    this.timeoutHandle = setTimeout(() => {
      this.logger.debug("Timeout reached after resume - executing callback");
      this.isActive = false;
      this.timeoutHandle = null;
 
      Eif (this.callback) {
        this.callback();
      }
    }, remainingMs);
 
    this.logger.debug(`Timeout resumed - ${remainingMs}ms remaining`);
    return true;
  }
 
  /**
   * Stop and clear the timeout. Prevents any zombie timers.
   * This is the critical method for preventing memory leaks.
   */
  clear(): void {
    if (this.timeoutHandle) {
      clearTimeout(this.timeoutHandle);
      this.timeoutHandle = null;
      this.logger.debug("Timeout cleared");
    }
 
    this.timeoutDeadlineMs = null;
    this.pausedRemainingMs = null;
    this.isActive = false;
    this.isPaused = false;
    // Note: We keep the callback reference for reuse
  }
 
  /**
   * Get the remaining time in milliseconds.
   * Returns null if no timeout is active.
   */
  getRemainingMs(): number | null {
    if (!this.isActive) {
      return null;
    }
 
    if (this.isPaused) {
      return this.pausedRemainingMs;
    }
 
    Iif (!this.timeoutDeadlineMs) {
      return null;
    }
 
    const now = Date.now();
    return Math.max(0, this.timeoutDeadlineMs - now);
  }
 
  /**
   * Check if timeout is currently active (scheduled and not expired).
   */
  isTimeoutActive(): boolean {
    return this.isActive;
  }
 
  /**
   * Check if timeout is currently paused.
   */
  isTimeoutPaused(): boolean {
    return this.isPaused;
  }
 
  /**
   * Update the timeout callback.
   */
  setCallback(callback: TimeoutCallback): void {
    this.callback = callback;
  }
}