41 lines
1.4 KiB
Python
41 lines
1.4 KiB
Python
import threading
|
|
from datetime import datetime
|
|
from uuid import UUID
|
|
|
|
from domain.sandbox import SandboxSession
|
|
from usecase.interface import SandboxSessionRepository
|
|
|
|
|
|
class InMemorySandboxSessionRepository(SandboxSessionRepository):
|
|
def __init__(self) -> None:
|
|
self._sessions_by_chat_id: dict[UUID, SandboxSession] = {}
|
|
self._lock = threading.Lock()
|
|
|
|
def replace_all(self, sessions: list[SandboxSession]) -> None:
|
|
with self._lock:
|
|
self._sessions_by_chat_id = {
|
|
session.chat_id: session for session in sessions
|
|
}
|
|
|
|
def get_active_by_chat_id(self, chat_id: UUID) -> SandboxSession | None:
|
|
with self._lock:
|
|
return self._sessions_by_chat_id.get(chat_id)
|
|
|
|
def list_expired(self, now: datetime) -> list[SandboxSession]:
|
|
with self._lock:
|
|
return [
|
|
session
|
|
for session in self._sessions_by_chat_id.values()
|
|
if session.expires_at <= now
|
|
]
|
|
|
|
def save(self, session: SandboxSession) -> None:
|
|
with self._lock:
|
|
self._sessions_by_chat_id[session.chat_id] = session
|
|
|
|
def delete(self, session_id: UUID) -> None:
|
|
with self._lock:
|
|
for chat_id, session in tuple(self._sessions_by_chat_id.items()):
|
|
if session.session_id == session_id:
|
|
del self._sessions_by_chat_id[chat_id]
|
|
return
|