Skip to main content

ash_log/
error.rs

1//! Reporting writes that did not happen.
2//!
3//! # Why this exists
4//!
5//! Tamper evidence proves that nothing in the log was altered. It says nothing
6//! about what never reached the log at all: a full disk, a broken pipe, or a
7//! revoked file handle ends the audit trail silently, and the surviving entries
8//! still verify perfectly. An attacker who can fill a disk can therefore stop
9//! the record without leaving a mark in it.
10//!
11//! [`AuditBackend::log_audit`](crate::AuditBackend::log_audit) returns `()` and
12//! cannot be changed to return a `Result` without breaking every implementation
13//! downstream. Instead a backend reports failures to an [`ErrorSink`], which the
14//! application installs where it can act on them — a metric, an alert, or a
15//! panic if the deployment would rather stop than log unwitnessed.
16
17use std::sync::Arc;
18use std::sync::atomic::{AtomicU64, Ordering};
19
20/// A write that did not reach its destination.
21#[derive(Debug)]
22pub struct WriteError {
23    /// Which backend failed, for attributing the fault in a fan-out.
24    pub backend: &'static str,
25    /// What went wrong.
26    pub source: std::io::Error,
27    /// Events lost to this failure. Usually 1, but a buffered backend can lose
28    /// a whole batch at once.
29    pub events_lost: u64,
30}
31
32impl std::fmt::Display for WriteError {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        write!(
35            f,
36            "{}: audit write failed, {} event(s) lost: {}",
37            self.backend, self.events_lost, self.source
38        )
39    }
40}
41
42impl std::error::Error for WriteError {
43    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
44        Some(&self.source)
45    }
46}
47
48/// Receives write failures reported by a backend.
49///
50/// Implementations must not panic on the write path unless stopping the process
51/// is the intended response, and must not themselves log through the failing
52/// backend.
53pub trait ErrorSink: Send + Sync {
54    /// Report one failed write.
55    fn on_error(&self, error: &WriteError);
56}
57
58/// Discards failures. The default, preserving the behaviour of backends that
59/// predate this trait.
60#[derive(Debug, Clone, Copy, Default)]
61pub struct IgnoreErrors;
62
63impl ErrorSink for IgnoreErrors {
64    fn on_error(&self, _error: &WriteError) {}
65}
66
67/// Writes failures to stderr.
68///
69/// The obvious default for a service that already collects stderr. Uses stderr
70/// specifically so a failing stdout backend cannot swallow the report of its own
71/// failure.
72#[derive(Debug, Clone, Copy, Default)]
73pub struct StderrErrorSink;
74
75impl ErrorSink for StderrErrorSink {
76    fn on_error(&self, error: &WriteError) {
77        // Deliberately `eprintln!` rather than a logger: reporting a logging
78        // failure through the logger risks recursing into the same fault.
79        eprintln!("ash-log: {error}");
80    }
81}
82
83/// Counts failures and lost events without storing them.
84///
85/// Suitable for exporting as a metric. A non-zero
86/// [`events_lost`](Self::events_lost) means the audit record is incomplete,
87/// which no amount of chain verification will reveal.
88#[derive(Debug, Default)]
89pub struct CountingErrorSink {
90    failures: AtomicU64,
91    events_lost: AtomicU64,
92}
93
94impl CountingErrorSink {
95    /// A sink with both counters at zero.
96    #[must_use]
97    pub fn new() -> Self {
98        Self::default()
99    }
100
101    /// Number of failed writes reported.
102    #[must_use]
103    pub fn failures(&self) -> u64 {
104        self.failures.load(Ordering::Relaxed)
105    }
106
107    /// Total events lost across all failures.
108    #[must_use]
109    pub fn events_lost(&self) -> u64 {
110        self.events_lost.load(Ordering::Relaxed)
111    }
112
113    /// Whether any write has failed.
114    ///
115    /// Check this alongside chain verification: a verified chain that lost
116    /// events is a complete record of an incomplete history.
117    #[must_use]
118    pub fn had_failures(&self) -> bool {
119        self.failures() > 0
120    }
121}
122
123impl ErrorSink for CountingErrorSink {
124    fn on_error(&self, error: &WriteError) {
125        self.failures.fetch_add(1, Ordering::Relaxed);
126        self.events_lost
127            .fetch_add(error.events_lost, Ordering::Relaxed);
128    }
129}
130
131/// Calls a closure for each failure.
132///
133/// ```rust
134/// use ash_log::*;
135/// use std::sync::{Arc, Mutex};
136///
137/// let seen = Arc::new(Mutex::new(Vec::new()));
138/// let captured = seen.clone();
139/// let sink = FnErrorSink::new(move |error| {
140///     captured.lock().unwrap().push(error.to_string());
141/// });
142/// # let _ = sink;
143/// ```
144pub struct FnErrorSink<F: Fn(&WriteError) + Send + Sync>(F);
145
146impl<F: Fn(&WriteError) + Send + Sync> FnErrorSink<F> {
147    /// Wrap `f` as an error sink.
148    pub const fn new(f: F) -> Self {
149        Self(f)
150    }
151}
152
153impl<F: Fn(&WriteError) + Send + Sync> ErrorSink for FnErrorSink<F> {
154    fn on_error(&self, error: &WriteError) {
155        (self.0)(error);
156    }
157}
158
159impl<T: ErrorSink + ?Sized> ErrorSink for Arc<T> {
160    fn on_error(&self, error: &WriteError) {
161        (**self).on_error(error);
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    fn error(events_lost: u64) -> WriteError {
170        WriteError {
171            backend: "TestBackend",
172            source: std::io::Error::other("disk full"),
173            events_lost,
174        }
175    }
176
177    #[test]
178    fn test_counting_sink_accumulates_losses() {
179        let sink = CountingErrorSink::new();
180        assert!(!sink.had_failures());
181
182        sink.on_error(&error(1));
183        sink.on_error(&error(64));
184
185        assert_eq!(sink.failures(), 2);
186        assert_eq!(sink.events_lost(), 65, "a batch loss counts every event");
187        assert!(sink.had_failures());
188    }
189
190    #[test]
191    fn test_error_displays_backend_and_loss() {
192        let rendered = error(3).to_string();
193        assert!(
194            rendered.contains("TestBackend"),
195            "names the failing backend"
196        );
197        assert!(rendered.contains('3'), "states how many events were lost");
198        assert!(rendered.contains("disk full"), "includes the cause");
199    }
200
201    #[test]
202    fn test_fn_sink_receives_errors() {
203        let count = Arc::new(AtomicU64::new(0));
204        let seen = count.clone();
205        let sink = FnErrorSink::new(move |_| {
206            seen.fetch_add(1, Ordering::Relaxed);
207        });
208
209        sink.on_error(&error(1));
210        assert_eq!(count.load(Ordering::Relaxed), 1);
211    }
212}