guard-agent-rs 3.2.2

Telemetry and monitoring agent for the Guard ecosystem (Rust).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! Optional buffer persistence.
//!
//! Every accepted event and metric can be written to a durable store before it
//! is buffered, so a process crash does not lose telemetry that the ingestion
//! API never acknowledged. The handshake is at-least-once: records are written
//! on enqueue, deleted only after the server confirms the batch, and reloaded
//! into the in-memory buffer on startup.
//!
//! Persistence is fail-open. Any store error increments
//! `redis_persist_failures` (surfaced through
//! [`AgentStats`](crate::AgentStats)), logs a warning, and leaves the event in
//! memory; it never blocks or fails a `send_*` call.
//!
//! Two backends ship in the crate:
//!
//! - [`InMemoryRedisStore`], always available, useful for tests and for
//!   embedding.
//! - `RedisClientHandler`, behind the `persistence` feature, wrapping the
//!   `redis` crate's multiplexed async connection.
//!
//! Callers may also implement [`RedisHandler`] themselves and attach it with
//! [`GuardAgent::attach_redis_handler`](crate::GuardAgent::attach_redis_handler),
//! mirroring the Python agent's injected handler protocol.

use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, Instant};

use crate::error::GuardAgentError;
use async_trait::async_trait;

/// Namespace for persisted events.
pub const NAMESPACE_EVENTS: &str = "agent_events";

/// Namespace for persisted metrics.
pub const NAMESPACE_METRICS: &str = "agent_metrics";

/// TTL applied to every persisted record, in seconds.
pub const PERSIST_TTL_SECONDS: u64 = 3600;

/// Durable store used by the agent for buffer persistence.
///
/// Implementations receive a namespace ([`NAMESPACE_EVENTS`] or
/// [`NAMESPACE_METRICS`]) and a short record key. Keys returned by
/// [`list_keys`](RedisHandler::list_keys) must be the short keys, without any
/// prefix the implementation adds internally.
#[async_trait]
pub trait RedisHandler: Send + Sync + 'static {
    /// Stores `value` under `key`, expiring after `ttl_seconds`.
    async fn set_key(
        &self,
        namespace: &str,
        key: &str,
        value: &str,
        ttl_seconds: u64,
    ) -> Result<(), GuardAgentError>;

    /// Loads a record, returning `None` when it is missing or expired.
    async fn get_key(&self, namespace: &str, key: &str) -> Result<Option<String>, GuardAgentError>;

    /// Deletes the given records. Missing keys are ignored.
    async fn delete_keys(&self, namespace: &str, keys: &[String]) -> Result<(), GuardAgentError>;

    /// Lists the short keys currently stored in `namespace`.
    async fn list_keys(&self, namespace: &str) -> Result<Vec<String>, GuardAgentError>;

    /// Deletes every record in `namespace`.
    async fn clear_namespace(&self, namespace: &str) -> Result<(), GuardAgentError>;
}

fn namespaced_key(namespace: &str, key: &str) -> String {
    format!("{namespace}:{key}")
}

#[derive(Debug)]
struct Entry {
    value: String,
    expires_at: Option<Instant>,
}

impl Entry {
    fn is_expired(&self, now: Instant) -> bool {
        self.expires_at.is_some_and(|expires_at| now >= expires_at)
    }
}

/// In-memory [`RedisHandler`] with lazy TTL expiry.
///
/// Intended for tests and embedded use. It is not shared across processes, so
/// it only protects against failures within a single agent lifetime.
#[derive(Debug, Default)]
pub struct InMemoryRedisStore {
    entries: Mutex<HashMap<String, Entry>>,
}

impl InMemoryRedisStore {
    /// Creates an empty store.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns the number of live (non-expired) records.
    #[must_use]
    pub fn len(&self) -> usize {
        let now = Instant::now();
        let mut entries = self.entries.lock().expect("store mutex not poisoned");
        entries.retain(|_, entry| !entry.is_expired(now));
        entries.len()
    }

    /// Returns `true` when no live records are stored.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns the value stored under `namespace:key`, ignoring expiry.
    ///
    /// Useful in tests that assert retained records regardless of TTL.
    #[must_use]
    pub fn peek(&self, namespace: &str, key: &str) -> Option<String> {
        let entries = self.entries.lock().expect("store mutex not poisoned");
        entries
            .get(&namespaced_key(namespace, key))
            .map(|entry| entry.value.clone())
    }

    /// Returns every short key stored in `namespace`, including expired ones.
    #[must_use]
    pub fn keys(&self, namespace: &str) -> Vec<String> {
        let prefix = format!("{namespace}:");
        let entries = self.entries.lock().expect("store mutex not poisoned");
        let mut keys: Vec<String> = entries
            .keys()
            .filter_map(|key| key.strip_prefix(&prefix).map(str::to_owned))
            .collect();
        keys.sort();
        keys
    }
}

#[async_trait]
impl RedisHandler for InMemoryRedisStore {
    async fn set_key(
        &self,
        namespace: &str,
        key: &str,
        value: &str,
        ttl_seconds: u64,
    ) -> Result<(), GuardAgentError> {
        let expires_at = if ttl_seconds == 0 {
            None
        } else {
            Some(Instant::now() + Duration::from_secs(ttl_seconds))
        };
        let mut entries = self.entries.lock().expect("store mutex not poisoned");
        entries.insert(
            namespaced_key(namespace, key),
            Entry {
                value: value.to_owned(),
                expires_at,
            },
        );
        Ok(())
    }

    async fn get_key(&self, namespace: &str, key: &str) -> Result<Option<String>, GuardAgentError> {
        let now = Instant::now();
        let full_key = namespaced_key(namespace, key);
        let mut entries = self.entries.lock().expect("store mutex not poisoned");
        if entries
            .get(&full_key)
            .is_some_and(|entry| entry.is_expired(now))
        {
            entries.remove(&full_key);
        }
        Ok(entries.get(&full_key).map(|entry| entry.value.clone()))
    }

    async fn delete_keys(&self, namespace: &str, keys: &[String]) -> Result<(), GuardAgentError> {
        let mut entries = self.entries.lock().expect("store mutex not poisoned");
        for key in keys {
            entries.remove(&namespaced_key(namespace, key));
        }
        Ok(())
    }

    async fn list_keys(&self, namespace: &str) -> Result<Vec<String>, GuardAgentError> {
        let now = Instant::now();
        let prefix = format!("{namespace}:");
        let mut entries = self.entries.lock().expect("store mutex not poisoned");
        entries.retain(|_, entry| !entry.is_expired(now));
        let mut keys: Vec<String> = entries
            .keys()
            .filter_map(|key| key.strip_prefix(&prefix).map(str::to_owned))
            .collect();
        keys.sort();
        Ok(keys)
    }

    async fn clear_namespace(&self, namespace: &str) -> Result<(), GuardAgentError> {
        let prefix = format!("{namespace}:");
        let mut entries = self.entries.lock().expect("store mutex not poisoned");
        entries.retain(|key, _| !key.starts_with(&prefix));
        Ok(())
    }
}

/// [`RedisHandler`] backed by the `redis` crate.
///
/// Keys are composed as `<key_prefix>:<namespace>:<key>` and the record value
/// is the compact JSON wire form of the event or metric.
#[cfg(feature = "persistence")]
#[derive(Debug, Clone)]
pub struct RedisClientHandler {
    connection: redis::aio::MultiplexedConnection,
    key_prefix: String,
    command_timeout: Duration,
}

#[cfg(feature = "persistence")]
impl RedisClientHandler {
    /// Connects to Redis using [`RedisConfig`](crate::RedisConfig).
    ///
    /// The connection is established eagerly so a misconfigured or unreachable
    /// server surfaces at startup, where the agent can degrade to memory-only
    /// operation with a single warning.
    pub async fn connect(config: &crate::config::RedisConfig) -> Result<Self, GuardAgentError> {
        let client = redis::Client::open(config.url.as_str())
            .map_err(|error| GuardAgentError::Redis(error.to_string()))?;
        let connection = client
            .get_multiplexed_async_connection()
            .await
            .map_err(|error| GuardAgentError::Redis(error.to_string()))?;
        Ok(Self {
            connection,
            key_prefix: config.key_prefix.clone(),
            command_timeout: Duration::from_millis(config.command_timeout_ms),
        })
    }

    fn full_key(&self, namespace: &str, key: &str) -> String {
        format!("{}:{namespace}:{key}", self.key_prefix)
    }

    async fn query<T: redis::FromRedisValue>(
        &self,
        cmd: &redis::Cmd,
    ) -> Result<T, GuardAgentError> {
        let mut connection = self.connection.clone();
        let pending = cmd.query_async::<T>(&mut connection);
        tokio::time::timeout(self.command_timeout, pending)
            .await
            .map_err(|_| GuardAgentError::Redis("command timed out".to_owned()))?
            .map_err(|error| GuardAgentError::Redis(error.to_string()))
    }
}

#[cfg(feature = "persistence")]
#[async_trait]
impl RedisHandler for RedisClientHandler {
    async fn set_key(
        &self,
        namespace: &str,
        key: &str,
        value: &str,
        ttl_seconds: u64,
    ) -> Result<(), GuardAgentError> {
        let mut cmd = redis::cmd("SET");
        cmd.arg(self.full_key(namespace, key))
            .arg(value)
            .arg("EX")
            .arg(ttl_seconds);
        let _: () = self.query(&cmd).await?;
        Ok(())
    }

    async fn get_key(&self, namespace: &str, key: &str) -> Result<Option<String>, GuardAgentError> {
        let mut cmd = redis::cmd("GET");
        cmd.arg(self.full_key(namespace, key));
        self.query(&cmd).await
    }

    async fn delete_keys(&self, namespace: &str, keys: &[String]) -> Result<(), GuardAgentError> {
        if keys.is_empty() {
            return Ok(());
        }
        let mut cmd = redis::cmd("DEL");
        for key in keys {
            cmd.arg(self.full_key(namespace, key));
        }
        let _: () = self.query(&cmd).await?;
        Ok(())
    }

    async fn list_keys(&self, namespace: &str) -> Result<Vec<String>, GuardAgentError> {
        let prefix = format!("{}:{namespace}:", self.key_prefix);
        let mut cmd = redis::cmd("KEYS");
        cmd.arg(format!("{prefix}*"));
        let full_keys: Vec<String> = self.query(&cmd).await?;
        let mut short_keys: Vec<String> = full_keys
            .iter()
            .filter_map(|key| key.strip_prefix(&prefix).map(str::to_owned))
            .collect();
        short_keys.sort();
        Ok(short_keys)
    }

    async fn clear_namespace(&self, namespace: &str) -> Result<(), GuardAgentError> {
        let keys = self.list_keys(namespace).await?;
        self.delete_keys(namespace, &keys).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The malformed URL fails at `redis::Client::open` before any I/O.
    #[cfg(feature = "persistence")]
    #[tokio::test]
    async fn connect_rejects_malformed_urls_without_io() {
        let config = crate::config::RedisConfig {
            url: "not-a-redis-url".to_owned(),
            key_prefix: "guard".to_owned(),
            command_timeout_ms: 1_000,
        };
        let outcome = RedisClientHandler::connect(&config).await;
        assert!(matches!(outcome, Err(GuardAgentError::Redis(_))));
    }

    /// A listener that completes the client's SETINFO handshake and then
    /// goes silent drives the first real command through its timeout arm.
    #[cfg(feature = "persistence")]
    #[tokio::test]
    async fn query_times_out_against_a_silent_server() {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            use std::io::{Read as _, Write as _};
            let (mut stream, _) = listener.accept().expect("the client connects");
            let mut buffer = [0u8; 1024];
            // Answer the best-effort SETINFO handshake (errors are ignored
            // by the client), then stop responding entirely.
            loop {
                let read = stream.read(&mut buffer).expect("socket read");
                let handshake = buffer[..read]
                    .windows(7)
                    .filter(|w| w == b"SETINFO")
                    .count();
                if handshake == 0 {
                    break;
                }
                for _ in 0..handshake {
                    let _ = stream.write_all(b"-ERR unknown command\r\n");
                }
                let _ = stream.flush();
            }
            std::thread::sleep(std::time::Duration::from_secs(10));
        });
        let config = crate::config::RedisConfig {
            url: format!("redis://{addr}"),
            key_prefix: "guard".to_owned(),
            command_timeout_ms: 50,
        };
        let handler = RedisClientHandler::connect(&config)
            .await
            .expect("the handshake completes");
        let outcome = handler.get_key(NAMESPACE_EVENTS, "slow").await;
        assert!(
            matches!(&outcome, Err(GuardAgentError::Redis(message)) if message.contains("timed out")),
            "{outcome:?}"
        );
    }

    /// A listener that answers the first real command with a RESP error
    /// surfaces that error through the query arm.
    #[cfg(feature = "persistence")]
    #[tokio::test]
    async fn query_surfaces_resp_errors_from_the_server() {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            use std::io::{Read as _, Write as _};
            let (mut stream, _) = listener.accept().expect("the client connects");
            let mut buffer = [0u8; 1024];
            loop {
                let read = stream.read(&mut buffer).expect("socket read");
                // SETINFO handshake chunks get error replies the client
                // tolerates; every later chunk (a real command) gets the
                // RESP error this test is about.
                let handshake = buffer[..read]
                    .windows(7)
                    .filter(|w| w == b"SETINFO")
                    .count();
                for _ in 0..handshake {
                    let _ = stream.write_all(b"-ERR unknown command\r\n");
                }
                if handshake == 0 {
                    let _ = stream.write_all(b"-ERR mocked failure\r\n");
                    let _ = stream.flush();
                    std::thread::sleep(std::time::Duration::from_secs(5));
                } else {
                    let _ = stream.flush();
                }
            }
        });
        let config = crate::config::RedisConfig {
            url: format!("redis://{addr}"),
            key_prefix: "guard".to_owned(),
            command_timeout_ms: 2_000,
        };
        let handler = RedisClientHandler::connect(&config)
            .await
            .expect("the handshake completes");
        let outcome = handler.get_key(NAMESPACE_EVENTS, "boom").await;
        assert!(
            matches!(outcome, Err(GuardAgentError::Redis(_))),
            "{outcome:?}"
        );
    }

    async fn stored_keys(store: &InMemoryRedisStore, namespace: &str) -> Vec<String> {
        store.list_keys(namespace).await.unwrap()
    }

    #[tokio::test]
    async fn peek_reads_stored_values_regardless_of_expiry() {
        let store = InMemoryRedisStore::new();
        store
            .set_key(
                NAMESPACE_EVENTS,
                "event_peek",
                "{\"b\":2}",
                PERSIST_TTL_SECONDS,
            )
            .await
            .unwrap();
        assert_eq!(
            store.peek(NAMESPACE_EVENTS, "event_peek").as_deref(),
            Some("{\"b\":2}")
        );
        assert_eq!(store.peek(NAMESPACE_EVENTS, "missing"), None);
    }

    #[tokio::test]
    async fn set_and_get_round_trip() {
        let store = InMemoryRedisStore::new();
        store
            .set_key(
                NAMESPACE_EVENTS,
                "event_1",
                "{\"a\":1}",
                PERSIST_TTL_SECONDS,
            )
            .await
            .unwrap();
        let loaded = store.get_key(NAMESPACE_EVENTS, "event_1").await.unwrap();
        assert_eq!(loaded.as_deref(), Some("{\"a\":1}"));
        assert!(
            store
                .get_key(NAMESPACE_EVENTS, "missing")
                .await
                .unwrap()
                .is_none()
        );
    }

    #[tokio::test]
    async fn namespaces_are_isolated() {
        let store = InMemoryRedisStore::new();
        store
            .set_key(NAMESPACE_EVENTS, "shared", "event", PERSIST_TTL_SECONDS)
            .await
            .unwrap();
        store
            .set_key(NAMESPACE_METRICS, "shared", "metric", PERSIST_TTL_SECONDS)
            .await
            .unwrap();

        assert_eq!(
            stored_keys(&store, NAMESPACE_EVENTS).await,
            vec!["shared".to_owned()]
        );
        assert_eq!(
            stored_keys(&store, NAMESPACE_METRICS).await,
            vec!["shared".to_owned()]
        );
        assert_eq!(
            store
                .get_key(NAMESPACE_EVENTS, "shared")
                .await
                .unwrap()
                .as_deref(),
            Some("event")
        );
    }

    #[tokio::test]
    async fn delete_removes_records_and_ignores_missing() {
        let store = InMemoryRedisStore::new();
        store
            .set_key(NAMESPACE_EVENTS, "a", "1", PERSIST_TTL_SECONDS)
            .await
            .unwrap();
        store
            .set_key(NAMESPACE_EVENTS, "b", "2", PERSIST_TTL_SECONDS)
            .await
            .unwrap();

        store
            .delete_keys(NAMESPACE_EVENTS, &["a".to_owned(), "missing".to_owned()])
            .await
            .unwrap();
        assert_eq!(
            stored_keys(&store, NAMESPACE_EVENTS).await,
            vec!["b".to_owned()]
        );
    }

    #[tokio::test]
    async fn clear_namespace_wipes_only_that_namespace() {
        let store = InMemoryRedisStore::new();
        store
            .set_key(NAMESPACE_EVENTS, "a", "1", PERSIST_TTL_SECONDS)
            .await
            .unwrap();
        store
            .set_key(NAMESPACE_METRICS, "b", "2", PERSIST_TTL_SECONDS)
            .await
            .unwrap();

        store.clear_namespace(NAMESPACE_EVENTS).await.unwrap();
        assert_eq!(
            stored_keys(&store, NAMESPACE_EVENTS).await,
            Vec::<String>::new()
        );
        assert_eq!(
            stored_keys(&store, NAMESPACE_METRICS).await,
            vec!["b".to_owned()]
        );
    }

    #[tokio::test]
    async fn expired_records_disappear() {
        let store = InMemoryRedisStore::new();
        store
            .set_key(NAMESPACE_EVENTS, "short_lived", "1", 1)
            .await
            .unwrap();
        assert!(
            store
                .get_key(NAMESPACE_EVENTS, "short_lived")
                .await
                .unwrap()
                .is_some()
        );

        tokio::time::sleep(Duration::from_millis(1100)).await;

        assert!(
            store
                .get_key(NAMESPACE_EVENTS, "short_lived")
                .await
                .unwrap()
                .is_none()
        );
        assert_eq!(
            stored_keys(&store, NAMESPACE_EVENTS).await,
            Vec::<String>::new()
        );
        assert_eq!(store.len(), 0);
        assert!(store.is_empty());
    }

    #[tokio::test]
    async fn ttl_zero_never_expires() {
        let store = InMemoryRedisStore::new();
        store
            .set_key(NAMESPACE_EVENTS, "forever", "1", 0)
            .await
            .unwrap();
        assert!(
            store
                .get_key(NAMESPACE_EVENTS, "forever")
                .await
                .unwrap()
                .is_some()
        );
    }

    #[test]
    fn namespaced_keys_are_prefixed() {
        assert_eq!(
            namespaced_key(NAMESPACE_EVENTS, "event_1"),
            "agent_events:event_1"
        );
    }
}