-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathDurableTaskSourceGenerator.cs
More file actions
871 lines (766 loc) · 38.2 KB
/
DurableTaskSourceGenerator.cs
File metadata and controls
871 lines (766 loc) · 38.2 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Microsoft.DurableTask.Generators.AzureFunctions;
namespace Microsoft.DurableTask.Generators
{
/// <summary>
/// Generator for DurableTask.
/// </summary>
[Generator]
public class DurableTaskSourceGenerator : IIncrementalGenerator
{
/* Example input:
*
* [DurableTask("MyActivity")]
* class MyActivity : TaskActivityBase<CustomType, string>
* {
* public Task<string> RunAsync(CustomType input)
* {
* string instanceId = this.Context.InstanceId;
* // ...
* return input.ToString();
* }
* }
*
* Example output:
*
* public static Task<string> CallMyActivityAsync(this TaskOrchestrationContext ctx, int input, TaskOptions? options = null)
* {
* return ctx.CallActivityAsync("MyActivity", input, options);
* }
*/
/// <summary>
/// Diagnostic ID for invalid task names.
/// </summary>
const string InvalidTaskNameDiagnosticId = "DURABLE3001";
/// <summary>
/// Diagnostic ID for invalid event names.
/// </summary>
const string InvalidEventNameDiagnosticId = "DURABLE3002";
static readonly DiagnosticDescriptor InvalidTaskNameRule = new(
InvalidTaskNameDiagnosticId,
title: "Invalid task name",
messageFormat: "The task name '{0}' is not a valid C# identifier. Task names must start with a letter or underscore and contain only letters, digits, and underscores.",
category: "DurableTask.Design",
DiagnosticSeverity.Error,
isEnabledByDefault: true);
static readonly DiagnosticDescriptor InvalidEventNameRule = new(
InvalidEventNameDiagnosticId,
title: "Invalid event name",
messageFormat: "The event name '{0}' is not a valid C# identifier. Event names must start with a letter or underscore and contain only letters, digits, and underscores.",
category: "DurableTask.Design",
DiagnosticSeverity.Error,
isEnabledByDefault: true);
/// <inheritdoc/>
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Create providers for DurableTask attributes
IncrementalValuesProvider<DurableTaskTypeInfo> durableTaskAttributes = context.SyntaxProvider
.CreateSyntaxProvider(
predicate: static (node, _) => node is AttributeSyntax,
transform: static (ctx, _) => GetDurableTaskTypeInfo(ctx))
.Where(static info => info != null)!;
// Create providers for DurableEvent attributes
IncrementalValuesProvider<DurableEventTypeInfo> durableEventAttributes = context.SyntaxProvider
.CreateSyntaxProvider(
predicate: static (node, _) => node is AttributeSyntax,
transform: static (ctx, _) => GetDurableEventTypeInfo(ctx))
.Where(static info => info != null)!;
// Create providers for Durable Functions
IncrementalValuesProvider<DurableFunction> durableFunctions = context.SyntaxProvider
.CreateSyntaxProvider(
predicate: static (node, _) => node is MethodDeclarationSyntax,
transform: static (ctx, _) => GetDurableFunction(ctx))
.Where(static func => func != null)!;
// Get the project type configuration from MSBuild properties
IncrementalValueProvider<string?> projectTypeProvider = context.AnalyzerConfigOptionsProvider
.Select(static (provider, _) =>
{
provider.GlobalOptions.TryGetValue("build_property.DurableTaskGeneratorProjectType", out string? projectType);
return projectType;
});
// Collect all results and check if Durable Functions is referenced
IncrementalValueProvider<(Compilation, ImmutableArray<DurableTaskTypeInfo>, ImmutableArray<DurableEventTypeInfo>, ImmutableArray<DurableFunction>, string?)> compilationAndTasks =
durableTaskAttributes.Collect()
.Combine(durableEventAttributes.Collect())
.Combine(durableFunctions.Collect())
.Combine(context.CompilationProvider)
.Combine(projectTypeProvider)
// Roslyn's IncrementalValueProvider.Combine creates nested tuple pairs: ((Left, Right), Right)
// After multiple .Combine() calls, we unpack the nested structure:
// x.Right = projectType (string?)
// x.Left.Right = Compilation
// x.Left.Left.Left.Left = DurableTaskAttributes (orchestrators, activities, entities)
// x.Left.Left.Left.Right = DurableEventAttributes (events)
// x.Left.Left.Right = DurableFunctions (Azure Functions metadata)
.Select((x, _) => (x.Left.Right, x.Left.Left.Left.Left, x.Left.Left.Left.Right, x.Left.Left.Right, x.Right));
// Generate the source
context.RegisterSourceOutput(compilationAndTasks, static (spc, source) => Execute(spc, source.Item1, source.Item2, source.Item3, source.Item4, source.Item5));
}
static DurableTaskTypeInfo? GetDurableTaskTypeInfo(GeneratorSyntaxContext context)
{
AttributeSyntax attribute = (AttributeSyntax)context.Node;
ITypeSymbol? attributeType = context.SemanticModel.GetTypeInfo(attribute.Name).Type;
if (attributeType?.ToString() != "Microsoft.DurableTask.DurableTaskAttribute")
{
return null;
}
if (attribute.Parent is not AttributeListSyntax list || list.Parent is not ClassDeclarationSyntax classDeclaration)
{
return null;
}
// Verify that the attribute is being used on a non-abstract class
if (classDeclaration.Modifiers.Any(SyntaxKind.AbstractKeyword))
{
return null;
}
if (context.SemanticModel.GetDeclaredSymbol(classDeclaration) is not ITypeSymbol classType)
{
return null;
}
string className = classType.ToDisplayString();
INamedTypeSymbol? taskType = null;
DurableTaskKind kind = DurableTaskKind.Orchestrator;
INamedTypeSymbol? baseType = classType.BaseType;
while (baseType != null)
{
if (baseType.ContainingAssembly.Name == "Microsoft.DurableTask.Abstractions")
{
if (baseType.Name == "TaskActivity")
{
taskType = baseType;
kind = DurableTaskKind.Activity;
break;
}
else if (baseType.Name == "TaskOrchestrator")
{
taskType = baseType;
kind = DurableTaskKind.Orchestrator;
break;
}
else if (baseType.Name == "TaskEntity")
{
taskType = baseType;
kind = DurableTaskKind.Entity;
break;
}
}
baseType = baseType.BaseType;
}
// TaskEntity has 1 type parameter (TState), while TaskActivity and TaskOrchestrator have 2 (TInput, TOutput)
if (taskType == null)
{
return null;
}
if (kind == DurableTaskKind.Entity)
{
// Entity only has a single TState type parameter
if (taskType.TypeParameters.Length < 1)
{
return null;
}
}
else
{
// Orchestrator and Activity have TInput and TOutput type parameters
if (taskType.TypeParameters.Length <= 1)
{
return null;
}
}
ITypeSymbol? inputType = kind == DurableTaskKind.Entity ? null : taskType.TypeArguments.First();
ITypeSymbol? outputType = kind == DurableTaskKind.Entity ? null : taskType.TypeArguments.Last();
string taskName = classType.Name;
Location? taskNameLocation = null;
if (attribute.ArgumentList?.Arguments.Count > 0)
{
ExpressionSyntax expression = attribute.ArgumentList.Arguments[0].Expression;
taskName = context.SemanticModel.GetConstantValue(expression).ToString();
taskNameLocation = expression.GetLocation();
}
return new DurableTaskTypeInfo(className, taskName, inputType, outputType, kind, taskNameLocation);
}
static DurableEventTypeInfo? GetDurableEventTypeInfo(GeneratorSyntaxContext context)
{
AttributeSyntax attribute = (AttributeSyntax)context.Node;
ITypeSymbol? attributeType = context.SemanticModel.GetTypeInfo(attribute.Name).Type;
if (attributeType?.ToString() != "Microsoft.DurableTask.DurableEventAttribute")
{
return null;
}
// DurableEventAttribute can be applied to both class and struct (record)
TypeDeclarationSyntax? typeDeclaration = attribute.Parent?.Parent as TypeDeclarationSyntax;
if (typeDeclaration == null)
{
return null;
}
// Verify that the attribute is being used on a non-abstract type
if (typeDeclaration.Modifiers.Any(SyntaxKind.AbstractKeyword))
{
return null;
}
if (context.SemanticModel.GetDeclaredSymbol(typeDeclaration) is not ITypeSymbol eventType)
{
return null;
}
string eventName = eventType.Name;
Location? eventNameLocation = null;
if (attribute.ArgumentList?.Arguments.Count > 0)
{
ExpressionSyntax expression = attribute.ArgumentList.Arguments[0].Expression;
Optional<object?> constantValue = context.SemanticModel.GetConstantValue(expression);
if (constantValue.HasValue && constantValue.Value is string value)
{
eventName = value;
eventNameLocation = expression.GetLocation();
}
}
return new DurableEventTypeInfo(eventName, eventType, eventNameLocation);
}
static DurableFunction? GetDurableFunction(GeneratorSyntaxContext context)
{
MethodDeclarationSyntax method = (MethodDeclarationSyntax)context.Node;
if (DurableFunction.TryParse(context.SemanticModel, method, out DurableFunction? function))
{
return function;
}
return null;
}
/// <summary>
/// Determines if code generation should be skipped for Durable Functions scenarios.
/// Returns true if only entities exist and the runtime supports native class-based invocation,
/// since entities don't generate extension methods and the runtime handles their registration.
/// </summary>
static bool ShouldSkipGenerationForDurableFunctions(
bool supportsNativeClassBasedInvocation,
List<DurableTaskTypeInfo> orchestrators,
List<DurableTaskTypeInfo> activities,
ImmutableArray<DurableEventTypeInfo> allEvents,
ImmutableArray<DurableFunction> allFunctions)
{
return supportsNativeClassBasedInvocation &&
orchestrators.Count == 0 &&
activities.Count == 0 &&
allEvents.Length == 0 &&
allFunctions.Length == 0;
}
/// Checks if a name is a valid C# identifier.
/// </summary>
/// <param name="name">The name to validate.</param>
/// <returns>True if the name is a valid C# identifier, false otherwise.</returns>
static bool IsValidCSharpIdentifier(string name)
{
if (string.IsNullOrEmpty(name))
{
return false;
}
// Use Roslyn's built-in identifier validation
return SyntaxFacts.IsValidIdentifier(name);
}
static void Execute(
SourceProductionContext context,
Compilation compilation,
ImmutableArray<DurableTaskTypeInfo> allTasks,
ImmutableArray<DurableEventTypeInfo> allEvents,
ImmutableArray<DurableFunction> allFunctions,
string? projectType)
{
if (allTasks.IsDefaultOrEmpty && allEvents.IsDefaultOrEmpty && allFunctions.IsDefaultOrEmpty)
{
return;
}
// Validate task names and report diagnostics for invalid identifiers
foreach (DurableTaskTypeInfo task in allTasks)
{
if (!IsValidCSharpIdentifier(task.TaskName))
{
Location location = task.TaskNameLocation ?? Location.None;
Diagnostic diagnostic = Diagnostic.Create(InvalidTaskNameRule, location, task.TaskName);
context.ReportDiagnostic(diagnostic);
}
}
// Validate event names and report diagnostics for invalid identifiers
foreach (DurableEventTypeInfo eventInfo in allEvents.Where(e => !IsValidCSharpIdentifier(e.EventName)))
{
Location location = eventInfo.EventNameLocation ?? Location.None;
Diagnostic diagnostic = Diagnostic.Create(InvalidEventNameRule, location, eventInfo.EventName);
context.ReportDiagnostic(diagnostic);
}
// Determine if we should generate Durable Functions specific code
bool isDurableFunctions = DetermineIsDurableFunctions(compilation, allFunctions, projectType);
// Check if the Durable Functions extension version supports native class-based invocation.
// This feature was introduced in PR #3229: https://github.com/Azure/azure-functions-durable-extension/pull/3229
// For the isolated worker extension (Microsoft.Azure.Functions.Worker.Extensions.DurableTask),
// native class-based invocation support was added in version 1.11.0.
bool supportsNativeClassBasedInvocation = false;
if (isDurableFunctions)
{
var durableFunctionsAssembly = compilation.ReferencedAssemblyNames.FirstOrDefault(
assembly => assembly.Name.Equals("Microsoft.Azure.Functions.Worker.Extensions.DurableTask", StringComparison.OrdinalIgnoreCase));
if (durableFunctionsAssembly != null && durableFunctionsAssembly.Version >= new Version(1, 11, 0))
{
supportsNativeClassBasedInvocation = true;
}
}
// Separate tasks into orchestrators, activities, and entities
// Skip tasks with invalid names to avoid generating invalid code
List<DurableTaskTypeInfo> orchestrators = new();
List<DurableTaskTypeInfo> activities = new();
List<DurableTaskTypeInfo> entities = new();
IEnumerable<DurableTaskTypeInfo> validTasks = allTasks
.Where(task => IsValidCSharpIdentifier(task.TaskName));
foreach (DurableTaskTypeInfo task in validTasks)
{
if (task.IsActivity)
{
activities.Add(task);
}
else if (task.IsEntity)
{
entities.Add(task);
}
else
{
orchestrators.Add(task);
}
}
// Filter out events with invalid names
List<DurableEventTypeInfo> validEvents = allEvents
.Where(eventInfo => IsValidCSharpIdentifier(eventInfo.EventName))
.ToList();
int found = activities.Count + orchestrators.Count + entities.Count + validEvents.Count + allFunctions.Length;
if (found == 0)
{
return;
}
// With Durable Functions' native support for class-based invocations (PR #3229, v3.8.0+),
// we no longer generate [Function] definitions for class-based tasks when the runtime
// supports native invocation. If we have ONLY entities (no orchestrators, no activities,
// no events, no method-based functions), then there's nothing to generate for those
// scenarios since entities don't have extension methods.
if (ShouldSkipGenerationForDurableFunctions(supportsNativeClassBasedInvocation, orchestrators, activities, allEvents, allFunctions))
{
return;
}
StringBuilder sourceBuilder = new(capacity: found * 1024);
sourceBuilder.Append(@"// <auto-generated/>
#nullable enable
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.DurableTask.Internal;");
if (isDurableFunctions)
{
sourceBuilder.Append(@"
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.DependencyInjection;");
}
sourceBuilder.Append(@"
namespace Microsoft.DurableTask
{
public static class GeneratedDurableTaskExtensions
{");
// Generate singleton orchestrator instances for older Durable Functions versions
// that don't have native class-based invocation support
if (isDurableFunctions && !supportsNativeClassBasedInvocation)
{
foreach (DurableTaskTypeInfo orchestrator in orchestrators)
{
sourceBuilder.AppendLine($@"
static readonly ITaskOrchestrator singleton{orchestrator.TaskName} = new {orchestrator.TypeName}();");
}
}
// Note: When targeting Azure Functions (Durable Functions scenarios) with native support
// for class-based invocations (PR #3229, v3.8.0+), we no longer generate [Function] attribute
// definitions for class-based orchestrators, activities, and entities (i.e., classes that
// implement ITaskOrchestrator, ITaskActivity, or ITaskEntity and are decorated with the
// [DurableTask] attribute). The Durable Functions runtime handles function registration
// for these types automatically in those scenarios. For older versions of Durable Functions
// (prior to v3.8.0) or non-Durable Functions scenarios (for example, ASP.NET Core using
// the Durable Task Scheduler), we continue to generate [Function] definitions.
// We always generate extension methods for type-safe invocation.
foreach (DurableTaskTypeInfo orchestrator in orchestrators)
{
// Only generate [Function] definitions for Durable Functions if the runtime doesn't
// support native class-based invocation (versions prior to v3.8.0)
if (isDurableFunctions && !supportsNativeClassBasedInvocation)
{
AddOrchestratorFunctionDeclaration(sourceBuilder, orchestrator);
}
AddOrchestratorCallMethod(sourceBuilder, orchestrator);
AddSubOrchestratorCallMethod(sourceBuilder, orchestrator);
}
foreach (DurableTaskTypeInfo activity in activities)
{
AddActivityCallMethod(sourceBuilder, activity);
// Only generate [Function] definitions for Durable Functions if the runtime doesn't
// support native class-based invocation (versions prior to v3.8.0)
if (isDurableFunctions && !supportsNativeClassBasedInvocation)
{
AddActivityFunctionDeclaration(sourceBuilder, activity);
}
}
foreach (DurableTaskTypeInfo entity in entities)
{
// Only generate [Function] definitions for Durable Functions if the runtime doesn't
// support native class-based invocation (versions prior to v3.8.0)
if (isDurableFunctions && !supportsNativeClassBasedInvocation)
{
AddEntityFunctionDeclaration(sourceBuilder, entity);
}
}
// Activity function triggers are supported for code-gen (but not orchestration triggers)
IEnumerable<DurableFunction> activityTriggers = allFunctions.Where(
df => df.Kind == DurableFunctionKind.Activity);
foreach (DurableFunction function in activityTriggers)
{
AddActivityCallMethod(sourceBuilder, function);
}
// Generate WaitFor{EventName}Async methods for each event type
foreach (DurableEventTypeInfo eventInfo in validEvents)
{
AddEventWaitMethod(sourceBuilder, eventInfo);
AddEventSendMethod(sourceBuilder, eventInfo);
}
// Note: The GeneratedActivityContext class is only needed for older versions of
// Durable Functions (prior to v3.8.0) that don't have native class-based invocation support.
// For v3.8.0+, the runtime handles class-based invocations natively.
if (isDurableFunctions && !supportsNativeClassBasedInvocation)
{
if (activities.Count > 0)
{
// Functions-specific helper class, which is only needed when
// using the class-based syntax with older Durable Functions versions.
AddGeneratedActivityContextClass(sourceBuilder);
}
}
else if (!isDurableFunctions)
{
// ASP.NET Core-specific service registration methods
// Only generate if there are actually tasks to register
if (orchestrators.Count > 0 || activities.Count > 0 || entities.Count > 0)
{
AddRegistrationMethodForAllTasks(
sourceBuilder,
orchestrators,
activities,
entities);
}
}
sourceBuilder.AppendLine(" }").AppendLine("}");
context.AddSource("GeneratedDurableTaskExtensions.cs", SourceText.From(sourceBuilder.ToString(), Encoding.UTF8, SourceHashAlgorithm.Sha256));
}
/// <summary>
/// Determines whether the current project should be treated as an Azure Functions-based Durable Functions project.
/// </summary>
/// <param name="compilation">The Roslyn compilation for the project, used to inspect referenced assemblies.</param>
/// <param name="allFunctions">The collection of discovered Durable Functions triggers in the project.</param>
/// <param name="projectType">
/// An optional project type hint. When set to <c>"Functions"</c> or <c>"Standalone"</c>, this value takes precedence
/// over automatic detection. Any other value (including <c>"Auto"</c>) falls back to auto-detection.
/// </param>
/// <returns>
/// <c>true</c> if the project is determined to be a Durable Functions (Azure Functions) project; otherwise, <c>false</c>.
/// </returns>
static bool DetermineIsDurableFunctions(Compilation compilation, ImmutableArray<DurableFunction> allFunctions, string? projectType)
{
// Check if the user has explicitly configured the project type
if (!string.IsNullOrWhiteSpace(projectType))
{
// Explicit configuration takes precedence
if (projectType!.Equals("Functions", StringComparison.OrdinalIgnoreCase))
{
return true;
}
else if (projectType.Equals("Standalone", StringComparison.OrdinalIgnoreCase))
{
return false;
}
// If "Auto" or unrecognized value, fall through to auto-detection
}
// Auto-detect based on the presence of Azure Functions trigger attributes
// If we found any methods with OrchestrationTrigger, ActivityTrigger, or EntityTrigger attributes,
// then this is a Durable Functions project
if (!allFunctions.IsDefaultOrEmpty)
{
return true;
}
// Fallback: check if Durable Functions assembly is referenced
// This handles edge cases where the project references the assembly but hasn't defined triggers yet
return compilation.ReferencedAssemblyNames.Any(
assembly => assembly.Name.Equals("Microsoft.Azure.Functions.Worker.Extensions.DurableTask", StringComparison.OrdinalIgnoreCase));
}
static void AddOrchestratorFunctionDeclaration(StringBuilder sourceBuilder, DurableTaskTypeInfo orchestrator)
{
sourceBuilder.AppendLine($@"
[Function(nameof({orchestrator.TaskName}))]
public static Task<{orchestrator.OutputType}> {orchestrator.TaskName}([OrchestrationTrigger] TaskOrchestrationContext context)
{{
return singleton{orchestrator.TaskName}.RunAsync(context, context.GetInput<{orchestrator.InputType}>())
.ContinueWith(t => ({orchestrator.OutputType})(t.Result ?? default({orchestrator.OutputType})!), TaskContinuationOptions.ExecuteSynchronously);
}}");
}
static void AddOrchestratorCallMethod(StringBuilder sourceBuilder, DurableTaskTypeInfo orchestrator)
{
sourceBuilder.AppendLine($@"
/// <summary>
/// Schedules a new instance of the <see cref=""{orchestrator.TypeName}""/> orchestrator.
/// </summary>
/// <inheritdoc cref=""IOrchestrationSubmitter.ScheduleNewOrchestrationInstanceAsync""/>
public static Task<string> ScheduleNew{orchestrator.TaskName}InstanceAsync(
this IOrchestrationSubmitter client, {orchestrator.InputParameter}, StartOrchestrationOptions? options = null)
{{
return client.ScheduleNewOrchestrationInstanceAsync(""{orchestrator.TaskName}"", input, options);
}}");
}
static void AddSubOrchestratorCallMethod(StringBuilder sourceBuilder, DurableTaskTypeInfo orchestrator)
{
sourceBuilder.AppendLine($@"
/// <summary>
/// Calls the <see cref=""{orchestrator.TypeName}""/> sub-orchestrator.
/// </summary>
/// <inheritdoc cref=""TaskOrchestrationContext.CallSubOrchestratorAsync(TaskName, object?, TaskOptions?)""/>
public static Task<{orchestrator.OutputType}> Call{orchestrator.TaskName}Async(
this TaskOrchestrationContext context, {orchestrator.InputParameter}, TaskOptions? options = null)
{{
return context.CallSubOrchestratorAsync<{orchestrator.OutputType}>(""{orchestrator.TaskName}"", input, options);
}}");
}
static void AddActivityCallMethod(StringBuilder sourceBuilder, DurableTaskTypeInfo activity)
{
sourceBuilder.AppendLine($@"
/// <summary>
/// Calls the <see cref=""{activity.TypeName}""/> activity.
/// </summary>
/// <inheritdoc cref=""TaskOrchestrationContext.CallActivityAsync(TaskName, object?, TaskOptions?)""/>
public static Task<{activity.OutputType}> Call{activity.TaskName}Async(this TaskOrchestrationContext ctx, {activity.InputParameter}, TaskOptions? options = null)
{{
return ctx.CallActivityAsync<{activity.OutputType}>(""{activity.TaskName}"", input, options);
}}");
}
static void AddActivityCallMethod(StringBuilder sourceBuilder, DurableFunction activity)
{
if (activity.ReturnsVoid)
{
sourceBuilder.AppendLine($@"
/// <summary>
/// Calls the <see cref=""{activity.FullTypeName}""/> activity.
/// </summary>
/// <inheritdoc cref=""TaskOrchestrationContext.CallActivityAsync(TaskName, object?, TaskOptions?)""/>
public static Task Call{activity.Name}Async(this TaskOrchestrationContext ctx, {activity.Parameter}, TaskOptions? options = null)
{{
return ctx.CallActivityAsync(""{activity.Name}"", {activity.Parameter.Name}, options);
}}");
}
else
{
sourceBuilder.AppendLine($@"
/// <summary>
/// Calls the <see cref=""{activity.FullTypeName}""/> activity.
/// </summary>
/// <inheritdoc cref=""TaskOrchestrationContext.CallActivityAsync(TaskName, object?, TaskOptions?)""/>
public static Task<{activity.ReturnType}> Call{activity.Name}Async(this TaskOrchestrationContext ctx, {activity.Parameter}, TaskOptions? options = null)
{{
return ctx.CallActivityAsync<{activity.ReturnType}>(""{activity.Name}"", {activity.Parameter.Name}, options);
}}");
}
}
static void AddEventWaitMethod(StringBuilder sourceBuilder, DurableEventTypeInfo eventInfo)
{
sourceBuilder.AppendLine($@"
/// <summary>
/// Waits for an external event of type <see cref=""{eventInfo.TypeName}""/>.
/// </summary>
/// <inheritdoc cref=""TaskOrchestrationContext.WaitForExternalEvent{{T}}(string, CancellationToken)""/>
public static Task<{eventInfo.TypeName}> WaitFor{eventInfo.EventName}Async(this TaskOrchestrationContext context, CancellationToken cancellationToken = default)
{{
return context.WaitForExternalEvent<{eventInfo.TypeName}>(""{eventInfo.EventName}"", cancellationToken);
}}");
}
static void AddEventSendMethod(StringBuilder sourceBuilder, DurableEventTypeInfo eventInfo)
{
sourceBuilder.AppendLine($@"
/// <summary>
/// Sends an external event of type <see cref=""{eventInfo.TypeName}""/> to another orchestration instance.
/// </summary>
/// <inheritdoc cref=""TaskOrchestrationContext.SendEvent(string, string, object)""/>
public static void Send{eventInfo.EventName}(this TaskOrchestrationContext context, string instanceId, {eventInfo.TypeName} eventData)
{{
context.SendEvent(instanceId, ""{eventInfo.EventName}"", eventData);
}}");
}
static void AddActivityFunctionDeclaration(StringBuilder sourceBuilder, DurableTaskTypeInfo activity)
{
// GeneratedActivityContext is a generated class that we use for each generated activity trigger definition.
// Note that the second "instanceId" parameter is populated via the Azure Functions binding context.
sourceBuilder.AppendLine($@"
[Function(nameof({activity.TaskName}))]
public static async Task<{activity.OutputType}> {activity.TaskName}([ActivityTrigger] {activity.InputParameter}, string instanceId, FunctionContext executionContext)
{{
ITaskActivity activity = ActivatorUtilities.GetServiceOrCreateInstance<{activity.TypeName}>(executionContext.InstanceServices);
TaskActivityContext context = new GeneratedActivityContext(""{activity.TaskName}"", instanceId);
object? result = await activity.RunAsync(context, input);
return ({activity.OutputType})result!;
}}");
}
static void AddEntityFunctionDeclaration(StringBuilder sourceBuilder, DurableTaskTypeInfo entity)
{
// Generate the entity trigger function that dispatches to the entity implementation.
sourceBuilder.AppendLine($@"
[Function(nameof({entity.TaskName}))]
public static Task {entity.TaskName}([EntityTrigger] TaskEntityDispatcher dispatcher)
{{
return dispatcher.DispatchAsync<{entity.TypeName}>();
}}");
}
/// <summary>
/// Adds a custom ITaskActivityContext implementation used by code generated from <see cref="AddActivityFunctionDeclaration"/>.
/// </summary>
static void AddGeneratedActivityContextClass(StringBuilder sourceBuilder)
{
// NOTE: Any breaking changes to ITaskActivityContext need to be reflected here as well.
sourceBuilder.AppendLine(GetGeneratedActivityContextCode());
}
/// <summary>
/// Gets the generated activity context code.
/// </summary>
/// <returns>The generated activity context code.</returns>
public static string GetGeneratedActivityContextCode() => $@"
sealed class GeneratedActivityContext : TaskActivityContext
{{
public GeneratedActivityContext(TaskName name, string instanceId)
{{
this.Name = name;
this.InstanceId = instanceId;
}}
public override TaskName Name {{ get; }}
public override string InstanceId {{ get; }}
}}";
static void AddRegistrationMethodForAllTasks(
StringBuilder sourceBuilder,
IEnumerable<DurableTaskTypeInfo> orchestrators,
IEnumerable<DurableTaskTypeInfo> activities,
IEnumerable<DurableTaskTypeInfo> entities)
{
// internal so it does not conflict with other projects with this generated file.
sourceBuilder.Append($@"
internal static DurableTaskRegistry AddAllGeneratedTasks(this DurableTaskRegistry builder)
{{");
foreach (DurableTaskTypeInfo taskInfo in orchestrators)
{
sourceBuilder.Append($@"
builder.AddOrchestrator<{taskInfo.TypeName}>();");
}
foreach (DurableTaskTypeInfo taskInfo in activities)
{
sourceBuilder.Append($@"
builder.AddActivity<{taskInfo.TypeName}>();");
}
foreach (DurableTaskTypeInfo taskInfo in entities)
{
sourceBuilder.Append($@"
builder.AddEntity<{taskInfo.TypeName}>();");
}
sourceBuilder.AppendLine($@"
return builder;
}}");
}
enum DurableTaskKind
{
Orchestrator,
Activity,
Entity
}
class DurableTaskTypeInfo
{
public DurableTaskTypeInfo(
string taskType,
string taskName,
ITypeSymbol? inputType,
ITypeSymbol? outputType,
DurableTaskKind kind,
Location? taskNameLocation = null)
{
this.TypeName = taskType;
this.TaskName = taskName;
this.Kind = kind;
this.TaskNameLocation = taskNameLocation;
// Entities only have a state type parameter, not input/output
if (kind == DurableTaskKind.Entity)
{
this.InputType = string.Empty;
this.InputParameter = string.Empty;
this.OutputType = string.Empty;
}
else
{
this.InputType = GetRenderedTypeExpression(inputType);
this.InputParameter = this.InputType + " input";
if (this.InputType[this.InputType.Length - 1] == '?')
{
this.InputParameter += " = default";
}
this.OutputType = GetRenderedTypeExpression(outputType);
}
}
public string TypeName { get; }
public string TaskName { get; }
public string InputType { get; }
public string InputParameter { get; }
public string OutputType { get; }
public DurableTaskKind Kind { get; }
public Location? TaskNameLocation { get; }
public bool IsActivity => this.Kind == DurableTaskKind.Activity;
public bool IsOrchestrator => this.Kind == DurableTaskKind.Orchestrator;
public bool IsEntity => this.Kind == DurableTaskKind.Entity;
static string GetRenderedTypeExpression(ITypeSymbol? symbol)
{
if (symbol == null)
{
return "object";
}
string expression = symbol.ToString();
if (expression.StartsWith("System.", StringComparison.Ordinal)
&& symbol.ContainingNamespace.Name == "System")
{
expression = expression.Substring("System.".Length);
}
return expression;
}
}
class DurableEventTypeInfo
{
public DurableEventTypeInfo(string eventName, ITypeSymbol eventType, Location? eventNameLocation = null)
{
this.TypeName = GetRenderedTypeExpression(eventType);
this.EventName = eventName;
this.EventNameLocation = eventNameLocation;
}
public string TypeName { get; }
public string EventName { get; }
public Location? EventNameLocation { get; }
static string GetRenderedTypeExpression(ITypeSymbol? symbol)
{
if (symbol == null)
{
return "object";
}
string expression = symbol.ToString();
if (expression.StartsWith("System.", StringComparison.Ordinal)
&& symbol.ContainingNamespace.Name == "System")
{
expression = expression.Substring("System.".Length);
}
return expression;
}
}
}
}