All files / server/services arduino-output-parser.ts

93.1% Statements 54/58
79.24% Branches 42/53
100% Functions 4/4
93.1% Lines 54/58

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            13x                                                         13x                                                           38319x 16x   38303x 15x       38288x     38288x 233x 233x 233x         38055x 38055x 2x             38053x 38053x 36701x             1352x 1352x 1x               1351x     1351x 1334x         1334x 1334x         17x             5x                             12x             6x 6x       6x                               1334x 1334x 1334x 1334x   1334x                                         233x 233x 233x 233x 233x 233x   233x 233x   2x 2x 2x 6x   6x 6x 6x 6x 6x                   233x                              
// arduino-output-parser.ts
// Pure parsing logic for Arduino C++ mock output
 
import { Logger } from "@shared/logger";
import type { IOPinRecord } from "@shared/schema";
 
const logger = new Logger("ArduinoOutputParser");
 
/**
 * Parsed stderr output types (discriminated union for type safety)
 */
export type ParsedStderrOutput =
  | { type: "serial_event"; timestamp: number; data: string }
  | { type: "registry_start" }
  | { type: "registry_end" }
  | {
      type: "registry_pin";
      pinRecord: IOPinRecord;
    }
  | { type: "pin_mode"; pin: number; mode: number }
  | { type: "pin_value"; pin: number; value: number }
  | { type: "pin_pwm"; pin: number; value: number }
  | { type: "debug_marker"; marker: string }
  | { type: "text"; line: string }
  | { type: "ignored" };
 
/**
 * ArduinoOutputParser - Stateless parser for Arduino mock output
 * 
 * Responsibilities:
 * - Parse stderr lines from C++ Arduino mock
 * - Extract structured data (serial events, pin states, registry)
 * - No side effects - pure functions only
 */
export class ArduinoOutputParser {
  private static readonly PATTERNS = {
    serialEvent: /\[\[SERIAL_EVENT:(\d+):([A-Za-z0-9+/=]+)\]\]/,
    registryStart: /\[\[IO_REGISTRY_START\]\]/,
    registryEnd: /\[\[IO_REGISTRY_END\]\]/,
    registryPin: /\[\[IO_PIN:([^:]+):([01]):(\d+):(\d+):?(.*)\]\]/,
    pinMode: /\[\[PIN_MODE:(\d+):(\d+)\]\]/,
    pinValue: /\[\[PIN_VALUE:(\d+):(\d+)\]\]/,
    pinPwm: /\[\[PIN_PWM:(\d+):(\d+)\]\]/,
    // Debug markers - should be ignored
    digitalRead: /\[\[DREAD:(\d+):(\d+)\]\]/,
    pinSet: /\[\[PIN_SET:(\d+):(\d+)\]\]/,
    stdinRecv: /\[\[STDIN_RECV:(.+)\]\]/,
    // Pause/Resume timing markers - should be ignored
    timeFrozen: /\[\[TIME_FROZEN:(\d+)\]\]/,
    timeResumed: /\[\[TIME_RESUMED:(\d+)\]\]/,
  };
 
  /**
   * Parse a single stderr line from Arduino mock process
   * Priority order: registry markers > pin states > serial events > text
   * 
   * @param line - Raw stderr line
   * @param processStartTime - Server timestamp when process started (for serial event timestamps)
   * @returns Structured ParsedStderrOutput object
   */
  parseStderrLine(
    line: string,
    processStartTime: number | null,
  ): ParsedStderrOutput {
    // Priority 1: Registry markers (start/end)
    if (ArduinoOutputParser.PATTERNS.registryStart.test(line)) {
      return { type: "registry_start" };
    }
    if (ArduinoOutputParser.PATTERNS.registryEnd.test(line)) {
      return { type: "registry_end" };
    }
 
    // Priority 2: Registry pin data
    const registryPinMatch = line.match(
      ArduinoOutputParser.PATTERNS.registryPin,
    );
    if (registryPinMatch) {
      const pinRecord = this.parseRegistryPin(registryPinMatch);
      Eif (pinRecord) {
        return { type: "registry_pin", pinRecord };
      }
    }
 
    // Priority 3: Pin state changes
    const pinModeMatch = line.match(ArduinoOutputParser.PATTERNS.pinMode);
    if (pinModeMatch) {
      return {
        type: "pin_mode",
        pin: parseInt(pinModeMatch[1]),
        mode: parseInt(pinModeMatch[2]),
      };
    }
 
    const pinValueMatch = line.match(ArduinoOutputParser.PATTERNS.pinValue);
    if (pinValueMatch) {
      return {
        type: "pin_value",
        pin: parseInt(pinValueMatch[1]),
        value: parseInt(pinValueMatch[2]),
      };
    }
 
    const pinPwmMatch = line.match(ArduinoOutputParser.PATTERNS.pinPwm);
    if (pinPwmMatch) {
      return {
        type: "pin_pwm",
        pin: parseInt(pinPwmMatch[1]),
        value: parseInt(pinPwmMatch[2]),
      };
    }
 
    // Priority 4: Serial events
    const serialEventMatch = line.match(
      ArduinoOutputParser.PATTERNS.serialEvent,
    );
    if (serialEventMatch) {
      const parsed = this.parseSerialEvent(
        serialEventMatch[1],
        serialEventMatch[2],
        processStartTime,
      );
      Eif (parsed) {
        return parsed;
      }
    }
 
    // Priority 5: Debug markers (ignore these)
    if (
      ArduinoOutputParser.PATTERNS.digitalRead.test(line) ||
      ArduinoOutputParser.PATTERNS.pinSet.test(line) ||
      ArduinoOutputParser.PATTERNS.stdinRecv.test(line) ||
      ArduinoOutputParser.PATTERNS.timeFrozen.test(line) ||
      ArduinoOutputParser.PATTERNS.timeResumed.test(line)
    ) {
      return { type: "ignored" };
    }
 
    // Priority 6: Protocol fragments (from interrupted writes during SIGSTOP/SIGCONT
    // or from thread-interleaved stderr output before the cerrMutex fix).
    // These occur when C++ is mid-write of a [[...]] message when SIGSTOP arrives,
    // or when two threads wrote to stderr concurrently without proper locking.
    // After SIGCONT, the rest of the message (e.g., "]]") arrives as a separate chunk.
    //
    // Patterns to catch:
    //   "]]"                           standalone closing brackets
    //   "[["                           standalone opening brackets
    //   "[[SERIAL_EVENT:" (no "]]")    partial protocol header
    //   "4579:WzAw...Cg==]]"           tail of a split SERIAL_EVENT (timestamp:base64]])
    //   "WzAwMDAwMl0g...Cg==]]"        base64 tail + closing brackets
    if (
      line === "]]" ||
      line === "[[" ||
      (/^\[\[.{0,50}$/.test(line) && !line.includes("]]")) ||  // Partial [[... without closing
      /^[A-Za-z0-9+/=:]{1,}\]\]$/.test(line) ||                // timestamp:base64 tail + ]]
      /^\d+:[A-Za-z0-9+/=]+/.test(line)                        // timestamp:base64 (no brackets)
    ) {
      logger.debug(`Ignoring protocol fragment: ${line.substring(0, 80)}...`);
      return { type: "ignored" };
    }
 
    // Default: Regular text (error/warning message)
    return { type: "text", line };
  }
 
  /**
   * Parse serial event from base64 encoded data
   * 
   * @param timestampStr - Raw timestamp string (millis since process start)
   * @param base64Data - Base64 encoded serial data
   * @param processStartTime - Server-side process start timestamp
   * @returns Parsed serial event or null on error
   */
  private parseSerialEvent(
    timestampStr: string,
    base64Data: string,
    processStartTime: number | null,
  ): ParsedStderrOutput | null {
    try {
      const ts = parseInt(timestampStr, 10);
      const buf = Buffer.from(base64Data, "base64");
      const decoded = buf.toString("utf8");
 
      return {
        type: "serial_event",
        timestamp: (processStartTime || Date.now()) + ts,
        data: decoded,
      };
    } catch (e) {
      logger.warn(
        `Failed to parse SERIAL_EVENT: ${e instanceof Error ? e.message : String(e)}`,
      );
      return null;
    }
  }
 
  /**
   * Parse I/O registry pin definition
   * Format: [[IO_PIN:pin:defined:line:pinMode:operations]]
   * 
   * @param match - Regex match array from registryPin pattern
   * @returns IOPinRecord or null on error
   */
  private parseRegistryPin(match: RegExpMatchArray): IOPinRecord | null {
    try {
      const pin = match[1];
      const defined = match[2] === "1";
      const definedLine = parseInt(match[3]);
      const pinModeParsed = parseInt(match[4]);
      const operationsStr = match[5];
 
      const usedAt: Array<{ line: number; operation: string }> = [];
      if (operationsStr) {
        // Parse operations: "pinMode:1@0:digitalWrite@5" -> extract operation@line pairs
        const opMatches = operationsStr.match(/([^:@]+(?::\d+)?@\d+)/g);
        Eif (opMatches) {
          opMatches.forEach((opMatch) => {
            Eif (opMatch && !opMatch.startsWith("_count")) {
              // Skip metadata like _count
              const atIndex = opMatch.lastIndexOf("@");
              Eif (atIndex > 0) {
                const operation = opMatch.substring(0, atIndex);
                const lineStr = opMatch.substring(atIndex + 1);
                usedAt.push({
                  line: parseInt(lineStr) || 0,
                  operation,
                });
              }
            }
          });
        }
      }
 
      return {
        pin,
        defined,
        pinMode: pinModeParsed,
        definedAt: defined ? { line: definedLine } : undefined,
        usedAt,
      };
    } catch (e) {
      logger.warn(
        `Failed to parse registry pin: ${e instanceof Error ? e.message : String(e)}`,
      );
      return null;
    }
  }
}