"""Post-commit notifications marshal mutations onto the owning event loop.""" import asyncio from dataclasses import dataclass, field from threading import RLock @dataclass class Entry: organization_id: object epoch: int auth_session_id: object runtime: object loop: asyncio.AbstractEventLoop finished: asyncio.Event = field(default_factory=asyncio.Event) ENTRIES = {} _LOCK = RLock() def register(session_id, organization_id, epoch, auth_session_id, runtime): with _LOCK: ENTRIES[session_id] = Entry(organization_id, epoch, auth_session_id, runtime, asyncio.get_running_loop()) def unregister(session_id): with _LOCK: entry = ENTRIES.pop(session_id, None) if entry: entry.finished.set() def notify(*, organization_id=None, new_epoch=None, auth_session_id=None, session_id=None, code='CONTEXT_REVOKED'): with _LOCK: selected = [e for sid, e in ENTRIES.items() if (organization_id is None or e.organization_id == organization_id) and (new_epoch is None or e.epoch < new_epoch) and (auth_session_id is None or e.auth_session_id == auth_session_id) and (session_id is None or sid == session_id)] async def fail(entry): async with entry.runtime.lock: entry.runtime.fail(code) for entry in selected: if not entry.loop.is_closed(): entry.loop.call_soon_threadsafe(lambda e=entry: asyncio.create_task(fail(e))) return len(selected) async def shutdown(): with _LOCK: entries = list(ENTRIES.values()) for entry in entries: async with entry.runtime.lock: entry.runtime.fail('LIVE_SERVER_SHUTDOWN') await asyncio.gather(*(e.finished.wait() for e in entries), return_exceptions=True)