Skip to main content

aa_storage_memory/
lifecycle_store.rs

1//! In-memory [`LifecycleStore`] backed by a `DashMap`.
2
3use std::sync::Arc;
4use std::time::Instant;
5
6use aa_storage::{AgentId, LifecycleStore, Result, StorageError};
7use async_trait::async_trait;
8use dashmap::DashMap;
9
10/// A `DashMap`-backed [`LifecycleStore`] mapping a registered agent to the
11/// instant of its last heartbeat. Cloning shares the same underlying map.
12#[derive(Clone, Default)]
13pub struct MemoryLifecycleStore {
14    agents: Arc<DashMap<[u8; 16], Instant>>,
15}
16
17impl MemoryLifecycleStore {
18    /// Create an empty store.
19    pub fn new() -> Self {
20        Self::default()
21    }
22}
23
24#[async_trait]
25impl LifecycleStore for MemoryLifecycleStore {
26    async fn register(&self, agent_id: &AgentId) -> Result<()> {
27        self.agents.insert(*agent_id.as_bytes(), Instant::now());
28        Ok(())
29    }
30
31    async fn heartbeat(&self, agent_id: &AgentId) -> Result<()> {
32        match self.agents.get_mut(agent_id.as_bytes()) {
33            Some(mut entry) => {
34                *entry = Instant::now();
35                Ok(())
36            }
37            None => Err(StorageError::NotFound(format!("agent {:?}", agent_id.as_bytes()))),
38        }
39    }
40
41    async fn deregister(&self, agent_id: &AgentId) -> Result<()> {
42        self.agents.remove(agent_id.as_bytes());
43        Ok(())
44    }
45}