use crate::history::{
HistoryOutcome, ImportSessionRequest, RewriteHistoryRequest, RewrittenHistory, SessionHistory,
};
use crate::service::{
identity_not_found, session_already_exists, session_id_not_found, session_not_found_for,
validate_scope, validate_session_id,
};
use crate::{
AppendEventRequest, CreateRequest, DeleteRequest, Event, Events, GetRequest, KEY_PREFIX_TEMP,
ListRequest, Session, SessionService, State, state_utils,
};
use adk_core::identity::AdkIdentity;
use adk_core::{ErrorCategory, ErrorComponent, Result};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use mongodb::bson::{self, Document, doc};
use mongodb::options::{FindOptions, IndexOptions, ReturnDocument, UpdateOptions};
use mongodb::{Client, Database, IndexModel};
use serde_json::Value;
use std::collections::HashMap;
use tracing::instrument;
use uuid::Uuid;
pub(crate) fn hello_supports_transactions(reply: &Document) -> bool {
reply.contains_key("setName") || reply.get_str("msg") == Ok("isdbgrid")
}
pub struct MongoSessionService {
db: Database,
supports_transactions: bool,
}
impl MongoSessionService {
pub async fn new(connection_string: &str, database_name: &str) -> Result<Self> {
let client_options = mongodb::options::ClientOptions::parse(connection_string)
.await
.map_err(|e| adk_core::AdkError::session(format!("mongodb connection failed: {e}")))?;
let client = Client::with_options(client_options)
.map_err(|e| adk_core::AdkError::session(format!("mongodb connection failed: {e}")))?;
let db = client.database(database_name);
let supports_transactions = match db.run_command(doc! { "hello": 1 }).await {
Ok(reply) => hello_supports_transactions(&reply),
Err(error) => {
tracing::warn!(error = %error, "mongodb hello failed; writing without transactions");
false
}
};
if supports_transactions {
tracing::info!("mongodb replica set or sharded cluster detected; transactions enabled");
} else {
tracing::info!(
"mongodb standalone detected; writing sequentially without transactions"
);
}
Ok(Self { db, supports_transactions })
}
pub fn supports_transactions(&self) -> bool {
self.supports_transactions
}
const REGISTRY_COLLECTION: &'static str = "_adk_session_migrations";
const MONGO_SESSION_MIGRATIONS: &'static [(i64, &'static str)] =
&[(1, "create initial indexes"), (2, "index events in read order")];
pub async fn migrate(&self) -> Result<()> {
self.db
.collection::<Document>(Self::REGISTRY_COLLECTION)
.create_index(
IndexModel::builder()
.keys(doc! { "version": 1 })
.options(
IndexOptions::builder()
.unique(true)
.name("idx_migration_version_unique".to_string())
.build(),
)
.build(),
)
.await
.map_err(|e| {
adk_core::AdkError::session(format!("migration registry creation failed: {e}"))
})?;
let mut max_applied = self.read_max_applied_version().await?;
if max_applied == 0 {
let existing = self.detect_existing_tables().await?;
if existing
&& let Some(&(version, description)) = Self::MONGO_SESSION_MIGRATIONS.first()
{
self.record_migration(version, description).await?;
max_applied = version;
}
}
let max_compiled = Self::MONGO_SESSION_MIGRATIONS.last().map(|s| s.0).unwrap_or(0);
if max_applied > max_compiled {
return Err(adk_core::AdkError::session(format!(
"schema version mismatch: database is at v{max_applied} but code only knows up to v{max_compiled}. Upgrade your ADK version."
)));
}
for &(version, description) in Self::MONGO_SESSION_MIGRATIONS {
if version <= max_applied {
continue;
}
run_mongo_session_step(&self.db, version).await.map_err(|e| {
adk_core::AdkError::session(format!(
"{}",
crate::migration::MigrationError {
version,
description: description.to_string(),
cause: e.to_string(),
}
))
})?;
self.record_migration(version, description).await?;
}
Ok(())
}
pub async fn schema_version(&self) -> Result<i64> {
let collections = self.db.list_collection_names().await.map_err(|e| {
adk_core::AdkError::session(format!("schema version query failed: {e}"))
})?;
if !collections.contains(&Self::REGISTRY_COLLECTION.to_string()) {
return Ok(0);
}
self.read_max_applied_version().await
}
async fn read_max_applied_version(&self) -> Result<i64> {
use mongodb::options::FindOneOptions;
let registry = self.db.collection::<Document>(Self::REGISTRY_COLLECTION);
let opts = FindOneOptions::builder().sort(doc! { "version": -1 }).build();
let result = registry.find_one(doc! {}).with_options(opts).await.map_err(|e| {
adk_core::AdkError::session(format!("migration registry read failed: {e}"))
})?;
match result {
Some(doc) => Ok(doc.get_i64("version").unwrap_or(0)),
None => Ok(0),
}
}
async fn detect_existing_tables(&self) -> Result<bool> {
let failed = |e: mongodb::error::Error| {
adk_core::AdkError::session(format!("baseline detection failed: {e}"))
};
let collections = self.db.list_collection_names().await.map_err(failed)?;
if !collections.iter().any(|name| name == "user_states") {
return Ok(false);
}
let indexes = self
.db
.collection::<Document>("user_states")
.list_index_names()
.await
.map_err(failed)?;
Ok(indexes.iter().any(|name| name == "idx_user_states_unique"))
}
async fn record_migration(&self, version: i64, description: &str) -> Result<()> {
let registry = self.db.collection::<Document>(Self::REGISTRY_COLLECTION);
let now = chrono_to_bson_dt(Utc::now());
let recorded = registry
.update_one(
doc! { "version": version },
doc! { "$setOnInsert": { "description": description, "applied_at": now } },
)
.upsert(true)
.await;
match recorded {
Ok(_) => Ok(()),
Err(e) if is_duplicate_key(&e) => Ok(()),
Err(e) => Err(e),
}
.map_err(|e| {
adk_core::AdkError::session(format!(
"{}",
crate::migration::MigrationError {
version,
description: description.to_string(),
cause: format!("registry record failed: {e}"),
}
))
})?;
Ok(())
}
async fn maybe_start_transaction(&self) -> Result<Option<mongodb::ClientSession>> {
if self.supports_transactions {
let mut s =
self.db.client().start_session().await.map_err(|e| {
adk_core::AdkError::session(format!("session start failed: {e}"))
})?;
s.start_transaction().await.map_err(|e| {
adk_core::AdkError::session(format!("transaction start failed: {e}"))
})?;
Ok(Some(s))
} else {
Ok(None)
}
}
async fn maybe_commit(session: &mut Option<mongodb::ClientSession>) -> Result<()> {
if let Some(s) = session {
s.commit_transaction()
.await
.map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;
}
Ok(())
}
}
async fn run_mongo_session_step(db: &Database, version: i64) -> Result<()> {
match version {
1 => mongo_session_v1(db).await,
2 => mongo_session_v2(db).await,
_ => Err(adk_core::AdkError::session(format!("unknown migration version: {version}"))),
}
}
async fn mongo_session_v1(db: &Database) -> Result<()> {
db.collection::<Document>("sessions")
.create_index(
IndexModel::builder()
.keys(doc! { "app_name": 1, "user_id": 1, "session_id": 1 })
.options(
IndexOptions::builder()
.unique(true)
.name("idx_sessions_unique".to_string())
.build(),
)
.build(),
)
.await
.map_err(|e| adk_core::AdkError::session(format!("index creation failed: {e}")))?;
db.collection::<Document>("events")
.create_index(
IndexModel::builder()
.keys(doc! { "session_id": 1, "timestamp": 1 })
.options(IndexOptions::builder().name("idx_events_session_ts".to_string()).build())
.build(),
)
.await
.map_err(|e| adk_core::AdkError::session(format!("index creation failed: {e}")))?;
db.collection::<Document>("app_states")
.create_index(
IndexModel::builder()
.keys(doc! { "app_name": 1 })
.options(
IndexOptions::builder()
.unique(true)
.name("idx_app_states_unique".to_string())
.build(),
)
.build(),
)
.await
.map_err(|e| adk_core::AdkError::session(format!("index creation failed: {e}")))?;
db.collection::<Document>("user_states")
.create_index(
IndexModel::builder()
.keys(doc! { "app_name": 1, "user_id": 1 })
.options(
IndexOptions::builder()
.unique(true)
.name("idx_user_states_unique".to_string())
.build(),
)
.build(),
)
.await
.map_err(|e| adk_core::AdkError::session(format!("index creation failed: {e}")))?;
Ok(())
}
async fn mongo_session_v2(db: &Database) -> Result<()> {
db.collection::<Document>("events")
.create_index(
IndexModel::builder()
.keys(doc! {
"app_name": 1, "user_id": 1, "session_id": 1, "timestamp": 1, "seq": 1,
})
.options(IndexOptions::builder().name("idx_events_read_order".to_string()).build())
.build(),
)
.await
.map_err(|e| adk_core::AdkError::session(format!("index creation failed: {e}")))?;
Ok(())
}
fn is_duplicate_key(error: &mongodb::error::Error) -> bool {
use mongodb::error::{ErrorKind, WriteFailure};
match &*error.kind {
ErrorKind::Write(WriteFailure::WriteError(write)) => write.code == 11000,
_ => false,
}
}
const MAX_REWRITE_ATTEMPTS: usize = 16;
fn state_to_bson(
state: &HashMap<String, Value>,
) -> std::result::Result<Document, adk_core::AdkError> {
let json_value = serde_json::to_value(state)
.map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
let bson_value = bson::to_bson(&json_value)
.map_err(|e| adk_core::AdkError::session(format!("bson conversion failed: {e}")))?;
match bson_value {
bson::Bson::Document(doc) => Ok(doc),
_ => Ok(Document::new()),
}
}
fn bson_to_state(doc: &Document) -> HashMap<String, Value> {
let bson_value = bson::Bson::Document(doc.clone());
match bson::from_bson::<serde_json::Value>(bson_value) {
Ok(Value::Object(map)) => map.into_iter().collect(),
_ => HashMap::new(),
}
}
fn chrono_to_bson_dt(dt: DateTime<Utc>) -> bson::DateTime {
bson::DateTime::from_millis(dt.timestamp_millis())
}
fn bson_dt_to_chrono(dt: bson::DateTime) -> DateTime<Utc> {
let millis = dt.timestamp_millis();
DateTime::from_timestamp_millis(millis).unwrap_or_default()
}
fn merge_state_pipeline(
delta: &HashMap<String, Value>,
updated_at: bson::DateTime,
) -> std::result::Result<Vec<Document>, adk_core::AdkError> {
let delta = state_to_bson(delta)?;
Ok(vec![doc! { "$set": {
"state": { "$mergeObjects": [{ "$ifNull": ["$state", {}] }, { "$literal": delta }] },
"updated_at": updated_at,
} }])
}
macro_rules! with_optional_session {
($action:expr, $session:expr) => {
match $session {
Some(s) => $action.session(s).await,
None => $action.await,
}
};
}
impl MongoSessionService {
async fn read_tiers(
&self,
txn: &mut Option<mongodb::ClientSession>,
app_name: &str,
user_id: &str,
) -> Result<(HashMap<String, Value>, HashMap<String, Value>)> {
let app_coll = self.db.collection::<Document>("app_states");
let user_coll = self.db.collection::<Document>("user_states");
let app_state =
with_optional_session!(app_coll.find_one(doc! { "app_name": app_name }), txn.as_mut())
.map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
.and_then(|d| d.get_document("state").ok().map(bson_to_state))
.unwrap_or_default();
let user_state = with_optional_session!(
user_coll.find_one(doc! { "app_name": app_name, "user_id": user_id }),
txn.as_mut()
)
.map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
.and_then(|d| d.get_document("state").ok().map(bson_to_state))
.unwrap_or_default();
Ok((app_state, user_state))
}
async fn apply_tier_deltas(
&self,
txn: &mut Option<mongodb::ClientSession>,
app_name: &str,
user_id: &str,
app_delta: &HashMap<String, Value>,
user_delta: &HashMap<String, Value>,
updated_at: bson::DateTime,
) -> Result<()> {
let upsert = UpdateOptions::builder().upsert(true).build();
if !app_delta.is_empty() {
let app_coll = self.db.collection::<Document>("app_states");
with_optional_session!(
app_coll
.update_one(
doc! { "app_name": app_name },
merge_state_pipeline(app_delta, updated_at)?
)
.with_options(upsert.clone()),
txn.as_mut()
)
.map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;
}
if !user_delta.is_empty() {
let user_coll = self.db.collection::<Document>("user_states");
with_optional_session!(
user_coll
.update_one(
doc! { "app_name": app_name, "user_id": user_id },
merge_state_pipeline(user_delta, updated_at)?
)
.with_options(upsert),
txn.as_mut()
)
.map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;
}
Ok(())
}
async fn load_history(
&self,
txn: &mut Option<mongodb::ClientSession>,
identity: &AdkIdentity,
) -> Result<(SessionHistory, bson::Bson, bson::Bson)> {
let filter = doc! {
"app_name": identity.app_name.as_ref(),
"user_id": identity.user_id.as_ref(),
"session_id": identity.session_id.as_ref(),
};
let session_doc = with_optional_session!(
self.db.collection::<Document>("sessions").find_one(filter.clone()),
txn.as_mut()
)
.map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
.ok_or_else(|| identity_not_found(identity))?;
let stored = session_doc.get_document("state").map(bson_to_state).unwrap_or_default();
let (_, _, state) = state_utils::extract_state_deltas(&stored);
let initial_state = session_doc.get_document("initial_state").ok().map(bson_to_state);
let event_seq = session_doc.get("event_seq").cloned().unwrap_or(bson::Bson::Null);
let updated_at = session_doc.get("updated_at").cloned().unwrap_or(bson::Bson::Null);
let events_coll = self.db.collection::<Document>("events");
let options = FindOptions::builder().sort(doc! { "timestamp": 1, "seq": 1 }).build();
let query_error =
|e: mongodb::error::Error| adk_core::AdkError::session(format!("query failed: {e}"));
let mut docs = Vec::new();
match txn.as_mut() {
Some(session) => {
let mut cursor = events_coll
.find(filter)
.with_options(options)
.session(&mut *session)
.await
.map_err(query_error)?;
while cursor.advance(&mut *session).await.map_err(query_error)? {
docs.push(cursor.deserialize_current().map_err(query_error)?);
}
}
None => {
let mut cursor =
events_coll.find(filter).with_options(options).await.map_err(query_error)?;
while cursor.advance().await.map_err(query_error)? {
docs.push(cursor.deserialize_current().map_err(query_error)?);
}
}
}
let events = docs.iter().filter_map(doc_to_event).collect();
Ok((SessionHistory::new(events, state, initial_state), event_seq, updated_at))
}
async fn try_rewrite(
&self,
req: &RewriteHistoryRequest,
) -> Result<Option<(RewrittenHistory, DateTime<Utc>)>> {
let identity = &req.identity;
let (app_name, user_id, session_id) =
(identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
let mut txn = self.maybe_start_transaction().await?;
let (history, event_seq, updated_at) = self.load_history(&mut txn, identity).await?;
let rewritten = history.rewrite(identity, &req.rewrite, req.expected_version.as_deref())?;
let now = Utc::now();
let claimed = with_optional_session!(
self.db.collection::<Document>("sessions").update_one(
doc! {
"app_name": app_name, "user_id": user_id, "session_id": session_id,
"event_seq": event_seq, "updated_at": updated_at,
},
doc! { "$set": {
"state": state_to_bson(&rewritten.state)?,
"updated_at": chrono_to_bson_dt(now),
} }
),
txn.as_mut()
)
.map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?;
if claimed.matched_count == 0 {
if let Some(session) = txn.as_mut() {
session.abort_transaction().await.ok();
}
return Ok(None);
}
let events_coll = self.db.collection::<Document>("events");
let change = &rewritten.change;
if !change.removed.is_empty() {
with_optional_session!(
events_coll.delete_many(doc! {
"app_name": app_name, "user_id": user_id, "session_id": session_id,
"id": { "$in": &change.removed },
}),
txn.as_mut()
)
.map_err(|e| adk_core::AdkError::session(format!("delete events failed: {e}")))?;
}
for event in rewritten.events.iter().filter(|e| change.replaced.contains(&e.id)) {
let replacement = event_doc(app_name, user_id, session_id, event, 0)?;
with_optional_session!(
events_coll.update_one(
doc! {
"app_name": app_name, "user_id": user_id, "session_id": session_id,
"id": &event.id,
},
doc! { "$set": {
"invocation_id": replacement.get("invocation_id").cloned(),
"branch": replacement.get("branch").cloned(),
"author": replacement.get("author").cloned(),
"llm_response": replacement.get("llm_response").cloned(),
"actions": replacement.get("actions").cloned(),
"long_running_tool_ids": replacement.get("long_running_tool_ids").cloned(),
} }
),
txn.as_mut()
)
.map_err(|e| adk_core::AdkError::session(format!("update event failed: {e}")))?;
}
Self::maybe_commit(&mut txn).await?;
Ok(Some((rewritten, now)))
}
async fn apply_event(
&self,
txn: &mut Option<mongodb::ClientSession>,
app_name: &str,
user_id: &str,
session_id: &str,
event: &Event,
) -> Result<()> {
let sess_coll = self.db.collection::<Document>("sessions");
let ev_coll = self.db.collection::<Document>("events");
let (app_delta, user_delta, session_delta) =
state_utils::extract_state_deltas(&event.actions.state_delta);
let bson_ts = chrono_to_bson_dt(event.timestamp);
let mut pipeline = merge_state_pipeline(&session_delta, bson_ts)?;
if let Some(set) =
pipeline.first_mut().and_then(|stage| stage.get_document_mut("$set").ok())
{
set.insert(
"event_seq",
doc! { "$add": [{ "$toLong": { "$ifNull": ["$event_seq", 0] } }, 1] },
);
}
let updated = with_optional_session!(
sess_coll
.find_one_and_update(
doc! { "app_name": app_name, "user_id": user_id, "session_id": session_id },
pipeline
)
.return_document(ReturnDocument::After)
.projection(doc! { "event_seq": 1 }),
txn.as_mut()
)
.map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?
.ok_or_else(|| session_not_found_for(app_name, user_id, session_id))?;
let seq = updated
.get_i64("event_seq")
.or_else(|_| updated.get_i32("event_seq").map(i64::from))
.unwrap_or_default();
self.apply_tier_deltas(txn, app_name, user_id, &app_delta, &user_delta, bson_ts).await?;
with_optional_session!(
ev_coll.insert_one(event_doc(app_name, user_id, session_id, event, seq)?),
txn.as_mut()
)
.map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;
Ok(())
}
}
#[async_trait]
impl SessionService for MongoSessionService {
#[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id))]
async fn create(&self, req: CreateRequest) -> Result<Box<dyn Session>> {
req.try_identity()?;
let session_id = req.session_id.unwrap_or_else(|| Uuid::new_v4().to_string());
let now = Utc::now();
let bson_now = chrono_to_bson_dt(now);
let (app_delta, user_delta, session_state) = state_utils::extract_state_deltas(&req.state);
let sess_coll = self.db.collection::<Document>("sessions");
let conflict = || session_already_exists(&req.app_name, &req.user_id, &session_id);
let identity = doc! {
"app_name": &req.app_name, "user_id": &req.user_id, "session_id": &session_id,
};
let mut txn = self.maybe_start_transaction().await?;
let existing = with_optional_session!(sess_coll.find_one(identity.clone()), txn.as_mut())
.map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
if existing.is_some() {
return Err(conflict());
}
let session_bson = state_to_bson(&session_state)?;
let mut session_doc = identity;
session_doc.insert("initial_state", session_bson.clone());
session_doc.insert("state", session_bson);
session_doc.insert("created_at", bson_now);
session_doc.insert("updated_at", bson_now);
with_optional_session!(sess_coll.insert_one(session_doc), txn.as_mut()).map_err(|e| {
if is_duplicate_key(&e) {
conflict()
} else {
adk_core::AdkError::session(format!("insert failed: {e}"))
}
})?;
self.apply_tier_deltas(
&mut txn,
&req.app_name,
&req.user_id,
&app_delta,
&user_delta,
bson_now,
)
.await?;
let (app_state, user_state) =
self.read_tiers(&mut txn, &req.app_name, &req.user_id).await?;
MongoSessionService::maybe_commit(&mut txn).await?;
Ok(Box::new(MongoSession {
app_name: req.app_name,
user_id: req.user_id,
session_id,
state: state_utils::merge_states(&app_state, &user_state, &session_state),
events: Vec::new(),
updated_at: now,
}))
}
#[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id, session_id = %req.session_id))]
async fn get(&self, req: GetRequest) -> Result<Box<dyn Session>> {
req.try_identity()?;
let sess_coll = self.db.collection::<Document>("sessions");
let session_doc = sess_coll
.find_one(doc! { "app_name": &req.app_name, "user_id": &req.user_id, "session_id": &req.session_id })
.await.map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
.ok_or_else(|| crate::service::session_not_found(&req))?;
let stored = session_doc.get_document("state").map(bson_to_state).unwrap_or_default();
let (app_state, user_state) =
self.read_tiers(&mut None, &req.app_name, &req.user_id).await?;
let updated_at = session_doc
.get_datetime("updated_at")
.map(|dt| bson_dt_to_chrono(*dt))
.unwrap_or_else(|_| Utc::now());
let events_coll = self.db.collection::<Document>("events");
let mut cursor = events_coll
.find(doc! { "app_name": &req.app_name, "user_id": &req.user_id, "session_id": &req.session_id })
.with_options(FindOptions::builder().sort(doc! { "timestamp": 1, "seq": 1 }).build())
.await.map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
let mut events: Vec<Event> = Vec::new();
while cursor
.advance()
.await
.map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
{
let doc = cursor
.deserialize_current()
.map_err(|e| adk_core::AdkError::session(format!("deserialize failed: {e}")))?;
if let Some(event) = doc_to_event(&doc) {
events.push(event);
}
}
if let Some(num) = req.num_recent_events {
let start = events.len().saturating_sub(num);
events = events[start..].to_vec();
}
if let Some(after) = req.after {
events.retain(|e| e.timestamp >= after);
}
Ok(Box::new(MongoSession {
app_name: req.app_name,
user_id: req.user_id,
session_id: req.session_id,
state: state_utils::merge_current_tiers(&app_state, &user_state, &stored),
events,
updated_at,
}))
}
#[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id))]
async fn list(&self, req: ListRequest) -> Result<Vec<Box<dyn Session>>> {
validate_scope(&req.app_name, &req.user_id)?;
let sess_coll = self.db.collection::<Document>("sessions");
let opts = FindOptions::builder()
.sort(doc! { "updated_at": -1, "session_id": -1 })
.limit(req.limit.map(|l| l as i64))
.skip(req.offset.map(|o| o as u64))
.build();
let mut cursor = sess_coll
.find(doc! { "app_name": &req.app_name, "user_id": &req.user_id })
.with_options(opts)
.await
.map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
let (app_state, user_state) =
self.read_tiers(&mut None, &req.app_name, &req.user_id).await?;
let mut sessions: Vec<Box<dyn Session>> = Vec::new();
while cursor
.advance()
.await
.map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
{
let doc = cursor
.deserialize_current()
.map_err(|e| adk_core::AdkError::session(format!("deserialize failed: {e}")))?;
let stored = doc.get_document("state").map(bson_to_state).unwrap_or_default();
sessions.push(Box::new(MongoSession {
app_name: req.app_name.clone(),
user_id: req.user_id.clone(),
session_id: doc.get_str("session_id").unwrap_or_default().to_string(),
state: state_utils::merge_current_tiers(&app_state, &user_state, &stored),
events: Vec::new(),
updated_at: doc
.get_datetime("updated_at")
.map(|dt| bson_dt_to_chrono(*dt))
.unwrap_or_else(|_| Utc::now()),
}));
}
Ok(sessions)
}
#[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id, session_id = %req.session_id))]
async fn delete(&self, req: DeleteRequest) -> Result<()> {
req.try_identity()?;
let ev_coll = self.db.collection::<Document>("events");
let sess_coll = self.db.collection::<Document>("sessions");
let filter = doc! { "app_name": &req.app_name, "user_id": &req.user_id, "session_id": &req.session_id };
let mut txn = self.maybe_start_transaction().await?;
with_optional_session!(ev_coll.delete_many(filter.clone()), txn.as_mut())
.map_err(|e| adk_core::AdkError::session(format!("delete failed: {e}")))?;
with_optional_session!(sess_coll.delete_one(filter), txn.as_mut())
.map_err(|e| adk_core::AdkError::session(format!("delete failed: {e}")))?;
MongoSessionService::maybe_commit(&mut txn).await?;
Ok(())
}
#[instrument(skip_all, fields(session_id = %session_id))]
async fn append_event(&self, session_id: &str, mut event: Event) -> Result<()> {
validate_session_id(session_id)?;
event.actions.state_delta.retain(|k, _| !k.starts_with(KEY_PREFIX_TEMP));
let sess_coll = self.db.collection::<Document>("sessions");
let mut txn = self.maybe_start_transaction().await?;
let session_doc = with_optional_session!(
sess_coll.find_one(doc! { "session_id": session_id }),
txn.as_mut()
)
.map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
.ok_or_else(|| session_id_not_found(session_id))?;
let app_name = session_doc.get_str("app_name").unwrap_or_default().to_string();
let user_id = session_doc.get_str("user_id").unwrap_or_default().to_string();
self.apply_event(&mut txn, &app_name, &user_id, session_id, &event).await?;
MongoSessionService::maybe_commit(&mut txn).await?;
Ok(())
}
#[instrument(skip_all, fields(
app_name = %req.identity.app_name,
user_id = %req.identity.user_id,
session_id = %req.identity.session_id,
))]
async fn append_event_for_identity(&self, req: AppendEventRequest) -> Result<()> {
let mut event = req.event;
event.actions.state_delta.retain(|k, _| !k.starts_with(KEY_PREFIX_TEMP));
let mut txn = self.maybe_start_transaction().await?;
self.apply_event(
&mut txn,
req.identity.app_name.as_ref(),
req.identity.user_id.as_ref(),
req.identity.session_id.as_ref(),
&event,
)
.await?;
MongoSessionService::maybe_commit(&mut txn).await?;
Ok(())
}
#[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
async fn delete_all_sessions(&self, app_name: &str, user_id: &str) -> Result<()> {
validate_scope(app_name, user_id)?;
let filter = doc! { "app_name": app_name, "user_id": user_id };
let ev_coll = self.db.collection::<Document>("events");
let sess_coll = self.db.collection::<Document>("sessions");
let user_coll = self.db.collection::<Document>("user_states");
let mut txn = self.maybe_start_transaction().await?;
with_optional_session!(ev_coll.delete_many(filter.clone()), txn.as_mut())
.map_err(|e| adk_core::AdkError::session(format!("delete_all_sessions failed: {e}")))?;
with_optional_session!(sess_coll.delete_many(filter.clone()), txn.as_mut())
.map_err(|e| adk_core::AdkError::session(format!("delete_all_sessions failed: {e}")))?;
with_optional_session!(user_coll.delete_many(filter), txn.as_mut())
.map_err(|e| adk_core::AdkError::session(format!("delete_all_sessions failed: {e}")))?;
MongoSessionService::maybe_commit(&mut txn).await?;
Ok(())
}
#[instrument(skip_all)]
async fn history(&self, identity: &AdkIdentity) -> Result<SessionHistory> {
Ok(self.load_history(&mut None, identity).await?.0)
}
async fn rewrite_history(&self, req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
let identity = &req.identity;
for _ in 0..MAX_REWRITE_ATTEMPTS {
let Some((rewritten, updated_at)) = self.try_rewrite(&req).await? else {
continue;
};
let (app_state, user_state) = self
.read_tiers(&mut None, identity.app_name.as_ref(), identity.user_id.as_ref())
.await?;
let session = Box::new(MongoSession {
app_name: identity.app_name.as_ref().to_string(),
user_id: identity.user_id.as_ref().to_string(),
session_id: identity.session_id.as_ref().to_string(),
state: state_utils::merge_states(&app_state, &user_state, &rewritten.state),
events: rewritten.events,
updated_at,
});
return Ok(HistoryOutcome::new(session, rewritten.change));
}
Err(adk_core::AdkError::new(
ErrorComponent::Session,
ErrorCategory::Unavailable,
"session.mongodb.history_contention",
format!(
"session '{}' changed on each of {MAX_REWRITE_ATTEMPTS} rewrite attempts; retry \
the rewrite",
identity.session_id
),
))
}
async fn import_session(&self, req: ImportSessionRequest) -> Result<Box<dyn Session>> {
let identity = &req.identity;
let (app_name, user_id, session_id) =
(identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
let (_, _, state) = state_utils::extract_state_deltas(&req.state);
let (_, _, initial_state) = state_utils::extract_state_deltas(&req.initial_state);
let updated_at = req.events.last().map_or_else(Utc::now, |event| event.timestamp);
let event_count = i64::try_from(req.events.len()).unwrap_or(i64::MAX);
let mut txn = self.maybe_start_transaction().await?;
let session_doc = doc! {
"app_name": app_name, "user_id": user_id, "session_id": session_id,
"state": state_to_bson(&state)?,
"initial_state": state_to_bson(&initial_state)?,
"created_at": chrono_to_bson_dt(Utc::now()),
"updated_at": chrono_to_bson_dt(updated_at),
"event_seq": event_count,
};
with_optional_session!(
self.db.collection::<Document>("sessions").insert_one(session_doc),
txn.as_mut()
)
.map_err(|e| {
if is_duplicate_key(&e) {
session_already_exists(app_name, user_id, session_id)
} else {
adk_core::AdkError::session(format!("insert failed: {e}"))
}
})?;
if !req.events.is_empty() {
let docs = req
.events
.iter()
.zip(1_i64..)
.map(|(event, seq)| event_doc(app_name, user_id, session_id, event, seq))
.collect::<Result<Vec<_>>>()?;
let inserted = with_optional_session!(
self.db.collection::<Document>("events").insert_many(docs),
txn.as_mut()
);
if let Err(error) = inserted {
if txn.is_none() {
let _ = self
.db
.collection::<Document>("sessions")
.delete_one(doc! {
"app_name": app_name, "user_id": user_id, "session_id": session_id,
})
.await;
}
return Err(adk_core::AdkError::session(format!("insert events failed: {error}")));
}
}
let (app_state, user_state) = self.read_tiers(&mut txn, app_name, user_id).await?;
MongoSessionService::maybe_commit(&mut txn).await?;
Ok(Box::new(MongoSession {
app_name: app_name.to_string(),
user_id: user_id.to_string(),
session_id: session_id.to_string(),
state: state_utils::merge_states(&app_state, &user_state, &state),
events: req.events,
updated_at,
}))
}
async fn health_check(&self) -> Result<()> {
self.db
.run_command(doc! { "ping": 1 })
.await
.map_err(|e| adk_core::AdkError::session(format!("health check failed: {e}")))?;
Ok(())
}
}
fn event_doc(
app_name: &str,
user_id: &str,
session_id: &str,
event: &Event,
seq: i64,
) -> Result<Document> {
let llm_bson = bson::to_bson(&event.llm_response)
.map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
let act_bson = bson::to_bson(&event.actions)
.map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
let tid_bson = bson::to_bson(&event.long_running_tool_ids)
.map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
Ok(doc! {
"id": &event.id, "session_id": session_id, "app_name": app_name, "user_id": user_id,
"invocation_id": &event.invocation_id, "branch": &event.branch, "author": &event.author,
"timestamp": chrono_to_bson_dt(event.timestamp), "seq": seq, "llm_response": llm_bson,
"actions": act_bson, "long_running_tool_ids": tid_bson,
})
}
fn doc_to_event(doc: &Document) -> Option<Event> {
let llm_response_bson = doc.get("llm_response")?;
let actions_bson = doc.get("actions")?;
let tool_ids_bson = doc.get("long_running_tool_ids")?;
let llm_response = bson::from_bson(llm_response_bson.clone()).ok()?;
let actions = bson::from_bson(actions_bson.clone()).ok()?;
let long_running_tool_ids = bson::from_bson(tool_ids_bson.clone()).ok()?;
let timestamp = doc
.get_datetime("timestamp")
.map(|dt| bson_dt_to_chrono(*dt))
.unwrap_or_else(|_| Utc::now());
Some(Event {
id: doc.get_str("id").unwrap_or_default().to_string(),
timestamp,
invocation_id: doc.get_str("invocation_id").unwrap_or_default().to_string(),
branch: doc.get_str("branch").unwrap_or_default().to_string(),
author: doc.get_str("author").unwrap_or_default().to_string(),
llm_request: None,
llm_response,
actions,
long_running_tool_ids,
provider_metadata: std::collections::HashMap::new(),
})
}
struct MongoSession {
app_name: String,
user_id: String,
session_id: String,
state: HashMap<String, Value>,
events: Vec<Event>,
updated_at: DateTime<Utc>,
}
impl Session for MongoSession {
fn id(&self) -> &str {
&self.session_id
}
fn app_name(&self) -> &str {
&self.app_name
}
fn user_id(&self) -> &str {
&self.user_id
}
fn state(&self) -> &dyn State {
self
}
fn events(&self) -> &dyn Events {
self
}
fn last_update_time(&self) -> DateTime<Utc> {
self.updated_at
}
fn take_events(&mut self) -> Vec<Event> {
std::mem::take(&mut self.events)
}
}
impl State for MongoSession {
fn get(&self, key: &str) -> Option<Value> {
self.state.get(key).cloned()
}
fn set(&mut self, key: String, value: Value) {
if let Err(msg) = adk_core::validate_state_key(&key) {
tracing::warn!(key = %key, "rejecting invalid state key: {msg}");
return;
}
self.state.insert(key, value);
}
fn all(&self) -> HashMap<String, Value> {
self.state.clone()
}
}
impl Events for MongoSession {
fn all(&self) -> Vec<Event> {
self.events.clone()
}
fn len(&self) -> usize {
self.events.len()
}
fn at(&self, index: usize) -> Option<&Event> {
self.events.get(index)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn replica_set_members_support_transactions() {
let primary = doc! { "isWritablePrimary": true, "setName": "rs0", "hosts": ["a:27017"] };
assert!(hello_supports_transactions(&primary));
let secondary = doc! { "isWritablePrimary": false, "secondary": true, "setName": "rs0" };
assert!(hello_supports_transactions(&secondary));
}
#[test]
fn mongos_routers_support_transactions() {
let mongos = doc! { "isWritablePrimary": true, "msg": "isdbgrid", "maxWireVersion": 21 };
assert!(hello_supports_transactions(&mongos));
}
#[test]
fn standalone_servers_do_not_support_transactions() {
let standalone = doc! { "isWritablePrimary": true, "maxWireVersion": 21 };
assert!(!hello_supports_transactions(&standalone));
assert!(!hello_supports_transactions(&doc! { "msg": "not a router" }));
}
}