Skip to main content

aura_agent/runtime/
lifecycle.rs

1//! Lifecycle Manager
2//!
3//! Manages component lifecycle and system shutdown.
4
5use super::EffectContext;
6use crate::handlers::SessionServiceApi;
7use crate::runtime::AuraEffectSystem;
8use std::sync::Arc;
9
10/// Lifecycle manager for coordinating system startup and shutdown
11pub struct LifecycleManager {
12    /// Session cleanup timeout in seconds (default: 1 hour)
13    session_cleanup_timeout: u64,
14}
15
16impl LifecycleManager {
17    /// Create a new lifecycle manager
18    pub fn new() -> Self {
19        Self {
20            session_cleanup_timeout: 3600, // 1 hour default
21        }
22    }
23
24    /// Create lifecycle manager with custom session timeout
25    pub fn with_session_timeout(timeout_seconds: u64) -> Self {
26        Self {
27            session_cleanup_timeout: timeout_seconds,
28        }
29    }
30
31    /// Initialize services on startup
32    ///
33    /// Performs startup tasks like cleaning up stale sessions.
34    pub async fn initialize(
35        &self,
36        effects: Arc<AuraEffectSystem>,
37        authority_context: crate::core::AuthorityContext,
38    ) -> Result<(), crate::AgentError> {
39        // Clean up any stale sessions from previous runs
40        let account_id = aura_core::types::identifiers::AccountId::new_from_entropy(
41            aura_core::hash::hash(&authority_context.authority_id().to_bytes()),
42        );
43
44        let session_service = SessionServiceApi::new(effects, authority_context, account_id)
45            .map_err(|e| crate::AgentError::runtime(format!("Session service init failed: {e}")))?;
46
47        // Clean up sessions older than the timeout
48        match session_service
49            .cleanup_expired(self.session_cleanup_timeout)
50            .await
51        {
52            Ok(cleaned) => {
53                if !cleaned.is_empty() {
54                    tracing::info!("Cleaned up {} expired sessions on startup", cleaned.len());
55                }
56            }
57            Err(e) => {
58                tracing::warn!("Failed to cleanup expired sessions on startup: {}", e);
59            }
60        }
61
62        Ok(())
63    }
64
65    /// Shutdown all managed components
66    pub async fn shutdown(self, _ctx: &EffectContext) -> Result<(), crate::AgentError> {
67        // Coordinate clean shutdown of all components
68        // Session data is already persisted to storage, so no action needed
69        tracing::info!("Lifecycle manager shutdown complete");
70        Ok(())
71    }
72}
73
74impl Default for LifecycleManager {
75    fn default() -> Self {
76        Self::new()
77    }
78}