From 96765ccc3aba6b624f6b22da88ee096ee5e92473 Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Sat, 24 Jan 2026 11:10:32 -0500 Subject: [PATCH 01/17] refactor(codebase): normalize code style by updating formatting across multiple files - Corrected inconsistent parameter formatting in constructors and method declarations. - Adjusted newline usage to ensure better readability and consistency in indentation. - Standardized the wrapping of multi-line argument values and initializer blocks. - Updated project references in .csproj files by removing unnecessary spaces for uniform formatting. --- CLAUDE.md | 1 + Directory.Packages.props | 122 ++++---- MinimalLambda.sln.DotSettings | 148 ++-------- README.md | 48 ++-- .../MinimalLambda.Benchmarks.csproj | 4 +- ...nimalLambda.Example.ClassMiddleware.csproj | 2 +- .../Program.cs | 5 +- .../MinimalLambda.Example.Events.csproj | 8 +- .../MinimalLambda.Example.Events/Program.cs | 43 ++- .../MinimalLambda.Example.HelloWorld.csproj | 4 +- .../Program.cs | 5 +- ...MinimalLambda.Example.HelloWorldAot.csproj | 2 +- .../Program.cs | 44 ++- .../MinimalLambda.Example.Lifecycle.csproj | 2 +- .../Program.cs | 59 ++-- .../Function.cs | 3 +- ...MinimalLambda.Example.OpenTelemetry.csproj | 16 +- .../OpenTelemetryRegistrationExtensions.cs | 62 ++-- .../AotCompatibility.TestApp.csproj | 30 +- .../AlbRequestEnvelope.cs | 8 +- .../AlbResponseEnvelope.cs | 8 +- .../AlbResponseEnvelopeBase.cs | 3 +- .../MinimalLambda.Envelopes.Alb/AlbResult.cs | 6 +- .../MinimalLambda.Envelopes.Alb.csproj | 10 +- .../MinimalLambda.Envelopes.Alb/README.md | 4 +- .../ApiGatewayRequestEnvelope.cs | 8 +- .../ApiGatewayResponseEnvelope.cs | 8 +- .../ApiGatewayResult.cs | 6 +- .../ApiGatewayV2RequestEnvelope.cs | 8 +- .../ApiGatewayV2RequestEnvelopeBase.cs | 3 +- .../ApiGatewayV2ResponseEnvelope.cs | 8 +- .../ApiGatewayV2ResponseEnvelopeBase.cs | 3 +- .../ApiGatewayV2Result.cs | 9 +- .../MinimalLambda.Envelopes.ApiGateway.csproj | 10 +- .../README.md | 7 +- .../CloudWatchLogsEnvelopeBase.cs | 12 +- .../CloudWatchLogsEnvelopeT.cs | 11 +- ...imalLambda.Envelopes.CloudWatchLogs.csproj | 8 +- .../README.md | 4 +- .../KafkaEnvelope.cs | 22 +- .../MinimalLambda.Envelopes.Kafka.csproj | 8 +- .../MinimalLambda.Envelopes.Kafka/README.md | 4 +- .../KinesisEnvelope.cs | 14 +- .../MinimalLambda.Envelopes.Kinesis.csproj | 10 +- .../MinimalLambda.Envelopes.Kinesis/README.md | 4 +- .../KinesisFirehoseEventEnvelope.cs | 11 +- .../KinesisFirehoseResponseEnvelope.cs | 8 +- .../KinesisFirehoseResponseEnvelopeBase.cs | 3 +- ...malLambda.Envelopes.KinesisFirehose.csproj | 8 +- .../README.md | 4 +- .../MinimalLambda.Envelopes.Sns.csproj | 8 +- .../MinimalLambda.Envelopes.Sns/README.md | 4 +- .../SnsEnvelope.cs | 11 +- .../MinimalLambda.Envelopes.Sqs.csproj | 10 +- .../MinimalLambda.Envelopes.Sqs/README.md | 4 +- .../SqsEnvelope.cs | 8 +- .../SqsSnsEnvelope.cs | 14 +- .../BaseHttpResultExtensions.cs | 12 +- .../HttpResultExtensions.cs | 9 +- .../MinimalLambda.Envelopes/IHttpResult.cs | 6 +- .../MinimalLambda.Envelopes.csproj | 6 +- .../MinimalLambda.Envelopes/README.md | 10 +- src/Envelopes/README.md | 4 +- .../Attributes/EventAttribute.cs | 3 +- .../Builders/ILambdaInvocationBuilder.cs | 3 +- .../MinimalLambda.Abstractions.csproj | 10 +- src/MinimalLambda.Abstractions/README.md | 6 +- .../MiddlewareOpenTelemetryExtensions.cs | 22 +- .../MinimalLambda.OpenTelemetry.csproj | 8 +- .../OnShutdownOpenTelemetryExtensions.cs | 50 ++-- src/MinimalLambda.OpenTelemetry/README.md | 6 +- .../AnalyzerReleases.Shipped.md | 4 +- .../Diagnostics/DiagnosticGenerator.cs | 12 +- .../Diagnostics/DiagnosticInfo.cs | 10 +- .../Diagnostics/DiagnosticResult.cs | 8 +- .../Diagnostics/Diagnostics.cs | 17 +- .../Emitters/InvocationHandlerEmitter.cs | 6 +- .../Emitters/LifecycleHandlerEmitter.cs | 11 +- .../Emitters/MiddlewareClassEmitter.cs | 6 +- .../Emitters/TemplateHelper.cs | 16 +- .../Extensions/EnumerableExtensions.cs | 15 +- .../IncrementalValueProviderExtensions.cs | 13 +- .../Extensions/MethodSymbolExtensions.cs | 39 +-- .../Extensions/ParameterSymbolExtensions.cs | 65 ++--- .../Extensions/SyntaxNodeExtensions.cs | 6 +- .../Extensions/TypeSymbolExtensions.cs | 6 +- .../GeneratorContext.cs | 6 +- .../MinimalLambda.SourceGenerators.csproj | 20 +- .../MinimalLambdaGenerator.cs | 31 +- .../Handlers/LifecycleHandlerParameterInfo.cs | 55 ++-- .../Models/Handlers/LifecycleMethodInfo.cs | 61 ++-- .../Models/Handlers/MapHandlerMethodInfo.cs | 48 ++-- .../Handlers/MapHandlerParameterInfo.cs | 58 ++-- .../Models/Middleware/MiddlewareClassInfo.cs | 77 ++--- .../Middleware/MiddlewareParameterInfo.cs | 52 ++-- .../Models/Middleware/UseMiddlewareTInfo.cs | 50 ++-- .../Models/Shared/CompilationInfo.cs | 3 +- .../Shared/InterceptableLocationInfo.cs | 12 +- .../Models/Shared/LocationInfo.cs | 9 +- .../SyntaxProviders/HandlerSyntaxProvider.cs | 55 ++-- .../UseMiddlewareTSyntaxProvider.cs | 34 +-- .../WellKnownTypes/BoundedCacheWithFactory.cs | 3 +- .../WellKnownTypes/WellKnownTypes.cs | 31 +- .../DeferredHostBuilder.cs | 33 +-- .../LambdaApplicationFactory.cs | 79 ++--- ...aApplicationFactoryContentRootAttribute.cs | 10 +- .../LambdaHttpHandler.cs | 12 +- .../LambdaRuntimeRouteManager.cs | 15 +- src/MinimalLambda.Testing/LambdaTestServer.cs | 140 ++++----- .../LambdaTestServerExtensions.cs | 18 +- .../MinimalLambda.Testing.csproj | 16 +- .../Models/LambdaHttpTransaction.cs | 3 +- .../Models/PendingInvocation.cs | 6 +- src/MinimalLambda.Testing/README.md | 2 +- src/MinimalLambda.Testing/TaskHelpers.cs | 25 +- .../DefaultLambdaOnInitBuilderFactory.cs | 3 +- .../DefaultLambdaOnShutdownBuilderFactory.cs | 3 +- ...daHttpClientServiceCollectionExtensions.cs | 15 +- .../MiddlewareLambdaApplicationExtensions.cs | 3 +- .../SerializerServiceCollectionExtensions.cs | 11 +- .../Extensions/ServiceCollectionExtensions.cs | 52 ++-- .../MapHandlerLambdaApplicationExtensions.cs | 3 +- .../OnInitLambdaApplicationExtensions.cs | 3 +- .../OnShutdownLambdaApplicationExtensions.cs | 3 +- ...seMiddlewareLambdaApplicationExtensions.cs | 4 +- .../Builder/LambdaApplication.cs | 10 +- .../Builder/LambdaApplicationBuilder.cs | 34 +-- .../Builder/LambdaInvocationBuilder.cs | 7 +- .../Builder/LambdaOnInitBuilder.cs | 15 +- .../Builder/LambdaOnShutdownBuilder.cs | 9 +- .../ClearLambdaOutputFormattingMiddleware.cs | 3 +- .../Middleware/RequestEnvelopeMiddleware.cs | 16 +- ...utFormattingLambdaApplicationExtensions.cs | 19 +- .../DefaultLambdaCancellationFactory.cs | 10 +- .../ILambdaInvocationContextFactory.cs | 3 +- .../Context/ILambdaLifecycleContextFactory.cs | 3 +- .../Core/Context/LambdaInvocationContext.cs | 3 +- .../Context/LambdaInvocationContextFactory.cs | 15 +- .../Core/Context/LambdaLifecycleContext.cs | 3 +- .../Context/LambdaLifecycleContextFactory.cs | 19 +- .../Core/Features/DefaultEventFeature.cs | 16 +- .../Core/Features/DefaultFeatureCollection.cs | 6 +- .../Features/FeatureCollectionExtensions.cs | 5 +- ...eatureLambdaInvocationContextExtensions.cs | 6 +- .../Options/HostOptionsPostConfiguration.cs | 4 +- src/MinimalLambda/MinimalLambda.csproj | 30 +- src/MinimalLambda/README.md | 24 +- .../Runtime/ILambdaBootstrapOrchestrator.cs | 3 +- .../Runtime/LambdaBootstrapAdapter.cs | 13 +- .../Runtime/LambdaHandlerComposer.cs | 21 +- .../Runtime/LambdaHostedService.cs | 16 +- src/MinimalLambda/build/MinimalLambda.targets | 2 +- tasks/FormattingTasks.yml | 5 +- .../AlbRequestEnvelopeTests.cs | 6 +- .../AlbResponseEnvelopeTests.cs | 6 +- .../ApiGatewayRequestEnvelopeTests.cs | 12 +- .../ApiGatewayResponseEnvelopeTests.cs | 36 +-- .../ApiGatewayResultTests.cs | 3 +- .../ApiGatewayV2RequestEnvelopeTests.cs | 12 +- .../ApiGatewayV2ResponseEnvelopeTests.cs | 42 +-- .../ApiGatewayV2ResultTests.cs | 9 +- .../CloudWatchLogsEnvelopeTests.cs | 130 ++++----- .../KafkaEnvelopeTests.cs | 157 +++++----- .../KinesisEnvelopeTests.cs | 9 +- .../KinesisFirehoseEventEnvelopeTests.cs | 26 +- .../KinesisFirehoseResponseEnvelopeTests.cs | 56 ++-- .../MinimalLambda.Envelopes.UnitTests.csproj | 32 +-- .../SnsEnvelopeTests.cs | 11 +- .../SqsEnvelopeTests.cs | 24 +- .../SqsSnsEnvelopeTests.cs | 63 ++-- .../AutoNSubstituteDataAttribute.cs | 11 +- .../MiddlewareOpenTelemetryExtensionsTest.cs | 19 +- ...nimalLambda.OpenTelemetry.UnitTests.csproj | 44 +-- .../OnShutdownOpenTelemetryExtensionsTests.cs | 96 +++---- .../DiagnosticTests.cs | 27 +- .../GeneratorTestHelpers.cs | 49 ++-- ...alLambda.SourceGenerators.UnitTests.csproj | 44 +-- .../VerifyTests/BlockLambdaVerifyTests.cs | 36 +-- .../ExpressionLambdaVerifyTests.cs | 66 ++--- .../VerifyTests/KeyedServiceVerifyTests.cs | 18 +- .../VerifyTests/OnInitVerifyTests.cs | 48 ++-- .../VerifyTests/OnShutdownVerifyTests.cs | 30 +- .../VerifyTests/StaticMethodVerifyTests.cs | 27 +- .../VerifyTests/UseMiddlewareTVerifyTests.cs | 42 +-- ...alLambda.Testing.UnitTests.DiLambda.csproj | 6 +- .../Program.cs | 63 ++-- ...bda.Testing.UnitTests.NoEventLambda.csproj | 4 +- .../Program.cs | 10 +- ....Testing.UnitTests.NoResponseLambda.csproj | 4 +- ...mbda.Testing.UnitTests.SimpleLambda.csproj | 4 +- .../Program.cs | 14 +- .../AutoNSubstituteDataAttribute.cs | 11 +- .../DiLambdaTests.cs | 115 +++----- .../DictionaryExtensionsTest.cs | 6 +- .../MinimalLambda.Testing.UnitTests.csproj | 40 +-- .../NoEventLambdaTests.cs | 26 +- .../NoResponseLambdaTests.cs | 12 +- .../SimpleLambdaTests.cs | 71 ++--- .../AutoNSubstituteDataAttribute.cs | 11 +- .../DefaultLambdaOnInitBuilderFactoryTests.cs | 15 +- ...aultLambdaOnShutdownBuilderFactoryTests.cs | 15 +- ...pClientServiceCollectionExtensionsTests.cs | 33 +-- ...dlewareLambdaApplicationExtensionsTests.cs | 28 +- ...ializerServiceCollectionExtensionsTests.cs | 7 +- .../ServiceCollectionExtensionsTests.cs | 45 ++- .../Builder/LambdaApplicationBuilderTests.cs | 6 +- .../Builder/LambdaApplicationTests.cs | 6 +- .../Builder/LambdaInvocationBuilderTests.cs | 24 +- .../Builder/LambdaOnInitBuilderTests.cs | 126 +++----- .../Builder/LambdaOnShutdownBuilderTests.cs | 18 +- .../DefaultLambdaCancellationFactoryTests.cs | 42 ++- .../LambdaInvocationContextAccessorTests.cs | 9 +- .../Context/LambdaInvocationContextFactory.cs | 31 +- .../Context/LambdaInvocationContextTests.cs | 270 ++++++------------ .../LambdaLifecycleContextFactoryTests.cs | 130 +++------ .../Context/LambdaLifecycleContextTests.cs | 176 ++++-------- .../DefaultEventFeatureProviderTests.cs | 36 +-- .../Core/Features/DefaultEventFeatureTests.cs | 74 ++--- .../Features/DefaultFeatureCollectionTests.cs | 12 +- .../DefaultResponseFeatureProviderTests.cs | 39 +-- .../Features/DefaultResponseFeatureTests.cs | 48 ++-- ...reLambdaInvocationContextExtensionsTest.cs | 120 +++----- .../HostOptionsPostConfigurationTests.cs | 47 ++- .../Runtime/LambdaHandlerComposerTests.cs | 27 +- .../Core/Runtime/LambdaHostedServiceTests.cs | 152 ++++------ .../MinimalLambda.UnitTests.csproj | 50 ++-- 226 files changed, 2289 insertions(+), 3565 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 4de85d18..0ad5a757 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -94,6 +94,7 @@ task test:watch # dotnet watch ... test ``` Direct `dotnet` commands: + ```bash # Run the full test suite (solution-level) DOTNET_NOLOGO=1 dotnet test --configuration Release diff --git a/Directory.Packages.props b/Directory.Packages.props index 4df426c3..eca25b9c 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -5,81 +5,81 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + - - - - - + + + + + - - - - + + + + - - - + + + - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + - - - - + + + + - - + + - - - + + + - - - + + + diff --git a/MinimalLambda.sln.DotSettings b/MinimalLambda.sln.DotSettings index 7fa61dc4..8f064ea4 100644 --- a/MinimalLambda.sln.DotSettings +++ b/MinimalLambda.sln.DotSettings @@ -1,140 +1,48 @@ ο»Ώ - DO_NOT_SHOW - <?xml version="1.0" encoding="utf-16"?><Profile name="Full Custom Cleanup"><CppReformatCode>True</CppReformatCode><FSharpReformatCode>True</FSharpReformatCode><ShaderLabReformatCode>True</ShaderLabReformatCode><XMLReformatCode>True</XMLReformatCode><VBReformatCode>True</VBReformatCode><CSReformatCode>True</CSReformatCode><CSharpReformatComments>True</CSharpReformatComments><CSCodeStyleAttributes ArrangeVarStyle="True" ArrangeTypeAccessModifier="True" ArrangeTypeMemberAccessModifier="True" SortModifiers="True" ArrangeArgumentsStyle="True" RemoveRedundantParentheses="True" AddMissingParentheses="True" ArrangeBraces="True" ArrangeAttributes="True" ArrangeCodeBodyStyle="True" ArrangeTrailingCommas="True" ArrangeObjectCreation="True" ArrangeDefaultValue="True" ArrangeNamespaces="True" ArrangeNullCheckingPattern="True" /><CSArrangeQualifiers>True</CSArrangeQualifiers><CSFixBuiltinTypeReferences>True</CSFixBuiltinTypeReferences><CppCodeStyleCleanupDescriptor ArrangeBraces="True" ArrangeAuto="True" ArrangeFunctionDeclarations="True" ArrangeNestedNamespaces="True" ArrangeTypeAliases="True" ArrangeCVQualifiers="True" ArrangeSlashesInIncludeDirectives="True" ArrangeOverridingFunctions="True" SortDefinitions="True" SortIncludeDirectives="True" SortMemberInitializers="True" /><FormatAttributeQuoteDescriptor>True</FormatAttributeQuoteDescriptor><CSOptimizeUsings><OptimizeUsings>True</OptimizeUsings></CSOptimizeUsings><CSShortenReferences>True</CSShortenReferences><VBOptimizeImports>True</VBOptimizeImports><VBShortenReferences>True</VBShortenReferences><Xaml.RemoveRedundantNamespaceAlias>True</Xaml.RemoveRedundantNamespaceAlias><AspOptimizeRegisterDirectives>True</AspOptimizeRegisterDirectives><RemoveCodeRedundancies>True</RemoveCodeRedundancies><CSUseAutoProperty>True</CSUseAutoProperty><CSMakeFieldReadonly>True</CSMakeFieldReadonly><CSMakeAutoPropertyGetOnly>True</CSMakeAutoPropertyGetOnly><CppAddTypenameTemplateKeywords>True</CppAddTypenameTemplateKeywords><CppCStyleToStaticCastDescriptor>True</CppCStyleToStaticCastDescriptor><CppRedundantDereferences>True</CppRedundantDereferences><CppDeleteRedundantAccessSpecifier>True</CppDeleteRedundantAccessSpecifier><CppRemoveCastDescriptor>True</CppRemoveCastDescriptor><CppRemoveElseKeyword>True</CppRemoveElseKeyword><CppShortenQualifiedName>True</CppShortenQualifiedName><CppDeleteRedundantSpecifier>True</CppDeleteRedundantSpecifier><CppRemoveStatement>True</CppRemoveStatement><CppDeleteRedundantTypenameTemplateKeywords>True</CppDeleteRedundantTypenameTemplateKeywords><CppReplaceExpressionWithBooleanConst>True</CppReplaceExpressionWithBooleanConst><CppMakeIfConstexpr>True</CppMakeIfConstexpr><CppMakePostfixOperatorPrefix>True</CppMakePostfixOperatorPrefix><CppMakeVariableConstexpr>True</CppMakeVariableConstexpr><CppChangeSmartPointerToMakeFunction>True</CppChangeSmartPointerToMakeFunction><CppReplaceThrowWithRethrowFix>True</CppReplaceThrowWithRethrowFix><CppTypeTraitAliasDescriptor>True</CppTypeTraitAliasDescriptor><CppRemoveRedundantConditionalExpressionDescriptor>True</CppRemoveRedundantConditionalExpressionDescriptor><CppSimplifyConditionalExpressionDescriptor>True</CppSimplifyConditionalExpressionDescriptor><CppReplaceExpressionWithNullptr>True</CppReplaceExpressionWithNullptr><CppReplaceTieWithStructuredBindingDescriptor>True</CppReplaceTieWithStructuredBindingDescriptor><CppUseAssociativeContainsDescriptor>True</CppUseAssociativeContainsDescriptor><CppUseEraseAlgorithmDescriptor>True</CppUseEraseAlgorithmDescriptor><CppJoinDeclarationAndAssignmentDescriptor>True</CppJoinDeclarationAndAssignmentDescriptor><CppMakeClassFinal>True</CppMakeClassFinal><CppMakeLocalVarConstDescriptor>True</CppMakeLocalVarConstDescriptor><CppMakeMethodConst>True</CppMakeMethodConst><CppMakeMethodStatic>True</CppMakeMethodStatic><CppMakePtrOrRefParameterConst>True</CppMakePtrOrRefParameterConst><CppMakeParameterConst>True</CppMakeParameterConst><CppPassValueParameterByConstReference>True</CppPassValueParameterByConstReference><CppRemoveElaboratedTypeSpecifierDescriptor>True</CppRemoveElaboratedTypeSpecifierDescriptor><CppRemoveRedundantLambdaParameterListDescriptor>True</CppRemoveRedundantLambdaParameterListDescriptor><CppRemoveRedundantMemberInitializerDescriptor>True</CppRemoveRedundantMemberInitializerDescriptor><CppRemoveRedundantParentheses>True</CppRemoveRedundantParentheses><CppRemoveTemplateArgumentsDescriptor>True</CppRemoveTemplateArgumentsDescriptor><CppRemoveUnreachableCode>True</CppRemoveUnreachableCode><CppRemoveUnusedIncludes>True</CppRemoveUnusedIncludes><CppRemoveUnusedLambdaCaptures>True</CppRemoveUnusedLambdaCaptures><CppReplaceIfWithIfConsteval>True</CppReplaceIfWithIfConsteval><RemoveCodeRedundanciesVB>True</RemoveCodeRedundanciesVB><VBMakeFieldReadonly>True</VBMakeFieldReadonly><Xaml.RedundantFreezeAttribute>True</Xaml.RedundantFreezeAttribute><Xaml.RemoveRedundantModifiersAttribute>True</Xaml.RemoveRedundantModifiersAttribute><Xaml.RemoveRedundantNameAttribute>True</Xaml.RemoveRedundantNameAttribute><Xaml.RemoveRedundantResource>True</Xaml.RemoveRedundantResource><Xaml.RemoveRedundantCollectionProperty>True</Xaml.RemoveRedundantCollectionProperty><Xaml.RemoveRedundantAttachedPropertySetter>True</Xaml.RemoveRedundantAttachedPropertySetter><Xaml.RemoveRedundantStyledValue>True</Xaml.RemoveRedundantStyledValue><Xaml.RemoveForbiddenResourceName>True</Xaml.RemoveForbiddenResourceName><Xaml.RemoveRedundantGridDefinitionsAttribute>True</Xaml.RemoveRedundantGridDefinitionsAttribute><Xaml.RemoveRedundantUpdateSourceTriggerAttribute>True</Xaml.RemoveRedundantUpdateSourceTriggerAttribute><Xaml.RemoveRedundantBindingModeAttribute>True</Xaml.RemoveRedundantBindingModeAttribute><Xaml.RemoveRedundantGridSpanAttribut>True</Xaml.RemoveRedundantGridSpanAttribut><IDEA_SETTINGS>&lt;profile version="1.0"&gt; - &lt;option name="myName" value="Full Custom Cleanup" /&gt; - &lt;inspection_tool class="ConditionalExpressionWithIdenticalBranchesJS" enabled="true" level="WARNING" enabled_by_default="true" /&gt; - &lt;inspection_tool class="ES6ShorthandObjectProperty" enabled="true" level="WARNING" enabled_by_default="true" /&gt; - &lt;inspection_tool class="JSArrowFunctionBracesCanBeRemoved" enabled="true" level="WARNING" enabled_by_default="true" /&gt; - &lt;inspection_tool class="JSRemoveUnnecessaryParentheses" enabled="true" level="WARNING" enabled_by_default="true" /&gt; - &lt;inspection_tool class="UnterminatedStatementJS" enabled="true" level="WARNING" enabled_by_default="true" /&gt; -&lt;/profile&gt;</IDEA_SETTINGS><RIDER_SETTINGS>&lt;profile&gt; - &lt;Language id="CSS"&gt; - &lt;Rearrange&gt;false&lt;/Rearrange&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="EditorConfig"&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="HCL"&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="HTML"&gt; - &lt;Rearrange&gt;false&lt;/Rearrange&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;OptimizeImports&gt;true&lt;/OptimizeImports&gt; - &lt;/Language&gt; - &lt;Language id="HTTP Request"&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="Handlebars"&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="Ini"&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="JSON"&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="Jade"&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="JavaScript"&gt; - &lt;Rearrange&gt;false&lt;/Rearrange&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;OptimizeImports&gt;true&lt;/OptimizeImports&gt; - &lt;/Language&gt; - &lt;Language id="Markdown"&gt; - &lt;Reformat&gt;false&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="Mermaid"&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="PowerShell"&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="Properties"&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="RELAX-NG"&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="Razor"&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="SQL"&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="TOML"&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="VueExpr"&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="XML"&gt; - &lt;Rearrange&gt;false&lt;/Rearrange&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;OptimizeImports&gt;true&lt;/OptimizeImports&gt; - &lt;/Language&gt; - &lt;Language id="liquid"&gt; - &lt;Reformat&gt;false&lt;/Reformat&gt; - &lt;/Language&gt; - &lt;Language id="yaml"&gt; - &lt;Reformat&gt;true&lt;/Reformat&gt; - &lt;/Language&gt; -&lt;/profile&gt;</RIDER_SETTINGS><CSharpFormatDocComments>True</CSharpFormatDocComments></Profile> - Built-in: Full Cleanup - NotRequired - NotRequired - NotRequired - NotRequired - ExpressionBody - ExpressionBody - ExpressionBody - True - False + TOGETHER_SAME_LINE + True + True + True + True + INSIDE + 1 + 1 + False + False False False - False + False False + False + False False False - True - 1 - ALWAYS - ALWAYS - ALWAYS + 0 + True + NEVER + NEVER + ALWAYS False NEVER - False - False - ALWAYS_IF_MULTILINE + STRONGLY + False True True CHOP_IF_LONG + CHOP_IF_LONG False - True + True True + True True - True - True + True + CHOP_IF_LONG + CHOP_IF_LONG CHOP_IF_LONG - True + True CHOP_IF_LONG CHOP_IF_LONG - 2 - False - False - 2 - ByFirstAttr - True - False - True - False - False - True - False - False - True + CHOP_IF_LONG True True True diff --git a/README.md b/README.md index 2afe9c9b..f7937f6a 100644 --- a/README.md +++ b/README.md @@ -5,32 +5,46 @@ [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=j-d-ha_minimal-lambda&metric=alert_status&token=9fb519975d91379dcfbc6c13a4bd4207131af6e3)](https://sonarcloud.io/summary/new_code?id=j-d-ha_minimal-lambda) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) -**Lambda-first hosting with Minimal API-inspired patterns** – Familiar .NET ergonomics with handlers, DI, and middleware, purpose-built for AWS Lambda triggers. +**Lambda-first hosting with Minimal API-inspired patterns** – Familiar .NET ergonomics with +handlers, DI, and middleware, purpose-built for AWS Lambda triggers. > πŸ“š **[View Full Documentation](https://j-d-ha.github.io/minimal-lambda/)** ## Overview -MinimalLambda brings the clean, declarative style of ASP.NET Core Minimal APIs to AWS Lambda while staying grounded in Lambda’s execution model. Use the same mental model (builder, DI, middleware, handler mapping) while leaning on Lambda-specific features like strongly-typed envelopes, lifecycle hooks, scoped invocations, and source generation. +MinimalLambda brings the clean, declarative style of ASP.NET Core Minimal APIs to AWS Lambda while +staying grounded in Lambda’s execution model. Use the same mental model (builder, DI, middleware, +handler mapping) while leaning on Lambda-specific features like strongly-typed envelopes, lifecycle +hooks, scoped invocations, and source generation. - **Familiar builder flow**: `LambdaApplication.CreateBuilder()` β†’ `Build()` β†’ `RunAsync()` -- **.NET DI you already use**: `builder.Services.AddScoped()` with Lambda-safe lifetimes +- **.NET DI you already use**: `builder.Services.AddScoped()` with + Lambda-safe lifetimes - **Handler mapping, Lambda edition**: `lambda.MapHandler(...)` instead of crafting raw handlers - **Middleware for cross-cutting concerns**: `lambda.UseMiddleware(...)` to wrap your pipeline -- **Lambda-first runtime**: Lifecycle hooks, cancellation token management, and strongly typed envelope models for event triggers +- **Lambda-first runtime**: Lifecycle hooks, cancellation token management, and strongly typed + envelope models for event triggers -Instead of writing boilerplate Lambda handlers, you keep familiar .NET patterns while the framework handles event envelopes, dependency injection, scoped lifetimes, middleware, and compile-time code generation for zero reflection overhead. +Instead of writing boilerplate Lambda handlers, you keep familiar .NET patterns while the framework +handles event envelopes, dependency injection, scoped lifetimes, middleware, and compile-time code +generation for zero reflection overhead. ## Key Features -- **Minimal API Pattern** – Map handlers with `lambda.MapHandler(...)` just like `app.MapGet()` in ASP.NET Core – clean, declarative, and intuitive -- **Dependency Injection** – Constructor and parameter injection using `Microsoft.Extensions.DependencyInjection` with proper scoped lifetimes per invocation -- **Middleware Pipeline** – Familiar `Use()` pattern for cross-cutting concerns like logging, validation, and error handling -- **Source Generated** – Compile-time code generation for zero reflection overhead and optimal performance +- **Minimal API Pattern** – Map handlers with `lambda.MapHandler(...)` just like `app.MapGet()` in + ASP.NET Core – clean, declarative, and intuitive +- **Dependency Injection** – Constructor and parameter injection using + `Microsoft.Extensions.DependencyInjection` with proper scoped lifetimes per invocation +- **Middleware Pipeline** – Familiar `Use()` pattern for cross-cutting concerns like logging, + validation, and error handling +- **Source Generated** – Compile-time code generation for zero reflection overhead and optimal + performance - **AOT Ready** – Native AOT compilation support for fast cold starts - **Built-in Observability** – OpenTelemetry integration for distributed tracing and metrics -- **Type-Safe Envelopes** – Strongly-typed event wrappers for SQS, SNS, API Gateway, Kinesis, and more -- **Minimal Runtime Overhead** – Lightweight abstraction layer built on the same foundation as ASP.NET Core +- **Type-Safe Envelopes** – Strongly-typed event wrappers for SQS, SNS, API Gateway, Kinesis, and + more +- **Minimal Runtime Overhead** – Lightweight abstraction layer built on the same foundation as + ASP.NET Core ## Packages @@ -41,20 +55,20 @@ The framework is divided into multiple NuGet packages: The core packages provide the fundamental hosting framework, abstractions, and observability support for building AWS Lambda functions. -| Package | NuGet | Downloads | -|--------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------| -| [**MinimalLambda**](./src/MinimalLambda/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda/) | +| Package | NuGet | Downloads | +|--------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------| +| [**MinimalLambda**](./src/MinimalLambda/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda/) | | [**MinimalLambda.Abstractions**](./src/MinimalLambda.Abstractions/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions/) | | [**MinimalLambda.OpenTelemetry**](./src/MinimalLambda.OpenTelemetry/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry/) | -| [**MinimalLambda.Testing**](./src/MinimalLambda.Testing/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Testing.svg)](https://www.nuget.org/packages/MinimalLambda.Testing) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Testing.svg)](https://www.nuget.org/packages/MinimalLambda.Testing/) | +| [**MinimalLambda.Testing**](./src/MinimalLambda.Testing/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Testing.svg)](https://www.nuget.org/packages/MinimalLambda.Testing) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Testing.svg)](https://www.nuget.org/packages/MinimalLambda.Testing/) | ### Envelopes Packages Envelope packages provide specialized support for handling different AWS Lambda event sources, including SQS, SNS, API Gateway, Kinesis, and more. -| Package | NuGet | Downloads | -|------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Package | NuGet | Downloads | +|----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [**MinimalLambda.Envelopes**](./src/Envelopes/MinimalLambda.Envelopes/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Envelopes.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Envelopes.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes/) | | [**MinimalLambda.Envelopes.Sqs**](./MinimalLambda.Envelopes.Sqs/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Envelopes.Sqs.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.Sqs) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Envelopes.Sqs.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.Sqs/) | | [**MinimalLambda.Envelopes.ApiGateway**](./MinimalLambda.Envelopes.ApiGateway/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Envelopes.ApiGateway.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.ApiGateway) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Envelopes.ApiGateway.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.ApiGateway/) | diff --git a/benchmarks/MinimalLambda.Benchmarks/MinimalLambda.Benchmarks.csproj b/benchmarks/MinimalLambda.Benchmarks/MinimalLambda.Benchmarks.csproj index 3605ebdf..fa64581f 100644 --- a/benchmarks/MinimalLambda.Benchmarks/MinimalLambda.Benchmarks.csproj +++ b/benchmarks/MinimalLambda.Benchmarks/MinimalLambda.Benchmarks.csproj @@ -16,9 +16,9 @@ false - + - + diff --git a/examples/MinimalLambda.Example.ClassMiddleware/MinimalLambda.Example.ClassMiddleware.csproj b/examples/MinimalLambda.Example.ClassMiddleware/MinimalLambda.Example.ClassMiddleware.csproj index 6df39b83..c9012444 100644 --- a/examples/MinimalLambda.Example.ClassMiddleware/MinimalLambda.Example.ClassMiddleware.csproj +++ b/examples/MinimalLambda.Example.ClassMiddleware/MinimalLambda.Example.ClassMiddleware.csproj @@ -15,7 +15,7 @@ false - + (); -lambda.MapHandler( - ([FromEvent] Request request) => new Response($"Hello {request.Name}!", DateTime.UtcNow) -); +lambda.MapHandler(([FromEvent] Request request) => +new Response($"Hello {request.Name}!", DateTime.UtcNow)); await lambda.RunAsync(); diff --git a/examples/MinimalLambda.Example.Events/MinimalLambda.Example.Events.csproj b/examples/MinimalLambda.Example.Events/MinimalLambda.Example.Events.csproj index 9dc53ef2..fd0b955f 100644 --- a/examples/MinimalLambda.Example.Events/MinimalLambda.Example.Events.csproj +++ b/examples/MinimalLambda.Example.Events/MinimalLambda.Example.Events.csproj @@ -17,15 +17,15 @@ false - + - - - + + + diff --git a/examples/MinimalLambda.Example.Events/Program.cs b/examples/MinimalLambda.Example.Events/Program.cs index ce4a6779..76cdf357 100644 --- a/examples/MinimalLambda.Example.Events/Program.cs +++ b/examples/MinimalLambda.Example.Events/Program.cs @@ -26,32 +26,29 @@ var lambda = builder.Build(); -lambda.MapHandler( - ( - [FromEvent] ApiGatewayRequestEnvelope request, - ILogger logger, - ILambdaInvocationContext _ - ) => - { - logger.LogInformation("In Handler. Payload: {Payload}", request.Body); - - if (request.BodyContent == null) - return ApiGatewayResult.InternalServerError(new BadErrorDetails("Bad error")); +lambda.MapHandler(( + [FromEvent] ApiGatewayRequestEnvelope request, + ILogger logger, + ILambdaInvocationContext _) => +{ + logger.LogInformation("In Handler. Payload: {Payload}", request.Body); - if (request.BodyContent.Name == "error") - return ApiGatewayResult - .BadRequest(new ErrorDetails("bummer")) - .Customize(response => - { - response.Headers.Add("X-Custom-Header", "Custom Value"); - response.MultiValueHeaders.Add("X-Custom-Header", ["Custom Value 2"]); - }); + if (request.BodyContent == null) + return ApiGatewayResult.InternalServerError(new BadErrorDetails("Bad error")); + if (request.BodyContent.Name == "error") return ApiGatewayResult - .Ok(new Response($"Hello {request.BodyContent?.Name}!", DateTime.UtcNow)) - .Customize(result => result.Headers.Add("X-Custom-Header", "Custom Value")); - } -); + .BadRequest(new ErrorDetails("bummer")) + .Customize(response => + { + response.Headers.Add("X-Custom-Header", "Custom Value"); + response.MultiValueHeaders.Add("X-Custom-Header", ["Custom Value 2"]); + }); + + return ApiGatewayResult + .Ok(new Response($"Hello {request.BodyContent?.Name}!", DateTime.UtcNow)) + .Customize(result => result.Headers.Add("X-Custom-Header", "Custom Value")); +}); await lambda.RunAsync(); diff --git a/examples/MinimalLambda.Example.HelloWorld/MinimalLambda.Example.HelloWorld.csproj b/examples/MinimalLambda.Example.HelloWorld/MinimalLambda.Example.HelloWorld.csproj index 0b7656ab..4f68fea1 100644 --- a/examples/MinimalLambda.Example.HelloWorld/MinimalLambda.Example.HelloWorld.csproj +++ b/examples/MinimalLambda.Example.HelloWorld/MinimalLambda.Example.HelloWorld.csproj @@ -16,13 +16,13 @@ false - + - + diff --git a/examples/MinimalLambda.Example.HelloWorld/Program.cs b/examples/MinimalLambda.Example.HelloWorld/Program.cs index 2200e8d7..1b46d6a1 100644 --- a/examples/MinimalLambda.Example.HelloWorld/Program.cs +++ b/examples/MinimalLambda.Example.HelloWorld/Program.cs @@ -9,9 +9,8 @@ var lambda = builder.Build(); // Map your handler - the event is automatically injected -lambda.MapHandler( - ([FromEvent] Request request) => new Response($"Hello {request.Name}!", DateTime.UtcNow) -); +lambda.MapHandler(([FromEvent] Request request) => +new Response($"Hello {request.Name}!", DateTime.UtcNow)); // Run the Lambda await lambda.RunAsync(); diff --git a/examples/MinimalLambda.Example.HelloWorldAot/MinimalLambda.Example.HelloWorldAot.csproj b/examples/MinimalLambda.Example.HelloWorldAot/MinimalLambda.Example.HelloWorldAot.csproj index 83de0610..3fc1ddbe 100644 --- a/examples/MinimalLambda.Example.HelloWorldAot/MinimalLambda.Example.HelloWorldAot.csproj +++ b/examples/MinimalLambda.Example.HelloWorldAot/MinimalLambda.Example.HelloWorldAot.csproj @@ -24,7 +24,7 @@ false - + - { - Console.WriteLine("[Middleware 1] Before"); - await next(context); - Console.WriteLine("[Middleware 1] After"); - } -); - -lambda.UseMiddleware( - async (context, next) => - { - Console.WriteLine("[Middleware 2] Before"); - await next(context); - Console.WriteLine("[Middleware 2] After"); - } -); - -lambda.MapHandler( - ([FromEvent] string input) => - { - Console.WriteLine("hello world from aot"); - return "hello world from aot"; - } -); +lambda.UseMiddleware(async (context, next) => +{ + Console.WriteLine("[Middleware 1] Before"); + await next(context); + Console.WriteLine("[Middleware 1] After"); +}); + +lambda.UseMiddleware(async (context, next) => +{ + Console.WriteLine("[Middleware 2] Before"); + await next(context); + Console.WriteLine("[Middleware 2] After"); +}); + +lambda.MapHandler(([FromEvent] string input) => +{ + Console.WriteLine("hello world from aot"); + return "hello world from aot"; +}); await lambda.RunAsync(); diff --git a/examples/MinimalLambda.Example.Lifecycle/MinimalLambda.Example.Lifecycle.csproj b/examples/MinimalLambda.Example.Lifecycle/MinimalLambda.Example.Lifecycle.csproj index 6df39b83..c9012444 100644 --- a/examples/MinimalLambda.Example.Lifecycle/MinimalLambda.Example.Lifecycle.csproj +++ b/examples/MinimalLambda.Example.Lifecycle/MinimalLambda.Example.Lifecycle.csproj @@ -15,7 +15,7 @@ false - + (ILogger logger, CancellationToken cancellationToken) => +lambda.OnInit(async Task (ILogger logger, CancellationToken cancellationToken) => +{ + var stopwatch = Stopwatch.StartNew(); + while (!cancellationToken.IsCancellationRequested) { - var stopwatch = Stopwatch.StartNew(); - while (!cancellationToken.IsCancellationRequested) + logger.LogInformation( + "Waiting for init to timeout. {ElapsedMilliseconds}ms elapsed", + stopwatch.ElapsedMilliseconds); + try { - logger.LogInformation( - "Waiting for init to timeout. {ElapsedMilliseconds}ms elapsed", - stopwatch.ElapsedMilliseconds - ); - try - { - await Task.Delay(TimeSpan.FromMilliseconds(100), cancellationToken); - } - catch - { - // ignored - } + await Task.Delay(TimeSpan.FromMilliseconds(100), cancellationToken); + } + catch + { + // ignored } - - return true; } -); + + return true; +}); lambda.MapHandler(() => { @@ -57,21 +54,17 @@ async Task (ILogger logger, CancellationToken cancellationToken) return new Response("Hello world"); }); -lambda.OnShutdown( - (CancellationToken _) => - { - Console.WriteLine("Shutting down..."); - return Task.CompletedTask; - } -); +lambda.OnShutdown((CancellationToken _) => +{ + Console.WriteLine("Shutting down..."); + return Task.CompletedTask; +}); -lambda.OnShutdown( - Task (IService service) => - { - Console.WriteLine(service.GetMessage()); - return Task.CompletedTask; - } -); +lambda.OnShutdown(Task (IService service) => +{ + Console.WriteLine(service.GetMessage()); + return Task.CompletedTask; +}); lambda.OnShutdown(Task () => Task.CompletedTask); diff --git a/examples/MinimalLambda.Example.OpenTelemetry/Function.cs b/examples/MinimalLambda.Example.OpenTelemetry/Function.cs index 29e38258..afa87881 100644 --- a/examples/MinimalLambda.Example.OpenTelemetry/Function.cs +++ b/examples/MinimalLambda.Example.OpenTelemetry/Function.cs @@ -8,8 +8,7 @@ internal static async Task Handler( [FromEvent] Request request, IService service, Instrumentation instrumentation, - CancellationToken cancellationToken - ) + CancellationToken cancellationToken) { using var activity = instrumentation.ActivitySource.StartActivity(); diff --git a/examples/MinimalLambda.Example.OpenTelemetry/MinimalLambda.Example.OpenTelemetry.csproj b/examples/MinimalLambda.Example.OpenTelemetry/MinimalLambda.Example.OpenTelemetry.csproj index 14eda7b7..26a703b9 100644 --- a/examples/MinimalLambda.Example.OpenTelemetry/MinimalLambda.Example.OpenTelemetry.csproj +++ b/examples/MinimalLambda.Example.OpenTelemetry/MinimalLambda.Example.OpenTelemetry.csproj @@ -16,22 +16,22 @@ false - - + + - + - - - - + + + + - + diff --git a/examples/MinimalLambda.Example.OpenTelemetry/OpenTelemetryRegistrationExtensions.cs b/examples/MinimalLambda.Example.OpenTelemetry/OpenTelemetryRegistrationExtensions.cs index 38f56b33..36e0deaa 100644 --- a/examples/MinimalLambda.Example.OpenTelemetry/OpenTelemetryRegistrationExtensions.cs +++ b/examples/MinimalLambda.Example.OpenTelemetry/OpenTelemetryRegistrationExtensions.cs @@ -13,41 +13,33 @@ internal static IServiceCollection AddOtel(this IServiceCollection services) { services .AddOpenTelemetry() - .WithTracing(configure => - configure - .AddAWSLambdaConfigurations() - .AddSource(Instrumentation.ActivitySourceName) - .SetResourceBuilder( - ResourceBuilder - .CreateDefault() - .AddService( - Instrumentation.ActivitySourceName, - serviceVersion: Instrumentation.ActivitySourceVersion - ) - ) - .AddOtlpExporter(options => - { - options.Endpoint = new Uri("http://localhost:4318/v1/traces"); - options.Protocol = OtlpExportProtocol.HttpProtobuf; - }) - ) - .WithMetrics(configure => - configure - .AddMeter(Instrumentation.ActivitySourceName) - .SetResourceBuilder( - ResourceBuilder - .CreateDefault() - .AddService( - Instrumentation.ActivitySourceName, - serviceVersion: Instrumentation.ActivitySourceVersion - ) - ) - .AddOtlpExporter(options => - { - options.Endpoint = new Uri("http://localhost:4318/v1/metrics"); - options.Protocol = OtlpExportProtocol.HttpProtobuf; - }) - ); + .WithTracing(configure => configure + .AddAWSLambdaConfigurations() + .AddSource(Instrumentation.ActivitySourceName) + .SetResourceBuilder( + ResourceBuilder + .CreateDefault() + .AddService( + Instrumentation.ActivitySourceName, + serviceVersion: Instrumentation.ActivitySourceVersion)) + .AddOtlpExporter(options => + { + options.Endpoint = new Uri("http://localhost:4318/v1/traces"); + options.Protocol = OtlpExportProtocol.HttpProtobuf; + })) + .WithMetrics(configure => configure + .AddMeter(Instrumentation.ActivitySourceName) + .SetResourceBuilder( + ResourceBuilder + .CreateDefault() + .AddService( + Instrumentation.ActivitySourceName, + serviceVersion: Instrumentation.ActivitySourceVersion)) + .AddOtlpExporter(options => + { + options.Endpoint = new Uri("http://localhost:4318/v1/metrics"); + options.Protocol = OtlpExportProtocol.HttpProtobuf; + })); return services; } diff --git a/src/AotCompatibility.TestApp/AotCompatibility.TestApp.csproj b/src/AotCompatibility.TestApp/AotCompatibility.TestApp.csproj index 45f3c93c..544db0c0 100644 --- a/src/AotCompatibility.TestApp/AotCompatibility.TestApp.csproj +++ b/src/AotCompatibility.TestApp/AotCompatibility.TestApp.csproj @@ -12,22 +12,22 @@ false - - - - - - - - - - - - + + + + + + + + + + + + - - + + - + diff --git a/src/Envelopes/MinimalLambda.Envelopes.Alb/AlbRequestEnvelope.cs b/src/Envelopes/MinimalLambda.Envelopes.Alb/AlbRequestEnvelope.cs index 9fbc0fe5..fd6d9946 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Alb/AlbRequestEnvelope.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.Alb/AlbRequestEnvelope.cs @@ -17,13 +17,13 @@ public sealed class AlbRequestEnvelope : AlbRequestEnvelopeBase [UnconditionalSuppressMessage( "Aot", "IL3050:RequiresDynamicCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] [UnconditionalSuppressMessage( "Aot", "IL2026:RequiresUnreferencedCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] public override void ExtractPayload(EnvelopeOptions options) => BodyContent = JsonSerializer.Deserialize(Body, options.JsonOptions); } diff --git a/src/Envelopes/MinimalLambda.Envelopes.Alb/AlbResponseEnvelope.cs b/src/Envelopes/MinimalLambda.Envelopes.Alb/AlbResponseEnvelope.cs index e6f12ad4..b3c1099d 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Alb/AlbResponseEnvelope.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.Alb/AlbResponseEnvelope.cs @@ -17,13 +17,13 @@ public sealed class AlbResponseEnvelope : AlbResponseEnvelopeBase [UnconditionalSuppressMessage( "Aot", "IL3050:RequiresDynamicCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] [UnconditionalSuppressMessage( "Aot", "IL2026:RequiresUnreferencedCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] public override void PackPayload(EnvelopeOptions options) => Body = JsonSerializer.Serialize(BodyContent, options.JsonOptions); } diff --git a/src/Envelopes/MinimalLambda.Envelopes.Alb/AlbResponseEnvelopeBase.cs b/src/Envelopes/MinimalLambda.Envelopes.Alb/AlbResponseEnvelopeBase.cs index 8d427723..4791a165 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Alb/AlbResponseEnvelopeBase.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.Alb/AlbResponseEnvelopeBase.cs @@ -13,8 +13,7 @@ namespace MinimalLambda.Envelopes.Alb; /// into the response body using their chosen serialization strategy. /// public abstract class AlbResponseEnvelopeBase - : ApplicationLoadBalancerResponse, - IResponseEnvelope + : ApplicationLoadBalancerResponse, IResponseEnvelope { /// The deserialized content of the [JsonIgnore] diff --git a/src/Envelopes/MinimalLambda.Envelopes.Alb/AlbResult.cs b/src/Envelopes/MinimalLambda.Envelopes.Alb/AlbResult.cs index c0196dd8..d545e4e2 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Alb/AlbResult.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.Alb/AlbResult.cs @@ -44,8 +44,7 @@ public static AlbResult Create( int statusCode, T? bodyContent, IDictionary headers, - bool isBase64Encoded - ) => + bool isBase64Encoded) => new( new AlbResponseEnvelope { @@ -53,8 +52,7 @@ bool isBase64Encoded BodyContent = bodyContent, Headers = headers, IsBase64Encoded = isBase64Encoded, - } - ); + }); /// Creates an ALB result from an existing response envelope. /// The type of content in the envelope's body. diff --git a/src/Envelopes/MinimalLambda.Envelopes.Alb/MinimalLambda.Envelopes.Alb.csproj b/src/Envelopes/MinimalLambda.Envelopes.Alb/MinimalLambda.Envelopes.Alb.csproj index 7e59109f..5a59e00d 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Alb/MinimalLambda.Envelopes.Alb.csproj +++ b/src/Envelopes/MinimalLambda.Envelopes.Alb/MinimalLambda.Envelopes.Alb.csproj @@ -14,15 +14,15 @@ - - + + - - + + - + diff --git a/src/Envelopes/MinimalLambda.Envelopes.Alb/README.md b/src/Envelopes/MinimalLambda.Envelopes.Alb/README.md index 2aa6b673..bd23bb2c 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Alb/README.md +++ b/src/Envelopes/MinimalLambda.Envelopes.Alb/README.md @@ -175,8 +175,8 @@ builder.Services.ConfigureEnvelopeOptions(options => Additional packages in the minimal-lambda framework for abstractions, observability, and event source handling. -| Package | NuGet | Downloads | -|-------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Package | NuGet | Downloads | +|-----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [**MinimalLambda**](../../MinimalLambda/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda/) | | [**MinimalLambda.Abstractions**](../../MinimalLambda.Abstractions/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions/) | | [**MinimalLambda.OpenTelemetry**](../../MinimalLambda.OpenTelemetry/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry/) | diff --git a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayRequestEnvelope.cs b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayRequestEnvelope.cs index 44ff6efb..1b917899 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayRequestEnvelope.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayRequestEnvelope.cs @@ -17,13 +17,13 @@ public sealed class ApiGatewayRequestEnvelope : ApiGatewayRequestEnvelopeBase [UnconditionalSuppressMessage( "Aot", "IL3050:RequiresDynamicCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] [UnconditionalSuppressMessage( "Aot", "IL2026:RequiresUnreferencedCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] public override void ExtractPayload(EnvelopeOptions options) => BodyContent = JsonSerializer.Deserialize(Body, options.JsonOptions); } diff --git a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayResponseEnvelope.cs b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayResponseEnvelope.cs index 198f3d3d..80957e1c 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayResponseEnvelope.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayResponseEnvelope.cs @@ -17,13 +17,13 @@ public sealed class ApiGatewayResponseEnvelope : ApiGatewayResponseEnvelopeBa [UnconditionalSuppressMessage( "Aot", "IL3050:RequiresDynamicCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] [UnconditionalSuppressMessage( "Aot", "IL2026:RequiresUnreferencedCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] public override void PackPayload(EnvelopeOptions options) => Body = JsonSerializer.Serialize(BodyContent, options.JsonOptions); } diff --git a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayResult.cs b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayResult.cs index 41c17323..01042ade 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayResult.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayResult.cs @@ -43,8 +43,7 @@ public static ApiGatewayResult Create( int statusCode, T? bodyContent, IDictionary headers, - bool isBase64Encoded - ) => + bool isBase64Encoded) => new( new ApiGatewayResponseEnvelope { @@ -52,8 +51,7 @@ bool isBase64Encoded BodyContent = bodyContent, Headers = headers, IsBase64Encoded = isBase64Encoded, - } - ); + }); /// Creates an API Gateway result from an existing response envelope. /// The type of content in the envelope's body. diff --git a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2RequestEnvelope.cs b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2RequestEnvelope.cs index f624ef0c..92d777b5 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2RequestEnvelope.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2RequestEnvelope.cs @@ -17,13 +17,13 @@ public sealed class ApiGatewayV2RequestEnvelope : ApiGatewayV2RequestEnvelope [UnconditionalSuppressMessage( "Aot", "IL3050:RequiresDynamicCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] [UnconditionalSuppressMessage( "Aot", "IL2026:RequiresUnreferencedCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] public override void ExtractPayload(EnvelopeOptions options) => BodyContent = JsonSerializer.Deserialize(Body, options.JsonOptions); } diff --git a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2RequestEnvelopeBase.cs b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2RequestEnvelopeBase.cs index 337cb313..9e6bdd29 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2RequestEnvelopeBase.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2RequestEnvelopeBase.cs @@ -13,8 +13,7 @@ namespace MinimalLambda.Envelopes.ApiGateway; /// property using their chosen deserialization strategy. /// public abstract class ApiGatewayV2RequestEnvelopeBase - : APIGatewayHttpApiV2ProxyRequest, - IRequestEnvelope + : APIGatewayHttpApiV2ProxyRequest, IRequestEnvelope { /// The deserialized content of the [JsonIgnore] diff --git a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2ResponseEnvelope.cs b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2ResponseEnvelope.cs index 616a8b12..d65f4768 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2ResponseEnvelope.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2ResponseEnvelope.cs @@ -17,13 +17,13 @@ public sealed class ApiGatewayV2ResponseEnvelope : ApiGatewayV2ResponseEnvelo [UnconditionalSuppressMessage( "Aot", "IL3050:RequiresDynamicCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] [UnconditionalSuppressMessage( "Aot", "IL2026:RequiresUnreferencedCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] public override void PackPayload(EnvelopeOptions options) => Body = JsonSerializer.Serialize(BodyContent, options.JsonOptions); } diff --git a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2ResponseEnvelopeBase.cs b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2ResponseEnvelopeBase.cs index 45e4d2b1..9640f71e 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2ResponseEnvelopeBase.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2ResponseEnvelopeBase.cs @@ -13,8 +13,7 @@ namespace MinimalLambda.Envelopes.ApiGateway; /// into the response body using their chosen serialization strategy. /// public abstract class ApiGatewayV2ResponseEnvelopeBase - : APIGatewayHttpApiV2ProxyResponse, - IResponseEnvelope + : APIGatewayHttpApiV2ProxyResponse, IResponseEnvelope { /// The deserialized content of the [JsonIgnore] diff --git a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2Result.cs b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2Result.cs index 278850eb..0a947e3b 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2Result.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/ApiGatewayV2Result.cs @@ -14,8 +14,7 @@ namespace MinimalLambda.Envelopes.ApiGateway; /// returning responses from Lambda proxy integrations with API Gateway HTTP APIs. /// public sealed class ApiGatewayV2Result - : APIGatewayHttpApiV2ProxyResponse, - IHttpResult + : APIGatewayHttpApiV2ProxyResponse, IHttpResult { [JsonIgnore] private readonly IResponseEnvelope? _inner; @@ -45,8 +44,7 @@ public static ApiGatewayV2Result Create( int statusCode, T? bodyContent, IDictionary headers, - bool isBase64Encoded - ) => + bool isBase64Encoded) => new( new ApiGatewayV2ResponseEnvelope { @@ -54,8 +52,7 @@ bool isBase64Encoded BodyContent = bodyContent, Headers = headers, IsBase64Encoded = isBase64Encoded, - } - ); + }); /// Creates an API Gateway v2 result from an existing response envelope. /// The type of content in the envelope's body. diff --git a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/MinimalLambda.Envelopes.ApiGateway.csproj b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/MinimalLambda.Envelopes.ApiGateway.csproj index f80233dc..0d617cf2 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/MinimalLambda.Envelopes.ApiGateway.csproj +++ b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/MinimalLambda.Envelopes.ApiGateway.csproj @@ -14,15 +14,15 @@ - - + + - - + + - + diff --git a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/README.md b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/README.md index 68ea5f23..cf126e52 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/README.md +++ b/src/Envelopes/MinimalLambda.Envelopes.ApiGateway/README.md @@ -158,7 +158,8 @@ When using .NET Native AOT, register all envelope and payload types in your `Jso internal partial class SerializerContext : JsonSerializerContext; ``` -**When using `ApiGatewayResult` / `ApiGatewayV2Result` with multiple return types**, register each type separately: +**When using `ApiGatewayResult` / `ApiGatewayV2Result` with multiple return types**, register each +type separately: ```csharp [JsonSerializable(typeof(ApiGatewayRequestEnvelope))] @@ -191,8 +192,8 @@ builder.Services.ConfigureEnvelopeOptions(options => Additional packages in the minimal-lambda framework for abstractions, observability, and event source handling. -| Package | NuGet | Downloads | -|-------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Package | NuGet | Downloads | +|-----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [**MinimalLambda**](../../MinimalLambda/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda/) | | [**MinimalLambda.Abstractions**](../../MinimalLambda.Abstractions/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions/) | | [**MinimalLambda.OpenTelemetry**](../../MinimalLambda.OpenTelemetry/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry/) | diff --git a/src/Envelopes/MinimalLambda.Envelopes.CloudWatchLogs/CloudWatchLogsEnvelopeBase.cs b/src/Envelopes/MinimalLambda.Envelopes.CloudWatchLogs/CloudWatchLogsEnvelopeBase.cs index dc01a612..afc644fa 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.CloudWatchLogs/CloudWatchLogsEnvelopeBase.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.CloudWatchLogs/CloudWatchLogsEnvelopeBase.cs @@ -23,21 +23,21 @@ public abstract class CloudWatchLogsEnvelopeBase : CloudWatchLogsEvent, IRequ [UnconditionalSuppressMessage( "Aot", "IL3050:RequiresDynamicCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] [UnconditionalSuppressMessage( "Aot", "IL2026:RequiresUnreferencedCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] public virtual void ExtractPayload(EnvelopeOptions options) { var decodedData = Awslogs.DecodeData(); AwslogsContent = JsonSerializer.Deserialize( decodedData, - options.LambdaDefaultJsonOptions - ) ?? throw new InvalidOperationException("Invalid CloudWatch Logs data."); + options.LambdaDefaultJsonOptions) + ?? throw new InvalidOperationException("Invalid CloudWatch Logs data."); } /// diff --git a/src/Envelopes/MinimalLambda.Envelopes.CloudWatchLogs/CloudWatchLogsEnvelopeT.cs b/src/Envelopes/MinimalLambda.Envelopes.CloudWatchLogs/CloudWatchLogsEnvelopeT.cs index df94ce42..0c707da1 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.CloudWatchLogs/CloudWatchLogsEnvelopeT.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.CloudWatchLogs/CloudWatchLogsEnvelopeT.cs @@ -30,13 +30,13 @@ public sealed class CloudWatchLogsEnvelope : CloudWatchLogsEnvelopeBase [UnconditionalSuppressMessage( "Aot", "IL3050:RequiresDynamicCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] [UnconditionalSuppressMessage( "Aot", "IL2026:RequiresUnreferencedCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] public override void ExtractPayload(EnvelopeOptions options) { base.ExtractPayload(options); @@ -44,7 +44,6 @@ public override void ExtractPayload(EnvelopeOptions options) foreach (var logEvent in AwslogsContent!.LogEvents) logEvent.MessageContent = JsonSerializer.Deserialize( logEvent.Message, - options.JsonOptions - ); + options.JsonOptions); } } diff --git a/src/Envelopes/MinimalLambda.Envelopes.CloudWatchLogs/MinimalLambda.Envelopes.CloudWatchLogs.csproj b/src/Envelopes/MinimalLambda.Envelopes.CloudWatchLogs/MinimalLambda.Envelopes.CloudWatchLogs.csproj index 48307564..5231f268 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.CloudWatchLogs/MinimalLambda.Envelopes.CloudWatchLogs.csproj +++ b/src/Envelopes/MinimalLambda.Envelopes.CloudWatchLogs/MinimalLambda.Envelopes.CloudWatchLogs.csproj @@ -14,14 +14,14 @@ - - + + - + - + diff --git a/src/Envelopes/MinimalLambda.Envelopes.CloudWatchLogs/README.md b/src/Envelopes/MinimalLambda.Envelopes.CloudWatchLogs/README.md index 8f139f1b..4dcc93ec 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.CloudWatchLogs/README.md +++ b/src/Envelopes/MinimalLambda.Envelopes.CloudWatchLogs/README.md @@ -122,8 +122,8 @@ builder.Services.ConfigureEnvelopeOptions(options => Additional packages in the minimal-lambda framework for abstractions, observability, and event source handling. -| Package | NuGet | Downloads | -|-------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Package | NuGet | Downloads | +|-----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [**MinimalLambda**](../../MinimalLambda/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda/) | | [**MinimalLambda.Abstractions**](../../MinimalLambda.Abstractions/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions/) | | [**MinimalLambda.OpenTelemetry**](../../MinimalLambda.OpenTelemetry/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry/) | diff --git a/src/Envelopes/MinimalLambda.Envelopes.Kafka/KafkaEnvelope.cs b/src/Envelopes/MinimalLambda.Envelopes.Kafka/KafkaEnvelope.cs index bf70872c..d9152d82 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Kafka/KafkaEnvelope.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.Kafka/KafkaEnvelope.cs @@ -18,22 +18,22 @@ public sealed class KafkaEnvelope : KafkaEnvelopeBase [UnconditionalSuppressMessage( "Aot", "IL3050:RequiresDynamicCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] [UnconditionalSuppressMessage( "Aot", "IL2026:RequiresUnreferencedCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] public override void ExtractPayload(EnvelopeOptions options) { foreach (var topic in Records) - foreach (var record in topic.Value) - { - using var reader = new StreamReader(record.Value, Encoding.UTF8, leaveOpen: true); - var base64String = reader.ReadToEnd(); - var jsonBytes = Convert.FromBase64String(base64String); - record.ValueContent = JsonSerializer.Deserialize(jsonBytes, options.JsonOptions); - } + foreach (var record in topic.Value) + { + using var reader = new StreamReader(record.Value, Encoding.UTF8, leaveOpen: true); + var base64String = reader.ReadToEnd(); + var jsonBytes = Convert.FromBase64String(base64String); + record.ValueContent = JsonSerializer.Deserialize(jsonBytes, options.JsonOptions); + } } } diff --git a/src/Envelopes/MinimalLambda.Envelopes.Kafka/MinimalLambda.Envelopes.Kafka.csproj b/src/Envelopes/MinimalLambda.Envelopes.Kafka/MinimalLambda.Envelopes.Kafka.csproj index 69172b80..dcb70d40 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Kafka/MinimalLambda.Envelopes.Kafka.csproj +++ b/src/Envelopes/MinimalLambda.Envelopes.Kafka/MinimalLambda.Envelopes.Kafka.csproj @@ -15,14 +15,14 @@ - - + + - + - + diff --git a/src/Envelopes/MinimalLambda.Envelopes.Kafka/README.md b/src/Envelopes/MinimalLambda.Envelopes.Kafka/README.md index 6479bdf1..58eb40e1 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Kafka/README.md +++ b/src/Envelopes/MinimalLambda.Envelopes.Kafka/README.md @@ -126,8 +126,8 @@ builder.Services.ConfigureEnvelopeOptions(options => Additional packages in the minimal-lambda framework for abstractions, observability, and event source handling. -| Package | NuGet | Downloads | -|-------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Package | NuGet | Downloads | +|-----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [**MinimalLambda**](../../MinimalLambda/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda/) | | [**MinimalLambda.Abstractions**](../../MinimalLambda.Abstractions/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions/) | | [**MinimalLambda.OpenTelemetry**](../../MinimalLambda.OpenTelemetry/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry/) | diff --git a/src/Envelopes/MinimalLambda.Envelopes.Kinesis/KinesisEnvelope.cs b/src/Envelopes/MinimalLambda.Envelopes.Kinesis/KinesisEnvelope.cs index 7f235162..f8eeb54b 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Kinesis/KinesisEnvelope.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.Kinesis/KinesisEnvelope.cs @@ -18,13 +18,13 @@ public sealed class KinesisEnvelope : KinesisEnvelopeBase [UnconditionalSuppressMessage( "Aot", "IL3050:RequiresDynamicCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] [UnconditionalSuppressMessage( "Aot", "IL2026:RequiresUnreferencedCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] public override void ExtractPayload(EnvelopeOptions options) { foreach (var record in Records) @@ -32,14 +32,12 @@ public override void ExtractPayload(EnvelopeOptions options) using var reader = new StreamReader( record.Kinesis.Data, Encoding.UTF8, - leaveOpen: true - ); + leaveOpen: true); var base64String = reader.ReadToEnd(); var jsonBytes = Convert.FromBase64String(base64String); record.Kinesis.DataContent = JsonSerializer.Deserialize( jsonBytes, - options.JsonOptions - ); + options.JsonOptions); } } } diff --git a/src/Envelopes/MinimalLambda.Envelopes.Kinesis/MinimalLambda.Envelopes.Kinesis.csproj b/src/Envelopes/MinimalLambda.Envelopes.Kinesis/MinimalLambda.Envelopes.Kinesis.csproj index 89cdc799..83b3ec0e 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Kinesis/MinimalLambda.Envelopes.Kinesis.csproj +++ b/src/Envelopes/MinimalLambda.Envelopes.Kinesis/MinimalLambda.Envelopes.Kinesis.csproj @@ -14,15 +14,15 @@ - - + + - + - - + + diff --git a/src/Envelopes/MinimalLambda.Envelopes.Kinesis/README.md b/src/Envelopes/MinimalLambda.Envelopes.Kinesis/README.md index 67888405..58442288 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Kinesis/README.md +++ b/src/Envelopes/MinimalLambda.Envelopes.Kinesis/README.md @@ -117,8 +117,8 @@ builder.Services.ConfigureEnvelopeOptions(options => Additional packages in the minimal-lambda framework for abstractions, observability, and event source handling. -| Package | NuGet | Downloads | -|-------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Package | NuGet | Downloads | +|-----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [**MinimalLambda**](../../MinimalLambda/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda/) | | [**MinimalLambda.Abstractions**](../../MinimalLambda.Abstractions/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions/) | | [**MinimalLambda.OpenTelemetry**](../../MinimalLambda.OpenTelemetry/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry/) | diff --git a/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/KinesisFirehoseEventEnvelope.cs b/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/KinesisFirehoseEventEnvelope.cs index 6cc87cf8..e74cbf07 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/KinesisFirehoseEventEnvelope.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/KinesisFirehoseEventEnvelope.cs @@ -17,19 +17,18 @@ public sealed class KinesisFirehoseEventEnvelope : KinesisFirehoseEventEnvelo [UnconditionalSuppressMessage( "Aot", "IL3050:RequiresDynamicCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] [UnconditionalSuppressMessage( "Aot", "IL2026:RequiresUnreferencedCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] public override void ExtractPayload(EnvelopeOptions options) { foreach (var record in Records) record.DataContent = JsonSerializer.Deserialize( record.DecodeData(), - options.JsonOptions - ); + options.JsonOptions); } } diff --git a/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/KinesisFirehoseResponseEnvelope.cs b/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/KinesisFirehoseResponseEnvelope.cs index 59cf4c81..a58bde8e 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/KinesisFirehoseResponseEnvelope.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/KinesisFirehoseResponseEnvelope.cs @@ -17,13 +17,13 @@ public sealed class KinesisFirehoseResponseEnvelope : KinesisFirehoseResponse [UnconditionalSuppressMessage( "Aot", "IL3050:RequiresDynamicCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] [UnconditionalSuppressMessage( "Aot", "IL2026:RequiresUnreferencedCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] public override void PackPayload(EnvelopeOptions options) { foreach (var record in Records) diff --git a/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/KinesisFirehoseResponseEnvelopeBase.cs b/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/KinesisFirehoseResponseEnvelopeBase.cs index 09261419..5633f683 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/KinesisFirehoseResponseEnvelopeBase.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/KinesisFirehoseResponseEnvelopeBase.cs @@ -13,8 +13,7 @@ namespace MinimalLambda.Envelopes.KinesisFirehose; /// their chosen serialization strategy. /// public abstract class KinesisFirehoseResponseEnvelopeBase - : KinesisFirehoseResponse, - IResponseEnvelope + : KinesisFirehoseResponse, IResponseEnvelope { /// public new required IList Records { get; set; } diff --git a/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/MinimalLambda.Envelopes.KinesisFirehose.csproj b/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/MinimalLambda.Envelopes.KinesisFirehose.csproj index e11173c5..ee363bc0 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/MinimalLambda.Envelopes.KinesisFirehose.csproj +++ b/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/MinimalLambda.Envelopes.KinesisFirehose.csproj @@ -14,14 +14,14 @@ - - + + - + - + diff --git a/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/README.md b/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/README.md index dac8e8be..d8315e72 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/README.md +++ b/src/Envelopes/MinimalLambda.Envelopes.KinesisFirehose/README.md @@ -152,8 +152,8 @@ builder.Services.ConfigureEnvelopeOptions(options => Additional packages in the minimal-lambda framework for abstractions, observability, and event source handling. -| Package | NuGet | Downloads | -|-------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Package | NuGet | Downloads | +|-----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [**MinimalLambda**](../../MinimalLambda/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda/) | | [**MinimalLambda.Abstractions**](../../MinimalLambda.Abstractions/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions/) | | [**MinimalLambda.OpenTelemetry**](../../MinimalLambda.OpenTelemetry/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry/) | diff --git a/src/Envelopes/MinimalLambda.Envelopes.Sns/MinimalLambda.Envelopes.Sns.csproj b/src/Envelopes/MinimalLambda.Envelopes.Sns/MinimalLambda.Envelopes.Sns.csproj index 969d1454..53b06aee 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Sns/MinimalLambda.Envelopes.Sns.csproj +++ b/src/Envelopes/MinimalLambda.Envelopes.Sns/MinimalLambda.Envelopes.Sns.csproj @@ -14,14 +14,14 @@ - - + + - + - + diff --git a/src/Envelopes/MinimalLambda.Envelopes.Sns/README.md b/src/Envelopes/MinimalLambda.Envelopes.Sns/README.md index a63aaf28..969fb256 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Sns/README.md +++ b/src/Envelopes/MinimalLambda.Envelopes.Sns/README.md @@ -104,8 +104,8 @@ builder.Services.ConfigureEnvelopeOptions(options => Additional packages in the minimal-lambda framework for abstractions, observability, and event source handling. -| Package | NuGet | Downloads | -|-------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Package | NuGet | Downloads | +|-----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [**MinimalLambda**](../../MinimalLambda/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda/) | | [**MinimalLambda.Abstractions**](../../MinimalLambda.Abstractions/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions/) | | [**MinimalLambda.OpenTelemetry**](../../MinimalLambda.OpenTelemetry/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry/) | diff --git a/src/Envelopes/MinimalLambda.Envelopes.Sns/SnsEnvelope.cs b/src/Envelopes/MinimalLambda.Envelopes.Sns/SnsEnvelope.cs index 36ecd689..498de220 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Sns/SnsEnvelope.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.Sns/SnsEnvelope.cs @@ -17,19 +17,18 @@ public sealed class SnsEnvelope : SnsEnvelopeBase [UnconditionalSuppressMessage( "Aot", "IL3050:RequiresDynamicCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] [UnconditionalSuppressMessage( "Aot", "IL2026:RequiresUnreferencedCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] public override void ExtractPayload(EnvelopeOptions options) { foreach (var record in Records) record.Sns.MessageContent = JsonSerializer.Deserialize( record.Sns.Message, - options.JsonOptions - ); + options.JsonOptions); } } diff --git a/src/Envelopes/MinimalLambda.Envelopes.Sqs/MinimalLambda.Envelopes.Sqs.csproj b/src/Envelopes/MinimalLambda.Envelopes.Sqs/MinimalLambda.Envelopes.Sqs.csproj index a5b7b798..427bd86f 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Sqs/MinimalLambda.Envelopes.Sqs.csproj +++ b/src/Envelopes/MinimalLambda.Envelopes.Sqs/MinimalLambda.Envelopes.Sqs.csproj @@ -14,15 +14,15 @@ - - + + - - + + - + diff --git a/src/Envelopes/MinimalLambda.Envelopes.Sqs/README.md b/src/Envelopes/MinimalLambda.Envelopes.Sqs/README.md index 7f3a881b..16eae635 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Sqs/README.md +++ b/src/Envelopes/MinimalLambda.Envelopes.Sqs/README.md @@ -148,8 +148,8 @@ Lambda function processes messages from that queue. Additional packages in the minimal-lambda framework for abstractions, observability, and event source handling. -| Package | NuGet | Downloads | -|-------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Package | NuGet | Downloads | +|-----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [**MinimalLambda**](../../MinimalLambda/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda/) | | [**MinimalLambda.Abstractions**](../../MinimalLambda.Abstractions/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions/) | | [**MinimalLambda.OpenTelemetry**](../../MinimalLambda.OpenTelemetry/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry/) | diff --git a/src/Envelopes/MinimalLambda.Envelopes.Sqs/SqsEnvelope.cs b/src/Envelopes/MinimalLambda.Envelopes.Sqs/SqsEnvelope.cs index 03a59ca3..7a1ceaa0 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Sqs/SqsEnvelope.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.Sqs/SqsEnvelope.cs @@ -17,13 +17,13 @@ public sealed class SqsEnvelope : SqsEnvelopeBase [UnconditionalSuppressMessage( "Aot", "IL3050:RequiresDynamicCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] [UnconditionalSuppressMessage( "Aot", "IL2026:RequiresUnreferencedCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] public override void ExtractPayload(EnvelopeOptions options) { foreach (var record in Records) diff --git a/src/Envelopes/MinimalLambda.Envelopes.Sqs/SqsSnsEnvelope.cs b/src/Envelopes/MinimalLambda.Envelopes.Sqs/SqsSnsEnvelope.cs index 84371143..a55a150d 100644 --- a/src/Envelopes/MinimalLambda.Envelopes.Sqs/SqsSnsEnvelope.cs +++ b/src/Envelopes/MinimalLambda.Envelopes.Sqs/SqsSnsEnvelope.cs @@ -37,26 +37,24 @@ public sealed class SqsSnsEnvelope : SqsEnvelopeBase.SnsMe [UnconditionalSuppressMessage( "Aot", "IL3050:RequiresDynamicCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] [UnconditionalSuppressMessage( "Aot", "IL2026:RequiresUnreferencedCode", - Justification = "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T" - )] + Justification = + "Safe when EnvelopeOptions.JsonOptions includes source-generated context for T")] public override void ExtractPayload(EnvelopeOptions options) { foreach (var record in Records) { record.BodyContent = JsonSerializer.Deserialize.SnsMessageEnvelope>( record.Body, - options.LambdaDefaultJsonOptions - ); + options.LambdaDefaultJsonOptions); record.BodyContent!.MessageContent = JsonSerializer.Deserialize( record.BodyContent.Message, - options.JsonOptions - ); + options.JsonOptions); } } } diff --git a/src/Envelopes/MinimalLambda.Envelopes/BaseHttpResultExtensions.cs b/src/Envelopes/MinimalLambda.Envelopes/BaseHttpResultExtensions.cs index 1a7307ff..4be5ab7f 100644 --- a/src/Envelopes/MinimalLambda.Envelopes/BaseHttpResultExtensions.cs +++ b/src/Envelopes/MinimalLambda.Envelopes/BaseHttpResultExtensions.cs @@ -3,8 +3,7 @@ namespace MinimalLambda.Envelopes; /// Provides factory extension methods for creating HTTP results. public static class BaseHttpResultExtensions { - extension(IHttpResult) - where TResult : IHttpResult + extension(IHttpResult) where TResult : IHttpResult { /// Creates an HTTP result with the specified status code. /// The HTTP status code. @@ -25,8 +24,7 @@ public static TResult Text(int statusCode, string body) => { ["Content-Type"] = "text/plain; charset=utf-8", }, - false - ) + false) .Customize(result => result.Body = body); /// Creates an application/json HTTP result. @@ -42,12 +40,10 @@ public static TResult Json(int statusCode, T bodyContent) => { ["Content-Type"] = "application/json; charset=utf-8", }, - false - ); + false); } - extension(TResult result) - where TResult : IHttpResult + extension(TResult result) where TResult : IHttpResult { /// Applies customizations to the result. /// An action to customize the result properties. diff --git a/src/Envelopes/MinimalLambda.Envelopes/HttpResultExtensions.cs b/src/Envelopes/MinimalLambda.Envelopes/HttpResultExtensions.cs index e4081aaa..a65fec85 100644 --- a/src/Envelopes/MinimalLambda.Envelopes/HttpResultExtensions.cs +++ b/src/Envelopes/MinimalLambda.Envelopes/HttpResultExtensions.cs @@ -5,8 +5,7 @@ namespace MinimalLambda.Envelopes; /// Provides convenience extension methods for common HTTP status codes. public static class HttpResultExtensions { - extension(IHttpResult) - where TResult : IHttpResult + extension(IHttpResult) where TResult : IHttpResult { // ── 200 Ok ─────────────────────────────────────────────────────────────────────── @@ -164,8 +163,7 @@ public static TResult UnprocessableEntity() => public static TResult UnprocessableEntity(T bodyContent) => BaseHttpResultExtensions.Json( StatusCodes.Status422UnprocessableEntity, - bodyContent - ); + bodyContent); // ── 500 Internal Server Error ──────────────────────────────────────────────────── @@ -181,7 +179,6 @@ public static TResult InternalServerError() => public static TResult InternalServerError(T bodyContent) => BaseHttpResultExtensions.Json( StatusCodes.Status500InternalServerError, - bodyContent - ); + bodyContent); } } diff --git a/src/Envelopes/MinimalLambda.Envelopes/IHttpResult.cs b/src/Envelopes/MinimalLambda.Envelopes/IHttpResult.cs index 075042a3..f015fc77 100644 --- a/src/Envelopes/MinimalLambda.Envelopes/IHttpResult.cs +++ b/src/Envelopes/MinimalLambda.Envelopes/IHttpResult.cs @@ -5,8 +5,7 @@ namespace MinimalLambda.Envelopes; /// Gateway v2 Lambda integrations. /// /// The concrete implementing type for fluent method chaining. -public interface IHttpResult : IResponseEnvelope - where TSelf : IHttpResult +public interface IHttpResult : IResponseEnvelope where TSelf : IHttpResult { /// Gets or sets the response body content. public string Body { get; set; } @@ -31,6 +30,5 @@ static abstract TSelf Create( int statusCode, TResponse? bodyContent, IDictionary headers, - bool isBase64Encoded - ); + bool isBase64Encoded); } diff --git a/src/Envelopes/MinimalLambda.Envelopes/MinimalLambda.Envelopes.csproj b/src/Envelopes/MinimalLambda.Envelopes/MinimalLambda.Envelopes.csproj index 57381f7e..784782e5 100644 --- a/src/Envelopes/MinimalLambda.Envelopes/MinimalLambda.Envelopes.csproj +++ b/src/Envelopes/MinimalLambda.Envelopes/MinimalLambda.Envelopes.csproj @@ -23,12 +23,12 @@ $(NoWarn);AD0001 - + - + - + diff --git a/src/Envelopes/MinimalLambda.Envelopes/README.md b/src/Envelopes/MinimalLambda.Envelopes/README.md index b5dede00..f9202248 100644 --- a/src/Envelopes/MinimalLambda.Envelopes/README.md +++ b/src/Envelopes/MinimalLambda.Envelopes/README.md @@ -6,7 +6,8 @@ Shared infrastructure and abstractions for envelope packages. ## Overview -This package contains shared infrastructure and common abstractions used across envelope packages in the MinimalLambda framework. +This package contains shared infrastructure and common abstractions used across envelope packages in +the MinimalLambda framework. > [!NOTE] > This is an infrastructure package automatically referenced by other envelope packages. @@ -17,10 +18,11 @@ This package contains shared infrastructure and common abstractions used across ## Other Packages -Additional packages in the minimal-lambda framework for abstractions, observability, and event source handling. +Additional packages in the minimal-lambda framework for abstractions, observability, and event +source handling. -| Package | NuGet | Downloads | -|-------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Package | NuGet | Downloads | +|-----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [**MinimalLambda**](../../MinimalLambda/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda/) | | [**MinimalLambda.Abstractions**](../../MinimalLambda.Abstractions/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions/) | | [**MinimalLambda.OpenTelemetry**](../../MinimalLambda.OpenTelemetry/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry/) | diff --git a/src/Envelopes/README.md b/src/Envelopes/README.md index 17ff5c74..6d07ee09 100644 --- a/src/Envelopes/README.md +++ b/src/Envelopes/README.md @@ -22,8 +22,8 @@ IDE support and compile-time type checking. ## Packages -| Lambda Event Type | Package | NuGet | Downloads | -|--------------------------------------|-------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Lambda Event Type | Package | NuGet | Downloads | +|--------------------------------------|-----------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | SQS | [**MinimalLambda.Envelopes.Sqs**](./MinimalLambda.Envelopes.Sqs/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Envelopes.Sqs.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.Sqs) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Envelopes.Sqs.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.Sqs/) | | SQS (SNS-to-SQS Subscription) | [**MinimalLambda.Envelopes.Sqs**](./MinimalLambda.Envelopes.Sqs/README.md#sqssnsenvelope---sns-to-sqs-subscription-pattern) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Envelopes.Sqs.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.Sqs) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Envelopes.Sqs.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.Sqs/) | | API Gateway (REST/HTTP/WebSocket) | [**MinimalLambda.Envelopes.ApiGateway**](./MinimalLambda.Envelopes.ApiGateway/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Envelopes.ApiGateway.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.ApiGateway) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Envelopes.ApiGateway.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.ApiGateway/) | diff --git a/src/MinimalLambda.Abstractions/Attributes/EventAttribute.cs b/src/MinimalLambda.Abstractions/Attributes/EventAttribute.cs index 82e69df5..fab830f8 100644 --- a/src/MinimalLambda.Abstractions/Attributes/EventAttribute.cs +++ b/src/MinimalLambda.Abstractions/Attributes/EventAttribute.cs @@ -25,7 +25,6 @@ namespace MinimalLambda.Builder; /// /// [Obsolete( - "This Attribute is obsolete because it does not follow .NET naming conventions and can cuse naming conflicts with System.Diagnostics.Tracing.EventAttribute. Use FromEventAttribute instead." -)] + "This Attribute is obsolete because it does not follow .NET naming conventions and can cuse naming conflicts with System.Diagnostics.Tracing.EventAttribute. Use FromEventAttribute instead.")] [AttributeUsage(AttributeTargets.Parameter)] public sealed class EventAttribute : Attribute; diff --git a/src/MinimalLambda.Abstractions/Builders/ILambdaInvocationBuilder.cs b/src/MinimalLambda.Abstractions/Builders/ILambdaInvocationBuilder.cs index 085b7935..9be14927 100644 --- a/src/MinimalLambda.Abstractions/Builders/ILambdaInvocationBuilder.cs +++ b/src/MinimalLambda.Abstractions/Builders/ILambdaInvocationBuilder.cs @@ -52,8 +52,7 @@ public interface ILambdaInvocationBuilder /// /// The current instance for method chaining. ILambdaInvocationBuilder Use( - Func middleware - ); + Func middleware); /// Builds the final invocation delegate by composing the handler and middleware. /// diff --git a/src/MinimalLambda.Abstractions/MinimalLambda.Abstractions.csproj b/src/MinimalLambda.Abstractions/MinimalLambda.Abstractions.csproj index 3f72e3ad..81a3c06f 100644 --- a/src/MinimalLambda.Abstractions/MinimalLambda.Abstractions.csproj +++ b/src/MinimalLambda.Abstractions/MinimalLambda.Abstractions.csproj @@ -13,14 +13,14 @@ README.md - - + + - - + + - + diff --git a/src/MinimalLambda.Abstractions/README.md b/src/MinimalLambda.Abstractions/README.md index d057ff7c..f47ebfa0 100644 --- a/src/MinimalLambda.Abstractions/README.md +++ b/src/MinimalLambda.Abstractions/README.md @@ -208,12 +208,12 @@ For implementation details and examples, see [MinimalLambda](../MinimalLambda/RE Additional packages in the minimal-lambda framework for abstractions, observability, and event source handling. -| Package | NuGet | Downloads | -|-----------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Package | NuGet | Downloads | +|---------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [**MinimalLambda**](../MinimalLambda/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda/) | | [**MinimalLambda.Abstractions**](../MinimalLambda.Abstractions/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions/) | | [**MinimalLambda.OpenTelemetry**](../MinimalLambda.OpenTelemetry/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry/) | -| [**MinimalLambda.Testing**](../MinimalLambda.Testing/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Testing.svg)](https://www.nuget.org/packages/MinimalLambda.Testing) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Testing.svg)](https://www.nuget.org/packages/MinimalLambda.Testing/) | +| [**MinimalLambda.Testing**](../MinimalLambda.Testing/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Testing.svg)](https://www.nuget.org/packages/MinimalLambda.Testing) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Testing.svg)](https://www.nuget.org/packages/MinimalLambda.Testing/) | | [**MinimalLambda.Envelopes**](../Envelopes/MinimalLambda.Envelopes/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Envelopes.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Envelopes.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes/) | | [**MinimalLambda.Envelopes.Sqs**](../Envelopes/MinimalLambda.Envelopes.Sqs/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Envelopes.Sqs.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.Sqs) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Envelopes.Sqs.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.Sqs/) | | [**MinimalLambda.Envelopes.ApiGateway**](../Envelopes/MinimalLambda.Envelopes.ApiGateway/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Envelopes.ApiGateway.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.ApiGateway) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Envelopes.ApiGateway.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.ApiGateway/) | diff --git a/src/MinimalLambda.OpenTelemetry/MiddlewareOpenTelemetryExtensions.cs b/src/MinimalLambda.OpenTelemetry/MiddlewareOpenTelemetryExtensions.cs index 5a6024a9..f6107da1 100644 --- a/src/MinimalLambda.OpenTelemetry/MiddlewareOpenTelemetryExtensions.cs +++ b/src/MinimalLambda.OpenTelemetry/MiddlewareOpenTelemetryExtensions.cs @@ -36,20 +36,16 @@ public ILambdaInvocationBuilder UseOpenTelemetryTracing() var tracerProvider = builder.Services.GetRequiredService(); - return builder.Use(next => - context => - AWSLambdaWrapper.TraceAsync( - tracerProvider, - async Task (_, _) => - { - await next(context); + return builder.Use(next => context => AWSLambdaWrapper.TraceAsync( + tracerProvider, + async Task (_, _) => + { + await next(context); - return context.Features.Get()?.GetResponse(); - }, - context.Features.Get()?.GetEvent(context), - context - ) - ); + return context.Features.Get()?.GetResponse(); + }, + context.Features.Get()?.GetEvent(context), + context)); } } } diff --git a/src/MinimalLambda.OpenTelemetry/MinimalLambda.OpenTelemetry.csproj b/src/MinimalLambda.OpenTelemetry/MinimalLambda.OpenTelemetry.csproj index 875740ae..a59718c0 100644 --- a/src/MinimalLambda.OpenTelemetry/MinimalLambda.OpenTelemetry.csproj +++ b/src/MinimalLambda.OpenTelemetry/MinimalLambda.OpenTelemetry.csproj @@ -24,8 +24,8 @@ $(NoWarn);AD0001 - - + + - + - + diff --git a/src/MinimalLambda.OpenTelemetry/OnShutdownOpenTelemetryExtensions.cs b/src/MinimalLambda.OpenTelemetry/OnShutdownOpenTelemetryExtensions.cs index f97d8fd2..39114ba6 100644 --- a/src/MinimalLambda.OpenTelemetry/OnShutdownOpenTelemetryExtensions.cs +++ b/src/MinimalLambda.OpenTelemetry/OnShutdownOpenTelemetryExtensions.cs @@ -36,8 +36,7 @@ public static class OnShutdownOpenTelemetryExtensions /// /// public ILambdaOnShutdownBuilder OnShutdownFlushOpenTelemetry( - int timeoutMilliseconds = Timeout.Infinite - ) + int timeoutMilliseconds = Timeout.Infinite) { ArgumentNullException.ThrowIfNull(application); @@ -68,8 +67,7 @@ public ILambdaOnShutdownBuilder OnShutdownFlushOpenTelemetry( /// /// public ILambdaOnShutdownBuilder OnShutdownFlushTracer( - int timeoutMilliseconds = Timeout.Infinite - ) + int timeoutMilliseconds = Timeout.Infinite) { ArgumentNullException.ThrowIfNull(application); @@ -78,16 +76,12 @@ public ILambdaOnShutdownBuilder OnShutdownFlushTracer( application.Services.GetService()?.CreateLogger(LogCategory) ?? NullLogger.Instance; - application.OnShutdown( - (CancellationToken cancellationToken) => - RunForceFlush( - "tracer", - tracerProvider.ForceFlush, - timeoutMilliseconds, - logger, - cancellationToken - ) - ); + application.OnShutdown((CancellationToken cancellationToken) => RunForceFlush( + "tracer", + tracerProvider.ForceFlush, + timeoutMilliseconds, + logger, + cancellationToken)); return application; } @@ -112,8 +106,7 @@ public ILambdaOnShutdownBuilder OnShutdownFlushTracer( /// /// public ILambdaOnShutdownBuilder OnShutdownFlushMeter( - int timeoutMilliseconds = Timeout.Infinite - ) + int timeoutMilliseconds = Timeout.Infinite) { ArgumentNullException.ThrowIfNull(application); @@ -122,16 +115,12 @@ public ILambdaOnShutdownBuilder OnShutdownFlushMeter( application.Services.GetService()?.CreateLogger(LogCategory) ?? NullLogger.Instance; - application.OnShutdown( - (CancellationToken cancellationToken) => - RunForceFlush( - "meter", - meterProvider.ForceFlush, - timeoutMilliseconds, - logger, - cancellationToken - ) - ); + application.OnShutdown((CancellationToken cancellationToken) => RunForceFlush( + "meter", + meterProvider.ForceFlush, + timeoutMilliseconds, + logger, + cancellationToken)); return application; } @@ -142,8 +131,7 @@ private static async Task RunForceFlush( Func flusher, int timeoutMilliseconds, ILogger logger, - CancellationToken cancellationToken - ) + CancellationToken cancellationToken) { var flusherTask = Task.Run(() => flusher(timeoutMilliseconds), cancellationToken); @@ -153,8 +141,7 @@ CancellationToken cancellationToken { logger.LogWarning( "OpenTelemetry {ProviderName} provider force flush failed to complete within allocated time", - providerName - ); + providerName); return; } @@ -162,8 +149,7 @@ CancellationToken cancellationToken logger.LogInformation( "OpenTelemetry {ProviderName} provider force flush {Status}", providerName, - flusherTask.Result ? "succeeded" : "failed" - ); + flusherTask.Result ? "succeeded" : "failed"); } } } diff --git a/src/MinimalLambda.OpenTelemetry/README.md b/src/MinimalLambda.OpenTelemetry/README.md index 28fd759b..cf37927a 100644 --- a/src/MinimalLambda.OpenTelemetry/README.md +++ b/src/MinimalLambda.OpenTelemetry/README.md @@ -246,12 +246,12 @@ The example demonstrates: Additional packages in the minimal-lambda framework for abstractions, observability, and event source handling. -| Package | NuGet | Downloads | -|-----------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Package | NuGet | Downloads | +|---------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [**MinimalLambda**](../MinimalLambda/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda/) | | [**MinimalLambda.Abstractions**](../MinimalLambda.Abstractions/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions/) | | [**MinimalLambda.OpenTelemetry**](../MinimalLambda.OpenTelemetry/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry/) | -| [**MinimalLambda.Testing**](../MinimalLambda.Testing/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Testing.svg)](https://www.nuget.org/packages/MinimalLambda.Testing) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Testing.svg)](https://www.nuget.org/packages/MinimalLambda.Testing/) | +| [**MinimalLambda.Testing**](../MinimalLambda.Testing/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Testing.svg)](https://www.nuget.org/packages/MinimalLambda.Testing) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Testing.svg)](https://www.nuget.org/packages/MinimalLambda.Testing/) | | [**MinimalLambda.Envelopes**](../Envelopes/MinimalLambda.Envelopes/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Envelopes.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Envelopes.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes/) | | [**MinimalLambda.Envelopes.Sqs**](../Envelopes/MinimalLambda.Envelopes.Sqs/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Envelopes.Sqs.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.Sqs) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Envelopes.Sqs.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.Sqs/) | | [**MinimalLambda.Envelopes.ApiGateway**](../Envelopes/MinimalLambda.Envelopes.ApiGateway/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Envelopes.ApiGateway.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.ApiGateway) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Envelopes.ApiGateway.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.ApiGateway/) | diff --git a/src/MinimalLambda.SourceGenerators/AnalyzerReleases.Shipped.md b/src/MinimalLambda.SourceGenerators/AnalyzerReleases.Shipped.md index 7b062c27..796b6583 100644 --- a/src/MinimalLambda.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/MinimalLambda.SourceGenerators/AnalyzerReleases.Shipped.md @@ -19,8 +19,8 @@ ### New Rules - Rule ID | Category | Severity | Notes ----------|------------------------------|----------|----------------------------------- + Rule ID | Category | Severity | Notes +---------|-----------------------------|----------|----------------------------------- LH0001 | MinimalLambda.Usage | Error | Multiple method calls detected LH0002 | MinimalLambda.Usage | Error | Multiple parameters use attribute LH0003 | MinimalLambda.Usage | Error | Invalid attribute argument diff --git a/src/MinimalLambda.SourceGenerators/Diagnostics/DiagnosticGenerator.cs b/src/MinimalLambda.SourceGenerators/Diagnostics/DiagnosticGenerator.cs index 99dcc35e..b24091ab 100644 --- a/src/MinimalLambda.SourceGenerators/Diagnostics/DiagnosticGenerator.cs +++ b/src/MinimalLambda.SourceGenerators/Diagnostics/DiagnosticGenerator.cs @@ -14,26 +14,22 @@ internal static List GenerateDiagnostics(CompilationInfo compilation diagnostics.AddRange( compilationInfo .MapHandlerInvocationInfos.SelectMany(m => m.DiagnosticInfos) - .Select(d => d.ToDiagnostic()) - ); + .Select(d => d.ToDiagnostic())); diagnostics.AddRange( compilationInfo .OnInitInvocationInfos.SelectMany(m => m.DiagnosticInfos) - .Select(d => d.ToDiagnostic()) - ); + .Select(d => d.ToDiagnostic())); diagnostics.AddRange( compilationInfo .OnShutdownInvocationInfos.SelectMany(m => m.DiagnosticInfos) - .Select(d => d.ToDiagnostic()) - ); + .Select(d => d.ToDiagnostic())); diagnostics.AddRange( compilationInfo .UseMiddlewareTInfos.SelectMany(m => m.DiagnosticInfos) - .Select(d => d.ToDiagnostic()) - ); + .Select(d => d.ToDiagnostic())); return diagnostics; } diff --git a/src/MinimalLambda.SourceGenerators/Diagnostics/DiagnosticInfo.cs b/src/MinimalLambda.SourceGenerators/Diagnostics/DiagnosticInfo.cs index dee169c3..b184a51c 100644 --- a/src/MinimalLambda.SourceGenerators/Diagnostics/DiagnosticInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Diagnostics/DiagnosticInfo.cs @@ -6,8 +6,7 @@ namespace MinimalLambda.SourceGenerators.Models; internal sealed record DiagnosticInfo( DiagnosticDescriptor DiagnosticDescriptor, LocationInfo? LocationInfo = null, - params object?[] MessageArgs -) + params object?[] MessageArgs) { public bool Equals(DiagnosticInfo? other) => other is not null @@ -24,15 +23,14 @@ internal static class DiagnosticInfoExtensions internal static DiagnosticInfo Create( DiagnosticDescriptor diagnosticDescriptor, LocationInfo? locationInfo, - object?[] messageArgs - ) => new(diagnosticDescriptor, locationInfo, messageArgs); + object?[] messageArgs) => + new(diagnosticDescriptor, locationInfo, messageArgs); internal Diagnostic ToDiagnostic() => Diagnostic.Create( diagnosticInfo.DiagnosticDescriptor, diagnosticInfo.LocationInfo?.ToLocation(), - diagnosticInfo.MessageArgs - ); + diagnosticInfo.MessageArgs); internal void ReportDiagnostic(SourceProductionContext context) => context.ReportDiagnostic(diagnosticInfo.ToDiagnostic()); diff --git a/src/MinimalLambda.SourceGenerators/Diagnostics/DiagnosticResult.cs b/src/MinimalLambda.SourceGenerators/Diagnostics/DiagnosticResult.cs index fe071c68..9c7ccda4 100644 --- a/src/MinimalLambda.SourceGenerators/Diagnostics/DiagnosticResult.cs +++ b/src/MinimalLambda.SourceGenerators/Diagnostics/DiagnosticResult.cs @@ -28,8 +28,8 @@ private DiagnosticResult(bool isSuccess, T? value, DiagnosticInfo? error) public static DiagnosticResult Failure( DiagnosticDescriptor diagnosticDescriptor, LocationInfo? locationInfo = null, - params object?[] messageArgs - ) => new(false, default, new DiagnosticInfo(diagnosticDescriptor, locationInfo, messageArgs)); + params object?[] messageArgs) => + new(false, default, new DiagnosticInfo(diagnosticDescriptor, locationInfo, messageArgs)); public DiagnosticResult Map(Func map) => IsSuccess @@ -41,8 +41,8 @@ public DiagnosticResult Bind(Func> bind) = public TResult Match( Func onSuccess, - Func onFailure - ) => IsSuccess ? onSuccess(Value!) : onFailure(Error!); + Func onFailure) => + IsSuccess ? onSuccess(Value!) : onFailure(Error!); public void Switch(Action onSuccess, Action onFailure) { diff --git a/src/MinimalLambda.SourceGenerators/Diagnostics/Diagnostics.cs b/src/MinimalLambda.SourceGenerators/Diagnostics/Diagnostics.cs index d850d6c8..462e39ca 100644 --- a/src/MinimalLambda.SourceGenerators/Diagnostics/Diagnostics.cs +++ b/src/MinimalLambda.SourceGenerators/Diagnostics/Diagnostics.cs @@ -13,8 +13,7 @@ internal static class Diagnostics "Handler method contains multiple parameters that use the '{0}' attribute. Only one parameter can use this attribute.", UsageCategory, DiagnosticSeverity.Error, - true - ); + true); internal static readonly DiagnosticDescriptor InvalidAttributeArgument = new( "LH0003", @@ -22,18 +21,16 @@ internal static class Diagnostics "An argument of type '{0}' is not valid for this attribute. Please use a valid type.", UsageCategory, DiagnosticSeverity.Error, - true - ); + true); public static readonly DiagnosticDescriptor CSharpVersionTooLow = new( "LH0004", "C# language version too low", "MinimalLambda requires C# 11 or newer (or LanguageVersion=default with a modern SDK). " - + "Set latest or enable preview features.", + + "Set latest or enable preview features.", ConfigurationCategory, DiagnosticSeverity.Error, - true - ); + true); public static readonly DiagnosticDescriptor MultipleConstructorsWithAttribute = new( "LH0005", @@ -41,8 +38,7 @@ internal static class Diagnostics "Type contains multiple constructors that use the '{0}' attribute. Only one constructor can use this attribute.", ConfigurationCategory, DiagnosticSeverity.Error, - true - ); + true); public static readonly DiagnosticDescriptor MustBeConcreteType = new( "LH0006", @@ -50,6 +46,5 @@ internal static class Diagnostics "The type '{0}' must be a concrete class. Interfaces, abstract classes, and other non-instantiable types cannot be used as middleware.", ConfigurationCategory, DiagnosticSeverity.Error, - true - ); + true); } diff --git a/src/MinimalLambda.SourceGenerators/Emitters/InvocationHandlerEmitter.cs b/src/MinimalLambda.SourceGenerators/Emitters/InvocationHandlerEmitter.cs index dd7fed94..ad95e9e9 100644 --- a/src/MinimalLambda.SourceGenerators/Emitters/InvocationHandlerEmitter.cs +++ b/src/MinimalLambda.SourceGenerators/Emitters/InvocationHandlerEmitter.cs @@ -11,16 +11,14 @@ internal static class InvocationHandlerEmitter internal static void Emit( SourceProductionContext context, - ImmutableArray infos - ) + ImmutableArray infos) { if (infos.Length == 0) return; var code = TemplateHelper.Render( LambdaHostMapHandlerExtensionsTemplateFile, - new { TemplateHelper.GeneratedCodeAttribute, MapHandlerCalls = infos } - ); + new { TemplateHelper.GeneratedCodeAttribute, MapHandlerCalls = infos }); context.AddSource("MinimalLambda.InvocationHandlers.g.cs", code); } diff --git a/src/MinimalLambda.SourceGenerators/Emitters/LifecycleHandlerEmitter.cs b/src/MinimalLambda.SourceGenerators/Emitters/LifecycleHandlerEmitter.cs index 245c7a39..fd65662f 100644 --- a/src/MinimalLambda.SourceGenerators/Emitters/LifecycleHandlerEmitter.cs +++ b/src/MinimalLambda.SourceGenerators/Emitters/LifecycleHandlerEmitter.cs @@ -11,8 +11,7 @@ internal static class LifecycleHandlerEmitter internal static void Emit( SourceProductionContext context, - ImmutableArray infos - ) + ImmutableArray infos) { if (infos.Length == 0) return; @@ -21,13 +20,7 @@ ImmutableArray infos var code = TemplateHelper.Render( GenericHandlerTemplateFile, - new - { - TemplateHelper.GeneratedCodeAttribute, - Name = name, - Calls = infos, - } - ); + new { TemplateHelper.GeneratedCodeAttribute, Name = name, Calls = infos }); context.AddSource($"MinimalLambda.{name}Handlers.g.cs", code); } diff --git a/src/MinimalLambda.SourceGenerators/Emitters/MiddlewareClassEmitter.cs b/src/MinimalLambda.SourceGenerators/Emitters/MiddlewareClassEmitter.cs index e5b30f80..d1bfaa2a 100644 --- a/src/MinimalLambda.SourceGenerators/Emitters/MiddlewareClassEmitter.cs +++ b/src/MinimalLambda.SourceGenerators/Emitters/MiddlewareClassEmitter.cs @@ -10,16 +10,14 @@ internal static class MiddlewareClassEmitter internal static void Emit( SourceProductionContext context, - ImmutableArray infos - ) + ImmutableArray infos) { if (infos.Length == 0) return; var code = TemplateHelper.Render( UseMiddlewareTTemplateFile, - new { TemplateHelper.GeneratedCodeAttribute, Calls = infos } - ); + new { TemplateHelper.GeneratedCodeAttribute, Calls = infos }); context.AddSource("MinimalLambda.UseMiddleware.g.cs", code); } diff --git a/src/MinimalLambda.SourceGenerators/Emitters/TemplateHelper.cs b/src/MinimalLambda.SourceGenerators/Emitters/TemplateHelper.cs index cb2f2133..0ebdd29f 100644 --- a/src/MinimalLambda.SourceGenerators/Emitters/TemplateHelper.cs +++ b/src/MinimalLambda.SourceGenerators/Emitters/TemplateHelper.cs @@ -19,7 +19,8 @@ internal static class TemplateHelper var generatorName = assembly.GetName().Name; var generatorVersion = assembly.GetName().Version; - return $"""[global::System.CodeDom.Compiler.GeneratedCode("{generatorName}", "{generatorVersion}")]"""; + return + $"""[global::System.CodeDom.Compiler.GeneratedCode("{generatorName}", "{generatorVersion}")]"""; }); private static readonly ConcurrentDictionary Cache = new(); @@ -70,8 +71,7 @@ private static Template LoadTemplate(string relativePath) var availableResources = string.Join(", ", assembly.GetManifestResourceNames()); throw new InvalidOperationException( $"Did not find required resource ending in '{templateName}' in assembly '{baseName}'. " - + $"Available resources: {availableResources}" - ); + + $"Available resources: {availableResources}"); } // Load the template content @@ -79,8 +79,7 @@ private static Template LoadTemplate(string relativePath) if (stream == null) throw new FileNotFoundException( $"Template '{relativePath}' not found in embedded resources. " - + $"Manifest resource name: '{manifestTemplateName}'" - ); + + $"Manifest resource name: '{manifestTemplateName}'"); using var reader = new StreamReader(stream); var templateContent = reader.ReadToEnd(); @@ -92,11 +91,8 @@ private static Template LoadTemplate(string relativePath) var errors = string.Join( "\n", template.Messages.Select(m => - $"{relativePath}({m.Span.Start.Line},{m.Span.Start.Column}): {m.Message}" - ) - ); + $"{relativePath}({m.Span.Start.Line},{m.Span.Start.Column}): {m.Message}")); throw new InvalidOperationException( - $"Failed to parse template '{relativePath}':\n{errors}" - ); + $"Failed to parse template '{relativePath}':\n{errors}"); } } diff --git a/src/MinimalLambda.SourceGenerators/Extensions/EnumerableExtensions.cs b/src/MinimalLambda.SourceGenerators/Extensions/EnumerableExtensions.cs index 6677974b..e3c46286 100644 --- a/src/MinimalLambda.SourceGenerators/Extensions/EnumerableExtensions.cs +++ b/src/MinimalLambda.SourceGenerators/Extensions/EnumerableExtensions.cs @@ -15,24 +15,19 @@ public void ForEach(Action action) } internal (List Data, List Diagnostics) CollectDiagnosticResults( - Func> extractor - ) => + Func> extractor) => enumerable .Select(extractor) .Aggregate( - ( - Successes: new List(enumerable is ICollection c ? c.Count : 0), - Diagnostics: new List() - ), + (Successes: new List(enumerable is ICollection c ? c.Count : 0), + Diagnostics: new List()), static (acc, result) => { result.Switch( info => acc.Successes.Add(info), - diagnostic => acc.Diagnostics.Add(diagnostic) - ); + diagnostic => acc.Diagnostics.Add(diagnostic)); return acc; - } - ); + }); } } diff --git a/src/MinimalLambda.SourceGenerators/Extensions/IncrementalValueProviderExtensions.cs b/src/MinimalLambda.SourceGenerators/Extensions/IncrementalValueProviderExtensions.cs index 8bf2f2ae..d265d78f 100644 --- a/src/MinimalLambda.SourceGenerators/Extensions/IncrementalValueProviderExtensions.cs +++ b/src/MinimalLambda.SourceGenerators/Extensions/IncrementalValueProviderExtensions.cs @@ -5,21 +5,16 @@ namespace Microsoft.CodeAnalysis; internal static class IncrementalValueProviderExtensions { - extension(IncrementalValuesProvider valueProviders) - where T : class + extension(IncrementalValuesProvider valueProviders) where T : class { public IncrementalValuesProvider WhereNotNull() => valueProviders.Where(static v => v is not null).Select(static (v, _) => v!); } - extension(IncrementalValuesProvider valueProviders) - where T : IMethodInfo + extension(IncrementalValuesProvider valueProviders) where T : IMethodInfo { public IncrementalValuesProvider WhereNoErrors() => - valueProviders.Where(static c => - c.DiagnosticInfos.All(d => - d.DiagnosticDescriptor.DefaultSeverity != DiagnosticSeverity.Error - ) - ); + valueProviders.Where(static c => c.DiagnosticInfos.All(d => + d.DiagnosticDescriptor.DefaultSeverity != DiagnosticSeverity.Error)); } } diff --git a/src/MinimalLambda.SourceGenerators/Extensions/MethodSymbolExtensions.cs b/src/MinimalLambda.SourceGenerators/Extensions/MethodSymbolExtensions.cs index 740e2521..50c89d1f 100644 --- a/src/MinimalLambda.SourceGenerators/Extensions/MethodSymbolExtensions.cs +++ b/src/MinimalLambda.SourceGenerators/Extensions/MethodSymbolExtensions.cs @@ -14,14 +14,12 @@ internal string GetCastableSignature() { var returnType = methodSymbol.ReturnType.QualifiedNullableName; var parameters = methodSymbol - .Parameters.Select( - (p, i) => - { - var type = p.Type.QualifiedNullableName; - var defaultValue = p.IsOptional ? " = default" : ""; - return $"{type} arg{i}{defaultValue}"; - } - ) + .Parameters.Select((p, i) => + { + var type = p.Type.QualifiedNullableName; + var defaultValue = p.IsOptional ? " = default" : ""; + return $"{type} arg{i}{defaultValue}"; + }) .ToArray(); var parameterList = string.Join(", ", parameters); @@ -46,14 +44,12 @@ internal bool IsAwaitable(GeneratorContext context) // Check for ValueTask and ValueTask var valueTask = context.WellKnownTypes.Get( - WellKnownType.System_Threading_Tasks_ValueTask - ); + WellKnownType.System_Threading_Tasks_ValueTask); if (returnType.Equals(valueTask, SymbolEqualityComparer.Default)) return true; var valueTaskOfT = context.WellKnownTypes.Get( - WellKnownType.System_Threading_Tasks_ValueTask_T - ); + WellKnownType.System_Threading_Tasks_ValueTask_T); if (returnType.OriginalDefinition.Equals(valueTaskOfT, SymbolEqualityComparer.Default)) return true; @@ -66,8 +62,7 @@ internal bool IsAwaitable(GeneratorContext context) internal bool HasMeaningfulReturnType( GeneratorContext context, - [NotNullWhen(true)] out INamedTypeSymbol? unwrappedReturnType - ) + [NotNullWhen(true)] out INamedTypeSymbol? unwrappedReturnType) { unwrappedReturnType = null; @@ -91,8 +86,7 @@ bool IsVoidLike(ITypeSymbol type) => type, WellKnownType.System_Void, WellKnownType.System_Threading_Tasks_Task, - WellKnownType.System_Threading_Tasks_ValueTask - ); + WellKnownType.System_Threading_Tasks_ValueTask); } private ITypeSymbol UnwrapReturnType(GeneratorContext context) @@ -102,18 +96,13 @@ private ITypeSymbol UnwrapReturnType(GeneratorContext context) var taskOfT = context.WellKnownTypes.Get(WellKnownType.System_Threading_Tasks_Task_T); var valueTaskOfT = context.WellKnownTypes.Get( - WellKnownType.System_Threading_Tasks_ValueTask_T - ); + WellKnownType.System_Threading_Tasks_ValueTask_T); var originalDef = namedReturnType.OriginalDefinition; - if ( - ( - originalDef.Equals(taskOfT, SymbolEqualityComparer.Default) - || originalDef.Equals(valueTaskOfT, SymbolEqualityComparer.Default) - ) - && namedReturnType.TypeArguments.Length > 0 - ) + if ((originalDef.Equals(taskOfT, SymbolEqualityComparer.Default) + || originalDef.Equals(valueTaskOfT, SymbolEqualityComparer.Default)) + && namedReturnType.TypeArguments.Length > 0) return namedReturnType.TypeArguments[0]; return namedReturnType; diff --git a/src/MinimalLambda.SourceGenerators/Extensions/ParameterSymbolExtensions.cs b/src/MinimalLambda.SourceGenerators/Extensions/ParameterSymbolExtensions.cs index 17eb5cef..dbd0fea2 100644 --- a/src/MinimalLambda.SourceGenerators/Extensions/ParameterSymbolExtensions.cs +++ b/src/MinimalLambda.SourceGenerators/Extensions/ParameterSymbolExtensions.cs @@ -12,38 +12,30 @@ internal static class ParameterSymbolExtensions internal static bool IsDecoratedWithAttribute( this IParameterSymbol parameterSymbol, GeneratorContext context, - params WellKnownType[] attributeType - ) => + params WellKnownType[] attributeType) => parameterSymbol .GetAttributes() - .Any(a => - a.AttributeClass is not null - && context.WellKnownTypes.IsType(a.AttributeClass, attributeType) - ); + .Any(a => a.AttributeClass is not null + && context.WellKnownTypes.IsType(a.AttributeClass, attributeType)); extension(IParameterSymbol parameterSymbol) { internal bool IsFromEvent(GeneratorContext context) => parameterSymbol .GetAttributes() - .Any(attribute => - attribute.AttributeClass is not null - && context.WellKnownTypes.IsType( - attribute.AttributeClass, - WellKnownType.MinimalLambda_Builder_EventAttribute, - WellKnownType.MinimalLambda_Builder_FromEventAttribute - ) - ); + .Any(attribute => attribute.AttributeClass is not null + && context.WellKnownTypes.IsType( + attribute.AttributeClass, + WellKnownType.MinimalLambda_Builder_EventAttribute, + WellKnownType.MinimalLambda_Builder_FromEventAttribute)); internal DiagnosticResult<(string Assignment, string? Key)> GetDiParameterAssignment( - GeneratorContext context - ) + GeneratorContext context) { var paramType = parameterSymbol.Type.QualifiedNullableName; - var isRequired = - parameterSymbol.IsOptional - || parameterSymbol.NullableAnnotation == NullableAnnotation.Annotated; + var isRequired = parameterSymbol.IsOptional + || parameterSymbol.NullableAnnotation == NullableAnnotation.Annotated; return parameterSymbol .IsFromKeyedService(context) @@ -53,29 +45,23 @@ GeneratorContext context isRequired ? $"context.ServiceProvider.GetKeyedService<{paramType}>({result.Key})" : $"context.ServiceProvider.GetRequiredKeyedService<{paramType}>({result.Key})", - result.Key - ) + result.Key) : ( isRequired ? $"context.ServiceProvider.GetService<{paramType}>()" : $"context.ServiceProvider.GetRequiredService<{paramType}>()", - null - ) - ); + null)); } private DiagnosticResult<(bool IsKeyed, string? Key)> IsFromKeyedService( - GeneratorContext context - ) => + GeneratorContext context) => parameterSymbol .GetAttributes() - .FirstOrDefault(attribute => - attribute is { AttributeClass: not null } - && context.WellKnownTypes.IsType( - attribute.AttributeClass, - WellKnownType.Microsoft_Extensions_DependencyInjection_FromKeyedServicesAttribute - ) - ) + .FirstOrDefault(attribute => attribute is { AttributeClass: not null } + && context.WellKnownTypes.IsType( + attribute.AttributeClass, + WellKnownType + .Microsoft_Extensions_DependencyInjection_FromKeyedServicesAttribute)) ?.ExtractKeyedServiceKey() .Bind<(bool, string?)>(key => (true, key)) ?? (false, null); @@ -104,13 +90,12 @@ private DiagnosticResult ExtractKeyedServiceKey() return DiagnosticResult.Failure( MinimalLambda.SourceGenerators.Diagnostics.InvalidAttributeArgument, attributeData.GetAttributeArgumentLocation(0), - argument.Type?.QualifiedNullableName - ); + argument.Type?.QualifiedNullableName); return argument.Kind switch { - TypedConstantKind.Primitive when value is string strValue => - CSharp.SymbolDisplay.FormatLiteral(strValue, true), + TypedConstantKind.Primitive when value is string strValue => CSharp.SymbolDisplay + .FormatLiteral(strValue, true), TypedConstantKind.Primitive when value is char charValue => $"'{charValue}'", @@ -129,8 +114,10 @@ private DiagnosticResult ExtractKeyedServiceKey() } private LocationInfo? GetAttributeArgumentLocation(int index) => - attributeData.ApplicationSyntaxReference?.GetSyntax() - is AttributeSyntax { ArgumentList: { } argumentList } + attributeData.ApplicationSyntaxReference?.GetSyntax() is AttributeSyntax + { + ArgumentList: { } argumentList, + } ? argumentList .Arguments.ElementAtOrDefault(index) ?.Expression.GetLocation() diff --git a/src/MinimalLambda.SourceGenerators/Extensions/SyntaxNodeExtensions.cs b/src/MinimalLambda.SourceGenerators/Extensions/SyntaxNodeExtensions.cs index 6107bfde..b611ee1e 100644 --- a/src/MinimalLambda.SourceGenerators/Extensions/SyntaxNodeExtensions.cs +++ b/src/MinimalLambda.SourceGenerators/Extensions/SyntaxNodeExtensions.cs @@ -11,15 +11,13 @@ internal static class SyntaxNodeExtensions internal bool TryGetMethodName([NotNullWhen(true)] out string? methodName) { methodName = null; - if ( - node is InvocationExpressionSyntax + if (node is InvocationExpressionSyntax { Expression: MemberAccessExpressionSyntax { Name.Identifier.ValueText: var method, }, - } - ) + }) { methodName = method; return true; diff --git a/src/MinimalLambda.SourceGenerators/Extensions/TypeSymbolExtensions.cs b/src/MinimalLambda.SourceGenerators/Extensions/TypeSymbolExtensions.cs index e8d810f9..fa113ff4 100644 --- a/src/MinimalLambda.SourceGenerators/Extensions/TypeSymbolExtensions.cs +++ b/src/MinimalLambda.SourceGenerators/Extensions/TypeSymbolExtensions.cs @@ -6,13 +6,11 @@ internal static class TypeSymbolExtensions { private static readonly SymbolDisplayFormat NullableFormat = SymbolDisplayFormat.FullyQualifiedFormat.AddMiscellaneousOptions( - SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier - ); + SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier); private static readonly SymbolDisplayFormat NotNullableFormat = SymbolDisplayFormat.FullyQualifiedFormat.AddMiscellaneousOptions( - SymbolDisplayMiscellaneousOptions.ExpandNullable - ); + SymbolDisplayMiscellaneousOptions.ExpandNullable); extension(ITypeSymbol typeSymbol) { diff --git a/src/MinimalLambda.SourceGenerators/GeneratorContext.cs b/src/MinimalLambda.SourceGenerators/GeneratorContext.cs index aee0b820..bed00271 100644 --- a/src/MinimalLambda.SourceGenerators/GeneratorContext.cs +++ b/src/MinimalLambda.SourceGenerators/GeneratorContext.cs @@ -15,9 +15,9 @@ internal GeneratorContext(GeneratorSyntaxContext context, CancellationToken canc Node = context.Node; SemanticModel = context.SemanticModel; CancellationToken = cancellationToken; - WellKnownTypes = SourceGenerators.WellKnownTypes.WellKnownTypes.GetOrCreate( - context.SemanticModel.Compilation - ); + WellKnownTypes = + SourceGenerators.WellKnownTypes.WellKnownTypes.GetOrCreate( + context.SemanticModel.Compilation); } } diff --git a/src/MinimalLambda.SourceGenerators/MinimalLambda.SourceGenerators.csproj b/src/MinimalLambda.SourceGenerators/MinimalLambda.SourceGenerators.csproj index 5e1d51be..ac94ac09 100644 --- a/src/MinimalLambda.SourceGenerators/MinimalLambda.SourceGenerators.csproj +++ b/src/MinimalLambda.SourceGenerators/MinimalLambda.SourceGenerators.csproj @@ -11,8 +11,8 @@ false - - + + @@ -23,18 +23,18 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - - - - + + + + - - + + - - + + diff --git a/src/MinimalLambda.SourceGenerators/MinimalLambdaGenerator.cs b/src/MinimalLambda.SourceGenerators/MinimalLambdaGenerator.cs index 77dd17c7..fafe3215 100644 --- a/src/MinimalLambda.SourceGenerators/MinimalLambdaGenerator.cs +++ b/src/MinimalLambda.SourceGenerators/MinimalLambdaGenerator.cs @@ -12,14 +12,11 @@ public class MinimalLambdaGenerator : IIncrementalGenerator public void Initialize(IncrementalGeneratorInitializationContext context) { // Language version gate - only generate source if C# 11 or later is used - var csharpSufficient = context.CompilationProvider.Select( - static (compilation, _) => - compilation - is CSharpCompilation - { - LanguageVersion: LanguageVersion.Default or >= LanguageVersion.CSharp11, - } - ); + var csharpSufficient = context.CompilationProvider.Select(static (compilation, _) => + compilation is CSharpCompilation + { + LanguageVersion: LanguageVersion.Default or >= LanguageVersion.CSharp11, + }); context.RegisterSourceOutput( csharpSufficient, @@ -27,25 +24,21 @@ is CSharpCompilation { if (!ok) spc.ReportDiagnostic( - Diagnostic.Create(Diagnostics.CSharpVersionTooLow, Location.None) - ); - } - ); + Diagnostic.Create(Diagnostics.CSharpVersionTooLow, Location.None)); + }); // handler registration calls var registrationCalls = context .SyntaxProvider.CreateSyntaxProvider( HandlerSyntaxProvider.Predicate, - HandlerSyntaxProvider.Transformer - ) + HandlerSyntaxProvider.Transformer) .WhereNotNull(); // find UseMiddleware() calls var useMiddlewareTCalls = context .SyntaxProvider.CreateSyntaxProvider( UseMiddlewareTSyntaxProvider.Predicate, - UseMiddlewareTSyntaxProvider.Transformer - ) + UseMiddlewareTSyntaxProvider.Transformer) .WhereNotNull(); var invocationHandlerCalls = registrationCalls @@ -70,13 +63,11 @@ is CSharpCompilation context.RegisterSourceOutput( registrationCalls, - (ctx, call) => call.DiagnosticInfos.ForEach(d => d.ReportDiagnostic(ctx)) - ); + (ctx, call) => call.DiagnosticInfos.ForEach(d => d.ReportDiagnostic(ctx))); context.RegisterSourceOutput( useMiddlewareTCalls, - (ctx, call) => call.DiagnosticInfos.ForEach(d => d.ReportDiagnostic(ctx)) - ); + (ctx, call) => call.DiagnosticInfos.ForEach(d => d.ReportDiagnostic(ctx))); context.RegisterSourceOutput(invocationHandlerCalls, InvocationHandlerEmitter.Emit); context.RegisterSourceOutput(onInitHandlerCalls, LifecycleHandlerEmitter.Emit); diff --git a/src/MinimalLambda.SourceGenerators/Models/Handlers/LifecycleHandlerParameterInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Handlers/LifecycleHandlerParameterInfo.cs index f37eeb1a..bafafd64 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Handlers/LifecycleHandlerParameterInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Handlers/LifecycleHandlerParameterInfo.cs @@ -9,8 +9,7 @@ internal record LifecycleHandlerParameterInfo( bool IsFromKeyedService, LocationInfo? LocationInfo, ParameterSource Source, - string? KeyedServicesKey -); + string? KeyedServicesKey); internal static class LifecycleHandlerParameterInfoExtensions { @@ -18,8 +17,7 @@ internal static class LifecycleHandlerParameterInfoExtensions { internal static DiagnosticResult Create( IParameterSymbol parameter, - GeneratorContext context - ) + GeneratorContext context) { var parameterInfo = new LifecycleHandlerParameterInfo( IsFromKeyedService: false, @@ -27,55 +25,42 @@ GeneratorContext context Assignment: string.Empty, InfoComment: string.Empty, KeyedServicesKey: string.Empty, - Source: ParameterSource.Services - ); + Source: ParameterSource.Services); // context - if ( - context.WellKnownTypes.IsType( + if (context.WellKnownTypes.IsType( parameter.Type, - WellKnownType.MinimalLambda_ILambdaLifecycleContext - ) - ) + WellKnownType.MinimalLambda_ILambdaLifecycleContext)) return DiagnosticResult.Success( parameterInfo with { - Assignment = "context", - Source = ParameterSource.Context, - } - ); + Assignment = "context", Source = ParameterSource.Context, + }); // cancellation token - if ( - context.WellKnownTypes.IsType( + if (context.WellKnownTypes.IsType( parameter.Type, - WellKnownType.System_Threading_CancellationToken - ) - ) + WellKnownType.System_Threading_CancellationToken)) return DiagnosticResult.Success( parameterInfo with { Assignment = "context.CancellationToken", Source = ParameterSource.CancellationToken, - } - ); + }); // default assignment from Di return parameter .GetDiParameterAssignment(context) - .Bind(diInfo => - DiagnosticResult.Success( - parameterInfo with - { - Assignment = diInfo.Assignment, - IsFromKeyedService = diInfo.Key is not null, - Source = diInfo.Key is not null - ? ParameterSource.KeyedServices - : ParameterSource.Services, - KeyedServicesKey = diInfo.Key, - } - ) - ); + .Bind(diInfo => DiagnosticResult.Success( + parameterInfo with + { + Assignment = diInfo.Assignment, + IsFromKeyedService = diInfo.Key is not null, + Source = diInfo.Key is not null + ? ParameterSource.KeyedServices + : ParameterSource.Services, + KeyedServicesKey = diInfo.Key, + })); } } } diff --git a/src/MinimalLambda.SourceGenerators/Models/Handlers/LifecycleMethodInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Handlers/LifecycleMethodInfo.cs index 7272973c..a1bb45dc 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Handlers/LifecycleMethodInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Handlers/LifecycleMethodInfo.cs @@ -18,8 +18,7 @@ internal record LifecycleMethodInfo( string HandleReturningFromMethod, string ReturnType, bool HasAnyFromKeyedServices, - string BuilderName -) : IMethodInfo; + string BuilderName) : IMethodInfo; internal static class LifecycleMethodInfoExtensions { @@ -27,31 +26,27 @@ internal static class LifecycleMethodInfoExtensions { internal static LifecycleMethodInfo CreateForInit( IMethodSymbol methodSymbol, - GeneratorContext context - ) + GeneratorContext context) { var handlerCastType = methodSymbol.GetCastableSignature(); if (!InterceptableLocationInfo.TryGet(context, out var interceptableLocation)) throw new InvalidOperationException("Unable to get interceptable location"); - var (assignments, diagnostics) = methodSymbol.Parameters.CollectDiagnosticResults( - parameter => LifecycleHandlerParameterInfo.Create(parameter, context) - ); + var (assignments, diagnostics) = + methodSymbol.Parameters.CollectDiagnosticResults(parameter => + LifecycleHandlerParameterInfo.Create(parameter, context)); var isAwaitable = methodSymbol.IsAwaitable(context); var hasResponse = methodSymbol.HasMeaningfulReturnType( context, - out var unwrappedReturnType - ); + out var unwrappedReturnType); - var unwrappedReturnIsBool = - hasResponse - && context.WellKnownTypes.IsType( - unwrappedReturnType!, - WellKnownTypeData.WellKnownType.System_Boolean - ); + var unwrappedReturnIsBool = hasResponse + && context.WellKnownTypes.IsType( + unwrappedReturnType!, + WellKnownTypeData.WellKnownType.System_Boolean); /* * Return rules: @@ -61,18 +56,18 @@ out var unwrappedReturnType * result default + async, return true default, return Task.FromResult(true); */ - var returnIsTaskBool = - methodSymbol.ReturnType is INamedTypeSymbol namedTypeSymbol - && context.WellKnownTypes.IsType( - namedTypeSymbol.ConstructedFrom, - WellKnownTypeData.WellKnownType.System_Threading_Tasks_Task_T - ) - && unwrappedReturnIsBool; + var returnIsTaskBool = methodSymbol.ReturnType is INamedTypeSymbol namedTypeSymbol + && context.WellKnownTypes.IsType( + namedTypeSymbol.ConstructedFrom, + WellKnownTypeData.WellKnownType + .System_Threading_Tasks_Task_T) + && unwrappedReturnIsBool; var shouldAwait = isAwaitable && !returnIsTaskBool; - var handleResponseAssignment = - hasResponse && unwrappedReturnIsBool ? "var response = " : string.Empty; + var handleResponseAssignment = hasResponse && unwrappedReturnIsBool + ? "var response = " + : string.Empty; var handleReturningFromMethod = hasResponse switch { @@ -96,30 +91,27 @@ methodSymbol.ReturnType is INamedTypeSymbol namedTypeSymbol HandleResponseAssignment: handleResponseAssignment, HandleReturningFromMethod: handleReturningFromMethod, ReturnType: "Task", - HasAnyFromKeyedServices: hasAnyKeyedServices - ); + HasAnyFromKeyedServices: hasAnyKeyedServices); } internal static LifecycleMethodInfo CreateForShutdown( IMethodSymbol methodSymbol, - GeneratorContext context - ) + GeneratorContext context) { var handlerCastType = methodSymbol.GetCastableSignature(); if (!InterceptableLocationInfo.TryGet(context, out var interceptableLocation)) throw new InvalidOperationException("Unable to get interceptable location"); - var (assignments, diagnostics) = methodSymbol.Parameters.CollectDiagnosticResults( - parameter => LifecycleHandlerParameterInfo.Create(parameter, context) - ); + var (assignments, diagnostics) = + methodSymbol.Parameters.CollectDiagnosticResults(parameter => + LifecycleHandlerParameterInfo.Create(parameter, context)); var isAwaitable = methodSymbol.IsAwaitable(context); var returnIsTask = context.WellKnownTypes.IsType( methodSymbol.ReturnType, - WellKnownTypeData.WellKnownType.System_Threading_Tasks_Task - ); + WellKnownTypeData.WellKnownType.System_Threading_Tasks_Task); var shouldAwait = isAwaitable && !returnIsTask; @@ -145,8 +137,7 @@ GeneratorContext context HandleResponseAssignment: handleResponseAssignment, HandleReturningFromMethod: handleReturningFromMethod, ReturnType: "Task", - HasAnyFromKeyedServices: hasAnyKeyedServices - ); + HasAnyFromKeyedServices: hasAnyKeyedServices); } } } diff --git a/src/MinimalLambda.SourceGenerators/Models/Handlers/MapHandlerMethodInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Handlers/MapHandlerMethodInfo.cs index 8f1d853a..91b4a443 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Handlers/MapHandlerMethodInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Handlers/MapHandlerMethodInfo.cs @@ -21,49 +21,41 @@ internal record MapHandlerMethodInfo( string? UnwrappedResponseType, bool HasAnyFromKeyedServices, EquatableArray DiagnosticInfos, - MethodType MethodType = MethodType.MapHandler -) : IMethodInfo; + MethodType MethodType = MethodType.MapHandler) : IMethodInfo; internal static class MapHandlerMethodInfoExtensions { private static IEnumerable ReportMultipleEvents( IEnumerable assignments, - GeneratorContext context - ) + GeneratorContext context) { var eventAttribute = new Lazy(() => - context - .WellKnownTypes.Get(WellKnownType.MinimalLambda_Builder_FromEventAttribute) - .QualifiedNullableName - ); + context.WellKnownTypes.Get(WellKnownType.MinimalLambda_Builder_FromEventAttribute) + .QualifiedNullableName); return assignments .Where(a => a.IsEvent) .Skip(1) - .Select(a => - DiagnosticInfo.Create( - Diagnostics.MultipleParametersUseAttribute, - a.LocationInfo, - [eventAttribute.Value] - ) - ); + .Select(a => DiagnosticInfo.Create( + Diagnostics.MultipleParametersUseAttribute, + a.LocationInfo, + [eventAttribute.Value])); } extension(MapHandlerMethodInfo) { internal static MapHandlerMethodInfo Create( IMethodSymbol methodSymbol, - GeneratorContext context - ) + GeneratorContext context) { var handlerCastType = methodSymbol.GetCastableSignature(); if (!InterceptableLocationInfo.TryGet(context, out var interceptableLocation)) throw new InvalidOperationException("Unable to get interceptable location"); - var (assignments, diagnostics) = methodSymbol.Parameters.CollectDiagnosticResults( - parameter => MapHandlerParameterInfo.Create(parameter, context) - ); + var (assignments, diagnostics) = + methodSymbol.Parameters.CollectDiagnosticResults(parameter => + MapHandlerParameterInfo.Create(parameter, context)); // add parameter diagnostics diagnostics.AddRange(ReportMultipleEvents(assignments, context)); @@ -72,15 +64,12 @@ GeneratorContext context var hasResponse = methodSymbol.HasMeaningfulReturnType( context, - out var unwrappedReturnType - ); + out var unwrappedReturnType); - var isReturnTypeStream = - hasResponse - && context.WellKnownTypes.IsType( - methodSymbol.ReturnType, - WellKnownType.System_IO_Stream - ); + var isReturnTypeStream = hasResponse + && context.WellKnownTypes.IsType( + methodSymbol.ReturnType, + WellKnownType.System_IO_Stream); var hasEvent = assignments.Any(a => a.IsEvent); @@ -106,8 +95,7 @@ out var unwrappedReturnType EventType: eventType, UnwrappedResponseType: unwrappedReturnType?.QualifiedNullableName, HasAnyFromKeyedServices: hasAnyKeyedServices, - DiagnosticInfos: diagnostics.ToEquatableArray() - ); + DiagnosticInfos: diagnostics.ToEquatableArray()); } } } diff --git a/src/MinimalLambda.SourceGenerators/Models/Handlers/MapHandlerParameterInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Handlers/MapHandlerParameterInfo.cs index 4942e399..1695de2f 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Handlers/MapHandlerParameterInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Handlers/MapHandlerParameterInfo.cs @@ -13,8 +13,7 @@ internal record MapHandlerParameterInfo( bool IsFromKeyedService, LocationInfo? LocationInfo, ParameterSource Source, - string? KeyedServicesKey -); + string? KeyedServicesKey); internal static class MapHandlerParameterInfoExtensions { @@ -22,8 +21,7 @@ internal static class MapHandlerParameterInfoExtensions { internal static DiagnosticResult Create( IParameterSymbol parameter, - GeneratorContext context - ) + GeneratorContext context) { var paramType = parameter.Type.QualifiedNullableName; @@ -36,8 +34,7 @@ GeneratorContext context Assignment: string.Empty, InfoComment: string.Empty, KeyedServicesKey: string.Empty, - Source: ParameterSource.Services - ); + Source: ParameterSource.Services); // event if (parameter.IsFromEvent(context)) @@ -51,56 +48,43 @@ parameterInfo with : $"context.GetRequiredEvent<{paramType}>()", IsEvent = true, Source = ParameterSource.Event, - } - ); + }); // context - if ( - context.WellKnownTypes.IsType( + if (context.WellKnownTypes.IsType( parameter.Type, WellKnownType.Amazon_Lambda_Core_ILambdaContext, - WellKnownType.MinimalLambda_ILambdaInvocationContext - ) - ) + WellKnownType.MinimalLambda_ILambdaInvocationContext)) return DiagnosticResult.Success( parameterInfo with { - Assignment = "context", - Source = ParameterSource.Context, - } - ); + Assignment = "context", Source = ParameterSource.Context, + }); // cancellation token - if ( - context.WellKnownTypes.IsType( + if (context.WellKnownTypes.IsType( parameter.Type, - WellKnownType.System_Threading_CancellationToken - ) - ) + WellKnownType.System_Threading_CancellationToken)) return DiagnosticResult.Success( parameterInfo with { Assignment = "context.CancellationToken", Source = ParameterSource.CancellationToken, - } - ); + }); // default assignment from Di return parameter .GetDiParameterAssignment(context) - .Bind(diInfo => - DiagnosticResult.Success( - parameterInfo with - { - Assignment = diInfo.Assignment, - IsFromKeyedService = diInfo.Key is not null, - Source = diInfo.Key is not null - ? ParameterSource.KeyedServices - : ParameterSource.Services, - KeyedServicesKey = diInfo.Key, - } - ) - ); + .Bind(diInfo => DiagnosticResult.Success( + parameterInfo with + { + Assignment = diInfo.Assignment, + IsFromKeyedService = diInfo.Key is not null, + Source = diInfo.Key is not null + ? ParameterSource.KeyedServices + : ParameterSource.Services, + KeyedServicesKey = diInfo.Key, + })); } } } diff --git a/src/MinimalLambda.SourceGenerators/Models/Middleware/MiddlewareClassInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Middleware/MiddlewareClassInfo.cs index 9c03be0c..12f029e3 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Middleware/MiddlewareClassInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Middleware/MiddlewareClassInfo.cs @@ -14,8 +14,7 @@ internal record MiddlewareClassInfo( EquatableArray ParameterInfos, bool ImplementsDisposable, bool ImplementsAsyncDisposable, - bool AllParametersFromServices -); + bool AllParametersFromServices); internal static class MiddlewareExtensions { @@ -27,21 +26,17 @@ internal static class MiddlewareExtensions internal static (MiddlewareClassInfo? Info, List Diagnostics) Create( INamedTypeSymbol typeSymbol, Location? location, - GeneratorContext context - ) + GeneratorContext context) { // validate that middleware class is a concrete -> not interface or abstract class if (typeSymbol.TypeKind == TypeKind.Interface || typeSymbol.IsAbstract) - return ( - null, - [ - DiagnosticInfo.Create( - Diagnostics.MustBeConcreteType, - location?.ToLocationInfo(), - [typeSymbol.QualifiedName] - ), - ] - ); + return (null, + [ + DiagnosticInfo.Create( + Diagnostics.MustBeConcreteType, + location?.ToLocationInfo(), + [typeSymbol.QualifiedName]), + ]); List diagnostics = []; @@ -63,8 +58,7 @@ GeneratorContext context var parameterInfos = constructor is not null ? constructor .Parameters.CollectDiagnosticResults(parameter => - MiddlewareParameterInfo.Create(parameter, context) - ) + MiddlewareParameterInfo.Create(parameter, context)) .Map(results => { diagnostics.AddRange(results.Diagnostics); @@ -74,13 +68,11 @@ GeneratorContext context // implements IDisposable var implementsIDisposable = typeSymbol.AllInterfaces.Any(i => - context.WellKnownTypes.IsType(i, WellKnownType.System_IDisposable) - ); + context.WellKnownTypes.IsType(i, WellKnownType.System_IDisposable)); // implements IAsyncDisposable var implementsIAsyncDisposable = typeSymbol.AllInterfaces.Any(i => - context.WellKnownTypes.IsType(i, WellKnownType.System_IAsyncDisposable) - ); + context.WellKnownTypes.IsType(i, WellKnownType.System_IAsyncDisposable)); // are all parameters for the constructor from services var allParametersFromServices = parameterInfos.All(p => p.FromServices); @@ -92,48 +84,37 @@ GeneratorContext context parameterInfos.ToEquatableArray(), implementsIDisposable, implementsIAsyncDisposable, - allParametersFromServices - ), - diagnostics - ); + allParametersFromServices), diagnostics); } } private static (IMethodSymbol? MethodSymbol, DiagnosticInfo[] DiagnosticInfos) GetConstructor( INamedTypeSymbol namedTypeSymbol, - GeneratorContext context - ) + GeneratorContext context) { // 1. Get constructors annotated with `[MiddlewareConstructor]` var constructors = namedTypeSymbol .InstanceConstructors.Where(c => - c.GetAttributes() - .Any(a => - a.AttributeClass is not null - && context.WellKnownTypes.IsType( - a.AttributeClass, - WellKnownType.MinimalLambda_Builder_MiddlewareConstructorAttribute - ) - ) - ) + c + .GetAttributes() + .Any(a => a.AttributeClass is not null + && context.WellKnownTypes.IsType( + a.AttributeClass, + WellKnownType + .MinimalLambda_Builder_MiddlewareConstructorAttribute))) .ToArray(); return constructors.Length switch { // if more than one found, we will return diagnostics - > 1 => ( - MethodSymbol: null, + > 1 => (MethodSymbol: null, DiagnosticInfos: constructors .Skip(1) - .Select(c => - DiagnosticInfo.Create( - Diagnostics.MultipleConstructorsWithAttribute, - c.Locations.FirstOrDefault()?.ToLocationInfo(), - [MiddlewareConstructor] - ) - ) - .ToArray() - ), + .Select(c => DiagnosticInfo.Create( + Diagnostics.MultipleConstructorsWithAttribute, + c.Locations.FirstOrDefault()?.ToLocationInfo(), + [MiddlewareConstructor])) + .ToArray()), // return single constructor that has an `[MiddlewareConstructor]` attribute 1 => (MethodSymbol: constructors.FirstOrDefault(), DiagnosticInfos: []), @@ -142,9 +123,7 @@ a.AttributeClass is not null _ => ( MethodSymbol: namedTypeSymbol .InstanceConstructors.OrderByDescending(c => c.Parameters.Length) - .First(), - DiagnosticInfos: [] - ), + .First(), DiagnosticInfos: []), }; } } diff --git a/src/MinimalLambda.SourceGenerators/Models/Middleware/MiddlewareParameterInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Middleware/MiddlewareParameterInfo.cs index 3ad20474..3abe534d 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Middleware/MiddlewareParameterInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Middleware/MiddlewareParameterInfo.cs @@ -13,8 +13,7 @@ internal record MiddlewareParameterInfo( string FromServicesAssignment, string InfoComment, ParameterSource ServiceSource, - string? KeyedServicesKey -); + string? KeyedServicesKey); internal static class MiddlewareParameterInfoExtensions { @@ -22,8 +21,7 @@ internal static class MiddlewareParameterInfoExtensions { internal static DiagnosticResult Create( IParameterSymbol parameterSymbol, - GeneratorContext context - ) + GeneratorContext context) { context.ThrowIfCancellationRequested(); @@ -39,38 +37,32 @@ GeneratorContext context // determine if it has a `[FromArguments]` attribute var fromArguments = parameterSymbol.IsDecoratedWithAttribute( context, - WellKnownType.MinimalLambda_Builder_FromArgumentsAttribute - ); + WellKnownType.MinimalLambda_Builder_FromArgumentsAttribute); // determine if it has a `[FromServices]` attribute - var fromServices = - !fromArguments - && parameterSymbol.IsDecoratedWithAttribute( - context, - WellKnownType.MinimalLambda_Builder_FromServicesAttribute, - WellKnownType.Microsoft_Extensions_DependencyInjection_FromKeyedServicesAttribute - ); + var fromServices = !fromArguments + && parameterSymbol.IsDecoratedWithAttribute( + context, + WellKnownType.MinimalLambda_Builder_FromServicesAttribute, + WellKnownType + .Microsoft_Extensions_DependencyInjection_FromKeyedServicesAttribute); // assignment from services return parameterSymbol .GetDiParameterAssignment(context) - .Bind(diInfo => - DiagnosticResult.Success( - new MiddlewareParameterInfo( - InfoComment: "", - Name: name, - GloballyQualifiedType: globallyQualifiedType, - GloballyQualifiedNotNullableType: globallyQualifiedNotNullableType, - FromArguments: fromArguments, - FromServices: fromServices, - FromServicesAssignment: diInfo.Assignment, - ServiceSource: diInfo.Key is not null - ? ParameterSource.KeyedServices - : ParameterSource.Services, - KeyedServicesKey: diInfo.Key - ) - ) - ); + .Bind(diInfo => DiagnosticResult.Success( + new MiddlewareParameterInfo( + InfoComment: "", + Name: name, + GloballyQualifiedType: globallyQualifiedType, + GloballyQualifiedNotNullableType: globallyQualifiedNotNullableType, + FromArguments: fromArguments, + FromServices: fromServices, + FromServicesAssignment: diInfo.Assignment, + ServiceSource: diInfo.Key is not null + ? ParameterSource.KeyedServices + : ParameterSource.Services, + KeyedServicesKey: diInfo.Key))); } } } diff --git a/src/MinimalLambda.SourceGenerators/Models/Middleware/UseMiddlewareTInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Middleware/UseMiddlewareTInfo.cs index 8531bdfe..0955f566 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Middleware/UseMiddlewareTInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Middleware/UseMiddlewareTInfo.cs @@ -13,8 +13,7 @@ internal record UseMiddlewareTInfo( string? InterceptableLocationAttribute, MiddlewareClassInfo? ClassInfo, EquatableArray DiagnosticInfos, - MethodType MethodType -) : IMethodInfo; + MethodType MethodType) : IMethodInfo; internal static class UseMiddlewareTInfoExtensions { @@ -22,37 +21,28 @@ internal static class UseMiddlewareTInfoExtensions { internal static UseMiddlewareTInfo Create( IInvocationOperation invocationOperation, - GeneratorContext context - ) + GeneratorContext context) { - if ( - invocationOperation.Syntax - is not InvocationExpressionSyntax invocationExpressionSyntax - ) + if (invocationOperation.Syntax is not InvocationExpressionSyntax + invocationExpressionSyntax) throw new InvalidOperationException("Syntax is not InvocationExpressionSyntax"); List diagnosticInfos = []; - var interceptableLocation = ( - context.SemanticModel.GetInterceptableLocation( - invocationExpressionSyntax, - context.CancellationToken - ) - ?? throw new InvalidOperationException( - "Interceptable location is null (Should not happen)" - ) - ) + var interceptableLocation = + (context.SemanticModel.GetInterceptableLocation( + invocationExpressionSyntax, + context.CancellationToken) + ?? throw new InvalidOperationException( + "Interceptable location is null (Should not happen)")) .ToInterceptableLocationInfo() .Attribute; var middlewareClassType = invocationOperation .TargetMethod.TypeArguments.FirstOrDefault() - .Map(typeSymbol => - typeSymbol as INamedTypeSymbol - ?? throw new InvalidOperationException( - "Middleware class type is not INamedTypeSymbol (Should not happen)" - ) - ); + .Map(typeSymbol => typeSymbol as INamedTypeSymbol + ?? throw new InvalidOperationException( + "Middleware class type is not INamedTypeSymbol (Should not happen)")); TryGetLocationInfo(invocationExpressionSyntax, out var typeArgumentLocation); @@ -68,21 +58,19 @@ typeSymbol as INamedTypeSymbol interceptableLocation, classInfo, diagnosticInfos.ToEquatableArray(), - MethodType.UseMiddlewareT - ); + MethodType.UseMiddlewareT); } } private static bool TryGetLocationInfo( InvocationExpressionSyntax invocationExpressionSyntax, - out Location? locationInfo - ) + out Location? locationInfo) { locationInfo = null; - if ( - invocationExpressionSyntax is - { Expression: MemberAccessExpressionSyntax { Name: GenericNameSyntax genericName } } - ) + if (invocationExpressionSyntax is + { + Expression: MemberAccessExpressionSyntax { Name: GenericNameSyntax genericName }, + }) { var typeArgument = genericName.TypeArgumentList.Arguments[0]; locationInfo = typeArgument.GetLocation(); diff --git a/src/MinimalLambda.SourceGenerators/Models/Shared/CompilationInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Shared/CompilationInfo.cs index d8d6ed1a..8659da96 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Shared/CompilationInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Shared/CompilationInfo.cs @@ -6,5 +6,4 @@ internal sealed record CompilationInfo( EquatableArray MapHandlerInvocationInfos, EquatableArray OnShutdownInvocationInfos, EquatableArray OnInitInvocationInfos, - EquatableArray UseMiddlewareTInfos -); + EquatableArray UseMiddlewareTInfos); diff --git a/src/MinimalLambda.SourceGenerators/Models/Shared/InterceptableLocationInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Shared/InterceptableLocationInfo.cs index 3550eae6..062128f9 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Shared/InterceptableLocationInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Shared/InterceptableLocationInfo.cs @@ -11,18 +11,15 @@ internal static class InterceptableLocationInfoExtensions extension(InterceptableLocationInfo location) { internal static InterceptableLocationInfo CreateFrom( - InterceptableLocation interceptableLocation - ) => + InterceptableLocation interceptableLocation) => new( interceptableLocation.Version, interceptableLocation.Data, - interceptableLocation.GetDisplayLocation() - ); + interceptableLocation.GetDisplayLocation()); internal static bool TryGet( GeneratorContext context, - [NotNullWhen(true)] out InterceptableLocationInfo? interceptableLocationInfo - ) + [NotNullWhen(true)] out InterceptableLocationInfo? interceptableLocationInfo) { interceptableLocationInfo = null; @@ -31,8 +28,7 @@ internal static bool TryGet( var interceptableLocation = context.SemanticModel.GetInterceptableLocation( invocationExpr, - context.CancellationToken - ); + context.CancellationToken); if (interceptableLocation is null) return false; diff --git a/src/MinimalLambda.SourceGenerators/Models/Shared/LocationInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Shared/LocationInfo.cs index 4949383f..dd19fd12 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Shared/LocationInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Shared/LocationInfo.cs @@ -7,8 +7,7 @@ namespace MinimalLambda.SourceGenerators.Models; internal readonly record struct LocationInfo( string FilePath, TextSpan TextSpan, - LinePositionSpan LineSpan -); + LinePositionSpan LineSpan); internal static class LocationInfoExtensions { @@ -23,8 +22,7 @@ internal Location ToLocation() => : new LocationInfo( location.SourceTree.FilePath, location.SourceSpan, - location.GetLineSpan().Span - ); + location.GetLineSpan().Span); internal static LocationInfo? Create(ISymbol symbol) => LocationInfo.Create(symbol.Locations.FirstOrDefault()); @@ -41,8 +39,7 @@ location.SourceTree is null : new LocationInfo( location.SourceTree.FilePath, location.SourceSpan, - location.GetLineSpan().Span - ); + location.GetLineSpan().Span); } extension(ISymbol symbol) diff --git a/src/MinimalLambda.SourceGenerators/SyntaxProviders/HandlerSyntaxProvider.cs b/src/MinimalLambda.SourceGenerators/SyntaxProviders/HandlerSyntaxProvider.cs index d1594d38..083c50f2 100644 --- a/src/MinimalLambda.SourceGenerators/SyntaxProviders/HandlerSyntaxProvider.cs +++ b/src/MinimalLambda.SourceGenerators/SyntaxProviders/HandlerSyntaxProvider.cs @@ -29,8 +29,7 @@ internal static bool Predicate(SyntaxNode node, CancellationToken _) => internal static IMethodInfo? Transformer( GeneratorSyntaxContext syntaxContext, - CancellationToken cancellationToken - ) + CancellationToken cancellationToken) { var context = new GeneratorContext(syntaxContext, cancellationToken); @@ -51,32 +50,29 @@ CancellationToken cancellationToken private static bool TryGetInvocationOperation( GeneratorContext context, - [NotNullWhen(true)] out IInvocationOperation? invocationOperation - ) + [NotNullWhen(true)] out IInvocationOperation? invocationOperation) { invocationOperation = null; var operation = context.SemanticModel.GetOperation(context.Node, context.CancellationToken); - if ( - operation - is IInvocationOperation + if (operation is IInvocationOperation + { + TargetMethod.ContainingNamespace: { - TargetMethod.ContainingNamespace: + Name: "Builder", + ContainingNamespace : { - Name: "Builder", - ContainingNamespace: - { Name: "MinimalLambda", ContainingNamespace.IsGlobalNamespace: true }, + Name: "MinimalLambda", ContainingNamespace.IsGlobalNamespace: true, }, - } targetOperation + }, + } targetOperation && targetOperation.TargetMethod.ContainingAssembly.Name == "MinimalLambda" && targetOperation.TryGetRouteHandlerArgument(out var routeHandlerParameter) && routeHandlerParameter is { Parameter.Type: { } delegateType } && SymbolEqualityComparer.Default.Equals( delegateType, - context.WellKnownTypes.Get(WellKnownType.System_Delegate) - ) - ) + context.WellKnownTypes.Get(WellKnownType.System_Delegate))) { invocationOperation = targetOperation; return true; @@ -88,8 +84,7 @@ is IInvocationOperation private static bool TryGetHandlerMethod( this IInvocationOperation invocation, SemanticModel semanticModel, - [NotNullWhen(true)] out IMethodSymbol? method - ) + [NotNullWhen(true)] out IMethodSymbol? method) { method = null; if (invocation.TryGetRouteHandlerArgument(out var argument)) @@ -103,33 +98,29 @@ private static bool TryGetHandlerMethod( private static IMethodSymbol? ResolveMethodFromOperation( IOperation operation, - SemanticModel semanticModel - ) => + SemanticModel semanticModel) => operation switch { IArgumentOperation argument => ResolveMethodFromOperation( argument.Value, - semanticModel - ), + semanticModel), IConversionOperation conv => ResolveMethodFromOperation(conv.Operand, semanticModel), IDelegateCreationOperation del => ResolveMethodFromOperation(del.Target, semanticModel), - IFieldReferenceOperation { Field.IsReadOnly: true } f - when ResolveDeclarationOperation(f.Field, semanticModel) is { } op => - ResolveMethodFromOperation(op, semanticModel), + IFieldReferenceOperation { Field.IsReadOnly: true } f when ResolveDeclarationOperation( + f.Field, + semanticModel) is { } op => ResolveMethodFromOperation(op, semanticModel), IAnonymousFunctionOperation anon => anon.Symbol, ILocalFunctionOperation local => local.Symbol, IMethodReferenceOperation method => method.Method, IParenthesizedOperation parenthesized => ResolveMethodFromOperation( parenthesized.Operand, - semanticModel - ), + semanticModel), _ => null, }; private static bool TryGetRouteHandlerArgument( this IInvocationOperation invocation, - [NotNullWhen(true)] out IArgumentOperation? argumentOperation - ) + [NotNullWhen(true)] out IArgumentOperation? argumentOperation) { argumentOperation = null; var routeHandlerArgumentOrdinal = invocation.Arguments.Length - 1; @@ -146,8 +137,7 @@ private static bool TryGetRouteHandlerArgument( private static IOperation? ResolveDeclarationOperation( ISymbol symbol, - SemanticModel? semanticModel - ) => + SemanticModel? semanticModel) => symbol .DeclaringSyntaxReferences.Select(syntaxReference => syntaxReference.GetSyntax()) .OfType() @@ -155,9 +145,8 @@ private static bool TryGetRouteHandlerArgument( .Select(syn => { var expr = syn.Initializer!.Value; - var targetSemanticModel = semanticModel?.Compilation.GetSemanticModel( - expr.SyntaxTree - ); + var targetSemanticModel = + semanticModel?.Compilation.GetSemanticModel(expr.SyntaxTree); return targetSemanticModel?.GetOperation(expr); }) .FirstOrDefault(operation => operation is not null); diff --git a/src/MinimalLambda.SourceGenerators/SyntaxProviders/UseMiddlewareTSyntaxProvider.cs b/src/MinimalLambda.SourceGenerators/SyntaxProviders/UseMiddlewareTSyntaxProvider.cs index 52281d89..6db273c8 100644 --- a/src/MinimalLambda.SourceGenerators/SyntaxProviders/UseMiddlewareTSyntaxProvider.cs +++ b/src/MinimalLambda.SourceGenerators/SyntaxProviders/UseMiddlewareTSyntaxProvider.cs @@ -17,8 +17,7 @@ internal static bool Predicate(SyntaxNode node, CancellationToken _) => internal static UseMiddlewareTInfo? Transformer( GeneratorSyntaxContext syntaxContext, - CancellationToken cancellationToken - ) + CancellationToken cancellationToken) { var context = new GeneratorContext(syntaxContext, cancellationToken); @@ -29,35 +28,32 @@ CancellationToken cancellationToken private static bool TryGetInvocationOperation( GeneratorContext context, - [NotNullWhen(true)] out IInvocationOperation? invocationOperation - ) + [NotNullWhen(true)] out IInvocationOperation? invocationOperation) { invocationOperation = null; var operation = context.SemanticModel.GetOperation(context.Node, context.CancellationToken); - if ( - operation - is IInvocationOperation + if (operation is IInvocationOperation + { + TargetMethod: { - TargetMethod: + IsGenericMethod: true, + ContainingAssembly.Name: "MinimalLambda", + ContainingNamespace: { - IsGenericMethod: true, - ContainingAssembly.Name: "MinimalLambda", + Name: "Builder", ContainingNamespace: { - Name: "Builder", - ContainingNamespace: - { Name: "MinimalLambda", ContainingNamespace.IsGlobalNamespace: true }, + Name: "MinimalLambda", ContainingNamespace.IsGlobalNamespace: true, }, }, - } targetOperation - && targetOperation.TargetMethod.ConstructedFrom.TypeParameters.FirstOrDefault() - is { } typeParameter + }, + } targetOperation + && targetOperation.TargetMethod.ConstructedFrom.TypeParameters.FirstOrDefault() is + { } typeParameter && typeParameter.ConstraintTypes.Any(c => - context.WellKnownTypes.IsType(c, WellKnownType.MinimalLambda_ILambdaMiddleware) - ) - ) + context.WellKnownTypes.IsType(c, WellKnownType.MinimalLambda_ILambdaMiddleware))) { invocationOperation = targetOperation; return true; diff --git a/src/MinimalLambda.SourceGenerators/WellKnownTypes/BoundedCacheWithFactory.cs b/src/MinimalLambda.SourceGenerators/WellKnownTypes/BoundedCacheWithFactory.cs index b41c0a0d..d234a518 100644 --- a/src/MinimalLambda.SourceGenerators/WellKnownTypes/BoundedCacheWithFactory.cs +++ b/src/MinimalLambda.SourceGenerators/WellKnownTypes/BoundedCacheWithFactory.cs @@ -19,8 +19,7 @@ namespace MinimalLambda.SourceGenerators.WellKnownTypes; /// when the /// cached value has a cyclic reference to the key preventing early garbage collection of entries. /// -internal class BoundedCacheWithFactory - where TKey : class +internal class BoundedCacheWithFactory where TKey : class { // Bounded weak reference cache. // Size 5 is an arbitrarily chosen bound, which can be tuned in future as required. diff --git a/src/MinimalLambda.SourceGenerators/WellKnownTypes/WellKnownTypes.cs b/src/MinimalLambda.SourceGenerators/WellKnownTypes/WellKnownTypes.cs index bdda23b7..960a06d7 100644 --- a/src/MinimalLambda.SourceGenerators/WellKnownTypes/WellKnownTypes.cs +++ b/src/MinimalLambda.SourceGenerators/WellKnownTypes/WellKnownTypes.cs @@ -16,10 +16,8 @@ namespace MinimalLambda.SourceGenerators.WellKnownTypes; internal class WellKnownTypes { - private static readonly BoundedCacheWithFactory< - Compilation, - WellKnownTypes - > LazyWellKnownTypesCache = new(); + private static readonly BoundedCacheWithFactory + LazyWellKnownTypesCache = new(); public static WellKnownTypes GetOrCreate(Compilation compilation) => LazyWellKnownTypesCache.GetOrCreateValue(compilation, static c => new WellKnownTypes(c)); @@ -49,8 +47,7 @@ private static void AssertEnumAndTableInSync() Debug.Assert( name == typeIdName, - $"Enum name ({typeIdName}) and type name ({name}) must match at {i}" - ); + $"Enum name ({typeIdName}) and type name ({name}) must match at {i}"); } } @@ -77,12 +74,10 @@ public INamedTypeSymbol Get(WellKnownTypeData.WellKnownType type) private INamedTypeSymbol GetAndCache(int index) { var result = GetTypeByMetadataNameInTargetAssembly( - WellKnownTypeData.WellKnownTypeNames[index] - ); + WellKnownTypeData.WellKnownTypeNames[index]); if (result == null) throw new InvalidOperationException( - $"Failed to resolve well-known type '{WellKnownTypeData.WellKnownTypeNames[index]}'." - ); + $"Failed to resolve well-known type '{WellKnownTypeData.WellKnownTypeNames[index]}'."); Interlocked.CompareExchange(ref _lazyWellKnownTypes[index], result, null); @@ -105,16 +100,12 @@ private INamedTypeSymbol GetAndCache(int index) // namespace + type name in their apps or libraries. // Workaround this situation by prioritizing types in System and Microsoft assemblies. foreach (var type in types) - if ( - type.ContainingAssembly.Identity.Name.StartsWith( + if (type.ContainingAssembly.Identity.Name.StartsWith( "System.", - StringComparison.Ordinal - ) + StringComparison.Ordinal) || type.ContainingAssembly.Identity.Name.StartsWith( "Microsoft.", - StringComparison.Ordinal - ) - ) + StringComparison.Ordinal)) return type; return null; @@ -126,8 +117,7 @@ public bool IsType(ITypeSymbol type, params WellKnownTypeData.WellKnownType[] we public bool IsType( ITypeSymbol type, WellKnownTypeData.WellKnownType[] wellKnownTypes, - [NotNullWhen(true)] out WellKnownTypeData.WellKnownType? match - ) + [NotNullWhen(true)] out WellKnownTypeData.WellKnownType? match) { foreach (var wellKnownType in wellKnownTypes) if (SymbolEqualityComparer.Default.Equals(type, Get(wellKnownType))) @@ -142,8 +132,7 @@ public bool IsType( public bool Implements( ITypeSymbol type, - WellKnownTypeData.WellKnownType[] interfaceWellKnownTypes - ) + WellKnownTypeData.WellKnownType[] interfaceWellKnownTypes) { foreach (var wellKnownType in interfaceWellKnownTypes) if (Implements(type, Get(wellKnownType))) diff --git a/src/MinimalLambda.Testing/DeferredHostBuilder.cs b/src/MinimalLambda.Testing/DeferredHostBuilder.cs index 66228a8b..6b175b66 100644 --- a/src/MinimalLambda.Testing/DeferredHostBuilder.cs +++ b/src/MinimalLambda.Testing/DeferredHostBuilder.cs @@ -16,9 +16,8 @@ namespace MinimalLambda.Testing; // ConfigureHostBuilder internal sealed class DeferredHostBuilder : IHostBuilder { - private readonly TaskCompletionSource _entryPointCompletionTcs = new( - TaskCreationOptions.RunContinuationsAsynchronously - ); + private readonly TaskCompletionSource _entryPointCompletionTcs = + new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly ConfigurationManager _hostConfiguration = new(); @@ -26,8 +25,7 @@ internal sealed class DeferredHostBuilder : IHostBuilder // application // exits due to an exception or because it didn't wait for the shutdown signal private readonly TaskCompletionSource _hostStartTcs = new( - TaskCreationOptions.RunContinuationsAsynchronously - ); + TaskCreationOptions.RunContinuationsAsynchronously); private Action _configure; private Func? _hostFactory; @@ -65,16 +63,14 @@ public IHost Build() } public IHostBuilder ConfigureAppConfiguration( - Action configureDelegate - ) + Action configureDelegate) { _configure += b => b.ConfigureAppConfiguration(configureDelegate); return this; } public IHostBuilder ConfigureContainer( - Action configureDelegate - ) + Action configureDelegate) { _configure += b => b.ConfigureContainer(configureDelegate); return this; @@ -90,25 +86,21 @@ public IHostBuilder ConfigureHostConfiguration(Action con } public IHostBuilder ConfigureServices( - Action configureDelegate - ) + Action configureDelegate) { _configure += b => b.ConfigureServices(configureDelegate); return this; } public IHostBuilder UseServiceProviderFactory( - IServiceProviderFactory factory - ) - where TContainerBuilder : notnull + IServiceProviderFactory factory) where TContainerBuilder : notnull { _configure += b => b.UseServiceProviderFactory(factory); return this; } public IHostBuilder UseServiceProviderFactory( - Func> factory - ) + Func> factory) where TContainerBuilder : notnull { _configure += b => b.UseServiceProviderFactory(factory); @@ -134,8 +126,7 @@ public void EntryPointCompleted(Exception? exception) private sealed class DeferredHost( IHost host, TaskCompletionSource hostStartedTcs, - IHostApplicationLifetime applicationLifetime - ) : IHost, IAsyncDisposable + IHostApplicationLifetime applicationLifetime) : IHost, IAsyncDisposable { public async ValueTask DisposeAsync() { @@ -160,16 +151,14 @@ public async Task StartAsync(CancellationToken cancellationToken = default) await using var reg = cancellationToken.UnsafeRegister( _ => hostStartedTcs.TrySetCanceled(), - null - ); + null); // Wait on the existing host to start running and have this call wait on that. This // avoids starting the actual host too early and // leaves the application in charge of calling start. await using var reg2 = applicationLifetime.ApplicationStarted.UnsafeRegister( _ => hostStartedTcs.TrySetResult(), - null - ); + null); await hostStartedTcs.Task.ConfigureAwait(false); } diff --git a/src/MinimalLambda.Testing/LambdaApplicationFactory.cs b/src/MinimalLambda.Testing/LambdaApplicationFactory.cs index e2c5bbfc..ad5e64e2 100644 --- a/src/MinimalLambda.Testing/LambdaApplicationFactory.cs +++ b/src/MinimalLambda.Testing/LambdaApplicationFactory.cs @@ -148,8 +148,7 @@ public void Dispose() /// creation. /// public LambdaApplicationFactory WithCancellationToken( - CancellationToken cancellationToken - ) + CancellationToken cancellationToken) { _stoppingToken = cancellationToken; return this; @@ -168,8 +167,8 @@ CancellationToken cancellationToken /// /// A new . public LambdaApplicationFactory WithHostBuilder( - Action configuration - ) => WithHostBuilderCore(configuration); + Action configuration) => + WithHostBuilderCore(configuration); /// /// Core implementation of that creates a derived factory with @@ -193,8 +192,7 @@ Action configuration /// factory creation behavior. /// protected virtual LambdaApplicationFactory WithHostBuilderCore( - Action configuration - ) + Action configuration) { var factory = new DelegatedLambdaApplicationFactory( ServerOptions, @@ -204,8 +202,7 @@ Action configuration { _configuration(builder); configuration(builder); - } - ); + }); _derivedFactories.Add(factory); @@ -234,8 +231,7 @@ private void EnsureServer() HostDefaults.ApplicationKey, typeof(TEntryPoint).Assembly.GetName().Name ?? string.Empty }, - } - ); + }); }); // This helper call does the hard work to determine if we can fallback to diagnostic // source events to get the host instance @@ -243,8 +239,7 @@ private void EnsureServer() typeof(TEntryPoint).Assembly, stopApplication: false, configureHostBuilder: deferredHostBuilder.ConfigureHostBuilder, - entrypointCompleted: deferredHostBuilder.EntryPointCompleted - ); + entrypointCompleted: deferredHostBuilder.EntryPointCompleted); if (factory is not null) { @@ -264,8 +259,7 @@ private void EnsureServer() [MemberNotNull(nameof(_server))] private void ConfigureHostBuilder( IHostBuilder hostBuilder, - Task entryPointCompletion - ) + Task entryPointCompletion) { SetContentRoot(hostBuilder); _configuration(hostBuilder); @@ -273,8 +267,7 @@ private void ConfigureHostBuilder( _server = new LambdaTestServer( entryPointCompletion, ServerOptions, - _stoppingToken ?? CancellationToken.None - ); + _stoppingToken ?? CancellationToken.None); // set Lambda Bootstrap Http Client hostBuilder.ConfigureServices(services => @@ -312,8 +305,7 @@ private void SetContentRoot(IHostBuilder builder) private static void UseSolutionRelativeContentRoot( IHostBuilder builder, - string solutionRelativePath - ) + string solutionRelativePath) { ArgumentNullException.ThrowIfNull(solutionRelativePath); @@ -331,8 +323,8 @@ string solutionRelativePath if (solutionPath != null) { builder.UseContentRoot( - Path.GetFullPath(Path.Combine(directoryInfo.FullName, solutionRelativePath)) - ); + Path.GetFullPath( + Path.Combine(directoryInfo.FullName, solutionRelativePath))); return; } } @@ -341,29 +333,25 @@ string solutionRelativePath } while (directoryInfo is not null); throw new InvalidOperationException( - $"Solution root could not be located using application root {applicationBasePath}." - ); + $"Solution root could not be located using application root {applicationBasePath}."); } private string? GetContentRootFromAssembly() { var metadataAttributes = GetContentRootMetadataAttributes( typeof(TEntryPoint).Assembly.FullName!, - typeof(TEntryPoint).Assembly.GetName().Name! - ); + typeof(TEntryPoint).Assembly.GetName().Name!); string? contentRoot = null; foreach (var contentRootAttribute in metadataAttributes) { var contentRootCandidate = Path.Combine( AppContext.BaseDirectory, - contentRootAttribute.ContentRootPath - ); + contentRootAttribute.ContentRootPath); var contentRootMarker = Path.Combine( contentRootCandidate, - Path.GetFileName(contentRootAttribute.ContentRootTest) - ); + Path.GetFileName(contentRootAttribute.ContentRootTest)); if (File.Exists(contentRootMarker)) { @@ -377,8 +365,7 @@ string solutionRelativePath private LambdaApplicationFactoryContentRootAttribute[] GetContentRootMetadataAttributes( string tEntryPointAssemblyFullName, - string tEntryPointAssemblyName - ) + string tEntryPointAssemblyName) { var testAssembly = GetTestAssemblies(); var metadataAttributes = testAssembly @@ -387,10 +374,11 @@ string tEntryPointAssemblyName string.Equals( a.Key, tEntryPointAssemblyFullName, - StringComparison.OrdinalIgnoreCase - ) - || string.Equals(a.Key, tEntryPointAssemblyName, StringComparison.OrdinalIgnoreCase) - ) + StringComparison.OrdinalIgnoreCase) + || string.Equals( + a.Key, + tEntryPointAssemblyName, + StringComparison.OrdinalIgnoreCase)) .OrderBy(a => a.Priority) .ToArray(); @@ -416,8 +404,7 @@ protected virtual IEnumerable GetTestAssemblies() var runtimeProjectLibraries = context.RuntimeLibraries.ToDictionary( r => r.Name, r => r, - StringComparer.Ordinal - ); + StringComparer.Ordinal); // Find the list of projects _ = context.CompileLibraries.Where(l => l.Type == "project"); @@ -426,10 +413,10 @@ protected virtual IEnumerable GetTestAssemblies() // Find the list of projects referencing TEntryPoint. var candidates = context.CompileLibraries.Where(library => - library.Dependencies.Any(d => - string.Equals(d.Name, entryPointAssemblyName, StringComparison.Ordinal) - ) - ); + library.Dependencies.Any(d => string.Equals( + d.Name, + entryPointAssemblyName, + StringComparison.Ordinal))); var testAssemblies = new List(); foreach (var candidate in candidates) @@ -453,8 +440,7 @@ private static void EnsureDepsFile() { if (typeof(TEntryPoint).Assembly.EntryPoint == null) throw new InvalidOperationException( - $"Invalid assembly entry point: {typeof(TEntryPoint).Assembly.FullName}" - ); + $"Invalid assembly entry point: {typeof(TEntryPoint).Assembly.FullName}"); var depsFileName = $"{typeof(TEntryPoint).Assembly.GetName().Name}.deps.json"; var depsFile = new FileInfo(Path.Combine(AppContext.BaseDirectory, depsFileName)); @@ -518,8 +504,7 @@ public DelegatedLambdaApplicationFactory( LambdaServerOptions options, Func createHost, Func> getTestAssemblies, - Action configureWebHost - ) + Action configureWebHost) { ServerOptions = options; _createHost = createHost; @@ -534,8 +519,7 @@ Action configureWebHost protected override void ConfigureWebHost(IHostBuilder builder) => _configuration(builder); protected override LambdaApplicationFactory WithHostBuilderCore( - Action configuration - ) => + Action configuration) => new DelegatedLambdaApplicationFactory( ServerOptions, _createHost, @@ -544,7 +528,6 @@ Action configuration { _configuration(builder); configuration(builder); - } - ); + }); } } diff --git a/src/MinimalLambda.Testing/LambdaApplicationFactoryContentRootAttribute.cs b/src/MinimalLambda.Testing/LambdaApplicationFactoryContentRootAttribute.cs index f3d11fea..7001a00f 100644 --- a/src/MinimalLambda.Testing/LambdaApplicationFactoryContentRootAttribute.cs +++ b/src/MinimalLambda.Testing/LambdaApplicationFactoryContentRootAttribute.cs @@ -56,20 +56,16 @@ public LambdaApplicationFactoryContentRootAttribute( string key, string contentRootPath, string contentRootTest, - string priority - ) + string priority) { Key = key; ContentRootPath = contentRootPath; ContentRootTest = contentRootTest; - if ( - int.TryParse( + if (int.TryParse( priority, NumberStyles.Integer, CultureInfo.InvariantCulture, - out var parsedPriority - ) - ) + out var parsedPriority)) Priority = parsedPriority; } diff --git a/src/MinimalLambda.Testing/LambdaHttpHandler.cs b/src/MinimalLambda.Testing/LambdaHttpHandler.cs index ec33b0df..187c68bd 100644 --- a/src/MinimalLambda.Testing/LambdaHttpHandler.cs +++ b/src/MinimalLambda.Testing/LambdaHttpHandler.cs @@ -8,18 +8,15 @@ namespace MinimalLambda.Testing; /// internal class LambdaTestingHttpHandler( Channel transactionChannel, - CancellationToken stoppingToken -) : HttpMessageHandler + CancellationToken stoppingToken) : HttpMessageHandler { protected override async Task SendAsync( HttpRequestMessage request, - CancellationToken cancellationToken - ) + CancellationToken cancellationToken) { using var cts = CancellationTokenSource.CreateLinkedTokenSource( cancellationToken, - stoppingToken - ); + stoppingToken); // Buffer the content to make it re-readable for downstream consumers if (request.Content != null) @@ -50,8 +47,7 @@ CancellationToken cancellationToken { // TestServer is shutting down; propagate cancellation to caller var canceled = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously - ); + TaskCreationOptions.RunContinuationsAsynchronously); canceled.TrySetCanceled(cts.Token); return await canceled.Task; } diff --git a/src/MinimalLambda.Testing/LambdaRuntimeRouteManager.cs b/src/MinimalLambda.Testing/LambdaRuntimeRouteManager.cs index 8d474122..3a8d9624 100644 --- a/src/MinimalLambda.Testing/LambdaRuntimeRouteManager.cs +++ b/src/MinimalLambda.Testing/LambdaRuntimeRouteManager.cs @@ -14,8 +14,7 @@ internal static class LambdaRuntimeRouteManager Method = HttpMethod.Get.Method, Matcher = new TemplateMatcher( TemplateParser.Parse("{version}/runtime/invocation/next"), - new RouteValueDictionary() - ), + new RouteValueDictionary()), }, new() { @@ -23,8 +22,7 @@ internal static class LambdaRuntimeRouteManager Method = HttpMethod.Post.Method, Matcher = new TemplateMatcher( TemplateParser.Parse("{version}/runtime/init/error"), - new RouteValueDictionary() - ), + new RouteValueDictionary()), }, new() { @@ -32,8 +30,7 @@ internal static class LambdaRuntimeRouteManager Method = HttpMethod.Post.Method, Matcher = new TemplateMatcher( TemplateParser.Parse("{version}/runtime/invocation/{requestId}/response"), - new RouteValueDictionary() - ), + new RouteValueDictionary()), }, new() { @@ -41,16 +38,14 @@ internal static class LambdaRuntimeRouteManager Method = HttpMethod.Post.Method, Matcher = new TemplateMatcher( TemplateParser.Parse("{version}/runtime/invocation/{requestId}/error"), - new RouteValueDictionary() - ), + new RouteValueDictionary()), }, ]; internal static bool TryMatch( HttpRequestMessage request, [NotNullWhen(true)] out RequestType? routeType, - [NotNullWhen(true)] out RouteValueDictionary? values - ) + [NotNullWhen(true)] out RouteValueDictionary? values) { routeType = null; values = null; diff --git a/src/MinimalLambda.Testing/LambdaTestServer.cs b/src/MinimalLambda.Testing/LambdaTestServer.cs index 3553ff64..c3e85514 100644 --- a/src/MinimalLambda.Testing/LambdaTestServer.cs +++ b/src/MinimalLambda.Testing/LambdaTestServer.cs @@ -35,16 +35,14 @@ public class LambdaTestServer : IAsyncDisposable /// TCS used to signal the startup has completed private readonly TaskCompletionSource _initCompletionTcs = new( - TaskCreationOptions.RunContinuationsAsynchronously - ); + TaskCreationOptions.RunContinuationsAsynchronously); /// JSON serializer options used to serialize/deserilize Lambda events and responses. private readonly JsonSerializerOptions _jsonSerializerOptions; /// Channel used to queue pending invocations in a FIFO manner. private readonly Channel _pendingInvocationIds = Channel.CreateUnbounded( - new UnboundedChannelOptions { SingleReader = true, SingleWriter = false } - ); + new UnboundedChannelOptions { SingleReader = true, SingleWriter = false }); /// Dictionary to track all invocations that have been sent to Lambda. private readonly ConcurrentDictionary _pendingInvocations = new(); @@ -60,8 +58,7 @@ public class LambdaTestServer : IAsyncDisposable /// Channel used to by the Lambda to send events to the server. private readonly Channel _transactionChannel = Channel.CreateUnbounded( - new UnboundedChannelOptions { SingleReader = true, SingleWriter = false } - ); + new UnboundedChannelOptions { SingleReader = true, SingleWriter = false }); /// Host application lifetime used to signal shutdown to the captioned Host. private IHostApplicationLifetime? _applicationLifetime; @@ -84,8 +81,7 @@ public class LambdaTestServer : IAsyncDisposable internal LambdaTestServer( Task? entryPointCompletion, LambdaServerOptions serverOptions, - CancellationToken shutdownToken = default - ) + CancellationToken shutdownToken = default) { ArgumentNullException.ThrowIfNull(entryPointCompletion); @@ -208,8 +204,7 @@ public async Task StartAsync(CancellationToken cancellationToken = return new InitResponse { InitStatus = InitStatus.InitAlreadyCompleted }; else if (State != ServerState.Created) throw new InvalidOperationException( - $"{nameof(LambdaTestServer)} has already been started and cannot be restarted." - ); + $"{nameof(LambdaTestServer)} has already been started and cannot be restarted."); if (_host is null) throw new InvalidOperationException("Host is not set."); @@ -247,8 +242,7 @@ await TaskHelpers } throw new InvalidOperationException( - $"{nameof(LambdaTestServer)} initialization failed with neither an error nor completion." - ); + $"{nameof(LambdaTestServer)} initialization failed with neither an error nor completion."); } finally { @@ -306,26 +300,21 @@ public async Task> InvokeAsync( TEvent? invokeEvent, bool noResponse, string? traceId = null, - CancellationToken cancellationToken = default - ) + CancellationToken cancellationToken = default) { // inorder to allow if (State != ServerState.Running) { var initResponse = await StartAsync(cancellationToken); - if ( - initResponse.InitStatus - is not (InitStatus.InitCompleted or InitStatus.InitAlreadyCompleted) - ) + if (initResponse.InitStatus is not (InitStatus.InitCompleted + or InitStatus.InitAlreadyCompleted)) throw new InvalidOperationException( - $"{nameof(LambdaTestServer)} failed to initialize and returned a status of {initResponse.InitStatus.ToString()}." - ); + $"{nameof(LambdaTestServer)} failed to initialize and returned a status of {initResponse.InitStatus.ToString()}."); } if (State != ServerState.Running) throw new InvalidOperationException( - $"{nameof(LambdaTestServer)} is in state {State} and cannot invoke an event. Expected state: Running." - ); + $"{nameof(LambdaTestServer)} is in state {State} and cannot invoke an event. Expected state: Running."); using var cts = LinkedCtsWithInvocationDeadline(cancellationToken); @@ -350,32 +339,25 @@ is not (InitStatus.InitCompleted or InitStatus.InitAlreadyCompleted) var responseMessage = completion.Request; var wasSuccess = completion.RequestType == RequestType.PostResponse; - var response = - wasSuccess && !noResponse - ? await ( - responseMessage.Content?.ReadFromJsonAsync( - _jsonSerializerOptions, - cts.Token - ) ?? Task.FromResult(default) - ) - : default; + var response = wasSuccess && !noResponse + ? await (responseMessage.Content?.ReadFromJsonAsync( + _jsonSerializerOptions, + cts.Token) + ?? Task.FromResult(default)) + : default; var error = !wasSuccess - ? await ( - responseMessage.Content?.ReadFromJsonAsync( - _jsonSerializerOptions, - cts.Token - ) ?? Task.FromResult(null) - ) + ? await (responseMessage.Content?.ReadFromJsonAsync( + _jsonSerializerOptions, + cts.Token) + ?? Task.FromResult(null)) : null; _pendingInvocations.TryRemove(requestId, out _); return new InvocationResponse { - WasSuccess = wasSuccess, - Response = response, - Error = error, + WasSuccess = wasSuccess, Response = response, Error = error, }; } @@ -410,8 +392,7 @@ public async Task StopAsync(CancellationToken cancellationToken = default) { if (State is <= ServerState.Created or >= ServerState.Stopping) throw new InvalidOperationException( - $"{nameof(LambdaTestServer)} cannot be stopped in state {State}." - ); + $"{nameof(LambdaTestServer)} cannot be stopped in state {State}."); State = ServerState.Stopping; @@ -435,20 +416,15 @@ private async Task ProcessTransactionsAsync() { try { - await foreach ( - var transaction in _transactionChannel.Reader.ReadAllAsync(_shutdownCts.Token) - ) + await foreach (var transaction in _transactionChannel.Reader.ReadAllAsync( + _shutdownCts.Token)) { - if ( - !LambdaRuntimeRouteManager.TryMatch( + if (!LambdaRuntimeRouteManager.TryMatch( transaction.Request, out var requestType, - out var routeValues - ) - ) + out var routeValues)) throw new InvalidOperationException( - $"Unexpected request received from the Lambda HTTP handler: {transaction.Request.Method} {transaction.Request.RequestUri}" - ); + $"Unexpected request received from the Lambda HTTP handler: {transaction.Request.Method} {transaction.Request.RequestUri}"); switch (requestType.Value) { @@ -470,8 +446,7 @@ out var routeValues default: throw new InvalidOperationException( - $"Unexpected request type {requestType} for {transaction.Request.RequestUri}" - ); + $"Unexpected request type {requestType} for {transaction.Request.RequestUri}"); } } } @@ -485,8 +460,7 @@ private async Task HandleGetNextInvocationAsync(LambdaHttpTransaction transactio { if (State == ServerState.Starting) _initCompletionTcs.SetResult( - new InitResponse { InitStatus = InitStatus.InitCompleted } - ); + new InitResponse { InitStatus = InitStatus.InitCompleted }); if (await _pendingInvocationIds.Reader.WaitToReadAsync(_shutdownCts.Token)) { @@ -498,8 +472,7 @@ private async Task HandleGetNextInvocationAsync(LambdaHttpTransaction transactio private async Task HandlePostResponseAsync( LambdaHttpTransaction transaction, - RouteValueDictionary routeValues - ) + RouteValueDictionary routeValues) { _pendingInvocations.GetRequired(routeValues["requestId"]?.ToString(), out var pending); @@ -507,14 +480,12 @@ RouteValueDictionary routeValues transaction.Respond(CreateSuccessResponse()); pending.ResponseTcs.SetResult( - await CreateCompletionAsync(RequestType.PostResponse, transaction.Request) - ); + await CreateCompletionAsync(RequestType.PostResponse, transaction.Request)); } private async Task HandlePostErrorAsync( LambdaHttpTransaction transaction, - RouteValueDictionary routeValues - ) + RouteValueDictionary routeValues) { _pendingInvocations.GetRequired(routeValues["requestId"]?.ToString(), out var pending); @@ -522,8 +493,7 @@ RouteValueDictionary routeValues transaction.Respond(CreateSuccessResponse()); pending.ResponseTcs.SetResult( - await CreateCompletionAsync(RequestType.PostError, transaction.Request) - ); + await CreateCompletionAsync(RequestType.PostError, transaction.Request)); } private async Task HandlePostInitErrorAsync(LambdaHttpTransaction transaction) @@ -533,39 +503,32 @@ private async Task HandlePostInitErrorAsync(LambdaHttpTransaction transaction) _initCompletionTcs.SetResult( new InitResponse { - Error = await ( - transaction.Request.Content?.ReadFromJsonAsync( - _jsonSerializerOptions - ) ?? Task.FromResult(null) - ), + Error = + await (transaction.Request.Content?.ReadFromJsonAsync( + _jsonSerializerOptions) + ?? Task.FromResult(null)), InitStatus = InitStatus.InitError, - } - ); + }); return; } throw new InvalidOperationException( - $"{nameof(LambdaTestServer)} is already started and as such an initialization error cannot be reported." - ); + $"{nameof(LambdaTestServer)} is already started and as such an initialization error cannot be reported."); } private HttpResponseMessage CreateEventResponse( TEvent? invokeEvent, string requestId, - string traceId - ) + string traceId) { - var response = new HttpResponseMessage(HttpStatusCode.OK) - { - Version = Version.Parse("1.1"), - }; + var response = + new HttpResponseMessage(HttpStatusCode.OK) { Version = Version.Parse("1.1") }; if (invokeEvent is not null) response.Content = new StringContent( JsonSerializer.Serialize(invokeEvent, _jsonSerializerOptions), Encoding.UTF8, - "application/json" - ); + "application/json"); // Add standard HTTP headers response.Headers.Date = new DateTimeOffset(DateTime.UtcNow, TimeSpan.Zero); @@ -592,13 +555,11 @@ private string GetRequestId() => private static async Task CreateCompletionAsync( RequestType requestType, - HttpRequestMessage sourceRequest - ) + HttpRequestMessage sourceRequest) { var clonedRequest = new HttpRequestMessage(sourceRequest.Method, sourceRequest.RequestUri) { - Version = sourceRequest.Version, - VersionPolicy = sourceRequest.VersionPolicy, + Version = sourceRequest.Version, VersionPolicy = sourceRequest.VersionPolicy, }; foreach (var header in sourceRequest.Headers) @@ -629,19 +590,16 @@ private static HttpResponseMessage CreateSuccessResponse() => {"status":"success"} """, Encoding.UTF8, - "application/json" - ), + "application/json"), Version = Version.Parse("1.1"), }; private CancellationTokenSource LinkedCtsWithInvocationDeadline( - CancellationToken cancellationTokens - ) + CancellationToken cancellationTokens) { var cts = CancellationTokenSource.CreateLinkedTokenSource( cancellationTokens, - _shutdownCts.Token - ); + _shutdownCts.Token); cts.CancelAfter(_serverOptions.FunctionTimeout); return cts; diff --git a/src/MinimalLambda.Testing/LambdaTestServerExtensions.cs b/src/MinimalLambda.Testing/LambdaTestServerExtensions.cs index 55a8167c..e80b3c33 100644 --- a/src/MinimalLambda.Testing/LambdaTestServerExtensions.cs +++ b/src/MinimalLambda.Testing/LambdaTestServerExtensions.cs @@ -45,13 +45,11 @@ public static class LambdaTestServerExtensions /// public Task> InvokeAsync( TEvent invokeEvent, - CancellationToken cancellationToken = default - ) => + CancellationToken cancellationToken = default) => server.InvokeAsync( invokeEvent, false, - cancellationToken: cancellationToken - ); + cancellationToken: cancellationToken); /// Invokes the Lambda function without an event and waits for the response. /// The expected type of the Lambda function's response. @@ -84,13 +82,11 @@ public Task> InvokeAsync( /// /// public Task> InvokeNoEventAsync( - CancellationToken cancellationToken = default - ) => + CancellationToken cancellationToken = default) => server.InvokeAsync( null, false, - cancellationToken: cancellationToken - ); + cancellationToken: cancellationToken); /// /// Invokes the Lambda function with the specified event but does not expect or deserialize a @@ -128,12 +124,10 @@ public Task> InvokeNoEventAsync( /// public async Task InvokeNoResponseAsync( TEvent invokeEvent, - CancellationToken cancellationToken = default - ) => + CancellationToken cancellationToken = default) => await server.InvokeAsync( invokeEvent, true, - cancellationToken: cancellationToken - ); + cancellationToken: cancellationToken); } } diff --git a/src/MinimalLambda.Testing/MinimalLambda.Testing.csproj b/src/MinimalLambda.Testing/MinimalLambda.Testing.csproj index 5e6101c5..609e41bc 100644 --- a/src/MinimalLambda.Testing/MinimalLambda.Testing.csproj +++ b/src/MinimalLambda.Testing/MinimalLambda.Testing.csproj @@ -25,19 +25,19 @@ $(NoWarn);AD0001 - + - + - - + + - - - - + + + + diff --git a/src/MinimalLambda.Testing/Models/LambdaHttpTransaction.cs b/src/MinimalLambda.Testing/Models/LambdaHttpTransaction.cs index d8ab6697..9124dc24 100644 --- a/src/MinimalLambda.Testing/Models/LambdaHttpTransaction.cs +++ b/src/MinimalLambda.Testing/Models/LambdaHttpTransaction.cs @@ -21,8 +21,7 @@ internal static LambdaHttpTransaction Create(HttpRequestMessage request) => { Request = request, ResponseTcs = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously - ), + TaskCreationOptions.RunContinuationsAsynchronously), }; /// Completes the transaction with a successful HTTP response. diff --git a/src/MinimalLambda.Testing/Models/PendingInvocation.cs b/src/MinimalLambda.Testing/Models/PendingInvocation.cs index 54437ea6..05089204 100644 --- a/src/MinimalLambda.Testing/Models/PendingInvocation.cs +++ b/src/MinimalLambda.Testing/Models/PendingInvocation.cs @@ -28,15 +28,13 @@ internal class PendingInvocation internal static PendingInvocation Create( string requestId, HttpResponseMessage eventResponse, - DateTimeOffset deadlineUtc - ) => + DateTimeOffset deadlineUtc) => new() { RequestId = requestId, EventResponse = eventResponse, ResponseTcs = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously - ), + TaskCreationOptions.RunContinuationsAsynchronously), DeadlineUtc = deadlineUtc, }; } diff --git a/src/MinimalLambda.Testing/README.md b/src/MinimalLambda.Testing/README.md index ca70a976..8e7c9aed 100644 --- a/src/MinimalLambda.Testing/README.md +++ b/src/MinimalLambda.Testing/README.md @@ -104,7 +104,7 @@ source handling. | [**MinimalLambda**](../MinimalLambda/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.svg)](https://www.nuget.org/packages/MinimalLambda/) | | [**MinimalLambda.Abstractions**](../MinimalLambda.Abstractions/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Abstractions.svg)](https://www.nuget.org/packages/MinimalLambda.Abstractions/) | | [**MinimalLambda.OpenTelemetry**](../MinimalLambda.OpenTelemetry/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.OpenTelemetry.svg)](https://www.nuget.org/packages/MinimalLambda.OpenTelemetry/) | -| [**MinimalLambda.Testing**](../MinimalLambda.Testing/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Testing.svg)](https://www.nuget.org/packages/MinimalLambda.Testing) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Testing.svg)](https://www.nuget.org/packages/MinimalLambda.Testing/) | +| [**MinimalLambda.Testing**](../MinimalLambda.Testing/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Testing.svg)](https://www.nuget.org/packages/MinimalLambda.Testing) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Testing.svg)](https://www.nuget.org/packages/MinimalLambda.Testing/) | | [**MinimalLambda.Envelopes**](../Envelopes/MinimalLambda.Envelopes/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Envelopes.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Envelopes.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes/) | | [**MinimalLambda.Envelopes.Sqs**](../Envelopes/MinimalLambda.Envelopes.Sqs/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Envelopes.Sqs.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.Sqs) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Envelopes.Sqs.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.Sqs/) | | [**MinimalLambda.Envelopes.ApiGateway**](../Envelopes/MinimalLambda.Envelopes.ApiGateway/README.md) | [![NuGet](https://img.shields.io/nuget/v/MinimalLambda.Envelopes.ApiGateway.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.ApiGateway) | [![Downloads](https://img.shields.io/nuget/dt/MinimalLambda.Envelopes.ApiGateway.svg)](https://www.nuget.org/packages/MinimalLambda.Envelopes.ApiGateway/) | diff --git a/src/MinimalLambda.Testing/TaskHelpers.cs b/src/MinimalLambda.Testing/TaskHelpers.cs index dede2c6d..ff4edbc9 100644 --- a/src/MinimalLambda.Testing/TaskHelpers.cs +++ b/src/MinimalLambda.Testing/TaskHelpers.cs @@ -16,21 +16,16 @@ internal static async Task WhenAll(params Task[] tasks) private static Exception[] ExtractExceptions(Task[] tasks) => tasks - .Where(t => - t - is { Exception: not null } - or Task { Status: TaskStatus.RanToCompletion, Result: not null } - or Task { Status: TaskStatus.RanToCompletion, Result: Exception } - ) - .Select(t => - t switch - { - { Exception: not null } => t.Exception!, - Task { Result: { } ex } => ex, - Task { Result: Exception ex } => ex, - _ => null, - } - ) + .Where(t => t is { Exception: not null } + or Task { Status: TaskStatus.RanToCompletion, Result: not null } + or Task { Status: TaskStatus.RanToCompletion, Result: Exception }) + .Select(t => t switch + { + { Exception: not null } => t.Exception!, + Task { Result: { } ex } => ex, + Task { Result: Exception ex } => ex, + _ => null, + }) .Where(static ex => ex is not null) .Cast() .ToArray(); diff --git a/src/MinimalLambda/Builder/DefaultLambdaOnInitBuilderFactory.cs b/src/MinimalLambda/Builder/DefaultLambdaOnInitBuilderFactory.cs index 7e73887f..2be6af21 100644 --- a/src/MinimalLambda/Builder/DefaultLambdaOnInitBuilderFactory.cs +++ b/src/MinimalLambda/Builder/DefaultLambdaOnInitBuilderFactory.cs @@ -7,8 +7,7 @@ internal class DefaultLambdaOnInitBuilderFactory( IServiceProvider serviceProvider, IServiceScopeFactory scopeFactory, IOptions options, - ILambdaLifecycleContextFactory contextFactory -) : ILambdaOnInitBuilderFactory + ILambdaLifecycleContextFactory contextFactory) : ILambdaOnInitBuilderFactory { public ILambdaOnInitBuilder CreateBuilder() => new LambdaOnInitBuilder(serviceProvider, scopeFactory, options, contextFactory); diff --git a/src/MinimalLambda/Builder/DefaultLambdaOnShutdownBuilderFactory.cs b/src/MinimalLambda/Builder/DefaultLambdaOnShutdownBuilderFactory.cs index cf001441..949a8fd6 100644 --- a/src/MinimalLambda/Builder/DefaultLambdaOnShutdownBuilderFactory.cs +++ b/src/MinimalLambda/Builder/DefaultLambdaOnShutdownBuilderFactory.cs @@ -5,8 +5,7 @@ namespace MinimalLambda.Builder; internal class DefaultLambdaOnShutdownBuilderFactory( IServiceProvider serviceProvider, IServiceScopeFactory scopeFactory, - ILambdaLifecycleContextFactory contextFactory -) : ILambdaOnShutdownBuilderFactory + ILambdaLifecycleContextFactory contextFactory) : ILambdaOnShutdownBuilderFactory { public ILambdaOnShutdownBuilder CreateBuilder() => new LambdaOnShutdownBuilder(serviceProvider, scopeFactory, contextFactory); diff --git a/src/MinimalLambda/Builder/Extensions/LambdaHttpClientServiceCollectionExtensions.cs b/src/MinimalLambda/Builder/Extensions/LambdaHttpClientServiceCollectionExtensions.cs index 9fd120a6..ddae80c5 100644 --- a/src/MinimalLambda/Builder/Extensions/LambdaHttpClientServiceCollectionExtensions.cs +++ b/src/MinimalLambda/Builder/Extensions/LambdaHttpClientServiceCollectionExtensions.cs @@ -20,8 +20,7 @@ public static class LambdaHttpClientServiceCollectionExtensions /// bootstrap to communicate with the Lambda runtime API. This overload is useful for testing /// scenarios where you want to inject a mock or fake HTTP client. /// - public IServiceCollection AddLambdaBootstrapHttpClient(T client) - where T : HttpClient + public IServiceCollection AddLambdaBootstrapHttpClient(T client) where T : HttpClient { ArgumentNullException.ThrowIfNull(services); @@ -45,8 +44,7 @@ public IServiceCollection AddLambdaBootstrapHttpClient(T client) /// /// public IServiceCollection AddLambdaBootstrapHttpClient( - Func factory - ) + Func factory) { ArgumentNullException.ThrowIfNull(services); @@ -67,8 +65,7 @@ public IServiceCollection AddLambdaBootstrapHttpClient( /// already been registered. This overload is useful for testing scenarios where you want to inject /// a mock or fake HTTP client without overwriting user-supplied configurations. /// - public void TryAddLambdaBootstrapHttpClient(T client) - where T : HttpClient + public void TryAddLambdaBootstrapHttpClient(T client) where T : HttpClient { ArgumentNullException.ThrowIfNull(services); @@ -91,15 +88,13 @@ public void TryAddLambdaBootstrapHttpClient(T client) /// /// public void TryAddLambdaBootstrapHttpClient( - Func factory - ) + Func factory) { ArgumentNullException.ThrowIfNull(services); services.TryAddKeyedSingleton( typeof(ILambdaBootstrapOrchestrator), - factory - ); + factory); } } } diff --git a/src/MinimalLambda/Builder/Extensions/MiddlewareLambdaApplicationExtensions.cs b/src/MinimalLambda/Builder/Extensions/MiddlewareLambdaApplicationExtensions.cs index 96d1ab9e..4ddf113f 100644 --- a/src/MinimalLambda/Builder/Extensions/MiddlewareLambdaApplicationExtensions.cs +++ b/src/MinimalLambda/Builder/Extensions/MiddlewareLambdaApplicationExtensions.cs @@ -28,8 +28,7 @@ public static class MiddlewareLambdaApplicationExtensions /// /// public ILambdaInvocationBuilder UseMiddleware( - Func middleware - ) + Func middleware) { ArgumentNullException.ThrowIfNull(application); diff --git a/src/MinimalLambda/Builder/Extensions/SerializerServiceCollectionExtensions.cs b/src/MinimalLambda/Builder/Extensions/SerializerServiceCollectionExtensions.cs index c82f9823..bb735e36 100644 --- a/src/MinimalLambda/Builder/Extensions/SerializerServiceCollectionExtensions.cs +++ b/src/MinimalLambda/Builder/Extensions/SerializerServiceCollectionExtensions.cs @@ -32,15 +32,14 @@ public static class SerializerServiceCollectionExtensions /// /// public IServiceCollection AddLambdaSerializerWithContext< - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TContext - >() - where TContext : JsonSerializerContext + [DynamicallyAccessedMembers( + DynamicallyAccessedMemberTypes.PublicConstructors)] + TContext>() where TContext : JsonSerializerContext { ArgumentNullException.ThrowIfNull(serviceCollection); - serviceCollection.AddSingleton( - _ => new SourceGeneratorLambdaJsonSerializer() - ); + serviceCollection.AddSingleton(_ => + new SourceGeneratorLambdaJsonSerializer()); return serviceCollection; } diff --git a/src/MinimalLambda/Builder/Extensions/ServiceCollectionExtensions.cs b/src/MinimalLambda/Builder/Extensions/ServiceCollectionExtensions.cs index 7fa8dfbb..6aff9dd2 100644 --- a/src/MinimalLambda/Builder/Extensions/ServiceCollectionExtensions.cs +++ b/src/MinimalLambda/Builder/Extensions/ServiceCollectionExtensions.cs @@ -20,20 +20,14 @@ public IServiceCollection AddLambdaHostCoreServices() ArgumentNullException.ThrowIfNull(services); // register core factories - services.AddSingleton< - ILambdaInvocationBuilderFactory, - DefaultLambdaInvocationBuilderFactory - >(); + services.AddSingleton(); services.AddSingleton(); - services.AddSingleton< - ILambdaOnShutdownBuilderFactory, - DefaultLambdaOnShutdownBuilderFactory - >(); + services.AddSingleton(); services.AddSingleton(); - services.AddSingleton< - ILambdaInvocationContextFactory, - LambdaInvocationContextFactory - >(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -45,20 +39,14 @@ public IServiceCollection AddLambdaHostCoreServices() services.AddHostedService(); // Register options related services - services.AddSingleton< - IPostConfigureOptions, - HostOptionsPostConfiguration - >(); - services.AddSingleton< - IPostConfigureOptions, - EnvelopeOptionsPostConfiguration - >(); + services.AddSingleton, + HostOptionsPostConfiguration>(); + services.AddSingleton, + EnvelopeOptionsPostConfiguration>(); // Register IFeatureProvider factories - services.AddSingleton< - IResponseFeatureProviderFactory, - ResponseFeatureProviderFactory - >(); + services.AddSingleton(); services.AddSingleton(); return services; @@ -72,8 +60,8 @@ public IServiceCollection AddLambdaHostCoreServices() [UnconditionalSuppressMessage( "Aot", "IL2026:RequiresUnreferencedCode", - Justification = "DefaultLambdaJsonSerializer is a fallback. Users can AddLambdaSerializerWithContext for AOT scenarios." - )] + Justification = + "DefaultLambdaJsonSerializer is a fallback. Users can AddLambdaSerializerWithContext for AOT scenarios.")] public IServiceCollection TryAddLambdaHostDefaultServices() { ArgumentNullException.ThrowIfNull(services); @@ -85,10 +73,8 @@ public IServiceCollection TryAddLambdaHostDefaultServices() services.TryAddSingleton(); #pragma warning restore IL2026 - services.TryAddSingleton< - ILambdaCancellationFactory, - DefaultLambdaCancellationFactory - >(); + services.TryAddSingleton(); return services; } @@ -108,10 +94,8 @@ public IServiceCollection AddLambdaInvocationContextAccessor() { ArgumentNullException.ThrowIfNull(services); - services.AddSingleton< - ILambdaInvocationContextAccessor, - LambdaInvocationContextAccessor - >(); + services.AddSingleton(); return services; } diff --git a/src/MinimalLambda/Builder/InterceptionTargets/MapHandlerLambdaApplicationExtensions.cs b/src/MinimalLambda/Builder/InterceptionTargets/MapHandlerLambdaApplicationExtensions.cs index ba2d17c3..3bc47650 100644 --- a/src/MinimalLambda/Builder/InterceptionTargets/MapHandlerLambdaApplicationExtensions.cs +++ b/src/MinimalLambda/Builder/InterceptionTargets/MapHandlerLambdaApplicationExtensions.cs @@ -42,8 +42,7 @@ public static class MapHandlerLambdaApplicationExtensions /// cref="ILambdaInvocationBuilder.Handle(LambdaInvocationDelegate)" /> public static ILambdaInvocationBuilder MapHandler( this ILambdaInvocationBuilder application, - Delegate handler - ) + Delegate handler) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); diff --git a/src/MinimalLambda/Builder/InterceptionTargets/OnInitLambdaApplicationExtensions.cs b/src/MinimalLambda/Builder/InterceptionTargets/OnInitLambdaApplicationExtensions.cs index c2f8f029..a9a691e5 100644 --- a/src/MinimalLambda/Builder/InterceptionTargets/OnInitLambdaApplicationExtensions.cs +++ b/src/MinimalLambda/Builder/InterceptionTargets/OnInitLambdaApplicationExtensions.cs @@ -46,8 +46,7 @@ public static class OnInitLambdaApplicationExtensions /// public static ILambdaOnInitBuilder OnInit( this ILambdaOnInitBuilder application, - Delegate handler - ) + Delegate handler) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); diff --git a/src/MinimalLambda/Builder/InterceptionTargets/OnShutdownLambdaApplicationExtensions.cs b/src/MinimalLambda/Builder/InterceptionTargets/OnShutdownLambdaApplicationExtensions.cs index 7ccaea58..d570dbcc 100644 --- a/src/MinimalLambda/Builder/InterceptionTargets/OnShutdownLambdaApplicationExtensions.cs +++ b/src/MinimalLambda/Builder/InterceptionTargets/OnShutdownLambdaApplicationExtensions.cs @@ -30,8 +30,7 @@ public static class OnShutdownLambdaApplicationExtensions /// public static ILambdaOnShutdownBuilder OnShutdown( this ILambdaOnShutdownBuilder application, - Delegate handler - ) + Delegate handler) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); diff --git a/src/MinimalLambda/Builder/InterceptionTargets/UseMiddlewareLambdaApplicationExtensions.cs b/src/MinimalLambda/Builder/InterceptionTargets/UseMiddlewareLambdaApplicationExtensions.cs index 260003cf..ad67d4e0 100644 --- a/src/MinimalLambda/Builder/InterceptionTargets/UseMiddlewareLambdaApplicationExtensions.cs +++ b/src/MinimalLambda/Builder/InterceptionTargets/UseMiddlewareLambdaApplicationExtensions.cs @@ -42,9 +42,7 @@ public static class UseMiddlewareLambdaApplicationExtensions /// public static ILambdaInvocationBuilder UseMiddleware( this ILambdaInvocationBuilder builder, - params object[] args - ) - where T : ILambdaMiddleware + params object[] args) where T : ILambdaMiddleware { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); diff --git a/src/MinimalLambda/Builder/LambdaApplication.cs b/src/MinimalLambda/Builder/LambdaApplication.cs index 4c2f0262..58102323 100644 --- a/src/MinimalLambda/Builder/LambdaApplication.cs +++ b/src/MinimalLambda/Builder/LambdaApplication.cs @@ -51,9 +51,10 @@ internal LambdaApplication(IHost host) /// Gets the application's logger. public ILogger Logger => - field ??= - _host.Services.GetService()?.CreateLogger(Environment.ApplicationName) - ?? NullLogger.Instance; + field ??= _host + .Services.GetService() + ?.CreateLogger(Environment.ApplicationName) + ?? NullLogger.Instance; /// public ValueTask DisposeAsync() => ((IAsyncDisposable)_host).DisposeAsync(); @@ -95,8 +96,7 @@ public ILambdaInvocationBuilder Handle(LambdaInvocationDelegate handler) /// public ILambdaInvocationBuilder Use( - Func middleware - ) + Func middleware) { _invocationBuilder.Use(middleware); return this; diff --git a/src/MinimalLambda/Builder/LambdaApplicationBuilder.cs b/src/MinimalLambda/Builder/LambdaApplicationBuilder.cs index 96d018af..5ad36d73 100644 --- a/src/MinimalLambda/Builder/LambdaApplicationBuilder.cs +++ b/src/MinimalLambda/Builder/LambdaApplicationBuilder.cs @@ -70,8 +70,7 @@ internal LambdaApplicationBuilder(LambdaApplicationOptions? settings) EnvironmentName = settings.EnvironmentName, ApplicationName = settings.ApplicationName, ContentRootPath = settings.ContentRootPath, - } - ); + }); if (!settings.DisableDefaults) { @@ -124,9 +123,8 @@ internal LambdaApplicationBuilder(LambdaApplicationOptions? settings) /// public void ConfigureContainer( IServiceProviderFactory factory, - Action? configure = null - ) - where TContainerBuilder : notnull => _hostBuilder.ConfigureContainer(factory, configure); + Action? configure = null) where TContainerBuilder : notnull => + _hostBuilder.ConfigureContainer(factory, configure); private void AddDefaultServices() => Services.AddLogging(logging => @@ -136,18 +134,16 @@ private void AddDefaultServices() => logging.Configure(options => { - options.ActivityTrackingOptions = - ActivityTrackingOptions.SpanId - | ActivityTrackingOptions.TraceId - | ActivityTrackingOptions.ParentId; + options.ActivityTrackingOptions = ActivityTrackingOptions.SpanId + | ActivityTrackingOptions.TraceId + | ActivityTrackingOptions.ParentId; }); }); private DefaultServiceProviderFactory GetServiceProviderFactory() => Environment.IsDevelopment() ? new DefaultServiceProviderFactory( - new ServiceProviderOptions { ValidateScopes = true, ValidateOnBuild = true } - ) + new ServiceProviderOptions { ValidateScopes = true, ValidateOnBuild = true }) : new DefaultServiceProviderFactory(); /// Applies default configuration sources to the application's configuration manager. @@ -188,10 +184,8 @@ private static void ResolveContentRoot(LambdaApplicationOptions settings) { // If the user has set the ContentRootPath explicitly, we don't need to do anything. This // will also capture if the user set DOTNET_CONTENTROOT. - if ( - settings.ContentRootPath is not null - || settings.Configuration?[HostDefaults.ContentRootKey] is not null - ) + if (settings.ContentRootPath is not null + || settings.Configuration?[HostDefaults.ContentRootKey] is not null) return; // If the user does not set DOTNET_CONTENTROOT or sets the content root explicitly, we will @@ -222,14 +216,11 @@ settings.ContentRootPath is not null // ignore case for Windows path comparisons given the file system is usually (always?) going // to be case insensitive for the system path. var cwd = System.Environment.CurrentDirectory; - if ( - !OperatingSystem.IsWindows() + if (!OperatingSystem.IsWindows() || !string.Equals( cwd, System.Environment.SystemDirectory, - StringComparison.OrdinalIgnoreCase - ) - ) + StringComparison.OrdinalIgnoreCase)) settings.ContentRootPath = cwd; } @@ -300,8 +291,7 @@ private void ConfigureOnInitBuilder(ILambdaOnInitBuilder builder) ArgumentNullException.ThrowIfNull(builder); Debug.Assert(_builtApplication is not null); - var settings = _builtApplication - .Services.GetRequiredService>() + var settings = _builtApplication.Services.GetRequiredService>() .Value; // Add default OnInit handlers if asked for diff --git a/src/MinimalLambda/Builder/LambdaInvocationBuilder.cs b/src/MinimalLambda/Builder/LambdaInvocationBuilder.cs index a9b0111f..77af45e1 100644 --- a/src/MinimalLambda/Builder/LambdaInvocationBuilder.cs +++ b/src/MinimalLambda/Builder/LambdaInvocationBuilder.cs @@ -5,8 +5,8 @@ internal class LambdaInvocationBuilder : ILambdaInvocationBuilder internal const string EventFeatureProviderKey = "__EventFeatureProvider"; internal const string ResponseFeatureProviderKey = "__ResponseFeatureProvider"; - private readonly List> _middleware = - []; + private readonly List> + _middleware = []; public LambdaInvocationBuilder(IServiceProvider services) { @@ -37,8 +37,7 @@ public ILambdaInvocationBuilder Handle(LambdaInvocationDelegate handler) } public ILambdaInvocationBuilder Use( - Func middleware - ) + Func middleware) { ArgumentNullException.ThrowIfNull(middleware); diff --git a/src/MinimalLambda/Builder/LambdaOnInitBuilder.cs b/src/MinimalLambda/Builder/LambdaOnInitBuilder.cs index a1c7c383..3d7d4760 100644 --- a/src/MinimalLambda/Builder/LambdaOnInitBuilder.cs +++ b/src/MinimalLambda/Builder/LambdaOnInitBuilder.cs @@ -15,8 +15,7 @@ public LambdaOnInitBuilder( IServiceProvider serviceProvider, IServiceScopeFactory scopeFactory, IOptions options, - ILambdaLifecycleContextFactory contextFactory - ) + ILambdaLifecycleContextFactory contextFactory) { ArgumentNullException.ThrowIfNull(serviceProvider); ArgumentNullException.ThrowIfNull(scopeFactory); @@ -62,8 +61,7 @@ public ILambdaOnInitBuilder OnInit(LambdaInitDelegate handler) catch (TaskCanceledException) when (cts.Token.IsCancellationRequested) { throw new OperationCanceledException( - "Running OnInit handlers did not complete within the allocated timeout period." - ); + "Running OnInit handlers did not complete within the allocated timeout period."); } var (errors, shouldContinue) = results.Aggregate( @@ -76,22 +74,19 @@ public ILambdaOnInitBuilder OnInit(LambdaInitDelegate handler) acc.shouldContinue = false; return acc; - } - ); + }); if (errors.Count > 0) throw new AggregateException( "Encountered errors while running OnInit handlers:", - errors - ); + errors); return shouldContinue; }; private async Task<(Exception? Error, bool ShouldContinue)> RunInitHandler( LambdaInitDelegate handler, - CancellationToken cancellationToken - ) + CancellationToken cancellationToken) { try { diff --git a/src/MinimalLambda/Builder/LambdaOnShutdownBuilder.cs b/src/MinimalLambda/Builder/LambdaOnShutdownBuilder.cs index 2b11a0bd..a4d464b6 100644 --- a/src/MinimalLambda/Builder/LambdaOnShutdownBuilder.cs +++ b/src/MinimalLambda/Builder/LambdaOnShutdownBuilder.cs @@ -12,8 +12,7 @@ internal class LambdaOnShutdownBuilder : ILambdaOnShutdownBuilder public LambdaOnShutdownBuilder( IServiceProvider serviceProvider, IServiceScopeFactory scopeFactory, - ILambdaLifecycleContextFactory contextFactory - ) + ILambdaLifecycleContextFactory contextFactory) { ArgumentNullException.ThrowIfNull(serviceProvider); ArgumentNullException.ThrowIfNull(scopeFactory); @@ -52,14 +51,12 @@ public Func Build() => if (errors.Length != 0) throw new AggregateException( "Encountered errors while running OnShutdown handlers:", - errors - ); + errors); }; private async Task RunShutdownHandler( LambdaShutdownDelegate handler, - CancellationToken cancellationToken - ) + CancellationToken cancellationToken) { try { diff --git a/src/MinimalLambda/Builder/Middleware/ClearLambdaOutputFormattingMiddleware.cs b/src/MinimalLambda/Builder/Middleware/ClearLambdaOutputFormattingMiddleware.cs index 6808ab63..a985023b 100644 --- a/src/MinimalLambda/Builder/Middleware/ClearLambdaOutputFormattingMiddleware.cs +++ b/src/MinimalLambda/Builder/Middleware/ClearLambdaOutputFormattingMiddleware.cs @@ -37,8 +37,7 @@ public ILambdaInvocationBuilder UseClearLambdaOutputFormatting() { // This will clear the output formatting set by the Lambda runtime. Console.SetOut( - new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true } - ); + new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true }); await next(context); }; }); diff --git a/src/MinimalLambda/Builder/Middleware/RequestEnvelopeMiddleware.cs b/src/MinimalLambda/Builder/Middleware/RequestEnvelopeMiddleware.cs index 78faf377..6d0f626b 100644 --- a/src/MinimalLambda/Builder/Middleware/RequestEnvelopeMiddleware.cs +++ b/src/MinimalLambda/Builder/Middleware/RequestEnvelopeMiddleware.cs @@ -42,18 +42,14 @@ public ILambdaInvocationBuilder UseExtractAndPackEnvelope() { return async context => { - if ( - context.Features.TryGet(out IEventFeature? eventFeature) - && eventFeature.GetEvent(context) is IRequestEnvelope requestEnvelope - ) + if (context.Features.TryGet(out IEventFeature? eventFeature) + && eventFeature.GetEvent(context) is IRequestEnvelope requestEnvelope) requestEnvelope.ExtractPayload(GetOptions()); await next(context); - if ( - context.Features.TryGet(out IResponseFeature? responseFeature) - && responseFeature.GetResponse() is IResponseEnvelope responseEnvelope - ) + if (context.Features.TryGet(out IResponseFeature? responseFeature) + && responseFeature.GetResponse() is IResponseEnvelope responseEnvelope) responseEnvelope.PackPayload(GetOptions()); }; }); @@ -61,8 +57,8 @@ public ILambdaInvocationBuilder UseExtractAndPackEnvelope() return application; EnvelopeOptions GetOptions() => - envelopeOptions ??= application - .Services.GetRequiredService>() + envelopeOptions ??= application.Services + .GetRequiredService>() .Value; } } diff --git a/src/MinimalLambda/Builder/OnInit/OutputFormattingLambdaApplicationExtensions.cs b/src/MinimalLambda/Builder/OnInit/OutputFormattingLambdaApplicationExtensions.cs index 58ade079..79c35a63 100644 --- a/src/MinimalLambda/Builder/OnInit/OutputFormattingLambdaApplicationExtensions.cs +++ b/src/MinimalLambda/Builder/OnInit/OutputFormattingLambdaApplicationExtensions.cs @@ -14,22 +14,19 @@ public static class OutputFormattingLambdaApplicationExtensions /// The Lambda application to configure. /// The configured for method chaining. public static ILambdaOnInitBuilder OnInitClearLambdaOutputFormatting( - this ILambdaOnInitBuilder application - ) + this ILambdaOnInitBuilder application) { ArgumentNullException.ThrowIfNull(application); - application.OnInit( - (ILogger? logger = null) => - { - // This will clear the output formatting set by the Lambda runtime. - Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true }); + application.OnInit((ILogger? logger = null) => + { + // This will clear the output formatting set by the Lambda runtime. + Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true }); - logger?.LogInformation("Clearing Lambda output formatting"); + logger?.LogInformation("Clearing Lambda output formatting"); - return Task.FromResult(true); - } - ); + return Task.FromResult(true); + }); return application; } diff --git a/src/MinimalLambda/Core/Cancellation/DefaultLambdaCancellationFactory.cs b/src/MinimalLambda/Core/Cancellation/DefaultLambdaCancellationFactory.cs index abd9fc36..557d1efb 100644 --- a/src/MinimalLambda/Core/Cancellation/DefaultLambdaCancellationFactory.cs +++ b/src/MinimalLambda/Core/Cancellation/DefaultLambdaCancellationFactory.cs @@ -30,8 +30,7 @@ public DefaultLambdaCancellationFactory(IOptions options) if (options.Value.InvocationCancellationBuffer < TimeSpan.Zero) throw new ArgumentException( "The InvocationCancellationBuffer inside options must be greater than or equal to zero.", - nameof(options) - ); + nameof(options)); _bufferDuration = options.Value.InvocationCancellationBuffer; } @@ -68,10 +67,9 @@ public CancellationTokenSource NewCancellationTokenSource(ILambdaContext context if (maxAllowedDuration <= TimeSpan.Zero) throw new InvalidOperationException( "CancellationTokenSource provided with insufficient time. " - + $"Lambda Remaining Time = {context.RemainingTime:c}, " - + $"Cancellation Token Buffer = {_bufferDuration:c}, " - + $"Candidate Token Duration = {maxAllowedDuration:c}" - ); + + $"Lambda Remaining Time = {context.RemainingTime:c}, " + + $"Cancellation Token Buffer = {_bufferDuration:c}, " + + $"Candidate Token Duration = {maxAllowedDuration:c}"); return new CancellationTokenSource(maxAllowedDuration); } diff --git a/src/MinimalLambda/Core/Context/ILambdaInvocationContextFactory.cs b/src/MinimalLambda/Core/Context/ILambdaInvocationContextFactory.cs index 4f353de1..5a1453a5 100644 --- a/src/MinimalLambda/Core/Context/ILambdaInvocationContextFactory.cs +++ b/src/MinimalLambda/Core/Context/ILambdaInvocationContextFactory.cs @@ -7,6 +7,5 @@ internal interface ILambdaInvocationContextFactory ILambdaInvocationContext Create( ILambdaContext lambdaContext, IDictionary properties, - CancellationToken cancellationToken - ); + CancellationToken cancellationToken); } diff --git a/src/MinimalLambda/Core/Context/ILambdaLifecycleContextFactory.cs b/src/MinimalLambda/Core/Context/ILambdaLifecycleContextFactory.cs index 5e1de4dd..ea2c646e 100644 --- a/src/MinimalLambda/Core/Context/ILambdaLifecycleContextFactory.cs +++ b/src/MinimalLambda/Core/Context/ILambdaLifecycleContextFactory.cs @@ -4,6 +4,5 @@ internal interface ILambdaLifecycleContextFactory { ILambdaLifecycleContext Create( IDictionary properties, - CancellationToken cancellationToken - ); + CancellationToken cancellationToken); } diff --git a/src/MinimalLambda/Core/Context/LambdaInvocationContext.cs b/src/MinimalLambda/Core/Context/LambdaInvocationContext.cs index 84face58..db671ae8 100644 --- a/src/MinimalLambda/Core/Context/LambdaInvocationContext.cs +++ b/src/MinimalLambda/Core/Context/LambdaInvocationContext.cs @@ -15,8 +15,7 @@ public LambdaInvocationContext( IServiceScopeFactory serviceScopeFactory, IDictionary properties, IFeatureCollection featuresCollection, - CancellationToken cancellationToken - ) + CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(lambdaContext); ArgumentNullException.ThrowIfNull(serviceScopeFactory); diff --git a/src/MinimalLambda/Core/Context/LambdaInvocationContextFactory.cs b/src/MinimalLambda/Core/Context/LambdaInvocationContextFactory.cs index 3598bb7a..887931d0 100644 --- a/src/MinimalLambda/Core/Context/LambdaInvocationContextFactory.cs +++ b/src/MinimalLambda/Core/Context/LambdaInvocationContextFactory.cs @@ -13,8 +13,7 @@ internal class LambdaInvocationContextFactory : ILambdaInvocationContextFactory public LambdaInvocationContextFactory( IServiceScopeFactory serviceScopeFactory, IFeatureCollectionFactory featureCollectionFactory, - ILambdaInvocationContextAccessor? contextAccessor = null - ) + ILambdaInvocationContextAccessor? contextAccessor = null) { ArgumentNullException.ThrowIfNull(serviceScopeFactory); ArgumentNullException.ThrowIfNull(featureCollectionFactory); @@ -27,8 +26,7 @@ public LambdaInvocationContextFactory( public ILambdaInvocationContext Create( ILambdaContext lambdaContext, IDictionary properties, - CancellationToken cancellationToken - ) + CancellationToken cancellationToken) { _featureProviders ??= CreateFeatureProviders(properties); @@ -37,8 +35,7 @@ CancellationToken cancellationToken _serviceScopeFactory, properties, _featureCollectionFactory.Create(_featureProviders), - cancellationToken - ); + cancellationToken); _contextAccessor?.LambdaInvocationContext = context; @@ -46,8 +43,7 @@ CancellationToken cancellationToken } private static IFeatureProvider[] CreateFeatureProviders( - IDictionary properties - ) + IDictionary properties) { var list = new List(2); @@ -60,8 +56,7 @@ private static IFeatureProvider[] CreateFeatureProviders( private static void AddIfPresent( IDictionary properties, string key, - List target - ) + List target) { if (properties.TryGetValue(key, out var value) && value is IFeatureProvider provider) target.Add(provider); diff --git a/src/MinimalLambda/Core/Context/LambdaLifecycleContext.cs b/src/MinimalLambda/Core/Context/LambdaLifecycleContext.cs index 3b532ffc..f1a76a4f 100644 --- a/src/MinimalLambda/Core/Context/LambdaLifecycleContext.cs +++ b/src/MinimalLambda/Core/Context/LambdaLifecycleContext.cs @@ -6,8 +6,7 @@ internal class LambdaLifecycleContext( LambdaLifecycleContext.Core contextCore, IServiceScopeFactory scopeFactory, IDictionary properties, - CancellationToken cancellationToken -) : ILambdaLifecycleContext, IAsyncDisposable + CancellationToken cancellationToken) : ILambdaLifecycleContext, IAsyncDisposable { private IServiceScope? _instanceServicesScope; diff --git a/src/MinimalLambda/Core/Context/LambdaLifecycleContextFactory.cs b/src/MinimalLambda/Core/Context/LambdaLifecycleContextFactory.cs index 247f6aa8..f1007cdb 100644 --- a/src/MinimalLambda/Core/Context/LambdaLifecycleContextFactory.cs +++ b/src/MinimalLambda/Core/Context/LambdaLifecycleContextFactory.cs @@ -6,15 +6,13 @@ namespace MinimalLambda; internal class LambdaLifecycleContextFactory( IServiceScopeFactory scopeFactory, ILifetimeStopwatch stopwatch, - IConfiguration configuration -) : ILambdaLifecycleContextFactory + IConfiguration configuration) : ILambdaLifecycleContextFactory { private LambdaLifecycleContext.Core? _contextCore; public ILambdaLifecycleContext Create( IDictionary properties, - CancellationToken cancellationToken - ) + CancellationToken cancellationToken) { _contextCore ??= new LambdaLifecycleContext.Core { @@ -22,12 +20,10 @@ CancellationToken cancellationToken Region = configuration["AWS_REGION"] ?? configuration["AWS_DEFAULT_REGION"], ExecutionEnvironment = configuration["AWS_EXECUTION_ENV"], FunctionName = configuration["AWS_LAMBDA_FUNCTION_NAME"], - FunctionMemorySize = int.TryParse( - configuration["AWS_LAMBDA_FUNCTION_MEMORY_SIZE"], - out var memorySize - ) - ? memorySize - : null, + FunctionMemorySize = + int.TryParse(configuration["AWS_LAMBDA_FUNCTION_MEMORY_SIZE"], out var memorySize) + ? memorySize + : null, FunctionVersion = configuration["AWS_LAMBDA_FUNCTION_VERSION"], InitializationType = configuration["AWS_LAMBDA_INITIALIZATION_TYPE"], LogGroupName = configuration["AWS_LAMBDA_LOG_GROUP_NAME"], @@ -39,7 +35,6 @@ out var memorySize _contextCore, scopeFactory, properties, - cancellationToken - ); + cancellationToken); } } diff --git a/src/MinimalLambda/Core/Features/DefaultEventFeature.cs b/src/MinimalLambda/Core/Features/DefaultEventFeature.cs index 6d0bb9f8..520f5b26 100644 --- a/src/MinimalLambda/Core/Features/DefaultEventFeature.cs +++ b/src/MinimalLambda/Core/Features/DefaultEventFeature.cs @@ -9,15 +9,13 @@ namespace MinimalLambda; /// internal class DefaultEventFeature(ILambdaSerializer? lambdaSerializer = null) : IEventFeature { - private readonly ILambdaSerializer _lambdaSerializer = - lambdaSerializer - ?? throw new ArgumentNullException( - nameof(lambdaSerializer), - "ILambdaSerializer has not been registered. In AOT scenarios you must provide an " - + "serializer by registering an ILambdaSerializer in the DI container. " - + "Use AddLambdaSerializerWithContext (registers the context for you) or " - + "manually register your serializer implementation." - ); + private readonly ILambdaSerializer _lambdaSerializer = lambdaSerializer + ?? throw new ArgumentNullException( + nameof(lambdaSerializer), + "ILambdaSerializer has not been registered. In AOT scenarios you must provide an " + + "serializer by registering an ILambdaSerializer in the DI container. " + + "Use AddLambdaSerializerWithContext (registers the context for you) or " + + "manually register your serializer implementation."); private T _data = default!; private bool _isDeserialized; diff --git a/src/MinimalLambda/Core/Features/DefaultFeatureCollection.cs b/src/MinimalLambda/Core/Features/DefaultFeatureCollection.cs index e9c833e3..5b358263 100644 --- a/src/MinimalLambda/Core/Features/DefaultFeatureCollection.cs +++ b/src/MinimalLambda/Core/Features/DefaultFeatureCollection.cs @@ -25,11 +25,9 @@ internal DefaultFeatureCollection(IEnumerable featureProviders public T? Get() { var type = typeof(T); - if ( - !_features.TryGetValue(type, out var feature) + if (!_features.TryGetValue(type, out var feature) && _featureProviders.Any(t => t.TryCreate(type, out feature)) - && !_features.TryAdd(type, feature!) - ) + && !_features.TryAdd(type, feature!)) feature = _features[type]; return feature is null ? default : (T)feature; diff --git a/src/MinimalLambda/Core/Features/FeatureCollectionExtensions.cs b/src/MinimalLambda/Core/Features/FeatureCollectionExtensions.cs index adb322e2..1018b46e 100644 --- a/src/MinimalLambda/Core/Features/FeatureCollectionExtensions.cs +++ b/src/MinimalLambda/Core/Features/FeatureCollectionExtensions.cs @@ -40,9 +40,8 @@ public T GetRequired() ArgumentNullException.ThrowIfNull(featureCollection); return featureCollection.Get() - ?? throw new InvalidOperationException( - $"Feature of type '{typeof(T).FullName}' is not available in the collection." - ); + ?? throw new InvalidOperationException( + $"Feature of type '{typeof(T).FullName}' is not available in the collection."); } } } diff --git a/src/MinimalLambda/Core/Features/FeatureLambdaInvocationContextExtensions.cs b/src/MinimalLambda/Core/Features/FeatureLambdaInvocationContextExtensions.cs index 3e139987..d9f1c539 100644 --- a/src/MinimalLambda/Core/Features/FeatureLambdaInvocationContextExtensions.cs +++ b/src/MinimalLambda/Core/Features/FeatureLambdaInvocationContextExtensions.cs @@ -50,8 +50,7 @@ public T GetRequiredEvent() if (!context.TryGetEvent(out var eventT)) throw new InvalidOperationException( - $"Lambda event of type '{typeof(T).FullName}' is not available in the context." - ); + $"Lambda event of type '{typeof(T).FullName}' is not available in the context."); return eventT; } @@ -102,8 +101,7 @@ public T GetRequiredResponse() if (!context.TryGetResponse(out var responseT)) throw new InvalidOperationException( - $"Lambda response of type '{typeof(T).FullName}' is not available in the context." - ); + $"Lambda response of type '{typeof(T).FullName}' is not available in the context."); return responseT; } diff --git a/src/MinimalLambda/Core/Options/HostOptionsPostConfiguration.cs b/src/MinimalLambda/Core/Options/HostOptionsPostConfiguration.cs index 7dd0b927..38c65f3c 100644 --- a/src/MinimalLambda/Core/Options/HostOptionsPostConfiguration.cs +++ b/src/MinimalLambda/Core/Options/HostOptionsPostConfiguration.cs @@ -16,8 +16,8 @@ public HostOptionsPostConfiguration(IOptions lambdaHostOption public void PostConfigure(string? name, HostOptions options) { - var shutdownTimeout = - _lambdaHostOptions.ShutdownDuration - _lambdaHostOptions.ShutdownDurationBuffer; + var shutdownTimeout = _lambdaHostOptions.ShutdownDuration + - _lambdaHostOptions.ShutdownDurationBuffer; options.ShutdownTimeout = shutdownTimeout >= TimeSpan.Zero ? shutdownTimeout : TimeSpan.Zero; diff --git a/src/MinimalLambda/MinimalLambda.csproj b/src/MinimalLambda/MinimalLambda.csproj index 56dad5f3..d6c06768 100644 --- a/src/MinimalLambda/MinimalLambda.csproj +++ b/src/MinimalLambda/MinimalLambda.csproj @@ -14,10 +14,10 @@ $(InterceptorsNamespaces);MinimalLambda.Generated - - - - + + + + - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + - - - - - + + + + + - - - - + Version="1.1.3" /> + + + + - - - + + + - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + - - - - + + + + - - + + - - - + + + - - - + + + \ No newline at end of file From 5098c15093d49fd2a3fe73cf001e466317ad9442 Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Sat, 24 Jan 2026 18:38:28 -0500 Subject: [PATCH 15/17] refactor(packages): standardize self-closing tag formatting and remove unused dependencies - Removed unnecessary `coverlet.collector` package references from test projects. - Updated `` tag formatting in `Directory.Packages.props` for consistency. --- Directory.Packages.props | 123 +++++++++--------- .../MinimalLambda.Envelopes.UnitTests.csproj | 1 - ...nimalLambda.OpenTelemetry.UnitTests.csproj | 1 - ...alLambda.SourceGenerators.UnitTests.csproj | 1 - .../MinimalLambda.Testing.UnitTests.csproj | 1 - .../MinimalLambda.UnitTests.csproj | 1 - 6 files changed, 61 insertions(+), 67 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 59354a34..73083ca4 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -5,80 +5,79 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + - - - - - + + + + + - - - - + Version="1.1.3"/> + + + + - - - + + + - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + - - - - + + + + - - + + - - - + + + - - - + + + \ No newline at end of file diff --git a/tests/MinimalLambda.Envelopes.UnitTests/MinimalLambda.Envelopes.UnitTests.csproj b/tests/MinimalLambda.Envelopes.UnitTests/MinimalLambda.Envelopes.UnitTests.csproj index 542df4bc..6d1110d9 100644 --- a/tests/MinimalLambda.Envelopes.UnitTests/MinimalLambda.Envelopes.UnitTests.csproj +++ b/tests/MinimalLambda.Envelopes.UnitTests/MinimalLambda.Envelopes.UnitTests.csproj @@ -16,7 +16,6 @@ - all diff --git a/tests/MinimalLambda.OpenTelemetry.UnitTests/MinimalLambda.OpenTelemetry.UnitTests.csproj b/tests/MinimalLambda.OpenTelemetry.UnitTests/MinimalLambda.OpenTelemetry.UnitTests.csproj index e5cd9ff1..777dce12 100644 --- a/tests/MinimalLambda.OpenTelemetry.UnitTests/MinimalLambda.OpenTelemetry.UnitTests.csproj +++ b/tests/MinimalLambda.OpenTelemetry.UnitTests/MinimalLambda.OpenTelemetry.UnitTests.csproj @@ -25,7 +25,6 @@ - diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/MinimalLambda.SourceGenerators.UnitTests.csproj b/tests/MinimalLambda.SourceGenerators.UnitTests/MinimalLambda.SourceGenerators.UnitTests.csproj index eed67f2e..358a341e 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/MinimalLambda.SourceGenerators.UnitTests.csproj +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/MinimalLambda.SourceGenerators.UnitTests.csproj @@ -17,7 +17,6 @@ - diff --git a/tests/MinimalLambda.Testing.UnitTests/Tests/MinimalLambda.Testing.UnitTests/MinimalLambda.Testing.UnitTests.csproj b/tests/MinimalLambda.Testing.UnitTests/Tests/MinimalLambda.Testing.UnitTests/MinimalLambda.Testing.UnitTests.csproj index 36e800ef..b9196065 100644 --- a/tests/MinimalLambda.Testing.UnitTests/Tests/MinimalLambda.Testing.UnitTests/MinimalLambda.Testing.UnitTests.csproj +++ b/tests/MinimalLambda.Testing.UnitTests/Tests/MinimalLambda.Testing.UnitTests/MinimalLambda.Testing.UnitTests.csproj @@ -22,7 +22,6 @@ - diff --git a/tests/MinimalLambda.UnitTests/MinimalLambda.UnitTests.csproj b/tests/MinimalLambda.UnitTests/MinimalLambda.UnitTests.csproj index 83f5f9c7..a855f24c 100644 --- a/tests/MinimalLambda.UnitTests/MinimalLambda.UnitTests.csproj +++ b/tests/MinimalLambda.UnitTests/MinimalLambda.UnitTests.csproj @@ -32,7 +32,6 @@ - all From fbec442884878fca89379f1b53b2de152d98a6ce Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Sat, 24 Jan 2026 18:45:06 -0500 Subject: [PATCH 16/17] refactor(packages): standardize self-closing tag formatting in `Directory.Packages.props` - Added spaces before self-closing slashes in `` tags for consistency. - Ensured consistent tag formatting across all package definitions. --- Directory.Packages.props | 122 +++++++++++++++++++-------------------- 1 file changed, 61 insertions(+), 61 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 73083ca4..be61890d 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -5,79 +5,79 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + - - - - - + + + + + - - - - + Version="1.1.3" /> + + + + - - - + + + - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + - - - - + + + + - - + + - - - + + + - - - + + + \ No newline at end of file From c26886a1c0a814a785a8d1e0d15373518064127d Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Sat, 24 Jan 2026 19:53:51 -0500 Subject: [PATCH 17/17] feat(workflows): add timeout configuration for build and test steps - Set `timeout-minutes` to 10 for primary job execution in `pr-build.yaml` and `main-build.yaml`. - Added `timeout-minutes` of 3 for the test step to prevent prolonged executions. --- .github/workflows/main-build.yaml | 3 +++ .github/workflows/pr-build.yaml | 3 +++ 2 files changed, 6 insertions(+) diff --git a/.github/workflows/main-build.yaml b/.github/workflows/main-build.yaml index 0c5051a5..ae901606 100644 --- a/.github/workflows/main-build.yaml +++ b/.github/workflows/main-build.yaml @@ -22,6 +22,8 @@ jobs: build-and-test: runs-on: ubuntu-latest + + timeout-minutes: 10 steps: - name: Act Workaround # https://github.com/nektos/act/issues/973 @@ -86,6 +88,7 @@ jobs: run: dotnet build --no-restore --configuration Release /p:TreatWarningsAsErrors=true - name: Run tests + timeout-minutes: 3 run: task test:ci - name: Stop SonarQube diff --git a/.github/workflows/pr-build.yaml b/.github/workflows/pr-build.yaml index 23fb751a..27a4494e 100644 --- a/.github/workflows/pr-build.yaml +++ b/.github/workflows/pr-build.yaml @@ -24,6 +24,8 @@ jobs: if: github.event.pull_request.draft == false runs-on: ubuntu-latest + + timeout-minutes: 10 steps: - name: Act Workaround # https://github.com/nektos/act/issues/973 @@ -90,6 +92,7 @@ jobs: run: dotnet build --no-restore --configuration Release /p:TreatWarningsAsErrors=true - name: Run tests + timeout-minutes: 3 run: task test:ci - name: Stop SonarQube