/
DurableOrchestrationContext.cs
1329 lines (1129 loc) · 54.5 KB
/
DurableOrchestrationContext.cs
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) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using DurableTask.Core;
using DurableTask.Core.Exceptions;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.WebJobs.Extensions.DurableTask
{
/// <summary>
/// Parameter data for orchestration bindings that can be used to schedule function-based activities.
/// </summary>
internal class DurableOrchestrationContext : DurableCommonContext, IDurableOrchestrationContext,
#pragma warning disable 618
DurableOrchestrationContextBase // for v1 legacy compatibility.
#pragma warning restore 618
{
public const string DefaultVersion = "";
private readonly Dictionary<string, IEventTaskCompletionSource> pendingExternalEvents =
new Dictionary<string, IEventTaskCompletionSource>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, Queue<string>> bufferedExternalEvents =
new Dictionary<string, Queue<string>>(StringComparer.OrdinalIgnoreCase);
private readonly DurabilityProvider durabilityProvider;
private readonly int maxActionCount;
private readonly MessagePayloadDataConverter messageDataConverter;
private readonly MessagePayloadDataConverter errorDataConverter;
private int actionCount;
private string serializedOutput;
private string serializedCustomStatus;
private bool isReplaying;
private int newGuidCounter = 0;
private LockReleaser lockReleaser = null;
private MessageSorter messageSorter;
internal DurableOrchestrationContext(DurableTaskExtension config, DurabilityProvider durabilityProvider, string functionName)
: base(config, functionName)
{
this.messageDataConverter = config.MessageDataConverter;
this.errorDataConverter = config.ErrorDataConverter;
this.durabilityProvider = durabilityProvider;
this.actionCount = 0;
this.maxActionCount = config.Options.MaxOrchestrationActions;
}
internal string ParentInstanceId { get; set; }
internal OrchestrationContext InnerContext { get; set; }
internal bool IsReplaying
{
get
{
return this.InnerContext?.IsReplaying ?? this.isReplaying;
}
set
{
this.isReplaying = value;
}
}
internal bool ContinuedAsNew { get; private set; }
internal bool IsCompleted { get; set; }
internal bool IsLongRunningTimer { get; private set; }
internal ExceptionDispatchInfo OrchestrationException { get; set; }
internal bool IsOutputSet => this.serializedOutput != null;
private string OrchestrationName => this.FunctionName;
internal bool PreserveUnprocessedEvents { get; set; }
/// <inheritdoc/>
DateTime IDurableOrchestrationContext.CurrentUtcDateTime => this.InnerContext.CurrentUtcDateTime;
/// <inheritdoc/>
bool IDurableOrchestrationContext.IsReplaying => this.InnerContext?.IsReplaying ?? this.IsReplaying;
/// <inheritdoc />
string IDurableOrchestrationContext.Name => this.OrchestrationName;
/// <inheritdoc />
string IDurableOrchestrationContext.InstanceId => this.InstanceId;
/// <inheritdoc />
string IDurableOrchestrationContext.ParentInstanceId => this.ParentInstanceId;
protected List<EntityId> ContextLocks { get; set; }
protected string LockRequestId { get; set; }
private MessageSorter MessageSorter => this.messageSorter ?? (this.messageSorter = new MessageSorter());
/// <summary>
/// Returns the orchestrator function input as a raw JSON string value.
/// </summary>
/// <returns>
/// The raw JSON-formatted orchestrator function input.
/// </returns>
internal string GetRawInput()
{
this.ThrowIfInvalidAccess();
return this.RawInput;
}
/// <summary>
/// Gets the input of the current orchestrator function instance as a <c>JToken</c>.
/// </summary>
/// <returns>
/// The parsed <c>JToken</c> representation of the orchestrator function input.
/// </returns>
internal JToken GetInputAsJson()
{
return MessagePayloadDataConverter.ConvertToJToken(this.RawInput);
}
/// <inheritdoc />
T IDurableOrchestrationContext.GetInput<T>()
{
this.ThrowIfInvalidAccess();
// Nulls need special handling because the JSON converter will throw
// if you try to convert a JSON null into a CLR value type.
if (this.RawInput == null || this.RawInput == "null")
{
return default(T);
}
return this.messageDataConverter.Deserialize<T>(this.RawInput);
}
/// <summary>
/// Sets the JSON-serializeable output of the current orchestrator function.
/// </summary>
/// <remarks>
/// If this method is not called explicitly, the return value of the orchestrator function is used as the output.
/// </remarks>
/// <param name="output">The JSON-serializeable value to use as the orchestrator function output.</param>
public void SetOutput(object output)
{
this.ThrowIfInvalidAccess();
if (this.IsOutputSet)
{
throw new InvalidOperationException("The output has already been set of this orchestration instance.");
}
if (output != null)
{
JToken json = output as JToken;
if (json != null)
{
this.serializedOutput = json.ToString(Formatting.None);
}
else
{
this.serializedOutput = this.messageDataConverter.Serialize(output);
}
}
else
{
this.serializedOutput = null;
}
}
internal string GetSerializedOutput()
{
return this.serializedOutput;
}
/// <inheritdoc />
void IDurableOrchestrationContext.SetCustomStatus(object customStatusObject)
{
this.ThrowIfInvalidAccess();
// Limit the custom status payload to 16 KB
const int MaxCustomStatusPayloadSizeInKB = 16;
this.serializedCustomStatus = this.messageDataConverter.Serialize(
customStatusObject,
MaxCustomStatusPayloadSizeInKB);
}
internal string GetSerializedCustomStatus()
{
return this.serializedCustomStatus;
}
Task<TResult> IDurableOrchestrationContext.CallSubOrchestratorAsync<TResult>(string functionName, object input)
{
return ((IDurableOrchestrationContext)this).CallSubOrchestratorAsync<TResult>(functionName, string.Empty, input);
}
/// <inheritdoc />
Task<TResult> IDurableOrchestrationContext.CallSubOrchestratorAsync<TResult>(string functionName, string instanceId, object input)
{
return this.CallDurableTaskFunctionAsync<TResult>(functionName, FunctionType.Orchestrator, false, instanceId, null, null, input, null);
}
/// <inheritdoc />
Task<TResult> IDurableOrchestrationContext.CallSubOrchestratorWithRetryAsync<TResult>(string functionName, RetryOptions retryOptions, string instanceId, object input)
{
if (retryOptions == null)
{
throw new ArgumentNullException(nameof(retryOptions));
}
return this.CallDurableTaskFunctionAsync<TResult>(functionName, FunctionType.Orchestrator, false, instanceId, null, retryOptions, input, null);
}
Task<DurableHttpResponse> IDurableOrchestrationContext.CallHttpAsync(HttpMethod method, Uri uri, string content)
{
DurableHttpRequest req = new DurableHttpRequest(
method: method,
uri: uri,
content: content);
return ((IDurableOrchestrationContext)this).CallHttpAsync(req);
}
Task<DurableHttpResponse> IDurableOrchestrationContext.CallHttpAsync(DurableHttpRequest req)
{
return ((IDurableOrchestrationContext)this).CallHttpAsync(req, null);
}
async Task<DurableHttpResponse> IDurableOrchestrationContext.CallHttpAsync(DurableHttpRequest req, RetryOptions retryOptions)
{
DurableHttpResponse durableHttpResponse = await this.ScheduleDurableHttpActivityAsync(req, retryOptions);
HttpStatusCode currStatusCode = durableHttpResponse.StatusCode;
while (currStatusCode == HttpStatusCode.Accepted && req.AsynchronousPatternEnabled)
{
var headersDictionary = new Dictionary<string, StringValues>(
durableHttpResponse.Headers,
StringComparer.OrdinalIgnoreCase);
DateTime fireAt = default(DateTime);
if (headersDictionary.TryGetValue("Retry-After", out StringValues retryAfter))
{
fireAt = this.InnerContext.CurrentUtcDateTime
.AddSeconds(int.Parse(retryAfter));
}
else
{
fireAt = this.InnerContext.CurrentUtcDateTime
.AddMilliseconds(this.Config.Options.HttpSettings.DefaultAsyncRequestSleepTimeMilliseconds);
}
this.IncrementActionsOrThrowException();
await this.InnerContext.CreateTimer(fireAt, CancellationToken.None);
DurableHttpRequest durableAsyncHttpRequest = this.CreateLocationPollRequest(
req,
durableHttpResponse.Headers["Location"]);
durableHttpResponse = await this.ScheduleDurableHttpActivityAsync(durableAsyncHttpRequest, retryOptions);
currStatusCode = durableHttpResponse.StatusCode;
}
return durableHttpResponse;
}
private async Task<DurableHttpResponse> ScheduleDurableHttpActivityAsync(DurableHttpRequest req, RetryOptions retryOptions = null)
{
DurableHttpResponse durableHttpResponse = await this.CallDurableTaskFunctionAsync<DurableHttpResponse>(
functionName: HttpOptions.HttpTaskActivityReservedName,
functionType: FunctionType.Activity,
oneWay: false,
instanceId: null,
operation: null,
retryOptions: retryOptions,
input: req,
scheduledTimeUtc: null);
return durableHttpResponse;
}
private DurableHttpRequest CreateLocationPollRequest(DurableHttpRequest durableHttpRequest, string locationUri)
{
DurableHttpRequest newDurableHttpRequest = new DurableHttpRequest(
method: HttpMethod.Get,
uri: new Uri(locationUri),
headers: durableHttpRequest.Headers,
tokenSource: durableHttpRequest.TokenSource,
timeout: durableHttpRequest.Timeout);
// Do not copy over the x-functions-key header, as in many cases, the
// functions key used for the initial request will be a Function-level key
// and the status endpoint requires a master key.
newDurableHttpRequest.Headers.Remove("x-functions-key");
return newDurableHttpRequest;
}
/// <inheritdoc />
async Task<T> IDurableOrchestrationContext.CreateTimer<T>(DateTime fireAt, T state, CancellationToken cancelToken)
{
this.ThrowIfInvalidAccess();
DateTime intervalFireAt = fireAt;
if (fireAt.Subtract(this.InnerContext.CurrentUtcDateTime) > this.durabilityProvider.MaximumDelayTime)
{
this.IsLongRunningTimer = true;
intervalFireAt = this.InnerContext.CurrentUtcDateTime.Add(this.durabilityProvider.LongRunningTimerIntervalLength);
}
T result = default;
if (!this.IsLongRunningTimer)
{
this.IncrementActionsOrThrowException();
Task<T> timerTask = this.InnerContext.CreateTimer(fireAt, state, cancelToken);
this.Config.TraceHelper.FunctionListening(
this.Config.Options.HubName,
this.OrchestrationName,
this.InstanceId,
reason: $"CreateTimer:{fireAt:o}",
isReplay: this.InnerContext.IsReplaying);
result = await timerTask;
}
else
{
this.Config.TraceHelper.FunctionListening(
this.Config.Options.HubName,
this.OrchestrationName,
this.InstanceId,
reason: $"CreateTimer:{fireAt:o}",
isReplay: this.InnerContext.IsReplaying);
while (this.InnerContext.CurrentUtcDateTime < fireAt && !cancelToken.IsCancellationRequested)
{
this.IncrementActionsOrThrowException();
Task<T> timerTask = this.InnerContext.CreateTimer(intervalFireAt, state, cancelToken);
result = await timerTask;
TimeSpan remainingTime = fireAt.Subtract(this.InnerContext.CurrentUtcDateTime);
if (remainingTime <= TimeSpan.Zero)
{
break;
}
else if (remainingTime < this.durabilityProvider.LongRunningTimerIntervalLength)
{
intervalFireAt = this.InnerContext.CurrentUtcDateTime.Add(remainingTime);
}
else
{
intervalFireAt = this.InnerContext.CurrentUtcDateTime.Add(this.durabilityProvider.LongRunningTimerIntervalLength);
}
}
}
this.Config.TraceHelper.TimerExpired(
this.Config.Options.HubName,
this.OrchestrationName,
this.InstanceId,
expirationTime: fireAt,
isReplay: this.InnerContext.IsReplaying);
this.IsLongRunningTimer = false;
return result;
}
// We now have built in long-timer support for C#, but in some scenarios, such as out-of-proc,
// we may still need to enforce this limitations until the solution works there as well.
internal void ThrowIfInvalidTimerLengthForStorageProvider(DateTime fireAt)
{
this.ThrowIfInvalidAccess();
if (!this.durabilityProvider.ValidateDelayTime(fireAt.Subtract(this.InnerContext.CurrentUtcDateTime), out string errorMessage))
{
throw new ArgumentException(errorMessage, nameof(fireAt));
}
}
/// <inheritdoc />
Task<T> IDurableOrchestrationContext.WaitForExternalEvent<T>(string name)
{
this.ThrowIfInvalidAccess();
return this.WaitForExternalEvent<T>(name, "ExternalEvent");
}
/// <inheritdoc/>
Task<T> IDurableOrchestrationContext.WaitForExternalEvent<T>(string name, TimeSpan timeout, CancellationToken cancelToken)
{
this.ThrowIfInvalidAccess();
Action<TaskCompletionSource<T>> timedOutAction = tcs =>
tcs.TrySetException(new TimeoutException($"Event {name} not received in {timeout}"));
return this.WaitForExternalEvent(name, timeout, timedOutAction, cancelToken);
}
/// <inheritdoc/>
Task<T> IDurableOrchestrationContext.WaitForExternalEvent<T>(string name, TimeSpan timeout, T defaultValue, CancellationToken cancelToken)
{
this.ThrowIfInvalidAccess();
Action<TaskCompletionSource<T>> timedOutAction = tcs => tcs.TrySetResult(defaultValue);
return this.WaitForExternalEvent(name, timeout, timedOutAction, cancelToken);
}
/// <inheritdoc />
Task<TResult> IDurableOrchestrationContext.CallActivityAsync<TResult>(string functionName, object input)
{
return this.CallDurableTaskFunctionAsync<TResult>(functionName, FunctionType.Activity, false, null, null, null, input, null);
}
/// <inheritdoc />
Task<TResult> IDurableOrchestrationContext.CallActivityWithRetryAsync<TResult>(string functionName, RetryOptions retryOptions, object input)
{
if (retryOptions == null)
{
throw new ArgumentNullException(nameof(retryOptions));
}
return this.CallDurableTaskFunctionAsync<TResult>(functionName, FunctionType.Activity, false, null, null, retryOptions, input, null);
}
/// <inheritdoc/>
bool IDurableOrchestrationContext.IsLocked(out IReadOnlyList<EntityId> ownedLocks)
{
ownedLocks = this.ContextLocks;
return ownedLocks != null;
}
/// <inheritdoc/>
Guid IDurableOrchestrationContext.NewGuid()
{
return this.NewGuid();
}
/// <inheritdoc/>
void IDurableOrchestrationContext.SignalEntity(EntityId entity, string operationName, object operationInput)
{
this.ThrowIfInvalidAccess();
if (operationName == null)
{
throw new ArgumentNullException(nameof(operationName));
}
var alreadyCompletedTask = this.CallDurableTaskFunctionAsync<object>(entity.EntityName, FunctionType.Entity, true, EntityId.GetSchedulerIdFromEntityId(entity), operationName, null, operationInput, null);
System.Diagnostics.Debug.Assert(alreadyCompletedTask.IsCompleted, "signaling entities is synchronous");
alreadyCompletedTask.Wait(); // just so we see exceptions during testing
}
/// <inheritdoc/>
void IDurableOrchestrationContext.SignalEntity(EntityId entity, DateTime startTime, string operationName, object operationInput)
{
this.ThrowIfInvalidAccess();
if (operationName == null)
{
throw new ArgumentNullException(nameof(operationName));
}
var alreadyCompletedTask = this.CallDurableTaskFunctionAsync<object>(entity.EntityName, FunctionType.Entity, true, EntityId.GetSchedulerIdFromEntityId(entity), operationName, null, operationInput, startTime);
System.Diagnostics.Debug.Assert(alreadyCompletedTask.IsCompleted, "scheduling operations on entities is synchronous");
alreadyCompletedTask.Wait(); // just so we see exceptions during testing
}
/// <inheritdoc/>
string IDurableOrchestrationContext.StartNewOrchestration(string functionName, object input, string instanceId)
{
// correlation
#if NETSTANDARD2_0
var context = CorrelationTraceContext.Current;
#endif
this.ThrowIfInvalidAccess();
var actualInstanceId = string.IsNullOrEmpty(instanceId) ? this.NewGuid().ToString() : instanceId;
var alreadyCompletedTask = this.CallDurableTaskFunctionAsync<string>(functionName, FunctionType.Orchestrator, true, actualInstanceId, null, null, input, null);
System.Diagnostics.Debug.Assert(alreadyCompletedTask.IsCompleted, "starting orchestrations is synchronous");
return actualInstanceId;
}
internal async Task<TResult> CallDurableTaskFunctionAsync<TResult>(
string functionName,
FunctionType functionType,
bool oneWay,
string instanceId,
string operation,
RetryOptions retryOptions,
object input,
DateTime? scheduledTimeUtc)
{
this.ThrowIfInvalidAccess();
if (retryOptions != null)
{
if (!this.durabilityProvider.ValidateDelayTime(retryOptions.MaxRetryInterval, out string errorMessage))
{
throw new ArgumentException(errorMessage, nameof(retryOptions.MaxRetryInterval));
}
if (!this.durabilityProvider.ValidateDelayTime(retryOptions.FirstRetryInterval, out errorMessage))
{
throw new ArgumentException(errorMessage, nameof(retryOptions.FirstRetryInterval));
}
}
// TODO: Support for versioning
string version = DefaultVersion;
this.Config.ThrowIfFunctionDoesNotExist(functionName, functionType);
Task<TResult> callTask = null;
EntityId? lockToUse = null;
string operationId = string.Empty;
string operationName = string.Empty;
switch (functionType)
{
case FunctionType.Activity:
System.Diagnostics.Debug.Assert(instanceId == null, "The instanceId parameter should not be used for activity functions.");
System.Diagnostics.Debug.Assert(operation == null, "The operation parameter should not be used for activity functions.");
System.Diagnostics.Debug.Assert(!oneWay, "The oneWay parameter should not be used for activity functions.");
if (retryOptions == null)
{
this.IncrementActionsOrThrowException();
callTask = this.InnerContext.ScheduleTask<TResult>(functionName, version, input);
}
else
{
this.IncrementActionsOrThrowException();
callTask = this.InnerContext.ScheduleWithRetry<TResult>(
functionName,
version,
retryOptions.GetRetryOptions(),
input);
}
break;
case FunctionType.Orchestrator:
// Instance IDs should not be reused when creating sub-orchestrations. This is a best-effort
// check. We cannot easily check the full hierarchy, so we just look at the current orchestration
// and the immediate parent.
if (string.Equals(instanceId, this.InstanceId, StringComparison.OrdinalIgnoreCase) ||
(this.ParentInstanceId != null && string.Equals(instanceId, this.ParentInstanceId, StringComparison.OrdinalIgnoreCase)))
{
throw new ArgumentException("The instance ID of a sub-orchestration must be different than the instance ID of a parent orchestration.");
}
System.Diagnostics.Debug.Assert(operation == null, "The operation parameter should not be used for activity functions.");
if (instanceId != null && instanceId.StartsWith("@"))
{
throw new ArgumentException(nameof(instanceId), "Orchestration instance ids must not start with @");
}
if (oneWay)
{
this.IncrementActionsOrThrowException();
var dummyTask = this.InnerContext.CreateSubOrchestrationInstance<TResult>(
functionName,
version,
instanceId,
input,
new Dictionary<string, string>() { { OrchestrationTags.FireAndForget, "" } });
System.Diagnostics.Debug.Assert(dummyTask.IsCompleted, "task should be fire-and-forget");
}
else
{
if (this.ContextLocks != null)
{
throw new LockingRulesViolationException("While holding locks, cannot call suborchestrators.");
}
if (retryOptions == null)
{
this.IncrementActionsOrThrowException();
callTask = this.InnerContext.CreateSubOrchestrationInstance<TResult>(
functionName,
version,
instanceId,
input);
}
else
{
this.IncrementActionsOrThrowException();
callTask = this.InnerContext.CreateSubOrchestrationInstanceWithRetry<TResult>(
functionName,
version,
instanceId,
retryOptions.GetRetryOptions(),
input);
}
}
break;
case FunctionType.Entity:
System.Diagnostics.Debug.Assert(operation != null, "The operation parameter is required.");
System.Diagnostics.Debug.Assert(retryOptions == null, "Retries are not supported for entity calls.");
System.Diagnostics.Debug.Assert(instanceId != null, "Entity calls need to specify the target entity.");
if (this.ContextLocks != null)
{
lockToUse = EntityId.GetEntityIdFromSchedulerId(instanceId);
if (oneWay)
{
if (this.ContextLocks.Contains(lockToUse.Value))
{
throw new LockingRulesViolationException("While holding locks, cannot signal entities whose lock is held.");
}
}
else
{
if (!this.ContextLocks.Remove(lockToUse.Value))
{
throw new LockingRulesViolationException("While holding locks, cannot call entities whose lock is not held.");
}
}
}
var guid = this.NewGuid(); // deterministically replayable unique id for this request
var target = new OrchestrationInstance() { InstanceId = instanceId };
operationId = guid.ToString();
operationName = operation;
var request = new RequestMessage()
{
ParentInstanceId = this.InstanceId,
ParentExecutionId = this.ExecutionId,
Id = guid,
IsSignal = oneWay,
Operation = operation,
ScheduledTime = scheduledTimeUtc,
};
if (input != null)
{
request.SetInput(input, this.messageDataConverter);
}
this.SendEntityMessage(target, request);
if (!oneWay)
{
callTask = this.WaitForEntityResponse<TResult>(guid, lockToUse);
}
break;
default:
throw new InvalidOperationException($"Unexpected function type '{functionType}'.");
}
string sourceFunctionId = this.FunctionName;
this.Config.TraceHelper.FunctionScheduled(
this.Config.Options.HubName,
functionName,
this.InstanceId,
reason: sourceFunctionId,
functionType: functionType,
isReplay: this.IsReplaying);
TResult output;
Exception exception = null;
if (oneWay)
{
return default(TResult);
}
System.Diagnostics.Debug.Assert(callTask != null, "Two-way operations are asynchronous, so callTask must not be null.");
try
{
output = await callTask;
}
catch (TaskFailedException e)
{
// Check to see if CallHttpAsync() threw a TimeoutException
// In this case, we want to throw a TimeoutException instead of a FunctionFailedException
if (functionName.Equals(HttpOptions.HttpTaskActivityReservedName) &&
(e.InnerException is TimeoutException || e.InnerException is HttpRequestException))
{
if (e.InnerException is HttpRequestException)
{
throw new HttpRequestException(e.Message);
}
throw e.InnerException;
}
exception = e;
string message = string.Format(
"The {0} function '{1}' failed: \"{2}\". See the function execution logs for additional details.",
functionType.ToString().ToLowerInvariant(),
functionName,
e.InnerException?.Message);
throw new FunctionFailedException(message, e.InnerException);
}
catch (SubOrchestrationFailedException e)
{
exception = e;
string message = string.Format(
"The {0} function '{1}' failed: \"{2}\". See the function execution logs for additional details.",
functionType.ToString().ToLowerInvariant(),
functionName,
e.InnerException?.Message);
throw new FunctionFailedException(message, e.InnerException);
}
catch (Exception e)
{
exception = e;
throw;
}
finally
{
if (exception != null && this.IsReplaying)
{
// If this were not a replay, then the orchestrator/activity/entity function trigger would have already
// emitted a FunctionFailed trace with the full exception details.
if (functionType == FunctionType.Entity)
{
this.Config.TraceHelper.OperationFailed(
this.Config.Options.HubName,
functionName,
this.InstanceId,
operationId,
operationName,
input: "(replayed)",
exception: "(replayed)",
duration: 0,
isReplay: true);
}
else
{
this.Config.TraceHelper.FunctionFailed(
this.Config.Options.HubName,
functionName,
this.InstanceId,
reason: $"(replayed {exception.GetType().Name})",
functionType: functionType,
isReplay: true);
}
}
}
if (this.IsReplaying)
{
// If this were not a replay, then the orchestrator/activity/entity function trigger would have already
// emitted a FunctionCompleted trace with the actual output details.
if (functionType == FunctionType.Entity)
{
this.Config.TraceHelper.OperationCompleted(
this.Config.Options.HubName,
functionName,
this.InstanceId,
operationId,
operationName,
input: "(replayed)",
output: "(replayed)",
duration: 0,
isReplay: true);
}
else
{
this.Config.TraceHelper.FunctionCompleted(
this.Config.Options.HubName,
functionName,
this.InstanceId,
output: "(replayed)",
continuedAsNew: false,
functionType: functionType,
isReplay: true);
}
}
return output;
}
internal async Task<TResult> WaitForEntityResponse<TResult>(Guid guid, EntityId? lockToUse)
{
var response = await this.WaitForExternalEvent<ResponseMessage>(guid.ToString(), "EntityResponse");
if (lockToUse.HasValue)
{
// the lock is available again now that the entity call returned
this.ContextLocks.Add(lockToUse.Value);
}
// can rethrow an exception if that was the result of the operation
return response.GetResult<TResult>(this.messageDataConverter, this.errorDataConverter);
}
internal Task<T> WaitForExternalEvent<T>(string name, string reason)
{
lock (this.pendingExternalEvents)
{
// We use a stack (a custom implementation using a single-linked list)
// to make it easier for users to abandon external events
// that they no longer care about. The common case is a Task.WhenAny in a loop.
IEventTaskCompletionSource taskCompletionSources;
EventTaskCompletionSource<T> tcs;
// Set up the stack for listening to external events
if (!this.pendingExternalEvents.TryGetValue(name, out taskCompletionSources))
{
tcs = new EventTaskCompletionSource<T>();
this.pendingExternalEvents[name] = tcs;
}
else
{
if (taskCompletionSources.EventType != typeof(T))
{
throw new ArgumentException("Events with the same name should have the same type argument.");
}
else
{
tcs = new EventTaskCompletionSource<T> { Next = taskCompletionSources };
this.pendingExternalEvents[name] = tcs;
}
}
// Check the queue to see if any events came in before the orchestrator was listening
if (this.bufferedExternalEvents.TryGetValue(name, out Queue<string> queue))
{
string rawInput = queue.Dequeue();
if (queue.Count == 0)
{
this.bufferedExternalEvents.Remove(name);
}
// We can call raise event right away, since we already have an event's input
this.RaiseEvent(name, rawInput);
}
else
{
this.Config.TraceHelper.FunctionListening(
this.Config.Options.HubName,
this.FunctionName,
this.InstanceId,
reason: $"WaitFor{reason}:{name}",
isReplay: this.IsReplaying);
}
return tcs.Task;
}
}
internal void RaiseEvent(string name, string input)
{
lock (this.pendingExternalEvents)
{
IEventTaskCompletionSource taskCompletionSources;
if (this.pendingExternalEvents.TryGetValue(name, out taskCompletionSources))
{
IEventTaskCompletionSource tcs = taskCompletionSources;
// If we're going to raise an event we should remove it from the pending collection
// because otherwise WaitForExternalEventAsync() will always find one with this key and run infinitely.
IEventTaskCompletionSource next = tcs.Next;
if (next == null)
{
this.pendingExternalEvents.Remove(name);
}
else
{
this.pendingExternalEvents[name] = next;
}
object deserializedObject = this.messageDataConverter.Deserialize(input, tcs.EventType);
if (deserializedObject is ResponseMessage responseMessage)
{
this.Config.TraceHelper.EntityResponseReceived(
this.HubName,
this.Name,
FunctionType.Orchestrator,
this.InstanceId,
name,
this.Config.GetIntputOutputTrace(responseMessage.Result),
this.IsReplaying);
}
else
{
this.Config.TraceHelper.ExternalEventRaised(
this.HubName,
this.Name,
this.InstanceId,
name,
this.Config.GetIntputOutputTrace(input),
this.IsReplaying);
}
tcs.TrySetResult(deserializedObject);
}
else
{
// Add the event to an (in-memory) queue, so we don't drop or lose it
if (!this.bufferedExternalEvents.TryGetValue(name, out Queue<string> bufferedEvents))
{
bufferedEvents = new Queue<string>();
this.bufferedExternalEvents[name] = bufferedEvents;
}
bufferedEvents.Enqueue(input);
this.Config.TraceHelper.ExternalEventSaved(
this.HubName,
this.Name,
FunctionType.Orchestrator,
this.InstanceId,
name,
this.IsReplaying);
}
}
}
internal void RescheduleBufferedExternalEvents()
{
var instance = new OrchestrationInstance { InstanceId = this.InstanceId };
foreach (var pair in this.bufferedExternalEvents)
{
string eventName = pair.Key;
Queue<string> events = pair.Value;
while (events.Count > 0)
{
// Need to round-trip serialization since SendEvent always tries to serialize.
string rawInput = events.Dequeue();
JToken jsonData = MessagePayloadDataConverter.ConvertToJToken(rawInput);
this.InnerContext.SendEvent(instance, eventName, jsonData);
}
}
}
private Task<T> WaitForExternalEvent<T>(string name, TimeSpan timeout, Action<TaskCompletionSource<T>> timeoutAction, CancellationToken cancelToken)
{
var tcs = new TaskCompletionSource<T>();
var cts = CancellationTokenSource.CreateLinkedTokenSource(cancelToken);
var timeoutAt = this.InnerContext.CurrentUtcDateTime + timeout;
var timeoutTask = ((IDurableOrchestrationContext)this).CreateTimer(timeoutAt, cts.Token);
var waitForEventTask = this.WaitForExternalEvent<T>(name, "ExternalEvent");
waitForEventTask.ContinueWith(
t =>
{
using (cts)
{
if (t.Exception != null)
{
tcs.TrySetException(t.Exception);
}
else
{
tcs.TrySetResult(t.Result);
}
cts.Cancel();
}
}, TaskContinuationOptions.ExecuteSynchronously);
timeoutTask.ContinueWith(
t =>
{
using (cts)
{
using (cts)
{
if (t.Exception == null)
{
timeoutAction(tcs);
}
else
{
// t.Exception is an aggregate exception, so grab internal exception
tcs.TrySetException(t.Exception.InnerException);
}
}