Skip to content
Open
Show file tree
Hide file tree
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
4 changes: 4 additions & 0 deletions docs/timeout.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 7 additions & 0 deletions statemachine/contrib/timeout.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class MyMachine(StateChart):
expired = waiting.to(timed_out)
"""

import asyncio
from typing import TYPE_CHECKING
from typing import Any

Expand Down Expand Up @@ -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:
Expand Down
8 changes: 7 additions & 1 deletion statemachine/invoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
5 changes: 5 additions & 0 deletions statemachine/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
78 changes: 78 additions & 0 deletions tests/test_contrib_timeout.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -34,6 +38,33 @@ def test_repr_with_on(self):
class TestTimeoutBasic:
"""Timeout fires done.invoke.<state> 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))
Expand Down Expand Up @@ -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"))
Expand Down