gadk_session/service.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//! The [`SessionService`] trait and the [`Session`] and [`State`] interfaces.
17
18use std::sync::Arc;
19
20use async_trait::async_trait;
21use chrono::{DateTime, Utc};
22use serde_json::{Map, Value};
23
24use crate::error::SessionError;
25use crate::event::Event;
26
27/// Prefix for app-level state keys, shared across all users and sessions of an app.
28///
29/// State prefixes are single-level and do not compose: `"app:temp:x"` is app-scoped and
30/// persists.
31pub const KEY_PREFIX_APP: &str = "app:";
32/// Prefix for temporary state keys, discarded after the current invocation.
33pub const KEY_PREFIX_TEMP: &str = "temp:";
34/// Prefix for user-level state keys, shared across all sessions of a user within an app.
35pub const KEY_PREFIX_USER: &str = "user:";
36
37/// A session storage service.
38#[async_trait]
39pub trait SessionService: Send + Sync {
40 /// Creates a session.
41 async fn create(&self, req: CreateRequest) -> Result<Arc<dyn Session>, SessionError>;
42 /// Gets a session; [`SessionError::NotFound`] if it does not exist (or belongs to
43 /// another user).
44 async fn get(&self, req: GetRequest) -> Result<Arc<dyn Session>, SessionError>;
45 /// Lists sessions; an empty result when there are none.
46 ///
47 /// The sessions are ordered by last update time ascending, so the last session is the most
48 /// recently active one. Sessions with equal update times are ordered by user ID, then by
49 /// session ID (see [`compare_by_last_update`]).
50 async fn list(&self, req: ListRequest) -> Result<Vec<Arc<dyn Session>>, SessionError>;
51 /// Deletes a session; a no-op when it does not exist.
52 async fn delete(&self, req: DeleteRequest) -> Result<(), SessionError>;
53 /// Appends `event` to `session` and removes temporary state keys from it.
54 ///
55 /// An event arriving with an empty ID must end up with one (assigned in place where the
56 /// implementation assigns it), and [`crate::EventActions::compaction`] must survive the
57 /// round trip. Returns [`SessionError::NotFound`] when the session is absent.
58 async fn append_event(
59 &self,
60 session: &dyn Session,
61 event: &mut Event,
62 ) -> Result<(), SessionError>;
63}
64
65/// A series of interactions between a user and agents.
66pub trait Session: Send + Sync {
67 /// The unique identifier of the session.
68 fn id(&self) -> &str;
69 /// The name of the app.
70 fn app_name(&self) -> &str;
71 /// The id of the user.
72 fn user_id(&self) -> &str;
73 /// The state of the session.
74 fn state(&self) -> &dyn State;
75 /// The events of the session, in order.
76 fn events(&self) -> Vec<Event>;
77 /// The time of the last update.
78 fn last_update_time(&self) -> DateTime<Utc>;
79 /// Downcasting support for implementations.
80 fn as_any(&self) -> &dyn std::any::Any;
81}
82
83/// The order [`SessionService::list`] documents: last update time ascending, ties by user ID,
84/// then session ID. Use it with a stable sort.
85pub fn compare_by_last_update(a: &dyn Session, b: &dyn Session) -> std::cmp::Ordering {
86 a.last_update_time()
87 .cmp(&b.last_update_time())
88 .then_with(|| a.user_id().cmp(b.user_id()))
89 .then_with(|| a.id().cmp(b.id()))
90}
91
92/// A key-value store of JSON values: read, write and list the state of a session.
93pub trait State: Send + Sync {
94 /// The value for `key`; [`SessionError::StateKeyNotExist`] if absent.
95 fn get(&self, key: &str) -> Result<Value, SessionError>;
96 /// Sets `key` to `value`, overwriting any existing value.
97 fn set(&self, key: &str, value: Value) -> Result<(), SessionError>;
98 /// A snapshot of all key-value pairs; order is not guaranteed.
99 fn all(&self) -> Vec<(String, Value)>;
100}
101
102/// A read-only view of a key-value store of JSON values.
103pub trait ReadonlyState: Send + Sync {
104 /// The value for `key`; [`SessionError::StateKeyNotExist`] if absent.
105 fn get(&self, key: &str) -> Result<Value, SessionError>;
106 /// A snapshot of all key-value pairs; order is not guaranteed.
107 fn all(&self) -> Vec<(String, Value)>;
108}
109
110/// A request to create a session.
111#[derive(Debug, Clone, Default, PartialEq)]
112pub struct CreateRequest {
113 /// The app name.
114 pub app_name: String,
115 /// The user id.
116 pub user_id: String,
117 /// Client-provided session id; autogenerated when `None`.
118 pub session_id: Option<String>,
119 /// Initial session state.
120 pub state: Option<Map<String, Value>>,
121}
122
123/// A request to get a session.
124#[derive(Debug, Clone, Default, PartialEq)]
125pub struct GetRequest {
126 /// The app name.
127 pub app_name: String,
128 /// The user id.
129 pub user_id: String,
130 /// The session id.
131 pub session_id: String,
132 /// Return at most this many most recent events; `0` applies no filter.
133 pub num_recent_events: usize,
134 /// Return events with timestamp >= this time; `None` applies no filter.
135 pub after: Option<DateTime<Utc>>,
136}
137
138/// A request to list sessions.
139#[derive(Debug, Clone, Default, PartialEq)]
140pub struct ListRequest {
141 /// The app name.
142 pub app_name: String,
143 /// The user id.
144 pub user_id: String,
145}
146
147/// A request to delete a session.
148#[derive(Debug, Clone, Default, PartialEq)]
149pub struct DeleteRequest {
150 /// The app name.
151 pub app_name: String,
152 /// The user id.
153 pub user_id: String,
154 /// The session id.
155 pub session_id: String,
156}