-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathworker.py
More file actions
1693 lines (1500 loc) · 71.9 KB
/
worker.py
File metadata and controls
1693 lines (1500 loc) · 71.9 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 logging
import os
import random
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta
from threading import Event, Thread
from types import GeneratorType
from enum import Enum
from typing import Any, Generator, Optional, Sequence, TypeVar, Union
from packaging.version import InvalidVersion, parse
import grpc
from google.protobuf import empty_pb2
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
from durabletask import task
from durabletask.internal.grpc_interceptor import DefaultClientInterceptorImpl
TInput = TypeVar("TInput")
TOutput = TypeVar("TOutput")
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_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_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]
versioning: Optional[VersioningOptions] = None
def __init__(self):
self.orchestrators = {}
self.activities = {}
def add_orchestrator(self, fn: task.Orchestrator) -> 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) -> 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]:
return self.orchestrators.get(name)
def add_activity(self, fn: task.Activity) -> 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) -> 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]:
return self.activities.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 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): 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=None,
log_formatter: Optional[logging.Formatter] = None,
secure_channel: bool = False,
interceptors: Optional[Sequence[shared.ClientInterceptor]] = None,
concurrency_options: Optional[ConcurrencyOptions] = 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
# 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)
@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) -> 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 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
get_work_items_request = pb.GetWorkItemsRequest(
maxConcurrentOrchestrationWorkItems=self._concurrency_options.maximum_concurrent_orchestration_work_items,
maxConcurrentActivityWorkItems=self._concurrency_options.maximum_concurrent_activity_work_items,
)
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,
work_item.orchestratorRequest,
stub,
work_item.completionToken,
)
elif work_item.HasField("activityRequest"):
self._async_worker_manager.submit_activity(
self._execute_activity,
work_item.activityRequest,
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: stubs.TaskHubSidecarServiceStub,
completionToken,
):
try:
executor = _OrchestrationExecutor(self._registry, self._logger)
result = executor.execute(req.instanceId, req.pastEvents, req.newEvents)
res = pb.OrchestratorResponse(
instanceId=req.instanceId,
actions=result.actions,
customStatus=ph.get_string_value(result.encoded_custom_status),
completionToken=completionToken,
)
except pe.AbandonOrchestrationError:
self._logger.info(
f"Abandoning orchestration. InstanceId = '{req.instanceId}'. Completion token = '{completionToken}'"
)
stub.AbandonTaskOrchestratorWorkItem(
pb.AbandonOrchestrationTaskRequest(
completionToken=completionToken
)
)
return
except Exception as ex:
self._logger.exception(
f"An error occurred while trying to execute instance '{req.instanceId}': {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=req.instanceId,
actions=actions,
completionToken=completionToken,
)
try:
stub.CompleteOrchestratorTask(res)
except Exception as ex:
self._logger.exception(
f"Failed to deliver orchestrator response for '{req.instanceId}' to sidecar: {ex}"
)
def _execute_activity(
self,
req: pb.ActivityRequest,
stub: stubs.TaskHubSidecarServiceStub,
completionToken,
):
instance_id = req.orchestrationInstance.instanceId
try:
executor = _ActivityExecutor(self._registry, self._logger)
result = executor.execute(
instance_id, req.name, req.taskId, req.input.value
)
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:
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}"
)
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] = {}
self._sequence_number = 0
self._current_utc_datetime = datetime(1000, 1, 1)
self._instance_id = instance_id
self._registry = registry
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
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):
if self._generator is None:
# This is never expected unless maybe there's an issue with the history
raise TypeError(
"The orchestrator generator is not initialized! Was the orchestration history corrupted?"
)
# We can resume the generator only if the previously yielded task
# has reached a completed state. The only time this won't be the
# case is if the user yielded on a WhenAll task and there are still
# outstanding child tasks that need to be completed.
while self._previous_task is not None and self._previous_task.is_complete:
next_task = None
if self._previous_task.is_failed:
# Raise the failure as an exception to the generator.
# The orchestrator can then either handle the exception or allow it to fail the orchestration.
next_task = self._generator.throw(self._previous_task.get_exception())
else:
# Resume the generator with the previous result.
# This will either return a Task or raise StopIteration if it's done.
next_task = self._generator.send(self._previous_task.get_result())
if not isinstance(next_task, task.Task):
raise TypeError("The orchestrator generator yielded a non-Task object")
self._previous_task = next_task
def set_complete(
self,
result: Any,
status: pb.OrchestrationStatus,
is_result_encoded: bool = False,
):
if self._is_complete:
return
self._is_complete = True
self._completion_status = status
self._pending_actions.clear() # Cancel any pending actions
self._result = result
result_json: Optional[str] = None
if result is not None:
result_json = result if is_result_encoded else shared.to_json(result)
action = ph.new_complete_orchestration_action(
self.next_sequence_number(), status, result_json
)
self._pending_actions[action.id] = action
def set_failed(self, ex: Union[Exception, pb.TaskFailureDetails]):
if self._is_complete:
return
self._is_complete = True
self._pending_actions.clear() # Cancel any pending actions
self._completion_status = pb.ORCHESTRATION_STATUS_FAILED
action = ph.new_complete_orchestration_action(
self.next_sequence_number(),
pb.ORCHESTRATION_STATUS_FAILED,
None,
ph.new_failure_details(ex) if isinstance(ex, Exception) else ex,
)
self._pending_actions[action.id] = action
def set_continued_as_new(self, new_input: Any, save_events: bool):
if self._is_complete:
return
self._is_complete = True
self._pending_actions.clear() # Cancel any pending actions
self._completion_status = pb.ORCHESTRATION_STATUS_CONTINUED_AS_NEW
self._new_input = new_input
self._save_events = save_events
def get_actions(self) -> list[pb.OrchestratorAction]:
if self._completion_status == pb.ORCHESTRATION_STATUS_CONTINUED_AS_NEW:
# When continuing-as-new, we only return a single completion action.
carryover_events: Optional[list[pb.HistoryEvent]] = None
if self._save_events:
carryover_events = []
# We need to save the current set of pending events so that they can be
# replayed when the new instance starts.
for event_name, values in self._received_events.items():
for event_value in values:
encoded_value = (
shared.to_json(event_value) if event_value else None
)
carryover_events.append(
ph.new_event_raised_event(event_name, encoded_value)
)
action = ph.new_complete_orchestration_action(
self.next_sequence_number(),
pb.ORCHESTRATION_STATUS_CONTINUED_AS_NEW,
result=shared.to_json(self._new_input)
if self._new_input is not None
else None,
failure_details=None,
carryover_events=carryover_events,
)
return [action]
else:
return list(self._pending_actions.values())
def next_sequence_number(self) -> int:
self._sequence_number += 1
return self._sequence_number
@property
def instance_id(self) -> str:
return self._instance_id
@property
def version(self) -> Optional[str]:
return self._version
@property
def current_utc_datetime(self) -> datetime:
return self._current_utc_datetime
@current_utc_datetime.setter
def current_utc_datetime(self, value: datetime):
self._current_utc_datetime = value
@property
def is_replaying(self) -> bool:
return self._is_replaying
def set_custom_status(self, custom_status: Any) -> None:
self._encoded_custom_status = (
shared.to_json(custom_status) if custom_status is not None else None
)
def create_timer(self, fire_at: Union[datetime, timedelta]) -> task.Task:
return self.create_timer_internal(fire_at)
def create_timer_internal(
self,
fire_at: Union[datetime, timedelta],
retryable_task: Optional[task.RetryableTask] = None,
) -> task.Task:
id = self.next_sequence_number()
if isinstance(fire_at, timedelta):
fire_at = self.current_utc_datetime + fire_at
action = ph.new_create_timer_action(id, fire_at)
self._pending_actions[id] = action
timer_task: task.TimerTask = task.TimerTask()
if retryable_task is not None:
timer_task.set_retryable_parent(retryable_task)
self._pending_tasks[id] = timer_task
return timer_task
def call_activity(
self,
activity: Union[task.Activity[TInput, TOutput], str],
*,
input: Optional[TInput] = None,
retry_policy: Optional[task.RetryPolicy] = None,
tags: Optional[dict[str, str]] = None,
) -> task.Task[TOutput]:
id = self.next_sequence_number()
self.call_activity_function_helper(
id, activity, input=input, retry_policy=retry_policy, is_sub_orch=False, tags=tags
)
return self._pending_tasks.get(id, task.CompletableTask())
def call_sub_orchestrator(
self,
orchestrator: task.Orchestrator[TInput, TOutput],
*,
input: Optional[TInput] = None,
instance_id: Optional[str] = None,
retry_policy: Optional[task.RetryPolicy] = None,
version: Optional[str] = None,
) -> task.Task[TOutput]:
id = self.next_sequence_number()
orchestrator_name = task.get_name(orchestrator)
default_version = self._registry.versioning.default_version if self._registry.versioning else None
orchestrator_version = version if version else default_version
self.call_activity_function_helper(
id,
orchestrator_name,
input=input,
retry_policy=retry_policy,
is_sub_orch=True,
instance_id=instance_id,
version=orchestrator_version
)
return self._pending_tasks.get(id, task.CompletableTask())
def call_activity_function_helper(
self,
id: Optional[int],
activity_function: Union[task.Activity[TInput, TOutput], str],
*,
input: Optional[TInput] = None,
retry_policy: Optional[task.RetryPolicy] = None,
tags: Optional[dict[str, str]] = None,
is_sub_orch: bool = False,
instance_id: Optional[str] = None,
fn_task: Optional[task.CompletableTask[TOutput]] = None,
version: Optional[str] = None,
):
if id is None:
id = self.next_sequence_number()
if fn_task is None:
encoded_input = shared.to_json(input) if input is not None else None
else:
# Here, we don't need to convert the input to JSON because it is already converted.
# We just need to take string representation of it.
encoded_input = str(input)
if not is_sub_orch:
name = (
activity_function
if isinstance(activity_function, str)
else task.get_name(activity_function)
)
action = ph.new_schedule_task_action(id, name, encoded_input, tags)
else:
if instance_id is None:
# Create a deteministic instance ID based on the parent instance ID
instance_id = f"{self.instance_id}:{id:04x}"
if not isinstance(activity_function, str):
raise ValueError("Orchestrator function name must be a string")
action = ph.new_create_sub_orchestration_action(
id, activity_function, instance_id, encoded_input, version
)
self._pending_actions[id] = action
if fn_task is None:
if retry_policy is None:
fn_task = task.CompletableTask[TOutput]()
else:
fn_task = task.RetryableTask[TOutput](
retry_policy=retry_policy,
action=action,
start_time=self.current_utc_datetime,
is_sub_orch=is_sub_orch,
)
self._pending_tasks[id] = fn_task
def wait_for_external_event(self, name: str) -> task.Task:
# Check to see if this event has already been received, in which case we
# can return it immediately. Otherwise, record out intent to receive an
# event with the given name so that we can resume the generator when it
# arrives. If there are multiple events with the same name, we return
# them in the order they were received.
external_event_task: task.CompletableTask = task.CompletableTask()
event_name = name.casefold()
event_list = self._received_events.get(event_name, None)
if event_list:
event_data = event_list.pop(0)
if not event_list:
del self._received_events[event_name]
external_event_task.complete(event_data)
else:
task_list = self._pending_events.get(event_name, None)
if not task_list:
task_list = []
self._pending_events[event_name] = task_list
task_list.append(external_event_task)
return external_event_task
def continue_as_new(self, new_input, *, save_events: bool = False) -> None:
if self._is_complete:
return
self.set_continued_as_new(new_input, save_events)
class ExecutionResults:
actions: list[pb.OrchestratorAction]
encoded_custom_status: Optional[str]
def __init__(
self, actions: list[pb.OrchestratorAction], encoded_custom_status: Optional[str]
):
self.actions = actions
self.encoded_custom_status = encoded_custom_status
class _OrchestrationExecutor:
_generator: Optional[task.Orchestrator] = None
def __init__(self, registry: _Registry, logger: logging.Logger):
self._registry = registry
self._logger = logger
self._is_suspended = False
self._suspended_events: list[pb.HistoryEvent] = []
def execute(
self,
instance_id: str,
old_events: Sequence[pb.HistoryEvent],
new_events: Sequence[pb.HistoryEvent],
) -> ExecutionResults:
if not new_events:
raise task.OrchestrationStateError(
"The new history event list must have at least one event in it."
)
ctx = _RuntimeOrchestrationContext(instance_id, self._registry)
version_failure = None
try:
# Rebuild local state by replaying old history into the orchestrator function
self._logger.debug(
f"{instance_id}: Rebuilding local state with {len(old_events)} history event..."
)
ctx._is_replaying = True
for old_event in old_events:
self.process_event(ctx, old_event)
# Process versioning if applicable
execution_started_events = [e.executionStarted for e in old_events if e.HasField("executionStarted")]
# We only check versioning if there are executionStarted events - otherwise, on the first replay when
# ctx.version will be Null, we may invalidate orchestrations early depending on the versioning strategy.
if self._registry.versioning and len(execution_started_events) > 0:
version_failure = self.evaluate_orchestration_versioning(
self._registry.versioning,
ctx.version
)
if version_failure:
self._logger.warning(
f"Orchestration version did not meet worker versioning requirements. "
f"Error action = '{self._registry.versioning.failure_strategy}'. "
f"Version error = '{version_failure}'"
)
raise pe.VersionFailureException
# Get new actions by executing newly received events into the orchestrator function