Skip to main content

adk_kernel/channels/
memory.rs

1//! The in-memory [`ChannelBindingStore`] (spec 3.3 §10 K1).
2
3use std::collections::BTreeMap;
4
5use async_trait::async_trait;
6use chrono::{DateTime, Utc};
7use tokio::sync::RwLock;
8
9use super::{ChannelBinding, ChannelBindingStore, ChannelPairingRequest};
10use crate::error::Result;
11
12/// A [`ChannelBindingStore`] in process memory, for tests and a kernel with no durable store
13/// (spec 3.3 §10 K1). Its pairings end with the process.
14///
15/// # Example
16///
17/// ```rust
18/// use adk_kernel::channels::{ChannelBinding, ChannelBindingStore, InMemoryChannelBindingStore};
19///
20/// # #[tokio::main(flavor = "current_thread")]
21/// # async fn main() -> adk_kernel::Result<()> {
22/// let store = InMemoryChannelBindingStore::new();
23/// let binding = ChannelBinding::new("telegram", "4217", "4217", "ana", chrono::Utc::now());
24/// store.put_binding(binding.clone()).await?;
25/// assert_eq!(store.get_binding(&binding.id).await?, Some(binding));
26/// # Ok(())
27/// # }
28/// ```
29#[derive(Debug, Default)]
30pub struct InMemoryChannelBindingStore {
31    bindings: RwLock<BTreeMap<String, ChannelBinding>>,
32    requests: RwLock<BTreeMap<(String, String), ChannelPairingRequest>>,
33}
34
35impl InMemoryChannelBindingStore {
36    /// An empty store.
37    pub fn new() -> Self {
38        Self::default()
39    }
40}
41
42#[async_trait]
43impl ChannelBindingStore for InMemoryChannelBindingStore {
44    async fn put_binding(&self, binding: ChannelBinding) -> Result<()> {
45        self.bindings.write().await.insert(binding.id.clone(), binding);
46        Ok(())
47    }
48
49    async fn get_binding(&self, id: &str) -> Result<Option<ChannelBinding>> {
50        Ok(self.bindings.read().await.get(id).cloned())
51    }
52
53    async fn list_bindings(&self) -> Result<Vec<ChannelBinding>> {
54        let mut bindings: Vec<_> = self.bindings.read().await.values().cloned().collect();
55        bindings.sort_by(|a, b| a.paired_at.cmp(&b.paired_at).then_with(|| a.id.cmp(&b.id)));
56        Ok(bindings)
57    }
58
59    async fn put_request(&self, request: ChannelPairingRequest) -> Result<()> {
60        let key = (request.channel.clone(), request.account.clone());
61        self.requests.write().await.insert(key, request);
62        Ok(())
63    }
64
65    async fn get_request(
66        &self,
67        channel: &str,
68        account: &str,
69    ) -> Result<Option<ChannelPairingRequest>> {
70        Ok(self.requests.read().await.get(&(channel.to_string(), account.to_string())).cloned())
71    }
72
73    async fn take_request(&self, code_hash: &str) -> Result<Option<ChannelPairingRequest>> {
74        let mut requests = self.requests.write().await;
75        let key = requests
76            .iter()
77            .find(|(_, request)| request.code_hash == code_hash)
78            .map(|(key, _)| key.clone());
79        Ok(key.and_then(|key| requests.remove(&key)))
80    }
81
82    async fn list_requests(&self) -> Result<Vec<ChannelPairingRequest>> {
83        let mut requests: Vec<_> = self.requests.read().await.values().cloned().collect();
84        requests.sort_by(|a, b| {
85            (a.requested_at, &a.channel, &a.account).cmp(&(b.requested_at, &b.channel, &b.account))
86        });
87        Ok(requests)
88    }
89
90    async fn prune_requests(&self, before: DateTime<Utc>) -> Result<usize> {
91        let mut requests = self.requests.write().await;
92        let count = requests.len();
93        requests.retain(|_, request| request.expires_at > before);
94        Ok(count - requests.len())
95    }
96}