All files / server/services serial-output-batcher.ts

92.13% Statements 82/89
82.14% Branches 23/28
91.66% Functions 11/12
93.02% Lines 80/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 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287                                                                                  86x 86x     86x 86x 86x 86x     86x     86x 86x           86x         86x     86x     86x             86x               86x 86x 86x                     86x 86x 86x 86x                           1368x     1367x 1367x   1367x     1367x             1367x               103x 3807x             35x 35x 35x       35x 14x 14x 14x 14x               21x 21x 21x               17x             84x 84x 43x 43x   84x                             80x                 80x 80x 80x 80x   80x                               3807x 3807x 3807x 3807x 3807x 3807x         3807x 3583x       224x   224x   185x 185x 185x 185x 185x 185x       39x 39x     39x 39x     1x 1x 1x     39x 24x 24x 24x       39x        
/**
 * Serial Output Batcher
 * 
 * Batches serial output with baudrate-based rate limiting to prevent overwhelming
 * the WebSocket connection and simulate realistic Arduino serial behavior.
 * 
 * Key features:
 * - Tick-based batching (default 50ms = 20 batches/sec, like PinStateBatcher)
 * - Baudrate-based byte budget per tick
 * - "Tail wins" drop strategy (newest data is kept when budget exceeded)
 * - Burst tolerance for short spikes (e.g., setup() output)
 * - Telemetry tracking (intended/actual/dropped bytes)
 * - Newline-aware cutting (prefer line boundaries)
 */
 
export interface SerialOutputBatcherConfig {
  /** Baudrate in bits per second (e.g., 115200) */
  baudrate: number;
  /** Tick interval in milliseconds (default: 50ms = 20 batches/sec) */
  tickIntervalMs?: number;
  /** Callback invoked with each batch. firstLineIncomplete=true if this chunk starts with a truncated line (due to drops). */
  onChunk: (data: string, firstLineIncomplete?: boolean) => void;
  /** Burst factor (default: 3 = 3× normal budget for short spikes) */
  burstFactor?: number;
}
 
export interface SerialOutputTelemetry {
  /** Total bytes intended to send since last reset */
  intended: number;
  /** Total bytes actually sent since last reset */
  actual: number;
  /** Total bytes dropped since last reset */
  dropped: number;
  /** Number of chunks sent since last reset */
  chunks: number;
  /** Cumulative bytes intended since batcher start (never resets) */
  totalBytes: number;
}
 
export class SerialOutputBatcher {
  private config: Required<SerialOutputBatcherConfig>;
  private pendingData = "";
  private tickTimer: NodeJS.Timeout | null = null;
  
  // Telemetry counters (reset periodically)
  private intendedBytes = 0;
  private actualBytes = 0;
  private droppedBytes = 0;
  private chunks = 0;
  
  // Total bytes counter (never reset, accumulates over lifetime)
  private totalBytes = 0;
  
  // Burst budget tracking
  private currentBudget = 0;
  private maxBudget = 0;
  
  // Fractional byte accumulator for low baudrates
  // At baud=1: normalBudget per tick = 0.005 bytes, which rounds to 0.
  // The accumulator carries over the fractional part so that after 200 ticks
  // (10 seconds), 1 byte gets through — correctly simulating 0.1 bytes/s.
  private budgetAccumulator = 0;
  
  // Maximum queue size before applying FIFO drops (for memory safety)
  // This prevents unbounded buffering in pathological cases (e.g., data arriving
  // much faster than baudrate allows). Typical value: 100KB.
  private readonly MAX_QUEUE_BYTES = 100_000;
  
  // Flag to prevent enqueue after destroy
  private destroyed = false;
  
  constructor(config: SerialOutputBatcherConfig) {
    this.config = {
      baudrate: config.baudrate,
      tickIntervalMs: config.tickIntervalMs ?? 50,
      onChunk: config.onChunk,
      burstFactor: config.burstFactor ?? 3,
    };
    
    this.updateBudget();
  }
  
  /**
   * Calculate and update byte budget based on baudrate
   */
  private updateBudget(): void {
    // Byte budget per tick = (baudrate / 10 bits per byte) × (tick interval in seconds)
    const bytesPerSecond = this.config.baudrate / 10;
    const bytesPerTick = bytesPerSecond * (this.config.tickIntervalMs / 1000);
    const burstBudget = bytesPerTick * this.config.burstFactor;
    
    // maxBudget: determines initial burst capacity and max accumulation.
    // For high bauds (≥ ~3333): burstBudget (3 × bytesPerTick) dominates naturally.
    // For low bauds (< 3333): a proportional floor ensures typical println() works.
    //   - The floor = min(50, ceil(bytesPerSecond × 0.5)) = "half a second of output, max 50"
    //   - At 300 baud: floor = min(50, 15) = 15 → covers "Hello World!\n" (14 bytes)
    //   - At 1200 baud: floor = min(50, 60) = 50 → same as old MIN_BUDGET
    //   - At baud=1: floor = min(50, 1) = 1 → nearly nothing (correct for 0.1 bytes/s)
    // The old hardcoded MIN_BUDGET=50 gave baud=1 a 50-byte free pass, defeating rate limiting.
    // This proportional approach fixes that while preserving setup() burst for standard bauds.
    const proportionalFloor = Math.min(50, Math.ceil(bytesPerSecond * 0.5));
    this.maxBudget = Math.max(1, Math.floor(burstBudget), proportionalFloor);
    this.currentBudget = this.maxBudget; // Start with full burst budget
    this.budgetAccumulator = 0;
  }
  
  /**
   * Enqueue data for batching
   * 
   * If queue size would exceed MAX_QUEUE_BYTES (memory safety limit),
   * drop oldest bytes using FIFO strategy (not "tail wins").
   * 
   * NOTE: We count ALL enqueued data as "intended" - even if it will later be dropped.
   * The telemetry semantic is: actual + dropped = intended
   */
  enqueue(data: string): void {
    // After destroy(), enqueue is a no-op
    if (this.destroyed) return;
    
    // Count as intended (part of telemetry accounting)
    this.intendedBytes += data.length;
    this.totalBytes += data.length;
    
    const newData = this.pendingData + data;
    
    // Check if we would exceed maximum queue size
    Iif (newData.length > this.MAX_QUEUE_BYTES) {
      const overflow = newData.length - this.MAX_QUEUE_BYTES;
      // FIFO: Drop oldest bytes (from the beginning)
      const dropped = overflow;
      this.droppedBytes += dropped;
      this.pendingData = newData.slice(overflow);
    } else {
      this.pendingData = newData;
    }
  }
  
  /**
   * Start the tick timer
   */
  start(): void {
    Iif (this.tickTimer) return;
    this.tickTimer = setInterval(() => this.tick(), this.config.tickIntervalMs);
  }
  
  /**
   * Stop the timer and flush remaining data (without limit)
   */
  stop(): void {
    Eif (this.tickTimer) {
      clearInterval(this.tickTimer);
      this.tickTimer = null;
    }
    
    // Flush all remaining data without budget limit
    if (this.pendingData.length > 0) {
      this.config.onChunk(this.pendingData);
      this.actualBytes += this.pendingData.length;
      this.chunks++;
      this.pendingData = "";
    }
  }
  
  /**
   * Pause the timer (keeps pending data)
   */
  pause(): void {
    Eif (this.tickTimer) {
      clearInterval(this.tickTimer);
      this.tickTimer = null;
    }
  }
  
  /**
   * Resume the timer
   */
  resume(): void {
    this.start();
  }
  
  /**
   * Destroy the batcher (stop timer, discard data, no callbacks)
   */
  destroy(): void {
    this.destroyed = true;
    if (this.tickTimer) {
      clearInterval(this.tickTimer);
      this.tickTimer = null;
    }
    this.pendingData = "";
  }
  
  /**
   * Change baudrate and recalculate budget
   */
  setBaudrate(baudrate: number): void {
    this.config.baudrate = baudrate;
    this.updateBudget();
  }
  
  /**
   * Get telemetry and reset counters (except totalBytes)
   */
  getTelemetryAndReset(): SerialOutputTelemetry {
    const telemetry: SerialOutputTelemetry = {
      intended: this.intendedBytes,
      actual: this.actualBytes,
      dropped: this.droppedBytes,
      chunks: this.chunks,
      totalBytes: this.totalBytes,
    };
    
    // Reset periodic counters
    this.intendedBytes = 0;
    this.actualBytes = 0;
    this.droppedBytes = 0;
    this.chunks = 0;
    
    return telemetry;
  }
  
  /**
   * Tick handler: process pending data with budget limit
   * 
   * STRATEGY: No data is dropped. Instead, data is buffered and will be sent
   * as the baudrate allows. This is correct for serial data where FIFO order matters
   * and completeness is more important than timing.
   * 
   * If bandwidth is insufficient for the data rate, output will be delayed but complete.
   */
  private tick(): void {
    // Token bucket replenishment with fractional byte accumulation.
    // At low baudrates, bytesPerTick < 1 (e.g., baud=1 → 0.005 bytes/tick).
    // We accumulate the fractional part and only grant whole bytes.
    const bytesPerSecond = this.config.baudrate / 10;
    const rawBytesPerTick = bytesPerSecond * (this.config.tickIntervalMs / 1000);
    this.budgetAccumulator += rawBytesPerTick;
    const wholeBytesToAdd = Math.floor(this.budgetAccumulator);
    this.budgetAccumulator -= wholeBytesToAdd;
    this.currentBudget = Math.min(
      this.currentBudget + wholeBytesToAdd,
      this.maxBudget
    );
    
    if (this.pendingData.length === 0) {
      return;
    }
    
    // Use current accumulated budget (can be up to maxBudget for bursts)
    const budget = this.currentBudget;
    
    if (this.pendingData.length <= budget) {
      // All data fits in budget
      const bytesToSend = this.pendingData.length;
      this.config.onChunk(this.pendingData, false); // no truncation
      this.actualBytes += bytesToSend;
      this.currentBudget -= bytesToSend;
      this.pendingData = "";
      this.chunks++;
    } else {
      // Data exceeds budget: send what fits, keep rest in buffer for next tick
      // NO DROPS - just FIFO: send first N bytes that fit in budget
      let dataToSend = this.pendingData.slice(0, budget);
      this.pendingData = this.pendingData.slice(budget);
      
      // Try to cut at newline boundary to avoid sending truncated lines
      const lastNewlineIndex = dataToSend.lastIndexOf("\n");
      if (lastNewlineIndex !== -1 && lastNewlineIndex < dataToSend.length - 1) {
        // There's a newline within budget-range (not at very end)
        // Keep everything up to and including that newline, requeue the rest
        const toRequeue = dataToSend.slice(lastNewlineIndex + 1);
        dataToSend = dataToSend.slice(0, lastNewlineIndex + 1);
        this.pendingData = toRequeue + this.pendingData;
      }
      
      if (dataToSend.length > 0) {
        this.config.onChunk(dataToSend, false); // data is complete, not truncated
        this.actualBytes += dataToSend.length;
        this.chunks++;
      }
      
      // Deduct what we sent from budget
      this.currentBudget = Math.max(0, this.currentBudget - dataToSend.length);
    }
  }
}