All files / server/services/sandbox stream-handler.ts

97.5% Statements 39/40
93.75% Branches 30/32
100% Functions 5/5
100% Lines 37/37

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                                                                95x   95x                       6x 2x 4x   3x                 8x             1x 1x 1x       8x 7x 1x   1x                         100013x   2x 2x     2x 2x     1x 1x     1x 1x 1x     1x 1x     1x 1x     2x 2x       1x     100002x 100002x                 100002x 100002x 100002x 99800x      
/**
 * StreamHandler: Manages I/O stream processing, pin state changes, and backpressure
 * Extracted from Etappe B: I/O Streams & Buffer Handling refactoring
 */
 
import type { IProcessController } from "../process-controller";
import type { PinStateBatcher } from "../pin-state-batcher";
import type { SerialOutputBatcher } from "../serial-output-batcher";
import type { RegistryManager } from "../registry-manager";
import type { ParsedStderrOutput } from "../arduino-output-parser";
import { Logger } from "@shared/logger";
import { RUNTIME_TEXT_LIMIT_NOTICE, type RuntimeTextLimiter } from "./runtime-text-limiter";
import type { PinStateChange } from "@shared/types/arduino.types";
 
interface StreamHandlerCallbacks {
  onPinState?: (pin: number, type: PinStateChange, value: number) => void;
  onOutput?: (line: string, isComplete?: boolean) => void;
  onError?: (line: string) => void;
}
 
interface StreamHandlerState {
  pinStateBatcher: PinStateBatcher | null;
  serialOutputBatcher: SerialOutputBatcher | null;
  backpressurePaused: boolean;
  isPaused: boolean;
  baudrate: number;
  registryManager: RegistryManager;
  /** Budget of the current run for runtime text lines; absent means unbounded. */
  runtimeTextLimiter?: Pick<RuntimeTextLimiter, "admit">;
}
 
export class StreamHandler {
  private readonly logger = new Logger("StreamHandler");
 
  constructor(private readonly processController: IProcessController) {}
 
  /**
   * Handle pin state changes (mode, value, pwm) with optional batcher or fallback
   */
  handlePinStateChange(
    pin: number,
    type: PinStateChange,
    value: number,
    state: StreamHandlerState,
    callbacks: StreamHandlerCallbacks,
  ): void {
    if (state.pinStateBatcher) {
      state.pinStateBatcher.enqueue(pin, type, value);
    } else if (callbacks.onPinState) {
      // Fallback if batcher not initialized
      callbacks.onPinState(pin, type, value);
    }
  }
 
  /**
   * Handle serial output event with backpressure management
   */
  handleSerialEvent(data: string, state: StreamHandlerState, callbacks: StreamHandlerCallbacks): void {
    // Check backpressure: if batcher exists and overloaded, pause child process
    if (
      state.serialOutputBatcher &&
      !state.backpressurePaused &&
      !state.isPaused &&
      state.baudrate > 300 && // don't throttle at very low baudrate
      state.serialOutputBatcher.isOverloaded()
    ) {
      this.logger.info("Backpressure: buffer overloaded, sending SIGSTOP");
      this.processController.kill("SIGSTOP");
      state.backpressurePaused = true;
    }
 
    // Route through SerialOutputBatcher for rate limiting
    if (state.serialOutputBatcher) {
      state.serialOutputBatcher.enqueue(data);
    } else Eif (callbacks.onOutput) {
      // Fallback if batcher not initialized
      callbacks.onOutput(data, true);
    }
  }
 
  /**
   * Handle a parsed line from stderr/stdout
   * Dispatches to appropriate handler based on message type
   */
  handleParsedLine(
    parsed: ParsedStderrOutput,
    state: StreamHandlerState,
    callbacks: StreamHandlerCallbacks,
  ): void {
    switch (parsed.type) {
      case "registry_start":
        state.registryManager.startCollection();
        break;
 
      case "registry_end":
        state.registryManager.finishCollection();
        break;
 
      case "registry_pin":
        state.registryManager.addPin(parsed.pinRecord);
        break;
 
      case "pin_mode":
        state.registryManager.updatePinMode(parsed.pin, parsed.mode);
        this.handlePinStateChange(parsed.pin, "mode", parsed.mode, state, callbacks);
        break;
 
      case "pin_value":
        this.handlePinStateChange(parsed.pin, "value", parsed.value, state, callbacks);
        break;
 
      case "pin_pwm":
        this.handlePinStateChange(parsed.pin, "pwm", parsed.value, state, callbacks);
        break;
 
      case "serial_event":
        this.handleSerialEvent(parsed.data, state, callbacks);
        break;
 
      case "ignored":
        // Debug markers - do nothing
        break;
 
      case "text":
        this.handleRuntimeText(parsed.line, state, callbacks);
        break;
    }
  }
 
  /**
   * Runtime text is sketch-controlled. The run's limiter bounds what reaches the
   * client; nothing is logged per line (the limiter logs drops aggregated).
   */
  private handleRuntimeText(line: string, state: StreamHandlerState, callbacks: StreamHandlerCallbacks): void {
    Iif (!callbacks.onError) return;
    const decision = state.runtimeTextLimiter?.admit() ?? "forward";
    if (decision === "forward") callbacks.onError(line);
    else if (decision === "notice") callbacks.onError(RUNTIME_TEXT_LIMIT_NOTICE);
  }
}