Skip to main content

ap_client/
memory_connection_store.rs

1use std::collections::HashMap;
2
3use ap_proxy_protocol::IdentityFingerprint;
4use async_trait::async_trait;
5
6use crate::error::ClientError;
7use crate::traits::{ConnectionInfo, ConnectionStore, ConnectionUpdate};
8
9/// In-memory connection store that does not persist to disk.
10///
11/// Used for ephemeral connections where the connection should not be saved.
12pub struct MemoryConnectionStore {
13    connections: HashMap<IdentityFingerprint, ConnectionInfo>,
14}
15
16impl MemoryConnectionStore {
17    pub fn new() -> Self {
18        Self {
19            connections: HashMap::new(),
20        }
21    }
22
23    /// Clear all cached connections.
24    pub fn clear(&mut self) {
25        self.connections.clear();
26    }
27}
28
29impl Default for MemoryConnectionStore {
30    fn default() -> Self {
31        Self::new()
32    }
33}
34
35#[async_trait]
36impl ConnectionStore for MemoryConnectionStore {
37    async fn get(&self, fingerprint: &IdentityFingerprint) -> Option<ConnectionInfo> {
38        self.connections.get(fingerprint).cloned()
39    }
40
41    async fn save(&mut self, connection: ConnectionInfo) -> Result<(), ClientError> {
42        self.connections.insert(connection.fingerprint, connection);
43        Ok(())
44    }
45
46    async fn update(&mut self, update: ConnectionUpdate) -> Result<(), ClientError> {
47        if let Some(connection) = self.connections.get_mut(&update.fingerprint) {
48            connection.last_connected_at = update.last_connected_at;
49            Ok(())
50        } else {
51            Err(ClientError::ConnectionCache(
52                "Connection not found".to_string(),
53            ))
54        }
55    }
56
57    async fn list(&self) -> Vec<ConnectionInfo> {
58        self.connections.values().cloned().collect()
59    }
60}