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
6pub trait Session: Send + Sync {
7 fn id(&self) -> &str;
8 fn app_name(&self) -> &str;
9 fn user_id(&self) -> &str;
10 fn state(&self) -> &dyn State;
11 fn events(&self) -> &dyn Events;
12 fn last_update_time(&self) -> DateTime<Utc>;
13
14 /// Returns the application name as a typed [`AppName`].
15 ///
16 /// Parses the value returned by [`app_name()`](Self::app_name). Returns an
17 /// error if the raw string fails validation (empty, null bytes, or exceeds
18 /// the maximum length).
19 ///
20 /// # Errors
21 ///
22 /// Returns [`AdkError::Config`](adk_core::AdkError::Config) when the
23 /// underlying string is not a valid identifier.
24 fn try_app_name(&self) -> Result<AppName> {
25 Ok(AppName::try_from(self.app_name())?)
26 }
27
28 /// Returns the user identifier as a typed [`UserId`].
29 ///
30 /// Parses the value returned by [`user_id()`](Self::user_id). Returns an
31 /// error if the raw string fails validation.
32 ///
33 /// # Errors
34 ///
35 /// Returns [`AdkError::Config`](adk_core::AdkError::Config) when the
36 /// underlying string is not a valid identifier.
37 fn try_user_id(&self) -> Result<UserId> {
38 Ok(UserId::try_from(self.user_id())?)
39 }
40
41 /// Returns the session identifier as a typed [`SessionId`].
42 ///
43 /// Parses the value returned by [`id()`](Self::id). Returns an error if
44 /// the raw string fails validation.
45 ///
46 /// # Errors
47 ///
48 /// Returns [`AdkError::Config`](adk_core::AdkError::Config) when the
49 /// underlying string is not a valid identifier.
50 fn try_session_id(&self) -> Result<SessionId> {
51 Ok(SessionId::try_from(self.id())?)
52 }
53
54 /// Returns the stable session-scoped [`AdkIdentity`] triple.
55 ///
56 /// Combines [`try_app_name()`](Self::try_app_name),
57 /// [`try_user_id()`](Self::try_user_id), and
58 /// [`try_session_id()`](Self::try_session_id) into a single composite
59 /// identity value.
60 ///
61 /// # Errors
62 ///
63 /// Returns an error if any of the three constituent identifiers fail
64 /// validation.
65 fn try_identity(&self) -> Result<AdkIdentity> {
66 Ok(AdkIdentity {
67 app_name: self.try_app_name()?,
68 user_id: self.try_user_id()?,
69 session_id: self.try_session_id()?,
70 })
71 }
72}
73
74pub const KEY_PREFIX_APP: &str = "app:";
75pub const KEY_PREFIX_TEMP: &str = "temp:";
76pub const KEY_PREFIX_USER: &str = "user:";