|
| 1 | +import logging |
| 2 | + |
| 3 | +from cadence.api.v1.common_pb2 import Payload |
| 4 | +from cadence.api.v1.service_worker_pb2 import ( |
| 5 | + PollForDecisionTaskResponse, |
| 6 | + RespondDecisionTaskCompletedRequest, |
| 7 | + RespondDecisionTaskFailedRequest |
| 8 | +) |
| 9 | +from cadence.api.v1.workflow_pb2 import DecisionTaskFailedCause |
| 10 | +from cadence.client import Client |
| 11 | +from cadence.worker._base_task_handler import BaseTaskHandler |
| 12 | +from cadence._internal.workflow.workflow_engine import WorkflowEngine, DecisionResult |
| 13 | +from cadence.workflow import WorkflowInfo |
| 14 | +from cadence.worker._registry import Registry |
| 15 | + |
| 16 | +logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | +class DecisionTaskHandler(BaseTaskHandler[PollForDecisionTaskResponse]): |
| 19 | + """ |
| 20 | + Task handler for processing decision tasks. |
| 21 | + |
| 22 | + This handler processes decision tasks and generates decisions using the workflow engine. |
| 23 | + """ |
| 24 | + |
| 25 | + def __init__(self, client: Client, task_list: str, registry: Registry, identity: str = "unknown", **options): |
| 26 | + """ |
| 27 | + Initialize the decision task handler. |
| 28 | + |
| 29 | + Args: |
| 30 | + client: The Cadence client instance |
| 31 | + task_list: The task list name |
| 32 | + registry: Registry containing workflow functions |
| 33 | + identity: The worker identity |
| 34 | + **options: Additional options for the handler |
| 35 | + """ |
| 36 | + super().__init__(client, task_list, identity, **options) |
| 37 | + self._registry = registry |
| 38 | + self._workflow_engine: WorkflowEngine |
| 39 | + |
| 40 | + |
| 41 | + async def _handle_task_implementation(self, task: PollForDecisionTaskResponse) -> None: |
| 42 | + """ |
| 43 | + Handle a decision task implementation. |
| 44 | + |
| 45 | + Args: |
| 46 | + task: The decision task to handle |
| 47 | + """ |
| 48 | + # Extract workflow execution info |
| 49 | + workflow_execution = task.workflow_execution |
| 50 | + workflow_type = task.workflow_type |
| 51 | + |
| 52 | + if not workflow_execution or not workflow_type: |
| 53 | + logger.error("Decision task missing workflow execution or type. Task: %r", task) |
| 54 | + raise ValueError("Missing workflow execution or type") |
| 55 | + |
| 56 | + workflow_id = workflow_execution.workflow_id |
| 57 | + run_id = workflow_execution.run_id |
| 58 | + workflow_type_name = workflow_type.name |
| 59 | + |
| 60 | + logger.info(f"Processing decision task for workflow {workflow_id} (type: {workflow_type_name})") |
| 61 | + |
| 62 | + try: |
| 63 | + workflow_func = self._registry.get_workflow(workflow_type_name) |
| 64 | + except KeyError: |
| 65 | + logger.error(f"Workflow type '{workflow_type_name}' not found in registry") |
| 66 | + raise KeyError(f"Workflow type '{workflow_type_name}' not found") |
| 67 | + |
| 68 | + # Create workflow info and engine |
| 69 | + workflow_info = WorkflowInfo( |
| 70 | + workflow_type=workflow_type_name, |
| 71 | + workflow_domain=self._client.domain, |
| 72 | + workflow_id=workflow_id, |
| 73 | + workflow_run_id=run_id |
| 74 | + ) |
| 75 | + |
| 76 | + self._workflow_engine = WorkflowEngine( |
| 77 | + info=workflow_info, |
| 78 | + client=self._client, |
| 79 | + workflow_func=workflow_func |
| 80 | + ) |
| 81 | + |
| 82 | + decision_result = await self._workflow_engine.process_decision(task) |
| 83 | + |
| 84 | + # Respond with the decisions |
| 85 | + await self._respond_decision_task_completed(task, decision_result) |
| 86 | + |
| 87 | + logger.info(f"Successfully processed decision task for workflow {workflow_id}") |
| 88 | + |
| 89 | + async def handle_task_failure(self, task: PollForDecisionTaskResponse, error: Exception) -> None: |
| 90 | + """ |
| 91 | + Handle decision task processing failure. |
| 92 | + |
| 93 | + Args: |
| 94 | + task: The task that failed |
| 95 | + error: The exception that occurred |
| 96 | + """ |
| 97 | + logger.error(f"Decision task failed: {error}") |
| 98 | + |
| 99 | + # Determine the failure cause |
| 100 | + cause = DecisionTaskFailedCause.DECISION_TASK_FAILED_CAUSE_UNHANDLED_DECISION |
| 101 | + if isinstance(error, KeyError): |
| 102 | + cause = DecisionTaskFailedCause.DECISION_TASK_FAILED_CAUSE_WORKFLOW_WORKER_UNHANDLED_FAILURE |
| 103 | + elif isinstance(error, ValueError): |
| 104 | + cause = DecisionTaskFailedCause.DECISION_TASK_FAILED_CAUSE_BAD_SCHEDULE_ACTIVITY_ATTRIBUTES |
| 105 | + |
| 106 | + # Create error details |
| 107 | + # TODO: Use a data converter for error details serialization |
| 108 | + error_message = str(error).encode('utf-8') |
| 109 | + details = Payload(data=error_message) |
| 110 | + |
| 111 | + # Respond with failure |
| 112 | + try: |
| 113 | + await self._client.worker_stub.RespondDecisionTaskFailed( |
| 114 | + RespondDecisionTaskFailedRequest( |
| 115 | + task_token=task.task_token, |
| 116 | + cause=cause, |
| 117 | + identity=self._identity, |
| 118 | + details=details |
| 119 | + ) |
| 120 | + ) |
| 121 | + logger.info("Decision task failure response sent") |
| 122 | + except Exception: |
| 123 | + logger.exception("Error responding to decision task failure") |
| 124 | + |
| 125 | + |
| 126 | + async def _respond_decision_task_completed(self, task: PollForDecisionTaskResponse, decision_result: DecisionResult) -> None: |
| 127 | + """ |
| 128 | + Respond to the service that the decision task has been completed. |
| 129 | + |
| 130 | + Args: |
| 131 | + task: The original decision task |
| 132 | + decision_result: The result containing decisions and query results |
| 133 | + """ |
| 134 | + try: |
| 135 | + request = RespondDecisionTaskCompletedRequest( |
| 136 | + task_token=task.task_token, |
| 137 | + decisions=decision_result.decisions, |
| 138 | + identity=self._identity, |
| 139 | + return_new_decision_task=True, |
| 140 | + force_create_new_decision_task=False |
| 141 | + ) |
| 142 | + |
| 143 | + await self._client.worker_stub.RespondDecisionTaskCompleted(request) |
| 144 | + logger.debug(f"Decision task completed with {len(decision_result.decisions)} decisions") |
| 145 | + |
| 146 | + except Exception: |
| 147 | + logger.exception("Error responding to decision task completion") |
| 148 | + raise |
0 commit comments