|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT License. |
| 3 | + |
| 4 | +import json |
| 5 | +from dataclasses import fields, is_dataclass |
| 6 | +from datetime import datetime, timezone |
| 7 | +from typing import Any, cast |
| 8 | + |
| 9 | +from durabletask import history, task |
| 10 | +from durabletask.client import OrchestrationStatus |
| 11 | + |
| 12 | +from .orchestration_runtime_status import from_durabletask_status |
| 13 | + |
| 14 | + |
| 15 | +def project_history( |
| 16 | + events: list[history.HistoryEvent], |
| 17 | + *, |
| 18 | + show_input: bool, |
| 19 | + show_history_output: bool) -> list[dict[str, Any]]: |
| 20 | + """Project Durable Task history events into the v1 status-query shape.""" |
| 21 | + projected: list[dict[str, Any]] = [] |
| 22 | + scheduled_tasks: dict[int, tuple[int, history.TaskScheduledEvent]] = {} |
| 23 | + scheduled_sub_orchestrations: dict[ |
| 24 | + int, tuple[int, history.SubOrchestrationInstanceCreatedEvent]] = {} |
| 25 | + removed_indexes: set[int] = set() |
| 26 | + |
| 27 | + for event in events: |
| 28 | + if isinstance( |
| 29 | + event, |
| 30 | + (history.OrchestratorStartedEvent, |
| 31 | + history.OrchestratorCompletedEvent)): |
| 32 | + continue |
| 33 | + |
| 34 | + item = _project_event( |
| 35 | + event, |
| 36 | + show_input=show_input, |
| 37 | + show_history_output=show_history_output) |
| 38 | + projected_index = len(projected) |
| 39 | + |
| 40 | + if isinstance(event, history.TaskScheduledEvent): |
| 41 | + scheduled_tasks[event.event_id] = (projected_index, event) |
| 42 | + elif isinstance( |
| 43 | + event, |
| 44 | + (history.TaskCompletedEvent, history.TaskFailedEvent)): |
| 45 | + _add_scheduled_event_data( |
| 46 | + item, |
| 47 | + event.task_scheduled_id, |
| 48 | + scheduled_tasks, |
| 49 | + removed_indexes, |
| 50 | + show_input) |
| 51 | + elif isinstance(event, history.SubOrchestrationInstanceCreatedEvent): |
| 52 | + scheduled_sub_orchestrations[event.event_id] = ( |
| 53 | + projected_index, event) |
| 54 | + elif isinstance( |
| 55 | + event, |
| 56 | + (history.SubOrchestrationInstanceCompletedEvent, |
| 57 | + history.SubOrchestrationInstanceFailedEvent)): |
| 58 | + _add_scheduled_event_data( |
| 59 | + item, |
| 60 | + event.task_scheduled_id, |
| 61 | + scheduled_sub_orchestrations, |
| 62 | + removed_indexes, |
| 63 | + show_input) |
| 64 | + |
| 65 | + projected.append(item) |
| 66 | + |
| 67 | + return [ |
| 68 | + event for index, event in enumerate(projected) |
| 69 | + if index not in removed_indexes |
| 70 | + ] |
| 71 | + |
| 72 | + |
| 73 | +def _project_event( |
| 74 | + event: history.HistoryEvent, |
| 75 | + *, |
| 76 | + show_input: bool, |
| 77 | + show_history_output: bool) -> dict[str, Any]: |
| 78 | + item = { |
| 79 | + "EventType": type(event).__name__.removesuffix("Event"), |
| 80 | + "Timestamp": _format_datetime(event.timestamp), |
| 81 | + } |
| 82 | + for field in fields(event): |
| 83 | + if field.name in {"event_id", "timestamp"}: |
| 84 | + continue |
| 85 | + if field.name == "input" and not show_input: |
| 86 | + continue |
| 87 | + if field.name in {"result", "output"} and not show_history_output: |
| 88 | + continue |
| 89 | + |
| 90 | + value = getattr(event, field.name) |
| 91 | + if value is None: |
| 92 | + continue |
| 93 | + if field.name in {"result", "output"}: |
| 94 | + value = _raw_payload(value) |
| 95 | + item[_field_name(field.name)] = _serialize(value) |
| 96 | + |
| 97 | + if isinstance( |
| 98 | + event, |
| 99 | + (history.TaskScheduledEvent, |
| 100 | + history.SubOrchestrationInstanceCreatedEvent)): |
| 101 | + item.pop("Version", None) |
| 102 | + elif isinstance(event, history.ExecutionStartedEvent): |
| 103 | + item["FunctionName"] = item.pop("Name") |
| 104 | + for field_name in ( |
| 105 | + "OrchestrationInstance", |
| 106 | + "ParentInstance", |
| 107 | + "Version", |
| 108 | + "Tags"): |
| 109 | + item.pop(field_name, None) |
| 110 | + elif isinstance( |
| 111 | + event, |
| 112 | + (history.TaskCompletedEvent, |
| 113 | + history.TaskFailedEvent, |
| 114 | + history.SubOrchestrationInstanceCompletedEvent, |
| 115 | + history.SubOrchestrationInstanceFailedEvent)): |
| 116 | + item.pop("TaskScheduledId", None) |
| 117 | + elif isinstance(event, history.ExecutionCompletedEvent): |
| 118 | + try: |
| 119 | + status = OrchestrationStatus(event.orchestration_status) |
| 120 | + except ValueError: |
| 121 | + pass |
| 122 | + else: |
| 123 | + item["OrchestrationStatus"] = from_durabletask_status(status).name |
| 124 | + elif isinstance(event, history.TimerFiredEvent): |
| 125 | + item.pop("TimerId", None) |
| 126 | + |
| 127 | + return item |
| 128 | + |
| 129 | + |
| 130 | +def _add_scheduled_event_data( |
| 131 | + item: dict[str, Any], |
| 132 | + scheduled_id: int, |
| 133 | + scheduled_events: dict[int, tuple[int, Any]], |
| 134 | + removed_indexes: set[int], |
| 135 | + show_input: bool) -> None: |
| 136 | + scheduled = scheduled_events.get(scheduled_id) |
| 137 | + if scheduled is None: |
| 138 | + return |
| 139 | + |
| 140 | + scheduled_index, scheduled_event = scheduled |
| 141 | + item["ScheduledTime"] = _format_datetime(scheduled_event.timestamp) |
| 142 | + item["FunctionName"] = scheduled_event.name |
| 143 | + if show_input and scheduled_event.input is not None: |
| 144 | + item["Input"] = scheduled_event.input |
| 145 | + removed_indexes.add(scheduled_index) |
| 146 | + |
| 147 | + |
| 148 | +def _serialize(value: Any) -> Any: |
| 149 | + if isinstance(value, datetime): |
| 150 | + return _format_datetime(value) |
| 151 | + if isinstance(value, task.FailureDetails): |
| 152 | + result = { |
| 153 | + "ErrorMessage": value.message, |
| 154 | + "ErrorType": value.error_type, |
| 155 | + } |
| 156 | + if value.stack_trace is not None: |
| 157 | + result["StackTrace"] = value.stack_trace |
| 158 | + return result |
| 159 | + if is_dataclass(value) and not isinstance(value, type): |
| 160 | + return { |
| 161 | + _field_name(field.name): _serialize(getattr(value, field.name)) |
| 162 | + for field in fields(value) |
| 163 | + if getattr(value, field.name) is not None |
| 164 | + } |
| 165 | + if isinstance(value, list): |
| 166 | + return [_serialize(item) for item in cast(list[Any], value)] |
| 167 | + if isinstance(value, dict): |
| 168 | + mapping = cast(dict[Any, Any], value) |
| 169 | + return {key: _serialize(item) for key, item in mapping.items()} |
| 170 | + return value |
| 171 | + |
| 172 | + |
| 173 | +def _field_name(name: str) -> str: |
| 174 | + if name == "scheduled_start_timestamp": |
| 175 | + return "ScheduledStartTime" |
| 176 | + if name in {"orchestration_span_id", "span_id"}: |
| 177 | + return "".join(part.title() for part in name.split("_"))[:-2] + "ID" |
| 178 | + return "".join(part.title() for part in name.split("_")) |
| 179 | + |
| 180 | + |
| 181 | +def _raw_payload(serialized: str) -> Any: |
| 182 | + try: |
| 183 | + return json.loads(serialized) |
| 184 | + except (TypeError, ValueError): |
| 185 | + return serialized |
| 186 | + |
| 187 | + |
| 188 | +def _format_datetime(value: datetime) -> str: |
| 189 | + if value.tzinfo is not None: |
| 190 | + value = value.astimezone(timezone.utc).replace(tzinfo=None) |
| 191 | + return value.strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z" |
0 commit comments