|
| 1 | +"""In-memory session store — a portable harness pattern. |
| 2 | +
|
| 3 | +Single-process, GIL-protected. Each session holds its conversation history |
| 4 | +as a list of message dicts compatible with the typical OpenAI chat |
| 5 | +completions format. Not safe for multi-process deployments; replace with |
| 6 | +Redis or a database for persistence and true concurrency safety. |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +from datetime import UTC, datetime |
| 12 | +from typing import Any |
| 13 | +from uuid import UUID, uuid4 |
| 14 | + |
| 15 | +from src.models.session import SessionInfo |
| 16 | + |
| 17 | + |
| 18 | +class SessionStore: |
| 19 | + """In-memory session store.""" |
| 20 | + |
| 21 | + def __init__(self) -> None: |
| 22 | + self._sessions: dict[str, dict[str, Any]] = {} |
| 23 | + |
| 24 | + def create(self) -> SessionInfo: |
| 25 | + """Create a new session with an empty conversation history.""" |
| 26 | + session_id = str(uuid4()) |
| 27 | + self._sessions[session_id] = { |
| 28 | + "session_id": session_id, |
| 29 | + "created_at": datetime.now(tz=UTC), |
| 30 | + "messages": [], |
| 31 | + } |
| 32 | + return SessionInfo( |
| 33 | + session_id=UUID(session_id), |
| 34 | + created_at=self._sessions[session_id]["created_at"], |
| 35 | + message_count=0, |
| 36 | + ) |
| 37 | + |
| 38 | + def get(self, session_id: str) -> SessionInfo | None: |
| 39 | + """Get session info, or None if not found.""" |
| 40 | + data = self._sessions.get(session_id) |
| 41 | + if data is None: |
| 42 | + return None |
| 43 | + return SessionInfo( |
| 44 | + session_id=UUID(data["session_id"]), |
| 45 | + created_at=data["created_at"], |
| 46 | + message_count=len(data["messages"]), |
| 47 | + ) |
| 48 | + |
| 49 | + def get_messages(self, session_id: str) -> list[dict[str, Any]] | None: |
| 50 | + """Get conversation history for a session, or None if not found.""" |
| 51 | + data = self._sessions.get(session_id) |
| 52 | + if data is None: |
| 53 | + return None |
| 54 | + return list(data["messages"]) |
| 55 | + |
| 56 | + def set_messages(self, session_id: str, messages: list[dict[str, Any]]) -> None: |
| 57 | + """Replace the conversation history for a session.""" |
| 58 | + if session_id in self._sessions: |
| 59 | + self._sessions[session_id]["messages"] = messages |
| 60 | + |
| 61 | + def exists(self, session_id: str) -> bool: |
| 62 | + """Check if a session exists.""" |
| 63 | + return session_id in self._sessions |
0 commit comments