|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT License. |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import logging |
| 7 | +import uuid |
| 8 | +from datetime import datetime, timezone |
| 9 | +from typing import TYPE_CHECKING, Any, List, Optional, Sequence, TypeVar, Union |
| 10 | + |
| 11 | +import durabletask.internal.helpers as helpers |
| 12 | +import durabletask.internal.orchestrator_service_pb2 as pb |
| 13 | +import durabletask.internal.shared as shared |
| 14 | +from durabletask import task |
| 15 | +from durabletask.internal.grpc_interceptor import ( |
| 16 | + DefaultAsyncClientInterceptorImpl, |
| 17 | + DefaultClientInterceptorImpl, |
| 18 | +) |
| 19 | + |
| 20 | +if TYPE_CHECKING: |
| 21 | + from durabletask.client import ( |
| 22 | + EntityQuery, |
| 23 | + OrchestrationQuery, |
| 24 | + OrchestrationState, |
| 25 | + OrchestrationStatus, |
| 26 | + ) |
| 27 | + from durabletask.entities import EntityInstanceId |
| 28 | + |
| 29 | +TInput = TypeVar('TInput') |
| 30 | +TOutput = TypeVar('TOutput') |
| 31 | + |
| 32 | + |
| 33 | +def prepare_sync_interceptors( |
| 34 | + metadata: Optional[list[tuple[str, str]]], |
| 35 | + interceptors: Optional[Sequence[shared.ClientInterceptor]] |
| 36 | +) -> Optional[list[shared.ClientInterceptor]]: |
| 37 | + """Prepare the list of sync gRPC interceptors, adding a metadata interceptor if needed.""" |
| 38 | + result: Optional[list[shared.ClientInterceptor]] = None |
| 39 | + if interceptors is not None: |
| 40 | + result = list(interceptors) |
| 41 | + if metadata is not None: |
| 42 | + result.append(DefaultClientInterceptorImpl(metadata)) |
| 43 | + elif metadata is not None: |
| 44 | + result = [DefaultClientInterceptorImpl(metadata)] |
| 45 | + return result |
| 46 | + |
| 47 | + |
| 48 | +def prepare_async_interceptors( |
| 49 | + metadata: Optional[list[tuple[str, str]]], |
| 50 | + interceptors: Optional[Sequence[shared.AsyncClientInterceptor]] |
| 51 | +) -> Optional[list[shared.AsyncClientInterceptor]]: |
| 52 | + """Prepare the list of async gRPC interceptors, adding a metadata interceptor if needed.""" |
| 53 | + result: Optional[list[shared.AsyncClientInterceptor]] = None |
| 54 | + if interceptors is not None: |
| 55 | + result = list(interceptors) |
| 56 | + if metadata is not None: |
| 57 | + result.append(DefaultAsyncClientInterceptorImpl(metadata)) |
| 58 | + elif metadata is not None: |
| 59 | + result = [DefaultAsyncClientInterceptorImpl(metadata)] |
| 60 | + return result |
| 61 | + |
| 62 | + |
| 63 | +def build_schedule_new_orchestration_req( |
| 64 | + orchestrator: Union[task.Orchestrator[TInput, TOutput], str], *, |
| 65 | + input: Optional[TInput], |
| 66 | + instance_id: Optional[str], |
| 67 | + start_at: Optional[datetime], |
| 68 | + reuse_id_policy: Optional[pb.OrchestrationIdReusePolicy], |
| 69 | + tags: Optional[dict[str, str]], |
| 70 | + version: Optional[str]) -> pb.CreateInstanceRequest: |
| 71 | + """Build a CreateInstanceRequest for scheduling a new orchestration.""" |
| 72 | + name = orchestrator if isinstance(orchestrator, str) else task.get_name(orchestrator) |
| 73 | + return pb.CreateInstanceRequest( |
| 74 | + name=name, |
| 75 | + instanceId=instance_id if instance_id else uuid.uuid4().hex, |
| 76 | + input=helpers.get_string_value(shared.to_json(input) if input is not None else None), |
| 77 | + scheduledStartTimestamp=helpers.new_timestamp(start_at) if start_at else None, |
| 78 | + version=helpers.get_string_value(version), |
| 79 | + orchestrationIdReusePolicy=reuse_id_policy, |
| 80 | + tags=tags |
| 81 | + ) |
| 82 | + |
| 83 | + |
| 84 | +def build_query_instances_req( |
| 85 | + orchestration_query: OrchestrationQuery, |
| 86 | + continuation_token) -> pb.QueryInstancesRequest: |
| 87 | + """Build a QueryInstancesRequest from an OrchestrationQuery.""" |
| 88 | + return pb.QueryInstancesRequest( |
| 89 | + query=pb.InstanceQuery( |
| 90 | + runtimeStatus=[status.value for status in orchestration_query.runtime_status] if orchestration_query.runtime_status else None, |
| 91 | + createdTimeFrom=helpers.new_timestamp(orchestration_query.created_time_from) if orchestration_query.created_time_from else None, |
| 92 | + createdTimeTo=helpers.new_timestamp(orchestration_query.created_time_to) if orchestration_query.created_time_to else None, |
| 93 | + maxInstanceCount=orchestration_query.max_instance_count, |
| 94 | + fetchInputsAndOutputs=orchestration_query.fetch_inputs_and_outputs, |
| 95 | + continuationToken=continuation_token |
| 96 | + ) |
| 97 | + ) |
| 98 | + |
| 99 | + |
| 100 | +def build_purge_by_filter_req( |
| 101 | + created_time_from: Optional[datetime], |
| 102 | + created_time_to: Optional[datetime], |
| 103 | + runtime_status: Optional[List[OrchestrationStatus]], |
| 104 | + recursive: bool) -> pb.PurgeInstancesRequest: |
| 105 | + """Build a PurgeInstancesRequest for purging orchestrations by filter.""" |
| 106 | + return pb.PurgeInstancesRequest( |
| 107 | + purgeInstanceFilter=pb.PurgeInstanceFilter( |
| 108 | + createdTimeFrom=helpers.new_timestamp(created_time_from) if created_time_from else None, |
| 109 | + createdTimeTo=helpers.new_timestamp(created_time_to) if created_time_to else None, |
| 110 | + runtimeStatus=[status.value for status in runtime_status] if runtime_status else None |
| 111 | + ), |
| 112 | + recursive=recursive |
| 113 | + ) |
| 114 | + |
| 115 | + |
| 116 | +def build_query_entities_req( |
| 117 | + entity_query: EntityQuery, |
| 118 | + continuation_token) -> pb.QueryEntitiesRequest: |
| 119 | + """Build a QueryEntitiesRequest from an EntityQuery.""" |
| 120 | + return pb.QueryEntitiesRequest( |
| 121 | + query=pb.EntityQuery( |
| 122 | + instanceIdStartsWith=helpers.get_string_value(entity_query.instance_id_starts_with), |
| 123 | + lastModifiedFrom=helpers.new_timestamp(entity_query.last_modified_from) if entity_query.last_modified_from else None, |
| 124 | + lastModifiedTo=helpers.new_timestamp(entity_query.last_modified_to) if entity_query.last_modified_to else None, |
| 125 | + includeState=entity_query.include_state, |
| 126 | + includeTransient=entity_query.include_transient, |
| 127 | + pageSize=helpers.get_int_value(entity_query.page_size), |
| 128 | + continuationToken=continuation_token |
| 129 | + ) |
| 130 | + ) |
| 131 | + |
| 132 | + |
| 133 | +def check_continuation_token(resp_token, prev_token, logger: logging.Logger) -> bool: |
| 134 | + """Check if a continuation token indicates more pages. Returns True to continue, False to stop.""" |
| 135 | + if resp_token and resp_token.value and resp_token.value != "0": |
| 136 | + logger.info(f"Received continuation token with value {resp_token.value}, fetching next page...") |
| 137 | + if prev_token and prev_token.value and prev_token.value == resp_token.value: |
| 138 | + logger.warning(f"Received the same continuation token value {resp_token.value} again, stopping to avoid infinite loop.") |
| 139 | + return False |
| 140 | + return True |
| 141 | + return False |
| 142 | + |
| 143 | + |
| 144 | +def log_completion_state( |
| 145 | + logger: logging.Logger, |
| 146 | + instance_id: str, |
| 147 | + state: Optional[OrchestrationState]): |
| 148 | + """Log the final state of a completed orchestration.""" |
| 149 | + if not state: |
| 150 | + return |
| 151 | + # Compare against proto constants to avoid circular imports with client.py |
| 152 | + status_val = state.runtime_status.value |
| 153 | + if status_val == pb.ORCHESTRATION_STATUS_FAILED and state.failure_details is not None: |
| 154 | + details = state.failure_details |
| 155 | + logger.info(f"Instance '{instance_id}' failed: [{details.error_type}] {details.message}") |
| 156 | + elif status_val == pb.ORCHESTRATION_STATUS_TERMINATED: |
| 157 | + logger.info(f"Instance '{instance_id}' was terminated.") |
| 158 | + elif status_val == pb.ORCHESTRATION_STATUS_COMPLETED: |
| 159 | + logger.info(f"Instance '{instance_id}' completed.") |
| 160 | + |
| 161 | + |
| 162 | +def build_raise_event_req( |
| 163 | + instance_id: str, |
| 164 | + event_name: str, |
| 165 | + data: Optional[Any] = None) -> pb.RaiseEventRequest: |
| 166 | + """Build a RaiseEventRequest for raising an orchestration event.""" |
| 167 | + return pb.RaiseEventRequest( |
| 168 | + instanceId=instance_id, |
| 169 | + name=event_name, |
| 170 | + input=helpers.get_string_value(shared.to_json(data) if data is not None else None) |
| 171 | + ) |
| 172 | + |
| 173 | + |
| 174 | +def build_terminate_req( |
| 175 | + instance_id: str, |
| 176 | + output: Optional[Any] = None, |
| 177 | + recursive: bool = True) -> pb.TerminateRequest: |
| 178 | + """Build a TerminateRequest for terminating an orchestration.""" |
| 179 | + return pb.TerminateRequest( |
| 180 | + instanceId=instance_id, |
| 181 | + output=helpers.get_string_value(shared.to_json(output) if output is not None else None), |
| 182 | + recursive=recursive |
| 183 | + ) |
| 184 | + |
| 185 | + |
| 186 | +def build_signal_entity_req( |
| 187 | + entity_instance_id: EntityInstanceId, |
| 188 | + operation_name: str, |
| 189 | + input: Optional[Any] = None) -> pb.SignalEntityRequest: |
| 190 | + """Build a SignalEntityRequest for signaling an entity.""" |
| 191 | + return pb.SignalEntityRequest( |
| 192 | + instanceId=str(entity_instance_id), |
| 193 | + name=operation_name, |
| 194 | + input=helpers.get_string_value(shared.to_json(input) if input is not None else None), |
| 195 | + requestId=str(uuid.uuid4()), |
| 196 | + scheduledTime=None, |
| 197 | + parentTraceContext=None, |
| 198 | + requestTime=helpers.new_timestamp(datetime.now(timezone.utc)) |
| 199 | + ) |
0 commit comments