Skip to main content

serial_mcp/
log_buffer.rs

1//! Per-connection in-memory event log with ring-buffer semantics.
2//!
3//! Stores typed [`LogEvent`] entries with millisecond-precision Unix
4//! timestamps. When the buffer reaches `capacity`, oldest entries are
5//! dropped. Accessible via tools (`get_log`, `clear_log`, `export_log`)
6//! and a resource (`serial://connections/{id}/log`).
7
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10use std::collections::VecDeque;
11use std::sync::{Arc, Mutex};
12use std::time::{SystemTime, UNIX_EPOCH};
13
14// ---- Event types -----------------------------------------------------------
15
16/// A single log event with timestamp, direction, and event data.
17#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
18pub struct LogEntry {
19    /// Milliseconds since Unix epoch.
20    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
21    pub timestamp_ms: u64,
22    /// `"rx"`, `"tx"`, or `null` for non-directional events.
23    #[serde(skip_serializing_if = "Option::is_none")]
24    pub direction: Option<String>,
25    /// The typed event payload.
26    pub event: LogEvent,
27}
28
29/// Typed event payloads stored in the log buffer.
30///
31/// The `#[serde(tag = "event")]` attribute ensures each entry carries a
32/// `"event"` field naming the variant, producing clean JSONL output.
33#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
34#[serde(tag = "event", rename_all = "snake_case")]
35pub enum LogEvent {
36    /// RX data chunk received from the device.
37    RxData {
38        #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
39        bytes: usize,
40    },
41    /// TX data chunk sent to the device.
42    TxData {
43        #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
44        bytes: usize,
45    },
46    /// Connection opened.
47    Open,
48    /// Connection closed (explicitly by user).
49    Close,
50    /// Port disconnected (fatal I/O error).
51    Disconnect { error: String },
52    /// Reconnect attempt started.
53    ReconnectStart {
54        #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
55        attempt: u32,
56    },
57    /// Reconnect succeeded.
58    ReconnectSuccess,
59    /// Reconnect attempt failed.
60    ReconnectFailed {
61        #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
62        attempt: u32,
63        error: String,
64    },
65    /// Max reconnect attempts exhausted.
66    ReconnectExhausted,
67    /// Match found in read.
68    MatchFound { pattern: String, mode: String },
69    /// Data truncated (bytes_returned < bytes_observed).
70    Truncated {
71        #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
72        observed: usize,
73        #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
74        returned: usize,
75    },
76    /// Read operation started.
77    ReadStarted,
78    /// Read operation completed.
79    ReadCompleted {
80        #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
81        bytes: usize,
82    },
83    /// Write operation started.
84    WriteStarted,
85    /// Write operation completed.
86    WriteCompleted {
87        #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
88        bytes: usize,
89    },
90    /// Generic error.
91    Error { message: String },
92}
93
94// ---- Log buffer ------------------------------------------------------------
95
96/// Thread-safe, bounded ring buffer of timestamped log events.
97#[derive(Debug)]
98pub struct LogBuffer {
99    events: Mutex<VecDeque<LogEntry>>,
100    capacity: usize,
101    enabled: bool,
102}
103
104impl LogBuffer {
105    /// Create a new log buffer with the given capacity and enabled flag.
106    pub fn new(capacity: usize, enabled: bool) -> Self {
107        Self {
108            events: Mutex::new(VecDeque::with_capacity(capacity)),
109            capacity,
110            enabled,
111        }
112    }
113
114    /// Return whether logging is enabled.
115    pub fn is_enabled(&self) -> bool {
116        self.enabled
117    }
118
119    /// Return the configured capacity (maximum number of events).
120    pub fn capacity(&self) -> usize {
121        self.capacity
122    }
123
124    /// Record a typed event with an optional direction.
125    pub fn record(&self, direction: Option<&str>, event: LogEvent) {
126        if !self.enabled {
127            return;
128        }
129        let timestamp_ms = SystemTime::now()
130            .duration_since(UNIX_EPOCH)
131            .map(|d| d.as_millis() as u64)
132            .unwrap_or(0);
133        let entry = LogEntry {
134            timestamp_ms,
135            direction: direction.map(str::to_string),
136            event,
137        };
138        let mut events = self.events.lock().expect("log mutex poisoned");
139        events.push_back(entry);
140        while events.len() > self.capacity {
141            events.pop_front();
142        }
143    }
144
145    /// Return a snapshot of all entries in the buffer.
146    pub fn snapshot(&self) -> Vec<LogEntry> {
147        let events = self.events.lock().expect("log mutex poisoned");
148        events.iter().cloned().collect()
149    }
150
151    /// Serialize the buffer to a bounded JSONL snapshot.
152    ///
153    /// Locks the log exactly once for a consistent point-in-time snapshot,
154    /// serializes one entry per line with a trailing newline, and checks the
155    /// projected size before extending the output (checked arithmetic).
156    /// Fails — leaving no output — when the exact snapshot exceeds
157    /// `max_bytes` (the capture per-file quota). The event deque itself is
158    /// never cloned and no second full output String is built.
159    pub fn jsonl_snapshot(&self, max_bytes: u64) -> Result<JsonlSnapshot, String> {
160        let events = self.events.lock().expect("log mutex poisoned");
161        let mut out: Vec<u8> = Vec::new();
162        let mut count: usize = 0;
163        for entry in events.iter() {
164            let line = serde_json::to_string(entry)
165                .map_err(|e| format!("Failed to serialize log entry: {e}"))?;
166            // Checked arithmetic before any projection: usize -> u64, then
167            // line + trailing newline, then cumulative size. Exact-limit
168            // behavior is preserved (projected == max_bytes is allowed).
169            let out_len =
170                u64::try_from(out.len()).map_err(|_| "log snapshot size overflow".to_string())?;
171            let line_len = u64::try_from(line.len())
172                .map_err(|_| "log snapshot line size overflow".to_string())?;
173            let needed = line_len
174                .checked_add(1)
175                .ok_or_else(|| "log snapshot line size overflow".to_string())?;
176            let projected = out_len
177                .checked_add(needed)
178                .ok_or_else(|| "log snapshot size overflow".to_string())?;
179            if projected > max_bytes {
180                return Err(format!(
181                    "log snapshot exceeds capture per-file quota ({max_bytes} bytes); \
182                     reduce log_capacity or raise --capture-max-file-bytes"
183                ));
184            }
185            out.extend_from_slice(line.as_bytes());
186            out.push(b'\n');
187            count = count
188                .checked_add(1)
189                .ok_or_else(|| "log snapshot event count overflow".to_string())?;
190        }
191        Ok(JsonlSnapshot {
192            bytes: out,
193            events: count,
194        })
195    }
196
197    /// Clear all entries from the buffer.
198    pub fn clear(&self) {
199        let mut events = self.events.lock().expect("log mutex poisoned");
200        events.clear();
201    }
202}
203
204/// A bounded point-in-time JSONL serialization of a [`LogBuffer`].
205#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct JsonlSnapshot {
207    /// Serialized bytes: one JSON object per line with trailing newline.
208    pub bytes: Vec<u8>,
209    /// Number of events serialized.
210    pub events: usize,
211}
212
213impl Default for LogBuffer {
214    fn default() -> Self {
215        Self::new(1024, false)
216    }
217}
218
219/// Typed wrapper to share across the server.
220impl LogBuffer {
221    pub fn new_shared(capacity: usize, enabled: bool) -> Arc<Self> {
222        Arc::new(Self::new(capacity, enabled))
223    }
224}
225
226// Helper shorthand for recording common events.
227impl LogBuffer {
228    pub fn rx_data(&self, bytes: usize) {
229        self.record(Some("rx"), LogEvent::RxData { bytes });
230    }
231
232    pub fn tx_data(&self, bytes: usize) {
233        self.record(Some("tx"), LogEvent::TxData { bytes });
234    }
235
236    pub fn opened(&self) {
237        self.record(None, LogEvent::Open);
238    }
239
240    pub fn closed(&self) {
241        self.record(None, LogEvent::Close);
242    }
243
244    pub fn match_found(&self, pattern: &str, mode: &str) {
245        self.record(
246            None,
247            LogEvent::MatchFound {
248                pattern: pattern.to_string(),
249                mode: mode.to_string(),
250            },
251        );
252    }
253
254    pub fn truncated(&self, observed: usize, returned: usize) {
255        self.record(None, LogEvent::Truncated { observed, returned });
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262
263    #[test]
264    fn log_buffer_records_and_snapshots() {
265        let log = LogBuffer::new(10, true);
266        log.rx_data(5);
267        log.tx_data(3);
268        let snap = log.snapshot();
269        assert_eq!(snap.len(), 2);
270        assert!(snap[0].timestamp_ms > 0);
271    }
272
273    #[test]
274    fn log_buffer_disabled_does_not_record() {
275        let log = LogBuffer::new(10, false);
276        log.rx_data(5);
277        assert!(log.snapshot().is_empty());
278    }
279
280    #[test]
281    fn log_buffer_evicts_when_capacity_exceeded() {
282        let log = LogBuffer::new(3, true);
283        for i in 0..5 {
284            log.rx_data(i);
285        }
286        let snap = log.snapshot();
287        assert_eq!(snap.len(), 3);
288        // Oldest (0,1) should be evicted; 2,3,4 remain
289        if let LogEvent::RxData { bytes } = &snap[0].event {
290            assert_eq!(*bytes, 2);
291        }
292    }
293
294    #[test]
295    fn log_buffer_clear_empties() {
296        let log = LogBuffer::new(10, true);
297        log.rx_data(1);
298        log.tx_data(2);
299        log.clear();
300        assert!(log.snapshot().is_empty());
301    }
302
303    #[test]
304    fn log_entry_serialization_is_jsonl_compatible() {
305        let log = LogBuffer::new(10, true);
306        log.rx_data(42);
307        let snap = log.snapshot();
308        let json = serde_json::to_string(&snap[0]).unwrap();
309        // Verify the "event" tag field is present
310        assert!(json.contains("\"event\":\"rx_data\""));
311        assert!(json.contains("\"bytes\":42"));
312        assert!(json.contains("\"direction\":\"rx\""));
313    }
314
315    #[test]
316    fn jsonl_snapshot_matches_get_log_snapshot() {
317        let log = LogBuffer::new(10, true);
318        log.opened();
319        log.rx_data(5);
320        log.tx_data(3);
321        log.match_found("OK", "literal_substring");
322        let snap = log.jsonl_snapshot(u64::MAX).unwrap();
323        assert_eq!(snap.events, 4);
324        let text = String::from_utf8(snap.bytes.clone()).unwrap();
325        assert_eq!(text.lines().count(), 4);
326        assert!(text.ends_with('\n'));
327        // Every line parses and equals the get_log snapshot entry.
328        let expected: Vec<LogEntry> = log.snapshot();
329        for (i, line) in text.lines().enumerate() {
330            let parsed: LogEntry = serde_json::from_str(line).unwrap();
331            assert_eq!(parsed, expected[i]);
332        }
333    }
334
335    #[test]
336    fn jsonl_snapshot_exact_limit_and_one_byte_over() {
337        let log = LogBuffer::new(10, true);
338        log.rx_data(1);
339        log.rx_data(2);
340        let unlimited = log.jsonl_snapshot(u64::MAX).unwrap();
341        assert!(!unlimited.bytes.is_empty());
342        // Exact limit succeeds with identical bytes.
343        let exact = log.jsonl_snapshot(unlimited.bytes.len() as u64).unwrap();
344        assert_eq!(exact.bytes, unlimited.bytes);
345        assert_eq!(exact.events, unlimited.events);
346        // One byte under the exact size fails and leaves no output.
347        let err = log
348            .jsonl_snapshot(unlimited.bytes.len() as u64 - 1)
349            .unwrap_err();
350        assert!(err.contains("quota"), "got: {err}");
351        // A zero limit fails for any non-empty log; succeeds for empty.
352        assert!(log.jsonl_snapshot(0).is_err());
353        let empty = LogBuffer::new(10, true);
354        let snap = empty.jsonl_snapshot(0).unwrap();
355        assert!(snap.bytes.is_empty());
356        assert_eq!(snap.events, 0);
357    }
358
359    #[test]
360    fn jsonl_snapshot_disabled_log_is_zero_bytes() {
361        let log = LogBuffer::new(10, false);
362        log.rx_data(5);
363        let snap = log.jsonl_snapshot(u64::MAX).unwrap();
364        assert!(snap.bytes.is_empty());
365        assert_eq!(snap.events, 0);
366    }
367
368    #[test]
369    fn jsonl_snapshot_is_point_in_time_under_concurrent_records() {
370        // The lock is held across the whole serialization: events recorded
371        // during the snapshot either appear fully or not at all — never
372        // partially interleaved.
373        let log = LogBuffer::new(1000, true);
374        log.rx_data(1);
375        let snap = log.jsonl_snapshot(u64::MAX).unwrap();
376        assert_eq!(snap.events, 1);
377        // Events recorded AFTER the snapshot are not in its bytes.
378        log.rx_data(2);
379        log.rx_data(3);
380        let lines = String::from_utf8(snap.bytes).unwrap();
381        assert_eq!(lines.lines().count(), 1);
382        assert!(!lines.contains("\"bytes\":2"));
383        assert!(!lines.contains("\"bytes\":3"));
384    }
385}