All files / server/routes/simulation ws-session-manager.ts

97.61% Statements 82/84
96.07% Branches 49/51
94.44% Functions 17/18
98.7% Lines 76/77

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                                                                              90x                       54x   54x     91x 91x 91x       62x 61x 61x 61x 61x       10x 9x 9x 9x 9x       59x 58x 58x 58x 58x       350x       88x 88x 87x   88x       2x               304x 304x 749x   304x       226x 226x 523x 104x                                     87x 1x   86x     86x   86x   86x 86x               86x 86x 86x 86x 86x 86x   86x 57x 57x 29x   3x 3x     86x 82x 82x   1x         82x 82x   1x           86x 83x           111x       110x 4x 4x         88x 88x 87x 87x 87x 87x 31x       88x 88x      
import { WebSocket } from "ws";
import { WSMessageType } from "@shared/schema";
import type { Logger } from "@shared/logger";
import type { SandboxRunner } from "../../services/sandbox-runner";
import type { SandboxRunnerPool } from "../../services/sandbox-runner-pool";
import { WsSessionLifecycle } from "../../services/ws-session-lifecycle";
import { sendMessageToClient } from "./ws-output-buffer";
import { webSocketMetricsTracker } from "../../services/server-metrics";
import type {
  SimulationAdmissionController,
  SimulationReservation,
} from "../../services/simulation-admission-controller";
 
export type ClientState = {
  subject: string;
  runner: SandboxRunner | null;
  isRunning: boolean;
  isPaused: boolean;
  testRunId?: string;
  queueAbortController: AbortController | null;
  reservation: SimulationReservation | null;
  metricsState?: "running" | "paused" | null;
  /**
   * In-flight release of this connection's lifecycle. Its reservation is
   * already detached from the state, but runner and admission are not yet
   * returned; a new start on this connection waits for it.
   */
  releasing?: Promise<void> | null;
  /** Incremented by stop, code change and disconnect to cancel waiting starts. */
  startGeneration?: number;
  closed?: boolean;
};
 
/**
 * A connection owns at most one simulation lifecycle: from admission until its
 * release has returned runner and admission. Separate connections of the same
 * subject remain independent (bounded by the per-subject admission limit).
 */
export function hasSimulationLifecycle(state: ClientState): boolean {
  return Boolean(
    state.reservation || state.runner || state.queueAbortController || state.releasing,
  );
}
 
interface WsSessionManagerParams {
  pool: SandboxRunnerPool;
  logger: Logger;
  admissionController?: Pick<SimulationAdmissionController, "release">;
}
 
export class WsSessionManager {
  private readonly clientRunners = new WsSessionLifecycle<WebSocket, ClientState>();
 
  constructor(private readonly params: WsSessionManagerParams) {}
 
  register(ws: WebSocket, state: ClientState): void {
    state.metricsState ??= null;
    webSocketMetricsTracker.onConnection();
    this.clientRunners.register(ws, state);
  }
 
  markSessionRunning(state: ClientState): void {
    if (state.metricsState === "running") return;
    state.isRunning = true;
    state.isPaused = false;
    webSocketMetricsTracker.onSessionStart();
    state.metricsState = "running";
  }
 
  markSessionPaused(state: ClientState): void {
    if (state.metricsState !== "running") return;
    state.isRunning = true;
    state.isPaused = true;
    webSocketMetricsTracker.onSessionPause();
    state.metricsState = "paused";
  }
 
  markSessionStopped(state: ClientState): void {
    if (state.metricsState === null || state.metricsState === undefined) return;
    state.isRunning = false;
    state.isPaused = false;
    webSocketMetricsTracker.onSessionStop(state.metricsState);
    state.metricsState = null;
  }
 
  get(ws: WebSocket): ClientState | undefined {
    return this.clientRunners.get(ws);
  }
 
  remove(ws: WebSocket): ClientState | undefined {
    const state = this.clientRunners.remove(ws);
    if (state) {
      webSocketMetricsTracker.onDisconnection();
    }
    return state;
  }
 
  entries(): IterableIterator<[WebSocket, ClientState]> {
    return this.clientRunners.entries();
  }
 
  get size(): number {
    return this.clientRunners.size;
  }
 
  countRunningClients(): number {
    let count = 0;
    for (const state of this.clientRunners.values()) {
      if (state.isRunning) count++;
    }
    return count;
  }
 
  broadcastWorkerTotal(excludeWs?: WebSocket): void {
    const newTotal = this.countRunningClients();
    for (const [otherWs, otherState] of this.clientRunners.entries()) {
      if (otherWs !== excludeWs && otherState.isRunning) {
        sendMessageToClient(otherWs, {
          type: WSMessageType.COMPILATION_STATUS,
          workerTotal: newTotal,
        });
      }
    }
  }
 
  /**
   * Ends the connection's current lifecycle. The reservation is detached
   * synchronously, so every async continuation of the old run sees that it no
   * longer owns the session; runner and admission are returned before the
   * returned promise settles. Concurrent callers join the release in flight.
   */
  safeReleaseRunner(
    state: ClientState,
    reason: string,
    expectedReservation: SimulationReservation | null = state.reservation,
  ): Promise<void> {
    if (expectedReservation && state.reservation !== expectedReservation) {
      return Promise.resolve();
    }
    Iif (state.releasing) return state.releasing;
 
    // The settled release clears itself before any waiter resumes.
    const release: Promise<void> = this.releaseLifecycle(state, reason, expectedReservation)
      .finally(() => {
        Eif (state.releasing === release) state.releasing = null;
      });
    state.releasing = release;
    return release;
  }
 
  private async releaseLifecycle(
    state: ClientState,
    reason: string,
    expectedReservation: SimulationReservation | null,
  ): Promise<void> {
    if (expectedReservation) state.reservation = null;
    const runner = state.runner;
    state.runner = null;
    const wasRunning = state.isRunning;
    state.isRunning = false;
    state.isPaused = false;
 
    if (state.metricsState !== null && state.metricsState !== undefined) {
      this.markSessionStopped(state);
      this.broadcastWorkerTotal();
    } else if (wasRunning) {
      // Compatibility for callers that construct legacy ClientState objects.
      webSocketMetricsTracker.onSessionStop();
      this.broadcastWorkerTotal();
    }
 
    if (runner) {
      try {
        await runner.stop();
      } catch (error) {
        this.params.logger.debug(
          `[SandboxRunnerPool] runner.stop() failed during ${reason}: ${error}`,
        );
      }
 
      try {
        await this.params.pool.releaseRunner(runner);
      } catch (error) {
        this.params.logger.warn(
          `[SandboxRunnerPool] releaseRunner failed during ${reason}: ${error}`,
        );
      }
    }
 
    if (expectedReservation) {
      this.params.admissionController?.release(expectedReservation);
    }
  }
 
  /** Cancels a start that is still waiting for this connection's previous release. */
  cancelPendingStart(state: ClientState): void {
    state.startGeneration = (state.startGeneration ?? 0) + 1;
  }
 
  abortQueuedAcquire(state: ClientState): void {
    if (state.queueAbortController) {
      state.queueAbortController.abort();
      state.queueAbortController = null;
    }
  }
 
  async cleanupClient(ws: WebSocket, reason: string): Promise<void> {
    const clientState = this.get(ws);
    if (clientState) {
      clientState.closed = true;
      this.cancelPendingStart(clientState);
      this.abortQueuedAcquire(clientState);
      if (clientState.runner || clientState.reservation) {
        await this.safeReleaseRunner(clientState, reason);
      }
    }
 
    this.remove(ws);
    this.broadcastWorkerTotal();
  }
}