1use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10use std::collections::VecDeque;
11use std::sync::{Arc, Mutex};
12use std::time::{SystemTime, UNIX_EPOCH};
13
14#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
18pub struct LogEntry {
19 #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
21 pub timestamp_ms: u64,
22 #[serde(skip_serializing_if = "Option::is_none")]
24 pub direction: Option<String>,
25 pub event: LogEvent,
27}
28
29#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
34#[serde(tag = "event", rename_all = "snake_case")]
35pub enum LogEvent {
36 RxData {
38 #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
39 bytes: usize,
40 },
41 TxData {
43 #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
44 bytes: usize,
45 },
46 Open,
48 Close,
50 Disconnect { error: String },
52 ReconnectStart {
54 #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
55 attempt: u32,
56 },
57 ReconnectSuccess,
59 ReconnectFailed {
61 #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
62 attempt: u32,
63 error: String,
64 },
65 ReconnectExhausted,
67 MatchFound { pattern: String, mode: String },
69 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 ReadStarted,
78 ReadCompleted {
80 #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
81 bytes: usize,
82 },
83 WriteStarted,
85 WriteCompleted {
87 #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
88 bytes: usize,
89 },
90 Error { message: String },
92}
93
94#[derive(Debug)]
98pub struct LogBuffer {
99 events: Mutex<VecDeque<LogEntry>>,
100 capacity: usize,
101 enabled: bool,
102}
103
104impl LogBuffer {
105 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 pub fn is_enabled(&self) -> bool {
116 self.enabled
117 }
118
119 pub fn capacity(&self) -> usize {
121 self.capacity
122 }
123
124 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 pub fn snapshot(&self) -> Vec<LogEntry> {
147 let events = self.events.lock().expect("log mutex poisoned");
148 events.iter().cloned().collect()
149 }
150
151 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 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 pub fn clear(&self) {
199 let mut events = self.events.lock().expect("log mutex poisoned");
200 events.clear();
201 }
202}
203
204#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct JsonlSnapshot {
207 pub bytes: Vec<u8>,
209 pub events: usize,
211}
212
213impl Default for LogBuffer {
214 fn default() -> Self {
215 Self::new(1024, false)
216 }
217}
218
219impl LogBuffer {
221 pub fn new_shared(capacity: usize, enabled: bool) -> Arc<Self> {
222 Arc::new(Self::new(capacity, enabled))
223 }
224}
225
226impl 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 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 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 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 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 let err = log
348 .jsonl_snapshot(unlimited.bytes.len() as u64 - 1)
349 .unwrap_err();
350 assert!(err.contains("quota"), "got: {err}");
351 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 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 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}