use std::collections::HashMap;
use adk_core::identity::AdkIdentity;
use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{Event, Session};
pub const ARCHIVE_KEY: &str = "adk:archived";
pub const ARCHIVE_AUTHOR: &str = "adk.session";
pub const SESSION_BUNDLE_FORMAT: &str = "adk.session.bundle/v1";
pub(crate) const LIST_PAGE: usize = 100;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ArchiveMark {
pub archived_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
impl ArchiveMark {
pub fn new(reason: Option<String>) -> Self {
Self { archived_at: Utc::now(), reason }
}
pub fn of(session: &dyn Session) -> Option<Self> {
Self::in_state(session.state().get(ARCHIVE_KEY).as_ref())
}
fn in_state(value: Option<&Value>) -> Option<Self> {
value
.filter(|value| value.is_object())
.and_then(|value| serde_json::from_value(value.clone()).ok())
}
pub(crate) fn event(&self) -> Result<Event> {
let value = serde_json::to_value(self).map_err(|error| {
AdkError::session(format!("the archive mark could not be serialized: {error}"))
})?;
Ok(marker_event(value))
}
}
pub(crate) fn marker_event(value: Value) -> Event {
let mut event = Event::new(format!("archive-{}", uuid::Uuid::new_v4()));
event.author = ARCHIVE_AUTHOR.to_string();
event.actions.state_delta.insert(ARCHIVE_KEY.to_string(), value);
event
}
pub(crate) fn is_marker_event(event: &Event) -> bool {
event.author == ARCHIVE_AUTHOR && event.actions.state_delta.contains_key(ARCHIVE_KEY)
}
pub fn ensure_writable(session: &dyn Session) -> Result<()> {
match ArchiveMark::of(session) {
None => Ok(()),
Some(mark) => Err(session_archived(session.id(), &mark)),
}
}
pub(crate) fn session_archived(session_id: &str, mark: &ArchiveMark) -> AdkError {
AdkError::new(
ErrorComponent::Session,
ErrorCategory::Conflict,
"session.archived",
format!(
"session '{session_id}' was archived at {} and is read-only; unarchive it with \
SessionService::unarchive (`adk-rust sessions unarchive {session_id}`) to continue \
it",
mark.archived_at.to_rfc3339()
),
)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct SessionBundle {
pub format: String,
pub exported_at: DateTime<Utc>,
pub app_name: String,
pub user_id: String,
pub session_id: String,
pub updated_at: DateTime<Utc>,
pub state: HashMap<String, Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub archived: Option<ArchiveMark>,
pub events: Vec<Event>,
}
impl SessionBundle {
pub fn of(session: &dyn Session) -> Self {
let (_, _, state) = crate::state_utils::extract_state_deltas(&session.state().all());
Self {
format: SESSION_BUNDLE_FORMAT.to_string(),
exported_at: Utc::now(),
app_name: session.app_name().to_string(),
user_id: session.user_id().to_string(),
session_id: session.id().to_string(),
updated_at: session.last_update_time(),
state,
archived: ArchiveMark::of(session),
events: session.events().all(),
}
}
pub fn identity(&self) -> Result<AdkIdentity> {
Ok(AdkIdentity::new(
self.app_name.as_str().try_into()?,
self.user_id.as_str().try_into()?,
self.session_id.as_str().try_into()?,
))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Keep {
Active,
Archived,
}
impl Keep {
pub(crate) fn keeps(self, session: &dyn Session) -> bool {
let archived = ArchiveMark::of(session).is_some();
match self {
Self::Active => !archived,
Self::Archived => archived,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{CreateRequest, InMemorySessionService, ListRequest, SessionService};
fn listing(limit: Option<usize>, offset: Option<usize>) -> ListRequest {
ListRequest { app_name: "app".into(), user_id: "ana".into(), limit, offset }
}
fn ids(sessions: &[Box<dyn Session>]) -> Vec<String> {
sessions.iter().map(|session| session.id().to_string()).collect()
}
#[tokio::test]
async fn listings_page_across_several_reads_of_list() {
let service = InMemorySessionService::new();
for index in 0..(LIST_PAGE * 2 + 50) {
let session = service
.create(CreateRequest {
app_name: "app".into(),
user_id: "ana".into(),
session_id: Some(format!("s{index:04}")),
state: Default::default(),
})
.await
.unwrap();
if index % 3 == 0 {
service.archive(&session.try_identity().unwrap(), None).await.unwrap();
}
}
let all = service.list(listing(None, None)).await.unwrap();
let active: Vec<String> = all
.iter()
.filter(|session| ArchiveMark::of(session.as_ref()).is_none())
.map(|session| session.id().to_string())
.collect();
let archived: Vec<String> = all
.iter()
.filter(|session| ArchiveMark::of(session.as_ref()).is_some())
.map(|session| session.id().to_string())
.collect();
assert_eq!((active.len(), archived.len()), (166, 84));
assert_eq!(ids(&service.list_active(listing(None, None)).await.unwrap()), active);
assert_eq!(ids(&service.list_archived(listing(None, None)).await.unwrap()), archived);
let page = service.list_active(listing(Some(100), Some(50))).await.unwrap();
assert_eq!(ids(&page), active[50..150].to_vec());
let tail = service.list_active(listing(Some(100), Some(150))).await.unwrap();
assert_eq!(ids(&tail), active[150..].to_vec());
let page = service.list_archived(listing(Some(10), Some(80))).await.unwrap();
assert_eq!(ids(&page), archived[80..].to_vec());
assert!(service.list_active(listing(Some(5), Some(500))).await.unwrap().is_empty());
}
#[test]
fn only_an_object_is_a_mark() {
assert_eq!(ArchiveMark::in_state(None), None);
assert_eq!(ArchiveMark::in_state(Some(&Value::Null)), None);
assert_eq!(ArchiveMark::in_state(Some(&serde_json::json!(true))), None);
let mark = ArchiveMark::new(Some("done".into()));
let value = serde_json::to_value(&mark).unwrap();
assert_eq!(ArchiveMark::in_state(Some(&value)), Some(mark.clone()));
let event = mark.event().unwrap();
assert_eq!(event.author, ARCHIVE_AUTHOR);
assert!(event.llm_response.content.is_none());
assert_eq!(event.actions.state_delta[ARCHIVE_KEY], value);
let error = session_archived("s1", &mark);
assert_eq!((error.code, error.category), ("session.archived", ErrorCategory::Conflict));
assert!(error.message.contains("adk-rust sessions unarchive s1"), "{}", error.message);
}
}