Skip to main content

adk_session/
session.rs

1use crate::{Events, State};
2use adk_core::Result;
3use adk_core::identity::{AdkIdentity, AppName, SessionId, UserId};
4use chrono::{DateTime, Utc};
5
6/// Trait representing a conversation session with state and event history.
7pub trait Session: Send + Sync {
8    /// Returns the session identifier.
9    fn id(&self) -> &str;
10    /// Returns the application name that owns this session.
11    fn app_name(&self) -> &str;
12    /// Returns the user identifier for the session owner.
13    fn user_id(&self) -> &str;
14    /// Returns a reference to the session's state store.
15    fn state(&self) -> &dyn State;
16    /// Returns a reference to the session's event history.
17    fn events(&self) -> &dyn Events;
18    /// Returns the timestamp of the last update to this session.
19    fn last_update_time(&self) -> DateTime<Utc>;
20
21    /// Moves the event history out of this session, leaving it empty.
22    ///
23    /// The runner calls it on the session it loaded for an invocation, which no one else
24    /// holds, so each turn moves the history instead of copying it. The default returns a
25    /// copy of [`events()`](Self::events) and leaves the session unchanged; every
26    /// `adk-session` backend moves its events instead.
27    ///
28    /// # Example
29    ///
30    /// ```rust
31    /// use adk_session::{CreateRequest, InMemorySessionService, SessionService};
32    ///
33    /// # #[tokio::main]
34    /// # async fn main() -> adk_core::Result<()> {
35    /// let service = InMemorySessionService::new();
36    /// let mut session = service
37    ///     .create(CreateRequest {
38    ///         app_name: "app".into(),
39    ///         user_id: "user".into(),
40    ///         session_id: None,
41    ///         state: Default::default(),
42    ///     })
43    ///     .await?;
44    /// let events = session.take_events();
45    /// assert!(events.is_empty());
46    /// assert_eq!(session.events().len(), 0);
47    /// # Ok(())
48    /// # }
49    /// ```
50    fn take_events(&mut self) -> Vec<adk_core::Event> {
51        self.events().all()
52    }
53
54    /// Returns the application name as a typed [`AppName`].
55    ///
56    /// Parses the value returned by [`app_name()`](Self::app_name). Returns an
57    /// error if the raw string fails validation (empty, null bytes, or exceeds
58    /// the maximum length).
59    ///
60    /// # Errors
61    ///
62    /// Returns [`AdkError::config`](adk_core::AdkError::config) when the
63    /// underlying string is not a valid identifier.
64    fn try_app_name(&self) -> Result<AppName> {
65        Ok(AppName::try_from(self.app_name())?)
66    }
67
68    /// Returns the user identifier as a typed [`UserId`].
69    ///
70    /// Parses the value returned by [`user_id()`](Self::user_id). Returns an
71    /// error if the raw string fails validation.
72    ///
73    /// # Errors
74    ///
75    /// Returns [`AdkError::config`](adk_core::AdkError::config) when the
76    /// underlying string is not a valid identifier.
77    fn try_user_id(&self) -> Result<UserId> {
78        Ok(UserId::try_from(self.user_id())?)
79    }
80
81    /// Returns the session identifier as a typed [`SessionId`].
82    ///
83    /// Parses the value returned by [`id()`](Self::id). Returns an error if
84    /// the raw string fails validation.
85    ///
86    /// # Errors
87    ///
88    /// Returns [`AdkError::config`](adk_core::AdkError::config) when the
89    /// underlying string is not a valid identifier.
90    fn try_session_id(&self) -> Result<SessionId> {
91        Ok(SessionId::try_from(self.id())?)
92    }
93
94    /// Returns the stable session-scoped [`AdkIdentity`] triple.
95    ///
96    /// Combines [`try_app_name()`](Self::try_app_name),
97    /// [`try_user_id()`](Self::try_user_id), and
98    /// [`try_session_id()`](Self::try_session_id) into a single composite
99    /// identity value.
100    ///
101    /// # Errors
102    ///
103    /// Returns an error if any of the three constituent identifiers fail
104    /// validation.
105    fn try_identity(&self) -> Result<AdkIdentity> {
106        Ok(AdkIdentity {
107            app_name: self.try_app_name()?,
108            user_id: self.try_user_id()?,
109            session_id: self.try_session_id()?,
110        })
111    }
112}
113
114/// Key prefix for application-scoped state entries.
115pub const KEY_PREFIX_APP: &str = "app:";
116/// Key prefix for temporary state entries (stripped on event append).
117pub const KEY_PREFIX_TEMP: &str = "temp:";
118/// Key prefix for user-scoped state entries.
119pub const KEY_PREFIX_USER: &str = "user:";