Repository navigation
Expand file tree
/
Copy pathgrpc_worker.go
More file actions
1547 lines (1442 loc) · 49.9 KB
/
Copy pathgrpc_worker.go
File metadata and controls
1547 lines (1442 loc) · 49.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
package client
import (
"context"
"errors"
"fmt"
"io"
"maps"
"math"
"math/rand/v2"
"runtime"
"slices"
"strings"
"sync"
"time"
"github.com/microsoft/durabletask-go/api"
"github.com/microsoft/durabletask-go/internal/helpers"
"github.com/microsoft/durabletask-go/internal/protos"
"github.com/microsoft/durabletask-go/task"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
)
var (
ErrTaskHubGrpcWorkerAlreadyRunning = errors.New("gRPC worker is already running")
errSilentDisconnect = errors.New("work item stream was silent beyond the configured timeout")
)
// maxWorkerConcurrency is the largest concurrency limit representable on the
// GetWorkItems wire contract, whose fields are 32-bit.
const maxWorkerConcurrency = math.MaxInt32
type workItemsStream interface {
Recv() (*protos.WorkItem, error)
}
type grpcWorkerClientFactory func(context.Context) (protos.TaskHubSidecarServiceClient, io.Closer, error)
// TaskHubGrpcWorkerConnectionFactory creates a gRPC connection for a worker
// stream generation. Each generation requests one intake connection and the
// configured completion budget. Every call must return a distinct connection
// and a distinct non-nil closer transferring ownership. Factories must honor cancellation;
// closers must return promptly.
type TaskHubGrpcWorkerConnectionFactory func(context.Context) (grpc.ClientConnInterface, io.Closer, error)
type TaskHubGrpcWorkerOption func(*taskHubGrpcWorkerOptions) error
type WorkerCapability = protos.WorkerCapability
const (
WorkerCapabilityHistoryStreaming WorkerCapability = protos.WorkerCapability_WORKER_CAPABILITY_HISTORY_STREAMING
WorkerCapabilityScheduledTasks WorkerCapability = protos.WorkerCapability_WORKER_CAPABILITY_SCHEDULED_TASKS
WorkerCapabilityLargePayloads WorkerCapability = protos.WorkerCapability_WORKER_CAPABILITY_LARGE_PAYLOADS
// DefaultMaxStreamedHistoryEvents and DefaultMaxStreamedHistoryBytes are
// the worker's default per-work-item replay-history safety bounds.
DefaultMaxStreamedHistoryEvents = api.DefaultHistoryMaxEvents
DefaultMaxStreamedHistoryBytes int64 = api.DefaultHistoryMaxBytes
// MaxStreamedHistoryEvents and MaxStreamedHistoryBytes bound configurable
// worker replay-history limits.
MaxStreamedHistoryEvents = api.MaxHistoryMaxEvents
MaxStreamedHistoryBytes int64 = api.MaxHistoryMaxBytes
// DefaultMaxOrchestratorCompletionBytes leaves headroom below the modern DTS
// orchestration-completion message limit.
DefaultMaxOrchestratorCompletionBytes = 4_089_446
minOrchestratorCompletionBytes = 64 * 1024
// DefaultWorkerCompletionConnections is the owned worker's completion budget,
// excluding its intake connection.
DefaultWorkerCompletionConnections = 3
)
type WorkItemFilter struct {
Name string
Versions []string
}
type WorkItemFilters struct {
Orchestrations []WorkItemFilter
Activities []WorkItemFilter
Entities []string
RejectAllOrchestrations bool
RejectAllActivities bool
RejectAllEntities bool
}
type taskHubGrpcWorkerOptions struct {
maxConcurrentOrchestrations int
maxConcurrentActivities int
maxConcurrentEntities int
completionConnections int
completionConnectionsConfigured bool
borrowedCompletionTransports []grpc.ClientConnInterface
helloTimeout time.Duration
silentDisconnectTimeout time.Duration
rpcTimeout time.Duration
reconnectBaseDelay time.Duration
reconnectMaxDelay time.Duration
transientRetryMaxAttempts int
transientRetryBaseDelay time.Duration
transientRetryMaxDelay time.Duration
maxStreamedHistoryEvents int
maxStreamedHistoryBytes int64
maxOrchestratorCompletionBytes int
maximumTimerInterval *time.Duration
taskExecutorOptions []task.TaskExecutorOption
versioning *task.VersioningOptions
capabilities []WorkerCapability
workItemFilters *WorkItemFilters
workItemFiltersConfigured bool
autoWorkItemFilters bool
largePayloads *api.LargePayloadOptions
converter api.DataConverter
unversionedOrchestrators map[string]struct{}
unversionedActivities map[string]struct{}
reconnectRandom randomInt64N
// waitFn overrides every delay the worker imposes on itself: reconnect
// backoff, transient RPC retry backoff, and work-item abandon delays. It is
// only set by tests so the deterministic delay schedule can be observed
// without sleeping.
waitFn func(context.Context, time.Duration) error
}
func defaultTaskHubGrpcWorkerOptions() taskHubGrpcWorkerOptions {
defaultConcurrency := 100 * runtime.GOMAXPROCS(0)
return taskHubGrpcWorkerOptions{
maxConcurrentOrchestrations: defaultConcurrency,
maxConcurrentActivities: defaultConcurrency,
maxConcurrentEntities: defaultConcurrency,
completionConnections: DefaultWorkerCompletionConnections,
helloTimeout: 30 * time.Second,
silentDisconnectTimeout: 2 * time.Minute,
rpcTimeout: 30 * time.Second,
reconnectBaseDelay: 200 * time.Millisecond,
reconnectMaxDelay: 15 * time.Second,
transientRetryMaxAttempts: 10,
transientRetryBaseDelay: 200 * time.Millisecond,
transientRetryMaxDelay: 15 * time.Second,
maxStreamedHistoryEvents: DefaultMaxStreamedHistoryEvents,
maxStreamedHistoryBytes: DefaultMaxStreamedHistoryBytes,
maxOrchestratorCompletionBytes: DefaultMaxOrchestratorCompletionBytes,
reconnectRandom: rand.Int64N,
capabilities: []WorkerCapability{WorkerCapabilityHistoryStreaming},
}
}
func WithMaxConcurrentOrchestrationWorkItems(n int) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
if err := validateWorkerConcurrency("orchestration", n); err != nil {
return err
}
options.maxConcurrentOrchestrations = n
return nil
}
}
func WithMaxConcurrentActivityWorkItems(n int) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
if err := validateWorkerConcurrency("activity", n); err != nil {
return err
}
options.maxConcurrentActivities = n
return nil
}
}
// WithMaxConcurrentEntityWorkItems limits concurrent entity batch execution.
func WithMaxConcurrentEntityWorkItems(n int) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
if err := validateWorkerConcurrency("entity", n); err != nil {
return err
}
options.maxConcurrentEntities = n
return nil
}
}
// WithWorkerCompletionConnections sets the dedicated completion/abandon budget
// per generation, excluding intake. The default is 3; valid values are 1 through
// 8. Isolation cannot be disabled. For a borrowed worker, an explicitly set
// budget must match the transports supplied by WithWorkerCompletionTransports.
func WithWorkerCompletionConnections(n int) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
if err := validateWorkerCompletionBudget(n); err != nil {
return err
}
options.completionConnections = n
options.completionConnectionsConfigured = true
return nil
}
}
// WithWorkerCompletionTransports supplies a borrowed worker's dedicated
// completion connections. They must be distinct from intake and one another,
// use equivalent authentication/worker metadata, and number between 1 and 8.
// The caller retains ownership and is responsible for readiness and recovery.
// This option is not valid with an owning connection factory.
func WithWorkerCompletionTransports(connections ...grpc.ClientConnInterface) TaskHubGrpcWorkerOption {
snapshot := slices.Clone(connections)
return func(options *taskHubGrpcWorkerOptions) error {
if err := validateWorkerCompletionBudget(len(snapshot)); err != nil {
return err
}
if err := validateWorkerCompletionTransports(nil, snapshot); err != nil {
return err
}
options.borrowedCompletionTransports = slices.Clone(snapshot)
return nil
}
}
// WithMaxStreamedHistoryEvents limits the number of history events retained
// while receiving a streamed orchestration history.
func WithMaxStreamedHistoryEvents(n int) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
if n <= 0 || n > MaxStreamedHistoryEvents {
return fmt.Errorf(
"maximum streamed history events must be between 1 and %d",
MaxStreamedHistoryEvents,
)
}
options.maxStreamedHistoryEvents = n
return nil
}
}
// WithMaxStreamedHistoryBytes limits the protobuf bytes retained while
// receiving a streamed orchestration history.
func WithMaxStreamedHistoryBytes(n int64) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
if n <= 0 || n > MaxStreamedHistoryBytes {
return fmt.Errorf(
"maximum streamed history bytes must be between 1 and %d",
MaxStreamedHistoryBytes,
)
}
options.maxStreamedHistoryBytes = n
return nil
}
}
// WithMaxOrchestratorCompletionBytes lowers the post-externalization response
// bound used before completing an orchestration work item. Multiple options are
// monotonic: a later option cannot raise an earlier transport-derived cap.
func WithMaxOrchestratorCompletionBytes(n int) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
if n < minOrchestratorCompletionBytes || n > DefaultMaxOrchestratorCompletionBytes {
return fmt.Errorf(
"maximum orchestrator completion bytes must be between %d and %d",
minOrchestratorCompletionBytes,
DefaultMaxOrchestratorCompletionBytes,
)
}
options.maxOrchestratorCompletionBytes = min(options.maxOrchestratorCompletionBytes, n)
return nil
}
}
// validateWorkerConcurrency rejects limits that cannot be advertised on the
// 32-bit GetWorkItems fields, which would otherwise silently wrap to a negative
// value on 64-bit platforms.
func validateWorkerConcurrency(kind string, n int) error {
if n <= 0 {
return fmt.Errorf("maximum concurrent %s work items must be greater than zero", kind)
}
if n > maxWorkerConcurrency {
return fmt.Errorf(
"maximum concurrent %s work items must be at most %d",
kind,
maxWorkerConcurrency,
)
}
return nil
}
func WithWorkerHelloTimeout(timeout time.Duration) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
if timeout <= 0 {
return fmt.Errorf("worker Hello timeout must be greater than zero")
}
options.helloTimeout = timeout
return nil
}
}
func WithWorkerSilentDisconnectTimeout(timeout time.Duration) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
if timeout <= 0 {
return fmt.Errorf("worker silent disconnect timeout must be greater than zero")
}
options.silentDisconnectTimeout = timeout
return nil
}
}
func WithWorkerRPCTimeout(timeout time.Duration) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
if timeout <= 0 {
return fmt.Errorf("worker RPC timeout must be greater than zero")
}
options.rpcTimeout = timeout
return nil
}
}
// WithWorkerReconnectBackoff configures the reconnect schedule. Nominal delays
// double from baseDelay, receive ±25% jitter, and remain within
// [baseDelay, maxDelay].
func WithWorkerReconnectBackoff(baseDelay, maxDelay time.Duration) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
if baseDelay <= 0 || maxDelay < baseDelay {
return fmt.Errorf("worker reconnect delays must be positive and max delay must be at least the base delay")
}
options.reconnectBaseDelay = baseDelay
options.reconnectMaxDelay = maxDelay
return nil
}
}
// WithWorkerTransientRetryPolicy configures the deterministic retry schedule for
// completion and abandon RPCs. Delays double from baseDelay and are always
// within [baseDelay, maxDelay].
func WithWorkerTransientRetryPolicy(maxAttempts int, baseDelay, maxDelay time.Duration) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
if maxAttempts <= 0 {
return fmt.Errorf("worker transient retry attempts must be greater than zero")
}
if baseDelay <= 0 || maxDelay < baseDelay {
return fmt.Errorf("worker transient retry delays must be positive and max delay must be at least the base delay")
}
options.transientRetryMaxAttempts = maxAttempts
options.transientRetryBaseDelay = baseDelay
options.transientRetryMaxDelay = maxDelay
return nil
}
}
// WithMaximumTimerInterval configures deterministic splitting of long durable
// timers. Changing this value is replay-breaking for affected in-flight
// orchestrations.
func WithMaximumTimerInterval(interval time.Duration) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
if interval < 0 {
return fmt.Errorf("maximum timer interval cannot be negative")
}
if interval == 0 {
interval = task.DefaultMaximumTimerInterval
}
options.maximumTimerInterval = &interval
return nil
}
}
// WithTaskExecutorOptions configures the task executor used by the gRPC worker.
// This allows task options such as task.WithVersioning to participate in DTS dispatch.
func WithTaskExecutorOptions(options ...task.TaskExecutorOption) TaskHubGrpcWorkerOption {
return func(workerOptions *taskHubGrpcWorkerOptions) error {
for _, option := range options {
if option == nil {
return errors.New("task executor option cannot be nil")
}
}
workerOptions.taskExecutorOptions = append(workerOptions.taskExecutorOptions, options...)
return nil
}
}
// WithTaskVersioning configures worker version acceptance and the default
// version used for sub-orchestrations.
func WithTaskVersioning(versioning task.VersioningOptions) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
if err := versioning.Validate(); err != nil {
return err
}
options.versioning = &versioning
return nil
}
}
// WithWorkerCapabilities explicitly configures the capabilities advertised to DTS.
func WithWorkerCapabilities(capabilities ...WorkerCapability) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
seen := make(map[WorkerCapability]struct{}, len(capabilities))
configured := make([]WorkerCapability, 0, len(capabilities))
for _, capability := range capabilities {
switch capability {
case WorkerCapabilityHistoryStreaming, WorkerCapabilityScheduledTasks, WorkerCapabilityLargePayloads:
default:
return fmt.Errorf("unsupported worker capability: %d", capability)
}
if _, ok := seen[capability]; ok {
continue
}
seen[capability] = struct{}{}
configured = append(configured, capability)
}
options.capabilities = configured
return nil
}
}
// WithScheduledTaskCapability controls scheduled-task capability advertisement.
func WithScheduledTaskCapability(enabled bool) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
options.capabilities = setWorkerCapability(options.capabilities, WorkerCapabilityScheduledTasks, enabled)
return nil
}
}
// CombineTaskHubGrpcWorkerOptions combines worker options into one option.
func CombineTaskHubGrpcWorkerOptions(options ...TaskHubGrpcWorkerOption) TaskHubGrpcWorkerOption {
return func(target *taskHubGrpcWorkerOptions) error {
for _, configure := range options {
if configure == nil {
continue
}
if err := configure(target); err != nil {
return err
}
}
return nil
}
}
// WithUnversionedOrchestratorNames allows explicitly unversioned system
// orchestrators to remain routable when strict worker versioning is enabled.
func WithUnversionedOrchestratorNames(names ...string) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
return addUnversionedTaskNames(&options.unversionedOrchestrators, "orchestrator", names)
}
}
// WithUnversionedActivityNames allows explicitly unversioned system activities
// to remain routable when strict worker versioning is enabled. System
// orchestrations run unversioned and an activity inherits its caller's version,
// so a system component's activities must be advertised unversioned too.
func WithUnversionedActivityNames(names ...string) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
return addUnversionedTaskNames(&options.unversionedActivities, "activity", names)
}
}
func addUnversionedTaskNames(
allowed *map[string]struct{},
kind string,
names []string,
) error {
if *allowed == nil {
*allowed = make(map[string]struct{}, len(names))
}
for _, name := range names {
name = strings.TrimSpace(name)
if name == "" {
return fmt.Errorf("unversioned %s name cannot be empty", kind)
}
(*allowed)[strings.ToLower(name)] = struct{}{}
}
return nil
}
// WithWorkItemFilters restricts orchestration/activity names and versions and entity names accepted by the worker.
// A nil per-kind list means no restriction for that kind. RejectAll* explicitly rejects a kind.
func WithWorkItemFilters(filters *WorkItemFilters) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
options.workItemFiltersConfigured = true
if filters == nil {
options.workItemFilters = nil
return nil
}
clone, err := cloneWorkItemFilters(filters)
if err != nil {
return err
}
options.workItemFilters = clone
return nil
}
}
// WithAutoWorkItemFilters derives task-name and task-version filters from the registry.
// Explicit [WithWorkItemFilters] configuration takes precedence.
func WithAutoWorkItemFilters() TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
options.autoWorkItemFilters = true
return nil
}
}
// WithWorkerLargePayloads configures worker payload hydration/externalization and advertises support.
func WithWorkerLargePayloads(options *api.LargePayloadOptions) TaskHubGrpcWorkerOption {
return func(workerOptions *taskHubGrpcWorkerOptions) error {
normalized, err := api.NormalizeLargePayloadOptions(options)
if err != nil {
return err
}
workerOptions.largePayloads = normalized
workerOptions.capabilities = setWorkerCapability(
workerOptions.capabilities,
WorkerCapabilityLargePayloads,
normalized != nil,
)
return nil
}
}
// WithWorkerDataConverter configures application payload serialization.
func WithWorkerDataConverter(converter api.DataConverter) TaskHubGrpcWorkerOption {
return func(options *taskHubGrpcWorkerOptions) error {
options.converter = api.NormalizeDataConverter(converter)
return nil
}
}
// TaskHubGrpcWorker executes orchestration, activity, and entity work received from a
// DTS gRPC work-item stream (named TaskHubSidecarService in the wire contract).
type TaskHubGrpcWorker struct {
clientFactory grpcWorkerClientFactory
executor task.Executor
logger api.Logger
options taskHubGrpcWorkerOptions
mu sync.Mutex
run *grpcWorkerRun
lastErr error
}
type grpcWorkerRun struct {
intakeCtx context.Context
cancelIntake context.CancelFunc
processingCtx context.Context
cancelProcessing context.CancelFunc
done chan struct{}
orchestrationSlots chan struct{}
activitySlots chan struct{}
entitySlots chan struct{}
pending sync.WaitGroup
retired sync.WaitGroup
err error
}
type grpcWorkerConnection struct {
client protos.TaskHubSidecarServiceClient
stream workItemsStream
cancelStream context.CancelFunc
closer io.Closer
pendingMu sync.Mutex
pendingChanged *sync.Cond
pendingWorkItems int
intakeClosed bool
}
func (c *grpcWorkerConnection) registerWorkItem(run *grpcWorkerRun) bool {
c.pendingMu.Lock()
defer c.pendingMu.Unlock()
if c.intakeClosed {
return false
}
c.pendingWorkItems++
run.pending.Add(1)
return true
}
func (c *grpcWorkerConnection) finishWorkItem(run *grpcWorkerRun) {
c.pendingMu.Lock()
c.pendingWorkItems--
if c.pendingWorkItems == 0 && c.pendingChanged != nil {
c.pendingChanged.Broadcast()
}
c.pendingMu.Unlock()
run.pending.Done()
}
func (c *grpcWorkerConnection) waitForWorkItemsLocked() {
if c.pendingWorkItems > 0 && c.pendingChanged == nil {
c.pendingChanged = sync.NewCond(&c.pendingMu)
}
for c.pendingWorkItems > 0 {
c.pendingChanged.Wait()
}
}
func (c *grpcWorkerConnection) waitForWorkItems() {
c.pendingMu.Lock()
defer c.pendingMu.Unlock()
c.waitForWorkItemsLocked()
}
func (c *grpcWorkerConnection) stopIntake() {
c.pendingMu.Lock()
defer c.pendingMu.Unlock()
c.waitForWorkItemsLocked()
c.intakeClosed = true
c.cancelStream()
}
// NewTaskHubGrpcWorker borrows intake and requires separate caller-owned
// completion connections supplied by WithWorkerCompletionTransports.
//
// The worker never closes or replaces the supplied connections: reconnect only
// recreates the stream on the same intake. Recovery is limited to what the
// caller's connections can do on their own. A connection that
// is permanently wedged (for example one whose credentials expired, or one whose
// endpoint moved) keeps producing poisoned streams and the worker keeps retrying
// on the escalating reconnect schedule without ever obtaining a fresh channel.
// Use [NewTaskHubGrpcWorkerWithConnectionFactory], or the Durable Task Scheduler
// NewWorker, when the worker should own and recreate its channels.
func NewTaskHubGrpcWorker(
cc grpc.ClientConnInterface,
registry *task.TaskRegistry,
logger api.Logger,
opts ...TaskHubGrpcWorkerOption,
) (*TaskHubGrpcWorker, error) {
if isNilWorkerTransport(cc) {
return nil, fmt.Errorf("gRPC connection is required")
}
var completions []grpc.ClientConnInterface
worker, err := newTaskHubGrpcWorker(
func(context.Context) (protos.TaskHubSidecarServiceClient, io.Closer, error) {
group := &workerCompletionTransport{intake: cc, completions: completions}
return protos.NewTaskHubSidecarServiceClient(group), nil, nil
},
registry,
logger,
opts...,
)
if err != nil {
return nil, err
}
completions = worker.options.borrowedCompletionTransports
if len(completions) == 0 {
return nil, fmt.Errorf("borrowed workers require separate connections via WithWorkerCompletionTransports")
}
if err := validateWorkerCompletionTransports(cc, completions); err != nil {
return nil, err
}
if worker.options.completionConnectionsConfigured && worker.options.completionConnections != len(completions) {
return nil, fmt.Errorf("worker completion budget must match the number of borrowed completion transports")
}
worker.options.completionConnections = len(completions)
return worker, nil
}
// NewTaskHubGrpcWorkerWithConnectionFactory creates a worker whose connection
// can be recreated after disconnects. Each returned closer is called only after
// all work dispatched through that connection has completed or been abandoned.
func NewTaskHubGrpcWorkerWithConnectionFactory(
factory TaskHubGrpcWorkerConnectionFactory,
registry *task.TaskRegistry,
logger api.Logger,
opts ...TaskHubGrpcWorkerOption,
) (*TaskHubGrpcWorker, error) {
if factory == nil {
return nil, fmt.Errorf("gRPC worker connection factory is required")
}
var worker *TaskHubGrpcWorker
var err error
worker, err = newTaskHubGrpcWorker(
func(ctx context.Context) (protos.TaskHubSidecarServiceClient, io.Closer, error) {
ctx, cancel := context.WithTimeout(ctx, worker.options.helloTimeout)
defer cancel()
group, err := newWorkerCompletionTransport(ctx, factory, worker.options.completionConnections)
if err != nil {
return nil, nil, err
}
return protos.NewTaskHubSidecarServiceClient(group), group, nil
},
registry,
logger,
opts...,
)
if err != nil {
return nil, err
}
if len(worker.options.borrowedCompletionTransports) != 0 {
return nil, fmt.Errorf("owning worker factories cannot use WithWorkerCompletionTransports")
}
return worker, nil
}
func newTaskHubGrpcWorker(
factory grpcWorkerClientFactory,
registry *task.TaskRegistry,
logger api.Logger,
opts ...TaskHubGrpcWorkerOption,
) (*TaskHubGrpcWorker, error) {
if factory == nil {
return nil, fmt.Errorf("gRPC worker client factory is required")
}
if registry == nil {
return nil, fmt.Errorf("task registry is required")
}
if logger == nil {
logger = api.DefaultLogger()
}
options := defaultTaskHubGrpcWorkerOptions()
for _, configure := range opts {
if configure == nil {
continue
}
if err := configure(&options); err != nil {
return nil, err
}
}
hasLargePayloadCapability := slices.Contains(options.capabilities, WorkerCapabilityLargePayloads)
if hasLargePayloadCapability && options.largePayloads == nil {
return nil, fmt.Errorf("large-payload capability requires worker large-payload options")
}
if options.largePayloads != nil {
options.capabilities = setWorkerCapability(options.capabilities, WorkerCapabilityLargePayloads, true)
}
snapshot := registry.Snapshot()
if options.workItemFiltersConfigured && options.workItemFilters != nil {
if err := validateWorkItemFilters(options.workItemFilters, snapshot); err != nil {
return nil, err
}
}
if options.autoWorkItemFilters && !options.workItemFiltersConfigured {
if err := validateAutoFilters(snapshot, options.versioning); err != nil {
return nil, err
}
options.workItemFilters = workItemFiltersFromRegistry(
snapshot,
options.versioning,
options.unversionedOrchestrators,
options.unversionedActivities,
)
}
return &TaskHubGrpcWorker{
clientFactory: factory,
executor: task.NewTaskExecutor(registry, options.executorOptions()...),
logger: logger,
options: options,
}, nil
}
// executorOptions returns the canonical executor configuration. Dedicated
// worker options are appended last so they consistently override generic ones.
func (options taskHubGrpcWorkerOptions) executorOptions() []task.TaskExecutorOption {
executorOptions := slices.Clone(options.taskExecutorOptions)
if options.maximumTimerInterval != nil {
executorOptions = append(executorOptions, task.WithMaximumTimerInterval(*options.maximumTimerInterval))
}
if options.versioning != nil {
executorOptions = append(executorOptions, task.WithVersioning(*options.versioning))
}
if options.converter != nil {
executorOptions = append(executorOptions, task.WithDataConverter(options.converter))
}
if len(options.unversionedOrchestrators) > 0 {
executorOptions = append(
executorOptions,
task.WithUnversionedOrchestratorNames(slices.Collect(maps.Keys(options.unversionedOrchestrators))...),
)
}
if len(options.unversionedActivities) > 0 {
executorOptions = append(
executorOptions,
task.WithUnversionedActivityNames(slices.Collect(maps.Keys(options.unversionedActivities))...),
)
}
return executorOptions
}
func workItemFiltersFromRegistry(
snapshot task.TaskRegistrySnapshot,
versioning *task.VersioningOptions,
allowedUnversionedOrchestrators map[string]struct{},
allowedUnversionedActivities map[string]struct{},
) *WorkItemFilters {
entities := slices.Clone(snapshot.Entities)
if slices.Contains(entities, "*") {
entities = nil
}
orchestrations := taskRegistrationsToFilters(
snapshot.Orchestrators, versioning, allowedUnversionedOrchestrators)
activities := taskRegistrationsToFilters(
snapshot.Activities, versioning, allowedUnversionedActivities)
// Nil denotes a wildcard registration; an empty non-nil list admits no work.
return &WorkItemFilters{
Orchestrations: orchestrations,
Activities: activities,
Entities: entities,
RejectAllOrchestrations: orchestrations != nil && len(orchestrations) == 0,
RejectAllActivities: activities != nil && len(activities) == 0,
RejectAllEntities: len(snapshot.Entities) == 0,
}
}
func validateAutoFilters(
snapshot task.TaskRegistrySnapshot,
versioning *task.VersioningOptions,
) error {
if versioning == nil {
return nil
}
if versioning.MatchStrategy == task.VersionMatchCurrentOrOlder {
for _, registrations := range [][]task.TaskRegistration{snapshot.Orchestrators, snapshot.Activities} {
for _, registration := range registrations {
if registration.Name == "*" {
return fmt.Errorf("automatic current-or-older filters require named registrations; configure explicit work-item filters for wildcard handlers")
}
}
}
return nil
}
if versioning.MatchStrategy != task.VersionMatchStrict {
return nil
}
if err := validateStrictRegistrations("orchestrator", snapshot.Orchestrators, versioning.Version); err != nil {
return err
}
return validateStrictRegistrations("activity", snapshot.Activities, versioning.Version)
}
func validateStrictRegistrations(
kind string,
registrations []task.TaskRegistration,
version string,
) error {
type versions struct {
hasUnversioned bool
versioned map[string]struct{}
}
byName := make(map[string]*versions)
for _, registration := range registrations {
name := strings.ToLower(registration.Name)
group := byName[name]
if group == nil {
group = &versions{versioned: make(map[string]struct{})}
byName[name] = group
}
if registration.Version == "" {
group.hasUnversioned = true
} else {
group.versioned[strings.ToLower(registration.Version)] = struct{}{}
}
}
for name, group := range byName {
if len(group.versioned) == 0 && group.hasUnversioned {
continue
}
if _, ok := group.versioned[strings.ToLower(version)]; !ok {
return fmt.Errorf("%s %q has no registration for strict worker version %q", kind, name, version)
}
}
return nil
}
func validateWorkItemFilters(filters *WorkItemFilters, snapshot task.TaskRegistrySnapshot) error {
if err := validateTaskFilterNames("orchestration", filters.Orchestrations, snapshot.Orchestrators); err != nil {
return err
}
if err := validateTaskFilterNames("activity", filters.Activities, snapshot.Activities); err != nil {
return err
}
if len(snapshot.Entities) == 0 || slices.Contains(snapshot.Entities, "*") {
return nil
}
entityNames := make(map[string]struct{}, len(snapshot.Entities))
for _, name := range snapshot.Entities {
entityNames[helpers.ToLowerInvariant(name)] = struct{}{}
}
for _, name := range filters.Entities {
if _, ok := entityNames[helpers.ToLowerInvariant(name)]; !ok {
return fmt.Errorf("entity work-item filter %q is not registered", name)
}
}
return nil
}
func validateTaskFilterNames(
kind string,
filters []WorkItemFilter,
registrations []task.TaskRegistration,
) error {
if len(registrations) == 0 {
return nil
}
names := make(map[string]struct{}, len(registrations))
for _, registration := range registrations {
if registration.Name == "*" {
return nil
}
names[strings.ToLower(registration.Name)] = struct{}{}
}
for _, filter := range filters {
if _, ok := names[strings.ToLower(filter.Name)]; !ok {
return fmt.Errorf("%s work-item filter %q is not registered", kind, filter.Name)
}
}
return nil
}
func taskRegistrationsToFilters(
registrations []task.TaskRegistration,
versioning *task.VersioningOptions,
allowedUnversioned map[string]struct{},
) []WorkItemFilter {
type filterGroup struct {
name string
versions map[string]string
}
groups := make(map[string]*filterGroup)
for _, registration := range registrations {
if registration.Name == "*" {
return nil
}
normalizedName := strings.ToLower(registration.Name)
group := groups[normalizedName]
if group == nil {
group = &filterGroup{name: registration.Name, versions: make(map[string]string)}
groups[normalizedName] = group
}
group.versions[strings.ToLower(registration.Version)] = registration.Version
}
filters := make([]WorkItemFilter, 0, len(groups))
currentOrOlder := versioning != nil && versioning.MatchStrategy == task.VersionMatchCurrentOrOlder
for _, group := range groups {
if versioning != nil && versioning.MatchStrategy == task.VersionMatchStrict {
if _, allowed := allowedUnversioned[strings.ToLower(group.name)]; allowed {
if unversioned, ok := group.versions[""]; ok {
versions := []string{unversioned}
if _, registered := group.versions[strings.ToLower(versioning.Version)]; registered && versioning.Version != "" {
versions = append(versions, versioning.Version)
}
filters = append(filters, WorkItemFilter{
Name: group.name,
Versions: versions,
})
continue
}
}
filters = append(filters, WorkItemFilter{
Name: group.name,
Versions: []string{versioning.Version},
})
continue
}
versions := make([]string, 0, len(group.versions))
_, hasUnversioned := group.versions[""]
for normalized, version := range group.versions {
if normalized != "" && (!currentOrOlder || helpers.CompareTaskVersions(version, versioning.Version) <= 0) {
versions = append(versions, version)
}
}
if currentOrOlder && hasUnversioned && len(group.versions) == 1 {
for _, version := range []string{versioning.Version, versioning.DefaultVersion} {
if version != "" && helpers.CompareTaskVersions(version, versioning.Version) <= 0 &&
!slices.ContainsFunc(versions, func(existing string) bool { return strings.EqualFold(existing, version) }) {
versions = append(versions, version)
}
}
}
slices.SortFunc(versions, func(left, right string) int {
return strings.Compare(strings.ToLower(left), strings.ToLower(right))
})
if hasUnversioned && (len(versions) > 0 || currentOrOlder) {
versions = append([]string{""}, versions...)
}
if currentOrOlder && len(versions) == 0 {
continue
}
filters = append(filters, WorkItemFilter{Name: group.name, Versions: versions})
}
slices.SortFunc(filters, func(left, right WorkItemFilter) int {
return strings.Compare(strings.ToLower(left.Name), strings.ToLower(right.Name))
})
return filters
}
// Start connects to the service, performs the Hello handshake, and starts the
// worker in the background.
func (w *TaskHubGrpcWorker) Start(ctx context.Context) error {
run, connection, err := w.begin(ctx)
if err != nil {
return err
}
go w.execute(run, connection)
return nil
}
// Run connects to the service, performs the Hello handshake, and blocks until
// the worker stops.
func (w *TaskHubGrpcWorker) Run(ctx context.Context) error {
run, connection, err := w.begin(ctx)
if err != nil {
return err
}
w.execute(run, connection)
return run.err
}
// Shutdown stops new dispatch and keeps the lease-owning intake stream open
// until received work completes or is abandoned. If ctx expires,