2022-12-01 05:33:20 +00:00
|
|
|
# Copyright (c) 2022 Kyle Schouviller (https://github.com/kyle0654)
|
|
|
|
|
|
|
|
import asyncio
|
2023-03-03 06:02:00 +00:00
|
|
|
import threading
|
2022-12-01 05:33:20 +00:00
|
|
|
from queue import Empty, Queue
|
|
|
|
from typing import Any
|
2023-03-03 06:02:00 +00:00
|
|
|
|
2022-12-01 05:33:20 +00:00
|
|
|
from fastapi_events.dispatcher import dispatch
|
2023-03-03 06:02:00 +00:00
|
|
|
|
2022-12-01 05:33:20 +00:00
|
|
|
from ..services.events import EventServiceBase
|
2023-03-03 06:02:00 +00:00
|
|
|
|
2022-12-01 05:33:20 +00:00
|
|
|
|
|
|
|
class FastAPIEventService(EventServiceBase):
|
|
|
|
event_handler_id: int
|
|
|
|
__queue: Queue
|
|
|
|
__stop_event: threading.Event
|
|
|
|
|
|
|
|
def __init__(self, event_handler_id: int) -> None:
|
|
|
|
self.event_handler_id = event_handler_id
|
|
|
|
self.__queue = Queue()
|
|
|
|
self.__stop_event = threading.Event()
|
2023-03-03 06:02:00 +00:00
|
|
|
asyncio.create_task(self.__dispatch_from_queue(stop_event=self.__stop_event))
|
2022-12-01 05:33:20 +00:00
|
|
|
|
|
|
|
super().__init__()
|
|
|
|
|
|
|
|
def stop(self, *args, **kwargs):
|
|
|
|
self.__stop_event.set()
|
|
|
|
self.__queue.put(None)
|
|
|
|
|
|
|
|
def dispatch(self, event_name: str, payload: Any) -> None:
|
2023-03-03 06:02:00 +00:00
|
|
|
self.__queue.put(dict(event_name=event_name, payload=payload))
|
2022-12-01 05:33:20 +00:00
|
|
|
|
|
|
|
async def __dispatch_from_queue(self, stop_event: threading.Event):
|
|
|
|
"""Get events on from the queue and dispatch them, from the correct thread"""
|
|
|
|
while not stop_event.is_set():
|
|
|
|
try:
|
2023-03-03 06:02:00 +00:00
|
|
|
event = self.__queue.get(block=False)
|
|
|
|
if not event: # Probably stopping
|
2022-12-01 05:33:20 +00:00
|
|
|
continue
|
|
|
|
|
|
|
|
dispatch(
|
2023-03-03 06:02:00 +00:00
|
|
|
event.get("event_name"),
|
|
|
|
payload=event.get("payload"),
|
|
|
|
middleware_id=self.event_handler_id,
|
|
|
|
)
|
2022-12-01 05:33:20 +00:00
|
|
|
|
|
|
|
except Empty:
|
|
|
|
await asyncio.sleep(0.001)
|
|
|
|
pass
|
|
|
|
|
|
|
|
except asyncio.CancelledError as e:
|
2023-03-03 06:02:00 +00:00
|
|
|
raise e # Raise a proper error
|