Skip to main content

adk_memory/
subject.rs

1//! Memory as a [`SubjectDataStore`] for `adk_core::subject::SubjectRights`.
2
3use std::sync::Arc;
4
5use adk_core::Result;
6use adk_core::subject::{
7    SUBJECT_UNSUPPORTED_CODE, StoreErasure, StoreSupport, SubjectDataStore, SubjectScope,
8};
9use async_trait::async_trait;
10use serde_json::{Value, json};
11
12use crate::service::MemoryService;
13
14/// Exports and erases a data subject's long-term memory through any [`MemoryService`].
15///
16/// The export lists every entry of each of the scope's user ids in each of its
17/// applications, as [`MemoryService::export_user`] returns them; the erasure calls
18/// [`MemoryService::delete_user`] for each, and counts what the export listed.
19///
20/// # Example
21///
22/// ```rust
23/// use std::sync::Arc;
24/// use adk_core::Content;
25/// use adk_core::principal::SubjectRef;
26/// use adk_core::subject::{SubjectDataStore, SubjectScope};
27/// use adk_memory::{InMemoryMemoryService, MemoryEntry, MemoryService, MemorySubjectData};
28///
29/// # #[tokio::main(flavor = "current_thread")]
30/// # async fn main() -> adk_core::Result<()> {
31/// let service = Arc::new(InMemoryMemoryService::new());
32/// let entry = MemoryEntry::new(Content::new("user").with_text("Hometown: Nairobi."), "user");
33/// service.add_session("shop", "alice", "s1", vec![entry]).await?;
34///
35/// let memory = MemorySubjectData::new(service);
36/// let scope = SubjectScope::new(["shop"], SubjectRef::human("alice"));
37/// assert_eq!(memory.erase(&scope).await?.deleted, 1);
38/// assert_eq!(memory.erase(&scope).await?.deleted, 0);
39/// # Ok(())
40/// # }
41/// ```
42#[derive(Clone)]
43pub struct MemorySubjectData {
44    service: Arc<dyn MemoryService>,
45    name: String,
46    support: StoreSupport,
47}
48
49impl MemorySubjectData {
50    /// Adapts `service`, named `memory` in reports, erasing with
51    /// [`StoreSupport::Hard`].
52    pub fn new(service: Arc<dyn MemoryService>) -> Self {
53        Self { service, name: "memory".to_string(), support: StoreSupport::Hard }
54    }
55
56    /// Sets the name reports use, for a deployment with more than one memory service.
57    #[must_use]
58    pub fn with_name(mut self, name: impl Into<String>) -> Self {
59        self.name = name.into();
60        self
61    }
62
63    /// Sets how the service erases, such as [`StoreSupport::Eventual`] for a managed
64    /// service whose deletions complete after `delete_user` returns.
65    #[must_use]
66    pub fn with_support(mut self, support: StoreSupport) -> Self {
67        self.support = support;
68        self
69    }
70}
71
72#[async_trait]
73impl SubjectDataStore for MemorySubjectData {
74    fn name(&self) -> &str {
75        &self.name
76    }
77
78    fn support(&self) -> StoreSupport {
79        self.support
80    }
81
82    async fn export(&self, scope: &SubjectScope) -> Result<Value> {
83        let mut groups = Vec::new();
84        for app_name in &scope.app_names {
85            for user_id in scope.user_ids() {
86                let entries = self.service.export_user(app_name, user_id).await?;
87                if !entries.is_empty() {
88                    groups.push(
89                        json!({ "appName": app_name, "userId": user_id, "entries": entries }),
90                    );
91                }
92            }
93        }
94        Ok(json!({ "memories": groups }))
95    }
96
97    async fn erase(&self, scope: &SubjectScope) -> Result<StoreErasure> {
98        let mut deleted = 0;
99        for app_name in &scope.app_names {
100            for user_id in scope.user_ids() {
101                // A backend that cannot list still deletes; its count is unknown.
102                deleted += match self.service.export_user(app_name, user_id).await {
103                    Ok(entries) => entries.len() as u64,
104                    Err(error) if error.code == SUBJECT_UNSUPPORTED_CODE => 0,
105                    Err(error) => return Err(error),
106                };
107                self.service.delete_user(app_name, user_id).await?;
108            }
109        }
110        Ok(StoreErasure::deleted(deleted))
111    }
112}