Skip to main content

gadk_session/
inmemory.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! An in-memory [`SessionService`].
17
18use std::collections::{BTreeMap, HashMap};
19use std::sync::Arc;
20
21use async_trait::async_trait;
22use chrono::{DateTime, Utc};
23use gadk_platform::{Platform, go_quote};
24use parking_lot::RwLock;
25use serde_json::{Map, Value};
26
27use crate::error::SessionError;
28use crate::event::{Event, zero_time};
29use crate::service::{
30    CreateRequest, DeleteRequest, GetRequest, KEY_PREFIX_APP, KEY_PREFIX_USER, ListRequest,
31    Session, SessionService, State, compare_by_last_update,
32};
33use crate::state_util::{
34    check_requested_auth_configs, extract_state_deltas, merge_states, require,
35    trim_temp_delta_state,
36};
37
38type StateMap = Map<String, Value>;
39/// `(app_name, user_id, session_id)`.
40type SessionKey = (String, String, String);
41
42/// An in-memory [`SessionService`]. Thread-safe.
43///
44/// State keys are routed by prefix: `app:` keys are shared by every session of the app,
45/// `user:` keys by every session of the user, and the rest belong to the session. `temp:`
46/// keys in appended event deltas are never persisted; `temp:` keys in the initial state given
47/// to `create` are kept in session state. Sessions handed out are copies of the service's
48/// record.
49///
50/// An event appended with an empty ID is given one:
51///
52/// ```
53/// # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async {
54/// use gadk_session::*;
55/// use std::sync::Arc;
56/// let svc: Arc<dyn SessionService> = Arc::new(InMemorySessionService::new());
57/// let s = svc.create(CreateRequest { app_name: "app".into(), user_id: "u".into(), ..Default::default() }).await.unwrap();
58/// let mut ev = Event::new(&gadk_platform::Platform::default(), "inv");
59/// ev.id.clear();
60/// svc.append_event(s.as_ref(), &mut ev).await.unwrap();
61/// assert!(!ev.id.is_empty());
62/// # });
63/// ```
64pub struct InMemorySessionService {
65    platform: Platform,
66    inner: RwLock<Inner>,
67}
68
69#[derive(Default)]
70struct Inner {
71    sessions: BTreeMap<SessionKey, StoredSession>,
72    app_state: HashMap<String, StateMap>,
73    user_state: HashMap<(String, String), StateMap>,
74}
75
76/// The service's canonical record of a session.
77struct StoredSession {
78    state: StateMap,
79    events: Vec<Event>,
80    updated_at: DateTime<Utc>,
81}
82
83impl InMemorySessionService {
84    /// A new, empty service using [`Platform::default`].
85    pub fn new() -> Self {
86        Self::with_platform(Platform::default())
87    }
88
89    /// A new, empty service taking time and session/event IDs from `platform`.
90    pub fn with_platform(platform: Platform) -> Self {
91        Self {
92            platform,
93            inner: RwLock::new(Inner::default()),
94        }
95    }
96}
97
98impl Default for InMemorySessionService {
99    fn default() -> Self {
100        Self::new()
101    }
102}
103
104impl std::fmt::Debug for InMemorySessionService {
105    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106        f.debug_struct("InMemorySessionService")
107            .finish_non_exhaustive()
108    }
109}
110
111impl Inner {
112    /// Session state plus the app and user state, prefixed back.
113    fn merged_state(&self, state: &StateMap, app_name: &str, user_id: &str) -> StateMap {
114        merge_states(
115            self.app_state.get(app_name),
116            self.user_state
117                .get(&(app_name.to_string(), user_id.to_string())),
118            state,
119        )
120    }
121
122    /// Applies a state delta to the app, user and session maps: the delta is split by key
123    /// prefix and each part is merged into its map.
124    fn apply_delta(
125        app_state: &mut HashMap<String, StateMap>,
126        user_state: &mut HashMap<(String, String), StateMap>,
127        session_state: &mut StateMap,
128        delta: &StateMap,
129        app_name: &str,
130        user_id: &str,
131    ) {
132        let (app, user, session) = extract_state_deltas(delta);
133        app_state
134            .entry(app_name.to_string())
135            .or_default()
136            .extend(app);
137        user_state
138            .entry((app_name.to_string(), user_id.to_string()))
139            .or_default()
140            .extend(user);
141        session_state.extend(session);
142    }
143}
144
145#[async_trait]
146impl SessionService for InMemorySessionService {
147    async fn create(&self, req: CreateRequest) -> Result<Arc<dyn Session>, SessionError> {
148        if req.app_name.is_empty() || req.user_id.is_empty() {
149            return Err(SessionError::InvalidRequest(format!(
150                "app_name and user_id are required, got app_name: {}, user_id: {}",
151                go_quote(&req.app_name),
152                go_quote(&req.user_id)
153            )));
154        }
155        let session_id = match req.session_id {
156            Some(id) if !id.is_empty() => id,
157            _ => self.platform.new_uuid(),
158        };
159        let key = (req.app_name, req.user_id, session_id);
160
161        let mut inner = self.inner.write();
162        if inner.sessions.contains_key(&key) {
163            return Err(SessionError::InvalidRequest(format!(
164                "session {} already exists",
165                key.2
166            )));
167        }
168
169        let Inner {
170            sessions,
171            app_state,
172            user_state,
173        } = &mut *inner;
174        // Stores the raw request state: app: and user: keys go to the shared maps (and are
175        // merged back on read), and every other key, temp: included, stays in session state.
176        // Only appended deltas are trimmed.
177        let mut state = StateMap::new();
178        if let Some(initial) = &req.state {
179            let (app, user, _) = extract_state_deltas(initial);
180            app_state.entry(key.0.clone()).or_default().extend(app);
181            user_state
182                .entry((key.0.clone(), key.1.clone()))
183                .or_default()
184                .extend(user);
185            state.extend(
186                initial
187                    .iter()
188                    .filter(|(k, _)| {
189                        !k.starts_with(KEY_PREFIX_APP) && !k.starts_with(KEY_PREFIX_USER)
190                    })
191                    .map(|(k, v)| (k.clone(), v.clone())),
192            );
193        }
194        let updated_at = self.platform.now();
195        let merged = merge_states(
196            app_state.get(&key.0),
197            user_state.get(&(key.0.clone(), key.1.clone())),
198            &state,
199        );
200        sessions.insert(
201            key.clone(),
202            StoredSession {
203                state,
204                events: Vec::new(),
205                updated_at,
206            },
207        );
208        drop(inner);
209
210        Ok(Arc::new(InMemorySession::new(
211            key,
212            merged,
213            Vec::new(),
214            updated_at,
215        )))
216    }
217
218    async fn get(&self, req: GetRequest) -> Result<Arc<dyn Session>, SessionError> {
219        require(&[
220            ("app_name", &req.app_name),
221            ("user_id", &req.user_id),
222            ("session_id", &req.session_id),
223        ])?;
224        let key = (req.app_name, req.user_id, req.session_id);
225
226        let inner = self.inner.read();
227        let stored = inner.sessions.get(&key).ok_or(SessionError::NotFound)?;
228        let state = inner.merged_state(&stored.state, &key.0, &key.1);
229
230        // The recent-events limit applies first, then the timestamp filter.
231        let mut events: &[Event] = &stored.events;
232        if req.num_recent_events > 0 {
233            let start = events.len().saturating_sub(req.num_recent_events);
234            events = &events[start..];
235        }
236        // Test every event rather than searching for a cut point: events are kept in append
237        // order, which need not be timestamp order.
238        let after = req.after.filter(|t| *t != zero_time());
239        let events: Vec<Event> = events
240            .iter()
241            .filter(|e| after.is_none_or(|after| e.timestamp >= after))
242            .cloned()
243            .collect();
244        let updated_at = stored.updated_at;
245        drop(inner);
246
247        Ok(Arc::new(InMemorySession::new(
248            key, state, events, updated_at,
249        )))
250    }
251
252    async fn list(&self, req: ListRequest) -> Result<Vec<Arc<dyn Session>>, SessionError> {
253        require(&[("app_name", &req.app_name)])?;
254
255        let inner = self.inner.read();
256        let mut sessions: Vec<Arc<dyn Session>> = inner
257            .sessions
258            .iter()
259            .filter(|((app, user, _), _)| {
260                *app == req.app_name && (req.user_id.is_empty() || *user == req.user_id)
261            })
262            .map(|(key, stored)| {
263                let state = inner.merged_state(&stored.state, &key.0, &key.1);
264                Arc::new(InMemorySession::new(
265                    key.clone(),
266                    state,
267                    Vec::new(),
268                    stored.updated_at,
269                )) as Arc<dyn Session>
270            })
271            .collect();
272        drop(inner);
273        sessions.sort_by(|a, b| compare_by_last_update(a.as_ref(), b.as_ref()));
274        Ok(sessions)
275    }
276
277    async fn delete(&self, req: DeleteRequest) -> Result<(), SessionError> {
278        require(&[
279            ("app_name", &req.app_name),
280            ("user_id", &req.user_id),
281            ("session_id", &req.session_id),
282        ])?;
283        let key = (req.app_name, req.user_id, req.session_id);
284        self.inner.write().sessions.remove(&key);
285        Ok(())
286    }
287
288    async fn append_event(
289        &self,
290        session: &dyn Session,
291        event: &mut Event,
292    ) -> Result<(), SessionError> {
293        // Partial events are not stored.
294        if event.response.partial {
295            return Ok(());
296        }
297        // A backend that persists events could not read this request back, so this one
298        // refuses it too.
299        check_requested_auth_configs(&event.actions.requested_auth_configs)
300            .map_err(|e| SessionError::Backend(format!("cannot append event: {e}").into()))?;
301        // Give the event an identity if it arrived without one, the same way a missing
302        // session ID is filled in on create.
303        if event.id.is_empty() {
304            event.id = self.platform.new_uuid();
305        }
306
307        let live = session
308            .as_any()
309            .downcast_ref::<InMemorySession>()
310            .ok_or_else(|| {
311                SessionError::InvalidRequest(
312                    "session not created by InMemorySessionService".to_string(),
313                )
314            })?;
315
316        let mut inner = self.inner.write();
317        let Inner {
318            sessions,
319            app_state,
320            user_state,
321        } = &mut *inner;
322        let stored = sessions.get_mut(&live.key).ok_or(SessionError::NotFound)?;
323
324        let trimmed = trim_temp_delta_state(event);
325
326        // Update the caller's session: the whole delta (temp: keys included) goes into its
327        // state and the trimmed event is recorded.
328        {
329            let mut data = live.data.write();
330            if let Some(delta) = &event.actions.state_delta {
331                data.state
332                    .extend(delta.iter().map(|(k, v)| (k.clone(), v.clone())));
333            }
334            data.events.push(trimmed.clone());
335            data.updated_at = event.timestamp;
336        }
337
338        // Update the canonical record.
339        stored.events.push(trimmed);
340        stored.updated_at = event.timestamp;
341        if let Some(delta) = event.actions.state_delta.as_ref().filter(|d| !d.is_empty()) {
342            Inner::apply_delta(
343                app_state,
344                user_state,
345                &mut stored.state,
346                delta,
347                &live.key.0,
348                &live.key.1,
349            );
350        }
351        Ok(())
352    }
353}
354
355/// A session handed out by [`InMemorySessionService`]: a copy of the service's record.
356struct InMemorySession {
357    key: SessionKey,
358    data: LiveState,
359}
360
361/// The mutable part of an [`InMemorySession`], behind one lock.
362struct LiveState(RwLock<LiveData>);
363
364struct LiveData {
365    state: StateMap,
366    events: Vec<Event>,
367    updated_at: DateTime<Utc>,
368}
369
370impl LiveState {
371    fn write(&self) -> parking_lot::RwLockWriteGuard<'_, LiveData> {
372        self.0.write()
373    }
374}
375
376impl InMemorySession {
377    fn new(
378        key: SessionKey,
379        state: StateMap,
380        events: Vec<Event>,
381        updated_at: DateTime<Utc>,
382    ) -> Self {
383        Self {
384            key,
385            data: LiveState(RwLock::new(LiveData {
386                state,
387                events,
388                updated_at,
389            })),
390        }
391    }
392}
393
394impl Session for InMemorySession {
395    fn id(&self) -> &str {
396        &self.key.2
397    }
398
399    fn app_name(&self) -> &str {
400        &self.key.0
401    }
402
403    fn user_id(&self) -> &str {
404        &self.key.1
405    }
406
407    fn state(&self) -> &dyn State {
408        &self.data
409    }
410
411    fn events(&self) -> Vec<Event> {
412        self.data.0.read().events.clone()
413    }
414
415    fn last_update_time(&self) -> DateTime<Utc> {
416        self.data.0.read().updated_at
417    }
418
419    fn as_any(&self) -> &dyn std::any::Any {
420        self
421    }
422}
423
424impl State for LiveState {
425    fn get(&self, key: &str) -> Result<Value, SessionError> {
426        self.0
427            .read()
428            .state
429            .get(key)
430            .cloned()
431            .ok_or(SessionError::StateKeyNotExist)
432    }
433
434    fn set(&self, key: &str, value: Value) -> Result<(), SessionError> {
435        self.0.write().state.insert(key.to_string(), value);
436        Ok(())
437    }
438
439    fn all(&self) -> Vec<(String, Value)> {
440        // A snapshot taken under the lock, so iterating it never races a writer.
441        self.0
442            .read()
443            .state
444            .iter()
445            .map(|(k, v)| (k.clone(), v.clone()))
446            .collect()
447    }
448}