Skip to content

feat(source-generators): support multiple MapHandler invocations with custom feature providers#214

Merged
j-d-ha merged 52 commits into
mainfrom
feature/#189-support-multiple-map-handler
Dec 4, 2025
Merged

feat(source-generators): support multiple MapHandler invocations with custom feature providers#214
j-d-ha merged 52 commits into
mainfrom
feature/#189-support-multiple-map-handler

Conversation

@j-d-ha

@j-d-ha j-d-ha commented Dec 3, 2025

Copy link
Copy Markdown
Collaborator

🚀 Pull Request

📋 Summary

This PR implements support for multiple MapHandler invocations with custom feature providers, enabling more flexible Lambda handler registration patterns. The changes include:

  • Feature Provider Factories: Added IEventFeatureProviderFactory and IResponseFeatureProviderFactory interfaces to enable custom feature provider creation
  • Multiple MapHandler Support: Extended source generators to support multiple MapHandler() invocations in the same application
  • Improved Feature Handling: Enhanced LambdaHostContextFactory and DefaultFeatureCollectionFactory to accept custom feature providers
  • OpenTelemetry Refactoring: Simplified OpenTelemetry integration by removing AWS Lambda-specific adapters and consolidating middleware
  • Test Improvements: Refactored tests to use [Theory, AutoNSubstituteData] pattern for cleaner, more maintainable test code

✅ Checklist

  • My changes build cleanly
  • I've added/updated relevant tests
  • I've added/updated documentation or README
  • I've followed the coding style for this project
  • I've tested the changes locally (if applicable)

🧪 Related Issues or PRs

Closes #189


💬 Notes for Reviewers

Key architectural changes:

  1. Feature Provider Pattern: The new factory interfaces allow customization of event and response feature providers at the per-handler level
  2. Source Generator Updates: The MapHandler template now generates code that registers feature providers and handles multiple invocations correctly

Areas to focus on:

  • Feature provider registration and lifecycle management
  • Source generator output for multiple handlers
  • Test coverage for new factory interfaces

- Added null-checking logic to filter out null `IFeatureProvider` instances.
- Simplified constructor and improved internal field initialization.
- Added null-checking logic to filter out null `IFeatureProvider` instances.
- Simplified constructor and improved internal field initialization.
…p-handler' into feature/#189-support-multiple-map-handler
- Introduced `EventFeatureProviderFactory` and `ResponseFeatureProviderFactory` implementations.
- Added `IEventFeatureProviderFactory` and `IResponseFeatureProviderFactory` interfaces.
- Registered feature provider factories into the service collection.
- Added summary and remarks for `IResponseFeatureProviderFactory` and `IEventFeatureProviderFactory`.
- Documented type parameters and return values for `Create<T>` methods.
- Updated `DefaultEventFeatureProvider` and `DefaultResponseFeatureProvider` visibility to internal.
- Enhances encapsulation and restricts unnecessary exposure of types.
…om providers

- Added a new `Create` method overload accepting `IEnumerable<IFeatureProvider>`.
- Enables combining default and custom feature providers when creating `DefaultFeatureCollection`.
…ctory method

- Updated `DefaultFeature in` `IFeatureCollectionFactory.Create` to use `.ToArray()` after concatenation.
- Ensures compatibility with collections requiring fixed-size arrays from concatenation outputs.
- Added `_featureProviders` field to store custom feature providers.
- Resolved `FeatureProvidersKey` from properties to populate `_featureProviders`.
- Updated `DefaultLambdaHostContext` creation to pass `_featureProviders` to `Create` method.
…lectionFactory`

- Deleted `IFeatureCollectionFactory.Create()` method that accepts no parameters.
- Simplified `DefaultFeatureCollectionFactory` by removing unused functionality.
- Replaced internal field initialization with constructor parameter assignment.
- Removed null-checking and filtering logic as it's no longer necessary.
- Updated `Create` method to use the constructor-initialized `providers`.
…xtensions`

- Introduced `FeatureProvidersKey` constant to store feature providers in application properties.
- Added logic to resolve and assign event and response feature providers to the application.
- Removed redundant `BuildInterceptor` method and associated feature provider registrations.
…ature providers

- Added logic to merge existing feature providers with new ones in `application.Properties`.
- Updated imports to include `System.Collections.Generic` and `System.Linq`.
…` invocations

- Deleted `MultipleMethodCalls` diagnostic descriptor (`LH0001`) and its related validation logic.
- Removed associated entry from `AnalyzerReleases.Unshipped.md`.
- Updated `AnalyzerReleases.Shipped.md` with a comment for the released diagnostics tracking.
…rSyntaxProvider`

- Removed unnecessary "Handle" argument from `HandlerInfoExtractor.Predicate` invocation.
- Added `README.md` for `AwsLambda.Host.SourceGenerators` with notes about release tracking files.
- Updated `AnalyzerReleases.Shipped.md` to remove unnecessary comment.
- Introduced new `UseOpenTelemetryTracing` extension to enable tracing for Lambda events.
- Added dependency on `OpenTelemetry.Instrumentation.AWSLambda` and updated service resolution logic.
- Deprecated old `UseOpenTelemetryTracing` method, renamed to `UseOpenTelemetryTracing_old`.
- Refactored `MapHandlerSources.Generate` to allow multiple `MapHandler` calls with distinct signatures.
- Updated template logic to iterate through multiple handler calls and generate interceptors.
- Simplified `BuildHandlerParameterAssignment` by converting to an expression-bodied method.
- Removed unused `MapHandlerInvocationInfo` filtering logic in `LambdaHostOutputGenerator`.
- Disabled OpenTelemetry tracing generation due to incompatible mapping logic.
…neration

- Added a check to skip source generation if any diagnostic has `DiagnosticSeverity.Error`.
- Modified `MapHandlerSources.Generate` logic to ensure source is only generated when handlers exist.
…nse handling

- Introduced `IsEventFeatureRequired` and `IsResponseFeatureRequired` flags in `MapHandlerSources`.
- Updated template logic to use the new flags for determining feature provider inclusion.
…andler templates

- Replaced `FeatureProvidersKey` with specific keys for event and response feature providers.
- Updated template logic to add feature providers only when not already registered in properties.
- Removed redundant merging logic for feature providers in the application properties.
- Removed unnecessary async lambda wrapping for `TraceAsync` method.
- Updated `UseOpenTelemetryTracing` logic to improve readability and eliminate redundant code.
…ve flexibility

- Added `CreateFeatureProviders` method for cleaner feature provider initialization logic.
- Replaced `FeatureProvidersKey` with `EventFeatureProviderKey` and `ResponseFeatureProviderKey`.
- Updated `LambdaHostContextFactory` to use arrays for feature providers instead of `IEnumerable`.
- Simplified feature provider resolution using specific keys in `LambdaHostContextFactory`.
…aHostContextFactory`

- Extracted repeating logic for feature provider addition into `AddIfPresent` helper method.
- Removed unnecessary `#region` and `#endregion` directives for a cleaner code structure.
- Adjusted various formatting options for C#, XML, and other languages.
- Enabled or refined properties like `OptimizeImports`, `Rearrange`, and wrapping behavior.
- Synced cleanup profiles for improved consistency across the project.
- Deleted `LambdaOpenTelemetryAdapters` and associated extensions for unused tracing logic.
- Removed related unit tests in `LambdaOpenTelemetryServiceProviderExtensionsTests`.
- Streamlined `UseOpenTelemetryTracing` by simplifying middleware definition.
- Eliminated outdated `UseOpenTelemetryTracing_old` with replaced new middleware strategy.
…dleware

- Added comprehensive unit tests to validate `UseOpenTelemetryTracing` behavior:
  - Ensures `ArgumentNullException` is thrown for null invocation builder.
  - Verifies `InvalidOperationException` is thrown when no `TracerProvider` is registered.
  - Confirms proper middleware registration and builder return behavior.
  - Tests middleware execution flow, ensuring the next delegate is invoked correctly.
- Improves test coverage for OpenTelemetry middleware in AWS Lambda scenarios.
…hots

- Deleted OpenTelemetry-related unit tests in `OtelEnabledVerifyTests`.
- Removed OpenTelemetry-generated snapshot files from `SourceGenerators.UnitTests`.
- Updated `GeneratorTestHelpers` to remove OpenTelemetry references from metadata setup.
…ure provider handling

- Replaced `BuildInterceptor` methods with refined `MapHandler aInvokerceptor0` for key consistency.
- Introduced `EventFeatureProviderKey` & `ResponseFeatureProviderKey`,
  Execution dynamically setups feature providers into application properties.
- Updated handling of application properties to prevent duplicating feature resolution or additions.
- Adjusted template test logic to reflect event-response processing adjustments. `Simplify` .
- Refactored `MapHandler` to use `Request` and `Response` records for structured input-output.
- Improved response with a timestamped message using `DateTime.Utcreduce verbosity`.
- Removed redundant `#region` directives for cleaner code structure.
…emplate

- Deleted unused `AwsLambda.Host.Core` import in `GenericHandler.scriban`.
- Simplified the generated output by cleaning up unnecessary using directives.
…ency

- Reordered OnShutdown interceptor generation to align with OnInit generator placement.
- Improved code readability by maintaining consistent section grouping for interceptors.
…eature provider handling

- Updated `Create` assertion to ensure `featureCollectionFactory` receives `IEnumerable<IFeatureProvider>`.
…se Theory and AutoNSubstituteData

- Replaced Fact with Theory and AutoNSubstituteData for parameterization.
- Updated Create tests to accept IEnumerable<IFeatureProvider> dependencies.
- Ensured improved test coverage with consistent dependency injection handling.
…ervices count

- Changed `InlineData` value from 11 to 13 in `AddLambdaHostCoreServices_RegistersExactlyNServices`.
- Updated test to reflect the updated number of registered services.
@j-d-ha j-d-ha changed the title feat(lambda-host): support multiple MapHandler invocations with custom feature providers feat(source-generators): support multiple MapHandler invocations with custom feature providers Dec 3, 2025
…ation

- Added a detailed section on `ILambdaHostContext` type-safe feature access methods.
- Documented the usage of nullable, try-pattern, and required methods for event/response handling.
- Included examples, method descriptions, and usage scenarios for clarity.
- Enhanced readability and understanding of available middleware utilities.
- Improved documentation on `UseOpenTelemetryTracing()` middleware for Lambda invocation pipeline.
- Explained dynamic event/response handling using `IEventFeature` and `IResponseFeature`.
- Described interoperability with multiple handlers and various AWS Lambda event source types.
- Clarified shutdown helpers' function for forcing telemetry flush during environment freeze.
- Updated documentation to detail scenarios with multiple `MapHandler` calls in the same codebase.
- Added a new "Multiple MapHandler Calls" section with examples and best practices.
- Explained design patterns for library-provided handlers and conditional handler registration.
- Clarified runtime behavior when multiple handlers are registered, including exceptions thrown.
@j-d-ha
j-d-ha requested a review from ncipollina December 3, 2025 21:19
…lity

- Removed redundant #region and #endregion directives across multiple files.
- Simplified code structure to enhance maintainability and visual clarity.
@j-d-ha
j-d-ha marked this pull request as ready for review December 3, 2025 23:08
@github-actions github-actions Bot added breaking-change Introduces a breaking change type: feat New feature labels Dec 4, 2025
@j-d-ha j-d-ha removed the breaking-change Introduces a breaking change label Dec 4, 2025
@j-d-ha

j-d-ha commented Dec 4, 2025

Copy link
Copy Markdown
Collaborator Author

@codex review

@codecov

codecov Bot commented Dec 4, 2025

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.03846% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...OpenTelemetry/MiddlewareOpenTelemetryExtensions.cs 93.75% 0 Missing and 1 partial ⚠️

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #214      +/-   ##
==========================================
- Coverage   90.92%   88.91%   -2.02%     
==========================================
  Files         102      105       +3     
  Lines        2227     2256      +29     
  Branches      252      255       +3     
==========================================
- Hits         2025     2006      -19     
- Misses        109      158      +49     
+ Partials       93       92       -1     
Files with missing lines Coverage Δ
....Host.OpenTelemetry/LambdaOpenTelemetryAdapters.cs 100.00% <ø> (ø)
...ourceGenerators/Diagnostics/DiagnosticGenerator.cs 94.73% <ø> (+0.98%) ⬆️
...a.Host.SourceGenerators/Diagnostics/Diagnostics.cs 100.00% <ø> (ø)
...tors/OutputGenerators/LambdaHostOutputGenerator.cs 100.00% <100.00%> (ø)
...ceGenerators/OutputGenerators/MapHandlerSources.cs 97.93% <100.00%> (+0.60%) ⬆️
...rators/SyntaxProviders/MapHandlerSyntaxProvider.cs 100.00% <100.00%> (ø)
.../Builder/Extensions/ServiceCollectionExtensions.cs 100.00% <100.00%> (ø)
.../AwsLambda.Host/Builder/LambdaInvocationBuilder.cs 100.00% <ø> (ø)
...mbda.Host/Core/Context/LambdaHostContextFactory.cs 100.00% <100.00%> (ø)
....Host/Core/Features/DefaultEventFeatureProvider.cs 100.00% <100.00%> (ø)
... and 5 more

... and 6 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 2269d42...197243e. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/AwsLambda.Host.SourceGenerators/Templates/MapHandler.scriban
Comment thread src/AwsLambda.Host.SourceGenerators/Templates/MapHandler.scriban
j-d-ha and others added 7 commits December 3, 2025 19:42
…textFactory

- Updated `AddIfPresent` method to use `List<IFeatureProvider>` instead of `ICollection<IFeatureProvider>`.
- Improves clarity and ensures compatibility with existing method usage.
…ambdaHostContextFactory

- Added a test to validate `Create` method retrieves features from properties.
- Ensured `featureCollectionFactory` correctly receives the expected feature providers.
- Added tests for `ResponseFeatureProviderFactory` to validate the `Create` method.
  - Ensured it returns a `DefaultResponseFeatureProvider<T>`.
  - Verified it implements `IFeatureProvider`.
- Added tests for `EventFeatureProviderFactory` to validate the `Create` method.
  - Ensured it returns a `DefaultEventFeatureProvider<T>`.
  - Verified it implements `IFeatureProvider`.
- Removed a repetitive section detailing middleware's seamless support for multiple event/response types.
- Streamlined the documentation to improve clarity and focus on core OpenTelemetry features.
- Adjusted column alignment for better readability in type-safe feature methods table.
- Ensured consistent spacing and formatting across all method descriptions.
@sonarqubecloud

sonarqubecloud Bot commented Dec 4, 2025

Copy link
Copy Markdown

@j-d-ha
j-d-ha merged commit dfa5ce3 into main Dec 4, 2025
10 checks passed
@j-d-ha
j-d-ha deleted the feature/#189-support-multiple-map-handler branch December 4, 2025 22:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: feat New feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(host): support multiple map handler implementations via source generation

1 participant