All files / server/services/workers compile-worker-utils.ts

97.8% Statements 89/91
91.3% Branches 21/23
95% Functions 19/20
98.83% Lines 85/86

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              2x 2x 2x           6x 10x   4x             7x       7x             15x 15x 10x   5x               4x 4x 1x   3x 3x 1x   2x                       4x   4x 9x 9x 2x 2x 2x   7x 1x       6x     1x                 7x 7x 7x 7x   7x 5x 5x 5x 5x 5x   5x 1x 1x 1x 1x 1x       5x 5x           7x                     4x 4x 4x 7x 4x 4x                       3x 3x 3x 3x 2x 1x           2x   3x 2x 2x 2x 1x             2x             5x             2x   2x 2x 2x 2x   2x 1x   2x 1x     2x 2x 1x 1x     1x 1x           2x      
/**
 * Extracted utility functions from compile-worker.ts
 *
 * These pure and I/O-only helpers are separated for testability.
 * The main compile-worker.ts thread imports them at runtime.
 */
 
import { createHash } from "node:crypto";
import { mkdir, open, readdir, rm, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
 
/**
 * Normalize and sort library names for deterministic hashing.
 */
export function normalizeLibraries(libraries?: string[]): string[] {
  return (libraries || [])
    .map((entry) => entry.trim())
    .filter(Boolean)
    .sort((a, b) => a.localeCompare(b));
}
 
/**
 * Compute a SHA-256 hash of code + FQBN for sketch identity.
 */
export function buildSketchHash(task: { code: string }, fqbn: string): string {
  const payload = JSON.stringify({
    code: task.code,
    fqbn,
  });
  return createHash("sha256").update(payload).digest("hex");
}
 
/**
 * Check whether a file exists on disk.
 */
export async function checkFileExists(filePath: string): Promise<boolean> {
  try {
    await stat(filePath);
    return true;
  } catch {
    return false;
  }
}
 
/**
 * Check whether a compiled binary (.hex or .elf) exists in the given directory.
 */
export async function checkBinaryExists(binaryDir: string, sketchHash: string): Promise<boolean> {
  try {
    await stat(join(binaryDir, `${sketchHash}.hex`));
    return true;
  } catch {
    try {
      await stat(join(binaryDir, `${sketchHash}.elf`));
      return true;
    } catch {
      return false;
    }
  }
}
 
/**
 * Acquire a file-based lock with polling and timeout.
 */
export async function acquireCoreCacheLock(
  lockPath: string,
  timeoutMs: number = 120000,
): Promise<{ acquired: boolean; waitedMs: number }> {
  const start = Date.now();
 
  while (Date.now() - start < timeoutMs) {
    try {
      const fd = await open(lockPath, "wx");
      await fd.writeFile(`${process.pid}:${new Date().toISOString()}`);
      await fd.close();
      return { acquired: true, waitedMs: Date.now() - start };
    } catch (error: any) {
      if (error?.code !== "EEXIST") {
        throw error;
      }
    }
 
    await new Promise((resolve) => setTimeout(resolve, 50));
  }
 
  return { acquired: false, waitedMs: Date.now() - start };
}
 
/**
 * Scan a directory and collect records with size and access time.
 */
export async function collectDirectoryRecords(
  targetDir: string,
): Promise<{ records: Array<{ fullPath: string; size: number; atimeMs: number }>; totalSize: number }> {
  await mkdir(targetDir, { recursive: true });
  const entries = await readdir(targetDir);
  const records: Array<{ fullPath: string; size: number; atimeMs: number }> = [];
  let totalSize = 0;
 
  for (const entry of entries) {
    const fullPath = join(targetDir, entry);
    try {
      const entryStat = await stat(fullPath);
      const atimeMs = entryStat.atimeMs || entryStat.mtimeMs;
      let size = entryStat.size;
 
      if (entryStat.isDirectory()) {
        const nested = await readdir(fullPath);
        size = 0;
        for (const nestedEntry of nested) {
          const nestedStat = await stat(join(fullPath, nestedEntry));
          size += nestedStat.size;
        }
      }
 
      totalSize += size;
      records.push({ fullPath, size, atimeMs });
    } catch {
      // ignore races with concurrent delete
    }
  }
 
  return { records, totalSize };
}
 
/**
 * Evict LRU entries from a sorted records list until total size is within budget.
 */
export async function evictLruEntries(
  records: Array<{ fullPath: string; size: number; atimeMs: number }>,
  totalSize: number,
  maxBytes: number,
): Promise<void> {
  records.sort((a, b) => a.atimeMs - b.atimeMs);
  let remaining = totalSize;
  for (const record of records) {
    if (remaining <= maxBytes) break;
    await rm(record.fullPath, { recursive: true, force: true });
    remaining -= record.size;
  }
}
 
/**
 * LRU cleanup of build cache directories, debounced via marker file.
 */
export async function cleanupCacheLru(
  buildCacheDir: string,
  targets: string[],
  maxBytes?: number,
): Promise<void> {
  const markerPath = join(buildCacheDir, ".cleanup-marker");
  const now = Date.now();
  try {
    const markerStat = await stat(markerPath);
    if (now - markerStat.mtimeMs < 60_000) {
      return;
    }
  } catch {
    // continue cleanup if marker doesn't exist
  }
 
  const effectiveMax = maxBytes ?? Number(process.env.BUILD_CACHE_MAX_BYTES || 2 * 1024 * 1024 * 1024);
 
  for (const targetDir of targets) {
    try {
      const { records, totalSize } = await collectDirectoryRecords(targetDir);
      if (totalSize > effectiveMax) {
        await evictLruEntries(records, totalSize, effectiveMax);
      }
    } catch {
      // skip directories that cannot be read
    }
  }
 
  await writeFile(markerPath, String(now));
}
 
/**
 * Create multiple directories in parallel.
 */
export async function ensureDirectories(dirs: string[]): Promise<void> {
  await Promise.all(dirs.map((dir) => mkdir(dir, { recursive: true })));
}
 
/**
 * Spawn arduino-cli with JSON output and return parsed result.
 */
export async function execArduinoCliJson(args: string[]): Promise<any> {
  const { spawn } = await import("node:child_process");
 
  return new Promise((resolve) => {
    const proc = spawn("arduino-cli", args);
    let stdout = "";
    let _stderr = "";
 
    proc.stdout?.on("data", (data: Buffer) => {
      stdout += data.toString();
    });
    proc.stderr?.on("data", (data: Buffer) => {
      _stderr += data.toString();
    });
 
    proc.on("close", (code: number | null) => {
      if (code !== 0) {
        resolve(null);
        return;
      }
 
      try {
        resolve(stdout ? JSON.parse(stdout) : null);
      } catch {
        resolve(null);
      }
    });
 
    proc.on("error", () => resolve(null));
  });
}