-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathworker.py
More file actions
3778 lines (3380 loc) · 174 KB
/
Copy pathworker.py
File metadata and controls
3778 lines (3380 loc) · 174 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 itertools
import json
import logging
import os
import time
from collections.abc import Callable, Generator, Sequence
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from threading import Event, Lock, Thread
from types import GeneratorType
from enum import Enum
from typing import Any, TypeVar, cast, overload
import uuid
from packaging.version import InvalidVersion, parse
import grpc
from google.protobuf import empty_pb2
from durabletask.grpc_options import (
GrpcChannelOptions,
GrpcWorkerResiliencyOptions,
)
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
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
import durabletask.internal.type_discovery as type_discovery
from durabletask.internal.grpc_resiliency import (
FailureTracker,
get_full_jitter_delay_seconds,
is_worker_transport_failure,
)
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
from durabletask.serialization import DataConverter, JsonDataConverter
TInput = TypeVar("TInput")
TOutput = TypeVar("TOutput")
T = TypeVar("T")
DATETIME_STRING_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'
DEFAULT_MAXIMUM_TIMER_INTERVAL = timedelta(days=3)
_STREAM_CLOSED_SENTINEL = object()
_WorkItem = tuple[Callable[..., Any], Callable[..., Any], tuple[Any, ...], dict[str, Any]]
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: int | None = None,
maximum_concurrent_orchestration_work_items: int | None = None,
maximum_concurrent_entity_work_items: int | None = None,
maximum_thread_pool_workers: int | None = 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 _WorkItemStreamOutcome(Enum):
SHUTDOWN = "shutdown"
GRACEFUL_CLOSE_BEFORE_FIRST_MESSAGE = "graceful_close_before_first_message"
GRACEFUL_CLOSE_AFTER_MESSAGE = "graceful_close_after_message"
SILENT_DISCONNECT = "silent_disconnect"
@dataclass
class _TrackedChannelState:
channel: Any
ref_count: int = 0
close_when_released: bool = False
class _InFlightChannelTracker:
def __init__(self):
self._lock = Lock()
# Keyed on the channel itself; gRPC channels are hashable by identity
# and we keep a strong reference via _TrackedChannelState so reuse-after-
# GC isn't a concern. Using the channel directly (instead of ``id()``)
# makes the invariant local to this class rather than something a
# reader has to verify by tracing _TrackedChannelState lifetimes.
self._states: dict[Any, _TrackedChannelState] = {}
def acquire(self, channel: Any):
with self._lock:
state = self._states.get(channel)
if state is None:
state = _TrackedChannelState(channel=channel)
self._states[channel] = state
state.ref_count += 1
released = False
def release() -> None:
nonlocal released
if released:
return
released = True
channel_to_close = None
with self._lock:
state = self._states.get(channel)
if state is None:
return
state.ref_count -= 1
if state.ref_count == 0:
if state.close_when_released:
channel_to_close = state.channel
del self._states[channel]
if channel_to_close is not None:
self._close_channel(channel_to_close)
return release
def retire(self, channel: Any) -> None:
channel_to_close = None
with self._lock:
state = self._states.get(channel)
if state is None:
channel_to_close = channel
else:
state.close_when_released = True
if channel_to_close is not None:
self._close_channel(channel_to_close)
@staticmethod
def _close_channel(channel: Any) -> None:
try:
channel.close()
except Exception:
logging.debug("Ignoring channel close failure during worker cleanup.", exc_info=True)
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: str | None = None
default_version: str | None = None
match_strategy: VersionMatchStrategy | None = None
failure_strategy: VersionFailureStrategy | None = None
def __init__(self, version: str | None = None,
default_version: str | None = None,
match_strategy: VersionMatchStrategy | None = None,
failure_strategy: VersionFailureStrategy | None = 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
# Sentinel object used to distinguish "auto-generate filters" from "clear filters (None)".
_AUTO_GENERATE_FILTERS = object()
@dataclass(frozen=True)
class OrchestrationWorkItemFilter:
"""Specifies a filter for orchestration work items."""
name: str
"""The name of the orchestration to filter."""
versions: list[str] = field(default_factory=list[str])
"""Optional list of versions to filter."""
@dataclass(frozen=True)
class ActivityWorkItemFilter:
"""Specifies a filter for activity work items."""
name: str
"""The name of the activity to filter."""
versions: list[str] = field(default_factory=list[str])
"""Optional list of versions to filter."""
@dataclass(frozen=True)
class EntityWorkItemFilter:
"""Specifies a filter for entity work items.
The name is normalized to lowercase to match entity registration
and instance ID conventions.
"""
name: str
"""The name of the entity to filter."""
def __post_init__(self):
EntityInstanceId.validate_entity_name(self.name)
object.__setattr__(self, 'name', self.name.lower())
@dataclass(frozen=True)
class WorkItemFilters:
"""Work item filters for a Durable Task Worker.
These filters are passed to the backend and only work items matching the
filters will be processed by the worker. If no filters are provided, the
worker will process all work items.
By default, no filters are applied. Call
:meth:`TaskHubGrpcWorker.use_work_item_filters` to enable filtering.
"""
orchestrations: list[OrchestrationWorkItemFilter] = field(default_factory=list[OrchestrationWorkItemFilter])
"""List of orchestration filters."""
activities: list[ActivityWorkItemFilter] = field(default_factory=list[ActivityWorkItemFilter])
"""List of activity filters."""
entities: list[EntityWorkItemFilter] = field(default_factory=list[EntityWorkItemFilter])
"""List of entity filters."""
@classmethod
def _from_registry(cls, registry: '_Registry') -> 'WorkItemFilters':
"""Auto-generate work item filters from the task registry."""
versions: list[str] = []
v = registry.versioning
if v and v.match_strategy == VersionMatchStrategy.STRICT and v.version:
versions = [v.version]
orchestrations = [
OrchestrationWorkItemFilter(name=name, versions=list(versions))
for name in registry.orchestrators
]
activities = [
ActivityWorkItemFilter(name=name, versions=list(versions))
for name in registry.activities
]
entities = [
EntityWorkItemFilter(name=name)
for name in registry.entities
]
return cls(
orchestrations=orchestrations,
activities=activities,
entities=entities,
)
def _to_grpc(self) -> pb.WorkItemFilters:
"""Convert to a gRPC WorkItemFilters message."""
grpc_filters = pb.WorkItemFilters()
for f in self.orchestrations:
grpc_filters.orchestrations.append(
pb.OrchestrationFilter(name=f.name, versions=f.versions)
)
for f in self.activities:
grpc_filters.activities.append(
pb.ActivityFilter(name=f.name, versions=f.versions)
)
for f in self.entities:
grpc_filters.entities.append(
pb.EntityFilter(name=f.name)
)
return grpc_filters
class _Registry:
orchestrators: dict[str, task.Orchestrator[Any, Any]]
activities: dict[str, task.Activity[Any, Any]]
entities: dict[str, task.Entity[Any, Any]]
versioning: VersioningOptions | None = 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) -> task.Orchestrator[Any, Any] | None:
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) -> task.Activity[Any, Any] | None:
return self.activities.get(name)
def add_entity(self, fn: task.Entity[Any, Any], name: str | None = 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[Any, Any]) -> 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) -> task.Entity[Any, Any] | None:
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 (str | None, optional): The gRPC endpoint address of the backend service.
Defaults to the value from environment variables or localhost.
metadata (list[tuple[str, str]] | None, optional): gRPC metadata to include with
requests. Used for authentication and routing. Defaults to None.
log_handler (logging.Handler | None, optional): Custom logging handler for worker logs. Defaults to None.
log_formatter (logging.Formatter | None, optional): Custom log formatter.
Defaults to None.
secure_channel (bool, optional): Whether to use a secure gRPC channel (TLS).
Defaults to False.
channel (grpc.Channel | None, optional): Pre-configured gRPC channel to use.
If set, host address, secure_channel, interceptors, and channel_options
are ignored when creating connections.
interceptors (Sequence[shared.ClientInterceptor] | None, optional): Custom gRPC
interceptors to apply to the channel. Defaults to None.
channel_options (GrpcChannelOptions | None, optional): Extra low-level gRPC
channel configuration including retry/service config options.
resiliency_options (GrpcWorkerResiliencyOptions | None, optional): Worker-side
gRPC resiliency settings retained for reconnect handling.
concurrency_options (ConcurrencyOptions | None, optional): Configuration for
controlling worker concurrency limits. If None, default settings are used.
emit_trace_spans (bool, optional): Whether the worker emits Durable Task
lifecycle spans. Set to ``False`` when the host owns those spans; the
worker will still make inbound trace context current during user-code
execution. Defaults to ``True``.
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: Any | None = None
_interceptors: list[shared.ClientInterceptor] | None = None
def __init__(
self,
*,
host_address: str | None = None,
metadata: list[tuple[str, str]] | None = None,
log_handler: logging.Handler | None = None,
log_formatter: logging.Formatter | None = None,
channel: grpc.Channel | None = None,
secure_channel: bool = False,
interceptors: Sequence[shared.ClientInterceptor] | None = None,
channel_options: GrpcChannelOptions | None = None,
resiliency_options: GrpcWorkerResiliencyOptions | None = None,
concurrency_options: ConcurrencyOptions | None = None,
maximum_timer_interval: timedelta | None = DEFAULT_MAXIMUM_TIMER_INTERVAL,
payload_store: PayloadStore | None = None,
data_converter: DataConverter | None = None,
emit_trace_spans: bool = True,
):
self._registry = _Registry()
# Shared by every entity batch this worker processes so that reflected
# entity method signatures are computed once instead of per operation.
self._entity_method_cache = _EntityMethodSignatureCache()
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._channel = channel
self._data_converter = data_converter if data_converter is not None else JsonDataConverter()
# The SDK owns (and may recreate) the gRPC channel only when the caller
# did not provide one. Mirrors ``TaskHubGrpcClient._owns_channel`` so
# both files use the same name for the same concept.
self._owns_channel = channel is None
self._secure_channel = secure_channel
self._payload_store = payload_store
self._emit_trace_spans = emit_trace_spans
self._channel_options = channel_options
self._resiliency_options = (
resiliency_options
if resiliency_options is not None
else GrpcWorkerResiliencyOptions()
)
# 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)
self._maximum_timer_interval = maximum_timer_interval
self._work_item_filters: WorkItemFilters | None = None
self._auto_generate_work_item_filters: bool = False
self._runLoop: Thread | None = None
# Extra worker capabilities advertised to the backend in
# GetWorkItemsRequest (in addition to ones derived from worker state such
# as LARGE_PAYLOADS). A feature-enablement helper like
# TaskHubGrpcWorker.configure_scheduled_tasks registers its own here.
self._capabilities: set[int] = set()
@property
def concurrency_options(self) -> ConcurrencyOptions:
"""Get the current concurrency options for this worker."""
return self._concurrency_options
@property
def maximum_timer_interval(self) -> timedelta | None:
"""Get the configured maximum timer interval for long timer chunking."""
return self._maximum_timer_interval
@property
def emit_trace_spans(self) -> bool:
"""Return whether this worker emits Durable Task lifecycle spans."""
return self._emit_trace_spans
def __enter__(self) -> "TaskHubGrpcWorker":
return self
def __exit__(self, *args: object) -> None:
self.stop()
def _classify_stream_outcome(
self,
*,
saw_message: bool,
timed_out: bool,
) -> _WorkItemStreamOutcome:
if timed_out:
return _WorkItemStreamOutcome.SILENT_DISCONNECT
if saw_message:
return _WorkItemStreamOutcome.GRACEFUL_CLOSE_AFTER_MESSAGE
return _WorkItemStreamOutcome.GRACEFUL_CLOSE_BEFORE_FIRST_MESSAGE
def _should_count_worker_failure(
self,
status_code: grpc.StatusCode,
) -> bool:
return is_worker_transport_failure(status_code)
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[Any, Any]) -> 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[Any, Any], name: str | None = 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 add_capability(self, capability: int) -> None:
"""Advertise a worker capability to the backend in ``GetWorkItemsRequest``.
Most users do not call this directly; feature-enablement helpers such as
:meth:`TaskHubGrpcWorker.configure_scheduled_tasks` use it to advertise
the capabilities (``pb.WORKER_CAPABILITY_*``) their feature relies on.
"""
if self._is_running:
raise RuntimeError(
"Capabilities cannot be added while the worker is running."
)
self._capabilities.add(capability)
def configure_scheduled_tasks(self) -> None:
"""Enable scheduled tasks support on this worker.
Registers the schedule entity and operation orchestrator and advertises
the scheduled-tasks capability to the backend. Call this before starting
the worker. Schedules are then managed from the client via
:class:`durabletask.scheduled.ScheduledTaskClient`.
"""
if self._is_running:
raise RuntimeError(
"Scheduled tasks cannot be configured while the worker is running."
)
# Imported lazily to avoid a circular import: durabletask.scheduled
# imports from durabletask.worker.
from durabletask.scheduled.orchestrator import (
execute_schedule_operation_orchestrator,
)
from durabletask.scheduled.schedule_entity import ENTITY_NAME, Schedule
self.add_entity(Schedule, ENTITY_NAME)
self.add_orchestrator(execute_schedule_operation_orchestrator)
self.add_capability(pb.WORKER_CAPABILITY_SCHEDULED_TASKS)
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
@overload
def use_work_item_filters(self) -> None:
...
@overload
def use_work_item_filters(self, filters: WorkItemFilters) -> None:
...
@overload
def use_work_item_filters(self, filters: None) -> None:
...
def use_work_item_filters(
self,
filters: WorkItemFilters | None | object = _AUTO_GENERATE_FILTERS,
) -> None:
"""Configures work item filters for the worker.
Work item filters tell the backend which orchestrations, activities,
and entities this worker can handle. When enabled, only matching work
items are dispatched to this worker.
By default no filters are applied and the worker processes all work
items. Calling this method enables filtering.
Args:
filters: The filters to apply. If omitted (default), filters are
auto-generated from registered orchestrations, activities, and
entities at :meth:`start` time. Pass a :class:`WorkItemFilters`
instance to provide explicit filters. Pass ``None`` to clear
any previously configured filters.
"""
if self._is_running:
raise RuntimeError(
"Work item filters cannot be changed while the worker is running."
)
if filters is _AUTO_GENERATE_FILTERS:
self._auto_generate_work_item_filters = True
self._work_item_filters = None
elif filters is None:
self._auto_generate_work_item_filters = False
self._work_item_filters = None
elif isinstance(filters, WorkItemFilters):
self._auto_generate_work_item_filters = False
self._work_item_filters = filters
else:
raise TypeError(
"filters must be a WorkItemFilters instance, None, or omitted."
)
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.")
# Auto-generate work item filters from registry if opted in
if self._auto_generate_work_item_filters:
self._work_item_filters = WorkItemFilters._from_registry(self._registry) # pyright: ignore[reportPrivateUsage]
self._shutdown.clear()
def run_loop() -> None:
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) -> None:
self._async_worker_manager.prepare_for_run()
worker_task = asyncio.create_task(self._async_worker_manager.run())
current_channel: grpc.Channel | None = self._channel
current_stub: Any | None = None
current_reader_thread: Thread | None = None
conn_retry_count = 0
failure_tracker = FailureTracker(
threshold=self._resiliency_options.channel_recreate_failure_threshold,
)
in_flight_channel_tracker = _InFlightChannelTracker()
def get_reconnect_delay_seconds() -> float:
return get_full_jitter_delay_seconds(
conn_retry_count,
base_seconds=self._resiliency_options.reconnect_backoff_base_seconds,
cap_seconds=self._resiliency_options.reconnect_backoff_cap_seconds,
)
def create_fresh_connection() -> None:
nonlocal current_channel, current_stub, conn_retry_count
current_stub = None
try:
if current_channel is None:
current_channel = shared.get_grpc_channel(
self._host_address,
self._secure_channel,
self._interceptors,
channel_options=self._channel_options,
)
current_stub = stubs.TaskHubSidecarServiceStub(current_channel)
hello_timeout = self._resiliency_options.hello_timeout_seconds
current_stub.Hello(empty_pb2.Empty(), timeout=hello_timeout)
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_stub = None
raise
def wrap_with_release(
handler: Callable[..., Any],
release: Callable[[], None],
) -> Callable[..., Any]:
def wrapped(*args: Any, **kwargs: Any) -> Any:
try:
return handler(*args, **kwargs)
finally:
release()
return wrapped
def submit_work_item(
submit_func: Callable[..., None],
handler: Callable[..., Any],
cancellation_handler: Callable[..., Any],
request: Any,
stub: Any,
completion_token: Any,
channel: grpc.Channel,
) -> None:
release = in_flight_channel_tracker.acquire(channel)
try:
submit_func(
wrap_with_release(handler, release),
wrap_with_release(cancellation_handler, release),
request,
stub,
completion_token,
)
except Exception:
release()
raise
def invalidate_connection(
*,
recreate_channel: bool = False,
close_channel: bool = False,
):
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
if (
current_channel is not None
and self._owns_channel
and (recreate_channel or close_channel)
):
in_flight_channel_tracker.retire(current_channel)
current_channel = None
current_stub = None
def should_invalidate_connection(rpc_error: grpc.RpcError) -> bool:
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 as ex:
recreate_channel = False
if isinstance(ex, grpc.RpcError):
error_code = ex.code() # type: ignore
if self._should_count_worker_failure(error_code):
recreate_channel = (
failure_tracker.record_failure()
and self._owns_channel
)
invalidate_connection(recreate_channel=recreate_channel)
conn_retry_count += 1
delay = get_reconnect_delay_seconds()
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
assert current_channel is not None
stub = current_stub
channel = current_channel
capabilities: list[Any] = []
if self._payload_store is not None:
capabilities.append(pb.WORKER_CAPABILITY_LARGE_PAYLOADS)
capabilities.extend(sorted(self._capabilities))
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,
)
if self._work_item_filters is not None:
get_work_items_request.workItemFilters.CopyFrom(
self._work_item_filters._to_grpc() # pyright: ignore[reportPrivateUsage]
)
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[Any] = queue.Queue()
saw_message = False
def stream_reader() -> None:
try:
response_stream = self._response_stream
if response_stream is None:
work_item_queue.put(_STREAM_CLOSED_SENTINEL)
return
for work_item in response_stream:
work_item_queue.put(work_item)
work_item_queue.put(_STREAM_CLOSED_SENTINEL)
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()
queue_timeout = (
self._resiliency_options.silent_disconnect_timeout_seconds or None
)
stream_outcome = None
while not self._shutdown.is_set():
try:
work_item = await asyncio.wait_for(
loop.run_in_executor(None, work_item_queue.get),
timeout=queue_timeout,
)
except asyncio.TimeoutError:
work_item = None
stream_outcome = self._classify_stream_outcome(
saw_message=saw_message,
timed_out=True,
)
break
if work_item is _STREAM_CLOSED_SENTINEL:
stream_outcome = self._classify_stream_outcome(
saw_message=saw_message,
timed_out=False,
)
break
try:
if isinstance(work_item, Exception):
raise work_item
saw_message = True
request_type = work_item.WhichOneof("request")
self._logger.debug(f'Received "{request_type}" work item')
if work_item.HasField("healthPing"):
failure_tracker.record_success()
continue
failure_tracker.record_success()
if work_item.HasField("orchestratorRequest"):
submit_work_item(
self._async_worker_manager.submit_orchestration,
self._execute_orchestrator,
self._cancel_orchestrator,