use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct LogEntry {
#[schemars(schema_with = "crate::schema_helpers::uint_schema")]
pub timestamp_ms: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub direction: Option<String>,
pub event: LogEvent,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum LogEvent {
RxData {
#[schemars(schema_with = "crate::schema_helpers::uint_schema")]
bytes: usize,
},
TxData {
#[schemars(schema_with = "crate::schema_helpers::uint_schema")]
bytes: usize,
},
Open,
Close,
Disconnect { error: String },
ReconnectStart {
#[schemars(schema_with = "crate::schema_helpers::uint_schema")]
attempt: u32,
},
ReconnectSuccess,
ReconnectFailed {
#[schemars(schema_with = "crate::schema_helpers::uint_schema")]
attempt: u32,
error: String,
},
ReconnectExhausted,
MatchFound { pattern: String, mode: String },
Truncated {
#[schemars(schema_with = "crate::schema_helpers::uint_schema")]
observed: usize,
#[schemars(schema_with = "crate::schema_helpers::uint_schema")]
returned: usize,
},
NotificationDropped { reason: String },
ReadStarted,
ReadCompleted {
#[schemars(schema_with = "crate::schema_helpers::uint_schema")]
bytes: usize,
},
WriteStarted,
WriteCompleted {
#[schemars(schema_with = "crate::schema_helpers::uint_schema")]
bytes: usize,
},
SubscribeStarted,
SubscribeStopped { reason: String },
Error { message: String },
}
#[derive(Debug)]
pub struct LogBuffer {
events: Mutex<VecDeque<LogEntry>>,
capacity: usize,
enabled: bool,
}
impl LogBuffer {
pub fn new(capacity: usize, enabled: bool) -> Self {
Self {
events: Mutex::new(VecDeque::with_capacity(capacity)),
capacity,
enabled,
}
}
pub fn is_enabled(&self) -> bool {
self.enabled
}
pub fn capacity(&self) -> usize {
self.capacity
}
pub fn record(&self, direction: Option<&str>, event: LogEvent) {
if !self.enabled {
return;
}
let timestamp_ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
let entry = LogEntry {
timestamp_ms,
direction: direction.map(str::to_string),
event,
};
let mut events = self.events.lock().expect("log mutex poisoned");
events.push_back(entry);
while events.len() > self.capacity {
events.pop_front();
}
}
pub fn snapshot(&self) -> Vec<LogEntry> {
let events = self.events.lock().expect("log mutex poisoned");
events.iter().cloned().collect()
}
pub fn clear(&self) {
let mut events = self.events.lock().expect("log mutex poisoned");
events.clear();
}
}
impl Default for LogBuffer {
fn default() -> Self {
Self::new(1024, false)
}
}
impl LogBuffer {
pub fn new_shared(capacity: usize, enabled: bool) -> Arc<Self> {
Arc::new(Self::new(capacity, enabled))
}
}
impl LogBuffer {
pub fn rx_data(&self, bytes: usize) {
self.record(Some("rx"), LogEvent::RxData { bytes });
}
pub fn tx_data(&self, bytes: usize) {
self.record(Some("tx"), LogEvent::TxData { bytes });
}
pub fn opened(&self) {
self.record(None, LogEvent::Open);
}
pub fn closed(&self) {
self.record(None, LogEvent::Close);
}
pub fn match_found(&self, pattern: &str, mode: &str) {
self.record(
None,
LogEvent::MatchFound {
pattern: pattern.to_string(),
mode: mode.to_string(),
},
);
}
pub fn truncated(&self, observed: usize, returned: usize) {
self.record(None, LogEvent::Truncated { observed, returned });
}
pub fn notification_dropped(&self, reason: &str) {
self.record(
None,
LogEvent::NotificationDropped {
reason: reason.to_string(),
},
);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn log_buffer_records_and_snapshots() {
let log = LogBuffer::new(10, true);
log.rx_data(5);
log.tx_data(3);
let snap = log.snapshot();
assert_eq!(snap.len(), 2);
assert!(snap[0].timestamp_ms > 0);
}
#[test]
fn log_buffer_disabled_does_not_record() {
let log = LogBuffer::new(10, false);
log.rx_data(5);
assert!(log.snapshot().is_empty());
}
#[test]
fn log_buffer_evicts_when_capacity_exceeded() {
let log = LogBuffer::new(3, true);
for i in 0..5 {
log.rx_data(i);
}
let snap = log.snapshot();
assert_eq!(snap.len(), 3);
if let LogEvent::RxData { bytes } = &snap[0].event {
assert_eq!(*bytes, 2);
}
}
#[test]
fn log_buffer_clear_empties() {
let log = LogBuffer::new(10, true);
log.rx_data(1);
log.tx_data(2);
log.clear();
assert!(log.snapshot().is_empty());
}
#[test]
fn log_entry_serialization_is_jsonl_compatible() {
let log = LogBuffer::new(10, true);
log.rx_data(42);
let snap = log.snapshot();
let json = serde_json::to_string(&snap[0]).unwrap();
assert!(json.contains("\"event\":\"rx_data\""));
assert!(json.contains("\"bytes\":42"));
assert!(json.contains("\"direction\":\"rx\""));
}
}