refactor(core): refactor lambda application and builder#163
Merged
j-d-ha merged 164 commits intoNov 23, 2025
Conversation
- Introduced `IFeatureCollection` for feature management in lambda handlers. - Added `ILambdaHandlerBuilder` to configure handler pipelines and features. - Implemented `ILambdaOnShutdownBuilder` for shutdown event handling. - Added `ILambdaOnInitBuilder` for initialization event handling.
…ensing - Added `FeatureCollection` implementation for feature management in AWS Lambda hosting. - Updated `IFeatureCollection` with additional methods for feature access and setting. - Included `THIRD-PARTY-LICENSES.txt` referencing azure-functions-dotnet-worker under MIT License.
- Introduced `LambdaHostedServiceOptions` to manage lambda lifecycle configuration. - Added properties for `ConfigureHandlerBuilder`, `ConfigureOnInitBuilder`, and `ConfigureOnShutdownBuilder`. - Updated solution with `THIRD-PARTY-LICENSES.txt` inclusion.
…terfaces - Updated method signatures to use `ILambdaHandlerBuilder`, `ILambdaOnInitBuilder`, and `ILambdaOnShutdownBuilder`. - Adjusted related return types and parameters in extensions for consistency with the builder pattern. - Replaced application shutdown registration with direct addition to `ShutdownHandlers`. - Enhanced clarity and alignment with builder pattern refinements.
- Updated `ILambdaHandlerBuilderFactory`, `ILambdaOnInitBuilderFactory`, and `ILambdaOnShutdownBuilderFactory` to be internal for improved encapsulation. - Ensured compatibility with builder pattern refinements and previous lifecycle management updates.
- Added `[Obsolete]` attribute to `ILambdaApplication` with a deprecation message. - Indicates intent to remove the interface in future updates.
…uilder` - Renamed `ILambdaHandlerBuilder` and related classes to `ILambdaInvocationBuilder` for clarity. - Updated method signatures, properties, and factory methods across host and pipeline. - Ensured consistent naming in extensions, middleware, and hosted service options.
…ce access - Added support for default OnInit handlers when `ClearLambdaOutputFormatting` is enabled. - Introduced properties for accessing core services like `Configuration`, `Environment`, `Lifetime`, and `Logger`. - Ensured fallback to `NullLogger` when no logger factory is available.
…tionBuilderFactory` - Updated class and interface naming for improved clarity and consistency. - Adjusted related references in the codebase accordingly.
…ambdaApplication` - Added support for `ILambdaInvocationBuilder`, `ILambdaOnInitBuilder`, and `ILambdaOnShutdownBuilder` in `LambdaApplication`. - Updated related properties, methods, and lifecycle management to use builder pattern. - Registered core builder factories in the service collection.
…older Move builder interfaces to a dedicated Builders subfolder for better organization and discoverability of related builder types.
…ename LambdaStartupDelegate - Move LambdaInvocationDelegate, LambdaShutdownDelegate to Delegates/ subfolder - Rename LambdaStartupDelegate to LambdaInitDelegate for semantic alignment with Init lifecycle phase - Update source generators to reference new delegate names and locations
… folder Move IRequestEnvelope and IResponseEnvelope to a dedicated Envelopes subfolder for better organization of envelope-related types.
- Move IFeatureCollection to Features subfolder - Add new feature interfaces: IEventFeature, IFeatureProvider, IResponseFeature - Enhance ILambdaHostContext with feature collection support
Rename implementation classes with Default prefix to follow convention: - LambdaXxxBuilderFactory → DefaultXxxBuilderFactory (3 factories) - LambdaCancellationTokenSourceFactory → DefaultLambdaCancellationFactory - LambdaHostContext → DefaultLambdaHostContext - FeatureCollection → DefaultFeatureCollection - FeatureCollectionFactory → DefaultFeatureCollectionFactory This signals these are standard implementations, leaving room for alternatives.
Remove 'Lambda' prefix from internal factory interfaces for reduced verbosity: - ILambdaInvocationBuilderFactory → IInvocationBuilderFactory - ILambdaOnInitBuilderFactory → IOnInitBuilderFactory - ILambdaOnShutdownBuilderFactory → IOnShutdownBuilderFactory - ILambdaCancellationTokenSourceFactory → ILambdaCancellationFactory Update implementations and service registrations to use new names.
…and extensions - Update FeatureCollectionExtensions with new factory references - Extract LambdaHostContextExtensions to FeatureLambdaHostContextExtensions for better co-location - Remove old factory and extension files (consolidated into new structure)
…ndling Introduce RawInvocationData to encapsulate raw event and response streams for low-level invocation handling scenarios.
Update LambdaApplication to implement builder interfaces and use new factory interface names for invocation, init, and shutdown builders.
Update LambdaHandlerComposer to use simplified factory interface names and update related hosted service tests.
Update source generators to use new delegate names and add support for LambdaApplicationBuilder.Build() syntax generation.
Update OpenTelemetry integration to use new delegate names (LambdaInitDelegate) and simplified factory interface names. Update related unit tests.
Rename test file for DefaultLambdaCancellationFactory and update verify test snapshots for new delegate names.
Remove old file paths that have been moved/renamed as part of the refactoring of builder interfaces, delegates, envelopes, and factory implementations.
…pattern - Replace direct TimeSpan usage with Options pattern for LambdaHostOptions. - Update all test methods to initialize DefaultLambdaCancellationFactory with Options.Create. - Ensure test assertions remain consistent with updated initialization logic.
…orts - Replaced `Stream`-based handler with direct `Request` and `Response` objects for clarity. - Removed unused imports: `System.IO` and `System.Text.Json` for cleaner and more maintainable code. - Updated middleware logging messages for consistent format.
…ancements - Add examples for `UseMiddleware()` with updated context parameters (`next(context)`). - Introduce new usage examples of `OnInit()` and `OnShutdown()` with dependency injection. - Document new configuration options: `ShutdownDuration`, `ShutdownDurationBuffer`, and `ClearLambdaOutputFormatting`. - Enhance examples to reflect improved middleware handling patterns and updated APIs.
- Updated method signatures and extended descriptions for `Handle()`, `Use()`, and builder properties. - Added new sections for `ILambdaHostContext`, highlighting contextual features and extended options. - Clarified differences between `Properties` and `Items` for build-time vs invocation-scoped data. - Improved documentation on the lifecycle: initialization (`OnInit`) and shutdown (`OnShutdown`).
- Corrected and streamlined code examples for setting up OpenTelemetry with AWS Lambda. - Updated namespace usage to reflect current builder API (`AwsLambda.Host.Builder`). - Simplified resource builder and handler mapping examples for clarity and accuracy. - Replaced outdated `AddSource` configuration with a more concise `MapHandler` usage example.
…r examples - Updated SQS handler example to include batch response handling for errors in message processing. - Streamlined code to use `SQSBatchResponse` for unprocessed SQS messages. - Improved API Gateway example to align with modern builder patterns and naming conventions. - Added clarity on internal record types and updated example formatting for readability.
- Adjusted example code to use `AwsLambda.Host.Builder` namespace for consistency. - Improved clarity in example setup for dependency injection.
…tation - Updated README files across multiple components to ensure consistent line break formatting. - Applied improved readability for long method descriptions and builder flow diagrams. - Reformatted parameters and remarks sections in XML documentation for clarity. - Simplified inconsistent spacing in sample and inline code examples.
- Adjusted line breaks in XML documentation for tracing middleware description. - Reformatted ILoggerFactory configuration details for improved clarity.
…up mocks - Introduced `AutoNSubstituteDataAttribute` for automating mock setup in unit tests. - Replaced manual mock creation and initialization with `[AutoNSubstituteData]`. - Simplified test code by removing redundant `CreateMocks` utility and inline mocks setup. - Updated tests to use `Theory` instead of `Fact` for parameterized test cases. - Added new `AutoNSubstituteDataAttribute` and `InlineAutoNSubstituteDataAttribute` helpers.
…ect context instantiation - Removed `CreateDefaultLambdaHostContext` helper and updated tests to create context inline. - Updated public test methods to use `internal` access modifier. - Converted remaining `Fact` tests to `Theory` tests with `[AutoNSubstituteData]`. - Improved test coverage by validating constructor dependencies explicitly. - Cleaned up unused code regions and redundant comments for improved test readability.
…eter validation - Replaced `ArgumentOutOfRangeException` with `ArgumentException` for improved clarity. - Updated exception message to explicitly reference `InvocationCancellationBuffer` parameter. - Removed redundant XML documentation to streamline code readability.
…ection.Get<T>` - Merged nested `if` statements for improved readability and maintainability. - Streamlined conditional checks for `_features` retrieval and addition logic.
- Updated assertions in unit tests to use generic type overloads for improved readability. - Replaced `typeof(T)` with `.Be<T>()` for consistency across test cases.
- Replaced `ArgumentOutOfRangeException` with `ArgumentException` in test assertions.
- Introduced `CreateMocks` utility for initializing mocks in unit tests. - Replaced inline mock initialization with `CreateMocks` to simplify setup. - Added `Mocks` class to centralize mock dependencies for test cases. - Updated `Dispose` and `DisposeAsync` tests to assert proper mock disposal behavior.
…ow on multiple calls - Updated `DefaultLambdaHostContextTests` to assert that `DisposeAsync` can be called multiple times. - Ensured the test uses `Should().NotThrowAsync` for improved assertion readability.
…atic - Updated helper method to be static for clarity and to enforce non-reliance on instance state.
…ability - Replaced inline assertions with Fluent Assertions to ensure consistent test styles. - Removed redundant `StartAsync` unit test as it is no longer required. - Updated `StopAsync` and `Dispose` tests to use lambda expressions for assertions. - Changed `Dispose` tests to validate idempotency with improved assertion clarity.
…` feature extraction - Updated `TryCreate` calls in unit tests to use `out var feature` for improved readability. - Ensured consistent variable usage across test cases to enhance test clarity and maintainability.
- Standardized variable names to use PascalCase for improved readability and consistency. - Updated mocks in `LambdaApplicationTests` to follow updated naming convention. - Ensured all `Dispose` and `DisposeAsync` tests validate consistent mock behavior.
- Updated `LambdaApplicationTests` to assert `host` parameter name with correct casing. - Ensured Fluent Assertions use consistent parameter naming format.
|
j-d-ha
deleted the
feature/#99-refactor-lambda-application-and-interfaces
branch
November 23, 2025 05:26
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.



Summary
This PR represents a major architectural refactoring of the aws-lambda-host framework, replacing the monolithic
ILambdaApplicationinterface with specialized builder interfaces (ILambdaInvocationBuilder,ILambdaOnInitBuilder,ILambdaOnShutdownBuilder) that provide clearer separation of concerns. The refactoring includes comprehensive unit tests, improved feature collection architecture, and enhanced lifecycle management.Key improvements:
Test Coverage: 67 new unit test classes with 2,000+ test cases added, covering:
Breaking Changes
1.
ILambdaApplicationRemoved (BREAKING)Removed in:
refactor(abstractions): remove ILambdaApplication and update namespacesThe
ILambdaApplicationinterface has been removed fromAwsLambda.Host.Abstractions. This interface was the previous monolithic API for all Lambda configuration.Migration:
Replace
ILambdaApplicationreferences with the appropriate specialized builder interface:ILambdaInvocationBuilderILambdaOnInitBuilderILambdaOnShutdownBuilderBefore:
After:
2. Namespace Reorganization (BREAKING)
Affected in: Multiple commits organizing features and builder types into logical namespaces
Core types have been reorganized into dedicated namespaces:
AwsLambda.Host.*AwsLambda.Host.Builder.*AwsLambda.Host.*AwsLambda.Host.Core.Features.*AwsLambda.Host.*AwsLambda.Host.Core.Context.*AwsLambda.Host.*AwsLambda.Host.Core.Options.*AwsLambda.Host.*AwsLambda.Host.Core.Runtime.*Global Usings have been added to simplify imports:
AwsLambda.Host.AbstractionsinAwsLambda.Host.Abstractions/GlobalUsings.csAwsLambda.Host.Builder,AwsLambda.Host.Core.*inAwsLambda.Host/GlobalUsings.cs3.
ILambdaCancellationFactoryMoved to Core (BREAKING)Moved in:
refactor(core): renameIOnInitBuilderFactorytoILambdaOnInitBuilderFactory``Moved from
AwsLambda.Host.Abstractions→AwsLambda.Host.Abstractions.CoreUpdate imports:
4. Handler Delegate Signatures Unchanged
Handler delegates remain compatible:
LambdaInvocationDelegate(ILambdaHostContext context) : TaskLambdaInitDelegate(IServiceProvider, CancellationToken) : Task<bool>LambdaShutdownDelegate(IServiceProvider, CancellationToken) : Task5. Builder Factory Interface Renames (BREAKING)
Renamed in:
refactor(core): rename interface names for consistencyFactory interfaces now follow a consistent naming pattern:
IInvocationBuilderFactoryILambdaInvocationBuilderFactoryIOnInitBuilderFactoryILambdaOnInitBuilderFactoryIOnShutdownBuilderFactoryILambdaOnShutdownBuilderFactoryThese are internal interfaces but if you have custom implementations, update references accordingly.
6. Feature Collection Architecture (BREAKING)
Added in:
feat(host): implement feature collection factory patternThe feature collection system has been redesigned:
IFeatureCollectionnow requires feature providersIEventFeature<T>andIResponseFeature<T>provide strongly-typed accessIFeatureProviderBefore:
After:
7. Context Extension Methods Updated (BREAKING)
Changed in:
feat(core): add GetRequiredEvent<T> and GetRequiredResponse<T> to Lambda context extensionsNew convenience methods added to
ILambdaHostContext:GetRequiredEvent<T>()– Get strongly-typed event dataGetRequiredResponse<T>()– Get strongly-typed response dataThese are extensions, so existing
context.Itemsandcontext.Propertiesaccess remain unchanged.8. OpenTelemetry Namespace Updates (BREAKING)
Changed in:
refactor(core): update namespaces in OpenTelemetry extensionsOpenTelemetry extensions now in dedicated namespace:
9. Removed Obsolete Types (BREAKING)
ILambdaLifecycleOrchestrator– Removed; functionality replaced by builder factoriesLambdaLifecycleOrchestrator– Removed; internal implementation detailLambdaApplication(old class) – Replaced with new builder-focused implementationChanges Summary
Builder Architecture
ILambdaInvocationBuilderfor handler and middleware configurationILambdaOnInitBuilderfor initialization handler managementILambdaOnShutdownBuilderfor shutdown handler managementLambdaApplicationto implement all three builder interfacesFeature Collection System
IFeatureCollectionandDefaultFeatureCollectionIFeatureProviderfor pluggable feature managementDefaultEventFeature<T>andDefaultResponseFeature<T>for strongly-typed data accessIFeatureCollectionFactoryContext and Lifecycle
ILambdaHostContextwith feature accessGetRequiredEvent<T>()andGetRequiredResponse<T>()DefaultLambdaHostContextimplementationDefaultLambdaCancellationFactoryService Integration
ServiceCollectionExtensionsfor fluent service registrationHostOptionsPostConfigurationfor options bindingCode Organization
AwsLambda.Host.BuildernamespaceAwsLambda.Host.CorenamespaceTest Coverage
Documentation
Checklist
Related Issues
Closes #99
Migration Guide
For a complete migration guide from the old API to the new builder-based architecture, see:
Notes for Reviewers
Key areas to review:
Known considerations:
ILambdaApplicationin favor of specialized builder interfaces