Skip to main content

adk_session/
service.rs

1use crate::history::{
2    ForkRequest, HistoryOutcome, HistoryRewrite, ImportSessionRequest, RewriteHistoryRequest,
3    SessionHistory,
4};
5use crate::{Event, Session};
6use adk_core::identity::{AdkIdentity, AppName, SessionId, UserId};
7use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
8use async_trait::async_trait;
9use chrono::{DateTime, Utc};
10use serde_json::Value;
11use std::collections::HashMap;
12
13/// Request to create a new session.
14#[derive(Debug, Clone)]
15pub struct CreateRequest {
16    /// Application name that owns the session.
17    pub app_name: String,
18    /// User identifier for the session owner.
19    pub user_id: String,
20    /// Optional session ID; generated if not provided.
21    pub session_id: Option<String>,
22    /// Initial state key-value pairs for the session.
23    pub state: HashMap<String, Value>,
24}
25
26impl CreateRequest {
27    /// Returns the application name as a typed [`AppName`].
28    ///
29    /// # Errors
30    ///
31    /// Returns an error if the raw string fails identity validation.
32    pub fn try_app_name(&self) -> Result<AppName> {
33        Ok(AppName::try_from(self.app_name.as_str())?)
34    }
35
36    /// Returns the user identifier as a typed [`UserId`].
37    ///
38    /// # Errors
39    ///
40    /// Returns an error if the raw string fails identity validation.
41    pub fn try_user_id(&self) -> Result<UserId> {
42        Ok(UserId::try_from(self.user_id.as_str())?)
43    }
44
45    /// Returns the session identifier as a typed [`SessionId`], if one was
46    /// provided.
47    ///
48    /// Returns `Ok(None)` when `session_id` is `None` (the service will
49    /// generate one). Returns an error only when a non-`None` value fails
50    /// identity validation.
51    ///
52    /// # Errors
53    ///
54    /// Returns an error if the provided session ID string fails validation.
55    pub fn try_session_id(&self) -> Result<Option<SessionId>> {
56        self.session_id.as_deref().map(SessionId::try_from).transpose().map_err(Into::into)
57    }
58
59    /// Returns the stable session-scoped [`AdkIdentity`] triple, if a session
60    /// ID was provided.
61    ///
62    /// Because `CreateRequest` allows `session_id` to be `None` (the backend
63    /// generates one), this returns `Ok(None)` when no session ID is present.
64    /// The app name and user ID are validated either way, so a backend can call
65    /// this once to validate every identifier the request carries.
66    ///
67    /// # Errors
68    ///
69    /// Returns an error if any of the constituent identifiers fail validation.
70    pub fn try_identity(&self) -> Result<Option<AdkIdentity>> {
71        let app_name = self.try_app_name()?;
72        let user_id = self.try_user_id()?;
73        Ok(self.try_session_id()?.map(|session_id| AdkIdentity { app_name, user_id, session_id }))
74    }
75}
76
77/// Request to retrieve an existing session.
78#[derive(Debug, Clone)]
79pub struct GetRequest {
80    /// Application name that owns the session.
81    pub app_name: String,
82    /// User identifier for the session owner.
83    pub user_id: String,
84    /// Session identifier to retrieve.
85    pub session_id: String,
86    /// If set, only return the N most recent events.
87    pub num_recent_events: Option<usize>,
88    /// If set, only return events after this timestamp.
89    pub after: Option<DateTime<Utc>>,
90}
91
92impl GetRequest {
93    /// Returns the stable session-scoped [`AdkIdentity`] triple.
94    ///
95    /// Parses `app_name`, `user_id`, and `session_id` into their typed
96    /// equivalents and combines them into an [`AdkIdentity`].
97    ///
98    /// # Errors
99    ///
100    /// Returns an error if any of the three identifiers fail validation.
101    pub fn try_identity(&self) -> Result<AdkIdentity> {
102        Ok(AdkIdentity {
103            app_name: AppName::try_from(self.app_name.as_str())?,
104            user_id: UserId::try_from(self.user_id.as_str())?,
105            session_id: SessionId::try_from(self.session_id.as_str())?,
106        })
107    }
108}
109
110/// Validates the `(app_name, user_id)` scope addressed by `list` and `delete_all_sessions`.
111pub(crate) fn validate_scope(app_name: &str, user_id: &str) -> Result<()> {
112    AppName::try_from(app_name)?;
113    UserId::try_from(user_id)?;
114    Ok(())
115}
116
117/// Validates a session ID addressed on its own, as by `append_event`.
118pub(crate) fn validate_session_id(session_id: &str) -> Result<()> {
119    SessionId::try_from(session_id)?;
120    Ok(())
121}
122
123/// Builds the canonical error returned when a session identity has no matching record.
124pub(crate) fn session_not_found(req: &GetRequest) -> AdkError {
125    session_not_found_for(&req.app_name, &req.user_id, &req.session_id)
126}
127
128/// Builds the canonical not-found error for a raw `(app_name, user_id, session_id)` triple.
129pub(crate) fn session_not_found_for(app_name: &str, user_id: &str, session_id: &str) -> AdkError {
130    AdkError::not_found(
131        ErrorComponent::Session,
132        "session.not_found",
133        format!("session '{session_id}' was not found for app '{app_name}' and user '{user_id}'"),
134    )
135}
136
137/// Builds the canonical not-found error for a typed session identity.
138pub(crate) fn identity_not_found(identity: &AdkIdentity) -> AdkError {
139    session_not_found_for(
140        identity.app_name.as_ref(),
141        identity.user_id.as_ref(),
142        identity.session_id.as_ref(),
143    )
144}
145
146/// Builds the canonical not-found error for a session addressed by its ID alone.
147pub(crate) fn session_id_not_found(session_id: &str) -> AdkError {
148    AdkError::not_found(
149        ErrorComponent::Session,
150        "session.not_found",
151        format!("session '{session_id}' was not found"),
152    )
153}
154
155/// Builds the error for a session ID that more than one app or user owns.
156pub(crate) fn ambiguous_session_id(session_id: &str) -> AdkError {
157    AdkError::new(
158        ErrorComponent::Session,
159        ErrorCategory::InvalidInput,
160        "session.ambiguous_id",
161        format!(
162            "session ID '{session_id}' exists for more than one app or user; use \
163             append_event_for_identity to address the session unambiguously"
164        ),
165    )
166}
167
168/// Builds the canonical conflict error returned when `create` names an existing session.
169pub(crate) fn session_already_exists(app_name: &str, user_id: &str, session_id: &str) -> AdkError {
170    AdkError::new(
171        ErrorComponent::Session,
172        ErrorCategory::Conflict,
173        "session.already_exists",
174        format!(
175            "session '{session_id}' already exists for app '{app_name}' and user '{user_id}'; \
176             read it with get, or omit session_id to create a new one"
177        ),
178    )
179}
180
181/// Builds the error returned when a rewind target is not an event of the session.
182pub(crate) fn rewind_event_not_found(identity: &AdkIdentity, event_id: &str) -> AdkError {
183    AdkError::not_found(
184        ErrorComponent::Session,
185        "session.event_not_found",
186        format!(
187            "event '{event_id}' is not in session '{}'; rewind targets an event the session holds",
188            identity.session_id
189        ),
190    )
191}
192
193/// Builds the error returned when `rewind_steps` asks for more steps than the session has events.
194pub(crate) fn rewind_steps_exceed(identity: &AdkIdentity, steps: usize, events: usize) -> AdkError {
195    AdkError::new(
196        ErrorComponent::Session,
197        ErrorCategory::InvalidInput,
198        "session.rewind.too_many_steps",
199        format!(
200            "cannot rewind {steps} steps: session '{}' holds {events} events",
201            identity.session_id
202        ),
203    )
204}
205
206/// Builds the error a backend returns for a history operation it cannot perform.
207pub(crate) fn history_unsupported(operation: &str, reason: &str) -> AdkError {
208    AdkError::new(
209        ErrorComponent::Session,
210        ErrorCategory::Unsupported,
211        "session.history.unsupported",
212        format!("this session backend cannot {operation}: {reason}"),
213    )
214}
215
216/// Request to list sessions for a given app and user.
217#[derive(Debug, Clone)]
218pub struct ListRequest {
219    /// Application name to filter sessions by.
220    pub app_name: String,
221    /// User identifier to filter sessions by.
222    pub user_id: String,
223    /// Maximum number of sessions to return. `None` means no limit.
224    pub limit: Option<usize>,
225    /// Number of sessions to skip for pagination. `None` means start from the beginning.
226    pub offset: Option<usize>,
227}
228
229impl ListRequest {
230    /// Returns the application name as a typed [`AppName`].
231    ///
232    /// # Errors
233    ///
234    /// Returns an error if the raw string fails identity validation.
235    pub fn try_app_name(&self) -> Result<AppName> {
236        Ok(AppName::try_from(self.app_name.as_str())?)
237    }
238
239    /// Returns the user identifier as a typed [`UserId`].
240    ///
241    /// # Errors
242    ///
243    /// Returns an error if the raw string fails identity validation.
244    pub fn try_user_id(&self) -> Result<UserId> {
245        Ok(UserId::try_from(self.user_id.as_str())?)
246    }
247}
248
249/// Request to append an event to a session using typed [`AdkIdentity`] addressing.
250///
251/// This is the preferred way to append events in new code because it uses the
252/// full `(app_name, user_id, session_id)` triple, eliminating ambiguity that
253/// can arise when a bare `session_id` string is not globally unique.
254///
255/// # Example
256///
257/// ```rust
258/// use adk_core::identity::{AdkIdentity, AppName, SessionId, UserId};
259/// use adk_session::AppendEventRequest;
260/// use adk_session::Event;
261///
262/// let identity = AdkIdentity::new(
263///     AppName::try_from("weather-app").unwrap(),
264///     UserId::try_from("user-123").unwrap(),
265///     SessionId::try_from("session-456").unwrap(),
266/// );
267///
268/// let event = Event::new("inv-001");
269/// let req = AppendEventRequest { identity, event };
270/// ```
271#[derive(Debug, Clone)]
272pub struct AppendEventRequest {
273    /// The typed session-scoped identity triple.
274    pub identity: AdkIdentity,
275    /// The event to append.
276    pub event: Event,
277}
278
279/// Request to delete a session.
280#[derive(Debug, Clone)]
281pub struct DeleteRequest {
282    /// Application name that owns the session.
283    pub app_name: String,
284    /// User identifier for the session owner.
285    pub user_id: String,
286    /// Session identifier to delete.
287    pub session_id: String,
288}
289
290impl DeleteRequest {
291    /// Returns the stable session-scoped [`AdkIdentity`] triple.
292    ///
293    /// Parses `app_name`, `user_id`, and `session_id` into their typed
294    /// equivalents and combines them into an [`AdkIdentity`].
295    ///
296    /// # Errors
297    ///
298    /// Returns an error if any of the three identifiers fail validation.
299    pub fn try_identity(&self) -> Result<AdkIdentity> {
300        Ok(AdkIdentity {
301            app_name: AppName::try_from(self.app_name.as_str())?,
302            user_id: UserId::try_from(self.user_id.as_str())?,
303            session_id: SessionId::try_from(self.session_id.as_str())?,
304        })
305    }
306}
307
308/// Trait for session persistence backends.
309///
310/// Implementations manage the full lifecycle of sessions: creation, retrieval,
311/// listing, deletion, and event appending.
312///
313/// Every method validates the app names, user IDs, and session IDs it receives against the
314/// [`AppName`], [`UserId`], and [`SessionId`] rules (non-empty, at most
315/// [`MAX_ID_LEN`](adk_core::identity::MAX_ID_LEN) bytes, no NUL) before it reads or writes
316/// storage, and rejects an invalid one with an
317/// [`InvalidInput`](adk_core::ErrorCategory::InvalidInput) error. The built-in backends all
318/// follow this rule.
319#[async_trait]
320pub trait SessionService: Send + Sync {
321    /// Creates a new session and returns it.
322    ///
323    /// # Errors
324    ///
325    /// Returns an invalid-input error when an identifier fails validation, and an
326    /// [`AdkError`] with code `session.already_exists` and a
327    /// [`Conflict`](adk_core::ErrorCategory::Conflict) category when a session with the same
328    /// `(app_name, user_id, session_id)` already exists. A conflicting create changes nothing:
329    /// the existing session keeps its events and state, and the app and user tiers are not
330    /// written. Callers that get-or-create read the session again on a conflict.
331    async fn create(&self, req: CreateRequest) -> Result<Box<dyn Session>>;
332    /// Retrieves an existing session by its complete identity.
333    ///
334    /// Implementations address sessions by the full `(app_name, user_id, session_id)` tuple.
335    /// When that valid identity has no matching record, implementations return an
336    /// [`AdkError`] with code `session.not_found` and a
337    /// [`NotFound`](adk_core::ErrorCategory::NotFound) category. Backend and transport failures
338    /// must not be reported as not-found errors.
339    ///
340    /// # Errors
341    ///
342    /// Returns an invalid-input error when an identifier fails validation, `session.not_found`
343    /// when no matching session exists, or a backend-specific error when retrieval fails.
344    async fn get(&self, req: GetRequest) -> Result<Box<dyn Session>>;
345    /// Lists the sessions of an app and user, most recently updated first.
346    ///
347    /// Sessions updated at the same instant are ordered by session ID, descending, so
348    /// `offset`/`limit` pages are stable. Archived sessions are listed too, with their
349    /// [`ArchiveMark`](crate::ArchiveMark) in their state;
350    /// [`list_active`](SessionService::list_active) leaves them out.
351    async fn list(&self, req: ListRequest) -> Result<Vec<Box<dyn Session>>>;
352    /// Delete a session by its identifiers.
353    async fn delete(&self, req: DeleteRequest) -> Result<()>;
354    /// Appends an event to the session with this ID.
355    ///
356    /// Events read back in timestamp order; events with equal timestamps keep the order they
357    /// were appended in.
358    ///
359    /// # Errors
360    ///
361    /// Returns `session.not_found` ([`NotFound`](adk_core::ErrorCategory::NotFound)) when no
362    /// session has this ID. An ID alone does not name one session when more than one app or
363    /// user holds it, so prefer
364    /// [`append_event_for_identity`](SessionService::append_event_for_identity).
365    async fn append_event(&self, session_id: &str, event: Event) -> Result<()>;
366
367    /// Get a session using typed [`AdkIdentity`] addressing.
368    ///
369    /// This is the preferred path for new code. It constructs a [`GetRequest`]
370    /// from the full `(app_name, user_id, session_id)` triple so that session
371    /// lookup is unambiguous.
372    ///
373    /// The default implementation delegates to
374    /// [`get`](SessionService::get) with a freshly built [`GetRequest`].
375    ///
376    /// # Errors
377    ///
378    /// Returns an error if the session cannot be retrieved.
379    async fn get_for_identity(&self, identity: &AdkIdentity) -> Result<Box<dyn Session>> {
380        self.get(GetRequest {
381            app_name: identity.app_name.as_ref().to_string(),
382            user_id: identity.user_id.as_ref().to_string(),
383            session_id: identity.session_id.as_ref().to_string(),
384            num_recent_events: None,
385            after: None,
386        })
387        .await
388    }
389
390    /// Delete a session using typed [`AdkIdentity`] addressing.
391    ///
392    /// This is the preferred path for new code. It constructs a
393    /// [`DeleteRequest`] from the full `(app_name, user_id, session_id)` triple
394    /// so that session deletion is unambiguous.
395    ///
396    /// The default implementation delegates to
397    /// [`delete`](SessionService::delete) with a freshly built
398    /// [`DeleteRequest`].
399    ///
400    /// # Errors
401    ///
402    /// Returns an error if the session cannot be deleted.
403    async fn delete_for_identity(&self, identity: &AdkIdentity) -> Result<()> {
404        self.delete(DeleteRequest {
405            app_name: identity.app_name.as_ref().to_string(),
406            user_id: identity.user_id.as_ref().to_string(),
407            session_id: identity.session_id.as_ref().to_string(),
408        })
409        .await
410    }
411
412    /// Append an event to a session using typed [`AdkIdentity`] addressing.
413    ///
414    /// This is the preferred path for new code. It uses the full
415    /// `(app_name, user_id, session_id)` triple so that session lookup is
416    /// unambiguous even when the same `session_id` string appears under
417    /// different apps or users.
418    ///
419    /// The default implementation delegates to the legacy
420    /// [`append_event`](SessionService::append_event) method using only the
421    /// `session_id` component. Backends that support composite-key addressing
422    /// should override this method to use all three identity fields.
423    ///
424    /// # Errors
425    ///
426    /// Returns an error if the event cannot be appended.
427    async fn append_event_for_identity(&self, req: AppendEventRequest) -> Result<()> {
428        self.append_event(req.identity.session_id.as_ref(), req.event).await
429    }
430
431    /// Erases what the user `user_id` holds in the app `app_name`: every session with its
432    /// events, and the user's `user:` state tier.
433    ///
434    /// The `app:` tier, the user's sessions and state in other apps, and other users'
435    /// sessions and state are untouched. No other method removes the `user:` tier, so this is
436    /// the call for bulk cleanup and for a request to erase a user's session data. The tier is
437    /// erased when the user has no sessions left, and a repeated call succeeds.
438    ///
439    /// The default implementation validates the identifiers, then returns
440    /// `session.delete_all.unsupported`.
441    ///
442    /// # Errors
443    ///
444    /// Returns an invalid-input error when an identifier fails validation,
445    /// `session.delete_all.unsupported` ([`Unsupported`](adk_core::ErrorCategory::Unsupported))
446    /// from a backend that does not implement it, or a backend error. A backend that cannot
447    /// erase in one transaction may have removed some sessions before the error; calling again
448    /// finishes the erasure.
449    async fn delete_all_sessions(&self, app_name: &str, user_id: &str) -> Result<()> {
450        validate_scope(app_name, user_id)?;
451        Err(AdkError::new(
452            ErrorComponent::Session,
453            ErrorCategory::Unsupported,
454            "session.delete_all.unsupported",
455            "this session backend does not implement delete_all_sessions; delete each session \
456             from `list` and erase the user's `user:` state in the backend",
457        ))
458    }
459
460    /// Reads the stored history of the session `identity`: its events, its own state, and the
461    /// state it was created with.
462    ///
463    /// The default reads the session with [`get_for_identity`](SessionService::get_for_identity)
464    /// and reports no recorded creation state; every `adk-session` backend that records one
465    /// returns it.
466    ///
467    /// # Errors
468    ///
469    /// Returns `session.not_found` when the session does not exist, or a backend error.
470    async fn history(&self, identity: &AdkIdentity) -> Result<SessionHistory> {
471        let session = self.get_for_identity(identity).await?;
472        let (_, _, state) = crate::state_utils::extract_state_deltas(&session.state().all());
473        Ok(SessionHistory::new(session.events().all(), state, None))
474    }
475
476    /// Rewrites the history of a session in place: a rewind or an edit.
477    ///
478    /// The backend reads the session, applies [`SessionHistory::rewrite`] to it, and writes the
479    /// result atomically, so a concurrent append either lands before the read or after the
480    /// write. The session's own state is rebuilt from the state it was created with plus the
481    /// state deltas of the events it keeps; the `app:` and `user:` tiers do not change. Only the
482    /// session that `identity` names changes, even when other apps or users hold a session with
483    /// the same ID. The rules every history operation follows are in [`crate::history`].
484    ///
485    /// # Errors
486    ///
487    /// Returns `session.history.unsupported` ([`Unsupported`](adk_core::ErrorCategory::Unsupported))
488    /// when the backend cannot delete events, `session.not_found` when the session does not
489    /// exist, and the errors of [`SessionHistory::rewrite`].
490    async fn rewrite_history(&self, _req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
491        Err(history_unsupported("rewrite history", "it does not implement rewrite_history"))
492    }
493
494    /// Creates a session that already holds events, without applying their state deltas to
495    /// the `app:` and `user:` tiers.
496    ///
497    /// # Errors
498    ///
499    /// Returns `session.history.unsupported` when the backend does not implement it,
500    /// `session.already_exists` ([`Conflict`](adk_core::ErrorCategory::Conflict)) when the session
501    /// exists, and an invalid-input error when an identifier fails validation.
502    async fn import_session(&self, _req: ImportSessionRequest) -> Result<Box<dyn Session>> {
503        Err(history_unsupported("import a session", "it does not implement import_session"))
504    }
505
506    /// Forks a session: creates a session of the same app and user that holds the source's
507    /// events up to [`ForkRequest::at_event_id`], with the state the source had there.
508    ///
509    /// The source does not change. The fork's events keep their IDs and timestamps, its state is
510    /// the source's creation state plus the deltas of the copied events, and it records its
511    /// [`ForkOrigin`](crate::ForkOrigin) under [`FORK_ORIGIN_KEY`](crate::FORK_ORIGIN_KEY). The
512    /// default reads the source with [`history`](SessionService::history) and creates the fork
513    /// with [`import_session`](SessionService::import_session).
514    ///
515    /// # Example
516    ///
517    /// ```rust
518    /// use adk_session::{CreateRequest, Event, ForkRequest, InMemorySessionService, SessionService};
519    ///
520    /// # #[tokio::main(flavor = "current_thread")]
521    /// # async fn main() -> adk_core::Result<()> {
522    /// let service = InMemorySessionService::new();
523    /// let source = service
524    ///     .create(CreateRequest {
525    ///         app_name: "app".into(),
526    ///         user_id: "alice".into(),
527    ///         session_id: Some("main".into()),
528    ///         state: Default::default(),
529    ///     })
530    ///     .await?;
531    /// let identity = source.try_identity()?;
532    /// let first = Event::new("inv-1");
533    /// let first_id = first.id.clone();
534    /// for event in [first, Event::new("inv-2")] {
535    ///     service
536    ///         .append_event_for_identity(adk_session::AppendEventRequest {
537    ///             identity: identity.clone(),
538    ///             event,
539    ///         })
540    ///         .await?;
541    /// }
542    ///
543    /// let fork = service.fork(ForkRequest::new(identity).at_event(first_id)).await?;
544    /// assert_eq!(fork.session.events().len(), 1);
545    /// # Ok(())
546    /// # }
547    /// ```
548    ///
549    /// # Errors
550    ///
551    /// Returns `session.not_found` when the source does not exist, `session.already_exists`
552    /// when the fork's session ID is taken, `session.history.unsupported` from a backend that
553    /// cannot import, and the errors of [`SessionHistory::fork`].
554    async fn fork(&self, req: ForkRequest) -> Result<HistoryOutcome> {
555        let source = self.history(&req.source).await?;
556        let (import, change) = source.fork(&req)?;
557        let session = self.import_session(import).await?;
558        Ok(HistoryOutcome::new(session, change))
559    }
560
561    /// Rewinds the session `identity` to `target_event_id`, removing every event after it.
562    ///
563    /// A [`rewrite_history`](SessionService::rewrite_history) with
564    /// [`HistoryRewrite::RewindTo`].
565    ///
566    /// # Errors
567    ///
568    /// Returns `session.event_not_found` when the target is not an event of the session, and
569    /// the errors of [`rewrite_history`](SessionService::rewrite_history).
570    async fn rewind(
571        &self,
572        identity: &AdkIdentity,
573        target_event_id: &str,
574    ) -> Result<Box<dyn Session>> {
575        let rewrite = HistoryRewrite::RewindTo { event_id: target_event_id.to_string() };
576        Ok(self
577            .rewrite_history(RewriteHistoryRequest::new(identity.clone(), rewrite))
578            .await?
579            .session)
580    }
581
582    /// Rewinds the session `identity` by `steps` events from the end.
583    ///
584    /// `steps == 0` returns the session unchanged, and `steps` equal to the event count removes
585    /// every event and leaves the state the session was created with.
586    ///
587    /// # Errors
588    ///
589    /// Returns `session.rewind.too_many_steps` ([`InvalidInput`](adk_core::ErrorCategory::InvalidInput))
590    /// when `steps` exceeds the event count, and the errors of
591    /// [`rewrite_history`](SessionService::rewrite_history).
592    async fn rewind_steps(&self, identity: &AdkIdentity, steps: usize) -> Result<Box<dyn Session>> {
593        if steps == 0 {
594            return self.get_for_identity(identity).await;
595        }
596        let rewrite = HistoryRewrite::RewindSteps { steps };
597        Ok(self
598            .rewrite_history(RewriteHistoryRequest::new(identity.clone(), rewrite))
599            .await?
600            .session)
601    }
602
603    /// Verify backend connectivity.
604    ///
605    /// Returns `Ok(())` if the backend is reachable and responsive.
606    /// Use this for Kubernetes readiness probes and `/healthz` endpoints.
607    /// The default implementation always succeeds (suitable for in-memory).
608    async fn health_check(&self) -> Result<()> {
609        Ok(())
610    }
611
612    /// Archives the session `identity`: it keeps its events and state, is left out of
613    /// [`list_active`](SessionService::list_active), and takes no new turns until
614    /// [`unarchive`](SessionService::unarchive) (see [`crate::archive`]).
615    ///
616    /// The mark is written to the session's own state under [`ARCHIVE_KEY`](crate::ARCHIVE_KEY)
617    /// by a content-less marker event, through
618    /// [`append_event_for_identity`](SessionService::append_event_for_identity), so it works on
619    /// every backend. Archiving an archived session changes nothing and returns its mark.
620    ///
621    /// # Example
622    ///
623    /// ```rust
624    /// use adk_session::{CreateRequest, InMemorySessionService, SessionService};
625    ///
626    /// # #[tokio::main(flavor = "current_thread")]
627    /// # async fn main() -> adk_core::Result<()> {
628    /// let service = InMemorySessionService::new();
629    /// let session = service
630    ///     .create(CreateRequest {
631    ///         app_name: "app".into(),
632    ///         user_id: "ana".into(),
633    ///         session_id: Some("s".into()),
634    ///         state: Default::default(),
635    ///     })
636    ///     .await?;
637    /// let identity = session.try_identity()?;
638    /// let first = service.archive(&identity, Some("done".into())).await?;
639    /// let again = service.archive(&identity, None).await?;
640    /// assert_eq!(first, again);
641    /// # Ok(())
642    /// # }
643    /// ```
644    ///
645    /// # Errors
646    ///
647    /// Returns `session.not_found` when the session does not exist, or a backend error.
648    async fn archive(
649        &self,
650        identity: &AdkIdentity,
651        reason: Option<String>,
652    ) -> Result<crate::ArchiveMark> {
653        let session = self.get_for_identity(identity).await?;
654        if let Some(mark) = crate::ArchiveMark::of(session.as_ref()) {
655            return Ok(mark);
656        }
657        let mark = crate::ArchiveMark::new(reason);
658        self.append_event_for_identity(AppendEventRequest {
659            identity: identity.clone(),
660            event: mark.event()?,
661        })
662        .await?;
663        Ok(mark)
664    }
665
666    /// Unarchives the session `identity`: it lists and takes turns again. Unarchiving a
667    /// session that is not archived changes nothing.
668    ///
669    /// The mark is cleared by a content-less marker event that sets
670    /// [`ARCHIVE_KEY`](crate::ARCHIVE_KEY) to `null`.
671    ///
672    /// # Errors
673    ///
674    /// Returns `session.not_found` when the session does not exist, or a backend error.
675    async fn unarchive(&self, identity: &AdkIdentity) -> Result<()> {
676        let session = self.get_for_identity(identity).await?;
677        if crate::ArchiveMark::of(session.as_ref()).is_none() {
678            return Ok(());
679        }
680        self.append_event_for_identity(AppendEventRequest {
681            identity: identity.clone(),
682            event: crate::archive::marker_event(Value::Null),
683        })
684        .await
685    }
686
687    /// Writes the session `identity` out as a portable [`SessionBundle`](crate::SessionBundle):
688    /// its identity, its own state, every event and its archive mark.
689    ///
690    /// # Errors
691    ///
692    /// Returns `session.not_found` when the session does not exist, or a backend error.
693    async fn export_session(&self, identity: &AdkIdentity) -> Result<crate::SessionBundle> {
694        let session = self.get_for_identity(identity).await?;
695        Ok(crate::SessionBundle::of(session.as_ref()))
696    }
697
698    /// Lists the sessions of an app and user that are not archived, in
699    /// [`list`](SessionService::list)'s order; `offset` and `limit` count only these.
700    ///
701    /// This is the listing a person sees: `adk-rust sessions list` and the REST API's
702    /// session list use it. The default reads [`list`](SessionService::list) a page at a
703    /// time and leaves archived sessions out.
704    ///
705    /// # Errors
706    ///
707    /// Returns what [`list`](SessionService::list) returns.
708    async fn list_active(&self, req: ListRequest) -> Result<Vec<Box<dyn Session>>> {
709        list_kept(self, req, crate::archive::Keep::Active).await
710    }
711
712    /// Lists the archived sessions of an app and user, in [`list`](SessionService::list)'s
713    /// order; `offset` and `limit` count only these.
714    ///
715    /// # Errors
716    ///
717    /// Returns what [`list`](SessionService::list) returns.
718    async fn list_archived(&self, req: ListRequest) -> Result<Vec<Box<dyn Session>>> {
719        list_kept(self, req, crate::archive::Keep::Archived).await
720    }
721}
722
723/// The sessions of `req` that `keep` keeps, with `offset` and `limit` counting only those,
724/// read from `list` a page at a time.
725async fn list_kept<S: SessionService + ?Sized>(
726    service: &S,
727    req: ListRequest,
728    keep: crate::archive::Keep,
729) -> Result<Vec<Box<dyn Session>>> {
730    validate_scope(&req.app_name, &req.user_id)?;
731    let mut skip = req.offset.unwrap_or(0);
732    let limit = req.limit.unwrap_or(usize::MAX);
733    let mut kept = Vec::new();
734    let mut position = 0;
735    while kept.len() < limit {
736        let page = service
737            .list(ListRequest {
738                app_name: req.app_name.clone(),
739                user_id: req.user_id.clone(),
740                limit: Some(crate::archive::LIST_PAGE),
741                offset: Some(position),
742            })
743            .await?;
744        let read = page.len();
745        position += read;
746        for session in page {
747            if !keep.keeps(session.as_ref()) {
748                continue;
749            }
750            if skip > 0 {
751                skip -= 1;
752                continue;
753            }
754            if kept.len() < limit {
755                kept.push(session);
756            }
757        }
758        if read < crate::archive::LIST_PAGE {
759            break;
760        }
761    }
762    Ok(kept)
763}