use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use crate::FailureKind;
use crate::plugin::PluginId;
pub const DIAGNOSTIC_CAPACITY: usize = 128;
pub const DIAGNOSTIC_MESSAGE_BYTES: usize = 4096;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum DiagnosticSeverity {
Debug,
Info,
Warning,
Error,
Fatal,
HostMisbehaving,
PluginMisbehaving,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Diagnostic {
pub severity: DiagnosticSeverity,
pub message: String,
pub plugin: Option<PluginId>,
pub slot: Option<usize>,
pub failure_kind: Option<FailureKind>,
pub truncated: bool,
}
impl Diagnostic {
#[doc(hidden)]
#[must_use]
pub fn new(
severity: DiagnosticSeverity,
message: String,
plugin: Option<PluginId>,
slot: Option<usize>,
failure_kind: Option<FailureKind>,
truncated: bool,
) -> Diagnostic {
Diagnostic {
severity,
message,
plugin,
slot,
failure_kind,
truncated,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
#[must_use]
pub struct DiagnosticBatch {
pub records: Vec<Diagnostic>,
pub dropped: u64,
}
impl DiagnosticBatch {
#[doc(hidden)]
pub fn new(records: Vec<Diagnostic>, dropped: u64) -> DiagnosticBatch {
DiagnosticBatch { records, dropped }
}
pub fn append(&mut self, mut other: Self) {
let available = DIAGNOSTIC_CAPACITY.saturating_sub(self.records.len());
let overflow = other.records.len().saturating_sub(available);
self.dropped = self
.dropped
.saturating_add(other.dropped)
.saturating_add(overflow as u64);
other.records.truncate(available);
self.records.extend(other.records);
}
}
#[derive(Default)]
struct Buffer {
records: Mutex<VecDeque<Diagnostic>>,
dropped: AtomicU64,
}
#[derive(Clone, Default)]
pub struct DiagnosticBuffer(Arc<Buffer>);
impl DiagnosticBuffer {
pub fn record(
&self,
severity: DiagnosticSeverity,
message: &str,
plugin: Option<&PluginId>,
slot: Option<usize>,
failure_kind: Option<FailureKind>,
) {
let Ok(mut records) = self.0.records.try_lock() else {
self.0.dropped.fetch_add(1, Ordering::Relaxed);
return;
};
if records.len() == DIAGNOSTIC_CAPACITY {
self.0.dropped.fetch_add(1, Ordering::Relaxed);
return;
}
let mut end = message.len().min(DIAGNOSTIC_MESSAGE_BYTES);
while !message.is_char_boundary(end) {
end -= 1;
}
records.push_back(Diagnostic {
severity,
message: message[..end].to_owned(),
plugin: plugin.cloned(),
slot,
failure_kind,
truncated: end < message.len(),
});
}
pub fn take(&self) -> DiagnosticBatch {
let mut records = self.0.records.lock().unwrap_or_else(|p| p.into_inner());
DiagnosticBatch {
records: records.drain(..).collect(),
dropped: self.0.dropped.swap(0, Ordering::Relaxed),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bounds_storage_and_reports_overflow_and_utf8_truncation() {
let buffer = DiagnosticBuffer::default();
let message = "한".repeat(DIAGNOSTIC_MESSAGE_BYTES);
for _ in 0..DIAGNOSTIC_CAPACITY + 3 {
buffer.record(DiagnosticSeverity::Warning, &message, None, None, None);
}
let batch = buffer.take();
assert_eq!(batch.records.len(), DIAGNOSTIC_CAPACITY);
assert_eq!(batch.dropped, 3);
assert!(
batch
.records
.iter()
.all(|r| r.truncated && r.message.len() <= DIAGNOSTIC_MESSAGE_BYTES)
);
assert_eq!(buffer.take(), DiagnosticBatch::default());
}
#[test]
fn contention_drops_without_waiting_and_snapshot_merge_counts_loss() {
let buffer = DiagnosticBuffer::default();
let guard = buffer.0.records.lock().unwrap();
buffer.record(DiagnosticSeverity::Info, "busy", None, None, None);
drop(guard);
assert_eq!(buffer.take().dropped, 1);
for _ in 0..DIAGNOSTIC_CAPACITY {
buffer.record(DiagnosticSeverity::Info, "retained", None, None, None);
}
let mut batch = buffer.take();
batch.append(batch.clone());
assert_eq!(batch.records.len(), DIAGNOSTIC_CAPACITY);
assert_eq!(batch.dropped, DIAGNOSTIC_CAPACITY as u64);
}
}