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 | 1776x 30x 2x 28x 28x 1x 27x 1760x 720x 83x 83x 83x 160x 160x 160x 400x 400x 1x 80x 80x 1x 1x 1x 320x 320x 80x 80x 82x 1x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 11x | /**
* Central UnoSim Configuration
*
* Single source of truth for all server-side tunable parameters.
* Values are read from environment variables with sensible defaults.
* Import this module instead of reading process.env directly.
*
* Two axes control the runtime topology:
* • Server Mode: "local" (dev machine) | "docker" (docker-compose)
* • Simulation Mode: "local" (native g++ child process) | "docker-sandbox" (isolated container)
*/
import os from "node:os";
import path from "node:path";
import { parseTrustConfig } from "./security/access-control";
// ── Mode Types ──────────────────────────────────────────────────────
/** Where the UnoSim server itself runs */
export type ServerMode = "local" | "docker";
/** Where Arduino sketch simulations are executed */
export type SimulationMode = "local" | "docker-sandbox";
// ── Env-var helpers ─────────────────────────────────────────────────
export function parseEnvInt(key: string, value: string | undefined, fallback: number, options: { min?: number; max?: number } = {}): number {
if (value === undefined || value.trim() === "") return fallback;
if (!/^[+-]?\d+$/.test(value.trim())) {
throw new Error(`Invalid ${key}: expected an integer, received "${value}"`);
}
const parsed = Number(value);
if (!Number.isSafeInteger(parsed) || (options.min !== undefined && parsed < options.min) || (options.max !== undefined && parsed > options.max)) {
throw new Error(`Invalid ${key}: value must be between ${options.min ?? "-∞"} and ${options.max ?? "∞"}`);
}
return parsed;
}
function envInt(key: string, fallback: number, options?: { min?: number; max?: number }): number {
return parseEnvInt(key, process.env[key], fallback, options);
}
function envStr(key: string, fallback: string): string {
return process.env[key] ?? fallback;
}
export function parseListenHost(
trustMode: "local" | "gateway",
configuredHost: string | undefined,
): string {
const defaultHost = trustMode === "local" ? "127.0.0.1" : "0.0.0.0";
const host = configuredHost?.trim();
return host || defaultHost;
}
function envEnum<T extends string>(key: string, fallback: T, allowed: readonly T[]): T {
const value = envStr(key, fallback);
Iif (!allowed.includes(value as T)) {
throw new Error(`Invalid ${key}: expected one of ${allowed.join(", ")}, received "${value}"`);
}
return value as T;
}
function envBool(key: string, fallback: boolean): boolean {
const v = process.env[key];
if (v === undefined) return fallback;
Eif (v === "1" || v.toLowerCase() === "true") return true;
if (v === "0" || v.toLowerCase() === "false") return false;
throw new Error(`Invalid ${key}: expected true/false, received "${v}"`);
}
function envFloat(key: string, fallback: string): string {
const value = process.env[key];
if (value === undefined || value.trim() === "") return fallback;
const parsed = Number(value);
Iif (!Number.isFinite(parsed) || parsed <= 0) {
throw new Error(`Invalid ${key}: expected a positive number, received "${value}"`);
}
return value.trim();
}
function envList(key: string, fallback: string[]): string[] {
const v = process.env[key];
Eif (v === undefined) return fallback;
return v
.split(",")
.map((s) => s.trim())
.filter(Boolean);
}
// ── Derived pool values ─────────────────────────────────────────────
const poolMinRunners = envInt("SANDBOX_POOL_MIN_RUNNERS", 5, { min: 0, max: 1000 });
// In dev (no docker-compose) maxRunners defaults to minRunners for safety.
// Production sets SANDBOX_POOL_MAX_RUNNERS=100 via docker-compose.yml.
const poolMaxRunners = envInt("SANDBOX_POOL_MAX_RUNNERS", poolMinRunners, { min: 0, max: 1000 });
export function validatePoolBounds(minRunners: number, maxRunners: number): void {
if (minRunners > maxRunners) {
throw new Error(`Invalid sandbox pool configuration: SANDBOX_POOL_MIN_RUNNERS (${minRunners}) must not exceed SANDBOX_POOL_MAX_RUNNERS (${maxRunners})`);
}
}
validatePoolBounds(poolMinRunners, poolMaxRunners);
const cwd = process.cwd();
const cpuCount = os.cpus().length;
const defaultWorkers = Math.min(8, Math.max(2, Math.floor(cpuCount * 0.5)));
const defaultCompileMaxConcurrent = Math.max(1, cpuCount - 1);
const trust = parseTrustConfig(process.env);
const localWebSocketOrigins = [
"http://localhost:3000",
"http://127.0.0.1:3000",
"http://localhost:5173",
"http://127.0.0.1:5173",
];
const examplesSource = envStr("UNOSIM_EXAMPLES_SOURCE", "").trim();
const examplesRef = envStr("UNOSIM_EXAMPLES_REF", "").trim();
const examplesAllowedHosts = envList("UNOSIM_EXAMPLES_ALLOWED_HOSTS", []).map((host) => host.toLowerCase());
Iif (examplesSource && !examplesRef) {
throw new Error("UNOSIM_EXAMPLES_REF is required when UNOSIM_EXAMPLES_SOURCE is configured");
}
Iif (examplesSource && process.env.NODE_ENV === "production" && examplesAllowedHosts.length === 0) {
throw new Error("UNOSIM_EXAMPLES_ALLOWED_HOSTS is required for external examples in production");
}
Iif (examplesSource && process.env.NODE_ENV === "production" && examplesRef === "main") {
throw new Error("UNOSIM_EXAMPLES_REF=main is not allowed for external examples in production");
}
// ── Config ──────────────────────────────────────────────────────────
export const config = {
/** Runtime environment name, captured once at startup. */
nodeEnv: process.env.NODE_ENV ?? "development",
/**
* Server mode: "local" (dev) or "docker" (docker-compose).
* Set via UNOSIM_SERVER_MODE env var; falls back to NODE_ENV detection.
*/
serverMode: envEnum(
"UNOSIM_SERVER_MODE",
process.env.NODE_ENV === "production" ? "docker" : "local",
["local", "docker"] as const,
),
/**
* Simulation execution mode.
* "docker-sandbox" uses isolated Docker containers per sketch.
* "local" compiles and runs sketches as native child processes.
* Set via UNOSIM_SIMULATION_MODE or legacy FORCE_DOCKER env var.
*/
simulationMode: envEnum(
"UNOSIM_SIMULATION_MODE",
envBool("FORCE_DOCKER", false) ? "docker-sandbox" : "local",
["local", "docker-sandbox"] as const,
),
/** True when running under a test framework */
isTest: process.env.NODE_ENV === "test",
/** HTTP and WebSocket authentication boundary. */
trust,
// ── Server ──────────────────────────────────────────────────────
server: {
/** HTTP and WebSocket listener port. */
port: envInt("PORT", 3000, { min: 1, max: 65535 }),
/** Listener host; local mode defaults to loopback, gateway mode to all interfaces. */
listenHost: parseListenHost(trust.mode, process.env.UNOSIM_LISTEN_HOST),
/**
* Register destructive endpoints used for test isolation.
* NODE_ENV=test is checked separately at the registration site so this
* flag cannot expose them in production by itself.
*/
enableTestEndpoints: envBool("ENABLE_TEST_ENDPOINTS", false),
/** CSP frame-ancestors: origins allowed to embed UnoSim in an iframe */
allowedFrameAncestors: envList(
"SIMULATOR_ALLOWED_PARENT_ORIGINS",
envList("ALLOW_EMBED_ORIGINS", [
"'self'",
"http://localhost:3000",
"http://127.0.0.1:3000",
"http://localhost:5173",
"http://127.0.0.1:5173",
]),
),
/** Exact browser origins allowed to open the simulation WebSocket. */
allowedWebSocketOrigins: envList(
"UNOSIM_ALLOWED_WS_ORIGINS",
trust.mode === "local" ? localWebSocketOrigins : [],
),
/** Completely bypass rate limiting (for E2E tests) */
disableRateLimit: envBool("DISABLE_RATE_LIMIT", false),
/** API route rate limit window */
apiRateLimitWindowMs: 15 * 60 * 1000,
/** API route rate limit in normal operation */
apiRateLimitMax: 300,
/** API route rate limit used when tests disable production throttling */
apiRateLimitTestMax: 10_000,
/** Dedicated compile request rate-limit window */
compileRateLimitWindowMs: envInt("COMPILE_RATE_LIMIT_WINDOW_MS", 60_000, {
min: 1,
max: 86_400_000,
}),
/** Compile requests allowed per trusted identity and window */
compileRateLimitMaxRequests: envInt("COMPILE_RATE_LIMIT_MAX_REQUESTS", 10, {
min: 1,
max: 10_000,
}),
/** Block duration after a trusted identity exceeds the compile limit */
compileRateLimitBlockDurationMs: envInt(
"COMPILE_RATE_LIMIT_BLOCK_DURATION_MS",
10_000,
{ min: 1, max: 86_400_000 },
),
/** Simulation start rate limit window */
simulationRateLimitWindowMs: envInt(
"SIMULATION_START_RATE_LIMIT_WINDOW_MS",
2_000,
{ min: 1, max: 86_400_000 },
),
/** Simulation starts allowed per window */
simulationRateLimitMaxRequests: envInt(
"SIMULATION_START_RATE_LIMIT_MAX_REQUESTS",
1,
{ min: 1, max: 10_000 },
),
/** Simulation start block duration after exceeding the limit */
simulationRateLimitBlockDurationMs: envInt(
"SIMULATION_START_RATE_LIMIT_BLOCK_DURATION_MS",
5_000,
{ min: 1, max: 86_400_000 },
),
/** Running plus queued simulation starts admitted by this process */
simulationAdmissionMax: envInt("SIMULATION_ADMISSION_MAX", 25, {
min: 1,
max: 500,
}),
/** Cleanup interval for inactive simulation rate-limit entries */
simulationRateLimitCleanupIntervalMs: 5 * 60 * 1000,
/** Inactive simulation rate-limit entries are removed after this duration */
simulationRateLimitInactiveTtlMs: 10 * 60 * 1000,
},
// ── Sandbox Pool ────────────────────────────────────────────────
sandbox: {
pool: {
/** Warm containers kept ready for instant allocation */
minRunners: poolMinRunners,
/** Hard upper bound on concurrent sandbox containers.
* Defaults to minRunners when SANDBOX_POOL_MAX_RUNNERS is not set (dev).
* docker-compose.yml sets this to 100 for production. */
maxRunners: poolMaxRunners,
/** Idle containers are destroyed after this duration */
idleTimeoutMs: envInt("SANDBOX_POOL_IDLE_TIMEOUT_MS", 120_000, { min: 1, max: 86_400_000 }),
/** Max time to wait for a runner before rejecting */
acquireTimeoutMs: 60_000,
/** Max time to wait while resetting a released runner */
resetTimeoutMs: 10_000,
/** Max queued acquire requests before rejecting immediately */
maxQueueSize: 500,
},
// ── Per-Container Resource Limits ───────────────────────────
resources: {
/**
* Docker --memory (and --memory-swap) limit in MB applied to every sandbox
* container. Two very different phases share this budget:
*
* • Compile phase g++/cc1plus needs 150–300 MB per invocation.
* Linux cgroup v2 (GitHub Actions / production) hard-kills the process
* the moment it exceeds the limit → must be ≥ 256 MB.
*
* • Runtime phase The pre-compiled AVR sketch typically uses < 30 MB.
* A tighter limit (e.g. 64 MB) would be safe here, but since compile
* and run happen in the same container, the compile-phase floor wins.
*
* Override with SANDBOX_MEMORY_MB. docker-compose.yml mirrors this value
* explicitly so all environments stay in sync.
*/
memoryMB: envInt("SANDBOX_MEMORY_MB", 256, { min: 64, max: 65_536 }),
/** Docker --cpus flag. 0.25 = 25% of one core. */
cpuLimit: envFloat("SANDBOX_CPU_LIMIT", "0.25"),
/** Max PIDs per container (prevents fork bombs) */
pidsLimit: 50,
/** Kill container after this many seconds */
maxExecutionTimeSec: 60,
/** Kill container if stdout/stderr exceeds this (bytes) */
maxOutputBytes: 100 * 1024 * 1024,
},
/** Docker image used for sandbox containers */
dockerImage: envStr("DOCKER_SANDBOX_IMAGE", "unosim-sandbox:latest"),
/** Docker daemon socket */
dockerHost: envStr("DOCKER_HOST", "unix:///var/run/docker.sock"),
},
// ── Compilation ─────────────────────────────────────────────────
compilation: {
/** Number of parallel compilation worker threads */
workerCount: envInt("WORKER_COUNT", defaultWorkers, { min: 1, max: 256 }),
/** Max simultaneous g++ processes inside Docker containers */
dockerCompileConcurrent: envInt("DOCKER_COMPILE_CONCURRENT", 8, { min: 1, max: 256 }),
/** Max simultaneous compile operations (gatekeeper) */
maxConcurrent: envInt(
"COMPILE_MAX_CONCURRENT",
defaultCompileMaxConcurrent,
{ min: 1, max: 256 },
),
/** Compilation timeout (ms) */
timeoutMs: 60_000,
/** Arduino Fully Qualified Board Name */
fqbn: envStr("ARDUINO_FQBN", "arduino:avr:uno"),
/** Arduino CLI core/library cache directory */
cacheDir: envStr(
"ARDUINO_CACHE_DIR",
path.join(cwd, "server/arduino-cache"),
),
/** Build artifact cache directory */
buildCacheDir: envStr("BUILD_CACHE_DIR", path.join(cwd, "storage/cache")),
/** LRU eviction trigger for build cache (bytes) */
buildCacheMaxBytes: envInt("BUILD_CACHE_MAX_BYTES", 2 * 1024 * 1024 * 1024, { min: 1, max: Number.MAX_SAFE_INTEGER }),
/** Max entries kept in the compile result cache */
resultCacheMaxEntries: 100,
/** Time-to-live for compile result cache entries */
resultCacheTtlMs: 5 * 60 * 1000,
/** Max queued compile requests in the unified gatekeeper */
gatekeeperMaxQueueSize: 500,
/** Bypass gatekeeper in E2E tests */
disableGatekeeper: envBool("DISABLE_COMPILE_GATEKEEPER", false),
},
// ── Examples ─────────────────────────────────────────────────────
examples: {
/** Server-side HTTPS base URL for a manifest/ref source. */
source: examplesSource,
/** Immutable tag or commit SHA; floating refs are development-only. */
ref: examplesRef,
/** Refresh interval for the in-memory external snapshot. */
refreshMs: envInt("UNOSIM_EXAMPLES_REFRESH_MS", 5 * 60 * 1000, { min: 1_000, max: 86_400_000 }),
/** Timeout applied to each external request. */
timeoutMs: envInt("UNOSIM_EXAMPLES_TIMEOUT_MS", 5_000, { min: 100, max: 120_000 }),
maxManifestBytes: envInt("UNOSIM_EXAMPLES_MAX_MANIFEST_BYTES", 256 * 1024, { min: 1, max: 10 * 1024 * 1024 }),
maxFileBytes: envInt("UNOSIM_EXAMPLES_MAX_FILE_BYTES", 128 * 1024, { min: 1, max: 10 * 1024 * 1024 }),
maxTotalBytes: envInt("UNOSIM_EXAMPLES_MAX_TOTAL_BYTES", 1024 * 1024, { min: 1, max: 100 * 1024 * 1024 }),
maxFiles: envInt("UNOSIM_EXAMPLES_MAX_FILES", 100, { min: 1, max: 10_000 }),
/** Exact host allowlist; required for configured production sources. */
allowedHosts: examplesAllowedHosts,
/** Only intended for local fixture tests, never production. */
allowHttp: envBool("UNOSIM_EXAMPLES_ALLOW_HTTP", false),
},
// ── Scattered Timeouts (centralized) ────────────────────────────
timeouts: {
/** Max time to wait for a compile slot from the gatekeeper */
compileGatekeeperAcquireMs: 30_000,
/** Unified gatekeeper distributed-lock TTL */
gatekeeperLockTTLMs: 60_000,
/** Interval for the gatekeeper to scan for expired locks */
gatekeeperLockCheckIntervalMs: 5_000,
/** Default timeout for generic process execution */
processExecutionDefaultMs: 20_000,
/** Default registry collection wait-mode duration */
registryWaitModeDefaultMs: 1_500,
/** Registry wait-mode duration applied after sketch start */
registryWaitModeAfterStartMs: 5_000,
/** Default tick interval for stream batchers (pin/serial) */
batcherTickIntervalMs: 50,
},
// ── Client Polling (served via GET /api/config) ─────────────────
client: {
/** /api/health ping interval */
healthPollIntervalMs: 15_000,
/** /api/status fetch interval */
statusPollIntervalMs: 60_000,
/** Suppress error toasts during startup */
startupGraceMs: 5_000,
/** Abort health/status fetch after this */
fetchTimeoutMs: 2_000,
},
};
/** Subset of config safe to expose to the browser via GET /api/config */
export function getClientConfig() {
return {
...config.client,
serverMode: config.serverMode,
simulationMode: config.simulationMode,
};
}
export type UnoSimConfig = typeof config;
/** Read the compile limit for components that support runtime test overrides. */
export function getCompileMaxConcurrent(): number {
return parseEnvInt("COMPILE_MAX_CONCURRENT", process.env.COMPILE_MAX_CONCURRENT, config.compilation.maxConcurrent, { min: 1, max: 256 });
}
|