Conghao97's picture tcftrees's picture
ProgramGen release
d086025
Raw History Blame Contribute Delete
22.6 kB
diff --git a/src/cafeteria/asyncio/callbacks.py b/src/cafeteria/asyncio/callbacks.py
new file mode 100644
index 0000000000000000000000000000000000000000..8031062063b018e23ae2026fe66218ea3adead34
--- /dev/null
+++ b/src/cafeteria/asyncio/callbacks.py
@@ -0,0 +1,214 @@
+import asyncio
+import logging
+import warnings
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import (
+ Any,
+ Callable,
+ Coroutine,
+ Dict,
+ Generator,
+ Hashable,
+ List,
+ Optional,
+ Tuple,
+ Union,
+)
+
+from cafeteria.logging import LoggedObject
+
+CallbackType = Union[Callable, Coroutine, "Callback"]
+CallbackResultType = Union[asyncio.Task, Generator, Coroutine]
+EventType = Optional[Union[Enum, Hashable, None]]
+
+logger = logging.getLogger()
+
+
+@dataclass
+class Callback:
+ function: CallbackType
+ args: Tuple[Any] = field(default_factory=list)
+ kwargs: Dict[str, Any] = field(default_factory=dict)
+
+ def __init__(self, function, *args: Any, **kwargs: Any) -> None:
+ super().__init__()
+ self.function = function
+ self.args = args
+ self.kwargs = kwargs
+
+ def trigger(self, *args: Any, **kwargs) -> CallbackResultType:
+ """
+ Trigger this callback by prepending given positional arguments and merging
+ given keyword arguments updating default keyword arguments.
+
+ :param args: Positional arguments to prepend.
+ :param kwargs: Keyword arguments to update defaults with.
+ :return: An awaitable result.
+ """
+ kwargz = dict(**self.kwargs)
+ kwargz.update(kwargs)
+ argz = args + self.args
+ return trigger_callback(self.function, *argz, **kwargz)
+
+
+@dataclass
+class SimpleTriggerCallback(Callback):
+ """
+ A callback dataclass implementation that allows for ignoring any additional
+ arguments provided at the time of trigger.
+ """
+
+ def __init__(self, function, *args: Any, **kwargs: Any) -> None:
+ super().__init__(function, *args, **kwargs)
+
+ def trigger(self, *_, **__) -> CallbackResultType:
+ """
+ Trigger callback ignoring provided arguments.
+ """
+ return super().trigger()
+
+
+def trigger_callback(callback: CallbackType, *args, **kwargs) -> CallbackResultType:
+ """
+ Helper function to trigger a callback (coroutine or callable) with the provided
+ positional/keyword arguments. This will return an awaitable callback result.
+
+ :param callback: The callback to use for this trigger. This could be a `Coroutine`,
+ `Callable` or a instance of :class:`cafeteria.asyncio.callbacks.Callback`.
+ :param args: The positional arguments to use when triggering a callback.
+ :param kwargs: The keyword arguments to use when triggering a callback.
+ :return: An awaitable result.
+ """
+ if isinstance(callback, Callback):
+ return callback.trigger(*args, **kwargs)
+
+ if asyncio.iscoroutinefunction(callback):
+ try:
+ return asyncio.create_task(callback(*args, **kwargs))
+ except RuntimeError:
+ logger.warning(
+ "Callback triggered without a running loop, skipping %s", callback
+ )
+ else:
+ try:
+ return asyncio.get_running_loop().run_in_executor(
+ None, lambda: callback(*args, **kwargs)
+ )
+ except RuntimeError:
+ callback(*args, **kwargs)
+
+
+class CallbackRegistry(LoggedObject):
+ def __init__(
+ self,
+ callbacks: Optional[
+ Dict[EventType, Union[CallbackType, List[CallbackType]]]
+ ] = None,
+ ) -> None:
+ self._callbacks: Dict[EventType, List[Callback]] = dict()
+ if callbacks is not None:
+ for event_type, callback in callbacks.items():
+ if not isinstance(callback, list):
+ callback = [callback]
+ for c in callback:
+ self.register(event_type, c)
+
+ def callbacks(self, event_type: EventType = None) -> List[Callback]:
+ """
+ Retrieve all callbacks registered for a particular *event_type*. If *event_type*
+ is `None` or does not have any callbacks already registered, the default
+ callbacks are returned.
+
+ :param event_type: Event type to retrieve callbacks for.
+ :return: Registered callbacks or default callbacks if none registered for the
+ event type.
+ """
+ return self._callbacks.get(event_type, self._callbacks.get(None, []))
+
+ def register(self, event_type: EventType, callback: CallbackType) -> None:
+ """
+ This method allows for a handler to be registered for a specified event type. If
+ the *event_type* is `None` this is registered as a default callback triggered
+ only when explicitly dispatched or no other event type matched the specified
+ event type when dispatching.
+
+ :param event_type: The type of event to associate the callback handler with.
+ :param callback: The callback handler to associate with this event.
+ """
+ if not isinstance(callback, Callback):
+ callback = Callback(function=callback)
+
+ if event_type not in self._callbacks:
+ self._callbacks[event_type] = list()
+ self._callbacks[event_type].append(callback)
+ self.logger.debug("Registered %s to %s", event_type, callback)
+
+ def deregister(self, event_type: EventType, callback: CallbackType) -> None:
+ """
+ This method allows for a handler to be de-registered for a specified event type
+ if it has already been registered. If *event_type* is set to `None`, *callback*
+ is removed (if exists) from the default callbacks.
+
+ :param event_type: The type of event the callback handler is associated with.
+ :param callback: The callback handler to de-register.
+ """
+ if not isinstance(callback, Callback):
+ callback = Callback(function=callback)
+
+ try:
+ self._callbacks.get(event_type, []).remove(callback)
+ except ValueError:
+ pass
+
+ def exists(self, event_type: EventType, callback: CallbackType) -> bool:
+ """
+ Check if callback exists for the specified *event_type*
+
+ :param event_type: The type of event to check the callback for.
+ :param callback: The callback handler to de-register.
+ :return: `True` if *callback* exists for the specified *event_type*.
+ """
+ if not isinstance(callback, Callback):
+ callback = Callback(function=callback)
+ return callback in self.callbacks(event_type)
+
+ def dispatch(self, event_type: EventType, *args: Any, **kwargs: Any):
+ """
+ Dispatch callbacks registered for an *event_type*. This arguments expects
+ any additional positional/keyword arguments required when triggering the
+ callback. If *event_type* is `None` or does not have any callbacks already
+ registered, the default callbacks (if any) are triggered.
+
+ :param event_type: Event type to dispatch
+ :param args: Positional arguments to be passed into the callback before any
+ pre-configured positional arguments.
+ :param kwargs: Keyword arguments to be passed when triggering the callback.
+ These override any pre-configured arguments.
+ """
+ self.logger.debug("Received event: %s", event_type)
+ for callback in self.callbacks(event_type):
+ self.logger.debug("Executing callback %s", callback)
+ _ = callback.trigger(*args, **kwargs)
+
+ async def handle_event(
+ self, event_type: EventType, *args: Any, **kwargs: Any
+ ) -> None:
+ """
+ Method called when an event is to be dispatched/handled. This arguments expects
+ any additional positional/keyword arguments required when triggering the
+ callback.
+
+ :param event_type: Event type to dispatch
+ :param args: Positional arguments to be passed into the callback before any
+ pre-configured positional arguments.
+ :param kwargs: Keyword arguments to be passed when triggering the callback.
+ These override any pre-configured arguments.
+ """
+ warnings.warn(
+ "CallbackRegistry.handle_event() is deprecated in favour of "
+ "CallbackRegistry.dispatch() and will be removed in a future version",
+ category=DeprecationWarning,
+ stacklevel=2,
+ )
+ return self.dispatch(event_type, *args, **kwargs)
diff --git a/src/cafeteria/asyncio/commons.py b/src/cafeteria/asyncio/commons.py
new file mode 100644
index 0000000000000000000000000000000000000000..2aff1de8c1440c5d5942bfdc65cadb368e1fad94
--- /dev/null
+++ b/src/cafeteria/asyncio/commons.py
@@ -0,0 +1,67 @@
+import asyncio
+import signal
+import warnings
+from asyncio import AbstractEventLoop
+from typing import Optional, Union
+
+
+async def cancel_all_tasks(
+ loop: Optional[AbstractEventLoop] = None, *ignore: asyncio.Task
+):
+ """
+ Cancel and wait for all running tasks in the specified or current event loop.
+
+ :param loop: Optional `AbstractEventLoop` to add signal handlers for, if not
+ provided, running loop is used.
+ :param ignore: If specified, these tasks are ignored even when running.
+ """
+ for task in asyncio.all_tasks(loop):
+ if task is asyncio.current_task() or task in ignore:
+ continue
+ if not (task.done() or task.cancelled()):
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+
+
+def cancel_tasks_on_termination(
+ loop: Optional[AbstractEventLoop] = None, *args: Union[signal.Signals, int, str]
+) -> None:
+ """
+ Helper method to add a signal handlers for specified or current event loop. Handlers
+ are registered for SIGINT, SIGTERM and any additional signals passed in.
+
+ :param loop: Optional `AbstractEventLoop` to add signal handlers for, if not
+ provided, running loop is used.
+ :param args: Additional signals to register cancellation for.
+ """
+ if loop is None:
+ loop = asyncio.get_running_loop()
+
+ for sig in {signal.SIGINT, signal.SIGTERM, *args}:
+ if not isinstance(sig, signal.Signals):
+ if isinstance(sig, int):
+ sig = signal.Signals(sig)
+ elif isinstance(sig, str):
+ try:
+ sig = getattr(signal, sig)
+ except AttributeError:
+ raise ValueError(f"Invalid signal name {sig}")
+ else:
+ raise ValueError(
+ f"Signal should be one of signal.Signals, int or str, got {type(sig)}"
+ )
+ loop.add_signal_handler(
+ sig, lambda: asyncio.ensure_future(cancel_all_tasks(loop=loop), loop=loop)
+ )
+
+
+def handle_signals(event_loop: AbstractEventLoop, *signames: str) -> None:
+ warnings.warn(
+ f"Use {cancel_tasks_on_termination.__name__} instead",
+ category=DeprecationWarning,
+ stacklevel=2,
+ )
+ return cancel_tasks_on_termination(loop=event_loop, *signames)
diff --git a/src/cafeteria/asyncio/patterns/application.py b/src/cafeteria/asyncio/patterns/application.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a4c63ce94ede97bc6909ece06e26b0b62975cdb
--- /dev/null
+++ b/src/cafeteria/asyncio/patterns/application.py
@@ -0,0 +1,27 @@
+import asyncio
+from abc import abstractmethod
+from typing import Any
+
+from cafeteria.asyncio.commons import cancel_tasks_on_termination
+from cafeteria.logging import LoggedObject
+
+
+class AsyncioGracefulApplication(LoggedObject):
+ @abstractmethod
+ async def main(self) -> Any:
+ """
+ The main method to execute for the application. The application runs until this
+ completes or errors out.
+ """
+ raise NotImplementedError
+
+ async def __main(self) -> Any:
+ cancel_tasks_on_termination()
+ return await self.main()
+
+ def run(self, debug: bool = False):
+ try:
+ self.logger.debug("Starting application")
+ return asyncio.run(self.__main(), debug=debug)
+ except (asyncio.CancelledError, KeyboardInterrupt):
+ self.logger.debug("Application halted")
diff --git a/src/cafeteria/asyncio/synchronous.py b/src/cafeteria/asyncio/synchronous.py
new file mode 100644
index 0000000000000000000000000000000000000000..820c31f17f27df3f04fc56a0f1772958d1b9552c
--- /dev/null
+++ b/src/cafeteria/asyncio/synchronous.py
@@ -0,0 +1,15 @@
+import asyncio
+from asyncio import Task
+from typing import Any, Coroutine, Union
+
+
+def execute_async_method(coroutine: Coroutine) -> Union[Any, Task]:
+ try:
+ loop = asyncio.get_event_loop()
+ except RuntimeError:
+ loop = asyncio.new_event_loop()
+
+ if loop.is_running():
+ return loop.create_task(coroutine)
+ else:
+ return loop.run_until_complete(coroutine)
diff --git a/tests/test_callbacks.py b/tests/test_callbacks.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c884912ada7e9a9c0fabc8ebefffdd65480a137
--- /dev/null
+++ b/tests/test_callbacks.py
@@ -0,0 +1,57 @@
+import asyncio
+
+import pytest
+
+from cafeteria.asyncio.callbacks import (
+ Callback,
+ SimpleTriggerCallback,
+ trigger_callback,
+)
+
+
+@pytest.mark.asyncio
+async def test_trigger_callback_blocking(mocker):
+ m = mocker.Mock()
+
+ result = trigger_callback(m, "foo", bar="baz")
+ assert isinstance(result, asyncio.Future)
+
+ await result
+ m.assert_called_once_with("foo", bar="baz")
+
+
+@pytest.mark.asyncio
+async def test_trigger_callback_coroutine():
+ call_args = []
+
+ # using a real corouting here as mocking will fail iscoroutine checks
+ async def coroutine(*_, **__):
+ call_args.append((_, __))
+
+ result = trigger_callback(coroutine, "foo", bar="baz")
+ assert isinstance(result, asyncio.Task)
+
+ await result
+ assert call_args == [(("foo",), dict(bar="baz"))]
+
+
+@pytest.mark.asyncio
+async def test_trigger_callback_callback(mocker):
+ m = mocker.Mock()
+ cb = Callback(m, "foo", bar="baz")
+ result = trigger_callback(cb, not_ignored=True)
+ assert isinstance(result, asyncio.Future)
+
+ await result
+ m.assert_called_once_with(*cb.args, **cb.kwargs, not_ignored=True)
+
+
+@pytest.mark.asyncio
+async def test_trigger_callback_simple_trigger_callback(mocker):
+ m = mocker.Mock()
+ cb = SimpleTriggerCallback(m, "foo", bar="baz")
+ result = trigger_callback(cb, ignored=True)
+ assert isinstance(result, asyncio.Future)
+
+ await result
+ m.assert_called_once_with(*cb.args, **cb.kwargs)
diff --git a/tests/test_callbacks_registry.py b/tests/test_callbacks_registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..8515f783b9430809a8518368c43d8884ef72793e
--- /dev/null
+++ b/tests/test_callbacks_registry.py
@@ -0,0 +1,140 @@
+import pytest
+
+from cafeteria.asyncio.callbacks import Callback, CallbackRegistry
+
+
+def test_callback_registry_simple(mocker):
+ callback_one = mocker.Mock()
+ callback_two = mocker.Mock()
+ registry = CallbackRegistry(callbacks={"one": callback_one, "two": callback_two})
+ registry.dispatch("one", "one")
+ registry.dispatch("two", "two")
+ registry.dispatch(None, "None")
+
+ callback_one.assert_called_once()
+ callback_one.assert_called_once_with("one")
+
+ callback_two.assert_called_once()
+ callback_two.assert_called_once_with("two")
+
+ callback_one.reset_mock()
+ registry.deregister("one", callback_one)
+ registry.dispatch("one", "one")
+
+ callback_one.assert_not_called()
+
+
+def test_callback_registry_multiple(mocker):
+ callback_one = mocker.Mock()
+ callback_two = mocker.Mock()
+ registry = CallbackRegistry(callbacks={"event": [callback_one, callback_two]})
+
+ assert len(registry.callbacks("event")) == 2
+
+ registry.dispatch("event", "event")
+
+ callback_one.assert_called_once()
+ callback_one.assert_called_once_with("event")
+
+ callback_two.assert_called_once()
+ callback_two.assert_called_once_with("event")
+
+ callback_one.reset_mock()
+ callback_two.reset_mock()
+
+ registry.deregister("event", callback_two)
+ registry.dispatch("event", "event")
+
+ callback_one.assert_called_once()
+ callback_one.assert_called_once_with("event")
+
+ callback_two.assert_not_called()
+
+
+def test_callback_registry_coro_without_loop(caplog):
+ async def hello():
+ pass
+
+ registry = CallbackRegistry(callbacks={"hello": hello})
+
+ with pytest.warns(RuntimeWarning):
+ registry.dispatch("hello")
+ assert "Callback triggered without a running loop" in caplog.text
+ assert f"skipping {str(hello)}" in caplog.text
+
+
+def test_callback_registry_callbacks(mocker):
+ callback_one = mocker.Mock()
+ callback_two = mocker.Mock()
+ callback_default = mocker.Mock()
+
+ registry = CallbackRegistry()
+ registry.register("one", callback_one)
+ registry.register("two", callback_two)
+ registry.register(None, callback_default)
+
+ assert registry.callbacks() == [Callback(callback_default)]
+ assert registry.callbacks("one") == [Callback(callback_one)]
+ assert registry.callbacks("two") == [Callback(callback_two)]
+
+
+def test_callback_registry_exists(mocker):
+ callback = mocker.Mock()
+
+ registry = CallbackRegistry()
+ registry.register("one", callback)
+
+ assert registry.exists("one", callback)
+ assert registry.exists("one", Callback(callback))
+ assert not registry.exists(None, callback)
+ assert not registry.exists("two", callback)
+
+
+def test_callback_registry_callbacks_default(mocker):
+ callback = mocker.Mock()
+ registry = CallbackRegistry()
+
+ assert registry.callbacks() == []
+
+ registry.register(None, callback)
+ assert registry.callbacks() == [Callback(callback)]
+
+
+def test_callback_registry_default(mocker):
+ callback = mocker.Mock()
+ registry = CallbackRegistry()
+ registry.register(None, callback)
+
+ registry.dispatch("doesnotexist", "one")
+
+ callback.assert_called_once()
+ callback.assert_called_once_with("one")
+
+ callback.reset_mock()
+ registry.dispatch(None, "one")
+
+ callback.assert_called_once()
+ callback.assert_called_once_with("one")
+
+ callback.reset_mock()
+ registry.deregister(None, callback)
+ registry.dispatch("doesnotexist", "two")
+ registry.dispatch(None, "two")
+
+ callback.assert_not_called()
+
+
+def test_callback_registry_deregister_non_existing():
+ # noinspection PyBroadException
+ try:
+ CallbackRegistry().deregister("one", lambda x: None)
+ except Exception:
+ pytest.fail("Unexpected exception")
+
+
+@pytest.mark.asyncio
+async def test_callback_registry_handle_event(mocker):
+ callback = mocker.Mock()
+ with pytest.warns(DeprecationWarning):
+ await CallbackRegistry(callbacks={"one": callback}).handle_event("one", "one")
+ callback.assert_called_once_with("one")
diff --git a/tests/test_commons.py b/tests/test_commons.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ec1f495701436dd8071b9f9fa026cc3c38d3e83
--- /dev/null
+++ b/tests/test_commons.py
@@ -0,0 +1,93 @@
+import asyncio
+import signal
+
+import pytest
+
+from cafeteria.asyncio.commons import cancel_all_tasks, cancel_tasks_on_termination
+
+
+# noinspection PyUnresolvedReferences,PyProtectedMember
+def ensure_signal_handlers_registered(
+ loop: asyncio.AbstractEventLoop, *args: signal.Signals
+) -> None:
+ assert len(loop._signal_handlers) == 2 + len(args)
+
+ # ensure default signal handlers registered added
+ assert signal.SIGINT in loop._signal_handlers
+ assert signal.SIGTERM in loop._signal_handlers
+
+ for arg in args:
+ assert arg in loop._signal_handlers
+
+
+def test_handle_signals(recwarn):
+ # noinspection PyDeprecation
+ from cafeteria.asyncio.commons import handle_signals
+
+ loop = asyncio.get_event_loop()
+ handle_signals(event_loop=loop)
+ ensure_signal_handlers_registered(loop)
+
+ # ensure a deprecation warning was issued
+ assert len(recwarn) == 1
+ w = recwarn.pop(DeprecationWarning)
+ assert issubclass(w.category, DeprecationWarning)
+ assert str(w.message) == "Use cancel_tasks_on_termination instead"
+
+
+def test_cancel_tasks_on_termination_default():
+ loop = asyncio.get_event_loop()
+ cancel_tasks_on_termination(loop, signal.SIGABRT)
+ ensure_signal_handlers_registered(loop, signal.SIGABRT)
+
+
+def test_cancel_tasks_on_termination_int():
+ loop = asyncio.get_event_loop()
+ cancel_tasks_on_termination(loop, 6)
+ ensure_signal_handlers_registered(loop, signal.SIGABRT)
+
+
+def test_cancel_tasks_on_termination_str():
+ loop = asyncio.get_event_loop()
+ cancel_tasks_on_termination(loop, "SIGABRT")
+ ensure_signal_handlers_registered(loop, signal.SIGABRT)
+
+
+def test_cancel_tasks_on_termination_invalid_type(mocker):
+ with pytest.raises(ValueError):
+ # noinspection PyTypeChecker
+ cancel_tasks_on_termination(asyncio.get_event_loop(), mocker.Mock())
+
+
+def test_cancel_tasks_on_termination_invalid_int():
+ with pytest.raises(ValueError):
+ # noinspection PyTypeChecker
+ cancel_tasks_on_termination(asyncio.get_event_loop(), 9999)
+
+
+def test_cancel_tasks_on_termination_invalid_str():
+ with pytest.raises(ValueError):
+ # noinspection PyTypeChecker
+ cancel_tasks_on_termination(asyncio.get_event_loop(), "FOOBAR")
+
+
+@pytest.mark.asyncio
+async def test_cancel_all_tasks():
+ async def infinity():
+ try:
+ while True:
+ await asyncio.sleep(2)
+ except asyncio.CancelledError:
+ pass
+
+ test_task = asyncio.current_task()
+ task = asyncio.ensure_future(infinity())
+
+ # ensure task is running
+ assert not (task.done() or task.cancelled())
+
+ await cancel_all_tasks(None, test_task)
+ assert task.cancelled()
+
+ # current task was ignored
+ assert not (test_task.done() or test_task.cancelled())