All files / server/routes compiler.routes.ts

90.69% Statements 78/86
85.71% Branches 48/56
91.66% Functions 11/12
94.8% Lines 73/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                                                                                      33x   33x 18x 18x   18x     15x       15x         9x 9x       10x               10x 10x                         2x 2x 2x             34x   30x 30x           30x 30x 1x 1x             1x     29x                 15x 15x 15x   3x 3x 1x 1x       24x 24x 11x 11x     24x 34x 34x 34x   33x 33x 18x   15x   15x         34x 34x 34x           34x 2x 2x 2x     13x 13x 1x   12x       34x 34x             10x   10x 10x 9x 9x 9x   9x     9x   3x 1x 1x 1x 1x   2x 2x 2x        
import type { Express, Response } from "express";
import type { CompilationResult, CompileRequestOptions } from "../services/arduino-compiler";
import type { Logger } from "@shared/logger";
import { compileRequestSchema } from "@shared/schema";
import { TEST_RUN_ID_PATTERN } from "@shared/input-limits";
import { resolvePathWithinRoot } from "../security/safe-paths";
import { compileMetricsTracker } from "../services/server-metrics";
import path from "node:path";
import type { RequestIdentity } from "../security/access-control";
import type { RateLimitResult } from "../services/rate-limiter";
import { operationError, SYSTEM_BUSY_MESSAGE } from "@shared/operation-errors";
import { CompileCapacityError } from "../services/compilation-worker-pool";
import { safeErrorLogMetadata } from "../services/safe-error-log-metadata";
 
type CompilerHeader = { name: string; content: string };
 
type CompilerDeps = {
  compiler: {
    compile: (code: string, headers?: CompilerHeader[], tempRoot?: string, options?: CompileRequestOptions) => Promise<CompilationResult>;
    tracksCompileMetrics?: boolean;
  };
  compilationCache: Map<string, { result: CompilationResult; timestamp: number }>;
  hashCode: (code: string, headers?: CompilerHeader[], options?: CompileRequestOptions) => string;
  CACHE_TTL: number;
  setLastCompiledCode: (subject: string, code: string) => void;
  logger: Logger;
  compileRateLimiter?: { checkLimit: (identity: string) => RateLimitResult };
  disableRateLimit?: boolean;
};
 
type CompileRequestData = {
  code: string;
  headers?: CompilerHeader[];
  entryFile?: string;
  fqbn?: string;
  libraries?: string[];
};
 
type ParsedCompileRequest =
  | { success: true; data: CompileRequestData }
  | { success: false; error: string };
 
function parseCompileRequest(body: unknown): ParsedCompileRequest {
  const parsedRequest = compileRequestSchema.safeParse(body);
 
  if (!parsedRequest.success) {
    const codeMissing = parsedRequest.error.issues.some(
      (issue) => issue.path[0] === "code" && issue.code === "invalid_type",
    );
    return { success: false, error: codeMissing ? "Code is required" : "Invalid compile request" };
  }
 
  Iif (!parsedRequest.data.code) {
    return { success: false, error: "Code is required" };
  }
 
  return { success: true, data: parsedRequest.data };
}
 
/** The HEX stays on the server: the client never uses it and it inflates every response. */
function withoutBinary(result: CompilationResult): CompilationResult {
  const { binary: _binary, ...clientResult } = result;
  return clientResult;
}
 
function isTimedOutCompileResult(result: CompilationResult): boolean {
  return !result.success && `${result.stderr ?? ""} ${result.errors.map((err) => err.message).join(" ")}`.toLowerCase().includes("timeout");
}
 
function recordCompileMetricIfNeeded(
  compiler: CompilerDeps["compiler"],
  compileStartTime: number,
  result: CompilationResult,
): void {
  Iif (compiler.tracksCompileMetrics === true) return;
  compileMetricsTracker.recordCompileComplete(
    compileStartTime,
    0,
    result.success,
    isTimedOutCompileResult(result),
  );
}
 
function recordCompileErrorIfNeeded(
  compiler: CompilerDeps["compiler"],
  compileStartTime: number | null,
  error: unknown,
): void {
  Iif (compileStartTime === null || compiler.tracksCompileMetrics === true) return;
  const message = error instanceof Error ? error.message : String(error);
  compileMetricsTracker.recordCompileComplete(compileStartTime, 0, false, message.toLowerCase().includes("timeout"));
}
 
function enforceCompileRateLimit(
  res: Response,
  deps: CompilerDeps,
): boolean {
  if (!deps.compileRateLimiter || deps.disableRateLimit) return true;
 
  const identity = res.locals.unosimIdentity as RequestIdentity | undefined;
  Iif (!identity) {
    deps.logger.error("[Compiler Route] Missing trusted request identity");
    res.status(500).json({ error: "Compilation failed" });
    return false;
  }
 
  const limit = deps.compileRateLimiter.checkLimit(identity.subject);
  if (!limit.allowed) {
    res.setHeader("Retry-After", String(limit.retryAfter));
    res.status(429).json({
      error: operationError(
        "RATE_LIMITED",
        "Compile rate limit exceeded. Please try again later.",
        limit.retryAfter,
      ),
    });
    return false;
  }
 
  return true;
}
 
function getCachedCompilation(
  compilationCache: CompilerDeps["compilationCache"],
  codeHash: string,
  cacheTtl: number,
  cacheDisabled: boolean,
): { result: CompilationResult; ageMs: number } | null {
  Iif (cacheDisabled) return null;
  const cachedEntry = compilationCache.get(codeHash);
  if (!cachedEntry) return null;
 
  const ageMs = Date.now() - cachedEntry.timestamp;
  if (ageMs < cacheTtl) return { result: cachedEntry.result, ageMs };
  compilationCache.delete(codeHash);
  return null;
}
 
export function registerCompilerRoutes(app: Express, deps: CompilerDeps) {
  const { compiler, compilationCache, hashCode, CACHE_TTL, setLastCompiledCode, logger } = deps;
  const rememberCompiledCode = (res: Response, code: string) => {
    const identity = res.locals.unosimIdentity as RequestIdentity | undefined;
    Eif (identity) setLastCompiledCode(identity.subject, code);
  };
 
  app.post("/api/compile", async (req, res) => {
    let compileStartTime: number | null = null;
    try {
      if (!enforceCompileRateLimit(res, deps)) return;
 
      const parsedRequest = parseCompileRequest(req.body);
      if (!parsedRequest.success) {
        return res.status(400).json({ error: parsedRequest.error });
      }
      const { code, headers, entryFile, fqbn, libraries } = parsedRequest.data;
 
      const compileOptions = {
        fqbn,
        libraries,
        ...(entryFile ? { entryFile } : {}),
      };
      const codeHash = hashCode(code, headers, compileOptions);
      const cacheDisabled = process.env.DISABLE_COMPILE_CACHE === "true";
      const cachedResult = getCachedCompilation(
        compilationCache,
        codeHash,
        CACHE_TTL,
        cacheDisabled,
      );
      if (cachedResult) {
        logger.info(`✅ Cache hit for code (age: ${cachedResult.ageMs}ms)`);
        rememberCompiledCode(res, code);
        return res.json({ ...cachedResult.result, cached: true });
      }
 
      const testRunIdHeader = req.header("x-test-run-id");
      if (testRunIdHeader !== undefined && !TEST_RUN_ID_PATTERN.test(testRunIdHeader)) {
        return res.status(400).json({ error: "Invalid test run ID" });
      }
      const compileTempRoot = testRunIdHeader
        ? resolvePathWithinRoot(path.join(process.cwd(), "temp"), testRunIdHeader)
        : undefined;
 
      compileStartTime = Date.now();
      const result: CompilationResult = await compiler.compile(
        code,
        headers,
        compileTempRoot,
        compileOptions,
      );
 
      recordCompileMetricIfNeeded(compiler, compileStartTime, result);
 
      const clientResult = withoutBinary(result);
      if (result.success) {
        Eif (!cacheDisabled) {
          compilationCache.set(codeHash, { result: clientResult, timestamp: Date.now() });
          logger.info(`✅ Cached compilation result for code`);
        }
        rememberCompiledCode(res, code);
      }
 
      res.json(clientResult);
    } catch (error) {
      if (error instanceof CompileCapacityError) {
        const retryAfter = 5;
        logger.warn(`[Compiler Route] Compile capacity exhausted: ${error.message}`);
        res.setHeader("Retry-After", String(retryAfter));
        return res.status(503).json({ error: operationError("SYSTEM_BUSY", SYSTEM_BUSY_MESSAGE, retryAfter) });
      }
      recordCompileErrorIfNeeded(compiler, compileStartTime, error);
      logger.error(`[Compiler Route] Error during /api/compile (${safeErrorLogMetadata(error)})`);
      res.status(500).json({ error: "Compilation failed" });
    }
  });
}