-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathNetheriteOrchestrationService.cs
1034 lines (856 loc) · 45 KB
/
NetheriteOrchestrationService.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) Microsoft Corporation.
// Licensed under the MIT License.
namespace DurableTask.Netherite
{
using DurableTask.Core;
using DurableTask.Core.Common;
using DurableTask.Core.History;
using DurableTask.Netherite.Faster;
using DurableTask.Netherite.Scaling;
using Microsoft.Azure.Storage;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Local partition of the distributed orchestration service.
/// </summary>
public class NetheriteOrchestrationService :
IOrchestrationService,
IOrchestrationServiceClient,
IOrchestrationServiceQueryClient,
TransportAbstraction.IHost,
IStorageProvider
{
readonly ITaskHub taskHub;
readonly TransportConnectionString.StorageChoices configuredStorage;
readonly TransportConnectionString.TransportChoices configuredTransport;
readonly MemoryTracker memoryTracker;
readonly WorkItemTraceHelper workItemTraceHelper;
readonly Stopwatch workItemStopwatch = new Stopwatch();
/// <summary>
/// The logger category prefix used for all ILoggers in this backend.
/// </summary>
public const string LoggerCategoryName = "DurableTask.Netherite";
CancellationTokenSource serviceShutdownSource;
Exception startupException;
Timer threadWatcher;
internal async ValueTask<Client> GetClientAsync()
{
if (this.checkedClient == null)
{
// we need to wait till the startup of the client is complete
await this.TryStartAsync(true);
}
if (this.startupException != null)
{
// to help observability we expose backend startup exceptions to client API calls
throw new InvalidOperationException($"Netherite backend failed to start: {this.startupException.Message}", this.startupException);
}
return this.checkedClient;
}
Client client;
Client checkedClient;
internal ILoadMonitorService LoadMonitorService { get; private set; }
internal NetheriteOrchestrationServiceSettings Settings { get; private set; }
internal uint NumberPartitions { get; private set; }
uint TransportAbstraction.IHost.NumberPartitions { set => this.NumberPartitions = value; }
internal string PathPrefix { get; private set; }
string TransportAbstraction.IHost.PathPrefix { set => this.PathPrefix = value; }
internal string StorageAccountName { get; private set; }
internal WorkItemQueue<ActivityWorkItem> ActivityWorkItemQueue { get; private set; }
internal WorkItemQueue<OrchestrationWorkItem> OrchestrationWorkItemQueue { get; private set; }
internal LoadPublisher LoadPublisher { get; private set; }
internal ILoggerFactory LoggerFactory { get; }
internal OrchestrationServiceTraceHelper TraceHelper { get; private set; }
public event Action OnStopping;
/// <inheritdoc/>
public override string ToString()
{
#if DEBUG
string configuration = "Debug";
#else
string configuration = "Release";
#endif
return $"NetheriteOrchestrationService on {this.configuredTransport}Transport and {this.configuredStorage}Storage, {configuration} build";
}
/// <summary>
/// Creates a new instance of the OrchestrationService with default settings
/// </summary>
public NetheriteOrchestrationService(NetheriteOrchestrationServiceSettings settings, ILoggerFactory loggerFactory)
{
this.LoggerFactory = loggerFactory;
this.Settings = settings;
this.TraceHelper = new OrchestrationServiceTraceHelper(loggerFactory, settings.LogLevelLimit, settings.WorkerId, settings.HubName);
this.workItemTraceHelper = new WorkItemTraceHelper(loggerFactory, settings.WorkItemLogLevelLimit, settings.HubName);
try
{
this.TraceHelper.TraceProgress("Reading configuration for transport and storage providers");
TransportConnectionString.Parse(this.Settings.ResolvedTransportConnectionString, out this.configuredStorage, out this.configuredTransport);
this.StorageAccountName = this.configuredStorage == TransportConnectionString.StorageChoices.Memory
? "Memory"
: CloudStorageAccount.Parse(this.Settings.ResolvedStorageConnectionString).Credentials.AccountName;
// set the account name in the trace helpers
this.TraceHelper.StorageAccountName = this.workItemTraceHelper.StorageAccountName = this.StorageAccountName;
this.TraceHelper.TraceCreated(Environment.ProcessorCount, this.configuredTransport, this.configuredStorage);
if (this.configuredStorage == TransportConnectionString.StorageChoices.Faster)
{
// force dll load here so exceptions are observed early
var _ = System.Threading.Channels.Channel.CreateBounded<DateTime>(10);
// throw descriptive exception if run on 32bit platform
if (!Environment.Is64BitProcess)
{
throw new NotSupportedException("Netherite backend requires 64bit, but current process is 32bit.");
}
this.memoryTracker = new MemoryTracker((long) (settings.InstanceCacheSizeMB ?? 400) * 1024 * 1024);
}
switch (this.configuredTransport)
{
case TransportConnectionString.TransportChoices.Memory:
this.taskHub = new Emulated.MemoryTransport(this, settings, this.TraceHelper.Logger);
break;
case TransportConnectionString.TransportChoices.EventHubs:
this.taskHub = new EventHubs.EventHubsTransport(this, settings, loggerFactory);
break;
default:
throw new NotImplementedException("no such transport choice");
}
if (this.configuredTransport != TransportConnectionString.TransportChoices.Memory)
{
this.TraceHelper.TraceProgress("Creating LoadMonitor Service");
if (!string.IsNullOrEmpty(settings.LoadInformationAzureTableName))
{
this.LoadMonitorService = new AzureTableLoadMonitor(settings.ResolvedStorageConnectionString, settings.LoadInformationAzureTableName, settings.HubName);
}
else
{
this.LoadMonitorService = new AzureBlobLoadMonitor(settings.ResolvedStorageConnectionString, settings.HubName);
}
}
this.workItemStopwatch.Start();
this.TraceHelper.TraceProgress(
$"Configured trace generation limits: general={settings.LogLevelLimit} , transport={settings.TransportLogLevelLimit}, storage={settings.StorageLogLevelLimit}, "
+ $"events={settings.EventLogLevelLimit}; workitems={settings.WorkItemLogLevelLimit}; clients={settings.ClientLogLevelLimit}; loadmonitor={settings.LoadMonitorLogLevelLimit}; etwEnabled={EtwSource.Log.IsEnabled()}; "
+ $"core.IsTraceEnabled={DurableTask.Core.Tracing.DefaultEventSource.Log.IsTraceEnabled}");
}
catch (Exception e) when (!Utils.IsFatal(e))
{
this.TraceHelper.TraceError("Could not create NetheriteOrchestrationService", e);
throw;
}
}
/// <summary>
/// Get a scaling monitor for autoscaling.
/// </summary>
/// <param name="monitor">The returned scaling monitor.</param>
/// <returns>true if autoscaling is supported, false otherwise</returns>
public bool TryGetScalingMonitor(out ScalingMonitor monitor)
{
if (this.configuredStorage == TransportConnectionString.StorageChoices.Faster
&& this.configuredTransport == TransportConnectionString.TransportChoices.EventHubs)
{
try
{
monitor = new ScalingMonitor(
this.Settings.ResolvedStorageConnectionString,
this.Settings.ResolvedTransportConnectionString,
this.Settings.LoadInformationAzureTableName,
this.Settings.HubName,
this.TraceHelper.TraceScaleRecommendation,
this.TraceHelper.TraceProgress,
this.TraceHelper.TraceError);
return true;
}
catch (Exception e)
{
this.TraceHelper.TraceError("ScaleMonitor failure during construction", e);
}
}
monitor = null;
return false;
}
public void WatchThreads(object _)
{
if (TrackedThreads.NumberThreads > 100)
{
this.TraceHelper.TraceError("Too many threads, shutting down", TrackedThreads.GetThreadNames());
Thread.Sleep(TimeSpan.FromSeconds(60));
System.Environment.Exit(333);
}
}
/******************************/
// storage provider
/******************************/
IPartitionState IStorageProvider.CreatePartitionState()
{
switch (this.configuredStorage)
{
case TransportConnectionString.StorageChoices.Memory:
return new MemoryStorage(this.TraceHelper.Logger);
case TransportConnectionString.StorageChoices.Faster:
return new Faster.FasterStorage(this.Settings, this.PathPrefix, this.memoryTracker, this.LoggerFactory);
default:
throw new NotImplementedException("no such storage choice");
}
}
async Task IStorageProvider.DeleteTaskhubAsync(string pathPrefix)
{
if (!(this.LoadMonitorService is null))
await this.LoadMonitorService.DeleteIfExistsAsync(CancellationToken.None).ConfigureAwait(false);
switch (this.configuredStorage)
{
case TransportConnectionString.StorageChoices.Memory:
await Task.Delay(10).ConfigureAwait(false);
break;
case TransportConnectionString.StorageChoices.Faster:
await Faster.FasterStorage.DeleteTaskhubStorageAsync(
this.Settings.ResolvedStorageConnectionString,
this.Settings.ResolvedPageBlobStorageConnectionString,
this.Settings.UseLocalDirectoryForPartitionStorage,
this.Settings.HubName,
pathPrefix).ConfigureAwait(false);
break;
default:
throw new NotImplementedException("no such storage choice");
}
}
/******************************/
// management methods
/******************************/
/// <inheritdoc />
async Task IOrchestrationService.CreateAsync() => await ((IOrchestrationService)this).CreateAsync(true);
/// <inheritdoc />
async Task IOrchestrationService.CreateAsync(bool recreateInstanceStore)
{
if (await this.taskHub.ExistsAsync())
{
if (recreateInstanceStore)
{
this.TraceHelper.TraceProgress("Creating");
await this.taskHub.DeleteAsync();
await this.taskHub.CreateIfNotExistsAsync();
}
}
else
{
await this.taskHub.CreateIfNotExistsAsync();
}
if (!(this.LoadMonitorService is null))
await this.LoadMonitorService.CreateIfNotExistsAsync(CancellationToken.None);
}
/// <inheritdoc />
async Task IOrchestrationService.CreateIfNotExistsAsync() => await ((IOrchestrationService)this).CreateAsync(false);
/// <inheritdoc />
async Task IOrchestrationService.DeleteAsync()
{
await this.taskHub.DeleteAsync();
if (!(this.LoadMonitorService is null))
await this.LoadMonitorService.DeleteIfExistsAsync(CancellationToken.None);
}
/// <inheritdoc />
async Task IOrchestrationService.DeleteAsync(bool deleteInstanceStore) => await ((IOrchestrationService)this).DeleteAsync();
/// <inheritdoc />
Task IOrchestrationService.StartAsync()
{
return this.TryStartAsync(false);
}
/// <inheritdoc />
Task IOrchestrationService.StopAsync(bool quickly)
{
return this.TryStopAsync(quickly);
}
/// <inheritdoc />
Task IOrchestrationService.StopAsync() => this.TryStopAsync(false);
enum ServiceState
{
None, Client, Full
}
Task<ServiceState> currentTransition = Task.FromResult(ServiceState.None);
public async Task TryStartAsync(bool clientOnly)
{
while (true)
{
var currentTransition = this.currentTransition;
var currentState = await currentTransition;
if (currentState == ServiceState.None)
{
var greenLight = new TaskCompletionSource<bool>();
var startTask = this.StartClientAsync(greenLight.Task);
var nextTransition = Interlocked.CompareExchange<Task<ServiceState>>(ref this.currentTransition, startTask, currentTransition);
greenLight.SetResult(nextTransition == currentTransition);
continue;
}
if (currentState == ServiceState.Client)
{
if (clientOnly)
{
return;
}
var greenLight = new TaskCompletionSource<bool>();
var startTask = this.StartWorkersAsync(greenLight.Task);
var nextTransition = Interlocked.CompareExchange<Task<ServiceState>>(ref this.currentTransition, startTask, currentTransition);
greenLight.SetResult(nextTransition == currentTransition);
continue;
}
return;
}
}
async Task<ServiceState> StartClientAsync(Task<bool> greenLight)
{
if (!await greenLight) return ServiceState.None;
try
{
this.TraceHelper.TraceProgress("Starting Client");
if (this.Settings.TestHooks != null)
{
this.TraceHelper.TraceProgress(this.Settings.TestHooks.ToString());
}
this.serviceShutdownSource = new CancellationTokenSource();
await this.taskHub.StartClientAsync();
System.Diagnostics.Debug.Assert(this.client != null, "Backend should have added client");
this.checkedClient = this.client;
this.TraceHelper.TraceProgress($"Started client");
return ServiceState.Client;
}
catch (Exception e) when (!Utils.IsFatal(e))
{
this.startupException = e;
this.TraceHelper.TraceError($"Failed to start: {e.Message}", e);
// invoke cancellation so that any partially-started partitions and event loops are terminated
try
{
this.serviceShutdownSource.Cancel();
this.serviceShutdownSource.Dispose();
this.serviceShutdownSource = null;
}
catch (Exception shutdownException)
{
this.TraceHelper.TraceError($"Exception while shutting down service: {shutdownException.Message}", shutdownException);
}
throw;
}
}
async Task<ServiceState> StartWorkersAsync(Task<bool> greenLight)
{
if (!await greenLight) return ServiceState.Client;
try
{
System.Diagnostics.Debug.Assert(this.client != null, "Backend should have added client");
this.TraceHelper.TraceProgress("Starting Workers");
this.ActivityWorkItemQueue = new WorkItemQueue<ActivityWorkItem>();
this.OrchestrationWorkItemQueue = new WorkItemQueue<OrchestrationWorkItem>();
LeaseTimer.Instance.DelayWarning = (int delay) =>
this.TraceHelper.TraceWarning($"Lease timer is running {delay}s behind schedule");
if (!(this.LoadMonitorService is null))
{
this.TraceHelper.TraceProgress("Starting Load Publisher");
this.LoadPublisher = new LoadPublisher(this.LoadMonitorService, CancellationToken.None, this.TraceHelper);
}
await this.taskHub.StartWorkersAsync();
if (this.Settings.PartitionCount != this.NumberPartitions)
{
this.TraceHelper.TraceWarning($"Ignoring configuration setting partitionCount={this.Settings.PartitionCount} because existing TaskHub has {this.NumberPartitions} partitions");
}
if (this.threadWatcher == null)
{
this.threadWatcher = new Timer(this.WatchThreads, null, 0, 120000);
}
this.TraceHelper.TraceProgress($"Started partitionCount={this.NumberPartitions}");
return ServiceState.Full;
}
catch (Exception e) when (!Utils.IsFatal(e))
{
this.startupException = e;
this.TraceHelper.TraceError($"Failed to start: {e.Message}", e);
// invoke cancellation so that any partially-started partitions and event loops are terminated
try
{
this.serviceShutdownSource.Cancel();
this.serviceShutdownSource.Dispose();
this.serviceShutdownSource = null;
}
catch(Exception shutdownException)
{
this.TraceHelper.TraceError($"Exception while shutting down service: {shutdownException.Message}", shutdownException);
}
throw;
}
}
async Task<ServiceState> TryStopAsync(bool quickly)
{
try
{
this.TraceHelper.TraceProgress($"Stopping quickly={quickly}");
this.OnStopping?.Invoke();
this.checkedClient = null;
this.client = null;
if (this.serviceShutdownSource != null)
{
this.serviceShutdownSource.Cancel();
this.serviceShutdownSource.Dispose();
this.serviceShutdownSource = null;
await this.taskHub.StopAsync();
this.ActivityWorkItemQueue.Dispose();
this.OrchestrationWorkItemQueue.Dispose();
}
this.threadWatcher?.Dispose();
this.threadWatcher = null;
this.TraceHelper.TraceProgress("Stopped cleanly");
return ServiceState.None;
}
catch (Exception e) when (!Utils.IsFatal(e))
{
this.TraceHelper.TraceError($"Failed to stop cleanly: {e.Message}", e);
throw;
}
finally
{
this.TraceHelper.TraceStopped();
}
}
/// <summary>
/// Computes the partition for the given instance.
/// </summary>
/// <param name="instanceId">The instance id.</param>
/// <returns>The partition id.</returns>
public uint GetPartitionId(string instanceId)
{
// if the instance id ends with !nn, where nn is a two-digit number, it indicates explicit partition placement
if (instanceId.Length >= 3
&& instanceId[instanceId.Length - 3] == '!'
&& uint.TryParse(instanceId.Substring(instanceId.Length - 2), out uint nn))
{
var partitionId = nn % this.NumberPartitions;
//this.Logger.LogTrace($"Instance: {instanceId} was explicitly placed on partition: {partitionId}");
return partitionId;
}
else
{
return Fnv1aHashHelper.ComputeHash(instanceId) % this.NumberPartitions;
}
}
uint GetNumberPartitions() => this.NumberPartitions;
/******************************/
// host methods
/******************************/
TransportAbstraction.IClient TransportAbstraction.IHost.AddClient(Guid clientId, Guid taskHubGuid, TransportAbstraction.ISender batchSender)
{
System.Diagnostics.Debug.Assert(this.client == null, "Backend should create only 1 client");
this.client = new Client(this, clientId, taskHubGuid, batchSender, this.workItemTraceHelper, this.serviceShutdownSource.Token);
return this.client;
}
TransportAbstraction.IPartition TransportAbstraction.IHost.AddPartition(uint partitionId, TransportAbstraction.ISender batchSender)
{
var partition = new Partition(this, partitionId, this.GetPartitionId, this.GetNumberPartitions, batchSender, this.Settings, this.StorageAccountName,
this.ActivityWorkItemQueue, this.OrchestrationWorkItemQueue, this.LoadPublisher, this.workItemTraceHelper);
return partition;
}
TransportAbstraction.ILoadMonitor TransportAbstraction.IHost.AddLoadMonitor(Guid taskHubGuid, TransportAbstraction.ISender batchSender)
{
return new LoadMonitor(this, taskHubGuid, batchSender);
}
IStorageProvider TransportAbstraction.IHost.StorageProvider => this;
IPartitionErrorHandler TransportAbstraction.IHost.CreateErrorHandler(uint partitionId)
{
return new PartitionErrorHandler((int) partitionId, this.TraceHelper.Logger, this.Settings.LogLevelLimit, this.StorageAccountName, this.Settings.HubName);
}
/******************************/
// client methods
/******************************/
/// <inheritdoc />
async Task IOrchestrationServiceClient.CreateTaskOrchestrationAsync(TaskMessage creationMessage)
=> await (await this.GetClientAsync()).CreateTaskOrchestrationAsync(
this.GetPartitionId(creationMessage.OrchestrationInstance.InstanceId),
creationMessage,
null);
/// <inheritdoc />
async Task IOrchestrationServiceClient.CreateTaskOrchestrationAsync(TaskMessage creationMessage, OrchestrationStatus[] dedupeStatuses)
=> await (await this.GetClientAsync()).CreateTaskOrchestrationAsync(
this.GetPartitionId(creationMessage.OrchestrationInstance.InstanceId),
creationMessage,
dedupeStatuses);
/// <inheritdoc />
async Task IOrchestrationServiceClient.SendTaskOrchestrationMessageAsync(TaskMessage message)
=> await (await this.GetClientAsync()).SendTaskOrchestrationMessageBatchAsync(
this.GetPartitionId(message.OrchestrationInstance.InstanceId),
new[] { message });
/// <inheritdoc />
async Task IOrchestrationServiceClient.SendTaskOrchestrationMessageBatchAsync(params TaskMessage[] messages)
{
var client = await this.GetClientAsync();
if (messages.Length != 0)
{
await Task.WhenAll(messages
.GroupBy(tm => this.GetPartitionId(tm.OrchestrationInstance.InstanceId))
.Select(group => client.SendTaskOrchestrationMessageBatchAsync(group.Key, group))
.ToList());
}
}
/// <inheritdoc />
async Task<OrchestrationState> IOrchestrationServiceClient.WaitForOrchestrationAsync(
string instanceId,
string executionId,
TimeSpan timeout,
CancellationToken cancellationToken)
=> await (await this.GetClientAsync()).WaitForOrchestrationAsync(
this.GetPartitionId(instanceId),
instanceId,
executionId,
timeout,
cancellationToken);
/// <inheritdoc />
async Task<OrchestrationState> IOrchestrationServiceClient.GetOrchestrationStateAsync(
string instanceId,
string executionId)
{
var state = await (await this.GetClientAsync()).GetOrchestrationStateAsync(this.GetPartitionId(instanceId), instanceId, true).ConfigureAwait(false);
return state != null && (executionId == null || executionId == state.OrchestrationInstance.ExecutionId)
? state
: null;
}
/// <inheritdoc />
async Task<IList<OrchestrationState>> IOrchestrationServiceClient.GetOrchestrationStateAsync(
string instanceId,
bool allExecutions)
{
// note: allExecutions is always ignored because storage contains never more than one execution.
var state = await (await this.GetClientAsync()).GetOrchestrationStateAsync(this.GetPartitionId(instanceId), instanceId, true).ConfigureAwait(false);
return state != null
? (new[] { state })
: (new OrchestrationState[0]);
}
/// <inheritdoc />
async Task IOrchestrationServiceClient.ForceTerminateTaskOrchestrationAsync(
string instanceId,
string message)
=> await (await this.GetClientAsync()).ForceTerminateTaskOrchestrationAsync(this.GetPartitionId(instanceId), instanceId, message);
/// <inheritdoc />
async Task<string> IOrchestrationServiceClient.GetOrchestrationHistoryAsync(
string instanceId,
string executionId)
{
var client = await this.GetClientAsync();
(string actualExecutionId, IList<HistoryEvent> history) =
await client.GetOrchestrationHistoryAsync(this.GetPartitionId(instanceId), instanceId).ConfigureAwait(false);
if (history != null && (executionId == null || executionId == actualExecutionId))
{
return JsonConvert.SerializeObject(history);
}
else
{
return JsonConvert.SerializeObject(new List<HistoryEvent>());
}
}
/// <inheritdoc />
async Task IOrchestrationServiceClient.PurgeOrchestrationHistoryAsync(
DateTime thresholdDateTimeUtc,
OrchestrationStateTimeRangeFilterType
timeRangeFilterType)
{
if (timeRangeFilterType != OrchestrationStateTimeRangeFilterType.OrchestrationCreatedTimeFilter)
{
throw new NotSupportedException("Purging is supported only for Orchestration created time filter.");
}
await (await this.GetClientAsync()).PurgeInstanceHistoryAsync(thresholdDateTimeUtc, null, null);
}
/// <inheritdoc />
async Task<OrchestrationState> IOrchestrationServiceQueryClient.GetOrchestrationStateAsync(string instanceId, bool fetchInput, bool fetchOutput)
{
return await (await this.GetClientAsync()).GetOrchestrationStateAsync(this.GetPartitionId(instanceId), instanceId, fetchInput, fetchOutput);
}
/// <inheritdoc />
async Task<IList<OrchestrationState>> IOrchestrationServiceQueryClient.GetAllOrchestrationStatesAsync(CancellationToken cancellationToken)
=> await (await this.GetClientAsync()).GetOrchestrationStateAsync(cancellationToken);
/// <inheritdoc />
async Task<IList<OrchestrationState>> IOrchestrationServiceQueryClient.GetOrchestrationStateAsync(DateTime? CreatedTimeFrom, DateTime? CreatedTimeTo, IEnumerable<OrchestrationStatus> RuntimeStatus, string InstanceIdPrefix, CancellationToken CancellationToken)
=> await (await this.GetClientAsync()).GetOrchestrationStateAsync(CreatedTimeFrom, CreatedTimeTo, RuntimeStatus, InstanceIdPrefix, CancellationToken);
/// <inheritdoc />
async Task<int> IOrchestrationServiceQueryClient.PurgeInstanceHistoryAsync(string instanceId)
=> await (await this.GetClientAsync()).DeleteAllDataForOrchestrationInstance(this.GetPartitionId(instanceId), instanceId);
/// <inheritdoc />
async Task<int> IOrchestrationServiceQueryClient.PurgeInstanceHistoryAsync(DateTime createdTimeFrom, DateTime? createdTimeTo, IEnumerable<OrchestrationStatus> runtimeStatus)
=> await (await this.GetClientAsync()).PurgeInstanceHistoryAsync(createdTimeFrom, createdTimeTo, runtimeStatus);
/// <inheritdoc />
async Task<InstanceQueryResult> IOrchestrationServiceQueryClient.QueryOrchestrationStatesAsync(InstanceQuery instanceQuery, int pageSize, string continuationToken, CancellationToken cancellationToken)
=> await (await this.GetClientAsync()).QueryOrchestrationStatesAsync(instanceQuery, pageSize, continuationToken, cancellationToken);
/******************************/
// Task orchestration methods
/******************************/
async Task<TaskOrchestrationWorkItem> IOrchestrationService.LockNextTaskOrchestrationWorkItemAsync(
TimeSpan receiveTimeout,
CancellationToken cancellationToken)
{
var nextOrchestrationWorkItem = await this.OrchestrationWorkItemQueue.GetNext(receiveTimeout, cancellationToken).ConfigureAwait(false);
if (nextOrchestrationWorkItem != null)
{
nextOrchestrationWorkItem.MessageBatch.WaitingSince = null;
this.workItemTraceHelper.TraceWorkItemStarted(
nextOrchestrationWorkItem.Partition.PartitionId,
WorkItemTraceHelper.WorkItemType.Orchestration,
nextOrchestrationWorkItem.MessageBatch.WorkItemId,
nextOrchestrationWorkItem.MessageBatch.InstanceId,
nextOrchestrationWorkItem.Type.ToString(),
WorkItemTraceHelper.FormatMessageIdList(nextOrchestrationWorkItem.MessageBatch.TracedMessages));
nextOrchestrationWorkItem.StartedAt = this.workItemStopwatch.Elapsed.TotalMilliseconds;
}
return nextOrchestrationWorkItem;
}
Task IOrchestrationService.CompleteTaskOrchestrationWorkItemAsync(
TaskOrchestrationWorkItem workItem,
OrchestrationRuntimeState newOrchestrationRuntimeState,
IList<TaskMessage> activityMessages,
IList<TaskMessage> orchestratorMessages,
IList<TaskMessage> timerMessages,
TaskMessage continuedAsNewMessage,
OrchestrationState state)
{
var orchestrationWorkItem = (OrchestrationWorkItem)workItem;
var messageBatch = orchestrationWorkItem.MessageBatch;
var partition = orchestrationWorkItem.Partition;
var latencyMs = this.workItemStopwatch.Elapsed.TotalMilliseconds - orchestrationWorkItem.StartedAt;
List<TaskMessage> localMessages = null;
List<TaskMessage> remoteMessages = null;
// DurableTask.Core keeps the original runtime state in the work item until after this call returns
// but we want it to contain the latest runtime state now (otherwise IsExecutableInstance returns incorrect results)
// so we update it now.
workItem.OrchestrationRuntimeState = newOrchestrationRuntimeState;
// all continue as new requests are processed immediately (DurableTask.Core always uses "fast" continue-as-new)
// so by the time we get here, it is not a continue as new
partition.Assert(continuedAsNewMessage == null, "unexpected continueAsNew message");
partition.Assert(workItem.OrchestrationRuntimeState.OrchestrationStatus != OrchestrationStatus.ContinuedAsNew, "unexpected continueAsNew status");
// we assign sequence numbers to all outgoing messages, to help us track them using unique message ids
long sequenceNumber = 0;
if (activityMessages != null)
{
foreach(TaskMessage taskMessage in activityMessages)
{
taskMessage.SequenceNumber = sequenceNumber++;
}
}
if (orchestratorMessages != null)
{
foreach (TaskMessage taskMessage in orchestratorMessages)
{
taskMessage.SequenceNumber = sequenceNumber++;
if (partition.PartitionId == partition.PartitionFunction(taskMessage.OrchestrationInstance.InstanceId))
{
if (Entities.IsDelayedEntityMessage(taskMessage, out _))
{
(timerMessages ??= new List<TaskMessage>()).Add(taskMessage);
}
else if (taskMessage.Event is ExecutionStartedEvent executionStartedEvent && executionStartedEvent.ScheduledStartTime.HasValue)
{
(timerMessages ??= new List<TaskMessage>()).Add(taskMessage);
}
else
{
(localMessages ??= new List<TaskMessage>()).Add(taskMessage);
}
}
else
{
(remoteMessages ??= new List<TaskMessage>()).Add(taskMessage);
}
}
}
if (timerMessages != null)
{
foreach (TaskMessage taskMessage in timerMessages)
{
taskMessage.SequenceNumber = sequenceNumber++;
}
}
if (partition.ErrorHandler.IsTerminated)
{
// we get here if the partition was terminated. The work is thrown away.
// It's unavoidable by design, but let's at least create a warning.
this.workItemTraceHelper.TraceWorkItemDiscarded(
partition.PartitionId,
WorkItemTraceHelper.WorkItemType.Orchestration,
messageBatch.WorkItemId,
workItem.InstanceId,
"",
"partition was terminated");
return Task.CompletedTask;
}
// if this orchestration is not done, and extended sessions are enabled, we keep the work item so we can reuse the execution cursor
bool cacheWorkItemForReuse = partition.Settings.CacheOrchestrationCursors && state.OrchestrationStatus == OrchestrationStatus.Running;
BatchProcessed batchProcessedEvent = new BatchProcessed()
{
PartitionId = partition.PartitionId,
SessionId = messageBatch.SessionId,
InstanceId = workItem.InstanceId,
BatchStartPosition = messageBatch.BatchStartPosition,
BatchLength = messageBatch.BatchLength,
NewEvents = (List<HistoryEvent>)newOrchestrationRuntimeState.NewEvents,
WorkItemForReuse = cacheWorkItemForReuse ? orchestrationWorkItem : null,
PackPartitionTaskMessages = partition.Settings.PackPartitionTaskMessages,
PersistFirst = partition.Settings.PersistStepsFirst ? BatchProcessed.PersistFirstStatus.Required : BatchProcessed.PersistFirstStatus.NotRequired,
OrchestrationStatus = state.OrchestrationStatus,
ExecutionId = state.OrchestrationInstance.ExecutionId,
ActivityMessages = (List<TaskMessage>)activityMessages,
LocalMessages = localMessages,
RemoteMessages = remoteMessages,
TimerMessages = (List<TaskMessage>)timerMessages,
Timestamp = state.LastUpdatedTime,
};
if (state.Status != orchestrationWorkItem.CustomStatus)
{
orchestrationWorkItem.CustomStatus = state.Status;
batchProcessedEvent.CustomStatusUpdated = true;
batchProcessedEvent.CustomStatus = state.Status;
}
this.workItemTraceHelper.TraceWorkItemCompleted(
partition.PartitionId,
WorkItemTraceHelper.WorkItemType.Orchestration,
messageBatch.WorkItemId,
workItem.InstanceId,
batchProcessedEvent.OrchestrationStatus,
latencyMs,
sequenceNumber);
partition.SubmitEvent(batchProcessedEvent);
if (this.workItemTraceHelper.TraceTaskMessages)
{
foreach (var taskMessage in batchProcessedEvent.LoopBackMessages())
{
this.workItemTraceHelper.TraceTaskMessageSent(partition.PartitionId, taskMessage, messageBatch.WorkItemId, null, null);
}
}
return Task.CompletedTask;
}
Task IOrchestrationService.AbandonTaskOrchestrationWorkItemAsync(TaskOrchestrationWorkItem workItem)
{
// We can get here due to transient execution failures of the functions runtime.
// In order to guarantee the work is done, we must enqueue a new work item.
var orchestrationWorkItem = (OrchestrationWorkItem)workItem;
var originalHistorySize = orchestrationWorkItem.OrchestrationRuntimeState.Events.Count - orchestrationWorkItem.OrchestrationRuntimeState.NewEvents.Count;
var originalCustomStatus = orchestrationWorkItem.OrchestrationRuntimeState.Status;
var originalHistory = orchestrationWorkItem.OrchestrationRuntimeState.Events.Take(originalHistorySize).ToList();
var newWorkItem = new OrchestrationWorkItem(orchestrationWorkItem.Partition, orchestrationWorkItem.MessageBatch, originalHistory, originalCustomStatus);
newWorkItem.Type = OrchestrationWorkItem.ExecutionType.ContinueFromHistory;
newWorkItem.HistorySize = originalHistory.Count;
orchestrationWorkItem.Partition.EnqueueOrchestrationWorkItem(newWorkItem);
return Task.CompletedTask;
}
Task IOrchestrationService.ReleaseTaskOrchestrationWorkItemAsync(TaskOrchestrationWorkItem workItem)
{
return Task.CompletedTask;
}
Task IOrchestrationService.RenewTaskOrchestrationWorkItemLockAsync(TaskOrchestrationWorkItem workItem)
{
// no renewal required. Work items never time out.
return Task.FromResult(workItem);
}
BehaviorOnContinueAsNew IOrchestrationService.EventBehaviourForContinueAsNew
=> this.Settings.EventBehaviourForContinueAsNew;
bool IOrchestrationService.IsMaxMessageCountExceeded(int currentMessageCount, OrchestrationRuntimeState runtimeState)
{
return false;
}
int IOrchestrationService.GetDelayInSecondsAfterOnProcessException(Exception exception)
{
return 0;
}
int IOrchestrationService.GetDelayInSecondsAfterOnFetchException(Exception exception)
{
return 0;
}
int IOrchestrationService.MaxConcurrentTaskOrchestrationWorkItems => this.Settings.MaxConcurrentOrchestratorFunctions;
int IOrchestrationService.TaskOrchestrationDispatcherCount => this.Settings.OrchestrationDispatcherCount;
/******************************/
// Task activity methods
/******************************/
async Task<TaskActivityWorkItem> IOrchestrationService.LockNextTaskActivityWorkItem(TimeSpan receiveTimeout, CancellationToken cancellationToken)
{
var nextActivityWorkItem = await this.ActivityWorkItemQueue.GetNext(receiveTimeout, cancellationToken).ConfigureAwait(false);
if (nextActivityWorkItem != null)
{
if (nextActivityWorkItem.WaitForDequeueCountPersistence != null)
{
await nextActivityWorkItem.WaitForDequeueCountPersistence.Task;
}
this.workItemTraceHelper.TraceWorkItemStarted(
nextActivityWorkItem.Partition.PartitionId,
WorkItemTraceHelper.WorkItemType.Activity,
nextActivityWorkItem.WorkItemId,
nextActivityWorkItem.TaskMessage.OrchestrationInstance.InstanceId,
nextActivityWorkItem.ExecutionType,
WorkItemTraceHelper.FormatMessageId(nextActivityWorkItem.TaskMessage, nextActivityWorkItem.OriginWorkItem));
nextActivityWorkItem.StartedAt = this.workItemStopwatch.Elapsed.TotalMilliseconds;
}
return nextActivityWorkItem;
}
Task IOrchestrationService.AbandonTaskActivityWorkItemAsync(TaskActivityWorkItem workItem)
{
// put it back into the work queue
this.ActivityWorkItemQueue.Add((ActivityWorkItem)workItem);
return Task.CompletedTask;
}
Task IOrchestrationService.CompleteTaskActivityWorkItemAsync(TaskActivityWorkItem workItem, TaskMessage responseMessage)
{
var activityWorkItem = (ActivityWorkItem)workItem;
var partition = activityWorkItem.Partition;
var latencyMs = this.workItemStopwatch.Elapsed.TotalMilliseconds - activityWorkItem.StartedAt;
var activityCompletedEvent = new ActivityCompleted()
{
PartitionId = activityWorkItem.Partition.PartitionId,
ActivityId = activityWorkItem.ActivityId,
OriginPartitionId = activityWorkItem.OriginPartition,
ReportedLoad = this.ActivityWorkItemQueue.Load,
Timestamp = DateTime.UtcNow,
LatencyMs = latencyMs,
Response = responseMessage,
};
if (partition.ErrorHandler.IsTerminated)
{
// we get here if the partition was terminated. The work is thrown away.
// It's unavoidable by design, but let's at least create a warning.
this.workItemTraceHelper.TraceWorkItemDiscarded(
partition.PartitionId,
WorkItemTraceHelper.WorkItemType.Activity,
activityWorkItem.WorkItemId,
activityWorkItem.TaskMessage.OrchestrationInstance.InstanceId,
"",
"partition was terminated"
);
return Task.CompletedTask;
}
this.workItemTraceHelper.TraceWorkItemCompleted(
partition.PartitionId,
WorkItemTraceHelper.WorkItemType.Activity,
activityWorkItem.WorkItemId,
activityWorkItem.TaskMessage.OrchestrationInstance.InstanceId,
WorkItemTraceHelper.ActivityStatus.Completed,