All files / server/services/compiler cache-manager.ts

97.26% Statements 71/73
88.23% Branches 15/17
81.81% Functions 9/11
100% Lines 66/66

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        15x                                           80x 80x 80x 157x 157x 4x 4x 4x         76x                     28x 28x 28x 28x 28x                     55x 55x                   9x 9x 9x   2x                       76x 76x 76x 2x 2x 2x   74x                       27x 27x 27x 27x 27x                   57x 57x 56x 56x   56x 1104x 555x 555x 555x 555x 554x 554x                     56x   7x 5x 10x 6x   6x 6x     1x                           80x 80x 4x 4x 4x 4x       76x 76x 2x 2x 2x 2x     74x    
import { readFile, writeFile, rename, mkdir, readdir, stat, rm, utimes } from "node:fs/promises";
import { join } from "node:path";
import { Logger } from "@shared/logger";
 
const logger = new Logger("CacheManager");
 
export interface CacheHitResult {
  cached: boolean;
  binary: Buffer | null;
  cacheType: "instant" | "hex" | "none";
  cachedOutput: string | null;
}
 
export interface CachePaths {
  binaryStorageDir: string;
  hexCacheDir: string;
}
 
/**
 * Reads binary from storage (tries .hex and .elf extensions).
 * Updates access time on hit.
 */
export async function readBinaryFromStorage(
  sketchHash: string,
  storageDir: string,
): Promise<Buffer | null> {
  const hexPath = join(storageDir, `${sketchHash}.hex`);
  const elfPath = join(storageDir, `${sketchHash}.elf`);
  for (const path of [hexPath, elfPath]) {
    try {
      const binary = await readFile(path);
      const now = new Date();
      await utimes(path, now, now).catch(() => undefined);
      return binary;
    } catch {
      // continue probing next extension
    }
  }
  return null;
}
 
/**
 * Writes binary to storage using atomic rename pattern.
 */
export async function writeBinaryToStorage(
  sketchHash: string,
  binary: Buffer,
  storageDir: string,
): Promise<void> {
  const targetPath = join(storageDir, `${sketchHash}.hex`);
  const tmpPath = `${targetPath}.tmp-${process.pid}-${Date.now()}`;
  await mkdir(storageDir, { recursive: true });
  await writeFile(tmpPath, binary);
  await rename(tmpPath, targetPath);
}
 
/**
 * Writes output text to cache.
 */
export async function writeOutputToCache(
  storageDir: string,
  sketchHash: string,
  output: string,
): Promise<void> {
  const outputPath = join(storageDir, `${sketchHash}.output.txt`);
  await writeFile(outputPath, output, "utf8");
}
 
/**
 * Reads output text from cache.
 */
export async function readOutputFromCache(
  storageDir: string,
  sketchHash: string,
): Promise<string | null> {
  const outputPath = join(storageDir, `${sketchHash}.output.txt`);
  try {
    return await readFile(outputPath, "utf8");
  } catch {
    return null;
  }
}
 
/**
 * Reads HEX binary from cache.
 * Updates access time on hit.
 */
export async function readHexFromCache(
  sketchHash: string,
  hexCacheDir: string,
): Promise<Buffer | null> {
  const cachePath = join(hexCacheDir, `${sketchHash}.hex`);
  try {
    const binary = await readFile(cachePath);
    const now = new Date();
    await utimes(cachePath, now, now).catch(() => undefined);
    return binary;
  } catch {
    return null;
  }
}
 
/**
 * Writes HEX binary to cache using atomic rename pattern.
 */
export async function writeHexToCache(
  sketchHash: string,
  hexCacheDir: string,
  binary: Buffer,
): Promise<void> {
  const cachePath = join(hexCacheDir, `${sketchHash}.hex`);
  const tmpPath = `${cachePath}.tmp-${process.pid}-${Date.now()}`;
  await mkdir(hexCacheDir, { recursive: true });
  await writeFile(tmpPath, binary);
  await rename(tmpPath, cachePath);
}
 
/**
 * LRU-style cleanup of hex cache to stay under maxBytes.
 */
export async function runHexCacheCleanup(
  hexCacheDir: string,
  maxBytes: number = 512 * 1024 * 1024,
): Promise<void> {
  try {
    const entries = await readdir(hexCacheDir);
    const files: Array<{ path: string; sidecarPath: string; size: number; atimeMs: number }> = [];
    let totalSize = 0;
 
    for (const entry of entries) {
      if (!entry.endsWith(".hex")) continue;
      const fullPath = join(hexCacheDir, entry);
      try {
        const fileStat = await stat(fullPath);
        if (!fileStat.isFile()) continue;
        totalSize += fileStat.size;
        files.push({
          path: fullPath,
          sidecarPath: join(hexCacheDir, `${entry.slice(0, -".hex".length)}.output.txt`),
          size: fileStat.size,
          atimeMs: fileStat.atimeMs || fileStat.mtimeMs,
        });
      } catch {
        // ignore disappearing files
      }
    }
 
    if (totalSize <= maxBytes) return;
 
    files.sort((a, b) => a.atimeMs - b.atimeMs);
    for (const file of files) {
      if (totalSize <= maxBytes) break;
      await rm(file.path, { force: true });
      // The output sidecar is useless without its binary and must not outlive it.
      await rm(file.sidecarPath, { force: true });
      totalSize -= file.size;
    }
  } catch (error) {
    logger.debug(`[CacheCleanup] skipped: ${error instanceof Error ? error.message : String(error)}`);
  }
}
 
/**
 * Checks both instant binary cache and hex cache for a compiled sketch.
 * Returns cache hit info including output sidecar.
 */
export async function checkCacheHits(
  sketchHash: string,
  paths: CachePaths,
  compileStartedAt: bigint,
): Promise<CacheHitResult> {
  // Check instant binary cache first (most recent)
  const instantBinary = await readBinaryFromStorage(sketchHash, paths.binaryStorageDir);
  if (instantBinary) {
    const elapsedMs = Number((process.hrtime.bigint() - compileStartedAt) / BigInt(1_000_000));
    logger.info(`[Cache] Hit for hash ${sketchHash} (${elapsedMs}ms)`);
    const cachedOutput = await readOutputFromCache(paths.binaryStorageDir, sketchHash);
    return { cached: true, binary: instantBinary, cacheType: "instant", cachedOutput };
  }
 
  // Check hex cache (persistent, shared across sessions)
  const cachedBinary = await readHexFromCache(sketchHash, paths.hexCacheDir);
  if (cachedBinary) {
    const elapsedMs = Number((process.hrtime.bigint() - compileStartedAt) / BigInt(1_000_000));
    logger.info(`[Cache] Hit for hash ${sketchHash} (${elapsedMs}ms)`);
    const cachedOutput = await readOutputFromCache(paths.hexCacheDir, sketchHash);
    return { cached: true, binary: cachedBinary, cacheType: "hex", cachedOutput };
  }
 
  return { cached: false, binary: null, cacheType: "none", cachedOutput: null };
}