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 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 | 4x 4x 2x 1x 1x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 16x 16x 16x 16x 16x 16x 5x 44x 44x 52x 44x 44x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 44x 1x 1x 1x 1x 1x 1x 1x 1x 44x 26x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 47x 47x 47x 1x 1x 1x 1x 46x 47x 46x 46x 2x 2x 44x 44x 44x 44x 47x 14x 14x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 47x 47x 47x 47x 47x 1x 1x 1x 1x 43x 43x 2x 1x 1x 1x 1x 4x 4x 3x 4x 4x 16x 16x 60x 2x 4x 3x 2x 16x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 2x 49x 49x 49x 49x 49x 49x 49x 49x 61x 49x 49x 49x 49x 49x 1x 1x 1x 1x 1x 1x 2x 2x 1x 2x 2x 2x 2x 2x 1x 16x | import { WebSocketServer, WebSocket } from "ws";
import type { Server } from "node:http";
import type { SandboxRunner } from "../services/sandbox-runner";
import {
type IOPinRecord,
type ClientToServerWSMessage,
type WSMessage,
WSMessageType,
} from "@shared/schema";
import type { Logger } from "@shared/logger";
import type { PinStateChange } from "@shared/types/arduino.types";
import { getSandboxRunnerPool } from "../services/sandbox-runner-pool";
import path from "node:path";
import { writeFile, access } from "node:fs/promises";
import {
createWebSocketAuthorizationVerifier,
getRequestAuthorization,
type TrustConfig,
} from "../security/access-control";
import { INPUT_LIMITS } from "@shared/input-limits";
import { WsMessageRouter } from "./simulation/ws-message-router";
import { type ClientState, WsSessionManager } from "./simulation/ws-session-manager";
import { sendMessageToClient, WsOutputBuffer } from "./simulation/ws-output-buffer";
import { WEBSOCKET_PROTOCOL_VERSION } from "../services/protocol-version";
import {
AdmissionResult,
SimulationAdmissionController,
SimulationReservation,
} from "../services/simulation-admission-controller";
import { operationError, SYSTEM_BUSY_MESSAGE } from "@shared/operation-errors";
function sendStartError(
ws: WebSocket,
error: ReturnType<typeof operationError>,
): void {
sendMessageToClient(ws, {
type: WSMessageType.OPERATION_ERROR,
operation: "start_simulation",
...error,
});
sendMessageToClient(ws, {
type: WSMessageType.SIMULATION_STATUS,
status: "stopped",
});
}
function rejectAdmission(
ws: WebSocket,
admission: Extract<AdmissionResult, { admitted: false }>,
): void {
if (admission.reason === "capacity") {
sendStartError(
ws,
operationError("SYSTEM_BUSY", SYSTEM_BUSY_MESSAGE, 5),
);
} else {
sendStartError(
ws,
operationError(
"SIMULATION_ALREADY_ACTIVE",
"Für diesen Nutzer läuft bereits eine Simulation oder wartet auf einen Runner.",
),
);
}
}
/**
* Handle "pause_simulation" WebSocket message
*/
function handlePauseSimulation(
_ws: WebSocket,
clientState: ClientState,
): void {
Eif (clientState?.runner && clientState.isRunning) {
const paused = clientState.runner.pause();
Eif (paused) {
clientState.isPaused = true;
sendMessageToClient(_ws, {
type: WSMessageType.SIMULATION_STATUS,
status: "paused",
});
sendMessageToClient(_ws, {
type: WSMessageType.SERIAL_OUTPUT,
data: "--- Simulation paused ---\n",
});
}
}
}
/**
* Handle "resume_simulation" WebSocket message
*/
function handleResumeSimulation(
_ws: WebSocket,
clientState: ClientState,
): void {
Eif (clientState?.runner && clientState.isPaused) {
const resumed = clientState.runner.resume();
Eif (resumed) {
clientState.isPaused = false;
clientState.isRunning = true;
sendMessageToClient(_ws, {
type: WSMessageType.SIMULATION_STATUS,
status: "running",
});
sendMessageToClient(_ws, {
type: WSMessageType.SERIAL_OUTPUT,
data: "--- Simulation resumed ---\n",
});
}
}
}
/**
* Handle "serial_input" WebSocket message
*/
function handleSerialInput(
_ws: WebSocket,
data: Extract<ClientToServerWSMessage, { type: "serial_input" }>,
clientState: ClientState,
): void {
Eif (
clientState?.runner &&
clientState?.isRunning &&
!clientState.isPaused
) {
clientState.runner.sendSerialInput(data.data);
}
}
/**
* Handle "set_pin_value" WebSocket message
*/
function handleSetPinValue(
_ws: WebSocket,
data: Extract<ClientToServerWSMessage, { type: "set_pin_value" }>,
clientState: ClientState,
): void {
Eif (
clientState?.runner &&
(clientState.isRunning || clientState.isPaused)
) {
clientState.runner.setPinValue(data.pin, data.value);
}
}
type SimulationDeps = {
SandboxRunner: typeof SandboxRunner;
getSimulationRateLimiter: () => {
checkLimit: (identity: string) => {
allowed: boolean;
retryAfter?: number;
};
};
getSimulationAdmissionController?: () => SimulationAdmissionController;
shouldSendSimulationEndMessage: (compileFailed: boolean) => boolean;
getLastCompiledCode: () => string | null;
logger: Logger;
runnerPool?: ReturnType<typeof getSandboxRunnerPool>;
trust: TrustConfig;
allowedWebSocketOrigins: readonly string[];
disableRateLimit: boolean;
};
// Return type exposes a small API used by other modules (test-reset)
export function registerSimulationWebSocket(
httpServer: Server,
deps: SimulationDeps,
) {
const {
getSimulationRateLimiter,
shouldSendSimulationEndMessage,
getLastCompiledCode,
logger,
runnerPool,
} = deps;
const pool = runnerPool ?? getSandboxRunnerPool();
const admissionController = deps.getSimulationAdmissionController?.() ??
new SimulationAdmissionController();
const wss = new WebSocketServer({
server: httpServer,
path: "/ws",
maxPayload: INPUT_LIMITS.webSocket.maxPayloadBytes,
// Disable per-message compression to eliminate zlib concurrency bottleneck.
// With 200+ simultaneous clients, the default concurrencyLimit:10 caused CPU
// starvation during pin-state bursts; disabling deflate entirely removes that
// constraint at the cost of slightly higher bandwidth (tolerable on LAN).
perMessageDeflate: false,
verifyClient: createWebSocketAuthorizationVerifier(
deps.trust,
deps.allowedWebSocketOrigins,
),
});
const sessionManager = new WsSessionManager({
pool,
logger,
admissionController,
});
const outputBuffer = new WsOutputBuffer();
function safeReleaseRunner(
state: ClientState,
reason: string,
): Promise<void> {
return sessionManager.safeReleaseRunner(state, reason);
}
/**
* Build all callback functions for sketch execution (onOutput, onError, etc.)
* Extracted to reduce cognitive complexity of message handler.
*/
function buildRunSketchCallbacks(
ws: WebSocket,
clientState: ClientState,
reservation: SimulationReservation,
) {
let compileFailed = false;
const onOutput = (line: string, isComplete?: boolean) => {
outputBuffer.sendSerialOutputBatched(ws, line, isComplete);
};
const onError = (err: string) => {
logger.warn(`[Client WS][ERR]: ${err}`);
outputBuffer.flushSerialOutputBuffer(ws);
sendMessageToClient(ws, {
type: WSMessageType.SERIAL_OUTPUT,
data: "[ERR] " + err,
});
};
const onExit = (_exitCode: number | null) => {
// Capture client state immediately — the session entry
// may be deleted by the ws "close" handler before the setTimeout fires.
const capturedCs = sessionManager.get(ws);
setTimeout(async () => {
try {
outputBuffer.flushSerialOutputBuffer(ws);
Eif (capturedCs) {
await sessionManager.safeReleaseRunner(
capturedCs,
"onExit",
reservation,
);
}
Iif (!shouldSendSimulationEndMessage(compileFailed)) return;
sendMessageToClient(ws, {
type: WSMessageType.SERIAL_OUTPUT,
data: "--- Simulation ended: Loop cycles completed ---\n",
isComplete: true,
});
sendMessageToClient(ws, {
type: WSMessageType.SIMULATION_STATUS,
status: "stopped",
});
outputBuffer.clearClient(ws);
} catch (err) {
logger.error(
`Error sending stop message: ${err instanceof Error ? err.message : String(err)}`,
);
}
}, 100);
};
const onCompileError = (compileErr: string) => {
compileFailed = true;
sendMessageToClient(ws, {
type: WSMessageType.COMPILATION_ERROR,
data: compileErr,
});
sendMessageToClient(ws, {
type: WSMessageType.COMPILATION_STATUS,
arduinoCliStatus: "error",
});
sendMessageToClient(ws, {
type: WSMessageType.SIMULATION_STATUS,
status: "stopped",
});
const cs = sessionManager.get(ws);
Eif (cs) {
sessionManager.safeReleaseRunner(
cs,
"onCompileError",
reservation,
).catch((error) => {
logger.warn(
`[SandboxRunnerPool] safeReleaseRunner failed in onCompileError: ${error}`,
);
});
}
logger.error(`[Client Compile Error]: ${compileErr}`);
};
const onCompileSuccess = () => {
sendMessageToClient(ws, {
type: WSMessageType.COMPILATION_STATUS,
arduinoCliStatus: "success",
});
};
const onCompileQueued = () => {
// gccStatus:queued removed in Phase 3.3.6 - queue state no longer emitted via WS
// arduinoCliStatus does not have a "queued" state
};
const onPinState = (pin: number, type: PinStateChange, value: number) => {
sendMessageToClient(ws, {
type: WSMessageType.PIN_STATE,
pin,
stateType: type,
value,
});
};
const onIORegistry = (
registry: IOPinRecord[],
baudrate: number | undefined,
reason?: string,
) => {
const message: Extract<WSMessage, { type: "io_registry" }> = {
type: WSMessageType.IO_REGISTRY,
registry,
};
if (baudrate !== undefined) message.baudrate = baudrate;
if (reason !== undefined) message.reason = reason;
sendMessageToClient(ws, message);
const baudSuffix = baudrate === undefined ? "" : `, baud=${baudrate}`;
logger.info(`[io_registry] ${registry.length} pins${baudSuffix}`);
// Async save without blocking — fire-and-forget with error handling
(async () => {
try {
const sketchDir = clientState?.runner?.getSketchDir();
if (!sketchDir) return;
try {
await access(sketchDir);
} catch {
return;
}
const registryFile = path.join(
sketchDir,
`io-registry-${Date.now()}.pending.json`,
);
await writeFile(registryFile, JSON.stringify(registry, null, 2));
logger.debug(`Registry saved: ${path.basename(registryFile)}`);
if (clientState.runner)
clientState.runner.setRegistryFile(registryFile);
} catch (err) {
logger.warn(
`Failed to save I/O Registry file: ${err instanceof Error ? err.message : String(err)}`,
);
}
})();
};
const onTelemetry = (metrics: {
timestamp: number;
intendedPinChangesPerSecond: number;
actualPinChangesPerSecond: number;
droppedPinChangesPerSecond: number;
batchesPerSecond: number;
avgStatesPerBatch: number;
serialOutputPerSecond: number;
serialBytesPerSecond: number;
serialBytesTotal: number;
serialIntendedBytesPerSecond: number;
serialDroppedBytesPerSecond: number;
}) => {
sendMessageToClient(ws, { type: WSMessageType.SIM_TELEMETRY, metrics });
};
const onPinStateBatch = (batch: {
states: Array<{ pin: number; stateType: PinStateChange; value: number }>;
timestamp: number;
}) => {
sendMessageToClient(ws, {
type: WSMessageType.PIN_STATE_BATCH,
states: batch.states,
timestamp: batch.timestamp,
});
};
return {
onOutput,
onError,
onExit,
onCompileError,
onCompileSuccess,
onCompileQueued,
onPinState,
onIORegistry,
onTelemetry,
onPinStateBatch,
compileFailed: () => compileFailed,
};
}
/**
* Acquires a runner from the pool for the given client.
* Manages the AbortController and handles pool-exhaustion / cancel errors.
* Returns false when the caller should return early.
* Extracted to keep handleStartSimulation below cognitive complexity threshold.
*/
async function acquireRunnerForClient(
ws: WebSocket,
clientState: ClientState,
reservation: SimulationReservation,
): Promise<boolean> {
const acquireAbort = new AbortController();
clientState.queueAbortController = acquireAbort;
try {
clientState.runner = await pool.acquireRunner(acquireAbort.signal);
clientState.queueAbortController = null;
Iif (clientState.reservation !== reservation) {
await pool.releaseRunner(clientState.runner);
clientState.runner = null;
return false;
}
logger.debug(
`[SandboxRunnerPool] Acquired runner for client. Pool stats: ${JSON.stringify(pool.getStats())}`,
);
return true;
} catch (error) {
clientState.queueAbortController = null;
const isCancelled =
error instanceof Error && error.message.includes("cancelled");
if (isCancelled) {
// Client disconnected while waiting — nothing to send, WS is already closed
logger.debug(
`[SandboxRunnerPool] Acquire cancelled because WS closed while queued`,
);
} else {
logger.error(`[SandboxRunnerPool] Failed to acquire runner: ${error}`);
sendStartError(
ws,
operationError("SYSTEM_BUSY", SYSTEM_BUSY_MESSAGE, 5),
);
}
clientState.runner = null;
clientState.isRunning = false;
clientState.isPaused = false;
await sessionManager.safeReleaseRunner(
clientState,
"runner-acquire-failed",
reservation,
);
return false;
}
}
/**
* Log consolidated run payload for audit/evidence.
* Extracted to keep handleStartSimulation below cognitive complexity threshold.
*/
function logRunPayloadAudit(
code: string,
timeoutSec: number | undefined,
sessionId: string | undefined,
): void {
try {
const payload = {
code,
timeoutSec,
context: { sessionId, label: "default-ws" },
};
logger.debug(
`[B1-Evidence] Payload: ${JSON.stringify(payload, null, 2)}`,
);
} catch (err) {
logger.warn(
`Could not stringify run payload for evidence: ${err instanceof Error ? err.message : String(err)}`,
);
}
}
/**
* Handle "start_simulation" WebSocket message
* Checks rate limits, acquires runner, and starts sketch execution.
*/
async function handleStartSimulation(
ws: WebSocket,
data: Extract<ClientToServerWSMessage, { type: "start_simulation" }>,
clientState: ClientState,
): Promise<void> {
// Rate limiting check
const rateLimiter = getSimulationRateLimiter();
const limitCheck = deps.disableRateLimit
? { allowed: true }
: rateLimiter.checkLimit(clientState.subject);
if (!limitCheck.allowed) {
const retryAfter = limitCheck.retryAfter || 30;
logger.warn(
`[RateLimit] Simulation start rejected. Retry after ${retryAfter}s`,
);
sendStartError(
ws,
operationError(
"RATE_LIMITED",
`Simulation start rate limit exceeded. Please wait ${retryAfter} seconds before starting again.`,
retryAfter,
),
);
return;
}
// Use per-client code from the WS message if provided (multi-client isolation),
// Deprecated compatibility fallback. New clients send code per session;
// remove this branch at the next protocol-major release.
const code =
"code" in data &&
typeof data.code === "string" &&
data.code.trim().length > 0
? data.code
: getLastCompiledCode();
Iif (!code) {
if (clientState.runner) {
await safeReleaseRunner(clientState, "missing-compiled-code");
}
clientState.isRunning = false;
clientState.isPaused = false;
sendMessageToClient(ws, {
type: WSMessageType.SERIAL_OUTPUT,
data: "[ERR] No compiled code available. Please compile first.\n",
});
sendMessageToClient(ws, {
type: WSMessageType.SIMULATION_STATUS,
status: "stopped",
});
return;
}
const admission = admissionController.reserve(clientState.subject);
if (!admission.admitted) {
rejectAdmission(ws, admission);
return;
}
const reservation = admission.reservation;
clientState.reservation = reservation;
// If the pool is saturated, notify client it is queued and wait for a slot
const statsBeforeAcquire = pool.getStats();
const willQueue =
statsBeforeAcquire.availableRunners === 0 &&
statsBeforeAcquire.totalRunners >= statsBeforeAcquire.maxRunners;
if (willQueue) {
logger.debug(
`[SandboxRunnerPool] Pool saturated — client queued (queue length: ${statsBeforeAcquire.queuedRequests + 1})`,
);
sendMessageToClient(ws, {
type: WSMessageType.SIMULATION_STATUS,
status: "queued",
});
}
// Acquire new runner from pool (may block until a slot is released).
// The AbortController is managed inside acquireRunnerForClient; it is set on
// clientState so the WS-close handler can cancel the wait on disconnect.
Iif (!(await acquireRunnerForClient(ws, clientState, reservation))) return;
const acquiredRunner = clientState.runner!; // non-null: acquireRunnerForClient returned true
// Slot assignment: tell client which runner slot they own immediately
const acquiredWorkerIndex = pool.getRunnerIndex(acquiredRunner);
// Update client state and notify running.
// isRunning is set BEFORE countRunningClients() so the new client is
// included in the total it (and others) receive.
clientState.isRunning = true;
clientState.isPaused = false;
sendMessageToClient(ws, {
type: WSMessageType.SIMULATION_STATUS,
status: "running",
});
sendMessageToClient(ws, {
type: WSMessageType.COMPILATION_STATUS,
arduinoCliStatus: "compiling",
workerIndex: acquiredWorkerIndex,
workerTotal: sessionManager.countRunningClients(),
});
// Broadcast updated count to all OTHER running clients (ws excluded because
// it just received the full workerIndex+workerTotal message above).
sessionManager.broadcastWorkerTotal(ws);
// Build callbacks
const callbacks = buildRunSketchCallbacks(ws, clientState, reservation);
const timeoutValue = "timeout" in data ? data.timeout : undefined;
logger.info(`[Simulation] Starting with timeout: ${timeoutValue}s`);
// Log consolidated payload for audit
logRunPayloadAudit(code, timeoutValue, clientState.testRunId);
// Capture runner reference before await – ws-close may set clientState.runner=null
// concurrently while runSketch is awaited, causing a null-dereference on getSandboxStatus.
const runnerForStatus = acquiredRunner;
// Start sketch execution and publish sandbox mode once the runner has resolved
try {
await acquiredRunner.runSketch({
code,
headers: data.headers,
onOutput: callbacks.onOutput,
onError: callbacks.onError,
onExit: callbacks.onExit,
onCompileError: callbacks.onCompileError,
onCompileSuccess: callbacks.onCompileSuccess,
onCompileQueued: callbacks.onCompileQueued,
onPinState: callbacks.onPinState,
timeoutSec: timeoutValue,
onIORegistry: callbacks.onIORegistry,
onTelemetry: callbacks.onTelemetry,
onPinStateBatch: callbacks.onPinStateBatch,
context: { sessionId: clientState.testRunId, label: "default-ws" },
});
} catch (error) {
logger.error(`[Simulation] runSketch failed: ${error}`);
await sessionManager.safeReleaseRunner(
clientState,
"runSketch-error",
reservation,
);
sendStartError(
ws,
operationError(
"SIMULATION_START_FAILED",
"Simulation could not be started.",
),
);
return;
}
const sandboxStatus = runnerForStatus.getSandboxStatus();
sendMessageToClient(ws, {
type: WSMessageType.COMPILATION_STATUS,
sandboxMode: sandboxStatus.mode,
});
}
/**
* Handle "code_changed" WebSocket message
*/
async function handleCodeChanged(
_ws: WebSocket,
clientState: ClientState,
): Promise<void> {
if (clientState?.runner || clientState?.reservation) {
sessionManager.abortQueuedAcquire(clientState);
await safeReleaseRunner(clientState, "code_changed");
sendMessageToClient(_ws, {
type: WSMessageType.SIMULATION_STATUS,
status: "stopped",
});
sendMessageToClient(_ws, {
type: WSMessageType.SERIAL_OUTPUT,
data: "--- Simulation stopped due to code change ---\n",
});
}
}
/**
* Handle "stop_simulation" WebSocket message
*/
async function handleStopSimulation(
_ws: WebSocket,
clientState: ClientState,
): Promise<void> {
sessionManager.abortQueuedAcquire(clientState);
if (clientState?.runner || clientState?.reservation) {
await safeReleaseRunner(clientState, "stop_simulation");
}
sendMessageToClient(_ws, {
type: WSMessageType.SIMULATION_STATUS,
status: "stopped",
});
sendMessageToClient(_ws, {
type: WSMessageType.SERIAL_OUTPUT,
data: "--- Simulation stopped ---\n",
});
}
let _wsConnectAttempts = 0;
const messageRouter = new WsMessageRouter({
logger,
getClientState: (ws) => sessionManager.get(ws),
handlers: {
startSimulation: handleStartSimulation,
codeChanged: (ws, _data, clientState) => handleCodeChanged(ws, clientState),
stopSimulation: (ws, _data, clientState) => handleStopSimulation(ws, clientState),
pauseSimulation: (ws, _data, clientState) => handlePauseSimulation(ws, clientState),
resumeSimulation: (ws, _data, clientState) => handleResumeSimulation(ws, clientState),
serialInput: handleSerialInput,
setPinValue: handleSetPinValue,
},
});
wss.on("connection", (ws, req) => {
const authorization = getRequestAuthorization(req, deps.trust);
Iif (!authorization.allowed) {
ws.close(1008, "Unauthorized");
return;
}
const identity = authorization.identity;
const url = req.url || "";
const urlParams = new URLSearchParams(url.split("?")[1] || "");
const testRunId = urlParams.get("testRunId") || undefined;
const testRunIdSuffix = testRunId ? ` [testRunId: ${testRunId}]` : "";
_wsConnectAttempts++;
logger.warn(
`New WebSocket client connected for subject ${identity.subject}${testRunIdSuffix}. Total clients: ${wss.clients.size} (attempt #${_wsConnectAttempts})`,
);
if (_wsConnectAttempts % 10 === 0) {
logger.warn(
`[WS milestone] ${_wsConnectAttempts} total connect attempts, ${wss.clients.size} currently open`,
);
}
sessionManager.register(ws, {
subject: identity.subject,
runner: null,
isRunning: false,
isPaused: false,
testRunId,
queueAbortController: null,
reservation: null,
});
const clientState = sessionManager.get(ws);
let simStatus: "paused" | "running" | "stopped";
Iif (clientState?.isPaused) {
simStatus = "paused";
I} else if (clientState?.isRunning) {
simStatus = "running";
} else {
simStatus = "stopped";
}
sendMessageToClient(ws, {
type: WSMessageType.SIMULATION_STATUS,
status: simStatus,
});
Iif (testRunId) {
sendMessageToClient(ws, {
type: WSMessageType.HANDSHAKE,
testRunId,
protocolVersion: WEBSOCKET_PROTOCOL_VERSION,
});
}
ws.on("message", async (message) => {
await messageRouter.route(ws, message);
});
ws.on("close", async (code: number, reason: Buffer) => {
await sessionManager.cleanupClient(ws, "ws-close");
// Clean up serial output buffer and timer
outputBuffer.clearClient(ws);
logger.warn(
`Client disconnected (code=${code}, reason=${reason.toString() || "—"}). Remaining clients: ${wss.clients.size}`,
);
});
ws.on("error", async (error) => {
await sessionManager.cleanupClient(ws, "ws-error");
// Clean up serial output buffer and timer
outputBuffer.clearClient(ws);
logger.error(
`WebSocket error: ${error instanceof Error ? error.message : String(error)}`,
);
});
});
async function stopAllRunnersAndNotify() {
const cleanedUpCount = sessionManager.size;
const cleanedTestRunIds: (string | undefined)[] = [];
for (const [ws, clientState] of sessionManager.entries()) {
sessionManager.abortQueuedAcquire(clientState);
if (clientState.runner || clientState.reservation) {
await safeReleaseRunner(clientState, "test-reset");
}
clientState.isRunning = false;
clientState.isPaused = false;
cleanedTestRunIds.push(clientState.testRunId);
sendMessageToClient(ws, {
type: WSMessageType.SIMULATION_STATUS,
status: "stopped",
});
}
const cleaned = cleanedTestRunIds.filter((id): id is string => Boolean(id));
return { cleanedUpCount, cleanedTestRunIds: cleaned };
}
return { wss, stopAllRunnersAndNotify };
}
|