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 | 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 23x 23x 23x 23x 23x 13x 6x 6x 6x 6x 23x 1x 1x 23x 23x 23x 23x 17x 23x 23x 13x 11x 11x 11x 11x 11x 24x 9x 9x 9x 9x 9x 9x 9x 9x 9x 7x 7x 7x 1x 1x 1x 1x 1x 1x 6x 5x 5x 5x 5x 5x 5x 1x 1x 1x 7x 7x 7x 7x 7x 9x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 2x 5x 5x 5x 5x 5x 1x 5x 1x 1x 5x 5x 5x 5x 6x 6x 5x 5x 4x | /**
* Compilation Worker Pool
*
* Manages a pool of worker threads for parallel C++ compilation.
* Decouples compilation from the main request thread to prevent blocking.
*
* Architecture:
* - Main Thread (Express): Receives /api/compile request → enqueues work
* - Worker Threads (N parallel): Each thread runs G++ compile independently
* - Queue Manager: Distributes work fairly when workers are busy
*
* Impact: Reduces compilation latency by ~30% under concurrent load
* (200 parallel requests sequentially → 4–8 workers process in parallel)
*/
import { Worker } from "node:worker_threads";
import path, { join } from "node:path";
import os from "node:os";
import fs from "node:fs";
import { Logger } from "@shared/logger";
import type { CompilationResult } from "./arduino-compiler";
import {
type CompileRequestPayload,
type AnyWorkerMessage,
type CompileRequestMessage,
createCompileRequest,
isReadyMessage,
isCompileResponse,
} from "@shared/worker-protocol";
import { config } from "../config";
import { compileMetricsTracker } from "./server-metrics";
/**
* Statistic tracking for monitoring pool health
*/
interface PoolStats {
activeWorkers: number;
totalTasks: number;
completedTasks: number;
failedTasks: number;
avgCompileTimeMs: number;
queuedTasks: number;
}
interface CompilationTask {
task: CompileRequestPayload;
resolve: (result: CompilationResult) => void;
reject: (error: Error) => void;
startTime: number;
}
interface ActiveCompilation {
item: CompilationTask;
compileStartTime: number;
queueWaitTimeMs: number;
messageHandler: (msg: AnyWorkerMessage) => void;
}
/**
* CompilationWorkerPool: Manage parallel compilation across worker threads
*/
export class CompilationWorkerPool {
private readonly logger = new Logger("CompilationWorkerPool");
private readonly numWorkers: number;
private readonly workers: Worker[] = [];
private readonly liveWorkers = new Set<number>();
private readonly availableWorkers: Set<number> = new Set();
private readonly queue: CompilationTask[] = [];
private readonly activeCompilations = new Map<number, ActiveCompilation>();
private isInitialized: boolean = false;
private readonly stats = {
totalTasks: 0,
completedTasks: 0,
failedTasks: 0,
compileTimes: [] as number[],
};
constructor(numWorkers?: number) {
// With per-worker temp dirs each worker has its own isolated directory,
// so race conditions in arduino-cli no longer occur.
// Safe upper bound raised to 8; WORKER_COUNT env var overrides.
const maxSafeWorkers = 8;
const recommendedWorkers = Math.max(2, Math.floor(os.cpus().length * 0.5));
this.numWorkers =
numWorkers ??
Math.min(
maxSafeWorkers,
config.compilation.workerCount ?? recommendedWorkers,
);
this.logger.info(
`[CompilationWorkerPool] Initializing with ${this.numWorkers} workers (max: ${maxSafeWorkers})`,
);
this.initializeWorkers();
}
/**
* Initialize all worker threads
*/
private initializeWorkers(): void {
// In development, workers are .ts; in production, they're .js after transpilation
const dirname = path.dirname(new URL(import.meta.url).pathname);
// Try .js first (production), fallback to .ts (development with tsx)
let workerScript = path.join(dirname, "workers", "compile-worker.js");
Iif (!fs.existsSync(workerScript)) {
workerScript = path.join(dirname, "workers", "compile-worker.ts");
}
// Validate worker file exists
Iif (!fs.existsSync(workerScript)) {
this.logger.error(
`[CompilationWorkerPool] Worker file not found: ${workerScript}`,
);
this.logger.warn(
`[CompilationWorkerPool] Worker pool disabled - falling back to synchronous compilation`,
);
// Don't throw - let CompilerWithFallback handle fallback to direct compiler
return;
}
this.logger.info(
`[CompilationWorkerPool] Using worker script: ${workerScript}`,
);
for (let i = 0; i < this.numWorkers; i++) {
try {
// Each worker gets its own temp directory to avoid arduino-cli race conditions
const workerTempRoot = join(os.tmpdir(), `unosim-worker-${i}`);
const worker = new Worker(workerScript, {
workerData: { workerId: i + 1, tempRoot: workerTempRoot },
});
const workerId = i;
worker.on("message", (msg: AnyWorkerMessage) => {
if (isReadyMessage(msg)) {
Eif (
this.liveWorkers.has(workerId) &&
!this.activeCompilations.has(workerId)
) {
this.availableWorkers.add(workerId);
}
this.logger.debug(`[Worker ${workerId}] Ready`);
this.processQueue();
}
});
worker.on("error", (err) => {
this.logger.error(`[Worker ${workerId}] Error: ${err.message}`);
this.handleWorkerFailure(workerId, err);
});
worker.on("exit", (code) => {
this.logger.warn(`[Worker ${workerId}] Exited with code ${code}`);
this.handleWorkerFailure(
workerId,
new Error(
`Compilation worker ${workerId} exited with code ${code}`,
),
);
// Optionally restart worker for resilience (not implemented in MVP)
});
this.workers[workerId] = worker;
this.liveWorkers.add(workerId);
this.logger.debug(`[Worker ${workerId}] Started`);
} catch (err) {
this.logger.error(
`Failed to start worker ${i}: ${err instanceof Error ? err.message : String(err)}`,
);
}
}
this.logger.info(
`[CompilationWorkerPool] ${this.liveWorkers.size} workers started`,
);
this.isInitialized = true;
}
/**
* Check if the pool is operational
*/
isOperational(): boolean {
return this.isInitialized && this.liveWorkers.size > 0;
}
/**
* Enqueue a compilation task
*/
async compile(task: CompileRequestPayload): Promise<CompilationResult> {
Iif (!this.isOperational()) {
throw new Error(
"Compilation worker pool is not operational. Worker files may not be available.",
);
}
this.stats.totalTasks++;
return new Promise((resolve, reject) => {
this.queue.push({
task,
resolve,
reject,
startTime: Date.now(),
});
this.processQueue();
});
}
/**
* Process queued tasks using available workers
*/
private processQueue(): void {
while (this.queue.length > 0 && this.availableWorkers.size > 0) {
const workerId = this.availableWorkers.values().next().value as number;
const queueItem = this.queue.shift();
Iif (!queueItem) break;
const { task, resolve, reject, startTime } = queueItem;
this.availableWorkers.delete(workerId);
const worker = this.workers[workerId];
const queueWaitTimeMs = Date.now() - startTime;
const compileStartTime = Date.now();
// Set up one-time message handler for this specific task
const messageHandler = (msg: AnyWorkerMessage) => {
Eif (isCompileResponse(msg)) {
const { payload } = msg;
if (payload.error) {
this.stats.failedTasks++;
compileMetricsTracker.recordCompileComplete(
compileStartTime,
queueWaitTimeMs,
false,
payload.error.message?.toLowerCase().includes("timeout") === true,
);
const errorMsg = payload.error.message || "Unknown worker error";
const error = new Error(errorMsg);
Iif (payload.error.stack) {
error.stack = payload.error.stack;
}
reject(error);
} else if (payload.result) {
const compileTimeMs = Date.now() - compileStartTime;
compileMetricsTracker.recordCompileComplete(
compileStartTime,
queueWaitTimeMs,
payload.result.success,
!payload.result.success && `${payload.result.stderr ?? ""} ${payload.result.errors.map((err) => err.message).join(" ")}`.toLowerCase().includes("timeout"),
);
this.stats.completedTasks++;
this.stats.compileTimes.push(compileTimeMs);
this.logger.info(
`[Worker ${workerId}] Compiled in ${compileTimeMs}ms`,
);
resolve(payload.result);
} else {
// Malformed response
this.stats.failedTasks++;
compileMetricsTracker.recordCompileComplete(
compileStartTime,
queueWaitTimeMs,
false,
false,
);
reject(new Error("Worker returned malformed response"));
}
// Clean up listener and mark worker as available
worker.off("message", messageHandler);
this.activeCompilations.delete(workerId);
Eif (this.liveWorkers.has(workerId)) {
this.availableWorkers.add(workerId);
}
this.processQueue(); // Process next in queue
}
};
this.activeCompilations.set(workerId, {
item: { task, resolve, reject, startTime },
compileStartTime,
queueWaitTimeMs,
messageHandler,
});
worker.on("message", messageHandler);
// Send compile task to worker using strict protocol
const message: CompileRequestMessage = createCompileRequest(task);
worker.postMessage(message);
}
}
private handleWorkerFailure(workerId: number, error: Error): void {
this.liveWorkers.delete(workerId);
this.availableWorkers.delete(workerId);
const active = this.activeCompilations.get(workerId);
Eif (active) {
this.workers[workerId]?.off("message", active.messageHandler);
this.activeCompilations.delete(workerId);
this.stats.failedTasks++;
compileMetricsTracker.recordCompileComplete(
active.compileStartTime,
active.queueWaitTimeMs,
false,
error.message.toLowerCase().includes("timeout"),
);
active.item.reject(error);
}
Eif (this.liveWorkers.size === 0 && this.queue.length > 0) {
const queued = this.queue.splice(0);
this.stats.failedTasks += queued.length;
for (const item of queued) {
item.reject(
new Error("Compilation worker pool has no operational workers"),
);
}
}
}
/**
* Get pool statistics
*/
getStats(): PoolStats {
const compileTimes = this.stats.compileTimes;
const avgCompileTimeMs =
compileTimes.length > 0
? compileTimes.reduce((a, b) => a + b, 0) / compileTimes.length
: 0;
return {
activeWorkers: this.activeCompilations.size,
totalTasks: this.stats.totalTasks,
completedTasks: this.stats.completedTasks,
failedTasks: this.stats.failedTasks,
avgCompileTimeMs,
queuedTasks: this.queue.length,
};
}
/**
* Gracefully shut down the pool
*/
async shutdown(): Promise<void> {
this.logger.info("[CompilationWorkerPool] Shutting down...");
this.isInitialized = false;
const shutdownError = new Error("Compilation worker pool is shutting down");
for (const item of this.queue.splice(0)) {
item.reject(shutdownError);
}
for (const [workerId, active] of this.activeCompilations) {
this.workers[workerId]?.off("message", active.messageHandler);
active.item.reject(shutdownError);
}
this.activeCompilations.clear();
this.availableWorkers.clear();
this.liveWorkers.clear();
const promises = this.workers.map((worker, idx) => {
return worker
.terminate()
.then(() => {
this.logger.debug(`[Worker ${idx}] Terminated`);
})
.catch((err) => {
this.logger.error(
`[Worker ${idx}] Termination error: ${err.message}`,
);
});
});
await Promise.all(promises);
this.logger.info("[CompilationWorkerPool] Shutdown complete");
}
}
/**
* Singleton instance
*/
let poolInstance: CompilationWorkerPool | null = null;
export function getCompilationPool(): CompilationWorkerPool {
poolInstance ??= new CompilationWorkerPool();
return poolInstance;
}
|