Skip to main content

adk_session/
consent_gate.rs

1//! A session service that writes nothing lasting for a subject without its consent.
2
3use std::sync::Arc;
4
5use adk_core::identity::AdkIdentity;
6use adk_core::principal::SubjectRef;
7use adk_core::subject::{ConsentGate, ConsentPurpose, consent_required_error};
8use adk_core::{KEY_PREFIX_USER, Result};
9use async_trait::async_trait;
10use serde_json::Value;
11
12use crate::Event;
13use crate::history::{
14    HistoryEdit, HistoryOutcome, HistoryRewrite, ImportSessionRequest, RewriteHistoryRequest,
15    SessionHistory,
16};
17use crate::inmemory::InMemorySessionService;
18use crate::service::{
19    AppendEventRequest, CreateRequest, DeleteRequest, GetRequest, ListRequest, SessionService,
20};
21use crate::session::Session;
22
23/// A [`SessionService`] that keeps a gated subject's conversation out of durable storage
24/// until the subject consents.
25///
26/// For a user the [`ConsentGate`] gates — a visitor id by default:
27///
28/// | Purpose | With live consent | Without |
29/// |---------|-------------------|---------|
30/// | [`SessionContinuity`](ConsentPurpose::SessionContinuity) | New sessions go to the durable service | New sessions live in process memory and end with the process; appending to a durable session fails with `consent.required` |
31/// | [`PersistentProfile`](ConsentPurpose::PersistentProfile) | `user:` keys are written | `user:` keys are dropped from created state and event deltas |
32///
33/// A subject being erased can create nothing and append nothing (`subject.erasing`). Reads
34/// and deletes reach both stores, so a conversation started before consent continues where
35/// it began, and erasure finds it. Users the gate does not gate pass straight through.
36///
37/// [`append_event_for_identity`](SessionService::append_event_for_identity) applies the
38/// gate; the identity-less [`append_event`](SessionService::append_event) names no user, so
39/// it appends to whichever store holds the session without dropping `user:` keys. The
40/// runner uses the identity form.
41///
42/// # Example
43///
44/// ```rust
45/// use std::sync::Arc;
46/// use adk_core::subject::{ConsentGate, InMemoryConsentStore, VisitorId};
47/// use adk_session::{ConsentGatedSessionService, CreateRequest, InMemorySessionService, SessionService};
48/// use serde_json::json;
49///
50/// # #[tokio::main(flavor = "current_thread")]
51/// # async fn main() -> adk_core::Result<()> {
52/// let durable = Arc::new(InMemorySessionService::new());
53/// let gate = ConsentGate::new(Arc::new(InMemoryConsentStore::new()));
54/// let sessions = ConsentGatedSessionService::new(durable.clone(), gate);
55///
56/// let visitor = VisitorId::generate();
57/// let session = sessions
58///     .create(CreateRequest {
59///         app_name: "shop".into(),
60///         user_id: visitor.to_string(),
61///         session_id: None,
62///         state: [("user:name".to_string(), json!("Wanjiru"))].into(),
63///     })
64///     .await?;
65/// assert!(session.state().get("user:name").is_none(), "no profile consent");
66/// let listed = durable
67///     .list(adk_session::ListRequest { app_name: "shop".into(), user_id: visitor.to_string(), limit: None, offset: None })
68///     .await?;
69/// assert!(listed.is_empty(), "no continuity consent: nothing durable");
70/// # Ok(())
71/// # }
72/// ```
73pub struct ConsentGatedSessionService {
74    durable: Arc<dyn SessionService>,
75    ephemeral: Arc<dyn SessionService>,
76    gate: ConsentGate,
77}
78
79impl std::fmt::Debug for ConsentGatedSessionService {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        f.debug_struct("ConsentGatedSessionService")
82            .field("gate", &self.gate)
83            .finish_non_exhaustive()
84    }
85}
86
87impl ConsentGatedSessionService {
88    /// Gates `durable` with `gate`, keeping unconsented sessions in process memory.
89    pub fn new(durable: Arc<dyn SessionService>, gate: ConsentGate) -> Self {
90        Self { durable, ephemeral: Arc::new(InMemorySessionService::new()), gate }
91    }
92
93    /// Keeps unconsented sessions in `ephemeral` instead of process memory, such as a
94    /// store whose records expire.
95    #[must_use]
96    pub fn with_ephemeral(mut self, ephemeral: Arc<dyn SessionService>) -> Self {
97        self.ephemeral = ephemeral;
98        self
99    }
100
101    /// The gated subject `user_id` names, after checking it may be written.
102    async fn writable(&self, user_id: &str) -> Result<Option<SubjectRef>> {
103        let Some(subject) = self.gate.subject_of(user_id) else { return Ok(None) };
104        self.gate.ensure_writable(&subject).await?;
105        Ok(Some(subject))
106    }
107
108    /// Drops `user:` keys from `state` unless `subject` consents to a persistent profile.
109    async fn profile_filter(
110        &self,
111        subject: &SubjectRef,
112        state: &mut std::collections::HashMap<String, Value>,
113    ) -> Result<()> {
114        if self.gate.permits(subject, &ConsentPurpose::PersistentProfile).await? {
115            return Ok(());
116        }
117        let before = state.len();
118        state.retain(|key, _| !key.starts_with(KEY_PREFIX_USER));
119        if state.len() != before {
120            tracing::warn!(
121                subject.kind = %subject.kind,
122                state.dropped = before - state.len(),
123                "user: state not written without consent for a persistent profile"
124            );
125        }
126        Ok(())
127    }
128
129    /// The store that holds the session `identity`: the durable one, else the ephemeral one.
130    async fn holder(&self, identity: &AdkIdentity) -> Result<&Arc<dyn SessionService>> {
131        match self.durable.get_for_identity(identity).await {
132            Ok(_) => Ok(&self.durable),
133            Err(error) if error.is_not_found() => Ok(&self.ephemeral),
134            Err(error) => Err(error),
135        }
136    }
137}
138
139#[async_trait]
140impl SessionService for ConsentGatedSessionService {
141    async fn create(&self, mut req: CreateRequest) -> Result<Box<dyn Session>> {
142        let Some(subject) = self.writable(&req.user_id).await? else {
143            return self.durable.create(req).await;
144        };
145        self.profile_filter(&subject, &mut req.state).await?;
146        if self.gate.permits(&subject, &ConsentPurpose::SessionContinuity).await? {
147            self.durable.create(req).await
148        } else {
149            self.ephemeral.create(req).await
150        }
151    }
152
153    async fn get(&self, req: GetRequest) -> Result<Box<dyn Session>> {
154        if self.gate.subject_of(&req.user_id).is_none() {
155            return self.durable.get(req).await;
156        }
157        match self.durable.get(req.clone()).await {
158            Err(error) if error.is_not_found() => self.ephemeral.get(req).await,
159            found => found,
160        }
161    }
162
163    async fn list(&self, req: ListRequest) -> Result<Vec<Box<dyn Session>>> {
164        if self.gate.subject_of(&req.user_id).is_none() {
165            return self.durable.list(req).await;
166        }
167        let all = ListRequest { limit: None, offset: None, ..req.clone() };
168        let mut sessions = self.durable.list(all.clone()).await?;
169        sessions.extend(self.ephemeral.list(all).await?);
170        sessions.sort_by(|a, b| {
171            b.last_update_time().cmp(&a.last_update_time()).then_with(|| b.id().cmp(a.id()))
172        });
173        let offset = req.offset.unwrap_or(0);
174        Ok(sessions.into_iter().skip(offset).take(req.limit.unwrap_or(usize::MAX)).collect())
175    }
176
177    async fn delete(&self, req: DeleteRequest) -> Result<()> {
178        if self.gate.subject_of(&req.user_id).is_some() {
179            self.ephemeral.delete(req.clone()).await?;
180        }
181        self.durable.delete(req).await
182    }
183
184    async fn append_event(&self, session_id: &str, event: Event) -> Result<()> {
185        match self.durable.append_event(session_id, event.clone()).await {
186            Err(error) if error.is_not_found() => {
187                self.ephemeral.append_event(session_id, event).await
188            }
189            appended => appended,
190        }
191    }
192
193    async fn append_event_for_identity(&self, mut req: AppendEventRequest) -> Result<()> {
194        let Some(subject) = self.writable(req.identity.user_id.as_ref()).await? else {
195            return self.durable.append_event_for_identity(req).await;
196        };
197        self.profile_filter(&subject, &mut req.event.actions.state_delta).await?;
198        let holder = self.holder(&req.identity).await?;
199        if Arc::ptr_eq(holder, &self.durable)
200            && !self.gate.permits(&subject, &ConsentPurpose::SessionContinuity).await?
201        {
202            return Err(consent_required_error(&ConsentPurpose::SessionContinuity));
203        }
204        holder.append_event_for_identity(req).await
205    }
206
207    async fn delete_all_sessions(&self, app_name: &str, user_id: &str) -> Result<()> {
208        if self.gate.subject_of(user_id).is_some() {
209            self.ephemeral.delete_all_sessions(app_name, user_id).await?;
210        }
211        self.durable.delete_all_sessions(app_name, user_id).await
212    }
213
214    async fn history(&self, identity: &AdkIdentity) -> Result<SessionHistory> {
215        self.holder(identity).await?.history(identity).await
216    }
217
218    async fn rewrite_history(&self, mut req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
219        if let Some(subject) = self.writable(req.identity.user_id.as_ref()).await?
220            && let HistoryRewrite::Edit { edits } = &mut req.rewrite
221        {
222            for edit in edits {
223                if let HistoryEdit::Replace { event } = edit {
224                    self.profile_filter(&subject, &mut event.actions.state_delta).await?;
225                }
226            }
227        }
228        self.holder(&req.identity).await?.rewrite_history(req).await
229    }
230
231    /// Routes the new session as [`create`](SessionService::create) does.
232    async fn import_session(&self, mut req: ImportSessionRequest) -> Result<Box<dyn Session>> {
233        let Some(subject) = self.writable(req.identity.user_id.as_ref()).await? else {
234            return self.durable.import_session(req).await;
235        };
236        for event in &mut req.events {
237            self.profile_filter(&subject, &mut event.actions.state_delta).await?;
238        }
239        if self.gate.permits(&subject, &ConsentPurpose::SessionContinuity).await? {
240            self.durable.import_session(req).await
241        } else {
242            self.ephemeral.import_session(req).await
243        }
244    }
245
246    async fn health_check(&self) -> Result<()> {
247        self.durable.health_check().await
248    }
249}