Skip to main content

adk_kernel/pairing/
memory.rs

1//! The in-memory [`DeviceStore`] (spec 3.3 §10 K2).
2
3use std::collections::BTreeMap;
4use std::sync::atomic::{AtomicU64, Ordering};
5
6use async_trait::async_trait;
7use chrono::{DateTime, Utc};
8use tokio::sync::RwLock;
9
10use super::{AttachmentHolder, DeviceAttachment, DeviceRecord, DeviceStore, PairingCode};
11use crate::error::Result;
12
13/// A [`DeviceStore`] in process memory, for tests and a kernel with no durable store (spec
14/// 3.3 §10 K2). Its devices end with the process, so they must pair again after a restart.
15///
16/// # Example
17///
18/// ```rust
19/// use std::sync::Arc;
20/// use adk_kernel::pairing::{InMemoryDeviceStore, IssueCode, Pairing};
21///
22/// # #[tokio::main(flavor = "current_thread")]
23/// # async fn main() -> adk_kernel::Result<()> {
24/// let pairing = Pairing::new(Arc::new(InMemoryDeviceStore::new()));
25/// let issued = pairing.issue(IssueCode::new("ana", ["operator"])).await?;
26/// pairing.claim(&issued.code, Some("Ana's phone")).await?;
27/// assert_eq!(pairing.devices().await?.len(), 1);
28/// # Ok(())
29/// # }
30/// ```
31#[derive(Debug, Default)]
32pub struct InMemoryDeviceStore {
33    codes: RwLock<BTreeMap<String, PairingCode>>,
34    devices: RwLock<BTreeMap<String, DeviceRecord>>,
35    attempts: AtomicU64,
36    attachments: RwLock<BTreeMap<(AttachmentHolder, String, String), DeviceAttachment>>,
37}
38
39impl InMemoryDeviceStore {
40    /// An empty store.
41    pub fn new() -> Self {
42        Self::default()
43    }
44}
45
46#[async_trait]
47impl DeviceStore for InMemoryDeviceStore {
48    async fn put_code(&self, code: PairingCode) -> Result<()> {
49        self.codes.write().await.insert(code.code_hash.clone(), code);
50        Ok(())
51    }
52
53    async fn take_code(&self, code_hash: &str) -> Result<Option<PairingCode>> {
54        Ok(self.codes.write().await.remove(code_hash))
55    }
56
57    async fn prune_codes(&self, before: DateTime<Utc>) -> Result<usize> {
58        let mut codes = self.codes.write().await;
59        let count = codes.len();
60        codes.retain(|_, code| code.expires_at > before);
61        Ok(count - codes.len())
62    }
63
64    async fn clear_codes(&self) -> Result<usize> {
65        let mut codes = self.codes.write().await;
66        let count = codes.len();
67        codes.clear();
68        Ok(count)
69    }
70
71    async fn put_device(&self, device: DeviceRecord) -> Result<()> {
72        self.devices.write().await.insert(device.id.clone(), device);
73        Ok(())
74    }
75
76    async fn get_device(&self, id: &str) -> Result<Option<DeviceRecord>> {
77        Ok(self.devices.read().await.get(id).cloned())
78    }
79
80    async fn list_devices(&self) -> Result<Vec<DeviceRecord>> {
81        let mut devices: Vec<DeviceRecord> = self.devices.read().await.values().cloned().collect();
82        devices.sort_by(|a, b| a.created_at.cmp(&b.created_at).then_with(|| a.id.cmp(&b.id)));
83        Ok(devices)
84    }
85
86    async fn count_claim_attempt(&self) -> Result<u64> {
87        Ok(self.attempts.fetch_add(1, Ordering::SeqCst) + 1)
88    }
89
90    async fn reset_claim_attempts(&self) -> Result<()> {
91        self.attempts.store(0, Ordering::SeqCst);
92        Ok(())
93    }
94
95    async fn put_attachment(&self, attachment: DeviceAttachment) -> Result<()> {
96        let key = (attachment.holder.clone(), attachment.kind.clone(), attachment.key.clone());
97        self.attachments.write().await.insert(key, attachment);
98        Ok(())
99    }
100
101    async fn put_attachment_if_absent(&self, attachment: DeviceAttachment) -> Result<bool> {
102        let key = (attachment.holder.clone(), attachment.kind.clone(), attachment.key.clone());
103        let mut attachments = self.attachments.write().await;
104        if attachments.contains_key(&key) {
105            return Ok(false);
106        }
107        attachments.insert(key, attachment);
108        Ok(true)
109    }
110
111    async fn attachments(
112        &self,
113        holder: &AttachmentHolder,
114        kind: &str,
115    ) -> Result<Vec<DeviceAttachment>> {
116        Ok(self
117            .attachments
118            .read()
119            .await
120            .values()
121            .filter(|attachment| &attachment.holder == holder && attachment.kind == kind)
122            .cloned()
123            .collect())
124    }
125
126    async fn remove_attachment(
127        &self,
128        holder: &AttachmentHolder,
129        kind: &str,
130        key: &str,
131    ) -> Result<bool> {
132        let key = (holder.clone(), kind.to_string(), key.to_string());
133        Ok(self.attachments.write().await.remove(&key).is_some())
134    }
135
136    async fn remove_attachments(&self, holder: &AttachmentHolder) -> Result<usize> {
137        let mut attachments = self.attachments.write().await;
138        let count = attachments.len();
139        attachments.retain(|(owner, _, _), _| owner != holder);
140        Ok(count - attachments.len())
141    }
142}