1010import time
1111from collections .abc import Callable , Generator , Sequence
1212from concurrent .futures import ThreadPoolExecutor
13+ from contextlib import contextmanager
1314from dataclasses import dataclass , field
1415from datetime import UTC , datetime , timedelta
1516from threading import Event , Lock , Thread
@@ -830,6 +831,18 @@ def wrap_with_release(
830831 handler : Callable [..., Any ],
831832 release : Callable [[], None ],
832833 ) -> Callable [..., Any ]:
834+ if inspect .iscoroutinefunction (handler ):
835+ # Keep coroutine handlers recognizable as such, so the worker
836+ # manager awaits them on its event loop rather than calling
837+ # them from the thread pool.
838+ async def wrapped_async (* args : Any , ** kwargs : Any ) -> Any :
839+ try :
840+ return await handler (* args , ** kwargs )
841+ finally :
842+ release ()
843+
844+ return wrapped_async
845+
833846 def wrapped (* args : Any , ** kwargs : Any ) -> Any :
834847 try :
835848 return handler (* args , ** kwargs )
@@ -1025,7 +1038,7 @@ def stream_reader(response_stream: Any = response_stream) -> None:
10251038 elif work_item .HasField ("activityRequest" ):
10261039 submit_work_item (
10271040 self ._async_worker_manager .submit_activity ,
1028- self ._execute_activity ,
1041+ self ._get_activity_handler ( work_item . activityRequest ) ,
10291042 self ._cancel_activity ,
10301043 work_item .activityRequest ,
10311044 stub ,
@@ -1399,54 +1412,130 @@ def _execute_activity(
13991412 payload_helpers .deexternalize_payloads (req , self ._payload_store )
14001413 try :
14011414 executor = _ActivityExecutor (self ._registry , self ._logger , self ._data_converter )
1402- with tracing .suppress_span_emission (not self ._emit_trace_spans ):
1403- with tracing .start_span (
1404- tracing .create_span_name ("activity" , req .name ),
1405- trace_context = req .parentTraceContext ,
1406- kind = tracing .SpanKind .SERVER ,
1407- attributes = {
1408- tracing .ATTR_TASK_TYPE : "activity" ,
1409- tracing .ATTR_TASK_INSTANCE_ID : instance_id ,
1410- tracing .ATTR_TASK_NAME : req .name ,
1411- tracing .ATTR_TASK_TASK_ID : str (req .taskId ),
1412- },
1413- ) as span :
1414- try :
1415- result = executor .execute (
1416- instance_id , req .name , req .taskId , req .input .value
1417- )
1418- except Exception as ex :
1419- tracing .set_span_error (span , ex )
1420- raise
1421- res = pb .ActivityResponse (
1422- instanceId = instance_id ,
1423- taskId = req .taskId ,
1424- result = ph .get_string_value (result ),
1425- completionToken = completionToken ,
1426- )
1415+ with self ._start_activity_span (req ) as span :
1416+ try :
1417+ result = executor .execute (
1418+ instance_id , req .name , req .taskId , req .input .value
1419+ )
1420+ except Exception as ex :
1421+ tracing .set_span_error (span , ex )
1422+ raise
1423+ res = self ._new_activity_response (req , completionToken , result )
14271424 except Exception as ex :
1428- res = pb .ActivityResponse (
1429- instanceId = instance_id ,
1430- taskId = req .taskId ,
1431- failureDetails = ph .new_failure_details (
1432- ex , self ._exception_properties_provider , self ._logger ),
1433- completionToken = completionToken ,
1434- )
1425+ res = self ._new_activity_failure_response (req , completionToken , ex )
1426+
1427+ self ._complete_activity_task (req , stub , res )
1428+ finally :
1429+ self ._on_activity_execution_completed (req )
1430+
1431+ async def _execute_activity_async (
1432+ self ,
1433+ req : pb .ActivityRequest ,
1434+ stub : Any ,
1435+ completionToken : Any ,
1436+ ) -> None :
1437+ """Executes an ``async def`` activity on the worker's event loop.
14351438
1439+ Mirrors :meth:`_execute_activity`, but awaits the activity instead of
1440+ occupying a thread-pool worker. The blocking calls around it (payload
1441+ store access and the gRPC completion) are offloaded to a thread so
1442+ they don't stall the event loop.
1443+ """
1444+ instance_id = req .orchestrationInstance .instanceId
1445+ self ._on_activity_execution_started (req )
1446+ try :
1447+ # De-externalize any large-payload tokens in the incoming request
1448+ if self ._payload_store is not None :
1449+ await asyncio .to_thread (
1450+ payload_helpers .deexternalize_payloads , req , self ._payload_store
1451+ )
14361452 try :
1437- # Externalize any large payloads in the response
1438- if self ._payload_store is not None :
1439- payload_helpers .externalize_payloads (
1440- res , self ._payload_store , instance_id = instance_id ,
1441- )
1442- stub .CompleteActivityTask (res )
1453+ executor = _ActivityExecutor (self ._registry , self ._logger , self ._data_converter )
1454+ with self ._start_activity_span (req ) as span :
1455+ try :
1456+ result = await executor .execute_async (
1457+ instance_id , req .name , req .taskId , req .input .value
1458+ )
1459+ except Exception as ex :
1460+ tracing .set_span_error (span , ex )
1461+ raise
1462+ res = self ._new_activity_response (req , completionToken , result )
14431463 except Exception as ex :
1444- self ._logger . exception (
1445- f"Failed to deliver activity response for ' { req . name } # { req . taskId } ' of orchestration ID ' { instance_id } ' to sidecar: { ex } "
1446- )
1464+ res = self ._new_activity_failure_response ( req , completionToken , ex )
1465+
1466+ await asyncio . to_thread ( self . _complete_activity_task , req , stub , res )
14471467 finally :
14481468 self ._on_activity_execution_completed (req )
14491469
1470+ def _get_activity_handler (self , req : pb .ActivityRequest ) -> Callable [..., Any ]:
1471+ """Returns the handler that executes the activity named by the request."""
1472+ fn = self ._registry .get_activity (req .name )
1473+ if fn is not None and _is_async_callable (fn ):
1474+ return self ._execute_activity_async
1475+ return self ._execute_activity
1476+
1477+ @contextmanager
1478+ def _start_activity_span (self , req : pb .ActivityRequest ):
1479+ with tracing .suppress_span_emission (not self ._emit_trace_spans ):
1480+ with tracing .start_span (
1481+ tracing .create_span_name ("activity" , req .name ),
1482+ trace_context = req .parentTraceContext ,
1483+ kind = tracing .SpanKind .SERVER ,
1484+ attributes = {
1485+ tracing .ATTR_TASK_TYPE : "activity" ,
1486+ tracing .ATTR_TASK_INSTANCE_ID : req .orchestrationInstance .instanceId ,
1487+ tracing .ATTR_TASK_NAME : req .name ,
1488+ tracing .ATTR_TASK_TASK_ID : str (req .taskId ),
1489+ },
1490+ ) as span :
1491+ yield span
1492+
1493+ def _new_activity_response (
1494+ self ,
1495+ req : pb .ActivityRequest ,
1496+ completionToken : Any ,
1497+ result : str | None ,
1498+ ) -> pb .ActivityResponse :
1499+ return pb .ActivityResponse (
1500+ instanceId = req .orchestrationInstance .instanceId ,
1501+ taskId = req .taskId ,
1502+ result = ph .get_string_value (result ),
1503+ completionToken = completionToken ,
1504+ )
1505+
1506+ def _new_activity_failure_response (
1507+ self ,
1508+ req : pb .ActivityRequest ,
1509+ completionToken : Any ,
1510+ ex : Exception ,
1511+ ) -> pb .ActivityResponse :
1512+ return pb .ActivityResponse (
1513+ instanceId = req .orchestrationInstance .instanceId ,
1514+ taskId = req .taskId ,
1515+ failureDetails = ph .new_failure_details (
1516+ ex , self ._exception_properties_provider , self ._logger ),
1517+ completionToken = completionToken ,
1518+ )
1519+
1520+ def _complete_activity_task (
1521+ self ,
1522+ req : pb .ActivityRequest ,
1523+ stub : Any ,
1524+ res : pb .ActivityResponse ,
1525+ ) -> None :
1526+ instance_id = req .orchestrationInstance .instanceId
1527+ try :
1528+ # Externalize any large payloads in the response
1529+ if self ._payload_store is not None :
1530+ payload_helpers .externalize_payloads (
1531+ res , self ._payload_store , instance_id = instance_id ,
1532+ )
1533+ stub .CompleteActivityTask (res )
1534+ except Exception as ex :
1535+ self ._logger .exception (
1536+ f"Failed to deliver activity response for '{ req .name } #{ req .taskId } ' of orchestration ID '{ instance_id } ' to sidecar: { ex } "
1537+ )
1538+
14501539 def _cancel_activity (
14511540 self ,
14521541 req : pb .ActivityRequest ,
@@ -1878,6 +1967,18 @@ def call_activity(
18781967 ) -> task .CompletableTask [T ]:
18791968 ...
18801969
1970+ @overload
1971+ def call_activity (
1972+ self ,
1973+ activity : task .AsyncActivity [TInput , TOutput ],
1974+ * ,
1975+ input : TInput | None = ...,
1976+ retry_policy : task .RetryPolicy | None = ...,
1977+ tags : dict [str , str ] | None = ...,
1978+ return_type : None = ...,
1979+ ) -> task .CompletableTask [TOutput ]:
1980+ ...
1981+
18811982 @overload
18821983 def call_activity (
18831984 self ,
@@ -3401,6 +3502,13 @@ def compare_versions(self, source_version: str | None, default_version: str | No
34013502 return (source_version > default_version ) - (source_version < default_version )
34023503
34033504
3505+ def _is_async_callable (fn : Callable [..., Any ]) -> bool :
3506+ """Returns True for ``async def`` functions and objects with an ``async def __call__``."""
3507+ return inspect .iscoroutinefunction (fn ) or inspect .iscoroutinefunction (
3508+ getattr (fn , "__call__" , None )
3509+ )
3510+
3511+
34043512class _ActivityExecutor :
34053513 def __init__ (self , registry : _Registry , logger : logging .Logger ,
34063514 data_converter : DataConverter ):
@@ -3416,6 +3524,45 @@ def execute(
34163524 encoded_input : str | None ,
34173525 ) -> str | None :
34183526 """Executes an activity function and returns the serialized result, if any."""
3527+ fn , ctx , activity_input = self ._prepare (orchestration_id , name , task_id , encoded_input )
3528+
3529+ # Execute the activity function
3530+ activity_output = fn (ctx , activity_input )
3531+ if inspect .isawaitable (activity_output ):
3532+ if inspect .iscoroutine (activity_output ):
3533+ activity_output .close ()
3534+ raise TypeError (
3535+ f"Activity '{ name } ' returned an awaitable from a synchronous call. "
3536+ "Declare the activity with 'async def' so the worker awaits it."
3537+ )
3538+
3539+ return self ._serialize_output (orchestration_id , name , task_id , activity_output )
3540+
3541+ async def execute_async (
3542+ self ,
3543+ orchestration_id : str ,
3544+ name : str ,
3545+ task_id : int ,
3546+ encoded_input : str | None ,
3547+ ) -> str | None :
3548+ """Executes an activity function, awaiting its result if it is awaitable,
3549+ and returns the serialized result, if any."""
3550+ fn , ctx , activity_input = self ._prepare (orchestration_id , name , task_id , encoded_input )
3551+
3552+ # Execute the activity function
3553+ activity_output = fn (ctx , activity_input )
3554+ if inspect .isawaitable (activity_output ):
3555+ activity_output = await activity_output
3556+
3557+ return self ._serialize_output (orchestration_id , name , task_id , activity_output )
3558+
3559+ def _prepare (
3560+ self ,
3561+ orchestration_id : str ,
3562+ name : str ,
3563+ task_id : int ,
3564+ encoded_input : str | None ,
3565+ ) -> tuple [task .Activity [Any , Any ], task .ActivityContext , Any ]:
34193566 self ._logger .debug (
34203567 f"{ orchestration_id } /{ task_id } : Executing activity '{ name } '..."
34213568 )
@@ -3428,10 +3575,15 @@ def execute(
34283575 input_type = type_discovery .activity_input_type (fn , self ._data_converter ) if encoded_input else None
34293576 activity_input = self ._data_converter .deserialize (encoded_input , input_type )
34303577 ctx = task .ActivityContext (orchestration_id , task_id )
3578+ return fn , ctx , activity_input
34313579
3432- # Execute the activity function
3433- activity_output = fn (ctx , activity_input )
3434-
3580+ def _serialize_output (
3581+ self ,
3582+ orchestration_id : str ,
3583+ name : str ,
3584+ task_id : int ,
3585+ activity_output : Any ,
3586+ ) -> str | None :
34353587 encoded_output = self ._data_converter .serialize (activity_output )
34363588 chars = len (encoded_output ) if encoded_output else 0
34373589 self ._logger .debug (
0 commit comments