All files / server/services pin-state-batcher.ts

97.36% Statements 37/38
75% Branches 9/12
100% Functions 11/11
97.29% Lines 36/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 142 143 144 145 146 147 148 149 150 151 152 153                                                                        54x 54x 54x 54x 54x     54x                     6656x 6656x 6656x             50x     4993x             21x 21x 21x     21x             1x 1x 1x                 1x             332x         332x 332x 332x 332x             41x 20x 20x   41x             4993x             5014x 4924x     90x 90x 90x   90x         90x      
/**
 * Pin State Batching Layer
 *
 * Batches high-frequency pin state changes into lower-frequency batches
 * to reduce WebSocket message overhead (2000 msg/sec → 20 msg/sec).
 *
 * Key Features:
 * - Tick-based batching (default 50ms = 20 batches/sec)
 * - "Last value wins" deduplication per pin:stateType
 * - Telemetry tracking (intended vs actual pin changes)
 * - Pause/Resume support
 * - Flush on stop
 */
 
import type { PinStateChange } from "@shared/types/arduino.types";
 
export interface PinStateEvent {
  pin: number;
  stateType: PinStateChange;
  value: number;
}
 
export interface PinStateBatch {
  states: PinStateEvent[];
  timestamp: number;
}
 
interface PinStateBatcherConfig {
  /** Tick interval in milliseconds (default: 50ms = 20 batches/sec) */
  tickIntervalMs?: number;
  /** Callback invoked with each batch */
  onBatch: (batch: PinStateBatch) => void;
}
 
export class PinStateBatcher {
  private readonly config: Required<PinStateBatcherConfig>;
  private readonly pendingStates = new Map<string, PinStateEvent>();
  private tickTimer: NodeJS.Timeout | null = null;
  private intendedCount = 0;
  private actualCount = 0;
  private batchCount = 0;
 
  constructor(config: PinStateBatcherConfig) {
    this.config = {
      tickIntervalMs: config.tickIntervalMs ?? 50,
      onBatch: config.onBatch,
    };
  }
 
  /**
   * Enqueue a pin state change.
   * Called for every pin change from the simulator (~2000/sec).
   */
  enqueue(pin: number, stateType: PinStateChange, value: number): void {
    const key = `${pin}:${stateType}`;
    this.pendingStates.set(key, { pin, stateType, value });
    this.intendedCount++;
  }
 
  /**
   * Start the tick timer to begin batching.
   */
  start(): void {
    Iif (this.tickTimer) {
      return; // Already started
    }
    this.tickTimer = setInterval(() => this.tick(), this.config.tickIntervalMs);
  }
 
  /**
   * Stop the tick timer and flush any remaining pending states.
   */
  stop(): void {
    Eif (this.tickTimer) {
      clearInterval(this.tickTimer);
      this.tickTimer = null;
    }
    // Flush remaining states
    this.flush();
  }
 
  /**
   * Pause ticking (keep pending states, stop timer).
   */
  pause(): void {
    Eif (this.tickTimer) {
      clearInterval(this.tickTimer);
      this.tickTimer = null;
    }
    // Do NOT flush - keep pending states
  }
 
  /**
   * Resume ticking after pause.
   */
  resume(): void {
    this.start();
  }
 
  /**
   * Get telemetry counters and reset them.
   */
  getTelemetryAndReset(): { intended: number; actual: number; batches: number } {
    const result = {
      intended: this.intendedCount,
      actual: this.actualCount,
      batches: this.batchCount,
    };
    this.intendedCount = 0;
    this.actualCount = 0;
    this.batchCount = 0;
    return result;
  }
 
  /**
   * Destroy the batcher, stop timer, discard pending states.
   */
  destroy(): void {
    if (this.tickTimer) {
      clearInterval(this.tickTimer);
      this.tickTimer = null;
    }
    this.pendingStates.clear();
  }
 
  /**
   * Tick handler: send batch if there are pending states.
   */
  private tick(): void {
    this.flush();
  }
 
  /**
   * Flush pending states as a batch.
   */
  private flush(): void {
    if (this.pendingStates.size === 0) {
      return;
    }
 
    const states = Array.from(this.pendingStates.values());
    this.pendingStates.clear();
    this.actualCount += states.length;
 
    this.config.onBatch({
      states,
      timestamp: Date.now(),
    });
 
    this.batchCount++;
  }
}