-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathProtoUtils.cs
More file actions
1312 lines (1193 loc) · 56.5 KB
/
ProtoUtils.cs
File metadata and controls
1312 lines (1193 loc) · 56.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 (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Buffers;
using System.Buffers.Text;
using System.Collections;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Text.Json;
using DurableTask.Core;
using DurableTask.Core.Command;
using DurableTask.Core.Entities;
using DurableTask.Core.Entities.OperationFormat;
using DurableTask.Core.History;
using DurableTask.Core.Tracing;
using Google.Protobuf;
using Google.Protobuf.Collections;
using Google.Protobuf.WellKnownTypes;
using DTCore = DurableTask.Core;
using P = Microsoft.DurableTask.Protobuf;
using TraceHelper = Microsoft.DurableTask.Tracing.TraceHelper;
namespace Microsoft.DurableTask;
/// <summary>
/// Protobuf utilities and helpers.
/// </summary>
static class ProtoUtils
{
/// <summary>
/// Converts a history event from <see cref="P.HistoryEvent" /> to <see cref="HistoryEvent" />.
/// </summary>
/// <param name="proto">The proto history event to converter.</param>
/// <returns>The converted history event.</returns>
/// <exception cref="NotSupportedException">When the provided history event type is not supported.</exception>
internal static HistoryEvent ConvertHistoryEvent(P.HistoryEvent proto)
{
return ConvertHistoryEvent(proto, conversionState: null);
}
/// <summary>
/// Converts a history event from <see cref="P.HistoryEvent" /> to <see cref="HistoryEvent"/>, and performs
/// stateful conversions of entity-related events.
/// </summary>
/// <param name="proto">The proto history event to converter.</param>
/// <param name="conversionState">State needed for converting entity-related history entries and actions.</param>
/// <returns>The converted history event.</returns>
/// <exception cref="NotSupportedException">When the provided history event type is not supported.</exception>
internal static HistoryEvent ConvertHistoryEvent(P.HistoryEvent proto, EntityConversionState? conversionState)
{
Check.NotNull(proto);
HistoryEvent historyEvent;
switch (proto.EventTypeCase)
{
case P.HistoryEvent.EventTypeOneofCase.ContinueAsNew:
historyEvent = new ContinueAsNewEvent(proto.EventId, proto.ContinueAsNew.Input);
break;
case P.HistoryEvent.EventTypeOneofCase.ExecutionStarted:
OrchestrationInstance instance = proto.ExecutionStarted.OrchestrationInstance.ToCore();
conversionState?.SetOrchestrationInstance(instance);
historyEvent = new ExecutionStartedEvent(proto.EventId, proto.ExecutionStarted.Input)
{
Name = proto.ExecutionStarted.Name,
Version = proto.ExecutionStarted.Version,
OrchestrationInstance = instance,
Tags = proto.ExecutionStarted.Tags,
ParentInstance = proto.ExecutionStarted.ParentInstance == null ? null : new ParentInstance
{
Name = proto.ExecutionStarted.ParentInstance.Name,
Version = proto.ExecutionStarted.ParentInstance.Version,
OrchestrationInstance = proto.ExecutionStarted.ParentInstance.OrchestrationInstance.ToCore(),
TaskScheduleId = proto.ExecutionStarted.ParentInstance.TaskScheduledId,
},
ScheduledStartTime = proto.ExecutionStarted.ScheduledStartTimestamp?.ToDateTime(),
};
break;
case P.HistoryEvent.EventTypeOneofCase.ExecutionCompleted:
historyEvent = new ExecutionCompletedEvent(
proto.EventId,
proto.ExecutionCompleted.Result,
proto.ExecutionCompleted.OrchestrationStatus.ToCore(),
proto.ExecutionCompleted.FailureDetails.ToCore());
break;
case P.HistoryEvent.EventTypeOneofCase.ExecutionTerminated:
historyEvent = new ExecutionTerminatedEvent(proto.EventId, proto.ExecutionTerminated.Input);
break;
case P.HistoryEvent.EventTypeOneofCase.ExecutionSuspended:
historyEvent = new ExecutionSuspendedEvent(proto.EventId, proto.ExecutionSuspended.Input);
break;
case P.HistoryEvent.EventTypeOneofCase.ExecutionResumed:
historyEvent = new ExecutionResumedEvent(proto.EventId, proto.ExecutionResumed.Input);
break;
case P.HistoryEvent.EventTypeOneofCase.TaskScheduled:
historyEvent = new TaskScheduledEvent(
proto.EventId,
proto.TaskScheduled.Name,
proto.TaskScheduled.Version,
proto.TaskScheduled.Input)
{
Tags = proto.TaskScheduled.Tags,
};
break;
case P.HistoryEvent.EventTypeOneofCase.TaskCompleted:
historyEvent = new TaskCompletedEvent(
proto.EventId,
proto.TaskCompleted.TaskScheduledId,
proto.TaskCompleted.Result);
break;
case P.HistoryEvent.EventTypeOneofCase.TaskFailed:
historyEvent = new TaskFailedEvent(
proto.EventId,
proto.TaskFailed.TaskScheduledId,
reason: null, /* not supported */
details: null, /* not supported */
proto.TaskFailed.FailureDetails.ToCore());
break;
case P.HistoryEvent.EventTypeOneofCase.SubOrchestrationInstanceCreated:
historyEvent = new SubOrchestrationInstanceCreatedEvent(proto.EventId)
{
Input = proto.SubOrchestrationInstanceCreated.Input,
InstanceId = proto.SubOrchestrationInstanceCreated.InstanceId,
Name = proto.SubOrchestrationInstanceCreated.Name,
Version = proto.SubOrchestrationInstanceCreated.Version,
};
break;
case P.HistoryEvent.EventTypeOneofCase.SubOrchestrationInstanceCompleted:
historyEvent = new SubOrchestrationInstanceCompletedEvent(
proto.EventId,
proto.SubOrchestrationInstanceCompleted.TaskScheduledId,
proto.SubOrchestrationInstanceCompleted.Result);
break;
case P.HistoryEvent.EventTypeOneofCase.SubOrchestrationInstanceFailed:
historyEvent = new SubOrchestrationInstanceFailedEvent(
proto.EventId,
proto.SubOrchestrationInstanceFailed.TaskScheduledId,
reason: null /* not supported */,
details: null /* not supported */,
proto.SubOrchestrationInstanceFailed.FailureDetails.ToCore());
break;
case P.HistoryEvent.EventTypeOneofCase.TimerCreated:
historyEvent = new TimerCreatedEvent(
proto.EventId,
proto.TimerCreated.FireAt.ToDateTime());
break;
case P.HistoryEvent.EventTypeOneofCase.TimerFired:
historyEvent = new TimerFiredEvent(
eventId: -1,
proto.TimerFired.FireAt.ToDateTime())
{
TimerId = proto.TimerFired.TimerId,
};
break;
case P.HistoryEvent.EventTypeOneofCase.OrchestratorStarted:
historyEvent = new OrchestratorStartedEvent(proto.EventId);
break;
case P.HistoryEvent.EventTypeOneofCase.OrchestratorCompleted:
historyEvent = new OrchestratorCompletedEvent(proto.EventId);
break;
case P.HistoryEvent.EventTypeOneofCase.EventSent:
historyEvent = new EventSentEvent(proto.EventId)
{
InstanceId = proto.EventSent.InstanceId,
Name = proto.EventSent.Name,
Input = proto.EventSent.Input,
};
break;
case P.HistoryEvent.EventTypeOneofCase.EventRaised:
historyEvent = new EventRaisedEvent(proto.EventId, proto.EventRaised.Input)
{
Name = proto.EventRaised.Name,
};
break;
case P.HistoryEvent.EventTypeOneofCase.EntityOperationCalled:
historyEvent = EntityConversions.EncodeOperationCalled(proto, conversionState!.CurrentInstance);
conversionState?.EntityRequestIds.Add(proto.EntityOperationCalled.RequestId);
break;
case P.HistoryEvent.EventTypeOneofCase.EntityOperationSignaled:
historyEvent = EntityConversions.EncodeOperationSignaled(proto);
conversionState?.EntityRequestIds.Add(proto.EntityOperationSignaled.RequestId);
break;
case P.HistoryEvent.EventTypeOneofCase.EntityLockRequested:
historyEvent = EntityConversions.EncodeLockRequested(proto, conversionState!.CurrentInstance);
conversionState?.AddUnlockObligations(proto.EntityLockRequested);
break;
case P.HistoryEvent.EventTypeOneofCase.EntityUnlockSent:
historyEvent = EntityConversions.EncodeUnlockSent(proto, conversionState!.CurrentInstance);
conversionState?.RemoveUnlockObligation(proto.EntityUnlockSent.TargetInstanceId);
break;
case P.HistoryEvent.EventTypeOneofCase.EntityLockGranted:
historyEvent = EntityConversions.EncodeLockGranted(proto);
break;
case P.HistoryEvent.EventTypeOneofCase.EntityOperationCompleted:
historyEvent = EntityConversions.EncodeOperationCompleted(proto);
break;
case P.HistoryEvent.EventTypeOneofCase.EntityOperationFailed:
historyEvent = EntityConversions.EncodeOperationFailed(proto);
break;
case P.HistoryEvent.EventTypeOneofCase.GenericEvent:
historyEvent = new GenericEvent(proto.EventId, proto.GenericEvent.Data);
break;
case P.HistoryEvent.EventTypeOneofCase.HistoryState:
historyEvent = new HistoryStateEvent(
proto.EventId,
new OrchestrationState
{
OrchestrationInstance = new OrchestrationInstance
{
InstanceId = proto.HistoryState.OrchestrationState.InstanceId,
},
Name = proto.HistoryState.OrchestrationState.Name,
Version = proto.HistoryState.OrchestrationState.Version,
ScheduledStartTime = proto.HistoryState.OrchestrationState.ScheduledStartTimestamp.ToDateTime(),
CreatedTime = proto.HistoryState.OrchestrationState.CreatedTimestamp.ToDateTime(),
LastUpdatedTime = proto.HistoryState.OrchestrationState.LastUpdatedTimestamp.ToDateTime(),
Input = proto.HistoryState.OrchestrationState.Input,
Output = proto.HistoryState.OrchestrationState.Output,
Status = proto.HistoryState.OrchestrationState.CustomStatus,
Tags = proto.HistoryState.OrchestrationState.Tags,
});
break;
case P.HistoryEvent.EventTypeOneofCase.ExecutionRewound:
historyEvent = new ExecutionRewoundEvent(proto.EventId);
break;
default:
throw new NotSupportedException($"Deserialization of {proto.EventTypeCase} is not supported.");
}
historyEvent.Timestamp = proto.Timestamp.ToDateTime();
return historyEvent;
}
/// <summary>
/// Converts a <see cref="DateTime" /> to a gRPC <see cref="Timestamp" />.
/// </summary>
/// <param name="dateTime">The date-time to convert.</param>
/// <returns>The gRPC timestamp.</returns>
internal static Timestamp ToTimestamp(this DateTime dateTime)
{
// The protobuf libraries require timestamps to be in UTC
if (dateTime.Kind == DateTimeKind.Unspecified)
{
dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
}
else if (dateTime.Kind == DateTimeKind.Local)
{
dateTime = dateTime.ToUniversalTime();
}
return Timestamp.FromDateTime(dateTime);
}
/// <summary>
/// Converts a <see cref="DateTime" /> to a gRPC <see cref="Timestamp" />.
/// </summary>
/// <param name="dateTime">The date-time to convert.</param>
/// <returns>The gRPC timestamp.</returns>
internal static Timestamp? ToTimestamp(this DateTime? dateTime)
=> dateTime.HasValue ? dateTime.Value.ToTimestamp() : null;
/// <summary>
/// Converts a <see cref="DateTimeOffset" /> to a gRPC <see cref="Timestamp" />.
/// </summary>
/// <param name="dateTime">The date-time to convert.</param>
/// <returns>The gRPC timestamp.</returns>
internal static Timestamp ToTimestamp(this DateTimeOffset dateTime) => Timestamp.FromDateTimeOffset(dateTime);
/// <summary>
/// Converts a <see cref="DateTimeOffset" /> to a gRPC <see cref="Timestamp" />.
/// </summary>
/// <param name="dateTime">The date-time to convert.</param>
/// <returns>The gRPC timestamp.</returns>
internal static Timestamp? ToTimestamp(this DateTimeOffset? dateTime)
=> dateTime.HasValue ? dateTime.Value.ToTimestamp() : null;
/// <summary>
/// Constructs a <see cref="P.OrchestratorResponse" />.
/// </summary>
/// <param name="instanceId">The orchestrator instance ID.</param>
/// <param name="executionId">The orchestrator execution ID.</param>
/// <param name="customStatus">The orchestrator customer status or <c>null</c> if no custom status.</param>
/// <param name="actions">The orchestrator actions.</param>
/// <param name="completionToken">
/// The completion token for the work item. It must be the exact same <see cref="P.WorkItem.CompletionToken" />
/// value that was provided by the corresponding <see cref="P.WorkItem"/> that triggered the orchestrator execution.
/// </param>
/// <param name="entityConversionState">The entity conversion state, or null if no conversion is required.</param>
/// <param name="orchestrationActivity">The <see cref="Activity" /> that represents orchestration execution.</param>
/// <param name="requiresHistory">Whether or not a history is required to complete the orchestration request and none was provided.</param>
/// <returns>The orchestrator response.</returns>
/// <exception cref="NotSupportedException">When an orchestrator action is unknown.</exception>
internal static P.OrchestratorResponse ConstructOrchestratorResponse(
string instanceId,
string executionId,
string? customStatus,
IEnumerable<OrchestratorAction>? actions,
string completionToken,
EntityConversionState? entityConversionState,
Activity? orchestrationActivity,
bool requiresHistory = false)
{
var response = new P.OrchestratorResponse
{
InstanceId = instanceId,
CustomStatus = customStatus,
CompletionToken = completionToken,
OrchestrationTraceContext =
new()
{
SpanID = orchestrationActivity?.SpanId.ToString(),
SpanStartTime = orchestrationActivity?.StartTimeUtc.ToTimestamp(),
},
RequiresHistory = requiresHistory,
};
// If a history is required and the orchestration request was not completed, then there is no list of actions.
if (requiresHistory)
{
return response;
}
Check.NotNull(actions);
foreach (OrchestratorAction action in actions)
{
var protoAction = new P.OrchestratorAction { Id = action.Id };
P.TraceContext? CreateTraceContext()
{
if (orchestrationActivity is null)
{
return null;
}
ActivitySpanId clientSpanId = ActivitySpanId.CreateRandom();
ActivityContext clientActivityContext = new(orchestrationActivity.TraceId, clientSpanId, orchestrationActivity.ActivityTraceFlags, orchestrationActivity.TraceStateString);
return new P.TraceContext
{
TraceParent = $"00-{clientActivityContext.TraceId}-{clientActivityContext.SpanId}-0{clientActivityContext.TraceFlags:d}",
TraceState = clientActivityContext.TraceState,
};
}
switch (action.OrchestratorActionType)
{
case OrchestratorActionType.ScheduleOrchestrator:
var scheduleTaskAction = (ScheduleTaskOrchestratorAction)action;
protoAction.ScheduleTask = new P.ScheduleTaskAction
{
Name = scheduleTaskAction.Name,
Version = scheduleTaskAction.Version,
Input = scheduleTaskAction.Input,
ParentTraceContext = CreateTraceContext(),
};
if (scheduleTaskAction.Tags != null)
{
foreach (KeyValuePair<string, string> tag in scheduleTaskAction.Tags)
{
protoAction.ScheduleTask.Tags[tag.Key] = tag.Value;
}
}
break;
case OrchestratorActionType.CreateSubOrchestration:
var subOrchestrationAction = (CreateSubOrchestrationAction)action;
protoAction.CreateSubOrchestration = new P.CreateSubOrchestrationAction
{
Input = subOrchestrationAction.Input,
InstanceId = subOrchestrationAction.InstanceId,
Name = subOrchestrationAction.Name,
Version = subOrchestrationAction.Version,
ParentTraceContext = CreateTraceContext(),
};
if (subOrchestrationAction.Tags != null)
{
foreach (KeyValuePair<string, string> tag in subOrchestrationAction.Tags)
{
protoAction.CreateSubOrchestration.Tags[tag.Key] = tag.Value;
}
}
break;
case OrchestratorActionType.CreateTimer:
var createTimerAction = (CreateTimerOrchestratorAction)action;
protoAction.CreateTimer = new P.CreateTimerAction
{
FireAt = createTimerAction.FireAt.ToTimestamp(),
};
break;
case OrchestratorActionType.SendEvent:
var sendEventAction = (SendEventOrchestratorAction)action;
if (sendEventAction.Instance == null)
{
throw new ArgumentException(
$"{nameof(SendEventOrchestratorAction)} cannot have a null Instance property!");
}
if (entityConversionState is not null
&& DTCore.Common.Entities.IsEntityInstance(sendEventAction.Instance.InstanceId)
&& sendEventAction.EventName is not null
&& sendEventAction.EventData is not null)
{
P.SendEntityMessageAction sendAction = new P.SendEntityMessageAction();
protoAction.SendEntityMessage = sendAction;
EntityConversions.DecodeEntityMessageAction(
sendEventAction.EventName,
sendEventAction.EventData,
sendEventAction.Instance.InstanceId,
sendAction,
out string requestId);
entityConversionState.EntityRequestIds.Add(requestId);
sendAction.ParentTraceContext = CreateTraceContext();
switch (sendAction.EntityMessageTypeCase)
{
case P.SendEntityMessageAction.EntityMessageTypeOneofCase.EntityLockRequested:
entityConversionState.AddUnlockObligations(sendAction.EntityLockRequested);
break;
case P.SendEntityMessageAction.EntityMessageTypeOneofCase.EntityUnlockSent:
entityConversionState.RemoveUnlockObligation(sendAction.EntityUnlockSent.TargetInstanceId);
break;
default:
break;
}
}
else
{
protoAction.SendEvent = new P.SendEventAction
{
Instance = sendEventAction.Instance.ToProtobuf(),
Name = sendEventAction.EventName,
Data = sendEventAction.EventData,
};
// Distributed Tracing: start a new trace activity derived from the orchestration
// for an EventRaisedEvent (external event)
using Activity? traceActivity = TraceHelper.StartTraceActivityForEventRaisedFromWorker(sendEventAction, instanceId, executionId);
traceActivity?.Stop();
}
break;
case OrchestratorActionType.OrchestrationComplete:
if (entityConversionState is not null)
{
// as a precaution, unlock any entities that were not unlocked for some reason, before
// completing the orchestration.
foreach ((string target, string criticalSectionId) in entityConversionState.ResetObligations())
{
response.Actions.Add(new P.OrchestratorAction
{
Id = action.Id,
SendEntityMessage = new P.SendEntityMessageAction
{
EntityUnlockSent = new P.EntityUnlockSentEvent
{
CriticalSectionId = criticalSectionId,
TargetInstanceId = target,
ParentInstanceId = entityConversionState.CurrentInstance?.InstanceId,
},
},
});
}
}
var completeAction = (OrchestrationCompleteOrchestratorAction)action;
protoAction.CompleteOrchestration = new P.CompleteOrchestrationAction
{
CarryoverEvents = { completeAction.CarryoverEvents.Select(ToProtobuf) },
Details = completeAction.Details,
NewVersion = completeAction.NewVersion,
OrchestrationStatus = completeAction.OrchestrationStatus.ToProtobuf(),
Result = completeAction.Result,
};
foreach (KeyValuePair<string, string> tag in completeAction.Tags)
{
protoAction.CompleteOrchestration.Tags[tag.Key] = tag.Value;
}
if (completeAction.OrchestrationStatus == OrchestrationStatus.Failed)
{
protoAction.CompleteOrchestration.FailureDetails = completeAction.FailureDetails.ToProtobuf();
}
break;
default:
throw new NotSupportedException($"Unknown orchestrator action: {action.OrchestratorActionType}");
}
response.Actions.Add(protoAction);
}
return response;
}
/// <summary>
/// Converts a <see cref="P.OrchestrationStatus" /> to a <see cref="OrchestrationStatus" />.
/// </summary>
/// <param name="status">The status to convert.</param>
/// <returns>The converted status.</returns>
internal static OrchestrationStatus ToCore(this P.OrchestrationStatus status)
{
return (OrchestrationStatus)status;
}
/// <summary>
/// Converts a <see cref="P.OrchestrationStatus" /> to a <see cref="OrchestrationStatus" />.
/// </summary>
/// <param name="status">The status to convert.</param>
/// <returns>The converted status.</returns>
[return: NotNullIfNotNull(nameof(status))]
internal static OrchestrationInstance? ToCore(this P.OrchestrationInstance? status)
{
if (status == null)
{
return null;
}
return new OrchestrationInstance
{
InstanceId = status.InstanceId,
ExecutionId = status.ExecutionId,
};
}
/// <summary>
/// Converts a <see cref="P.TaskFailureDetails" /> to a <see cref="TaskFailureDetails" />.
/// </summary>
/// <param name="failureDetails">The failure details to convert.</param>
/// <returns>The converted failure details.</returns>
[return: NotNullIfNotNull(nameof(failureDetails))]
internal static TaskFailureDetails? ToTaskFailureDetails(this P.TaskFailureDetails? failureDetails)
{
if (failureDetails == null)
{
return null;
}
return new TaskFailureDetails(
failureDetails.ErrorType,
failureDetails.ErrorMessage,
failureDetails.StackTrace,
failureDetails.InnerFailure.ToTaskFailureDetails(),
ConvertProperties(failureDetails.Properties));
}
/// <summary>
/// Converts a <see cref="Exception" /> to <see cref="P.TaskFailureDetails" />.
/// </summary>
/// <param name="e">The exception to convert.</param>
/// <param name="exceptionPropertiesProvider">Optional exception properties provider.</param>
/// <returns>The task failure details.</returns>
[return: NotNullIfNotNull(nameof(e))]
internal static P.TaskFailureDetails? ToTaskFailureDetails(this Exception? e, DTCore.IExceptionPropertiesProvider? exceptionPropertiesProvider = null)
{
if (e == null)
{
return null;
}
IDictionary<string, object?>? properties = exceptionPropertiesProvider?.GetExceptionProperties(e);
var taskFailureDetails = new P.TaskFailureDetails
{
ErrorType = e.GetType().FullName,
ErrorMessage = e.Message,
StackTrace = e.StackTrace,
InnerFailure = e.InnerException.ToTaskFailureDetails(exceptionPropertiesProvider),
};
if (properties != null)
{
foreach (var kvp in properties)
{
taskFailureDetails.Properties[kvp.Key] = ConvertObjectToValue(kvp.Value);
}
}
return taskFailureDetails;
}
/// <summary>
/// Converts a <see cref="P.EntityBatchRequest" /> to a <see cref="EntityBatchRequest" />.
/// </summary>
/// <param name="entityBatchRequest">The entity batch request to convert.</param>
/// <returns>The converted entity batch request.</returns>
[return: NotNullIfNotNull(nameof(entityBatchRequest))]
internal static EntityBatchRequest? ToEntityBatchRequest(this P.EntityBatchRequest? entityBatchRequest)
{
if (entityBatchRequest == null)
{
return null;
}
return new EntityBatchRequest()
{
EntityState = entityBatchRequest.EntityState,
InstanceId = entityBatchRequest.InstanceId,
Operations = entityBatchRequest.Operations.Select(r => r.ToOperationRequest()).ToList(),
};
}
/// <summary>
/// Converts a <see cref="P.EntityRequest" /> to a <see cref="EntityBatchRequest" />.
/// </summary>
/// <param name="entityRequest">The entity request to convert.</param>
/// <param name="batchRequest">The converted request.</param>
/// <param name="operationInfos">Additional info about each operation, required by DTS.</param>
internal static void ToEntityBatchRequest(
this P.EntityRequest entityRequest,
out EntityBatchRequest batchRequest,
out List<P.OperationInfo> operationInfos)
{
batchRequest = new EntityBatchRequest()
{
EntityState = entityRequest.EntityState,
InstanceId = entityRequest.InstanceId,
Operations = [], // operations are added to this collection below
};
operationInfos = new(entityRequest.OperationRequests.Count);
foreach (P.HistoryEvent? op in entityRequest.OperationRequests)
{
if (op.EntityOperationSignaled is not null)
{
batchRequest.Operations.Add(new OperationRequest
{
Id = Guid.Parse(op.EntityOperationSignaled.RequestId),
Operation = op.EntityOperationSignaled.Operation,
Input = op.EntityOperationSignaled.Input,
TraceContext = op.EntityOperationSignaled.ParentTraceContext is { } signalTc
? new DistributedTraceContext(signalTc.TraceParent, signalTc.TraceState)
: null,
});
operationInfos.Add(new P.OperationInfo
{
RequestId = op.EntityOperationSignaled.RequestId,
ResponseDestination = null, // means we don't send back a response to the caller
});
}
else if (op.EntityOperationCalled is not null)
{
batchRequest.Operations.Add(new OperationRequest
{
Id = Guid.Parse(op.EntityOperationCalled.RequestId),
Operation = op.EntityOperationCalled.Operation,
Input = op.EntityOperationCalled.Input,
TraceContext = op.EntityOperationCalled.ParentTraceContext is { } calledTc
? new DistributedTraceContext(calledTc.TraceParent, calledTc.TraceState)
: null,
});
operationInfos.Add(new P.OperationInfo
{
RequestId = op.EntityOperationCalled.RequestId,
ResponseDestination = new P.OrchestrationInstance
{
InstanceId = op.EntityOperationCalled.ParentInstanceId,
ExecutionId = op.EntityOperationCalled.ParentExecutionId,
},
});
}
}
}
/// <summary>
/// Converts a <see cref="P.OperationRequest" /> to a <see cref="OperationRequest" />.
/// </summary>
/// <param name="operationRequest">The operation request to convert.</param>
/// <returns>The converted operation request.</returns>
[return: NotNullIfNotNull(nameof(operationRequest))]
internal static OperationRequest? ToOperationRequest(this P.OperationRequest? operationRequest)
{
if (operationRequest == null)
{
return null;
}
return new OperationRequest()
{
Operation = operationRequest.Operation,
Input = operationRequest.Input,
Id = Guid.Parse(operationRequest.RequestId),
TraceContext = operationRequest.TraceContext != null ?
new DistributedTraceContext(
operationRequest.TraceContext.TraceParent,
operationRequest.TraceContext.TraceState) : null,
};
}
/// <summary>
/// Converts a <see cref="P.OperationResult" /> to a <see cref="OperationResult" />.
/// </summary>
/// <param name="operationResult">The operation result to convert.</param>
/// <returns>The converted operation result.</returns>
[return: NotNullIfNotNull(nameof(operationResult))]
internal static OperationResult? ToOperationResult(this P.OperationResult? operationResult)
{
if (operationResult == null)
{
return null;
}
switch (operationResult.ResultTypeCase)
{
case P.OperationResult.ResultTypeOneofCase.Success:
return new OperationResult()
{
Result = operationResult.Success.Result,
StartTimeUtc = operationResult.Success.StartTimeUtc?.ToDateTime(),
EndTimeUtc = operationResult.Success.EndTimeUtc?.ToDateTime(),
};
case P.OperationResult.ResultTypeOneofCase.Failure:
return new OperationResult()
{
FailureDetails = operationResult.Failure.FailureDetails.ToCore(),
StartTimeUtc = operationResult.Failure.StartTimeUtc?.ToDateTime(),
EndTimeUtc = operationResult.Failure.EndTimeUtc?.ToDateTime(),
};
default:
throw new NotSupportedException($"Deserialization of {operationResult.ResultTypeCase} is not supported.");
}
}
/// <summary>
/// Converts a <see cref="OperationResult" /> to <see cref="P.OperationResult" />.
/// </summary>
/// <param name="operationResult">The operation result to convert.</param>
/// <returns>The converted operation result.</returns>
[return: NotNullIfNotNull(nameof(operationResult))]
internal static P.OperationResult? ToOperationResult(this OperationResult? operationResult)
{
if (operationResult == null)
{
return null;
}
if (operationResult.FailureDetails == null)
{
return new P.OperationResult()
{
Success = new P.OperationResultSuccess()
{
Result = operationResult.Result,
StartTimeUtc = operationResult.StartTimeUtc?.ToTimestamp(),
EndTimeUtc = operationResult.EndTimeUtc?.ToTimestamp(),
},
};
}
else
{
return new P.OperationResult()
{
Failure = new P.OperationResultFailure()
{
FailureDetails = ToProtobuf(operationResult.FailureDetails),
StartTimeUtc = operationResult.StartTimeUtc?.ToTimestamp(),
EndTimeUtc = operationResult.EndTimeUtc?.ToTimestamp(),
},
};
}
}
/// <summary>
/// Converts a <see cref="P.OperationAction" /> to a <see cref="OperationAction" />.
/// </summary>
/// <param name="operationAction">The operation action to convert.</param>
/// <returns>The converted operation action.</returns>
[return: NotNullIfNotNull(nameof(operationAction))]
internal static OperationAction? ToOperationAction(this P.OperationAction? operationAction)
{
if (operationAction == null)
{
return null;
}
switch (operationAction.OperationActionTypeCase)
{
case P.OperationAction.OperationActionTypeOneofCase.SendSignal:
return new SendSignalOperationAction()
{
Name = operationAction.SendSignal.Name,
Input = operationAction.SendSignal.Input,
InstanceId = operationAction.SendSignal.InstanceId,
ScheduledTime = operationAction.SendSignal.ScheduledTime?.ToDateTime(),
RequestTime = operationAction.SendSignal.RequestTime?.ToDateTimeOffset(),
ParentTraceContext = operationAction.SendSignal.ParentTraceContext != null ?
new DistributedTraceContext(
operationAction.SendSignal.ParentTraceContext.TraceParent,
operationAction.SendSignal.ParentTraceContext.TraceState) : null,
};
case P.OperationAction.OperationActionTypeOneofCase.StartNewOrchestration:
return new StartNewOrchestrationOperationAction()
{
Name = operationAction.StartNewOrchestration.Name,
Input = operationAction.StartNewOrchestration.Input,
InstanceId = operationAction.StartNewOrchestration.InstanceId,
Version = operationAction.StartNewOrchestration.Version,
ScheduledStartTime = operationAction.StartNewOrchestration.ScheduledTime?.ToDateTime(),
RequestTime = operationAction.StartNewOrchestration.RequestTime?.ToDateTimeOffset(),
ParentTraceContext = operationAction.StartNewOrchestration.ParentTraceContext != null ?
new DistributedTraceContext(
operationAction.StartNewOrchestration.ParentTraceContext.TraceParent,
operationAction.StartNewOrchestration.ParentTraceContext.TraceState) : null,
};
default:
throw new NotSupportedException($"Deserialization of {operationAction.OperationActionTypeCase} is not supported.");
}
}
/// <summary>
/// Converts a <see cref="OperationAction" /> to <see cref="P.OperationAction" />.
/// </summary>
/// <param name="operationAction">The operation action to convert.</param>
/// <returns>The converted operation action.</returns>
[return: NotNullIfNotNull(nameof(operationAction))]
internal static P.OperationAction? ToOperationAction(this OperationAction? operationAction)
{
if (operationAction == null)
{
return null;
}
var action = new P.OperationAction();
switch (operationAction)
{
case SendSignalOperationAction sendSignalAction:
action.SendSignal = new P.SendSignalAction()
{
Name = sendSignalAction.Name,
Input = sendSignalAction.Input,
InstanceId = sendSignalAction.InstanceId,
ScheduledTime = sendSignalAction.ScheduledTime?.ToTimestamp(),
RequestTime = sendSignalAction.RequestTime?.ToTimestamp(),
ParentTraceContext = sendSignalAction.ParentTraceContext != null ?
new P.TraceContext
{
TraceParent = sendSignalAction.ParentTraceContext.TraceParent,
TraceState = sendSignalAction.ParentTraceContext.TraceState,
}
: null,
};
break;
case StartNewOrchestrationOperationAction startNewOrchestrationAction:
action.StartNewOrchestration = new P.StartNewOrchestrationAction()
{
Name = startNewOrchestrationAction.Name,
Input = startNewOrchestrationAction.Input,
Version = startNewOrchestrationAction.Version,
InstanceId = startNewOrchestrationAction.InstanceId,
ScheduledTime = startNewOrchestrationAction.ScheduledStartTime?.ToTimestamp(),
RequestTime = startNewOrchestrationAction.RequestTime?.ToTimestamp(),
ParentTraceContext = startNewOrchestrationAction.ParentTraceContext != null ?
new P.TraceContext
{
TraceParent = startNewOrchestrationAction.ParentTraceContext.TraceParent,
TraceState = startNewOrchestrationAction.ParentTraceContext.TraceState,
}
: null,
};
break;
}
return action;
}
/// <summary>
/// Converts a <see cref="P.EntityBatchResult" /> to a <see cref="EntityBatchResult" />.
/// </summary>
/// <param name="entityBatchResult">The operation result to convert.</param>
/// <returns>The converted operation result.</returns>
[return: NotNullIfNotNull(nameof(entityBatchResult))]
internal static EntityBatchResult? ToEntityBatchResult(this P.EntityBatchResult? entityBatchResult)
{
if (entityBatchResult == null)
{
return null;
}
return new EntityBatchResult()
{
Actions = entityBatchResult.Actions.Select(operationAction => operationAction!.ToOperationAction()).ToList(),
EntityState = entityBatchResult.EntityState,
Results = entityBatchResult.Results.Select(operationResult => operationResult!.ToOperationResult()).ToList(),
FailureDetails = entityBatchResult.FailureDetails.ToCore(),
};
}
/// <summary>
/// Converts a <see cref="EntityBatchResult" /> to <see cref="P.EntityBatchResult" />.
/// </summary>
/// <param name="entityBatchResult">The operation result to convert.</param>
/// <param name="completionToken">The completion token, or null for the older protocol.</param>
/// <param name="operationInfos">Additional information about each operation, required by DTS.</param>
/// <returns>The converted operation result.</returns>
[return: NotNullIfNotNull(nameof(entityBatchResult))]
internal static P.EntityBatchResult? ToEntityBatchResult(
this EntityBatchResult? entityBatchResult,
string? completionToken = null,
IEnumerable<P.OperationInfo>? operationInfos = null)
{
if (entityBatchResult == null)
{
return null;
}
return new P.EntityBatchResult()
{
EntityState = entityBatchResult.EntityState,
FailureDetails = entityBatchResult.FailureDetails.ToProtobuf(),
Actions = { entityBatchResult.Actions?.Select(a => a.ToOperationAction()) ?? [] },
Results = { entityBatchResult.Results?.Select(a => a.ToOperationResult()) ?? [] },
CompletionToken = completionToken ?? string.Empty,
OperationInfos = { operationInfos ?? [] },
};
}
/// <summary>
/// Converts the gRPC representation of orchestrator entity parameters to the DT.Core representation.
/// </summary>
/// <param name="parameters">The DT.Core representation.</param>
/// <returns>The gRPC representation.</returns>
[return: NotNullIfNotNull(nameof(parameters))]
internal static TaskOrchestrationEntityParameters? ToCore(this P.OrchestratorEntityParameters? parameters)
{
if (parameters == null)
{
return null;
}
return new TaskOrchestrationEntityParameters()
{
EntityMessageReorderWindow = parameters.EntityMessageReorderWindow.ToTimeSpan(),
};
}
/// <summary>
/// Gets the approximate byte count for a <see cref="P.TaskFailureDetails" />.
/// </summary>
/// <param name="failureDetails">The failure details.</param>
/// <returns>The approximate byte count.</returns>
internal static int GetApproximateByteCount(this P.TaskFailureDetails failureDetails)
{
// Protobuf strings are always UTF-8: https://developers.google.com/protocol-buffers/docs/proto3#scalar
Encoding encoding = Encoding.UTF8;
int byteCount = 0;
if (failureDetails.ErrorType != null)
{
byteCount += encoding.GetByteCount(failureDetails.ErrorType);
}
if (failureDetails.ErrorMessage != null)
{
byteCount += encoding.GetByteCount(failureDetails.ErrorMessage);
}
if (failureDetails.StackTrace != null)
{
byteCount += encoding.GetByteCount(failureDetails.StackTrace);
}
if (failureDetails.InnerFailure != null)
{
byteCount += failureDetails.InnerFailure.GetApproximateByteCount();
}
return byteCount;
}
/// <summary>
/// Decode a protobuf message from a base64 string.
/// </summary>
/// <typeparam name="T">The type to decode to.</typeparam>
/// <param name="parser">The message parser.</param>
/// <param name="encodedMessage">The base64 encoded message.</param>
/// <returns>The decoded message.</returns>
/// <exception cref="ArgumentException">If decoding fails.</exception>
internal static T Base64Decode<T>(this MessageParser parser, string encodedMessage) where T : IMessage
{
// Decode the base64 in a way that doesn't allocate a byte[] on each request
int encodedByteCount = Encoding.UTF8.GetByteCount(encodedMessage);
byte[] buffer = ArrayPool<byte>.Shared.Rent(encodedByteCount);