|
| 1 | +"""Exercise the public example with real ActivityContext thread/loop behavior.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import asyncio |
| 5 | +import importlib.util |
| 6 | +import unittest |
| 7 | +from pathlib import Path |
| 8 | +from threading import Event, Thread |
| 9 | +from threading import enumerate as threads |
| 10 | +from typing import Any |
| 11 | + |
| 12 | +from durable_workflow import activity |
| 13 | +from durable_workflow.activity import ActivityContext, ActivityInfo, _set_context |
| 14 | +from durable_workflow.errors import ActivityCancelled, ActivityLeaseAuthorityLost |
| 15 | + |
| 16 | +SPEC = importlib.util.spec_from_file_location( |
| 17 | + "threaded_heartbeats_example", |
| 18 | + Path(__file__).resolve().parents[1] / "examples" / "threaded_heartbeats.py", |
| 19 | +) |
| 20 | +assert SPEC is not None and SPEC.loader is not None |
| 21 | +EXAMPLE = importlib.util.module_from_spec(SPEC) |
| 22 | +SPEC.loader.exec_module(EXAMPLE) |
| 23 | + |
| 24 | + |
| 25 | +class HeartbeatClient: |
| 26 | + def __init__(self, response: Any = None) -> None: |
| 27 | + self.response = response if response is not None else {"can_continue": True} |
| 28 | + self.calls: list[dict[str, Any]] = [] |
| 29 | + self.observed = Event() |
| 30 | + |
| 31 | + async def heartbeat_activity_task(self, **request: Any) -> Any: |
| 32 | + self.calls.append(request) |
| 33 | + self.observed.set() |
| 34 | + if isinstance(self.response, Exception): |
| 35 | + raise self.response |
| 36 | + return self.response |
| 37 | + |
| 38 | + |
| 39 | +class ThreadedHeartbeatExampleTest(unittest.IsolatedAsyncioTestCase): |
| 40 | + async def asyncSetUp(self) -> None: |
| 41 | + self.client = HeartbeatClient() |
| 42 | + self.ctx = ActivityContext( |
| 43 | + info=ActivityInfo( |
| 44 | + "task-original", "export", "attempt-original", 2, "reports", "worker-original", |
| 45 | + ), |
| 46 | + client=self.client, # type: ignore[arg-type] |
| 47 | + ) |
| 48 | + _set_context(self.ctx) |
| 49 | + |
| 50 | + async def asyncTearDown(self) -> None: |
| 51 | + _set_context(None) |
| 52 | + self.assertFalse([thread for thread in threads() if thread.name == "activity-heartbeat"]) |
| 53 | + |
| 54 | + async def run_work(self, work: Any) -> Any: |
| 55 | + return await asyncio.wait_for( |
| 56 | + asyncio.to_thread(EXAMPLE.call_with_heartbeats, work, interval=0.01), |
| 57 | + timeout=3, |
| 58 | + ) |
| 59 | + |
| 60 | + async def test_new_thread_needs_the_captured_context(self) -> None: |
| 61 | + errors: list[BaseException] = [] |
| 62 | + |
| 63 | + def look_up_context() -> None: |
| 64 | + try: |
| 65 | + activity.context() |
| 66 | + except RuntimeError as error: |
| 67 | + errors.append(error) |
| 68 | + |
| 69 | + helper = Thread(target=look_up_context) |
| 70 | + helper.start() |
| 71 | + helper.join() |
| 72 | + self.assertEqual(len(errors), 1) |
| 73 | + self.assertIn("outside of an activity", str(errors[0])) |
| 74 | + |
| 75 | + async def test_return_keeps_original_attempt_and_joins(self) -> None: |
| 76 | + def work(cancelled: Event) -> dict[str, int]: |
| 77 | + self.assertTrue(self.client.observed.wait(2)) |
| 78 | + self.assertFalse(cancelled.is_set()) |
| 79 | + return {"count": 7} |
| 80 | + |
| 81 | + self.assertEqual(await self.run_work(work), {"count": 7}) |
| 82 | + self.assertTrue(self.client.calls) |
| 83 | + for request in self.client.calls: |
| 84 | + self.assertEqual(request["task_id"], "task-original") |
| 85 | + self.assertEqual(request["activity_attempt_id"], "attempt-original") |
| 86 | + self.assertEqual(request["lease_owner"], "worker-original") |
| 87 | + |
| 88 | + async def test_work_error_also_joins(self) -> None: |
| 89 | + original = ValueError("business call failed") |
| 90 | + |
| 91 | + def work(cancelled: Event) -> None: |
| 92 | + self.assertTrue(self.client.observed.wait(2)) |
| 93 | + raise original |
| 94 | + |
| 95 | + with self.assertRaises(ValueError) as caught: |
| 96 | + await self.run_work(work) |
| 97 | + self.assertIs(caught.exception, original) |
| 98 | + |
| 99 | + def cancelled_work(self, cancelled: Event) -> str: |
| 100 | + self.assertTrue(cancelled.wait(2)) |
| 101 | + return "must not be returned" |
| 102 | + |
| 103 | + async def test_cancellation_stops_work_and_preserves_type(self) -> None: |
| 104 | + self.client.response = {"cancel_requested": True} |
| 105 | + with self.assertRaises(ActivityCancelled): |
| 106 | + await self.run_work(self.cancelled_work) |
| 107 | + |
| 108 | + async def test_authority_loss_keeps_original_identity_and_reason(self) -> None: |
| 109 | + self.client.response = {"can_continue": False, "reason": "activity_attempt_replaced"} |
| 110 | + with self.assertRaises(ActivityLeaseAuthorityLost) as caught: |
| 111 | + await self.run_work(self.cancelled_work) |
| 112 | + self.assertEqual(caught.exception.task_id, "task-original") |
| 113 | + self.assertEqual(caught.exception.reason, "activity_attempt_replaced") |
| 114 | + |
| 115 | + async def test_transport_error_is_not_silently_lost(self) -> None: |
| 116 | + original = OSError("transport unavailable") |
| 117 | + self.client.response = original |
| 118 | + with self.assertRaises(OSError) as caught: |
| 119 | + await self.run_work(self.cancelled_work) |
| 120 | + self.assertIs(caught.exception, original) |
| 121 | + |
| 122 | + async def test_event_loop_call_refuses_before_work(self) -> None: |
| 123 | + with self.assertRaisesRegex(RuntimeError, "synchronous activity thread"): |
| 124 | + EXAMPLE.call_with_heartbeats(lambda cancelled: self.fail("must not run")) |
0 commit comments