-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession_manager.py
More file actions
104 lines (80 loc) · 3.63 KB
/
session_manager.py
File metadata and controls
104 lines (80 loc) · 3.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
"""
In-memory session management for chatbot conversations
"""
import uuid
from datetime import datetime, timedelta
from typing import Dict, List, Optional
from threading import Lock
from models import ChatMessage, MessageRole
class Session:
def __init__(self, session_id: str):
self.session_id = session_id
self.messages: List[ChatMessage] = []
self.created_at = datetime.utcnow()
self.last_accessed = datetime.utcnow()
def add_message(self, role: MessageRole, content: str) -> None:
"""Add a message to the session"""
message = ChatMessage(role=role, content=content)
self.messages.append(message)
self.last_accessed = datetime.utcnow()
def get_messages(self) -> List[ChatMessage]:
"""Get all messages in the session"""
self.last_accessed = datetime.utcnow()
return self.messages.copy()
def is_expired(self, timeout_hours: int = 1) -> bool:
"""Check if session is expired based on last access time"""
timeout_delta = timedelta(hours=timeout_hours)
return datetime.utcnow() - self.last_accessed > timeout_delta
class SessionManager:
def __init__(self, session_timeout_hours: int = 1):
self.sessions: Dict[str, Session] = {}
self.session_timeout_hours = session_timeout_hours
self._lock = Lock() # Thread safety for concurrent access
def create_session(self) -> str:
"""Create a new session and return its ID"""
session_id = str(uuid.uuid4())
with self._lock:
session = Session(session_id)
self.sessions[session_id] = session
return session_id
def get_session(self, session_id: str) -> Optional[Session]:
"""Get a session by ID, return None if not found or expired"""
with self._lock:
session = self.sessions.get(session_id)
if session is None:
return None
if session.is_expired(self.session_timeout_hours):
# Remove expired session
del self.sessions[session_id]
return None
return session
def add_message_to_session(self, session_id: str, role: MessageRole, content: str) -> bool:
"""Add a message to a session, return True if successful"""
session = self.get_session(session_id)
if session is None:
return False
session.add_message(role, content)
return True
def get_session_messages(self, session_id: str) -> Optional[List[ChatMessage]]:
"""Get all messages from a session"""
session = self.get_session(session_id)
if session is None:
return None
return session.get_messages()
def cleanup_expired_sessions(self) -> int:
"""Remove expired sessions and return count of removed sessions"""
expired_sessions = []
with self._lock:
for session_id, session in self.sessions.items():
if session.is_expired(self.session_timeout_hours):
expired_sessions.append(session_id)
for session_id in expired_sessions:
del self.sessions[session_id]
return len(expired_sessions)
def get_session_count(self) -> int:
"""Get current number of active sessions"""
with self._lock:
return len(self.sessions)
def session_exists(self, session_id: str) -> bool:
"""Check if a session exists and is not expired"""
return self.get_session(session_id) is not None