-
Notifications
You must be signed in to change notification settings - Fork 325
Expand file tree
/
Copy pathTaskOrchestrationDispatcher.cs
More file actions
1506 lines (1335 loc) · 78.5 KB
/
TaskOrchestrationDispatcher.cs
File metadata and controls
1506 lines (1335 loc) · 78.5 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 Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
#nullable enable
namespace DurableTask.Core
{
using DurableTask.Core.Command;
using DurableTask.Core.Common;
using DurableTask.Core.Entities;
using DurableTask.Core.Exceptions;
using DurableTask.Core.History;
using DurableTask.Core.Logging;
using DurableTask.Core.Middleware;
using DurableTask.Core.Serializing;
using DurableTask.Core.Settings;
using DurableTask.Core.Tracing;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ActivityStatusCode = Tracing.ActivityStatusCode;
/// <summary>
/// Dispatcher for orchestrations to handle processing and renewing, completion of orchestration events
/// </summary>
public class TaskOrchestrationDispatcher
{
static readonly Task CompletedTask = Task.FromResult(0);
readonly INameVersionObjectManager<TaskOrchestration> objectManager;
readonly IOrchestrationService orchestrationService;
readonly WorkItemDispatcher<TaskOrchestrationWorkItem> dispatcher;
readonly DispatchMiddlewarePipeline dispatchPipeline;
readonly LogHelper logHelper;
ErrorPropagationMode errorPropagationMode;
readonly NonBlockingCountdownLock concurrentSessionLock;
readonly IEntityOrchestrationService? entityOrchestrationService;
readonly EntityBackendProperties? entityBackendProperties;
readonly TaskOrchestrationEntityParameters? entityParameters;
readonly VersioningSettings? versioningSettings;
readonly IExceptionPropertiesProvider? exceptionPropertiesProvider;
/// <summary>
/// Initializes a new instance of the <see cref="TaskOrchestrationDispatcher"/> class with an exception properties provider.
/// </summary>
/// <param name="orchestrationService">The orchestration service implementation</param>
/// <param name="objectManager">The object manager for orchestrations</param>
/// <param name="dispatchPipeline">The dispatch middleware pipeline</param>
/// <param name="logHelper">The log helper</param>
/// <param name="errorPropagationMode">The error propagation mode</param>
/// <param name="versioningSettings">The versioning settings</param>
/// <param name="exceptionPropertiesProvider">The exception properties provider for extracting custom properties from exceptions</param>
internal TaskOrchestrationDispatcher(
IOrchestrationService orchestrationService,
INameVersionObjectManager<TaskOrchestration> objectManager,
DispatchMiddlewarePipeline dispatchPipeline,
LogHelper logHelper,
ErrorPropagationMode errorPropagationMode,
VersioningSettings versioningSettings,
IExceptionPropertiesProvider? exceptionPropertiesProvider)
{
this.objectManager = objectManager ?? throw new ArgumentNullException(nameof(objectManager));
this.orchestrationService = orchestrationService ?? throw new ArgumentNullException(nameof(orchestrationService));
this.dispatchPipeline = dispatchPipeline ?? throw new ArgumentNullException(nameof(dispatchPipeline));
this.logHelper = logHelper ?? throw new ArgumentNullException(nameof(logHelper));
this.errorPropagationMode = errorPropagationMode;
this.entityOrchestrationService = orchestrationService as IEntityOrchestrationService;
this.entityBackendProperties = this.entityOrchestrationService?.EntityBackendProperties;
this.entityParameters = TaskOrchestrationEntityParameters.FromEntityBackendProperties(this.entityBackendProperties);
this.versioningSettings = versioningSettings;
this.exceptionPropertiesProvider = exceptionPropertiesProvider;
this.dispatcher = new WorkItemDispatcher<TaskOrchestrationWorkItem>(
"TaskOrchestrationDispatcher",
item => item == null ? string.Empty : item.InstanceId,
this.OnFetchWorkItemAsync,
this.OnProcessWorkItemSessionAsync)
{
GetDelayInSecondsAfterOnFetchException = orchestrationService.GetDelayInSecondsAfterOnFetchException,
GetDelayInSecondsAfterOnProcessException = orchestrationService.GetDelayInSecondsAfterOnProcessException,
SafeReleaseWorkItem = orchestrationService.ReleaseTaskOrchestrationWorkItemAsync,
AbortWorkItem = orchestrationService.AbandonTaskOrchestrationWorkItemAsync,
DispatcherCount = orchestrationService.TaskOrchestrationDispatcherCount,
MaxConcurrentWorkItems = orchestrationService.MaxConcurrentTaskOrchestrationWorkItems,
LogHelper = logHelper,
};
// To avoid starvation, we only allow half of all concurrently execution orchestrations to
// leverage extended sessions.
var maxConcurrentSessions = (int)Math.Ceiling(this.dispatcher.MaxConcurrentWorkItems / 2.0);
this.concurrentSessionLock = new NonBlockingCountdownLock(maxConcurrentSessions);
}
/// <summary>
/// Starts the dispatcher to start getting and processing orchestration events
/// </summary>
public async Task StartAsync()
{
await this.dispatcher.StartAsync();
}
/// <summary>
/// Stops the dispatcher to stop getting and processing orchestration events
/// </summary>
/// <param name="forced">Flag indicating whether to stop gracefully or immediately</param>
public async Task StopAsync(bool forced)
{
await this.dispatcher.StopAsync(forced);
}
/// <summary>
/// Gets or sets flag whether to include additional details in error messages
/// </summary>
public bool IncludeDetails { get; set; }
/// <summary>
/// Gets or sets flag whether to pass orchestration input parameters to sub orchestrations
/// </summary>
public bool IncludeParameters { get; set; }
/// <summary>
/// Gets or sets the flag for whether or not entities are enabled
/// </summary>
public bool EntitiesEnabled { get; set; }
/// <summary>
/// Method to get the next work item to process within supplied timeout
/// </summary>
/// <param name="receiveTimeout">The max timeout to wait</param>
/// <param name="cancellationToken">A cancellation token used to cancel a fetch operation.</param>
/// <returns>A new TaskOrchestrationWorkItem</returns>
protected Task<TaskOrchestrationWorkItem> OnFetchWorkItemAsync(TimeSpan receiveTimeout, CancellationToken cancellationToken)
{
if (this.entityBackendProperties?.UseSeparateQueueForEntityWorkItems == true)
{
// only orchestrations should be served by this dispatcher, so we call
// the method which returns work items for orchestrations only.
return this.entityOrchestrationService!.LockNextOrchestrationWorkItemAsync(receiveTimeout, cancellationToken);
}
else
{
// both entities and orchestrations are served by this dispatcher,
// so we call the method that may return work items for either.
return this.orchestrationService.LockNextTaskOrchestrationWorkItemAsync(receiveTimeout, cancellationToken);
}
}
/// <summary>
/// Ensures the first ExecutionStarted event in the batch (if any) appears at the beginning
/// of its executionID history.
/// If this is not already the case, we move the first ExecutionStarted event "backwards"
/// until it either reaches the beginning of the list or reaches a different, non-null, executionID.
///
/// Note that this method modifies its input in-place.
/// </summary>
/// <param name="batch">The batch of workitems to potentially re-order in-place</param>
void EnsureExecutionStartedIsFirst(IList<TaskMessage> batch)
{
// We look for *the first* instance of an ExecutionStarted event in the batch, if any.
int index = 0;
string previousExecutionId = "";
int targetPosition = 0; // new position of ExecutionStarted in case of a re-ordering
TaskMessage? executionStartedEvent = null;
foreach (TaskMessage message in batch)
{
// Keep track of orchestrator generation changes, maybe update target position
string executionId = message.OrchestrationInstance.ExecutionId;
if (previousExecutionId != executionId)
{
// We want to re-position the ExecutionStarted event after the "right-most"
// event with a non-null executionID that came before it.
// So, only update target position if the executionID changed
// and the previous executionId was not null.
if (previousExecutionId != null)
{
targetPosition = index;
}
previousExecutionId = executionId;
}
// Find the first ExecutionStarted event.
if (message.Event.EventType == EventType.ExecutionStarted)
{
// ParentInstance needs to be null to avoid re-ordering
// ContinueAsNew events
if ((message.Event is ExecutionStartedEvent eventData) &&
(eventData.ParentInstance == null))
{
executionStartedEvent = message;
}
// We only consider the first ExecutionStarted event in the
// list, so we always break.
break;
}
index++;
}
// If we found an ExecutionStartedEvent, we place it either
// (A) in the beginning or
// (B) after the "right-most" event with non-null executionID that came before it.
int executionStartedIndex = index;
if ((executionStartedEvent != null) && (executionStartedIndex != targetPosition))
{
batch.RemoveAt(executionStartedIndex);
batch.Insert(targetPosition, executionStartedEvent);
}
}
async Task OnProcessWorkItemSessionAsync(TaskOrchestrationWorkItem workItem)
{
// DTFx history replay expects that ExecutionStarted comes before other events.
// If this is not already the case, due to a race-condition, we re-order the
// messages to enforce this expectation.
EnsureExecutionStartedIsFirst(workItem.NewMessages);
try
{
if (workItem.Session == null)
{
// Legacy behavior
await this.OnProcessWorkItemAsync(workItem);
return;
}
var concurrencyLockAcquired = false;
var processCount = 0;
try
{
while (true)
{
// If the provider provided work items, execute them.
if (workItem.NewMessages?.Count > 0)
{
// We only need to acquire the lock on the first execution within the extended session
if (!concurrencyLockAcquired)
{
concurrencyLockAcquired = this.concurrentSessionLock.Acquire();
}
workItem.IsExtendedSession = concurrencyLockAcquired;
// Regardless of whether or not we acquired the concurrent session lock, we will make sure to execute this work item.
// If we failed to acquire it, we will end the extended session after this execution.
bool isCompletedOrInterrupted = await this.OnProcessWorkItemAsync(workItem);
if (isCompletedOrInterrupted)
{
break;
}
processCount++;
}
// If we failed to acquire the concurrent session lock, we will end the extended session after the execution of the first work item
if (processCount > 0 && !concurrencyLockAcquired)
{
TraceHelper.Trace(TraceEventType.Verbose, "OnProcessWorkItemSession-MaxOperations", "Failed to acquire concurrent session lock.");
break;
}
TraceHelper.Trace(TraceEventType.Verbose, "OnProcessWorkItemSession-StartFetch", "Starting fetch of existing session.");
Stopwatch timer = Stopwatch.StartNew();
// Wait for new messages to arrive for the session. This call is expected to block (asynchronously)
// until either new messages are available or until a provider-specific timeout has expired.
workItem.NewMessages = await workItem.Session.FetchNewOrchestrationMessagesAsync(workItem);
if (workItem.NewMessages == null)
{
break;
}
TraceHelper.Trace(
TraceEventType.Verbose,
"OnProcessWorkItemSession-EndFetch",
$"Fetched {workItem.NewMessages.Count} new message(s) after {timer.ElapsedMilliseconds} ms from existing session.");
workItem.OrchestrationRuntimeState.NewEvents.Clear();
}
}
finally
{
if (concurrencyLockAcquired)
{
TraceHelper.Trace(
TraceEventType.Verbose,
"OnProcessWorkItemSession-Release",
$"Releasing extended session after {processCount} batch(es).");
this.concurrentSessionLock.Release();
await workItem.Session.EndSessionAsync();
}
}
}
catch (SessionAbortedException e)
{
// Either the orchestration or the orchestration service explicitly abandoned the session.
OrchestrationInstance instance = workItem.OrchestrationRuntimeState?.OrchestrationInstance ?? new OrchestrationInstance { InstanceId = workItem.InstanceId };
this.logHelper.OrchestrationAborted(instance, e.Message);
TraceHelper.TraceInstance(TraceEventType.Warning, "TaskOrchestrationDispatcher-ExecutionAborted", instance, "{0}", e.Message);
await this.orchestrationService.AbandonTaskOrchestrationWorkItemAsync(workItem);
}
}
/// <summary>
/// Method to process a new work item
/// </summary>
/// <param name="workItem">The work item to process</param>
protected async Task<bool> OnProcessWorkItemAsync(TaskOrchestrationWorkItem workItem)
{
var messagesToSend = new List<TaskMessage>();
var timerMessages = new List<TaskMessage>();
var orchestratorMessages = new List<TaskMessage>();
var isCompleted = false;
var continuedAsNew = false;
var isInterrupted = false;
var isRewinding = false;
// correlation
CorrelationTraceClient.Propagate(() => CorrelationTraceContext.Current = workItem.TraceContext);
ExecutionStartedEvent? continueAsNewExecutionStarted = null;
TaskMessage? continuedAsNewMessage = null;
IList<HistoryEvent>? carryOverEvents = null;
string? carryOverStatus = null;
workItem.OrchestrationRuntimeState.LogHelper = this.logHelper;
OrchestrationRuntimeState runtimeState = workItem.OrchestrationRuntimeState;
runtimeState.AddEvent(new OrchestratorStartedEvent(-1));
OrchestrationRuntimeState originalOrchestrationRuntimeState = runtimeState;
// Distributed tracing support: each orchestration execution is a trace activity
// that derives from an established parent trace context. It is expected that some
// listener will receive these events and publish them to a distributed trace logger.
ExecutionStartedEvent startEvent =
runtimeState.ExecutionStartedEvent ??
workItem.NewMessages.Select(msg => msg.Event).OfType<ExecutionStartedEvent>().FirstOrDefault();
ExecutionRewoundEvent rewindEvent =
workItem.NewMessages.Select(msg => msg.Event).OfType<ExecutionRewoundEvent>().LastOrDefault();
if (rewindEvent is not null && runtimeState.OrchestrationStatus != OrchestrationStatus.Running)
{
isRewinding = true;
if (rewindEvent.ParentTraceContext != null)
{
startEvent.ParentTraceContext = rewindEvent.ParentTraceContext;
}
// We set these to null here so that a new Activity is created to represent the execution of the rewound orchestration.
startEvent.ParentTraceContext.SpanId = null;
startEvent.ParentTraceContext.Id = null;
startEvent.ParentTraceContext.ActivityStartTime = null;
}
Activity? traceActivity = TraceHelper.StartTraceActivityForOrchestrationExecution(startEvent);
OrchestrationState? instanceState = null;
Task? renewTask = null;
using var renewCancellationTokenSource = new CancellationTokenSource();
if (workItem.LockedUntilUtc < DateTime.MaxValue)
{
// start a task to run RenewUntil
renewTask = Task.Factory.StartNew(
() => RenewUntil(workItem, this.orchestrationService, this.logHelper, nameof(TaskOrchestrationDispatcher), renewCancellationTokenSource.Token),
renewCancellationTokenSource.Token);
}
try
{
// Assumes that: if the batch contains a new "ExecutionStarted" event, it is the first message in the batch.
if (!ReconcileMessagesWithState(workItem, nameof(TaskOrchestrationDispatcher), this.errorPropagationMode, logHelper))
{
// TODO : mark an orchestration as faulted if there is data corruption
this.logHelper.DroppingOrchestrationWorkItem(workItem, "Received work-item for an invalid orchestration");
TraceHelper.TraceSession(
TraceEventType.Error,
"TaskOrchestrationDispatcher-DeletedOrchestration",
runtimeState.OrchestrationInstance?.InstanceId!,
"Received work-item for an invalid orchestration");
isCompleted = true;
traceActivity?.Dispose();
}
else
{
do
{
continuedAsNew = false;
continuedAsNewMessage = null;
IReadOnlyList<OrchestratorAction> decisions = new List<OrchestratorAction>();
bool versioningFailed = false;
if (this.versioningSettings != null)
{
switch (this.versioningSettings.MatchStrategy)
{
case VersioningSettings.VersionMatchStrategy.None:
// No versioning, do nothing
break;
case VersioningSettings.VersionMatchStrategy.Strict:
versioningFailed = this.versioningSettings.Version != runtimeState.Version;
break;
case VersioningSettings.VersionMatchStrategy.CurrentOrOlder:
// Positive result indicates the orchestration version is higher than the versioning settings.
versioningFailed = VersioningSettings.CompareVersions(runtimeState.Version, this.versioningSettings.Version) > 0;
break;
}
if (versioningFailed)
{
if (this.versioningSettings.FailureStrategy == VersioningSettings.VersionFailureStrategy.Fail)
{
var failureAction = new OrchestrationCompleteOrchestratorAction
{
Id = runtimeState.PastEvents.Count,
FailureDetails = new FailureDetails("VersionMismatch", "Orchestration version did not comply with Worker Versioning", null, null, true),
OrchestrationStatus = OrchestrationStatus.Failed,
};
decisions = new List<OrchestratorAction> { failureAction };
}
else // Abandon work item in all other cases (will be retried later).
{
await this.orchestrationService.AbandonTaskOrchestrationWorkItemAsync(workItem);
return true;
}
}
}
this.logHelper.OrchestrationExecuting(runtimeState.OrchestrationInstance!, runtimeState.Name);
TraceHelper.TraceInstance(
TraceEventType.Verbose,
"TaskOrchestrationDispatcher-ExecuteUserOrchestration-Begin",
runtimeState.OrchestrationInstance!,
"Executing user orchestration: {0}",
JsonDataConverter.Default.Serialize(runtimeState.GetOrchestrationRuntimeStateDump(), true));
if (!versioningFailed)
{
// In this case we skip the orchestration's execution since all tasks have been completed and it is in a terminal state.
// Instead we "rewind" its execution by removing all failed tasks (see ProcessRewindOrchestrationDecision).
// Upon receiving the next work item for the rewound orchestration, the failed tasks will be re-executed.
if (isRewinding)
{
decisions = new List<OrchestratorAction> { new RewindOrchestrationAction() };
}
else
{
if (workItem.Cursor == null)
{
workItem.Cursor = await this.ExecuteOrchestrationAsync(runtimeState, workItem);
}
else
{
await this.ResumeOrchestrationAsync(workItem);
}
decisions = workItem.Cursor.LatestDecisions.ToList();
}
}
this.logHelper.OrchestrationExecuted(
runtimeState.OrchestrationInstance!,
runtimeState.Name,
decisions);
TraceHelper.TraceInstance(
TraceEventType.Information,
"TaskOrchestrationDispatcher-ExecuteUserOrchestration-End",
runtimeState.OrchestrationInstance!,
"Executed user orchestration. Received {0} orchestrator actions: {1}",
decisions.Count,
string.Join(", ", decisions.Select(d => d.Id + ":" + d.OrchestratorActionType)));
// TODO: Exception handling for invalid decisions, which is increasingly likely
// when custom middleware is involved (e.g. out-of-process scenarios).
foreach (OrchestratorAction decision in decisions)
{
TraceHelper.TraceInstance(
TraceEventType.Information,
"TaskOrchestrationDispatcher-ProcessOrchestratorAction",
runtimeState.OrchestrationInstance!,
"Processing orchestrator action of type {0}",
decision.OrchestratorActionType);
switch (decision.OrchestratorActionType)
{
case OrchestratorActionType.ScheduleOrchestrator:
var scheduleTaskAction = (ScheduleTaskOrchestratorAction)decision;
var message = this.ProcessScheduleTaskDecision(
scheduleTaskAction,
runtimeState,
this.IncludeParameters,
traceActivity);
messagesToSend.Add(message);
break;
case OrchestratorActionType.CreateTimer:
var timerOrchestratorAction = (CreateTimerOrchestratorAction)decision;
timerMessages.Add(this.ProcessCreateTimerDecision(
timerOrchestratorAction,
runtimeState,
isInternal: false));
break;
case OrchestratorActionType.CreateSubOrchestration:
var createSubOrchestrationAction = (CreateSubOrchestrationAction)decision;
orchestratorMessages.Add(
this.ProcessCreateSubOrchestrationInstanceDecision(
createSubOrchestrationAction,
runtimeState,
this.IncludeParameters,
traceActivity));
break;
case OrchestratorActionType.SendEvent:
var sendEventAction = (SendEventOrchestratorAction)decision;
orchestratorMessages.Add(
this.ProcessSendEventDecision(sendEventAction, runtimeState));
break;
case OrchestratorActionType.OrchestrationComplete:
OrchestrationCompleteOrchestratorAction completeDecision = (OrchestrationCompleteOrchestratorAction)decision;
TaskMessage? workflowInstanceCompletedMessage =
this.ProcessWorkflowCompletedTaskDecision(completeDecision, runtimeState, this.IncludeDetails, out continuedAsNew);
if (workflowInstanceCompletedMessage != null)
{
// Send complete message to parent workflow or to itself to start a new execution
// Store the event so we can rebuild the state
carryOverEvents = null;
if (continuedAsNew)
{
continuedAsNewMessage = workflowInstanceCompletedMessage;
continueAsNewExecutionStarted = workflowInstanceCompletedMessage.Event as ExecutionStartedEvent;
if (completeDecision.CarryoverEvents.Any())
{
carryOverEvents = completeDecision.CarryoverEvents.ToList();
completeDecision.CarryoverEvents.Clear();
}
}
else
{
orchestratorMessages.Add(workflowInstanceCompletedMessage);
}
}
isCompleted = !continuedAsNew;
break;
case OrchestratorActionType.RewindOrchestration:
this.ProcessRewindOrchestrationDecision(
runtimeState,
out List<TaskMessage> subOrchestrationRewindMessages,
out OrchestrationRuntimeState newRuntimeState);
orchestratorMessages.AddRange(subOrchestrationRewindMessages);
workItem.OrchestrationRuntimeState = newRuntimeState;
runtimeState = newRuntimeState;
break;
default:
throw TraceHelper.TraceExceptionInstance(
TraceEventType.Error,
"TaskOrchestrationDispatcher-UnsupportedDecisionType",
runtimeState.OrchestrationInstance!,
new NotSupportedException($"Decision type '{decision.OrchestratorActionType}' not supported"));
}
// Underlying orchestration service provider may have a limit of messages per call, to avoid the situation
// we keep on asking the provider if message count is ok and stop processing new decisions if not.
//
// We also put in a fake timer to force next orchestration task for remaining messages
int totalMessages = messagesToSend.Count + orchestratorMessages.Count + timerMessages.Count;
if (this.orchestrationService.IsMaxMessageCountExceeded(totalMessages, runtimeState))
{
TraceHelper.TraceInstance(
TraceEventType.Information,
"TaskOrchestrationDispatcher-MaxMessageCountReached",
runtimeState.OrchestrationInstance!,
"MaxMessageCount reached. Adding timer to process remaining events in next attempt.");
if (isCompleted || continuedAsNew)
{
TraceHelper.TraceInstance(
TraceEventType.Information,
"TaskOrchestrationDispatcher-OrchestrationAlreadyCompleted",
runtimeState.OrchestrationInstance!,
"Orchestration already completed. Skip adding timer for splitting messages.");
break;
}
var dummyTimer = new CreateTimerOrchestratorAction
{
Id = FrameworkConstants.FakeTimerIdToSplitDecision,
FireAt = DateTime.UtcNow
};
timerMessages.Add(this.ProcessCreateTimerDecision(
dummyTimer,
runtimeState,
isInternal: true));
isInterrupted = true;
break;
}
}
// correlation
CorrelationTraceClient.Propagate(() =>
{
if (runtimeState.ExecutionStartedEvent != null)
runtimeState.ExecutionStartedEvent.Correlation = CorrelationTraceContext.Current.SerializableTraceContext;
});
// finish up processing of the work item
if (!continuedAsNew && runtimeState.Events.Last().EventType != EventType.OrchestratorCompleted)
{
runtimeState.AddEvent(new OrchestratorCompletedEvent(-1));
}
if (isCompleted)
{
TraceHelper.TraceSession(TraceEventType.Information, "TaskOrchestrationDispatcher-DeletingSessionState", workItem.InstanceId, "Deleting session state");
if (runtimeState.ExecutionStartedEvent != null)
{
instanceState = Utils.BuildOrchestrationState(runtimeState);
}
}
else
{
if (continuedAsNew)
{
TraceHelper.TraceSession(
TraceEventType.Information,
"TaskOrchestrationDispatcher-UpdatingStateForContinuation",
workItem.InstanceId,
"Updating state for continuation");
// correlation
CorrelationTraceClient.Propagate(() =>
{
continueAsNewExecutionStarted!.Correlation = CorrelationTraceContext.Current.SerializableTraceContext;
});
// Copy the distributed trace context, if any
continueAsNewExecutionStarted!.SetParentTraceContext(runtimeState.ExecutionStartedEvent);
runtimeState = new OrchestrationRuntimeState();
runtimeState.AddEvent(new OrchestratorStartedEvent(-1));
runtimeState.AddEvent(continueAsNewExecutionStarted!);
runtimeState.Status = workItem.OrchestrationRuntimeState.Status ?? carryOverStatus;
carryOverStatus = workItem.OrchestrationRuntimeState.Status;
if (carryOverEvents != null)
{
foreach (var historyEvent in carryOverEvents)
{
runtimeState.AddEvent(historyEvent);
}
}
runtimeState.AddEvent(new OrchestratorCompletedEvent(-1));
workItem.OrchestrationRuntimeState = runtimeState;
workItem.Cursor = null;
}
instanceState = Utils.BuildOrchestrationState(runtimeState);
}
} while (continuedAsNew);
}
}
finally
{
if (renewTask != null)
{
try
{
renewCancellationTokenSource.Cancel();
await renewTask;
}
catch (ObjectDisposedException)
{
// ignore
}
catch (OperationCanceledException)
{
// ignore
}
}
}
if (workItem.RestoreOriginalRuntimeStateDuringCompletion)
{
// some backends expect the original runtime state object
workItem.OrchestrationRuntimeState = originalOrchestrationRuntimeState;
}
runtimeState.Status = runtimeState.Status ?? carryOverStatus;
if (instanceState != null)
{
instanceState.Status = runtimeState.Status;
}
await this.orchestrationService.CompleteTaskOrchestrationWorkItemAsync(
workItem,
runtimeState,
continuedAsNew ? null : messagesToSend,
orchestratorMessages,
continuedAsNew ? null : timerMessages,
continuedAsNewMessage,
instanceState);
if (workItem.RestoreOriginalRuntimeStateDuringCompletion)
{
workItem.OrchestrationRuntimeState = runtimeState;
}
return isCompleted || continuedAsNew || isInterrupted || isRewinding;
}
static OrchestrationExecutionContext GetOrchestrationExecutionContext(OrchestrationRuntimeState runtimeState)
{
return new OrchestrationExecutionContext { OrchestrationTags = runtimeState.Tags ?? new Dictionary<string, string>(capacity: 0) };
}
static TimeSpan MinRenewalInterval = TimeSpan.FromSeconds(5); // prevents excessive retries if clocks are off
static TimeSpan MaxRenewalInterval = TimeSpan.FromSeconds(30);
internal static async Task RenewUntil(TaskOrchestrationWorkItem workItem, IOrchestrationService orchestrationService, LogHelper logHelper, string dispatcher, CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
TimeSpan delay = workItem.LockedUntilUtc - DateTime.UtcNow - TimeSpan.FromSeconds(30);
if (delay < MinRenewalInterval)
{
delay = MinRenewalInterval;
}
else if (delay > MaxRenewalInterval)
{
delay = MaxRenewalInterval;
}
await Utils.DelayWithCancellation(delay, cancellationToken);
if (cancellationToken.IsCancellationRequested)
{
return;
}
try
{
logHelper.RenewOrchestrationWorkItemStarting(workItem);
TraceHelper.Trace(TraceEventType.Information, $"{dispatcher}-RenewWorkItemStarting", "Renewing work item for instance {0}", workItem.InstanceId);
await orchestrationService.RenewTaskOrchestrationWorkItemLockAsync(workItem);
logHelper.RenewOrchestrationWorkItemCompleted(workItem);
TraceHelper.Trace(TraceEventType.Information, $"{dispatcher}-RenewWorkItemCompleted", "Successfully renewed work item for instance {0}", workItem.InstanceId);
}
catch (Exception exception) when (!Utils.IsFatal(exception))
{
logHelper.RenewOrchestrationWorkItemFailed(workItem, exception);
TraceHelper.TraceException(TraceEventType.Warning, $"{dispatcher}-RenewWorkItemFailed", exception, "Failed to renew work item for instance {0}", workItem.InstanceId);
}
}
}
async Task<OrchestrationExecutionCursor> ExecuteOrchestrationAsync(OrchestrationRuntimeState runtimeState, TaskOrchestrationWorkItem workItem)
{
// Get the TaskOrchestration implementation. If it's not found, it either means that the developer never
// registered it (which is an error, and we'll throw for this further down) or it could be that some custom
// middleware (e.g. out-of-process execution middleware) is intended to implement the orchestration logic.
TaskOrchestration? taskOrchestration = this.objectManager.GetObject(runtimeState.Name, runtimeState.Version!);
var dispatchContext = new DispatchMiddlewareContext();
dispatchContext.SetProperty(runtimeState.OrchestrationInstance);
dispatchContext.SetProperty(taskOrchestration);
dispatchContext.SetProperty(runtimeState);
dispatchContext.SetProperty(workItem);
dispatchContext.SetProperty(GetOrchestrationExecutionContext(runtimeState));
dispatchContext.SetProperty(this.entityParameters);
dispatchContext.SetProperty(new WorkItemMetadata(workItem.IsExtendedSession, includeState: true));
TaskOrchestrationExecutor? executor = null;
await this.dispatchPipeline.RunAsync(dispatchContext, _ =>
{
// Check to see if the custom middleware intercepted and substituted the orchestration execution
// with its own execution behavior, providing us with the end results. If so, we can terminate
// the dispatch pipeline here.
var resultFromMiddleware = dispatchContext.GetProperty<OrchestratorExecutionResult>();
if (resultFromMiddleware != null)
{
return CompletedTask;
}
if (taskOrchestration == null)
{
throw TraceHelper.TraceExceptionInstance(
TraceEventType.Error,
"TaskOrchestrationDispatcher-TypeMissing",
runtimeState.OrchestrationInstance!,
new TypeMissingException($"Orchestration not found: ({runtimeState.Name}, {runtimeState.Version})"));
}
executor = new TaskOrchestrationExecutor(
runtimeState,
taskOrchestration,
this.orchestrationService.EventBehaviourForContinueAsNew,
this.entityParameters,
this.errorPropagationMode,
this.exceptionPropertiesProvider);
OrchestratorExecutionResult resultFromOrchestrator = executor.Execute();
dispatchContext.SetProperty(resultFromOrchestrator);
return CompletedTask;
});
var result = dispatchContext.GetProperty<OrchestratorExecutionResult>();
IEnumerable<OrchestratorAction> decisions = result?.Actions ?? Enumerable.Empty<OrchestratorAction>();
runtimeState.Status = result?.CustomStatus;
return new OrchestrationExecutionCursor(runtimeState, taskOrchestration, executor, decisions);
}
async Task ResumeOrchestrationAsync(TaskOrchestrationWorkItem workItem)
{
OrchestrationExecutionCursor cursor = workItem.Cursor;
var dispatchContext = new DispatchMiddlewareContext();
dispatchContext.SetProperty(cursor.RuntimeState.OrchestrationInstance);
dispatchContext.SetProperty(cursor.TaskOrchestration);
dispatchContext.SetProperty(cursor.RuntimeState);
dispatchContext.SetProperty(workItem);
dispatchContext.SetProperty(new WorkItemMetadata(isExtendedSession: true, includeState: false));
cursor.LatestDecisions = Enumerable.Empty<OrchestratorAction>();
await this.dispatchPipeline.RunAsync(dispatchContext, _ =>
{
// Check to see if the custom middleware intercepted and substituted the orchestration execution
// with its own execution behavior, providing us with the end results. If so, we can terminate
// the dispatch pipeline here.
var resultFromMiddleware = dispatchContext.GetProperty<OrchestratorExecutionResult>();
if (resultFromMiddleware != null)
{
return CompletedTask;
}
OrchestratorExecutionResult resultFromOrchestrator = cursor.OrchestrationExecutor.ExecuteNewEvents();
dispatchContext.SetProperty(resultFromOrchestrator);
return CompletedTask;
});
var result = dispatchContext.GetProperty<OrchestratorExecutionResult>();
cursor.LatestDecisions = result?.Actions ?? Enumerable.Empty<OrchestratorAction>();
cursor.RuntimeState.Status = result?.CustomStatus;
}
/// <summary>
/// Converts new messages into history events that get appended to the existing orchestration state.
/// Returns False if the workItem should be discarded. True if it should be processed further.
/// Assumes that: if the batch contains a new "ExecutionStarted" event, it is the first message in the batch.
/// </summary>
/// <param name="workItem">A batch of work item messages.</param>
/// <param name="dispatcher">The name of the dispatcher, used for tracing.</param>
/// <param name="errorPropagationMode">The error propagation mode.</param>
/// <param name="logHelper">The log helper.</param>
/// <returns>True if workItem should be processed further. False otherwise.</returns>
internal static bool ReconcileMessagesWithState(TaskOrchestrationWorkItem workItem, string dispatcher, ErrorPropagationMode errorPropagationMode, LogHelper logHelper)
{
foreach (TaskMessage message in workItem.NewMessages)
{
OrchestrationInstance orchestrationInstance = message.OrchestrationInstance;
if (string.IsNullOrWhiteSpace(orchestrationInstance?.InstanceId))
{
throw TraceHelper.TraceException(
TraceEventType.Error,
$"{dispatcher}-OrchestrationInstanceMissing",
new InvalidOperationException("Message does not contain any OrchestrationInstance information"));
}
if (!workItem.OrchestrationRuntimeState.IsValid)
{
// we get here if the orchestration history is somehow corrupted (partially deleted, etc.)
return false;
}
if (workItem.OrchestrationRuntimeState.Events.Count == 1 && message.Event.EventType != EventType.ExecutionStarted)
{
// we get here because of:
// i) responses for scheduled tasks after the orchestrations have been completed
// ii) responses for explicitly deleted orchestrations
return false;
}
if (message.Event.EventType == EventType.ExecutionRewound
&& workItem.OrchestrationRuntimeState.OrchestrationStatus != OrchestrationStatus.Running
&& workItem.NewMessages.Count > 1)
{
foreach (TaskMessage droppedMessage in workItem.NewMessages)
{
if (droppedMessage.Event.EventType != EventType.ExecutionRewound)
{
logHelper.DroppingOrchestrationMessage(workItem, droppedMessage, "Multiple messages sent to an instance " +
"that is attempting to rewind from a terminal state. The only message that can be sent in " +
"this case is the rewind request.");
}
}
return false;
}
logHelper.ProcessingOrchestrationMessage(workItem, message);
TraceHelper.TraceInstance(
TraceEventType.Information,
$"{dispatcher}-ProcessEvent",
orchestrationInstance!,
"Processing new event with Id {0} and type {1}",
message.Event.EventId,
message.Event.EventType);
if (message.Event.EventType == EventType.ExecutionStarted)
{
if (workItem.OrchestrationRuntimeState.ExecutionStartedEvent != null)
{
// this was caused due to a dupe execution started event, swallow this one
logHelper.DroppingOrchestrationMessage(workItem, message, "Duplicate start event");
TraceHelper.TraceInstance(
TraceEventType.Warning,
$"{dispatcher}-DuplicateStartEvent",
orchestrationInstance!,
"Duplicate start event. Ignoring event with Id {0} and type {1} ",
message.Event.EventId,
message.Event.EventType);
continue;
}
}
else if (!string.IsNullOrWhiteSpace(orchestrationInstance?.ExecutionId)
&&
!string.Equals(orchestrationInstance!.ExecutionId,
workItem.OrchestrationRuntimeState.OrchestrationInstance?.ExecutionId))
{
// eat up any events for previous executions
logHelper.DroppingOrchestrationMessage(
workItem,
message,
$"ExecutionId of event ({orchestrationInstance.ExecutionId}) does not match current executionId");
TraceHelper.TraceInstance(
TraceEventType.Warning,
$"{dispatcher}-ExecutionIdMismatch",
orchestrationInstance,
"ExecutionId of event does not match current executionId. Ignoring event with Id {0} and type {1} ",
message.Event.EventId,
message.Event.EventType);
continue;
}
if (Activity.Current != null)
{
HistoryEvent historyEvent = message.Event;
if (historyEvent is TimerFiredEvent timerFiredEvent)
{
// We immediately publish the activity span for this timer by creating the activity and immediately calling Dispose() on it.
TraceHelper.EmitTraceActivityForTimer(workItem.OrchestrationRuntimeState.OrchestrationInstance, workItem.OrchestrationRuntimeState.Name, message.Event.Timestamp, timerFiredEvent);
}
else if (historyEvent is SubOrchestrationInstanceCompletedEvent subOrchestrationInstanceCompletedEvent)
{
SubOrchestrationInstanceCreatedEvent subOrchestrationCreatedEvent = workItem.OrchestrationRuntimeState.Events.OfType<SubOrchestrationInstanceCreatedEvent>().FirstOrDefault(x => x.EventId == subOrchestrationInstanceCompletedEvent.TaskScheduledId);
// We immediately publish the activity span for this sub-orchestration by creating the activity and immediately calling Dispose() on it.
TraceHelper.EmitTraceActivityForSubOrchestrationCompleted(workItem.OrchestrationRuntimeState.OrchestrationInstance, subOrchestrationCreatedEvent);
}
else if (historyEvent is SubOrchestrationInstanceFailedEvent subOrchestrationInstanceFailedEvent)
{
SubOrchestrationInstanceCreatedEvent subOrchestrationCreatedEvent = workItem.OrchestrationRuntimeState.Events.OfType<SubOrchestrationInstanceCreatedEvent>().FirstOrDefault(x => x.EventId == subOrchestrationInstanceFailedEvent.TaskScheduledId);
// We immediately publish the activity span for this sub-orchestration by creating the activity and immediately calling Dispose() on it.
TraceHelper.EmitTraceActivityForSubOrchestrationFailed(workItem.OrchestrationRuntimeState.OrchestrationInstance, subOrchestrationCreatedEvent, subOrchestrationInstanceFailedEvent, errorPropagationMode);
}
}
if (message.Event is TaskCompletedEvent taskCompletedEvent)
{
TaskScheduledEvent taskScheduledEvent = workItem.OrchestrationRuntimeState.Events.OfType<TaskScheduledEvent>().LastOrDefault(x => x.EventId == taskCompletedEvent.TaskScheduledId);
TraceHelper.EmitTraceActivityForTaskCompleted(workItem.OrchestrationRuntimeState.OrchestrationInstance, taskScheduledEvent);
}
else if (message.Event is TaskFailedEvent taskFailedEvent)
{
TaskScheduledEvent taskScheduledEvent = workItem.OrchestrationRuntimeState.Events.OfType<TaskScheduledEvent>().LastOrDefault(x => x.EventId == taskFailedEvent.TaskScheduledId);
TraceHelper.EmitTraceActivityForTaskFailed(workItem.OrchestrationRuntimeState.OrchestrationInstance, taskScheduledEvent, taskFailedEvent, errorPropagationMode);
}
// In this case, the ExecutionRewoundEvent has already been added to the history and is just sent as a way to trigger the failed deepest suborchestrations to rerun.
// We do not redundantly add it to the history in this situation.
if (!(message.Event is ExecutionRewoundEvent executionRewoundEvent && workItem.OrchestrationRuntimeState.OrchestrationStatus == OrchestrationStatus.Running))
{
workItem.OrchestrationRuntimeState.AddEvent(message.Event);
}
}
return true;
}