guard_agent_rs/error.rs
1//! Typed errors for the guard-agent-rs telemetry agent.
2
3use std::fmt;
4
5/// Root error type for every fallible operation in the agent.
6///
7/// The public API is deliberately narrow about what can fail:
8/// [`GuardAgent::new`](crate::GuardAgent::new) surfaces
9/// [`GuardAgentError::Config`], and
10/// [`GuardAgent::try_send_event`](crate::GuardAgent::try_send_event) can
11/// surface [`GuardAgentError::BufferFull`] when the overflow policy is
12/// [`BufferOverflowPolicy::Raise`](crate::BufferOverflowPolicy::Raise). Every
13/// transport, flush, and persistence failure is absorbed by the agent and
14/// reported through stats, logs, and the optional `on_error` hook instead,
15/// mirroring the failure-isolation policy of the Python and TypeScript agents.
16#[derive(Debug, thiserror::Error)]
17pub enum GuardAgentError {
18 /// The agent configuration failed validation.
19 #[error("Invalid agent configuration: {0}")]
20 Config(#[from] ConfigError),
21
22 /// The buffer is full and the configured overflow policy is `raise`.
23 #[error("Buffer full at capacity {capacity} and buffer_overflow_policy='raise'")]
24 BufferFull {
25 /// Configured per-kind buffer capacity that was exceeded.
26 capacity: usize,
27 },
28
29 /// The ingestion API responded with 429 Too Many Requests.
30 #[error("Rate limited (429); retry after {retry_after_seconds:.0}s")]
31 RateLimited {
32 /// Server-provided or defaulted delay in seconds.
33 retry_after_seconds: f64,
34 },
35
36 /// The request was permanently rejected (400, 404, 422) and will never be
37 /// retried. The affected batch is dropped by the flush layer.
38 #[error("Permanent client error {status_code}: {detail}")]
39 Permanent {
40 /// HTTP status code that triggered the rejection.
41 status_code: u16,
42 /// Truncated response body describing the rejection.
43 detail: String,
44 },
45
46 /// The request body exceeded the server payload cap (413).
47 #[error("Payload too large (413): {detail}")]
48 PayloadTooLarge {
49 /// Truncated response body describing the limit.
50 detail: String,
51 },
52
53 /// A non-permanent transport-level failure (network, timeout, 5xx,
54 /// authentication, circuit breaker open, unparseable response, ...).
55 #[error("{0}")]
56 Transport(String),
57
58 /// A payload could not be serialized.
59 #[error("Serialization error: {0}")]
60 Serialization(#[from] serde_json::Error),
61
62 /// A Redis persistence operation failed.
63 #[error("Redis error: {0}")]
64 Redis(String),
65
66 /// An encryption operation failed (mirrors the Python `EncryptionError`).
67 #[error("{0}")]
68 Encryption(String),
69
70 /// Encryption initialization failed; plaintext fallback is forbidden
71 /// (mirrors the Python `EncryptionConfigError`).
72 #[error("{0}")]
73 EncryptionConfig(String),
74}
75
76/// Validation failure report for [`AgentConfig`](crate::AgentConfig).
77///
78/// Collects every problem found instead of stopping at the first one, so a
79/// caller can fix the whole configuration in one pass.
80#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
81#[error("Invalid agent configuration: {}", problems.join("; "))]
82pub struct ConfigError {
83 /// Individual problems found, in field order.
84 pub problems: Vec<String>,
85}
86
87/// Stage identifiers passed to the optional `on_error` hook.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
89pub enum ErrorStage {
90 /// A transport send failed after exhausting retries, or a batch was
91 /// permanently dropped, or a payload could not be serialized.
92 TransportSend,
93 /// An events flush failed and the batch was requeued.
94 FlushEvents,
95 /// A metrics flush failed and the batch was requeued.
96 FlushMetrics,
97 /// An encryption step failed (key setup or payload encryption).
98 Encryption,
99}
100
101impl fmt::Display for ErrorStage {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 let label = match self {
104 Self::TransportSend => "transport_send",
105 Self::FlushEvents => "flush_events",
106 Self::FlushMetrics => "flush_metrics",
107 Self::Encryption => "encryption",
108 };
109 f.write_str(label)
110 }
111}
112
113#[cfg(test)]
114mod tests {
115 use super::*;
116
117 #[test]
118 fn config_error_joins_problems() {
119 let err = ConfigError {
120 problems: vec![
121 "api_key must be at least 10 characters long".into(),
122 "buffer_size must be greater than 0".into(),
123 ],
124 };
125 assert_eq!(
126 err.to_string(),
127 "Invalid agent configuration: api_key must be at least 10 characters long; \
128 buffer_size must be greater than 0"
129 );
130 }
131
132 #[test]
133 fn error_stage_labels_match_python_stages() {
134 assert_eq!(ErrorStage::TransportSend.to_string(), "transport_send");
135 assert_eq!(ErrorStage::FlushEvents.to_string(), "flush_events");
136 assert_eq!(ErrorStage::FlushMetrics.to_string(), "flush_metrics");
137 assert_eq!(ErrorStage::Encryption.to_string(), "encryption");
138 }
139
140 #[test]
141 fn error_messages_are_stable() {
142 let rate = GuardAgentError::RateLimited {
143 retry_after_seconds: 42.0,
144 };
145 assert_eq!(rate.to_string(), "Rate limited (429); retry after 42s");
146
147 let perm = GuardAgentError::Permanent {
148 status_code: 400,
149 detail: "bad request".into(),
150 };
151 assert_eq!(perm.to_string(), "Permanent client error 400: bad request");
152
153 let full = GuardAgentError::BufferFull { capacity: 10 };
154 assert_eq!(
155 full.to_string(),
156 "Buffer full at capacity 10 and buffer_overflow_policy='raise'"
157 );
158 }
159}