gadk-session 0.5.2

Sessions, events and the in-memory session service for gadk
Documentation
// Copyright 2026 Chris Olson
// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! The [`SessionService`] trait and the [`Session`] and [`State`] interfaces.

use std::sync::Arc;

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde_json::{Map, Value};

use crate::error::SessionError;
use crate::event::Event;

/// Prefix for app-level state keys, shared across all users and sessions of an app.
///
/// State prefixes are single-level and do not compose: `"app:temp:x"` is app-scoped and
/// persists.
pub const KEY_PREFIX_APP: &str = "app:";
/// Prefix for temporary state keys, discarded after the current invocation.
pub const KEY_PREFIX_TEMP: &str = "temp:";
/// Prefix for user-level state keys, shared across all sessions of a user within an app.
pub const KEY_PREFIX_USER: &str = "user:";

/// A session storage service.
#[async_trait]
pub trait SessionService: Send + Sync {
    /// Creates a session.
    async fn create(&self, req: CreateRequest) -> Result<Arc<dyn Session>, SessionError>;
    /// Gets a session; [`SessionError::NotFound`] if it does not exist (or belongs to
    /// another user).
    async fn get(&self, req: GetRequest) -> Result<Arc<dyn Session>, SessionError>;
    /// Lists sessions; an empty result when there are none.
    ///
    /// The sessions are ordered by last update time ascending, so the last session is the most
    /// recently active one. Sessions with equal update times are ordered by user ID, then by
    /// session ID (see [`compare_by_last_update`]).
    async fn list(&self, req: ListRequest) -> Result<Vec<Arc<dyn Session>>, SessionError>;
    /// Deletes a session; a no-op when it does not exist.
    async fn delete(&self, req: DeleteRequest) -> Result<(), SessionError>;
    /// Appends `event` to `session` and removes temporary state keys from it.
    ///
    /// An event arriving with an empty ID must end up with one (assigned in place where the
    /// implementation assigns it), and [`crate::EventActions::compaction`] must survive the
    /// round trip. Returns [`SessionError::NotFound`] when the session is absent.
    async fn append_event(
        &self,
        session: &dyn Session,
        event: &mut Event,
    ) -> Result<(), SessionError>;
}

/// A series of interactions between a user and agents.
pub trait Session: Send + Sync {
    /// The unique identifier of the session.
    fn id(&self) -> &str;
    /// The name of the app.
    fn app_name(&self) -> &str;
    /// The id of the user.
    fn user_id(&self) -> &str;
    /// The state of the session.
    fn state(&self) -> &dyn State;
    /// The events of the session, in order.
    fn events(&self) -> Vec<Event>;
    /// The time of the last update.
    fn last_update_time(&self) -> DateTime<Utc>;
    /// Downcasting support for implementations.
    fn as_any(&self) -> &dyn std::any::Any;
}

/// The order [`SessionService::list`] documents: last update time ascending, ties by user ID,
/// then session ID. Use it with a stable sort.
pub fn compare_by_last_update(a: &dyn Session, b: &dyn Session) -> std::cmp::Ordering {
    a.last_update_time()
        .cmp(&b.last_update_time())
        .then_with(|| a.user_id().cmp(b.user_id()))
        .then_with(|| a.id().cmp(b.id()))
}

/// A key-value store of JSON values: read, write and list the state of a session.
pub trait State: Send + Sync {
    /// The value for `key`; [`SessionError::StateKeyNotExist`] if absent.
    fn get(&self, key: &str) -> Result<Value, SessionError>;
    /// Sets `key` to `value`, overwriting any existing value.
    fn set(&self, key: &str, value: Value) -> Result<(), SessionError>;
    /// A snapshot of all key-value pairs; order is not guaranteed.
    fn all(&self) -> Vec<(String, Value)>;
}

/// A read-only view of a key-value store of JSON values.
pub trait ReadonlyState: Send + Sync {
    /// The value for `key`; [`SessionError::StateKeyNotExist`] if absent.
    fn get(&self, key: &str) -> Result<Value, SessionError>;
    /// A snapshot of all key-value pairs; order is not guaranteed.
    fn all(&self) -> Vec<(String, Value)>;
}

/// A request to create a session.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct CreateRequest {
    /// The app name.
    pub app_name: String,
    /// The user id.
    pub user_id: String,
    /// Client-provided session id; autogenerated when `None`.
    pub session_id: Option<String>,
    /// Initial session state.
    pub state: Option<Map<String, Value>>,
}

/// A request to get a session.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct GetRequest {
    /// The app name.
    pub app_name: String,
    /// The user id.
    pub user_id: String,
    /// The session id.
    pub session_id: String,
    /// Return at most this many most recent events; `0` applies no filter.
    pub num_recent_events: usize,
    /// Return events with timestamp >= this time; `None` applies no filter.
    pub after: Option<DateTime<Utc>>,
}

/// A request to list sessions.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ListRequest {
    /// The app name.
    pub app_name: String,
    /// The user id.
    pub user_id: String,
}

/// A request to delete a session.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct DeleteRequest {
    /// The app name.
    pub app_name: String,
    /// The user id.
    pub user_id: String,
    /// The session id.
    pub session_id: String,
}