All files / server/services/sandbox filesystem-helper.ts

100% Statements 58/58
87.5% Branches 28/32
100% Functions 9/9
100% Lines 56/56

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          15x                           84x     84x 84x             64x             42x             41x 41x 41x             30x 2x   2x 2x 2x 2x   1x                       57x 57x 57x 57x 57x   11x 11x           11x 11x   10x     10x                 13x 13x 13x   11x 11x 10x 1x 1x 1x   9x 9x 1x 1x   8x       11x 11x                       70x     64x 22x 22x 22x     42x 42x 12x 12x     30x 30x 29x   1x        
/**
 * FilesystemHelper: Manages temporary directory operations, cleanup, and path utilities
 * Extracted from Etappe C: Filesystem & Path Operations refactoring
 */
 
import { existsSync, renameSync, rmSync } from "node:fs";
import { Logger } from "@shared/logger";
import type { SketchFileBuilder } from "../sketch-file-builder";
import type { LocalCompiler } from "../local-compiler";
 
interface FilesystemHelperState {
  currentSketchDir: string | null;
  isCompiling: boolean;
  pendingCleanup: boolean;
  cleanupRetries: Map<string, number>;
  currentRegistryFile: string | null;
}
 
export class FilesystemHelper {
  private readonly logger = new Logger("FilesystemHelper");
 
  constructor(
    private readonly fileBuilder: SketchFileBuilder,
    private readonly localCompiler: LocalCompiler,
  ) {}
 
  /**
   * Check if compilation is currently in progress (blocks cleanup)
   */
  isCompilationInProgress(state: FilesystemHelperState): boolean {
    return state.isCompiling || this.localCompiler.isBusy;
  }
 
  /**
   * Check if a directory exists and is ready for cleanup
   */
  canCleanup(dir: string): boolean {
    return !!dir && existsSync(dir);
  }
 
  /**
   * Clear temporary directory from tracking after successful cleanup
   */
  clearTempDirTracking(state: FilesystemHelperState, dir: string): void {
    this.fileBuilder.clearCreatedSketchDir(dir);
    state.currentSketchDir = null;
    state.pendingCleanup = false;
  }
 
  /**
   * Mark a registry file for delayed cleanup
   */
  markRegistryForCleanup(state: FilesystemHelperState): void {
    if (state.currentRegistryFile && existsSync(state.currentRegistryFile)) {
      try {
        // Rename .pending.json to .cleanup.json
        const cleanupFile = state.currentRegistryFile.replaceAll(".pending.json", ".cleanup.json");
        renameSync(state.currentRegistryFile, cleanupFile);
        this.logger.debug(`Marked registry for cleanup: ${cleanupFile}`);
        state.currentRegistryFile = null;
      } catch (err) {
        this.logger.warn(
          `Failed to mark registry for cleanup: ${err instanceof Error ? err.message : String(err)}`,
        );
      }
    }
  }
 
  /**
   * Attempts to remove a directory with fallback strategies
   * Returns true if cleanup succeeded, false otherwise
   */
  attemptCleanupDir(dir: string): boolean {
    try {
      const cleanupDir = dir + ".cleanup";
      renameSync(dir, cleanupDir);
      this.logger.debug(`Marked temp directory for cleanup: ${cleanupDir}`);
      return true;
    } catch (err) {
      try {
        rmSync(dir, {
          recursive: true,
          force: true,
          maxRetries: 5,
          retryDelay: 100,
        });
        this.logger.debug(`Removed temp directory directly: ${dir}`);
        return true;
      } catch (error_) {
        this.logger.warn(
          `Failed to mark temp directory for cleanup: ${err instanceof Error ? err.message : String(err)}; remove failed: ${error_ instanceof Error ? error_.message : String(error_)}`,
        );
        return false;
      }
    }
  }
 
  /**
   * Schedule a cleanup retry with exponential backoff
   */
  scheduleCleanupRetry(state: FilesystemHelperState, dir: string): void {
    const attempts = (state.cleanupRetries.get(dir) ?? 0) + 1;
    state.cleanupRetries.set(dir, attempts);
    if (attempts > 8) return;
 
    const delayMs = Math.min(200 + attempts * 150, 2000);
    const timer = setTimeout(() => {
      if (!existsSync(dir)) {
        state.cleanupRetries.delete(dir);
        this.fileBuilder.clearCreatedSketchDir(dir);
        return;
      }
      const cleaned = this.attemptCleanupDir(dir);
      if (cleaned) {
        state.cleanupRetries.delete(dir);
        this.fileBuilder.clearCreatedSketchDir(dir);
      } else {
        this.scheduleCleanupRetry(state, dir);
      }
    }, delayMs);
 
    Eif (typeof timer.unref === "function") {
      timer.unref();
    }
  }
 
  /**
   * Attempts to remove the current sketch directory. If compilation is still
   * in progress, defers cleanup; the compile finisher will retry later.
   *
   * Defensive guard against race conditions where the linker writes the
   * executable while cleanup tries to delete the temp directory.
   */
  markTempDirForCleanup(state: FilesystemHelperState): void {
    if (!state.currentSketchDir) return;
 
    // Defer if compile is still running
    if (this.isCompilationInProgress(state)) {
      this.logger.debug("cleanup deferred until compile finishes");
      state.pendingCleanup = true;
      return;
    }
 
    const dir = state.currentSketchDir;
    if (!this.canCleanup(dir)) {
      this.clearTempDirTracking(state, dir);
      return;
    }
 
    const cleaned = this.attemptCleanupDir(dir);
    if (cleaned) {
      this.clearTempDirTracking(state, dir);
    } else {
      this.scheduleCleanupRetry(state, dir);
    }
  }
}