diff --git a/docs/timeout.md b/docs/timeout.md index a7a1fa2d..20cc1c37 100644 --- a/docs/timeout.md +++ b/docs/timeout.md @@ -32,6 +32,10 @@ In this example, if the machine stays in `waiting` for 5 seconds, If any other event causes a transition out of `waiting` first, the timer is cancelled automatically. +When the async engine runs on your event loop, the timer waits without using +a worker thread. Synchronous callers keep the thread-based timer, so custom +timeout events can still fire between calls to the machine. + ## Custom timeout event diff --git a/statemachine/contrib/timeout.py b/statemachine/contrib/timeout.py index 8998eb93..86b8affe 100644 --- a/statemachine/contrib/timeout.py +++ b/statemachine/contrib/timeout.py @@ -14,6 +14,7 @@ class MyMachine(StateChart): expired = waiting.to(timed_out) """ +import asyncio from typing import TYPE_CHECKING from typing import Any @@ -42,6 +43,12 @@ def run(self, ctx: "InvokeContext") -> Any: ctx.send(self.on) return None + async def _run_async(self, ctx: "InvokeContext") -> None: + await asyncio.sleep(self.duration) + if self.on is not None: + # A timer fires outside the macrostep that started it. + await ctx.machine.send(self.on, internal=False) + def __repr__(self) -> str: args = f"{self.duration}" if self.on is not None: diff --git a/statemachine/invoke.py b/statemachine/invoke.py index 1959c7d1..9e6d6652 100644 --- a/statemachine/invoke.py +++ b/statemachine/invoke.py @@ -19,6 +19,9 @@ from typing import Any from typing import runtime_checkable +from .contrib.timeout import _Timeout +from .utils import _is_sync_bridge_loop + try: from typing import Protocol except ImportError: # pragma: no cover @@ -463,7 +466,10 @@ async def _run_async_handler( invocation: Invocation, ): try: - if handler is not None and _has_async_run(handler): + if isinstance(handler, _Timeout) and not _is_sync_bridge_loop(): + await handler._run_async(ctx) + result = None + elif handler is not None and _has_async_run(handler): # Async IInvoke: call run() and await the coroutine directly # on the event loop (no executor needed). result = await handler.run(ctx) diff --git a/statemachine/utils.py b/statemachine/utils.py index ac1ddbb1..956c8cbe 100644 --- a/statemachine/utils.py +++ b/statemachine/utils.py @@ -44,6 +44,11 @@ def humanize_id(id: str) -> str: return _SEPARATOR_RE.sub(" ", id).strip().capitalize() +def _is_sync_bridge_loop() -> bool: + """Whether the current loop runs only during synchronous state machine calls.""" + return asyncio.get_running_loop() is getattr(_cached_loop, "loop", None) + + def run_async_from_sync(coroutine: "Any") -> "Any": """ Compatibility layer to run an async coroutine from a synchronous context. diff --git a/tests/test_contrib_timeout.py b/tests/test_contrib_timeout.py index ef4defcf..e501379c 100644 --- a/tests/test_contrib_timeout.py +++ b/tests/test_contrib_timeout.py @@ -1,11 +1,15 @@ """Tests for the timeout contrib module.""" +import asyncio import threading +from concurrent.futures import Future +from contextlib import closing import pytest from statemachine.contrib.timeout import _Timeout from statemachine.contrib.timeout import timeout +from statemachine import Event from statemachine import State from statemachine import StateChart @@ -34,6 +38,33 @@ def test_repr_with_on(self): class TestTimeoutBasic: """Timeout fires done.invoke. when no custom event is specified.""" + async def test_only_sync_handler_uses_executor(self, mocker): + loop = asyncio.get_running_loop() + run_in_executor = mocker.spy(loop, "run_in_executor") + completed = loop.create_future() + + class SyncHandler: + def run(self, ctx): + return threading.get_ident() + + class SM(StateChart): + waiting = State(initial=True, invoke=timeout(0.01)) + working = State(invoke=SyncHandler()) + done = State(final=True) + done_invoke_waiting = waiting.to(working) + done_invoke_working = working.to(done) + + async def on_enter_done(self, data): + completed.set_result(data) + + sm = SM() + await sm.activate_initial_state() + worker_thread = await asyncio.wait_for(completed, timeout=2) + + assert worker_thread != threading.get_ident() + run_in_executor.assert_called_once() + assert run_in_executor.call_args.args[0] is None + async def test_timeout_fires_done_invoke(self, sm_runner): class SM(StateChart): waiting = State(initial=True, invoke=timeout(0.05)) @@ -65,6 +96,53 @@ class SM(StateChart): class TestTimeoutCustomEvent: """Timeout fires a custom event via the `on` parameter.""" + def test_async_machine_driven_from_synchronous_code(self, monkeypatch): + from statemachine.utils import _cached_loop + + delivered: Future = Future() + + class SM(StateChart): + waiting = State(initial=True, invoke=timeout(0.01, on="expired")) + expired = waiting.to(None) + + async def on_expired(self): + delivered.set_result(asyncio.get_running_loop()) + + with closing(asyncio.new_event_loop()) as loop: + monkeypatch.setattr(_cached_loop, "loop", loop, raising=False) + sm = SM() + sm.activate_initial_state() + try: + # Synchronous callers do not pump the event loop between calls. + delivered.result(timeout=2) + finally: + for task in asyncio.all_tasks(loop): + loop.run_until_complete(task) + loop.run_until_complete(loop.shutdown_default_executor()) + if delivered.done() and delivered.result() is not loop: + delivered.result().close() + + async def test_internal_timeout_event_follows_queued_external_event(self): + loop = asyncio.get_running_loop() + final_state = loop.create_future() + + class SM(StateChart): + waiting = State(initial=True, invoke=timeout(0.01, on="expired")) + selected = State(final=True) + late = State(final=True) + choose = waiting.to(selected) + expired = Event(waiting.to(late), internal=True) + + async def on_enter_state(self, target): + if target.final: + loop.call_soon_threadsafe(final_state.set_result, target.id) + + sm = SM() + await sm.activate_initial_state() + sm.choose.put() + + assert await asyncio.wait_for(final_state, timeout=2) == "selected" + async def test_custom_event_fires(self, sm_runner): class SM(StateChart): waiting = State(initial=True, invoke=timeout(0.05, on="expired"))