ass_editor/sessions/
lifecycle.rs1use super::config::SessionConfig;
7use super::manager::EditorSessionManager;
8use super::session::EditorSession;
9use crate::core::{EditorDocument, EditorError, Result};
10
11#[cfg(not(feature = "std"))]
12use alloc::{
13 string::{String, ToString},
14 vec::Vec,
15};
16
17impl EditorSessionManager {
18 pub fn new() -> Self {
20 Self::with_config(SessionConfig::default())
21 }
22
23 pub fn create_session(&mut self, session_id: String) -> Result<()> {
25 self.create_session_with_document(session_id, EditorDocument::new())
26 }
27
28 pub fn create_session_with_document(
30 &mut self,
31 session_id: String,
32 document: EditorDocument,
33 ) -> Result<()> {
34 self.with_inner_mut(|inner| {
35 if inner.sessions.len() >= inner.config.max_sessions {
37 return Err(EditorError::SessionLimitExceeded {
38 current: inner.sessions.len(),
39 limit: inner.config.max_sessions,
40 });
41 }
42
43 let session = EditorSession::new(session_id.clone(), document);
45
46 inner.sessions.insert(session_id.clone(), session);
48
49 inner.stats.active_sessions += 1;
51
52 if inner.active_session_id.is_none() {
54 inner.active_session_id = Some(session_id);
55 }
56
57 Ok(())
58 })
59 }
60
61 pub fn switch_session(&mut self, session_id: &str) -> Result<()> {
63 self.with_inner_mut(|inner| {
64 if !inner.sessions.contains_key(session_id) {
66 return Err(EditorError::DocumentNotFound {
67 id: session_id.to_string(),
68 });
69 }
70
71 inner.active_session_id = Some(session_id.to_string());
73
74 #[cfg(feature = "std")]
76 if let Some(session) = inner.sessions.get_mut(session_id) {
77 session.touch();
78 }
79
80 Ok(())
81 })
82 }
83
84 pub fn active_session(&self) -> Result<Option<String>> {
86 Ok(self.with_inner(|inner| inner.active_session_id.clone()))
87 }
88
89 pub fn remove_session(&mut self, session_id: &str) -> Result<EditorSession> {
91 self.with_inner_mut(|inner| {
92 let session =
93 inner
94 .sessions
95 .remove(session_id)
96 .ok_or_else(|| EditorError::DocumentNotFound {
97 id: session_id.to_string(),
98 })?;
99
100 inner.stats.active_sessions -= 1;
102 inner.stats.total_memory_usage -= session.memory_usage;
103
104 if inner.active_session_id.as_ref() == Some(&session_id.to_string()) {
106 inner.active_session_id = None;
107 }
108
109 Ok(session)
110 })
111 }
112
113 pub fn list_sessions(&self) -> Result<Vec<String>> {
115 Ok(self.with_inner(|inner| inner.sessions.keys().cloned().collect()))
116 }
117}
118
119impl Default for EditorSessionManager {
120 fn default() -> Self {
121 Self::new()
122 }
123}