All files / server/routes compiler.routes.ts

87.67% Statements 64/73
82.69% Branches 43/52
90% Functions 9/10
93.84% Lines 61/65

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                                                                                20x   20x 10x 10x   10x     10x       10x       7x               7x 7x                         2x 2x 2x             21x   21x 21x           21x 21x 1x 1x             1x     20x                 10x 10x 10x   2x 2x 1x 1x       17x   17x 21x 21x 21x   20x 20x 10x   10x   10x 10x 10x           10x 1x 1x 1x     9x 9x 1x   8x       21x 21x                   7x   7x 6x 6x 6x   6x     6x   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 } from "@shared/operation-errors";
 
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: (code: string | null) => void;
  logger: Logger;
  compileRateLimiter?: { checkLimit: (identity: string) => RateLimitResult };
  disableRateLimit?: boolean;
};
 
type CompileRequestData = {
  code: string;
  headers?: CompilerHeader[];
  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 };
}
 
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 {
  Iif (!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;
 
  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, fqbn, libraries } = parsedRequest.data;
 
      const codeHash = hashCode(code, headers, { fqbn, libraries });
      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)`);
        setLastCompiledCode(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,
        {
          fqbn,
          libraries,
        },
      );
 
      recordCompileMetricIfNeeded(compiler, compileStartTime, result);
 
      if (result.success) {
        Eif (!cacheDisabled) {
          compilationCache.set(codeHash, { result, timestamp: Date.now() });
          logger.info(`✅ Cached compilation result for code`);
        }
        setLastCompiledCode(code);
      }
 
      res.json(result);
    } catch (error) {
      recordCompileErrorIfNeeded(compiler, compileStartTime, error);
      logger.error(`[Compiler Route] Error during /api/compile: ${error instanceof Error ? error.message : String(error)}`);
      res.status(500).json({ error: "Compilation failed" });
    }
  });
}