All files / server/services/sandbox/execution-phases cleanup-phase.ts

100% Statements 21/21
100% Branches 20/20
100% Functions 3/3
100% Lines 21/21

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                                      11x 6x     5x 5x   5x 10x 3x 7x 3x 4x 3x                 8x 6x   8x 6x                     14x 5x     9x 9x       7x   2x      
// execution-phases/cleanup-phase.ts
// Verantwortlichkeit: Cleanup nach Ausführung
// - Batchers flushen und stoppen
// - Message Queue leeren
// - Docker-Container cleanup
 
import type { Logger } from "@shared/logger";
import type { ProcessExecution } from "../../process-execution-port";
import type { ExecutionState } from "../execution-manager";
 
export interface CleanupDependencies {
  processExecutor: ProcessExecution;
  logger: Logger;
}
 
/**
 * Flush die Message Queue und sendet alle queued Messages an Callbacks
 */
export function flushMessageQueue(state: ExecutionState): void {
  if (state.messageQueue.length === 0) {
    return;
  }
 
  const queue = state.messageQueue;
  state.messageQueue = [];
 
  for (const msg of queue) {
    if (msg.type === "pinState" && state.pinStateCallback) {
      state.pinStateCallback(msg.data.pin, msg.data.stateType, msg.data.value);
    } else if (msg.type === "output" && state.onOutputCallback) {
      state.onOutputCallback(msg.data.line, msg.data.isComplete);
    } else if (msg.type === "error" && state.errorCallback) {
      state.errorCallback(msg.data.line);
    }
  }
}
 
/**
 * Stoppt Batchers (SerialOutputBatcher und PinStateBatcher)
 */
export function flushBatchers(state: ExecutionState): void {
  if (state.serialOutputBatcher) {
    state.serialOutputBatcher.stop();
  }
  if (state.pinStateBatcher) {
    state.pinStateBatcher.stop();
  }
}
 
/**
 * Räumt Docker-Container auf
 */
export async function cleanupDockerContainer(
  containerName: string | undefined,
  deps: CleanupDependencies,
): Promise<void> {
  if (!containerName) {
    return;
  }
 
  try {
    await deps.processExecutor.execute("docker", ["rm", "-f", containerName], {
      timeout: 5000,
      stdio: "pipe",
    });
    deps.logger.info(`Docker container cleanup: ${containerName}`);
  } catch (error) {
    deps.logger.debug(`Docker cleanup failed for ${containerName}: ${error}`);
  }
}