diff --git a/.autover/changes/a91e5b3c-2f7d-4c8a-9d16-0b4e7f3a2c58.json b/.autover/changes/a91e5b3c-2f7d-4c8a-9d16-0b4e7f3a2c58.json new file mode 100644 index 000000000..63e68edc8 --- /dev/null +++ b/.autover/changes/a91e5b3c-2f7d-4c8a-9d16-0b4e7f3a2c58.json @@ -0,0 +1,11 @@ +{ + "Projects": [ + { + "Name": "Amazon.Lambda.Annotations", + "Type": "Minor", + "ChangelogMessages": [ + "Add Tracing and PluginProvider options to [DurableExecution] to add OpenTelemetry or custom instrumentation plugins to the generated durable execution handler." + ] + } + ] +} diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Diagnostics/AnalyzerReleases.Unshipped.md b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Diagnostics/AnalyzerReleases.Unshipped.md index ffb739ddf..42c1010d9 100644 --- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Diagnostics/AnalyzerReleases.Unshipped.md +++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Diagnostics/AnalyzerReleases.Unshipped.md @@ -28,3 +28,6 @@ AWSLambda0142 | AWSLambdaCSharpGenerator | Error | Invalid DurableExecution meth AWSLambda0143 | AWSLambdaCSharpGenerator | Info | DurableExecution function with explicit Role needs checkpoint permissions AWSLambda0144 | AWSLambdaCSharpGenerator | Error | Invalid DurableExecutionAttribute AWSLambda0145 | AWSLambdaCSharpGenerator | Warning | Durable execution envelope types not registered with JsonSerializerContext +AWSLambda0146 | AWSLambdaCSharpGenerator | Error | Durable execution plugins are not available +AWSLambda0147 | AWSLambdaCSharpGenerator | Error | Durable execution tracing needs the OpenTelemetry package +AWSLambda0148 | AWSLambdaCSharpGenerator | Error | Invalid DurableExecution PluginProvider diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Diagnostics/DiagnosticDescriptors.cs b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Diagnostics/DiagnosticDescriptors.cs index cc40ce60a..08442bb3a 100644 --- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Diagnostics/DiagnosticDescriptors.cs +++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Diagnostics/DiagnosticDescriptors.cs @@ -324,6 +324,27 @@ public static class DiagnosticDescriptors DiagnosticSeverity.Error, isEnabledByDefault: true); + public static readonly DiagnosticDescriptor DurableExecutionPluginsUnavailable = new DiagnosticDescriptor(id: "AWSLambda0146", + title: "Durable execution plugins are not available", + messageFormat: "[DurableExecution] sets {0}, but the referenced Amazon.Lambda.DurableExecution package has no instrumentation plugin API ('{1}' was not found). Upgrade the Amazon.Lambda.DurableExecution package.", + category: "AWSLambdaCSharpGenerator", + DiagnosticSeverity.Error, + isEnabledByDefault: true); + + public static readonly DiagnosticDescriptor DurableExecutionTracingPackageMissing = new DiagnosticDescriptor(id: "AWSLambda0147", + title: "Durable execution tracing needs the OpenTelemetry package", + messageFormat: "[DurableExecution(Tracing = DurableTracing.{0})] registers the OpenTelemetry plugin, but the project does not reference the Amazon.Lambda.DurableExecution.OpenTelemetry package. Add a reference to it, or set Tracing to None.", + category: "AWSLambdaCSharpGenerator", + DiagnosticSeverity.Error, + isEnabledByDefault: true); + + public static readonly DiagnosticDescriptor DurableExecutionInvalidPluginProvider = new DiagnosticDescriptor(id: "AWSLambda0148", + title: "Invalid DurableExecution PluginProvider", + messageFormat: "[DurableExecution(PluginProvider = \"{0}\")] is not usable: {1}", + category: "AWSLambdaCSharpGenerator", + DiagnosticSeverity.Error, + isEnabledByDefault: true); + public static readonly DiagnosticDescriptor DurableExecutionMissingSerializableEnvelope = new DiagnosticDescriptor(id: "AWSLambda0145", title: "Durable execution envelope types not registered with JsonSerializerContext", messageFormat: "The [DurableExecution] function uses SourceGeneratorLambdaJsonSerializer<{0}>, but {0} does not register {1} with a [JsonSerializable] attribute. The durable runtime serializes the invocation envelope with this context, so add [JsonSerializable(typeof({1}))] to {0} or the function will fail at invocation time.", diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/Attributes/DurableExecutionAttributeBuilder.cs b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/Attributes/DurableExecutionAttributeBuilder.cs index 0b15d544b..b43daaf2f 100644 --- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/Attributes/DurableExecutionAttributeBuilder.cs +++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/Attributes/DurableExecutionAttributeBuilder.cs @@ -31,6 +31,14 @@ public static DurableExecutionAttribute Build(AttributeData att) { data.RetentionPeriodInDays = retentionPeriodInDays; } + else if (pair.Key == nameof(data.Tracing) && pair.Value.Value is int tracing) + { + data.Tracing = (DurableTracing)tracing; + } + else if (pair.Key == nameof(data.PluginProvider)) + { + data.PluginProvider = pair.Value.Value as string; + } } return data; diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/LambdaFunctionModel.cs b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/LambdaFunctionModel.cs index fd47d2dab..7fe382b26 100644 --- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/LambdaFunctionModel.cs +++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/LambdaFunctionModel.cs @@ -72,6 +72,26 @@ public class LambdaFunctionModel : ILambdaFunctionSerializable /// public IList Attributes => LambdaMethod.Attributes ?? new List(); + /// + /// The [DurableExecution] attribute of the function, or null when it has none. + /// + public DurableExecutionAttribute DurableExecution => + Attributes.OfType>().FirstOrDefault()?.Data; + + /// + /// True when the [DurableExecution] attribute asks for instrumentation plugins, through + /// Tracing or PluginProvider. The generated wrapper then passes + /// DurableExecutionOptions to DurableFunction.WrapAsync. + /// + public bool DurablePluginsEnabled + { + get + { + var durable = DurableExecution; + return durable != null && (durable.Tracing != DurableTracing.None || durable.PluginProvider != null); + } + } + /// public string ReturnTypeFullName => LambdaMethod.ReturnType.FullName; diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/DurableExecutionInvoke.cs b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/DurableExecutionInvoke.cs index bb49bb703..bf7b7382e 100644 --- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/DurableExecutionInvoke.cs +++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/DurableExecutionInvoke.cs @@ -46,6 +46,10 @@ public virtual string TransformText() ? $"<{inputType}, {_model.LambdaMethod.ReturnType.TaskTypeArgument}>" : $"<{inputType}>"; + // Plugins (Tracing / PluginProvider) travel in DurableExecutionOptions, built once in a static field of the + // generated class (see FieldsAndConstructor). Without them the call is unchanged. + var optionsArgument = _model.DurablePluginsEnabled ? ", __durableExecutionOptions__" : ""; + #line default #line hidden @@ -71,7 +75,14 @@ public virtual string TransformText() #line default #line hidden - this.Write(", __request__, __context__);\r\n"); + this.Write(", __request__, __context__"); + + #line 27 "C:\dev\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\DurableExecutionInvoke.tt" + this.Write(this.ToStringHelper.ToStringWithCulture(optionsArgument)); + + #line default + #line hidden + this.Write(");\r\n"); return this.GenerationEnvironment.ToString(); } } diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/DurableExecutionInvoke.tt b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/DurableExecutionInvoke.tt index 8d23675de..e67502952 100644 --- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/DurableExecutionInvoke.tt +++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/DurableExecutionInvoke.tt @@ -18,5 +18,9 @@ var typeArguments = _model.LambdaMethod.ReturnsGenericTask ? $"<{inputType}, {_model.LambdaMethod.ReturnType.TaskTypeArgument}>" : $"<{inputType}>"; + + // Plugins (Tracing / PluginProvider) travel in DurableExecutionOptions, built once in a static field of the + // generated class (see FieldsAndConstructor). Without them the call is unchanged. + var optionsArgument = _model.DurablePluginsEnabled ? ", __durableExecutionOptions__" : ""; #> - return await Amazon.Lambda.DurableExecution.DurableFunction.WrapAsync<#= typeArguments #>(<#= instance #>.<#= _model.LambdaMethod.Name #>, __request__, __context__); + return await Amazon.Lambda.DurableExecution.DurableFunction.WrapAsync<#= typeArguments #>(<#= instance #>.<#= _model.LambdaMethod.Name #>, __request__, __context__<#= optionsArgument #>); diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/FieldsAndConstructor.cs b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/FieldsAndConstructor.cs index 37d50c71b..955b2befd 100644 --- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/FieldsAndConstructor.cs +++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/FieldsAndConstructor.cs @@ -13,6 +13,7 @@ namespace Amazon.Lambda.Annotations.SourceGenerator.Templates using System.Text; using System.Collections.Generic; using Amazon.Lambda.Annotations.SourceGenerator.Extensions; + using Amazon.Lambda.Annotations; using System; /// @@ -92,6 +93,79 @@ public virtual string TransformText() #line 27 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt" + } + + if (_model.DurablePluginsEnabled) + { + var durable = _model.DurableExecution; + + + #line default + #line hidden + this.Write(@" + // The durable instrumentation plugins are created once, when the function starts. The SDK asks each factory + // for a new plugin on every invocation. + private static readonly Amazon.Lambda.DurableExecution.DurableExecutionOptions __durableExecutionOptions__ = CreateDurableExecutionOptions(); + + private static Amazon.Lambda.DurableExecution.DurableExecutionOptions CreateDurableExecutionOptions() + { + var options = new Amazon.Lambda.DurableExecution.DurableExecutionOptions(); +"); + + #line 46 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt" + + if (durable.Tracing != DurableTracing.None) + { + + + #line default + #line hidden + this.Write(" options.Plugins.Add(Amazon.Lambda.DurableExecution.OpenTelemetry.OtelPlugin.CreateFactory(Amazon.Lambda.DurableExecution.OpenTelemetry.OtelView."); + + #line 50 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt" + this.Write(this.ToStringHelper.ToStringWithCulture(durable.Tracing)); + + #line default + #line hidden + this.Write("));\r\n"); + + #line 51 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt" + + } + + if (durable.PluginProvider != null) + { + + + #line default + #line hidden + this.Write(" foreach (var factory in "); + + #line 57 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt" + this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.FullName)); + + #line default + #line hidden + this.Write("."); + + #line 57 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt" + this.Write(this.ToStringHelper.ToStringWithCulture(durable.PluginProvider)); + + #line default + #line hidden + this.Write("())\r\n options.Plugins.Add(factory);\r\n"); + + #line 59 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt" + + } + + + #line default + #line hidden + this.Write(" return options;\r\n }\r\n"); + + #line 65 "C:\projects\aws\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\FieldsAndConstructor.tt" + } diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/FieldsAndConstructor.tt b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/FieldsAndConstructor.tt index 35a1f2c59..f78201af5 100644 --- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/FieldsAndConstructor.tt +++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/FieldsAndConstructor.tt @@ -4,6 +4,7 @@ <#@ import namespace="System.Text" #> <#@ import namespace="System.Collections.Generic" #> <#@ import namespace="Amazon.Lambda.Annotations.SourceGenerator.Extensions" #> +<#@ import namespace="Amazon.Lambda.Annotations" #> <# if (_model.LambdaMethod.UsingDependencyInjection) { @@ -24,6 +25,39 @@ #> private readonly <#= _model.LambdaMethod.ContainingType.Name #> <#= _model.LambdaMethod.ContainingType.Name.ToCamelCase() #>; private readonly <#= _model.SerializerInfo.SerializerName #> serializer; +<# + } + + if (_model.DurablePluginsEnabled) + { + var durable = _model.DurableExecution; +#> + + // The durable instrumentation plugins are created once, when the function starts. The SDK asks each factory + // for a new plugin on every invocation. + private static readonly Amazon.Lambda.DurableExecution.DurableExecutionOptions __durableExecutionOptions__ = CreateDurableExecutionOptions(); + + private static Amazon.Lambda.DurableExecution.DurableExecutionOptions CreateDurableExecutionOptions() + { + var options = new Amazon.Lambda.DurableExecution.DurableExecutionOptions(); +<# + if (durable.Tracing != DurableTracing.None) + { +#> + options.Plugins.Add(Amazon.Lambda.DurableExecution.OpenTelemetry.OtelPlugin.CreateFactory(Amazon.Lambda.DurableExecution.OpenTelemetry.OtelView.<#= durable.Tracing #>)); +<# + } + + if (durable.PluginProvider != null) + { +#> + foreach (var factory in <#= _model.LambdaMethod.ContainingType.FullName #>.<#= durable.PluginProvider #>()) + options.Plugins.Add(factory); +<# + } +#> + return options; + } <# } #> diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/TypeFullNames.cs b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/TypeFullNames.cs index ceebf32ce..238cff47f 100644 --- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/TypeFullNames.cs +++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/TypeFullNames.cs @@ -78,6 +78,10 @@ public static class TypeFullNames public const string DurableExecutionInvocationOutput = "Amazon.Lambda.DurableExecution.DurableExecutionInvocationOutput"; public const string DurableFunction = "Amazon.Lambda.DurableExecution.DurableFunction"; public const string IDurableContext = "Amazon.Lambda.DurableExecution.IDurableContext"; + public const string DurableExecutionOptions = "Amazon.Lambda.DurableExecution.DurableExecutionOptions"; + public const string DurableInstrumentationPluginFactory = "Amazon.Lambda.DurableExecution.Instrumentation.IDurableInstrumentationPluginFactory"; + public const string DurableOtelPlugin = "Amazon.Lambda.DurableExecution.OpenTelemetry.OtelPlugin"; + public const string DurableOtelView = "Amazon.Lambda.DurableExecution.OpenTelemetry.OtelView"; public const string LambdaSerializerAttribute = "Amazon.Lambda.Core.LambdaSerializerAttribute"; public const string DefaultLambdaSerializer = "Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer"; diff --git a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Validation/LambdaFunctionValidator.cs b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Validation/LambdaFunctionValidator.cs index b580f2466..c0cc0692d 100644 --- a/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Validation/LambdaFunctionValidator.cs +++ b/Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Validation/LambdaFunctionValidator.cs @@ -106,6 +106,11 @@ private static void ValidateDurableExecution(GeneratorExecutionContext context, validationErrors.ForEach(errorMessage => diagnostics.Add(Diagnostic.Create(DiagnosticDescriptors.InvalidDurableExecutionAttribute, methodLocation, errorMessage))); } + // Tracing and PluginProvider make the generated code reference the plugin API, the OpenTelemetry + // package and a method of the user's class. Check each now so a mistake is a diagnostic on the user's + // method instead of a compile error in generated code. + ValidateDurablePlugins(context, lambdaMethodSymbol, lambdaFunctionModel, methodLocation, diagnostics); + // The generated wrapper hands the user method group to DurableFunction.WrapAsync, whose overloads // accept Func or Func>. A // mismatched signature would produce a C# error in the generated code, so reject it up front with @@ -127,6 +132,115 @@ private static void ValidateDurableExecution(GeneratorExecutionContext context, ValidateDurableExecutionSerializerContext(context, lambdaMethodSymbol, methodLocation, diagnostics); } + private static void ValidateDurablePlugins(GeneratorExecutionContext context, IMethodSymbol lambdaMethodSymbol, LambdaFunctionModel lambdaFunctionModel, Location methodLocation, List diagnostics) + { + var durable = lambdaFunctionModel.DurableExecution; + if (durable == null) + return; + + var wantsTracing = durable.Tracing != DurableTracing.None; + var wantsProvider = durable.PluginProvider != null; + if (!wantsTracing && !wantsProvider) + return; + + // An invalid attribute value was reported above; do not pile generated-code checks on top of it. + if (durable.Validate().Count > 0) + return; + + var compilation = context.Compilation; + var optionsType = compilation.GetTypeByMetadataName(TypeFullNames.DurableExecutionOptions); + var factoryType = compilation.GetTypeByMetadataName(TypeFullNames.DurableInstrumentationPluginFactory); + var setting = wantsTracing ? nameof(durable.Tracing) : nameof(durable.PluginProvider); + if (optionsType == null) + { + diagnostics.Add(Diagnostic.Create(DiagnosticDescriptors.DurableExecutionPluginsUnavailable, methodLocation, setting, TypeFullNames.DurableExecutionOptions)); + return; + } + if (factoryType == null) + { + diagnostics.Add(Diagnostic.Create(DiagnosticDescriptors.DurableExecutionPluginsUnavailable, methodLocation, setting, TypeFullNames.DurableInstrumentationPluginFactory)); + return; + } + + if (wantsTracing + && (compilation.GetTypeByMetadataName(TypeFullNames.DurableOtelPlugin) == null + || compilation.GetTypeByMetadataName(TypeFullNames.DurableOtelView) == null)) + { + diagnostics.Add(Diagnostic.Create(DiagnosticDescriptors.DurableExecutionTracingPackageMissing, methodLocation, durable.Tracing.ToString())); + } + + if (wantsProvider) + ValidateDurablePluginProvider(compilation, lambdaMethodSymbol, durable.PluginProvider, factoryType, methodLocation, diagnostics); + } + + private static void ValidateDurablePluginProvider(Compilation compilation, IMethodSymbol lambdaMethodSymbol, string providerName, INamedTypeSymbol factoryType, Location methodLocation, List diagnostics) + { + void Report(string detail) => + diagnostics.Add(Diagnostic.Create(DiagnosticDescriptors.DurableExecutionInvalidPluginProvider, methodLocation, providerName, detail)); + + var containingType = lambdaMethodSymbol.ContainingType; + var candidates = containingType.GetMembers(providerName).OfType().ToList(); + if (candidates.Count == 0) + { + Report($"'{containingType.ToDisplayString()}' has no method with that name."); + return; + } + + // Prefer a usable overload when there are several. The detail reported is for the first candidate otherwise. + var method = candidates.FirstOrDefault(m => m.IsStatic && m.Parameters.Length == 0 && m.TypeParameters.Length == 0 && IsCallableFromGeneratedCode(m)) + ?? candidates[0]; + + if (!method.IsStatic) + { + Report("it must be static."); + return; + } + if (method.Parameters.Length != 0 || method.TypeParameters.Length != 0) + { + Report("it must take no parameters and have no type parameters."); + return; + } + if (!IsCallableFromGeneratedCode(method)) + { + // The generated class is a different class in the same assembly, so private and protected members are out. + Report($"it is {method.DeclaredAccessibility.ToString().ToLowerInvariant()}, but the generated code must be able to call it. Make it internal or public."); + return; + } + + if (!ReturnsPluginFactories(compilation, method.ReturnType, factoryType)) + { + Report($"it must return IEnumerable<{TypeFullNames.DurableInstrumentationPluginFactory}> but returns '{method.ReturnType.ToDisplayString()}'."); + } + } + + private static bool IsCallableFromGeneratedCode(IMethodSymbol method) => + method.DeclaredAccessibility == Accessibility.Public + || method.DeclaredAccessibility == Accessibility.Internal + || method.DeclaredAccessibility == Accessibility.ProtectedOrInternal; + + /// + /// True when is an IEnumerable<T>, or implements one, where T is the + /// plugin factory interface or a type that implements it. That covers IEnumerable, arrays and lists. + /// + private static bool ReturnsPluginFactories(Compilation compilation, ITypeSymbol returnType, INamedTypeSymbol factoryType) + { + var enumerable = compilation.GetTypeByMetadataName("System.Collections.Generic.IEnumerable`1"); + if (enumerable == null || returnType == null) + return false; + + bool IsFactory(ITypeSymbol t) => + SymbolEqualityComparer.Default.Equals(t, factoryType) + || t.AllInterfaces.Any(i => SymbolEqualityComparer.Default.Equals(i, factoryType)); + + bool IsEnumerableOfFactory(ITypeSymbol t) => + t is INamedTypeSymbol named + && SymbolEqualityComparer.Default.Equals(named.OriginalDefinition, enumerable) + && named.TypeArguments.Length == 1 + && IsFactory(named.TypeArguments[0]); + + return IsEnumerableOfFactory(returnType) || returnType.AllInterfaces.Any(IsEnumerableOfFactory); + } + private static void ValidateDurableExecutionSerializerContext(GeneratorExecutionContext context, IMethodSymbol lambdaMethodSymbol, Location methodLocation, List diagnostics) { // The serializer is registered via [assembly: LambdaSerializer(typeof(...))] or the same attribute on diff --git a/Libraries/src/Amazon.Lambda.Annotations/DurableExecutionAttribute.cs b/Libraries/src/Amazon.Lambda.Annotations/DurableExecutionAttribute.cs index 0eb2a36ea..d8491de31 100644 --- a/Libraries/src/Amazon.Lambda.Annotations/DurableExecutionAttribute.cs +++ b/Libraries/src/Amazon.Lambda.Annotations/DurableExecutionAttribute.cs @@ -3,6 +3,27 @@ namespace Amazon.Lambda.Annotations { + /// + /// Which OpenTelemetry view a function registers. + /// + public enum DurableTracing + { + /// No tracing plugin is registered. + None = 0, + + /// + /// Registers the OpenTelemetry plugin with operations as children of the Workflow span + /// (OtelView.Execution). + /// + Execution = 1, + + /// + /// Registers the OpenTelemetry plugin with operations as children of the Invocation span + /// (OtelView.Invocation). + /// + Invocation = 2, + } + /// /// Marks a Lambda function method (also annotated with ) as a /// durable execution workflow. The Amazon.Lambda.Annotations source generator recognizes this @@ -59,6 +80,28 @@ public int RetentionPeriodInDays /// internal bool IsRetentionPeriodInDaysSet { get; private set; } + /// + /// Registers the Amazon.Lambda.DurableExecution.OpenTelemetry plugin with default options. The project must + /// reference that package, and the application must listen to the + /// Amazon.Lambda.DurableExecution activity source (for example through the ADOT layer). + /// The default is . It can be combined with : + /// the OpenTelemetry plugin is registered first, then the provider's. + /// + /// + /// This does not turn on X-Ray active tracing for the function. Set Tracing: Active on the function + /// yourself when X-Ray should sample and propagate a trace. + /// + public DurableTracing Tracing { get; set; } + + /// + /// The name of a static method on the same class that returns the instrumentation plugin factories to + /// register, for example nameof(GetPlugins). It must take no parameters, return + /// IEnumerable<IDurableInstrumentationPluginFactory>, and be at least internal. It is called + /// once, when the function's class is first used, and its factories serve every invocation. Use it to + /// configure the OpenTelemetry plugin (for example the flush callback) or to add other plugins. + /// + public string PluginProvider { get; set; } + /// /// The maximum duration, in seconds, that a single durable execution may run. /// Maps to DurableConfig.ExecutionTimeout on the generated function resource. @@ -84,6 +127,16 @@ internal List Validate() validationErrors.Add($"{nameof(ExecutionTimeout)} = {ExecutionTimeout}. It must be between 1 and {MaxExecutionTimeoutInSeconds}."); } + if (!Enum.IsDefined(typeof(DurableTracing), Tracing)) + { + validationErrors.Add($"{nameof(Tracing)} = {(int)Tracing}. It must be one of {string.Join(", ", Enum.GetNames(typeof(DurableTracing)))}."); + } + + if (PluginProvider != null && string.IsNullOrWhiteSpace(PluginProvider)) + { + validationErrors.Add($"{nameof(PluginProvider)} is empty. Name a static method, for example nameof(GetPlugins), or leave it unset."); + } + return validationErrors; } } diff --git a/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/README.md b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/README.md index 450355c64..b677f7f8b 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/README.md +++ b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/README.md @@ -106,6 +106,10 @@ The plugin supplies the `X-Amzn-Trace-Id` the SDK sends with a chained invoke: t To anchor the execution on a W3C `traceparent` the invoke carried on `clientContext.w3c` (`ILambdaContext.W3C`), set `ContextExtractor = ContextExtractors.W3C`. It returns the trace id, parent span id and sampled flag, and nothing when the header is missing or malformed. +## Lambda Annotations + +`[DurableExecution(Tracing = DurableTracing.Execution)]` (or `Invocation`) adds this plugin to the generated handler. The project must reference this package; otherwise the generator reports AWSLambda0147. `Tracing` does not turn on X-Ray Active tracing in `serverless.template`; set `Tracing: Active` yourself so Lambda supplies the trace header. + ## Span ids and `Activity` `Activity` has no public way to choose its own span id. The plugin sets the private `_spanId` and `_id` fields through `[UnsafeAccessor]`, only for the spans whose ids other invocations must reproduce. It is generated at compile time and works under trimming and Native AOT. The fields are not a contract: if a runtime changes them the override switches itself off and spans get random ids. Parenting inside one invocation still works; references across invocations (the Workflow span, the link from a replayed step to its first segment) then dangle. A test fails when the fields are missing. Listeners notified when a span starts see the random id; export and child spans see the derived one. @@ -113,4 +117,3 @@ To anchor the execution on a W3C `traceparent` the invoke carried on `clientCont ## Not yet available - Loading the plugin from an environment variable or a Lambda layer without code. -- `[DurableExecution(Tracing = ...)]` for Amazon.Lambda.Annotations. diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/README.md b/Libraries/src/Amazon.Lambda.DurableExecution/README.md index 3799667a0..ac6be65c3 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/README.md +++ b/Libraries/src/Amazon.Lambda.DurableExecution/README.md @@ -139,6 +139,12 @@ public class OrderProcessor } ``` +To add instrumentation plugins, set `PluginProvider` to the name of a static parameterless method on the same class that returns `IEnumerable`, and/or set `Tracing` to `DurableTracing.Execution` or `DurableTracing.Invocation` for OpenTelemetry (requires `Amazon.Lambda.DurableExecution.OpenTelemetry`). When both are set, the OpenTelemetry plugin runs first. The generator reports AWSLambda0146 to AWSLambda0148 when a plugin option cannot be honored. + +```csharp +[DurableExecution(300, Tracing = DurableTracing.Execution, PluginProvider = nameof(GetPlugins))] +``` + Works with both the executable and class-library programming models — set `[assembly: LambdaGlobalProperties(GenerateMain = true)]` for the executable model, or omit it for a class library (the generated `serverless.template` `Handler` adapts to each). The generator validates the `(TInput, IDurableContext) -> Task`/`Task` signature and Zip packaging, and reports a diagnostic otherwise. ## Documentation diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/DurableExecutionPluginTests.cs b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/DurableExecutionPluginTests.cs new file mode 100644 index 000000000..be4a4642a --- /dev/null +++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/DurableExecutionPluginTests.cs @@ -0,0 +1,366 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +using System; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Amazon.Lambda.Annotations.SourceGenerator.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Testing; +using Microsoft.CodeAnalysis.Text; +using Xunit; +using VerifyCS = Amazon.Lambda.Annotations.SourceGenerators.Tests.CSharpSourceGeneratorVerifier; + +namespace Amazon.Lambda.Annotations.SourceGenerators.Tests +{ + /// + /// [DurableExecution(Tracing = ..., PluginProvider = ...)]: what the generator emits for them, and the + /// diagnostics that stop a mistake from becoming a compile error in generated code. + /// + /// + /// The real durable packages cannot be referenced here (their AWSSDK.Core 4.x conflicts with the 3.7.x pin the + /// generator-test framework needs), so the types the generator resolves by metadata name, and the + /// WrapAsync overloads the wrapper binds to, are supplied as source stubs, as in the other durable tests. + /// + [Collection(TestServerlessAppCollection.Name)] + public class DurableExecutionPluginTests : IDisposable + { + private const string PluginApiStubs = @" +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Amazon.Lambda.Core; + +namespace Amazon.Lambda.DurableExecution.Instrumentation +{ + public interface IDurableInstrumentationPluginFactory { } +} + +namespace Amazon.Lambda.DurableExecution +{ + public interface IDurableContext { } + public sealed class DurableExecutionInvocationInput { } + public sealed class DurableExecutionInvocationOutput { } + + public sealed class DurableExecutionOptions + { + public IList Plugins { get; } = + new List(); + } + + public static class DurableFunction + { + public static Task WrapAsync( + Func> workflow, DurableExecutionInvocationInput invocationInput, ILambdaContext lambdaContext) + => Task.FromResult(new DurableExecutionInvocationOutput()); + + public static Task WrapAsync( + Func> workflow, DurableExecutionInvocationInput invocationInput, ILambdaContext lambdaContext, + DurableExecutionOptions options) + => Task.FromResult(new DurableExecutionInvocationOutput()); + + public static Task WrapAsync( + Func workflow, DurableExecutionInvocationInput invocationInput, ILambdaContext lambdaContext) + => Task.FromResult(new DurableExecutionInvocationOutput()); + + public static Task WrapAsync( + Func workflow, DurableExecutionInvocationInput invocationInput, ILambdaContext lambdaContext, + DurableExecutionOptions options) + => Task.FromResult(new DurableExecutionInvocationOutput()); + } +} +"; + + private const string OtelStubs = @" +namespace Amazon.Lambda.DurableExecution.OpenTelemetry +{ + public enum OtelView { Execution, Invocation } + + public static class OtelPlugin + { + public static Amazon.Lambda.DurableExecution.Instrumentation.IDurableInstrumentationPluginFactory CreateFactory(OtelView view = OtelView.Execution) => null; + } +} +"; + + // The package from before the plugin API: only the envelope types and the original WrapAsync. + private const string OldDurableStubs = @" +using System; +using System.Threading.Tasks; +using Amazon.Lambda.Core; + +namespace Amazon.Lambda.DurableExecution +{ + public interface IDurableContext { } + public sealed class DurableExecutionInvocationInput { } + public sealed class DurableExecutionInvocationOutput { } + + public static class DurableFunction + { + public static Task WrapAsync( + Func> workflow, DurableExecutionInvocationInput invocationInput, ILambdaContext lambdaContext) + => Task.FromResult(new DurableExecutionInvocationOutput()); + } +} +"; + + private const string AssemblyAttributes = + "[assembly: Amazon.Lambda.Core.LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]\n"; + + private static async Task AnnotationsSource(string fileName) => + await File.ReadAllTextAsync(Path.Combine("Amazon.Lambda.Annotations", fileName)); + + private static async Task NewTestAsync(string userSource, params string[] stubs) + { + var test = new VerifyCS.Test + { + TestState = + { + OutputKind = OutputKind.DynamicallyLinkedLibrary, + Sources = + { + ("Workflow.cs", userSource), + ("AssemblyAttributes.cs", AssemblyAttributes), + (Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), await AnnotationsSource("LambdaFunctionAttribute.cs")), + (Path.Combine("Amazon.Lambda.Annotations", "DurableExecutionAttribute.cs"), await AnnotationsSource("DurableExecutionAttribute.cs")), + }, + }, + }; + for (var i = 0; i < stubs.Length; i++) + test.TestState.Sources.Add(($"Stubs{i}.cs", stubs[i])); + + // The generator reports an Info (AWSLambda0103) for each file it writes; these tests are about the + // wrapper and the diagnostics. Generated-source comparison is off unless a test supplies snapshots. + test.DisabledDiagnostics.Add("AWSLambda0103"); + test.TestBehaviors |= TestBehaviors.SkipGeneratedSourcesCheck; + test.CompilerDiagnostics = CompilerDiagnostics.None; + return test; + } + + private static string Workflow(string attributeArguments, string members = "") => $@"using System.Collections.Generic; +using System.Threading.Tasks; +using Amazon.Lambda.Annotations; +using Amazon.Lambda.DurableExecution; +using Amazon.Lambda.DurableExecution.Instrumentation; + +namespace MyApp +{{ + public class Workflows + {{ +{members} [LambdaFunction] + [DurableExecution(300{attributeArguments})] + public Task Run(string input, IDurableContext ctx) => Task.FromResult(input); + }} +}}"; + + // The location the generator reports: from the [LambdaFunction] attribute to the end of the method. + private static DiagnosticResult At(string id, DiagnosticSeverity severity, string source) + { + var lines = source.Replace("\r\n", "\n").Split('\n'); + var first = Array.FindIndex(lines, l => l.Contains("[LambdaFunction]")); + var last = Array.FindIndex(lines, first, l => l.TrimStart().StartsWith("public Task Run")); + return new DiagnosticResult(id, severity) + .WithSpan("Workflow.cs", first + 1, lines[first].IndexOf('[') + 1, last + 1, lines[last].Length + 1); + } + + // ── What is generated ─────────────────────────────────────────────── + + [Fact] + public async Task VerifyDurablePlugins() + { + var test = new VerifyCS.Test + { + TestState = + { + OutputKind = OutputKind.DynamicallyLinkedLibrary, + Sources = + { + (Path.Combine("TestServerlessApp", "PlaceholderClass.cs"), await File.ReadAllTextAsync(Path.Combine("TestServerlessApp", "PlaceholderClass.cs"))), + (Path.Combine("TestServerlessApp", "DurableExecutionExamples", "DurablePluginExamples.cs"), await File.ReadAllTextAsync(Path.Combine("TestServerlessApp", "DurableExecutionExamples", "DurablePluginExamples.cs.txt"))), + ("PluginApiStubs.cs", PluginApiStubs), + ("OtelStubs.cs", OtelStubs), + (Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), await AnnotationsSource("LambdaFunctionAttribute.cs")), + (Path.Combine("Amazon.Lambda.Annotations", "DurableExecutionAttribute.cs"), await AnnotationsSource("DurableExecutionAttribute.cs")), + ("AssemblyAttributes.cs", AssemblyAttributes), + }, + }, + }; + + foreach (var name in new[] { "TracedDurableExecution", "ProviderDurableExecution", "TracedProviderDurableExecution" }) + { + var expected = await ReadSnapshotContent(Path.Combine("Snapshots", "DurableExecution", $"{name}_ProcessOrder_Generated.g.cs")); + test.TestState.GeneratedSources.Add(( + typeof(SourceGenerator.Generator), + $"{name}_ProcessOrder_Generated.g.cs", + SourceText.From(expected, Encoding.UTF8, SourceHashAlgorithm.Sha256))); + } + + test.DisabledDiagnostics.Add("AWSLambda0103"); + // The generated code is compiled against the stubs and must bind, including the WrapAsync overload that + // takes the options. Anything but the harness's own bookkeeping is a failure. + await test.RunAsync(); + } + + // ── Diagnostics: the attribute ────────────────────────────────────── + + [Fact] + public async Task TracingNone_AndNoProvider_ReportsNothing() + { + var source = Workflow(", Tracing = DurableTracing.None"); + var test = await NewTestAsync(source, OldDurableStubs); + + await test.RunAsync(); + } + + [Fact] + public async Task EmptyPluginProvider_IsAnInvalidAttribute() + { + var source = Workflow(", PluginProvider = \"\""); + var test = await NewTestAsync(source, PluginApiStubs); + test.TestState.ExpectedDiagnostics.Add(At("AWSLambda0144", DiagnosticSeverity.Error, source) + .WithArguments("PluginProvider is empty. Name a static method, for example nameof(GetPlugins), or leave it unset.")); + + await test.RunAsync(); + } + + [Fact] + public async Task UndefinedTracingValue_IsAnInvalidAttribute() + { + var source = Workflow(", Tracing = (DurableTracing)7"); + var test = await NewTestAsync(source, PluginApiStubs, OtelStubs); + test.TestState.ExpectedDiagnostics.Add(At("AWSLambda0144", DiagnosticSeverity.Error, source) + .WithArguments("Tracing = 7. It must be one of None, Execution, Invocation.")); + + await test.RunAsync(); + } + + // ── Diagnostics: Tracing ──────────────────────────────────────────── + + [Fact] + public async Task Tracing_WithoutTheOpenTelemetryPackage_ReportsError() + { + var source = Workflow(", Tracing = DurableTracing.Invocation"); + var test = await NewTestAsync(source, PluginApiStubs); + test.TestState.ExpectedDiagnostics.Add(At("AWSLambda0147", DiagnosticSeverity.Error, source).WithArguments("Invocation")); + + await test.RunAsync(); + } + + [Fact] + public async Task Tracing_WithAnOlderDurablePackage_ReportsThePluginApiIsMissing() + { + var source = Workflow(", Tracing = DurableTracing.Execution"); + var test = await NewTestAsync(source, OldDurableStubs, OtelStubs); + test.TestState.ExpectedDiagnostics.Add(At("AWSLambda0146", DiagnosticSeverity.Error, source) + .WithArguments("Tracing", "Amazon.Lambda.DurableExecution.DurableExecutionOptions")); + + await test.RunAsync(); + } + + [Fact] + public async Task Tracing_WithThePackages_ReportsNothing() + { + var source = Workflow(", Tracing = DurableTracing.Execution"); + var test = await NewTestAsync(source, PluginApiStubs, OtelStubs); + + await test.RunAsync(); + } + + // ── Diagnostics: PluginProvider ───────────────────────────────────── + + private const string Factories = "IEnumerable"; + + [Theory] + [InlineData("internal static " + Factories + " GetPlugins() => null;")] + [InlineData("public static " + Factories + " GetPlugins() => null;")] + [InlineData("protected internal static " + Factories + " GetPlugins() => null;")] + [InlineData("internal static IDurableInstrumentationPluginFactory[] GetPlugins() => null;")] + [InlineData("internal static List GetPlugins() => null;")] + [InlineData("internal static IEnumerable GetPlugins() => null;")] + public async Task PluginProvider_ThatCanBeCalled_ReportsNothing(string method) + { + var source = Workflow(", PluginProvider = nameof(GetPlugins)", " class MyFactory : IDurableInstrumentationPluginFactory { }\n " + method + "\n\n"); + var test = await NewTestAsync(source, PluginApiStubs); + + await test.RunAsync(); + } + + [Fact] + public async Task PluginProvider_WithNoSuchMethod_ReportsError() + { + var source = Workflow(", PluginProvider = \"Missing\""); + var test = await NewTestAsync(source, PluginApiStubs); + test.TestState.ExpectedDiagnostics.Add(At("AWSLambda0148", DiagnosticSeverity.Error, source) + .WithArguments("Missing", "'MyApp.Workflows' has no method with that name.")); + + await test.RunAsync(); + } + + [Theory] + [InlineData("internal " + Factories + " GetPlugins() => null;", "it must be static.")] + [InlineData("internal static " + Factories + " GetPlugins(int count) => null;", "it must take no parameters and have no type parameters.")] + [InlineData("internal static " + Factories + " GetPlugins() => null;", "it must take no parameters and have no type parameters.")] + [InlineData("private static " + Factories + " GetPlugins() => null;", "it is private, but the generated code must be able to call it. Make it internal or public.")] + [InlineData("protected static " + Factories + " GetPlugins() => null;", "it is protected, but the generated code must be able to call it. Make it internal or public.")] + [InlineData("internal static string GetPlugins() => null;", "it must return IEnumerable but returns 'string'.")] + [InlineData("internal static IEnumerable GetPlugins() => null;", "it must return IEnumerable but returns 'System.Collections.Generic.IEnumerable'.")] + public async Task PluginProvider_ThatCannotBeUsed_ReportsWhy(string method, string reason) + { + var source = Workflow(", PluginProvider = nameof(GetPlugins)", " " + method + "\n\n"); + var test = await NewTestAsync(source, PluginApiStubs); + test.TestState.ExpectedDiagnostics.Add(At("AWSLambda0148", DiagnosticSeverity.Error, source).WithArguments("GetPlugins", reason)); + + await test.RunAsync(); + } + + [Fact] + public async Task PluginProvider_WithAnOverloadThatWorks_IsAccepted() + { + var source = Workflow(", PluginProvider = nameof(GetPlugins)", + " internal static " + Factories + " GetPlugins(int count) => null;\n" + + " internal static " + Factories + " GetPlugins() => null;\n\n"); + var test = await NewTestAsync(source, PluginApiStubs); + + await test.RunAsync(); + } + + [Fact] + public async Task PluginProvider_WithAnOlderDurablePackage_ReportsThePluginApiIsMissing() + { + var source = Workflow(", PluginProvider = nameof(GetPlugins)", " internal static string GetPlugins() => null;\n\n"); + var test = await NewTestAsync(source, OldDurableStubs); + test.TestState.ExpectedDiagnostics.Add(At("AWSLambda0146", DiagnosticSeverity.Error, source) + .WithArguments("PluginProvider", "Amazon.Lambda.DurableExecution.DurableExecutionOptions")); + + await test.RunAsync(); + } + + [Fact] + public async Task TracingAndAProviderThatIsMissing_ReportBothProblems() + { + var source = Workflow(", Tracing = DurableTracing.Execution, PluginProvider = \"Missing\""); + var test = await NewTestAsync(source, PluginApiStubs); + test.TestState.ExpectedDiagnostics.Add(At("AWSLambda0147", DiagnosticSeverity.Error, source).WithArguments("Execution")); + test.TestState.ExpectedDiagnostics.Add(At("AWSLambda0148", DiagnosticSeverity.Error, source) + .WithArguments("Missing", "'MyApp.Workflows' has no method with that name.")); + + await test.RunAsync(); + } + + public void Dispose() + { + var template = Path.Combine("TestServerlessApp", "serverless.template"); + if (File.Exists(template)) + File.Delete(template); + } + + private static async Task ReadSnapshotContent(string snapshotPath) + { + var content = await File.ReadAllTextAsync(snapshotPath); + return content.Trim().ToEnvironmentLineEndings().ApplyReplacements(); + } + } +} diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/DurableExecution/ProviderDurableExecution_ProcessOrder_Generated.g.cs b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/DurableExecution/ProviderDurableExecution_ProcessOrder_Generated.g.cs new file mode 100644 index 000000000..cfc3de045 --- /dev/null +++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/DurableExecution/ProviderDurableExecution_ProcessOrder_Generated.g.cs @@ -0,0 +1,74 @@ +// + +using System; +using System.Linq; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using System.IO; +using Amazon.Lambda.Core; +using Amazon.Lambda.DurableExecution; + +namespace TestServerlessApp.DurableExecutionExamples +{ + /// + /// The generated Lambda function handler for . + /// + public class ProviderDurableExecution_ProcessOrder_Generated + { + private readonly ProviderDurableExecution providerDurableExecution; + private readonly Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer serializer; + + // The durable instrumentation plugins are created once, when the function starts. The SDK asks each factory + // for a new plugin on every invocation. + private static readonly Amazon.Lambda.DurableExecution.DurableExecutionOptions __durableExecutionOptions__ = CreateDurableExecutionOptions(); + + private static Amazon.Lambda.DurableExecution.DurableExecutionOptions CreateDurableExecutionOptions() + { + var options = new Amazon.Lambda.DurableExecution.DurableExecutionOptions(); + foreach (var factory in TestServerlessApp.DurableExecutionExamples.ProviderDurableExecution.GetPlugins()) + options.Plugins.Add(factory); + return options; + } + + /// + /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment + /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the + /// region the Lambda function is executed in. + /// + public ProviderDurableExecution_ProcessOrder_Generated() + { + SetExecutionEnvironment(); + providerDurableExecution = new ProviderDurableExecution(); + serializer = new Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer(); + } + + /// + /// The generated Lambda function handler for + /// + /// The durable execution service envelope that will be processed by the Lambda function handler. + /// The ILambdaContext that provides methods for logging and describing the Lambda environment. + /// Result of the Lambda function execution + public async System.Threading.Tasks.Task ProcessOrder(Amazon.Lambda.DurableExecution.DurableExecutionInvocationInput __request__, Amazon.Lambda.Core.ILambdaContext __context__) + { + return await Amazon.Lambda.DurableExecution.DurableFunction.WrapAsync(providerDurableExecution.ProcessOrder, __request__, __context__, __durableExecutionOptions__); + } + + private static void SetExecutionEnvironment() + { + const string envName = "AWS_EXECUTION_ENV"; + + var envValue = new StringBuilder(); + + // If there is an existing execution environment variable add the annotations package as a suffix. + if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName))) + { + envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_"); + } + + envValue.Append("lib/amazon-lambda-annotations#{ANNOTATIONS_ASSEMBLY_VERSION}"); + + Environment.SetEnvironmentVariable(envName, envValue.ToString()); + } + } +} \ No newline at end of file diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/DurableExecution/TracedDurableExecution_ProcessOrder_Generated.g.cs b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/DurableExecution/TracedDurableExecution_ProcessOrder_Generated.g.cs new file mode 100644 index 000000000..b5dcff33f --- /dev/null +++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/DurableExecution/TracedDurableExecution_ProcessOrder_Generated.g.cs @@ -0,0 +1,73 @@ +// + +using System; +using System.Linq; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using System.IO; +using Amazon.Lambda.Core; +using Amazon.Lambda.DurableExecution; + +namespace TestServerlessApp.DurableExecutionExamples +{ + /// + /// The generated Lambda function handler for . + /// + public class TracedDurableExecution_ProcessOrder_Generated + { + private readonly TracedDurableExecution tracedDurableExecution; + private readonly Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer serializer; + + // The durable instrumentation plugins are created once, when the function starts. The SDK asks each factory + // for a new plugin on every invocation. + private static readonly Amazon.Lambda.DurableExecution.DurableExecutionOptions __durableExecutionOptions__ = CreateDurableExecutionOptions(); + + private static Amazon.Lambda.DurableExecution.DurableExecutionOptions CreateDurableExecutionOptions() + { + var options = new Amazon.Lambda.DurableExecution.DurableExecutionOptions(); + options.Plugins.Add(Amazon.Lambda.DurableExecution.OpenTelemetry.OtelPlugin.CreateFactory(Amazon.Lambda.DurableExecution.OpenTelemetry.OtelView.Execution)); + return options; + } + + /// + /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment + /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the + /// region the Lambda function is executed in. + /// + public TracedDurableExecution_ProcessOrder_Generated() + { + SetExecutionEnvironment(); + tracedDurableExecution = new TracedDurableExecution(); + serializer = new Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer(); + } + + /// + /// The generated Lambda function handler for + /// + /// The durable execution service envelope that will be processed by the Lambda function handler. + /// The ILambdaContext that provides methods for logging and describing the Lambda environment. + /// Result of the Lambda function execution + public async System.Threading.Tasks.Task ProcessOrder(Amazon.Lambda.DurableExecution.DurableExecutionInvocationInput __request__, Amazon.Lambda.Core.ILambdaContext __context__) + { + return await Amazon.Lambda.DurableExecution.DurableFunction.WrapAsync(tracedDurableExecution.ProcessOrder, __request__, __context__, __durableExecutionOptions__); + } + + private static void SetExecutionEnvironment() + { + const string envName = "AWS_EXECUTION_ENV"; + + var envValue = new StringBuilder(); + + // If there is an existing execution environment variable add the annotations package as a suffix. + if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName))) + { + envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_"); + } + + envValue.Append("lib/amazon-lambda-annotations#{ANNOTATIONS_ASSEMBLY_VERSION}"); + + Environment.SetEnvironmentVariable(envName, envValue.ToString()); + } + } +} \ No newline at end of file diff --git a/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/DurableExecution/TracedProviderDurableExecution_ProcessOrder_Generated.g.cs b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/DurableExecution/TracedProviderDurableExecution_ProcessOrder_Generated.g.cs new file mode 100644 index 000000000..3125cd995 --- /dev/null +++ b/Libraries/test/Amazon.Lambda.Annotations.SourceGenerators.Tests/Snapshots/DurableExecution/TracedProviderDurableExecution_ProcessOrder_Generated.g.cs @@ -0,0 +1,75 @@ +// + +using System; +using System.Linq; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using System.IO; +using Amazon.Lambda.Core; +using Amazon.Lambda.DurableExecution; + +namespace TestServerlessApp.DurableExecutionExamples +{ + /// + /// The generated Lambda function handler for . + /// + public class TracedProviderDurableExecution_ProcessOrder_Generated + { + private readonly TracedProviderDurableExecution tracedProviderDurableExecution; + private readonly Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer serializer; + + // The durable instrumentation plugins are created once, when the function starts. The SDK asks each factory + // for a new plugin on every invocation. + private static readonly Amazon.Lambda.DurableExecution.DurableExecutionOptions __durableExecutionOptions__ = CreateDurableExecutionOptions(); + + private static Amazon.Lambda.DurableExecution.DurableExecutionOptions CreateDurableExecutionOptions() + { + var options = new Amazon.Lambda.DurableExecution.DurableExecutionOptions(); + options.Plugins.Add(Amazon.Lambda.DurableExecution.OpenTelemetry.OtelPlugin.CreateFactory(Amazon.Lambda.DurableExecution.OpenTelemetry.OtelView.Invocation)); + foreach (var factory in TestServerlessApp.DurableExecutionExamples.TracedProviderDurableExecution.GetPlugins()) + options.Plugins.Add(factory); + return options; + } + + /// + /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment + /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the + /// region the Lambda function is executed in. + /// + public TracedProviderDurableExecution_ProcessOrder_Generated() + { + SetExecutionEnvironment(); + tracedProviderDurableExecution = new TracedProviderDurableExecution(); + serializer = new Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer(); + } + + /// + /// The generated Lambda function handler for + /// + /// The durable execution service envelope that will be processed by the Lambda function handler. + /// The ILambdaContext that provides methods for logging and describing the Lambda environment. + /// Result of the Lambda function execution + public async System.Threading.Tasks.Task ProcessOrder(Amazon.Lambda.DurableExecution.DurableExecutionInvocationInput __request__, Amazon.Lambda.Core.ILambdaContext __context__) + { + return await Amazon.Lambda.DurableExecution.DurableFunction.WrapAsync(tracedProviderDurableExecution.ProcessOrder, __request__, __context__, __durableExecutionOptions__); + } + + private static void SetExecutionEnvironment() + { + const string envName = "AWS_EXECUTION_ENV"; + + var envValue = new StringBuilder(); + + // If there is an existing execution environment variable add the annotations package as a suffix. + if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName))) + { + envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_"); + } + + envValue.Append("lib/amazon-lambda-annotations#{ANNOTATIONS_ASSEMBLY_VERSION}"); + + Environment.SetEnvironmentVariable(envName, envValue.ToString()); + } + } +} \ No newline at end of file diff --git a/Libraries/test/TestDurableServerlessApp/Function.cs b/Libraries/test/TestDurableServerlessApp/Function.cs index 17385ef47..47b4c34ed 100644 --- a/Libraries/test/TestDurableServerlessApp/Function.cs +++ b/Libraries/test/TestDurableServerlessApp/Function.cs @@ -4,6 +4,7 @@ using Amazon.Lambda.Annotations; using Amazon.Lambda.Core; using Amazon.Lambda.DurableExecution; +using Amazon.Lambda.DurableExecution.Instrumentation; // Durable execution via the Lambda Annotations programming model, class-library variant. The source // generator emits the durable handler wrapper (Function_Workflow_Generated) that delegates to @@ -18,8 +19,12 @@ public class Function // [LambdaFunction] + [DurableExecution] => the generator emits DurableConfig (with the required // ExecutionTimeout) and the checkpoint-API IAM policy into serverless.template, and a wrapper that // calls DurableFunction.WrapAsync. Two chained steps exercise checkpointing. + // + // Tracing registers the OpenTelemetry plugin and PluginProvider adds more plugin factories, so the generated + // wrapper is built against the real plugin API on every build. With no listener on the activity source the + // plugin does nothing, so the workflow behaves as it did without them. [LambdaFunction] - [DurableExecution(executionTimeout: 300)] + [DurableExecution(executionTimeout: 300, Tracing = DurableTracing.Execution, PluginProvider = nameof(GetPlugins))] public async Task Workflow(TestEvent input, IDurableContext context) { var step1 = await context.StepAsync( @@ -32,6 +37,14 @@ public async Task Workflow(TestEvent input, IDurableContext context) return new TestResult { Status = "completed", Data = step2 }; } + + internal static IEnumerable GetPlugins() => new IDurableInstrumentationPluginFactory[] { new PassThroughPluginFactory() }; + + // A plugin factory that opts out of every invocation. It only proves a provider's factories are registered. + private sealed class PassThroughPluginFactory : IDurableInstrumentationPluginFactory + { + public IDurableInstrumentationPlugin? CreatePlugin(InvocationInfo info) => null; + } } public class TestEvent { public string? OrderId { get; set; } } diff --git a/Libraries/test/TestDurableServerlessApp/TestDurableServerlessApp.csproj b/Libraries/test/TestDurableServerlessApp/TestDurableServerlessApp.csproj index ba8f09322..bee1e984b 100644 --- a/Libraries/test/TestDurableServerlessApp/TestDurableServerlessApp.csproj +++ b/Libraries/test/TestDurableServerlessApp/TestDurableServerlessApp.csproj @@ -14,6 +14,7 @@ + diff --git a/Libraries/test/TestServerlessApp/DurableExecutionExamples/DurablePluginExamples.cs.txt b/Libraries/test/TestServerlessApp/DurableExecutionExamples/DurablePluginExamples.cs.txt new file mode 100644 index 000000000..0166d0902 --- /dev/null +++ b/Libraries/test/TestServerlessApp/DurableExecutionExamples/DurablePluginExamples.cs.txt @@ -0,0 +1,50 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +using System.Collections.Generic; +using System.Threading.Tasks; +using Amazon.Lambda.Annotations; +using Amazon.Lambda.DurableExecution; +using Amazon.Lambda.DurableExecution.Instrumentation; + +namespace TestServerlessApp.DurableExecutionExamples +{ + // This file represents valid usage of DurableExecutionAttribute.Tracing and .PluginProvider. It is a .txt file + // because we do not want to deploy these functions during integration tests; it is only fed to the + // source-generator unit tests. Refer to the VerifyDurablePlugins unit test. + + public class TracedDurableExecution + { + [LambdaFunction] + [DurableExecution(300, Tracing = DurableTracing.Execution)] + public Task ProcessOrder(string input, IDurableContext context) + { + return Task.FromResult(input); + } + } + + public class ProviderDurableExecution + { + // Internal is enough: the generated class is in the same assembly. + internal static IEnumerable GetPlugins() => new IDurableInstrumentationPluginFactory[0]; + + [LambdaFunction] + [DurableExecution(300, PluginProvider = nameof(GetPlugins))] + public Task ProcessOrder(string input, IDurableContext context) + { + return Task.CompletedTask; + } + } + + public class TracedProviderDurableExecution + { + public static IEnumerable GetPlugins() => new List(); + + [LambdaFunction] + [DurableExecution(300, Tracing = DurableTracing.Invocation, PluginProvider = nameof(GetPlugins))] + public Task ProcessOrder(string input, IDurableContext context) + { + return Task.FromResult(input); + } + } +}