Thread-safe session lock manager with per-event-loop isolation.
| 31 | |
| 32 | |
| 33 | class SessionLockManager: |
| 34 | """Thread-safe session lock manager with per-event-loop isolation.""" |
| 35 | |
| 36 | def __init__(self) -> None: |
| 37 | self._state_guard = threading.Lock() |
| 38 | self._loop_managers: weakref.WeakKeyDictionary[ |
| 39 | asyncio.AbstractEventLoop, _PerLoopSessionLockManager |
| 40 | ] = weakref.WeakKeyDictionary() |
| 41 | |
| 42 | def _get_loop_manager(self) -> _PerLoopSessionLockManager: |
| 43 | """Get the lock manager for the current event loop.""" |
| 44 | loop = asyncio.get_running_loop() |
| 45 | with self._state_guard: |
| 46 | return self._loop_managers.setdefault(loop, _PerLoopSessionLockManager()) |
| 47 | |
| 48 | @asynccontextmanager |
| 49 | async def acquire_lock(self, session_id: str): |
| 50 | manager = self._get_loop_manager() |
| 51 | async with manager.acquire_lock(session_id): |
| 52 | yield |
| 53 | |
| 54 | |
| 55 | session_lock_manager = SessionLockManager() |
no outgoing calls