use crate::{FailPolicy, GuardError, Verdict};
use core::fmt;
use std::collections::VecDeque;
use std::time::Duration;
const MAX_REASON_BYTES: usize = 256;
fn clamp(reason: &str) -> String {
if reason.len() <= MAX_REASON_BYTES {
return reason.to_owned();
}
let mut end = MAX_REASON_BYTES;
while end > 0 && !reason.is_char_boundary(end) {
end -= 1;
}
format!("{}…", &reason[..end])
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum TraceOutcome {
Allowed,
Blocked {
reason: String,
},
Modified,
Failed {
error: GuardError,
policy: FailPolicy,
halted: bool,
},
}
impl TraceOutcome {
pub fn from_verdict<O>(verdict: &Verdict<O>) -> Self {
match verdict {
Verdict::Allow => TraceOutcome::Allowed,
Verdict::Block { reason } => TraceOutcome::Blocked {
reason: clamp(reason),
},
Verdict::Modify(_) => TraceOutcome::Modified,
}
}
pub fn kind(&self) -> &'static str {
match self {
TraceOutcome::Allowed => "allowed",
TraceOutcome::Blocked { .. } => "blocked",
TraceOutcome::Modified => "modified",
TraceOutcome::Failed { .. } => "failed",
}
}
pub fn halted(&self) -> bool {
match self {
TraceOutcome::Blocked { .. } => true,
TraceOutcome::Failed { halted, .. } => *halted,
_ => false,
}
}
}
impl fmt::Display for TraceOutcome {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TraceOutcome::Allowed => f.write_str("allowed"),
TraceOutcome::Blocked { reason } => write!(f, "blocked: {reason}"),
TraceOutcome::Modified => f.write_str("modified"),
TraceOutcome::Failed { error, policy, .. } => write!(f, "failed ({policy}): {error}"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TraceEntry {
name: &'static str,
outcome: TraceOutcome,
elapsed: Duration,
}
impl TraceEntry {
pub fn new(name: &'static str, outcome: TraceOutcome, elapsed: Duration) -> Self {
TraceEntry {
name,
outcome,
elapsed,
}
}
pub fn name(&self) -> &'static str {
self.name
}
pub fn outcome(&self) -> &TraceOutcome {
&self.outcome
}
pub fn elapsed(&self) -> Duration {
self.elapsed
}
}
impl fmt::Display for TraceEntry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {} ({:?})", self.name, self.outcome, self.elapsed)
}
}
#[derive(Debug, Clone)]
pub struct Trace {
entries: VecDeque<TraceEntry>,
capacity: usize,
dropped: usize,
}
impl Trace {
pub const DEFAULT_CAPACITY: usize = 64;
pub fn new() -> Self {
Trace::with_capacity(Trace::DEFAULT_CAPACITY)
}
pub fn with_capacity(capacity: usize) -> Self {
Trace {
entries: VecDeque::with_capacity(capacity.min(Trace::DEFAULT_CAPACITY)),
capacity,
dropped: 0,
}
}
pub fn record(&mut self, entry: TraceEntry) {
if self.capacity == 0 {
self.dropped += 1;
return;
}
while self.entries.len() >= self.capacity {
self.entries.pop_front();
self.dropped += 1;
}
self.entries.push_back(entry);
}
pub fn iter(&self) -> impl Iterator<Item = &TraceEntry> {
self.entries.iter()
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn capacity(&self) -> usize {
self.capacity
}
pub fn dropped(&self) -> usize {
self.dropped
}
pub fn is_complete(&self) -> bool {
self.dropped == 0
}
pub fn last(&self) -> Option<&TraceEntry> {
self.entries.back()
}
pub fn halted_by(&self) -> Option<&'static str> {
self.entries
.iter()
.find(|entry| entry.outcome().halted())
.map(TraceEntry::name)
}
}
impl Default for Trace {
fn default() -> Self {
Trace::new()
}
}
impl<'a> IntoIterator for &'a Trace {
type Item = &'a TraceEntry;
type IntoIter = std::collections::vec_deque::Iter<'a, TraceEntry>;
fn into_iter(self) -> Self::IntoIter {
self.entries.iter()
}
}
impl fmt::Display for Trace {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.dropped > 0 {
writeln!(f, "[{} earlier entries dropped]", self.dropped)?;
}
for (index, entry) in self.entries.iter().enumerate() {
if index > 0 {
f.write_str("\n")?;
}
write!(f, "{entry}")?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn entry(name: &'static str) -> TraceEntry {
TraceEntry::new(name, TraceOutcome::Allowed, Duration::from_millis(1))
}
#[test]
fn entries_are_kept_in_order() {
let mut trace = Trace::new();
for name in ["a", "b", "c"] {
trace.record(entry(name));
}
let names: Vec<_> = trace.iter().map(TraceEntry::name).collect();
assert_eq!(names, ["a", "b", "c"]);
assert_eq!(trace.len(), 3);
assert!(trace.is_complete());
}
#[test]
fn memory_stays_flat_however_many_guards_run() {
let mut trace = Trace::with_capacity(8);
for _ in 0..100_000 {
trace.record(entry("noisy"));
}
assert_eq!(trace.len(), 8);
assert_eq!(trace.capacity(), 8);
assert_eq!(trace.dropped(), 100_000 - 8);
assert!(!trace.is_complete());
}
#[test]
fn a_full_trace_keeps_the_deciding_tail() {
let mut trace = Trace::with_capacity(2);
trace.record(entry("first"));
trace.record(entry("second"));
trace.record(TraceEntry::new(
"third",
TraceOutcome::Blocked {
reason: "no".to_owned(),
},
Duration::ZERO,
));
assert_eq!(trace.last().map(TraceEntry::name), Some("third"));
assert_eq!(trace.halted_by(), Some("third"));
}
#[test]
fn zero_capacity_records_nothing_but_still_counts() {
let mut trace = Trace::with_capacity(0);
trace.record(entry("a"));
trace.record(entry("b"));
assert!(trace.is_empty());
assert_eq!(trace.dropped(), 2);
}
#[test]
fn a_pathological_block_reason_is_clamped_on_a_char_boundary() {
let long = "é".repeat(1_000);
let outcome = TraceOutcome::from_verdict(&Verdict::<()>::block(long));
let TraceOutcome::Blocked { reason } = outcome else {
panic!("expected a blocked outcome");
};
assert!(reason.len() <= MAX_REASON_BYTES + '…'.len_utf8());
assert!(reason.ends_with('…'));
}
#[test]
fn a_short_reason_is_kept_verbatim() {
let outcome = TraceOutcome::from_verdict(&Verdict::<()>::block("banned phrase"));
assert_eq!(
outcome,
TraceOutcome::Blocked {
reason: "banned phrase".to_owned()
}
);
}
#[test]
fn outcome_kinds_are_unique_and_payload_free() {
let outcomes = [
TraceOutcome::Allowed,
TraceOutcome::Blocked {
reason: "spaces and such".to_owned(),
},
TraceOutcome::Modified,
TraceOutcome::Failed {
error: GuardError::Timeout,
policy: FailPolicy::FailClosed,
halted: true,
},
];
let mut kinds: Vec<_> = outcomes.iter().map(TraceOutcome::kind).collect();
kinds.sort_unstable();
kinds.dedup();
assert_eq!(kinds.len(), outcomes.len());
for outcome in &outcomes {
assert!(!outcome.kind().contains(' '));
}
}
#[test]
fn only_blocks_and_halting_failures_stop_the_pipeline() {
assert!(!TraceOutcome::Allowed.halted());
assert!(!TraceOutcome::Modified.halted());
assert!(
TraceOutcome::Blocked {
reason: "no".to_owned()
}
.halted()
);
assert!(
!TraceOutcome::Failed {
error: GuardError::Timeout,
policy: FailPolicy::FailOpen,
halted: false,
}
.halted()
);
}
#[test]
fn display_announces_truncation() {
let mut trace = Trace::with_capacity(1);
trace.record(entry("a"));
trace.record(entry("b"));
let rendered = trace.to_string();
assert!(rendered.starts_with("[1 earlier entries dropped]"));
assert!(rendered.contains("b allowed"));
assert!(!rendered.contains("a allowed"));
}
}