Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 store contextvar token in closure #6

Merged
merged 2 commits into from
Oct 19, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 3 additions & 10 deletions fastapi_events/middleware.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import asyncio
from collections import deque
from contextvars import Token
from typing import Optional, Deque, Iterable
from typing import Deque, Iterable

from starlette.types import ASGIApp, Scope, Receive, Send

Expand All @@ -14,27 +14,20 @@ class EventHandlerASGIMiddleware:
def __init__(self, app: ASGIApp, handlers: Iterable[BaseEventHandler]) -> None:
self.app = app
self._handlers: Iterable[BaseEventHandler] = handlers
self._token: Optional[Token] = None

async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] not in ["http", "websocket"]:
await self.app(scope, receive, send)
return

self._initialize_event_store()
token: Token = event_store.set(deque())
try:
await self.app(scope, receive, send)
finally:
await self._process_events()
self._teardown_event_store()
event_store.reset(token)

async def _process_events(self) -> None:
q: Deque[Event] = event_store.get()
await asyncio.gather(*[handler.handle_many(events=q)
for handler in self._handlers])

def _initialize_event_store(self) -> None:
self._token = event_store.set(deque())

def _teardown_event_store(self) -> None:
event_store.reset(self._token)