-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathworker.py
More file actions
2663 lines (2387 loc) · 122 KB
/
worker.py
File metadata and controls
2663 lines (2387 loc) · 122 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import asyncio
import inspect
import json
import logging
import os
import random
import time
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone
from threading import Event, Thread
from types import GeneratorType
from enum import Enum
from typing import Any, Generator, Optional, Sequence, Tuple, TypeVar, Union
import uuid
from packaging.version import InvalidVersion, parse
import grpc
from google.protobuf import empty_pb2
from durabletask.entities.entity_operation_failed_exception import EntityOperationFailedException
from durabletask.internal import helpers
from durabletask.internal.entity_state_shim import StateShim
from durabletask.internal.helpers import new_timestamp
from durabletask.entities import DurableEntity, EntityLock, EntityInstanceId, EntityContext
from durabletask.internal.json_encode_output_exception import JsonEncodeOutputException
from durabletask.internal.orchestration_entity_context import OrchestrationEntityContext
from durabletask.internal.proto_task_hub_sidecar_service_stub import ProtoTaskHubSidecarServiceStub
import durabletask.internal.helpers as ph
import durabletask.internal.exceptions as pe
import durabletask.internal.orchestrator_service_pb2 as pb
import durabletask.internal.orchestrator_service_pb2_grpc as stubs
import durabletask.internal.shared as shared
import durabletask.internal.tracing as tracing
from durabletask.payload import helpers as payload_helpers
from durabletask import task
from durabletask.internal.grpc_interceptor import DefaultClientInterceptorImpl
from durabletask.payload.store import PayloadStore
TInput = TypeVar("TInput")
TOutput = TypeVar("TOutput")
DATETIME_STRING_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'
class ConcurrencyOptions:
"""Configuration options for controlling concurrency of different work item types and the thread pool size.
This class provides fine-grained control over concurrent processing limits for
activities, orchestrations and the thread pool size.
"""
def __init__(
self,
maximum_concurrent_activity_work_items: Optional[int] = None,
maximum_concurrent_orchestration_work_items: Optional[int] = None,
maximum_concurrent_entity_work_items: Optional[int] = None,
maximum_thread_pool_workers: Optional[int] = None,
):
"""Initialize concurrency options.
Args:
maximum_concurrent_activity_work_items: Maximum number of activity work items
that can be processed concurrently. Defaults to 100 * processor_count.
maximum_concurrent_orchestration_work_items: Maximum number of orchestration work items
that can be processed concurrently. Defaults to 100 * processor_count.
maximum_thread_pool_workers: Maximum number of thread pool workers to use.
"""
processor_count = os.cpu_count() or 1
default_concurrency = 100 * processor_count
# see https://docs.python.org/3/library/concurrent.futures.html
default_max_workers = processor_count + 4
self.maximum_concurrent_activity_work_items = (
maximum_concurrent_activity_work_items
if maximum_concurrent_activity_work_items is not None
else default_concurrency
)
self.maximum_concurrent_orchestration_work_items = (
maximum_concurrent_orchestration_work_items
if maximum_concurrent_orchestration_work_items is not None
else default_concurrency
)
self.maximum_concurrent_entity_work_items = (
maximum_concurrent_entity_work_items
if maximum_concurrent_entity_work_items is not None
else default_concurrency
)
self.maximum_thread_pool_workers = (
maximum_thread_pool_workers
if maximum_thread_pool_workers is not None
else default_max_workers
)
class VersionMatchStrategy(Enum):
"""Enumeration for version matching strategies."""
NONE = 1
STRICT = 2
CURRENT_OR_OLDER = 3
class VersionFailureStrategy(Enum):
"""Enumeration for version failure strategies."""
REJECT = 1
FAIL = 2
class VersioningOptions:
"""Configuration options for orchestrator and activity versioning.
This class provides options to control how versioning is handled for orchestrators
and activities, including whether to use the default version and how to compare versions.
"""
version: Optional[str] = None
default_version: Optional[str] = None
match_strategy: Optional[VersionMatchStrategy] = None
failure_strategy: Optional[VersionFailureStrategy] = None
def __init__(self, version: Optional[str] = None,
default_version: Optional[str] = None,
match_strategy: Optional[VersionMatchStrategy] = None,
failure_strategy: Optional[VersionFailureStrategy] = None
):
"""Initialize versioning options.
Args:
version: The version of orchestrations that the worker can work on.
default_version: The default version that will be used for starting new sub-orchestrations.
match_strategy: The versioning strategy for the Durable Task worker.
failure_strategy: The versioning failure strategy for the Durable Task worker.
"""
self.version = version
self.default_version = default_version
self.match_strategy = match_strategy
self.failure_strategy = failure_strategy
class _Registry:
orchestrators: dict[str, task.Orchestrator]
activities: dict[str, task.Activity]
entities: dict[str, task.Entity]
versioning: Optional[VersioningOptions] = None
def __init__(self):
self.orchestrators = {}
self.activities = {}
self.entities = {}
def add_orchestrator(self, fn: task.Orchestrator[TInput, TOutput]) -> str:
if fn is None:
raise ValueError("An orchestrator function argument is required.")
name = task.get_name(fn)
self.add_named_orchestrator(name, fn)
return name
def add_named_orchestrator(self, name: str, fn: task.Orchestrator[TInput, TOutput]) -> None:
if not name:
raise ValueError("A non-empty orchestrator name is required.")
if name in self.orchestrators:
raise ValueError(f"A '{name}' orchestrator already exists.")
self.orchestrators[name] = fn
def get_orchestrator(self, name: str) -> Optional[task.Orchestrator[Any, Any]]:
return self.orchestrators.get(name)
def add_activity(self, fn: task.Activity[TInput, TOutput]) -> str:
if fn is None:
raise ValueError("An activity function argument is required.")
name = task.get_name(fn)
self.add_named_activity(name, fn)
return name
def add_named_activity(self, name: str, fn: task.Activity[TInput, TOutput]) -> None:
if not name:
raise ValueError("A non-empty activity name is required.")
if name in self.activities:
raise ValueError(f"A '{name}' activity already exists.")
self.activities[name] = fn
def get_activity(self, name: str) -> Optional[task.Activity[Any, Any]]:
return self.activities.get(name)
def add_entity(self, fn: task.Entity, name: Optional[str] = None) -> str:
if fn is None:
raise ValueError("An entity function argument is required.")
if name is None:
name = task.get_entity_name(fn)
self.add_named_entity(name, fn)
return name
def add_named_entity(self, name: str, fn: task.Entity) -> None:
name = name.lower()
EntityInstanceId.validate_entity_name(name)
if name in self.entities:
raise ValueError(f"A '{name}' entity already exists.")
self.entities[name] = fn
def get_entity(self, name: str) -> Optional[task.Entity]:
return self.entities.get(name)
class OrchestratorNotRegisteredError(ValueError):
"""Raised when attempting to start an orchestration that is not registered"""
pass
class ActivityNotRegisteredError(ValueError):
"""Raised when attempting to call an activity that is not registered"""
pass
class EntityNotRegisteredError(ValueError):
"""Raised when attempting to call an entity that is not registered"""
pass
class TaskHubGrpcWorker:
"""A gRPC-based worker for processing durable task orchestrations and activities.
This worker connects to a Durable Task backend service via gRPC to receive and process
work items including orchestration functions and activity functions. It provides
concurrent execution capabilities with configurable limits and automatic retry handling.
The worker manages the complete lifecycle:
- Registers orchestrator and activity functions
- Connects to the gRPC backend service
- Receives work items and executes them concurrently
- Handles failures, retries, and state management
- Provides logging and monitoring capabilities
Args:
host_address (Optional[str], optional): The gRPC endpoint address of the backend service.
Defaults to the value from environment variables or localhost.
metadata (Optional[list[tuple[str, str]]], optional): gRPC metadata to include with
requests. Used for authentication and routing. Defaults to None.
log_handler (optional[logging.Handler]): Custom logging handler for worker logs. Defaults to None.
log_formatter (Optional[logging.Formatter], optional): Custom log formatter.
Defaults to None.
secure_channel (bool, optional): Whether to use a secure gRPC channel (TLS).
Defaults to False.
interceptors (Optional[Sequence[shared.ClientInterceptor]], optional): Custom gRPC
interceptors to apply to the channel. Defaults to None.
concurrency_options (Optional[ConcurrencyOptions], optional): Configuration for
controlling worker concurrency limits. If None, default settings are used.
Attributes:
concurrency_options (ConcurrencyOptions): The current concurrency configuration.
Example:
Basic worker setup:
>>> from durabletask.worker import TaskHubGrpcWorker, ConcurrencyOptions
>>>
>>> # Create worker with custom concurrency settings
>>> concurrency = ConcurrencyOptions(
... maximum_concurrent_activity_work_items=50,
... maximum_concurrent_orchestration_work_items=20
... )
>>> worker = TaskHubGrpcWorker(
... host_address="localhost:4001",
... concurrency_options=concurrency
... )
>>>
>>> # Register functions
>>> @worker.add_orchestrator
... def my_orchestrator(context, input):
... result = yield context.call_activity("my_activity", input="hello")
... return result
>>>
>>> @worker.add_activity
... def my_activity(context, input):
... return f"Processed: {input}"
>>>
>>> # Start the worker
>>> worker.start()
>>> # ... worker runs in background thread
>>> worker.stop()
Using as context manager:
>>> with TaskHubGrpcWorker() as worker:
... worker.add_orchestrator(my_orchestrator)
... worker.add_activity(my_activity)
... worker.start()
... # Worker automatically stops when exiting context
Raises:
RuntimeError: If attempting to add orchestrators/activities while the worker is running,
or if starting a worker that is already running.
OrchestratorNotRegisteredError: If an orchestration work item references an
unregistered orchestrator function.
ActivityNotRegisteredError: If an activity work item references an unregistered
activity function.
"""
_response_stream: Optional[grpc.Future] = None
_interceptors: Optional[list[shared.ClientInterceptor]] = None
def __init__(
self,
*,
host_address: Optional[str] = None,
metadata: Optional[list[tuple[str, str]]] = None,
log_handler: Optional[logging.Handler] = None,
log_formatter: Optional[logging.Formatter] = None,
secure_channel: bool = False,
interceptors: Optional[Sequence[shared.ClientInterceptor]] = None,
concurrency_options: Optional[ConcurrencyOptions] = None,
payload_store: Optional[PayloadStore] = None,
):
self._registry = _Registry()
self._host_address = (
host_address if host_address else shared.get_default_host_address()
)
self._logger = shared.get_logger("worker", log_handler, log_formatter)
self._shutdown = Event()
self._is_running = False
self._secure_channel = secure_channel
self._payload_store = payload_store
# Use provided concurrency options or create default ones
self._concurrency_options = (
concurrency_options
if concurrency_options is not None
else ConcurrencyOptions()
)
# Determine the interceptors to use
if interceptors is not None:
self._interceptors = list(interceptors)
if metadata:
self._interceptors.append(DefaultClientInterceptorImpl(metadata))
elif metadata:
self._interceptors = [DefaultClientInterceptorImpl(metadata)]
else:
self._interceptors = None
self._async_worker_manager = _AsyncWorkerManager(self._concurrency_options, self._logger)
@property
def concurrency_options(self) -> ConcurrencyOptions:
"""Get the current concurrency options for this worker."""
return self._concurrency_options
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.stop()
def add_orchestrator(self, fn: task.Orchestrator[TInput, TOutput]) -> str:
"""Registers an orchestrator function with the worker."""
if self._is_running:
raise RuntimeError(
"Orchestrators cannot be added while the worker is running."
)
return self._registry.add_orchestrator(fn)
def add_activity(self, fn: task.Activity) -> str:
"""Registers an activity function with the worker."""
if self._is_running:
raise RuntimeError(
"Activities cannot be added while the worker is running."
)
return self._registry.add_activity(fn)
def add_entity(self, fn: task.Entity, name: Optional[str] = None) -> str:
"""Registers an entity function with the worker."""
if self._is_running:
raise RuntimeError(
"Entities cannot be added while the worker is running."
)
return self._registry.add_entity(fn, name)
def use_versioning(self, version: VersioningOptions) -> None:
"""Initializes versioning options for sub-orchestrators and activities."""
if self._is_running:
raise RuntimeError("Cannot set default version while the worker is running.")
self._registry.versioning = version
def start(self):
"""Starts the worker on a background thread and begins listening for work items."""
if self._is_running:
raise RuntimeError("The worker is already running.")
def run_loop():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(self._async_run_loop())
self._logger.info(f"Starting gRPC worker that connects to {self._host_address}")
self._runLoop = Thread(target=run_loop)
self._runLoop.start()
self._is_running = True
async def _async_run_loop(self):
worker_task = asyncio.create_task(self._async_worker_manager.run())
# Connection state management for retry fix
current_channel = None
current_stub = None
current_reader_thread = None
conn_retry_count = 0
conn_max_retry_delay = 60
def create_fresh_connection():
nonlocal current_channel, current_stub, conn_retry_count
if current_channel:
try:
current_channel.close()
except Exception:
pass
current_channel = None
current_stub = None
try:
current_channel = shared.get_grpc_channel(
self._host_address, self._secure_channel, self._interceptors
)
current_stub = stubs.TaskHubSidecarServiceStub(current_channel)
current_stub.Hello(empty_pb2.Empty())
conn_retry_count = 0
self._logger.info(f"Created fresh connection to {self._host_address}")
except Exception as e:
self._logger.warning(f"Failed to create connection: {e}")
current_channel = None
current_stub = None
raise
def invalidate_connection():
nonlocal current_channel, current_stub, current_reader_thread
# Cancel the response stream first to signal the reader thread to stop
if self._response_stream is not None:
try:
self._response_stream.cancel()
except Exception:
pass
self._response_stream = None
# Wait for the reader thread to finish
if current_reader_thread is not None:
try:
current_reader_thread.join(timeout=2)
if current_reader_thread.is_alive():
self._logger.warning("Stream reader thread did not shut down gracefully")
except Exception:
pass
current_reader_thread = None
# Close the channel
if current_channel:
try:
current_channel.close()
except Exception:
pass
current_channel = None
current_stub = None
def should_invalidate_connection(rpc_error):
error_code = rpc_error.code() # type: ignore
connection_level_errors = {
grpc.StatusCode.UNAVAILABLE,
grpc.StatusCode.DEADLINE_EXCEEDED,
grpc.StatusCode.CANCELLED,
grpc.StatusCode.UNAUTHENTICATED,
grpc.StatusCode.ABORTED,
}
return error_code in connection_level_errors
while not self._shutdown.is_set():
if current_stub is None:
try:
create_fresh_connection()
except Exception:
conn_retry_count += 1
delay = min(
conn_max_retry_delay,
(2 ** min(conn_retry_count, 6)) + random.uniform(0, 1),
)
self._logger.warning(
f"Connection failed, retrying in {delay:.2f} seconds (attempt {conn_retry_count})"
)
if self._shutdown.wait(delay):
break
continue
try:
assert current_stub is not None
stub = current_stub
capabilities = []
if self._payload_store is not None:
capabilities.append(pb.WORKER_CAPABILITY_LARGE_PAYLOADS)
get_work_items_request = pb.GetWorkItemsRequest(
maxConcurrentOrchestrationWorkItems=self._concurrency_options.maximum_concurrent_orchestration_work_items,
maxConcurrentActivityWorkItems=self._concurrency_options.maximum_concurrent_activity_work_items,
capabilities=capabilities,
)
self._response_stream = stub.GetWorkItems(get_work_items_request)
self._logger.info(
f"Successfully connected to {self._host_address}. Waiting for work items..."
)
# Use a thread to read from the blocking gRPC stream and forward to asyncio
import queue
work_item_queue = queue.Queue()
def stream_reader():
try:
for work_item in self._response_stream:
work_item_queue.put(work_item)
except Exception as e:
work_item_queue.put(e)
import threading
current_reader_thread = threading.Thread(target=stream_reader, daemon=True)
current_reader_thread.start()
loop = asyncio.get_running_loop()
while not self._shutdown.is_set():
try:
work_item = await loop.run_in_executor(
None, work_item_queue.get
)
if isinstance(work_item, Exception):
raise work_item
request_type = work_item.WhichOneof("request")
self._logger.debug(f'Received "{request_type}" work item')
if work_item.HasField("orchestratorRequest"):
self._async_worker_manager.submit_orchestration(
self._execute_orchestrator,
self._cancel_orchestrator,
work_item.orchestratorRequest,
stub,
work_item.completionToken,
)
elif work_item.HasField("activityRequest"):
self._async_worker_manager.submit_activity(
self._execute_activity,
self._cancel_activity,
work_item.activityRequest,
stub,
work_item.completionToken,
)
elif work_item.HasField("entityRequest"):
self._async_worker_manager.submit_entity_batch(
self._execute_entity_batch,
self._cancel_entity_batch,
work_item.entityRequest,
stub,
work_item.completionToken,
)
elif work_item.HasField("entityRequestV2"):
self._async_worker_manager.submit_entity_batch(
self._execute_entity_batch,
self._cancel_entity_batch,
work_item.entityRequestV2,
stub,
work_item.completionToken
)
elif work_item.HasField("healthPing"):
pass
else:
self._logger.warning(
f"Unexpected work item type: {request_type}"
)
except Exception as e:
self._logger.warning(f"Error in work item stream: {e}")
raise e
current_reader_thread.join(timeout=1)
self._logger.info("Work item stream ended normally")
except grpc.RpcError as rpc_error:
should_invalidate = should_invalidate_connection(rpc_error)
if should_invalidate:
invalidate_connection()
error_code = rpc_error.code() # type: ignore
error_details = str(rpc_error)
if error_code == grpc.StatusCode.CANCELLED:
self._logger.info(f"Disconnected from {self._host_address}")
break
elif error_code == grpc.StatusCode.UNAVAILABLE:
# Check if this is a connection timeout scenario
if "Timeout occurred" in error_details or "Failed to connect to remote host" in error_details:
self._logger.warning(
f"Connection timeout to {self._host_address}: {error_details} - will retry with fresh connection"
)
else:
self._logger.warning(
f"The sidecar at address {self._host_address} is unavailable: {error_details} - will continue retrying"
)
elif should_invalidate:
self._logger.warning(
f"Connection-level gRPC error ({error_code}): {rpc_error} - resetting connection"
)
else:
self._logger.warning(
f"Application-level gRPC error ({error_code}): {rpc_error}"
)
self._shutdown.wait(1)
except Exception as ex:
invalidate_connection()
self._logger.warning(f"Unexpected error: {ex}")
self._shutdown.wait(1)
invalidate_connection()
self._logger.info("No longer listening for work items")
self._async_worker_manager.shutdown()
await worker_task
def stop(self):
"""Stops the worker and waits for any pending work items to complete."""
if not self._is_running:
return
self._logger.info("Stopping gRPC worker...")
self._shutdown.set()
if self._response_stream is not None:
self._response_stream.cancel()
if self._runLoop is not None:
self._runLoop.join(timeout=30)
self._async_worker_manager.shutdown()
self._logger.info("Worker shutdown completed")
self._is_running = False
def _execute_orchestrator(
self,
req: pb.OrchestratorRequest,
stub: Union[stubs.TaskHubSidecarServiceStub, ProtoTaskHubSidecarServiceStub],
completionToken,
):
instance_id = req.instanceId
# De-externalize any large-payload tokens in the incoming request
if self._payload_store is not None:
payload_helpers.deexternalize_payloads(req, self._payload_store)
# Extract parent trace context from executionStarted event
parent_trace_ctx = None
orchestration_name = "<unknown>"
for e in list(req.pastEvents) + list(req.newEvents):
if e.HasField("executionStarted"):
orchestration_name = e.executionStarted.name
if e.executionStarted.HasField("parentTraceContext"):
parent_trace_ctx = e.executionStarted.parentTraceContext
break
# Determine the orchestration start time: reuse persisted value
# from a prior dispatch, or capture a new one.
if (req.HasField("orchestrationTraceContext") and req.orchestrationTraceContext.HasField("spanStartTime")):
start_time_ns = req.orchestrationTraceContext.spanStartTime.ToNanoseconds()
else:
start_time_ns = time.time_ns()
# Extract persisted orchestration span ID from a prior dispatch
persisted_orch_span_id = None
if (req.HasField("orchestrationTraceContext") and req.orchestrationTraceContext.HasField("spanID") and req.orchestrationTraceContext.spanID.value):
persisted_orch_span_id = req.orchestrationTraceContext.spanID.value
try:
executor = _OrchestrationExecutor(
self._registry, self._logger,
persisted_orch_span_id=persisted_orch_span_id)
result = executor.execute(instance_id, req.pastEvents, req.newEvents)
# Determine completion status for span
is_complete = False
is_failed = False
failure_details = None
for action in result.actions:
if action.HasField("completeOrchestration"):
is_complete = True
orch_status = action.completeOrchestration.orchestrationStatus
if orch_status == pb.ORCHESTRATION_STATUS_FAILED:
is_failed = True
failure_details = action.completeOrchestration.failureDetails
if is_complete:
# Orchestration finished — emit a single span covering its lifetime
tracing.emit_orchestration_span(
orchestration_name,
instance_id,
start_time_ns,
is_failed,
failure_details=failure_details,
parent_trace_context=parent_trace_ctx,
orchestration_trace_context=result._orchestration_trace_context,
)
# Include the span ID in the orchestration trace context
# so it persists across dispatches.
orch_span_id = None
if result._orchestration_trace_context:
orch_span_id = result._orchestration_trace_context.spanID
orch_trace_ctx = tracing.build_orchestration_trace_context(
start_time_ns, span_id=orch_span_id)
res = pb.OrchestratorResponse(
instanceId=instance_id,
actions=result.actions,
customStatus=ph.get_string_value(result.encoded_custom_status),
completionToken=completionToken,
orchestrationTraceContext=(
orch_trace_ctx if orch_trace_ctx
else req.orchestrationTraceContext
),
)
except pe.AbandonOrchestrationError:
# Abandoned — no span needed
self._logger.info(
f"Abandoning orchestration. InstanceId = '{instance_id}'. Completion token = '{completionToken}'"
)
stub.AbandonTaskOrchestratorWorkItem(
pb.AbandonOrchestrationTaskRequest(
completionToken=completionToken
)
)
return
except Exception as ex:
# Unhandled error — emit a failed span
tracing.emit_orchestration_span(
orchestration_name,
instance_id,
start_time_ns,
is_failed=True,
failure_details=ex,
parent_trace_context=parent_trace_ctx,
)
self._logger.exception(
f"An error occurred while trying to execute instance '{instance_id}': {ex}"
)
failure_details = ph.new_failure_details(ex)
actions = [
ph.new_complete_orchestration_action(
-1, pb.ORCHESTRATION_STATUS_FAILED, "", failure_details
)
]
res = pb.OrchestratorResponse(
instanceId=instance_id,
actions=actions,
completionToken=completionToken,
)
try:
# Externalize any large payloads in the response
if self._payload_store is not None:
payload_helpers.externalize_payloads(
res, self._payload_store, instance_id=instance_id,
)
stub.CompleteOrchestratorTask(res)
except Exception as ex:
self._logger.exception(
f"Failed to deliver orchestrator response for '{req.instanceId}' to sidecar: {ex}"
)
def _cancel_orchestrator(
self,
req: pb.OrchestratorRequest,
stub: Union[stubs.TaskHubSidecarServiceStub, ProtoTaskHubSidecarServiceStub],
completionToken,
):
stub.AbandonTaskOrchestratorWorkItem(
pb.AbandonOrchestrationTaskRequest(
completionToken=completionToken
)
)
self._logger.info(f"Cancelled orchestration task for invocation ID: {req.instanceId}")
def _execute_activity(
self,
req: pb.ActivityRequest,
stub: Union[stubs.TaskHubSidecarServiceStub, ProtoTaskHubSidecarServiceStub],
completionToken,
):
instance_id = req.orchestrationInstance.instanceId
# De-externalize any large-payload tokens in the incoming request
if self._payload_store is not None:
payload_helpers.deexternalize_payloads(req, self._payload_store)
try:
executor = _ActivityExecutor(self._registry, self._logger)
with tracing.start_span(
tracing.create_span_name("activity", req.name),
trace_context=req.parentTraceContext,
kind=tracing.SpanKind.SERVER,
attributes={
tracing.ATTR_TASK_TYPE: "activity",
tracing.ATTR_TASK_INSTANCE_ID: instance_id,
tracing.ATTR_TASK_NAME: req.name,
tracing.ATTR_TASK_TASK_ID: str(req.taskId),
},
) as span:
try:
result = executor.execute(
instance_id, req.name, req.taskId, req.input.value
)
except Exception as ex:
tracing.set_span_error(span, ex)
raise
res = pb.ActivityResponse(
instanceId=instance_id,
taskId=req.taskId,
result=ph.get_string_value(result),
completionToken=completionToken,
)
except Exception as ex:
res = pb.ActivityResponse(
instanceId=instance_id,
taskId=req.taskId,
failureDetails=ph.new_failure_details(ex),
completionToken=completionToken,
)
try:
# Externalize any large payloads in the response
if self._payload_store is not None:
payload_helpers.externalize_payloads(
res, self._payload_store, instance_id=instance_id,
)
stub.CompleteActivityTask(res)
except Exception as ex:
self._logger.exception(
f"Failed to deliver activity response for '{req.name}#{req.taskId}' of orchestration ID '{instance_id}' to sidecar: {ex}"
)
def _cancel_activity(
self,
req: pb.ActivityRequest,
stub: Union[stubs.TaskHubSidecarServiceStub, ProtoTaskHubSidecarServiceStub],
completionToken,
):
stub.AbandonTaskActivityWorkItem(
pb.AbandonActivityTaskRequest(
completionToken=completionToken
)
)
self._logger.info(f"Cancelled activity task for task ID: {req.taskId} on orchestration ID: {req.orchestrationInstance.instanceId}")
def _execute_entity_batch(
self,
req: Union[pb.EntityBatchRequest, pb.EntityRequest],
stub: Union[stubs.TaskHubSidecarServiceStub, ProtoTaskHubSidecarServiceStub],
completionToken,
):
operation_infos: list[pb.OperationInfo] = []
if isinstance(req, pb.EntityRequest):
req, operation_infos = helpers.convert_to_entity_batch_request(req)
# De-externalize any large-payload tokens in the incoming request
if self._payload_store is not None:
payload_helpers.deexternalize_payloads(req, self._payload_store)
entity_state = StateShim(shared.from_json(req.entityState.value) if req.entityState.value else None)
instance_id = req.instanceId
try:
entity_instance_id = EntityInstanceId.parse(instance_id)
except ValueError:
raise RuntimeError(f"Invalid entity instance ID '{instance_id}' in entity operation request.")
results: list[pb.OperationResult] = []
for operation in req.operations:
start_time = datetime.now(timezone.utc)
executor = _EntityExecutor(self._registry, self._logger)
operation_result = None
# Get the trace context for this operation, if available
op_trace_ctx = operation.traceContext if operation.HasField("traceContext") else None
with tracing.start_span(
tracing.create_span_name("entity", f"{entity_instance_id.entity}:{operation.operation}"),
trace_context=op_trace_ctx,
kind=tracing.SpanKind.SERVER,
attributes={
tracing.ATTR_TASK_TYPE: "entity",
tracing.ATTR_TASK_INSTANCE_ID: instance_id,
tracing.ATTR_TASK_NAME: entity_instance_id.entity,
"durabletask.entity.operation": operation.operation,
},
) as span:
try:
entity_result = executor.execute(
instance_id, entity_instance_id, operation.operation, entity_state, operation.input.value
)
entity_result = ph.get_string_value_or_empty(entity_result)
operation_result = pb.OperationResult(success=pb.OperationResultSuccess(
result=entity_result,
startTimeUtc=new_timestamp(start_time),
endTimeUtc=new_timestamp(datetime.now(timezone.utc))
))
results.append(operation_result)
entity_state.commit()
except Exception as ex:
tracing.set_span_error(span, ex)
self._logger.exception(ex)
operation_result = pb.OperationResult(failure=pb.OperationResultFailure(
failureDetails=ph.new_failure_details(ex),
startTimeUtc=new_timestamp(start_time),
endTimeUtc=new_timestamp(datetime.now(timezone.utc))
))
results.append(operation_result)
entity_state.rollback()
batch_result = pb.EntityBatchResult(
results=results,
actions=entity_state.get_operation_actions(),
entityState=helpers.get_string_value(shared.to_json(entity_state._current_state)) if entity_state._current_state else None,
failureDetails=None,
completionToken=completionToken,
operationInfos=operation_infos,
)
try:
# Externalize any large payloads in the response
if self._payload_store is not None:
payload_helpers.externalize_payloads(
batch_result, self._payload_store, instance_id=instance_id,
)
stub.CompleteEntityTask(batch_result)
except Exception as ex:
self._logger.exception(
f"Failed to deliver entity response for '{entity_instance_id}' of orchestration ID '{instance_id}' to sidecar: {ex}"
)
# TODO: Reset context
return batch_result
def _cancel_entity_batch(
self,
req: Union[pb.EntityBatchRequest, pb.EntityRequest],
stub: Union[stubs.TaskHubSidecarServiceStub, ProtoTaskHubSidecarServiceStub],
completionToken,
):
stub.AbandonTaskEntityWorkItem(
pb.AbandonEntityTaskRequest(
completionToken=completionToken
)
)
self._logger.info(f"Cancelled entity batch task for instance ID: {req.instanceId}")
class _RuntimeOrchestrationContext(task.OrchestrationContext):
_generator: Optional[Generator[task.Task, Any, Any]]
_previous_task: Optional[task.Task]
def __init__(self, instance_id: str, registry: _Registry):
self._generator = None
self._is_replaying = True
self._is_complete = False
self._result = None
self._pending_actions: dict[int, pb.OrchestratorAction] = {}
self._pending_tasks: dict[int, task.CompletableTask] = {}
# Maps entity ID to task ID
self._entity_task_id_map: dict[str, tuple[EntityInstanceId, str, int]] = {}
self._entity_lock_task_id_map: dict[str, tuple[EntityInstanceId, int]] = {}
# Maps criticalSectionId to task ID
self._entity_lock_id_map: dict[str, int] = {}
self._sequence_number = 0
self._new_uuid_counter = 0
self._current_utc_datetime = datetime(1000, 1, 1)
self._instance_id = instance_id
self._registry = registry
self._entity_context = OrchestrationEntityContext(instance_id)
self._version: Optional[str] = None
self._completion_status: Optional[pb.OrchestrationStatus] = None
self._received_events: dict[str, list[Any]] = {}
self._pending_events: dict[str, list[task.CompletableTask]] = {}
self._new_input: Optional[Any] = None
self._save_events = False
self._encoded_custom_status: Optional[str] = None
self._parent_trace_context: Optional[pb.TraceContext] = None
self._orchestration_trace_context: Optional[pb.TraceContext] = None
def run(self, generator: Generator[task.Task, Any, Any]):
self._generator = generator
# TODO: Do something with this task
task = next(generator) # this starts the generator
# TODO: Check if the task is null?
self._previous_task = task
def resume(self):