From 8dd3f817b13319362242416f8bd2fe65f582658a Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Mon, 26 Oct 2026 14:44:29 -0400 Subject: [PATCH 01/21] feat(examples): add MinimalLambda.Example.EventProcessor project - Created a new AWS Lambda example project for processing events. - Added project files, README, and default settings for Lambda deployment. - Integrated the new project with the solution (`MinimalLambda.sln`). --- MinimalLambda.sln | 15 +++ ...inimalLambda.Example.EventProcessor.csproj | 29 ++++ .../Program.cs | 15 +++ .../README.md | 124 ++++++++++++++++++ .../aws-lambda-tools-defaults.json | 15 +++ 5 files changed, 198 insertions(+) create mode 100644 examples/MinimalLambda.Example.EventProcessor/MinimalLambda.Example.EventProcessor.csproj create mode 100644 examples/MinimalLambda.Example.EventProcessor/Program.cs create mode 100644 examples/MinimalLambda.Example.EventProcessor/README.md create mode 100644 examples/MinimalLambda.Example.EventProcessor/aws-lambda-tools-defaults.json diff --git a/MinimalLambda.sln b/MinimalLambda.sln index 66aa3229..07685ece 100644 --- a/MinimalLambda.sln +++ b/MinimalLambda.sln @@ -105,6 +105,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MinimalLambda.Testing.UnitT EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MinimalLambda.Example.DurableExecution", "examples\MinimalLambda.Example.DurableExecution\MinimalLambda.Example.DurableExecution.csproj", "{998085AA-AEC6-45D9-9E51-26F09BD5138C}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MinimalLambda.Example.EventProcessor", "examples\MinimalLambda.Example.EventProcessor\MinimalLambda.Example.EventProcessor.csproj", "{42070274-45C6-4939-87D9-AD7E70F419F9}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -547,6 +549,18 @@ Global {998085AA-AEC6-45D9-9E51-26F09BD5138C}.Release|x64.Build.0 = Release|Any CPU {998085AA-AEC6-45D9-9E51-26F09BD5138C}.Release|x86.ActiveCfg = Release|Any CPU {998085AA-AEC6-45D9-9E51-26F09BD5138C}.Release|x86.Build.0 = Release|Any CPU + {42070274-45C6-4939-87D9-AD7E70F419F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {42070274-45C6-4939-87D9-AD7E70F419F9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {42070274-45C6-4939-87D9-AD7E70F419F9}.Debug|x64.ActiveCfg = Debug|Any CPU + {42070274-45C6-4939-87D9-AD7E70F419F9}.Debug|x64.Build.0 = Debug|Any CPU + {42070274-45C6-4939-87D9-AD7E70F419F9}.Debug|x86.ActiveCfg = Debug|Any CPU + {42070274-45C6-4939-87D9-AD7E70F419F9}.Debug|x86.Build.0 = Debug|Any CPU + {42070274-45C6-4939-87D9-AD7E70F419F9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {42070274-45C6-4939-87D9-AD7E70F419F9}.Release|Any CPU.Build.0 = Release|Any CPU + {42070274-45C6-4939-87D9-AD7E70F419F9}.Release|x64.ActiveCfg = Release|Any CPU + {42070274-45C6-4939-87D9-AD7E70F419F9}.Release|x64.Build.0 = Release|Any CPU + {42070274-45C6-4939-87D9-AD7E70F419F9}.Release|x86.ActiveCfg = Release|Any CPU + {42070274-45C6-4939-87D9-AD7E70F419F9}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -591,5 +605,6 @@ Global {A5852451-D1C2-4270-834C-BDCF03F4A9AA} = {0AB3BF05-4346-4AA6-1389-037BE0695223} {189636EE-6C05-46DB-8AEB-256F2617025C} = {D9109C8A-AFA8-49C8-A19C-381500902B4D} {998085AA-AEC6-45D9-9E51-26F09BD5138C} = {B36A84DF-456D-A817-6EDD-3EC3E7F6E11F} + {42070274-45C6-4939-87D9-AD7E70F419F9} = {B36A84DF-456D-A817-6EDD-3EC3E7F6E11F} EndGlobalSection EndGlobal diff --git a/examples/MinimalLambda.Example.EventProcessor/MinimalLambda.Example.EventProcessor.csproj b/examples/MinimalLambda.Example.EventProcessor/MinimalLambda.Example.EventProcessor.csproj new file mode 100644 index 00000000..ae2db060 --- /dev/null +++ b/examples/MinimalLambda.Example.EventProcessor/MinimalLambda.Example.EventProcessor.csproj @@ -0,0 +1,29 @@ + + + Exe + net8.0 + latest + enable + enable + true + Lambda + + true + + true + $(InterceptorsNamespaces);MinimalLambda.Generated + false + + + + + + + + + + \ No newline at end of file diff --git a/examples/MinimalLambda.Example.EventProcessor/Program.cs b/examples/MinimalLambda.Example.EventProcessor/Program.cs new file mode 100644 index 00000000..382ee3ad --- /dev/null +++ b/examples/MinimalLambda.Example.EventProcessor/Program.cs @@ -0,0 +1,15 @@ +using Microsoft.Extensions.Hosting; +using MinimalLambda.Builder; + +var builder = LambdaApplication.CreateBuilder(); + +var lambda = builder.Build(); + +// [FromEvent] binds the incoming Lambda event to the handler parameter. +lambda.MapHandler(([FromEvent] string input) => input.ToUpperInvariant()); + +// Start the Lambda runtime loop. +await lambda.RunAsync(); + +// Required so the generated test project can reference this top-level Program. +public partial class Program; diff --git a/examples/MinimalLambda.Example.EventProcessor/README.md b/examples/MinimalLambda.Example.EventProcessor/README.md new file mode 100644 index 00000000..9e156426 --- /dev/null +++ b/examples/MinimalLambda.Example.EventProcessor/README.md @@ -0,0 +1,124 @@ +# MinimalLambda.Example.EventProcessor + +MinimalLambda AWS Lambda function project. + +This starter project contains: + +- `Program.cs` - Lambda host setup and sample handler. +- `MinimalLambda.Example.EventProcessor.csproj` - .NET project configured for AWS Lambda deployment. +- `aws-lambda-tools-defaults.json` - default settings used by Visual Studio and `dotnet lambda` commands. +- `../../test/MinimalLambda.Example.EventProcessor.Tests` - integration tests using `MinimalLambda.Testing`. + +The generated handler accepts a `string` Lambda event and returns the uppercase equivalent. Replace the event type, return type, and handler body in `Program.cs` to match your Lambda trigger. + +## Prerequisites + +- .NET SDK 8.0 or later. +- AWS credentials configured locally if you plan to deploy. +- Amazon.Lambda.Tools for command-line deployment. + +Install Amazon.Lambda.Tools if needed: + +```bash +dotnet tool install -g Amazon.Lambda.Tools +``` + +Update Amazon.Lambda.Tools if already installed: + +```bash +dotnet tool update -g Amazon.Lambda.Tools +``` + +## Restore and build + +From this project directory: + +```bash +dotnet restore +dotnet build +``` + +## Run tests + +From this project directory: + +```bash +dotnet test ../../test/MinimalLambda.Example.EventProcessor.Tests/MinimalLambda.Example.EventProcessor.Tests.csproj +``` + +Or from the generated repository/folder root: + +```bash +dotnet test test/MinimalLambda.Example.EventProcessor.Tests/MinimalLambda.Example.EventProcessor.Tests.csproj +``` + +## Central Package Management + +This template emits versioned `PackageReference` items. If your repository uses Central Package Management, move those versions into `Directory.Packages.props` and remove `Version="..."` from the generated app and test project references. + +Add or update these entries at the repository root: + +```xml + + + + + + + +``` + +## Configure AWS deployment defaults + +`aws-lambda-tools-defaults.json` contains deployment defaults for `dotnet lambda` and the AWS Toolkit for Visual Studio: + +- `profile` - AWS credentials profile. +- `region` - AWS region. +- `function-runtime` - Lambda runtime. +- `function-memory-size` - memory in MB. +- `function-timeout` - timeout in seconds. +- `function-handler` - executable assembly name for this MinimalLambda app. + +You can set profile and region when creating the project: + +```bash +dotnet new mlambda -n MinimalLambda.Example.EventProcessor --profile default --region us-east-1 +``` + +Or edit `aws-lambda-tools-defaults.json` before deployment. + +## Deploy from the command line + +From this project directory: + +```bash +dotnet lambda deploy-function +``` + +The AWS Lambda .NET CLI reads `aws-lambda-tools-defaults.json` for default deployment settings and prompts for any missing values. + +Useful commands: + +```bash +dotnet lambda help +dotnet lambda list-functions +dotnet lambda invoke-function MinimalLambda.Example.EventProcessor --payload "hello world" +``` + +## Deploy from Visual Studio + +With the AWS Toolkit for Visual Studio installed: + +1. Right-click the project in Solution Explorer. +2. Select **Publish to AWS Lambda**. +3. Review values from `aws-lambda-tools-defaults.json`. +4. Publish the function. + +After deployment, use the AWS Explorer Lambda Function View to test invocations, configure event sources, update runtime configuration, and view CloudWatch logs. + +## Next steps + +- Replace the sample `string` handler with your event type. +- Register services with `builder.Services` in `Program.cs`. +- Add middleware with `lambda.UseMiddleware(...)` for logging, validation, or error handling. +- Update tests in `../../test/MinimalLambda.Example.EventProcessor.Tests` to cover your handler behavior. diff --git a/examples/MinimalLambda.Example.EventProcessor/aws-lambda-tools-defaults.json b/examples/MinimalLambda.Example.EventProcessor/aws-lambda-tools-defaults.json new file mode 100644 index 00000000..37cb089c --- /dev/null +++ b/examples/MinimalLambda.Example.EventProcessor/aws-lambda-tools-defaults.json @@ -0,0 +1,15 @@ +{ + "Information": [ + "This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.", + "To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.", + "dotnet lambda help", + "All the command line options for the Lambda command can be specified in this file." + ], + "profile": "", + "region": "", + "configuration": "Release", + "function-runtime": "dotnet8", + "function-memory-size": 512, + "function-timeout": 30, + "function-handler": "MinimalLambda.Example.EventProcessor" +} From ddf9a804b4c7a8e9f6a59e48240629fd618c3b82 Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Tue, 27 Oct 2026 12:01:06 -0400 Subject: [PATCH 02/21] docs(design): add proposal for event processor API Includes a draft for a public API to process Lambda event batches. - Defines callback signatures and type relationships for batch processing. - Outlines roles for callbacks: split, handle, onError, and createResponse. - Provides example usage and type flow for various event sources. - Describes boundaries and areas needing further decisions. --- designs/event-processor.md | 144 +++++++++++++++++++++++++++++++++++++ 1 file changed, 144 insertions(+) create mode 100644 designs/event-processor.md diff --git a/designs/event-processor.md b/designs/event-processor.md new file mode 100644 index 00000000..944e4bf6 --- /dev/null +++ b/designs/event-processor.md @@ -0,0 +1,144 @@ +# Event processor API proposal + +**Status:** Draft +**Scope:** Public API only + +## Context + +Lambda receives one event that may contain many independently processable records. SQS is the motivating case: each message may succeed or need retry, while Lambda expects one batch response containing the failed message IDs. + +`MapHandler` handles one Lambda invocation. This API adds a batch layer that splits the event, invokes one handler per item, collects results, and optionally creates the invocation response. + +## Goal + +Process each item in a Lambda event batch, optionally in parallel, and let an event-source-specific callback build the final Lambda response. + +The processor must not know SQS, Kinesis, DynamoDB Streams, or a response format. + +## API roles + +| Callback | Job | +| --- | --- | +| `split` | Turns the incoming event into source items. | +| `handle` | Processes one source item with injected services. | +| `onError` | Converts an item exception into the same result type as `handle`. | +| `createResponse` | Converts all source items and results into the Lambda response. | + +The response builder receives the original source item. It can use source-specific metadata, such as an SQS `MessageId`, without making the processor source-specific. + +## Proposed API + +```csharp +lambda.MapEventHandler( + split: (SqsEnvelope batch, ILambdaInvocationContext _) => + batch.Records, + + handle: async ( + SqsEnvelope.SqsMessageEnvelope item, + DocumentImporter importer) => + { + await importer.ImportAsync(item.BodyContent!); + return EventOutcome.Success; + }, + + onError: (item, exception, ILambdaInvocationContext _) => + EventOutcome.Retry, + + createResponse: (result, ILambdaInvocationContext _) => + new SQSBatchResponse( + result.Items + .Where(x => x.Result == EventOutcome.Retry) + .Select(x => new SQSBatchResponse.BatchItemFailure + { + ItemIdentifier = x.Item.MessageId, + }) + .ToList())); +``` + +For event sources that do not return a batch response: + +```csharp +lambda.MapEventHandler( + split: (S3Event batch, ILambdaInvocationContext _) => batch.Records, + handle: async (S3Event.S3EventNotificationRecord item, DocumentIndexer indexer) => + { + await indexer.IndexAsync(item.S3.Object.Key); + }); +``` + +## Type flow + +```text +TEvent -> IEnumerable -> TItemResult -> TResponse +``` + +```csharp +Func> split + +Func> handle + +Func onError + +Func, + ILambdaInvocationContext, + TResponse> createResponse +``` + +`TItem` is always the first handler parameter. This keeps the processed source record available to `createResponse`, including SQS `MessageId` and stream sequence numbers. + +`onError` returns the same `TItemResult` as `handle`. The response builder therefore consumes one result type. + +```csharp +public sealed record EventItemResult( + TItem Item, + TItemResult Result); + +public sealed class EventBatchResult +{ + public required IReadOnlyList> Items { get; init; } +} +``` + +## Overloads + +Provide handler overloads for zero through ten injected dependencies. The only changing part is the handler delegate: + +```csharp +Func +Func +Func +``` + +Use separate overloads when `onError` is present. Do not require callers to pass `null`. + +```csharp +MapEventHandler(split, handle, createResponse) +MapEventHandler(split, handle, onError, createResponse) +``` + +## Boundaries + +This proposal defines callback signatures and type relationships. It does not yet define: + +- how generated code resolves handler dependencies; +- concurrency, cancellation, or item-service scopes; +- logging, metrics, or exception policy; +- event-source configuration such as SQS `ReportBatchItemFailures`. + +## Static methods + +An inline lambda can infer dependency types. A static method group cannot infer generic dependency parameters from this API: + +```csharp +lambda.MapEventHandler(split, EventHandlers.HandleAsync); +``` + +Static handlers need explicit generic arguments or a typed local delegate. Decide whether that trade-off is acceptable before committing to generic dependency overloads. + +## Not decided + +- `Task` only, or `ValueTask` and synchronous handler overloads. +- Whether `onError` can be asynchronous or receive injected dependencies. +- Default behavior when `onError` is omitted. +- FIFO ordering and stop-on-failure behavior. +- Global and named `EventHandlerOptions` registration through DI. From de5e472268d8cf39e331b667f553507cea559819 Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Tue, 27 Oct 2026 19:03:13 -0400 Subject: [PATCH 03/21] feat(event-processor): prototype handler overloads --- Directory.Packages.props | 1 + designs/event-processor.md | 111 ++++++++++---- ...inimalLambda.Example.EventProcessor.csproj | 4 + .../Program.cs | 145 +++++++++++++++++- 4 files changed, 229 insertions(+), 32 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 9a91a070..c204d98d 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -13,6 +13,7 @@ + diff --git a/designs/event-processor.md b/designs/event-processor.md index 944e4bf6..4dc3c537 100644 --- a/designs/event-processor.md +++ b/designs/event-processor.md @@ -21,10 +21,10 @@ The processor must not know SQS, Kinesis, DynamoDB Streams, or a response format | --- | --- | | `split` | Turns the incoming event into source items. | | `handle` | Processes one source item with injected services. | -| `onError` | Converts an item exception into the same result type as `handle`. | -| `createResponse` | Converts all source items and results into the Lambda response. | +| `onError` | Optionally converts an item exception into a value. | +| `createResponse` | Converts collected values into the Lambda response. | -The response builder receives the original source item. It can use source-specific metadata, such as an SQS `MessageId`, without making the processor source-specific. +`onError` receives the source item. It can use source-specific metadata, such as an SQS `MessageId`, before returning a value for `createResponse`. ## Proposed API @@ -38,21 +38,16 @@ lambda.MapEventHandler( DocumentImporter importer) => { await importer.ImportAsync(item.BodyContent!); - return EventOutcome.Success; }, onError: (item, exception, ILambdaInvocationContext _) => - EventOutcome.Retry, - - createResponse: (result, ILambdaInvocationContext _) => - new SQSBatchResponse( - result.Items - .Where(x => x.Result == EventOutcome.Retry) - .Select(x => new SQSBatchResponse.BatchItemFailure - { - ItemIdentifier = x.Item.MessageId, - }) - .ToList())); + new SQSBatchResponse.BatchItemFailure + { + ItemIdentifier = item.MessageId, + }, + + createResponse: (failures, ILambdaInvocationContext _) => + new SQSBatchResponse(failures.ToList())); ``` For event sources that do not return a batch response: @@ -66,39 +61,89 @@ lambda.MapEventHandler( }); ``` +For a response after every item succeeds: + +```csharp +lambda.MapEventHandler( + split: (S3Event batch, ILambdaInvocationContext _) => batch.Records, + handle: async (S3Event.S3EventNotificationRecord item, DocumentIndexer indexer) => + { + await indexer.IndexAsync(item.S3.Object.Key); + }, + createResponse: (items, ILambdaInvocationContext _) => + new BatchSummary(items.Count())); +``` + ## Type flow +Without error mapping: + +```text +TEvent -> IEnumerable -> handle every item -> IEnumerable -> TResponse +``` + +```csharp +Func> split + +Func handle + +Func, ILambdaInvocationContext, TResponse> createResponse +``` + +If a handler throws, `createResponse` is not called. + +With error mapping: + ```text -TEvent -> IEnumerable -> TItemResult -> TResponse +TEvent -> IEnumerable -> TFailure -> TResponse ``` ```csharp Func> split -Func> handle +Func handle -Func onError +Func onError -Func, +Func, ILambdaInvocationContext, TResponse> createResponse ``` -`TItem` is always the first handler parameter. This keeps the processed source record available to `createResponse`, including SQS `MessageId` and stream sequence numbers. +`TItem` is always the first handler parameter. This keeps the processed source record available to `onError`. + +`TFailure` can be any type. SQS may return `SQSBatchResponse.BatchItemFailure`; another source may return an identifier, an error record, or a custom type. `createResponse` receives the collected failures only. + +## Unified item results + +When both `handle` and `onError` produce values for one response builder, they must return the same type: + +```csharp +Func> handle + +Func onError + +Func, ILambdaInvocationContext, TResponse> createResponse +``` + +```text +TEvent -> IEnumerable -> TResult -> IEnumerable -> TResponse +``` + +If `handle` returns `Task` or no value, it does not contribute a result to `createResponse`. The SQS failure example above uses this shape: only `onError` returns `TFailure`. -`onError` returns the same `TItemResult` as `handle`. The response builder therefore consumes one result type. +If success and failure need different data, use one shared union type for `TResult`: ```csharp -public sealed record EventItemResult( - TItem Item, - TItemResult Result); - -public sealed class EventBatchResult -{ - public required IReadOnlyList> Items { get; init; } -} +public abstract record ImportItemResult; + +public sealed record Imported(ImportResult Value) : ImportItemResult; + +public sealed record Retry(SQSBatchResponse.BatchItemFailure Value) : ImportItemResult; ``` +`handle` returns `Imported`, `onError` returns `Retry`, and `createResponse` accepts `IEnumerable`. + ## Overloads Provide handler overloads for zero through ten injected dependencies. The only changing part is the handler delegate: @@ -109,13 +154,19 @@ Func Func ``` -Use separate overloads when `onError` is present. Do not require callers to pass `null`. +Use separate overloads for each meaningful callback combination. Do not require callers to pass `null`. ```csharp +MapEventHandler(split, handle) +MapEventHandler(split, handle, onError) MapEventHandler(split, handle, createResponse) MapEventHandler(split, handle, onError, createResponse) ``` +`onError` without `createResponse` is an error observer and returns `Task`. The processor invokes it before following the default error policy. + +The response-only overload receives successful source items. The error-and-response overload receives failure values when `handle` has no result. When both callbacks return values, the builder receives their shared result type. + ## Boundaries This proposal defines callback signatures and type relationships. It does not yet define: diff --git a/examples/MinimalLambda.Example.EventProcessor/MinimalLambda.Example.EventProcessor.csproj b/examples/MinimalLambda.Example.EventProcessor/MinimalLambda.Example.EventProcessor.csproj index ae2db060..3c990c69 100644 --- a/examples/MinimalLambda.Example.EventProcessor/MinimalLambda.Example.EventProcessor.csproj +++ b/examples/MinimalLambda.Example.EventProcessor/MinimalLambda.Example.EventProcessor.csproj @@ -26,4 +26,8 @@ + + + + \ No newline at end of file diff --git a/examples/MinimalLambda.Example.EventProcessor/Program.cs b/examples/MinimalLambda.Example.EventProcessor/Program.cs index 382ee3ad..fc7ae8b4 100644 --- a/examples/MinimalLambda.Example.EventProcessor/Program.cs +++ b/examples/MinimalLambda.Example.EventProcessor/Program.cs @@ -1,15 +1,156 @@ +using Amazon.Lambda.S3Events; using Microsoft.Extensions.Hosting; +using MinimalLambda; using MinimalLambda.Builder; +using MinimalLambda.Envelopes.Sqs; var builder = LambdaApplication.CreateBuilder(); var lambda = builder.Build(); -// [FromEvent] binds the incoming Lambda event to the handler parameter. -lambda.MapHandler(([FromEvent] string input) => input.ToUpperInvariant()); +// No per-item result or Lambda response. +lambda.MapEventHandler( + (S3Event input, ILambdaInvocationContext _) => input.Records, + (S3Event.S3EventNotificationRecord item) => Task.CompletedTask); + +// One injected dependency. The splitter's TItem is the handler's first parameter. +lambda.MapEventHandler( + (S3Event input, ILambdaInvocationContext _) => input.Records, + (S3Event.S3EventNotificationRecord item, MyService service) => + { + service.DoStuff(item.S3.Object.Key); + return Task.CompletedTask; + }); + +// Two injected dependencies. The item remains the first handler parameter. +lambda.MapEventHandler( + (S3Event input, ILambdaInvocationContext _) => input.Records, + EventHandlers.HandleS3RecordAsync); + +// A per-item result and a typed batch response. +lambda.MapEventHandler( + (SqsEnvelope input, ILambdaInvocationContext _) => input.Records, + (SqsEnvelope.SqsMessageEnvelope item, MyService service) => + { + service.DoStuff(item.BodyContent?.Message ?? string.Empty); + return Task.FromResult(EventOutcome.Success); + }, + (result, _) + => new ExampleResponse( + result + .Items + .Where(item => item.Result == EventOutcome.Retry) + .Select(item => item.Item.MessageId) + .ToList())); + +// The error interceptor returns the same TItemResult as the item handler. +lambda.MapEventHandler( + (SqsEnvelope input, ILambdaInvocationContext _) => input.Records, + (SqsEnvelope.SqsMessageEnvelope item, MyService service) => + { + service.DoStuff(item.BodyContent?.Message ?? string.Empty); + return Task.FromResult(EventOutcome.Success); + }, + ( _, _, _) + => EventOutcome.Retry, + (result, _) + => new ExampleResponse( + result + .Items + .Where(item => item.Result == EventOutcome.Retry) + .Select(item => item.Item.MessageId) + .ToList())); // Start the Lambda runtime loop. await lambda.RunAsync(); +public record MyEvent(string Message); + +public enum EventOutcome +{ + Success, + Retry, +} + +public sealed record EventItemResult(TItem Item, TItemResult Result); + +public sealed class EventBatchResult +{ + public IReadOnlyList> Items { get; } = []; +} + +public sealed record ExampleResponse(IReadOnlyList RetryMessageIds); + // Required so the generated test project can reference this top-level Program. public partial class Program; + +public static class Extension +{ + extension(LambdaApplication lambda) + { + public LambdaApplication MapEventHandler( + Func> split, + Func handle, + EventHandlerOptions? options = null) + => lambda; + + public LambdaApplication MapEventHandler( + Func> split, + Func handle, + EventHandlerOptions? options = null) + => lambda; + + public LambdaApplication MapEventHandler( + Func> split, + Func handle, + EventHandlerOptions? options = null) + => lambda; + + public LambdaApplication + MapEventHandler( + Func> split, + Func> handle, + Func, ILambdaInvocationContext, TResponse> + createResponse, + EventHandlerOptions? options = null) + => lambda; + + public LambdaApplication + MapEventHandler( + Func> split, + Func> handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> + createResponse, + EventHandlerOptions? options = null) + => lambda; + } +} + +public sealed class EventHandlerOptions +{ + public int MaxConcurrentExecutions { get; init; } = 10; +} + +public class MyService +{ + public void DoStuff(string input) { } +} + +public class MyOtherService +{ + public void DoStuff(string input) { } +} + +public static class EventHandlers +{ + public static Task HandleS3RecordAsync( + S3Event.S3EventNotificationRecord item, + MyService service, + MyOtherService otherService) + { + service.DoStuff(item.S3.Object.Key); + otherService.DoStuff(item.EventName); + return Task.CompletedTask; + } +} From 5c89497fbe6b85a06c36656f3dfac7609aee795e Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Wed, 28 Oct 2026 16:11:20 -0400 Subject: [PATCH 04/21] feat(event-processor): add MapEventHandler API, generator, and runtime Add a batch event processor that splits one Lambda event into items, runs one asynchronous dependency-injection scope per item, and builds one response from completed contributions. - 55 MapEventHandler overloads: the N1/N2/N3 no-result and R1/R2 result families at arities 0-10 (TD0-TD9) after the item. - IEventProcessingContext exposes the item-first processing token plus StopProcessing and CancelProcessing, which block new admissions and drain admitted work. - EventHandlerOptions enables concurrency by default with a cap of 10, is captured at registration, and is validated before any callback runs. - The source generator discovers MapEventHandler calls, resolves handler parameters (item, invocation/Lambda context, processing context, cancellation token, DI, keyed services), and emits file-local interceptors, adapters, and a bounded worker runtime. Diagnostics LH0008-LH0011 cover unsupported signatures, bindings, unresolved handlers, and discarded results. Responses receive only completed contributions in source order; the processor fabricates nothing and never retries omitted items. Registration consumes the existing single invocation handler slot, so a second executed mapping throws. --- .../Core/IEventProcessingContext.cs | 56 + .../AnalyzerReleases.Unshipped.md | 4 + .../Diagnostics/Diagnostics.cs | 32 + .../Emitters/EventHandlerEmitter.cs | 30 + .../Extensions/ParameterSymbolExtensions.cs | 25 +- .../MinimalLambdaGenerator.cs | 7 + .../Models/Handlers/EventHandlerMethodInfo.cs | 737 ++++++++ .../Handlers/EventHandlerParameterInfo.cs | 24 + .../Models/Handlers/MethodType.cs | 1 + .../Models/Shared/ParameterSource.cs | 1 + .../SyntaxProviders/HandlerSyntaxProvider.cs | 20 +- .../Templates/MapEventHandler.scriban | 654 +++++++ .../WellKnownTypes/WellKnownTypeData.cs | 2 + .../Extensions/ServiceCollectionExtensions.cs | 5 + ...EventHandlerLambdaApplicationExtensions.cs | 1562 +++++++++++++++++ .../Core/Options/EventHandlerOptions.cs | 34 + .../Options/EventHandlerOptionsValidator.cs | 16 + 17 files changed, 3200 insertions(+), 10 deletions(-) create mode 100644 src/MinimalLambda.Abstractions/Core/IEventProcessingContext.cs create mode 100644 src/MinimalLambda.SourceGenerators/Emitters/EventHandlerEmitter.cs create mode 100644 src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs create mode 100644 src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerParameterInfo.cs create mode 100644 src/MinimalLambda.SourceGenerators/Templates/MapEventHandler.scriban create mode 100644 src/MinimalLambda/Builder/InterceptionTargets/MapEventHandlerLambdaApplicationExtensions.cs create mode 100644 src/MinimalLambda/Core/Options/EventHandlerOptions.cs create mode 100644 src/MinimalLambda/Core/Options/EventHandlerOptionsValidator.cs diff --git a/src/MinimalLambda.Abstractions/Core/IEventProcessingContext.cs b/src/MinimalLambda.Abstractions/Core/IEventProcessingContext.cs new file mode 100644 index 00000000..e4a08d01 --- /dev/null +++ b/src/MinimalLambda.Abstractions/Core/IEventProcessingContext.cs @@ -0,0 +1,56 @@ +namespace MinimalLambda; + +/// +/// Provides processing controls and cancellation state for one event-processor invocation. +/// +/// +/// +/// There is one processing context per processor invocation. Item handlers and error mappers +/// share it. It is injected as a framework parameter, not resolved from dependency injection, +/// and must not be retained beyond its owning invocation. +/// +/// +/// prevents new items from being admitted while admitted work +/// finishes normally. also stops admissions and signals +/// so admitted handlers can observe cooperative cancellation. +/// Both operations are thread-safe and idempotent. Stopping can be escalated to cancellation; +/// cancellation cannot be reversed. +/// +/// +/// Cancellation is cooperative. Neither operation forcibly interrupts a running handler, +/// undoes side effects, or guarantees that an active handler stops. Already completed results +/// are retained and passed to the response builder. +/// +/// +public interface IEventProcessingContext +{ + /// Gets the original Lambda invocation context. + ILambdaInvocationContext Invocation { get; } + + /// + /// Gets the token that links the invocation cancellation token with + /// requests made during handling. + /// + /// + /// Handlers receive this token through a + /// parameter. Use to observe the original invocation token. + /// + CancellationToken CancellationToken { get; } + + /// Stops admitting new source items while admitted work finishes normally. + /// + /// This method does not signal and does not fail the + /// invocation. Calling it after processing has completed has no effect. + /// + void StopProcessing(); + + /// + /// Stops admitting new source items and signals so admitted + /// handlers can cancel cooperatively. + /// + /// + /// Admitted handlers, cancellation callbacks, and scope disposal are drained before the + /// response is built. Calling this method after processing has completed has no effect. + /// + void CancelProcessing(); +} diff --git a/src/MinimalLambda.SourceGenerators/AnalyzerReleases.Unshipped.md b/src/MinimalLambda.SourceGenerators/AnalyzerReleases.Unshipped.md index db90d506..420cebd1 100644 --- a/src/MinimalLambda.SourceGenerators/AnalyzerReleases.Unshipped.md +++ b/src/MinimalLambda.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -3,3 +3,7 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------ LH0007 | MinimalLambda.Usage | Error | Durable handler signature diagnostics +LH0008 | MinimalLambda.Usage | Error | Event handler signature diagnostics +LH0009 | MinimalLambda.Usage | Error | Event handler binding diagnostics +LH0010 | MinimalLambda.Usage | Error | Event handler discovery diagnostics +LH0011 | MinimalLambda.Usage | Error | Discarded event handler result diagnostics diff --git a/src/MinimalLambda.SourceGenerators/Diagnostics/Diagnostics.cs b/src/MinimalLambda.SourceGenerators/Diagnostics/Diagnostics.cs index dd7fb923..66062e91 100644 --- a/src/MinimalLambda.SourceGenerators/Diagnostics/Diagnostics.cs +++ b/src/MinimalLambda.SourceGenerators/Diagnostics/Diagnostics.cs @@ -57,4 +57,36 @@ internal static class Diagnostics UsageCategory, DiagnosticSeverity.Error, true); + + internal static readonly DiagnosticDescriptor UnsupportedEventHandlerSignature = new( + "LH0008", + "Unsupported event handler signature", + "Event handler signature component '{0}' is not supported; use an item-first asynchronous handler returning Task or Task, value parameters, and types accessible to generated adapter code.", + UsageCategory, + DiagnosticSeverity.Error, + true); + + internal static readonly DiagnosticDescriptor UnsupportedEventHandlerBinding = new( + "LH0009", + "Unsupported event handler binding", + "Event handler binding '{0}' is not supported; the first parameter is the source item, and framework context or cancellation-token parameters cannot use service or event attributes.", + UsageCategory, + DiagnosticSeverity.Error, + true); + + internal static readonly DiagnosticDescriptor UnresolvedEventHandler = new( + "LH0010", + "Unresolved event handler", + "The event handler '{0}' cannot be resolved to a single analyzable method; use an explicitly typed lambda, a typed delegate local with one initialization, or an explicit method group.", + UsageCategory, + DiagnosticSeverity.Error, + true); + + internal static readonly DiagnosticDescriptor DiscardedEventHandlerResult = new( + "LH0011", + "Discarded event handler result", + "The event handler '{0}' returns a result but is bound to a no-result overload; use a result overload with a response builder or wrap the handler so it intentionally returns Task.", + UsageCategory, + DiagnosticSeverity.Error, + true); } diff --git a/src/MinimalLambda.SourceGenerators/Emitters/EventHandlerEmitter.cs b/src/MinimalLambda.SourceGenerators/Emitters/EventHandlerEmitter.cs new file mode 100644 index 00000000..89490352 --- /dev/null +++ b/src/MinimalLambda.SourceGenerators/Emitters/EventHandlerEmitter.cs @@ -0,0 +1,30 @@ +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis; +using MinimalLambda.SourceGenerators.Models; + +namespace MinimalLambda.SourceGenerators.Emitters; + +internal static class EventHandlerEmitter +{ + private const string TemplateFile = "Templates/MapEventHandler.scriban"; + + internal static void Emit( + SourceProductionContext context, + ImmutableArray infos) + { + if (infos.Length == 0) + return; + + var ordered = infos + .OrderBy(info => info.MapCallLocation.FilePath, System.StringComparer.Ordinal) + .ThenBy(info => info.SourceSpanStart) + .ToImmutableArray(); + + var code = TemplateHelper.Render( + TemplateFile, + new { TemplateHelper.GeneratedCodeAttribute, EventHandlerCalls = ordered }); + + context.AddSource("MinimalLambda.EventHandlers.g.cs", code); + } +} diff --git a/src/MinimalLambda.SourceGenerators/Extensions/ParameterSymbolExtensions.cs b/src/MinimalLambda.SourceGenerators/Extensions/ParameterSymbolExtensions.cs index ca5e04f8..8c361c2a 100644 --- a/src/MinimalLambda.SourceGenerators/Extensions/ParameterSymbolExtensions.cs +++ b/src/MinimalLambda.SourceGenerators/Extensions/ParameterSymbolExtensions.cs @@ -30,7 +30,8 @@ internal bool IsFromEvent(GeneratorContext context) => WellKnownType.MinimalLambda_Builder_FromEventAttribute)); internal DiagnosticResult<(string Assignment, string? Key)> GetDiParameterAssignment( - GeneratorContext context) + GeneratorContext context, + string serviceProviderExpression = "context.ServiceProvider") { var paramType = parameterSymbol.Type.QualifiedNullableName; @@ -43,16 +44,30 @@ internal bool IsFromEvent(GeneratorContext context) => result.IsKeyed ? ( isRequired - ? $"context.ServiceProvider.GetKeyedService<{paramType}>({result.Key})" - : $"context.ServiceProvider.GetRequiredKeyedService<{paramType}>({result.Key})", + ? $"{serviceProviderExpression}.GetKeyedService<{paramType}>({result.Key})" + : $"{serviceProviderExpression}.GetRequiredKeyedService<{paramType}>({result.Key})", result.Key) : ( isRequired - ? $"context.ServiceProvider.GetService<{paramType}>()" - : $"context.ServiceProvider.GetRequiredService<{paramType}>()", + ? $"{serviceProviderExpression}.GetService<{paramType}>()" + : $"{serviceProviderExpression}.GetRequiredService<{paramType}>()", null)); } + internal bool IsServiceBindingAttribute(GeneratorContext context) => + parameterSymbol + .GetAttributes() + .Any(attribute => + attribute.AttributeClass is not null + && context.WellKnownTypes.IsType( + attribute.AttributeClass, + WellKnownType.MinimalLambda_Builder_FromServicesAttribute, + WellKnownType.MinimalLambda_Builder_FromArgumentsAttribute, + WellKnownType + .Microsoft_Extensions_DependencyInjection_FromKeyedServicesAttribute) + || attribute.AttributeClass?.ToDisplayString() + == "Microsoft.Extensions.DependencyInjection.FromServicesAttribute"); + private DiagnosticResult<(bool IsKeyed, string? Key)> IsFromKeyedService(GeneratorContext context) => parameterSymbol diff --git a/src/MinimalLambda.SourceGenerators/MinimalLambdaGenerator.cs b/src/MinimalLambda.SourceGenerators/MinimalLambdaGenerator.cs index 47b7c5a5..e3bb68d6 100644 --- a/src/MinimalLambda.SourceGenerators/MinimalLambdaGenerator.cs +++ b/src/MinimalLambda.SourceGenerators/MinimalLambdaGenerator.cs @@ -54,6 +54,12 @@ compilation is CSharpCompilation .Where(static c => c is DurableMethodInfo) .Select(static (c, _) => (DurableMethodInfo)c); + var eventHandlerCalls = registrationCalls + .WhereNoErrors() + .Where(static c => c is EventHandlerMethodInfo) + .Select(static (c, _) => (EventHandlerMethodInfo)c) + .Collect(); + var validDurableHandlerCalls = durableHandlerModels.WhereNoErrors().Collect(); var onInitHandlerCalls = registrationCalls @@ -84,6 +90,7 @@ compilation is CSharpCompilation (ctx, call) => call.DiagnosticInfos.ForEach(d => d.ReportDiagnostic(ctx))); context.RegisterSourceOutput(invocationHandlerCalls, InvocationHandlerEmitter.Emit); + context.RegisterSourceOutput(eventHandlerCalls, EventHandlerEmitter.Emit); context.RegisterSourceOutput(validDurableHandlerCalls, DurableHandlerEmitter.Emit); context.RegisterSourceOutput(onInitHandlerCalls, LifecycleHandlerEmitter.Emit); context.RegisterSourceOutput(onShutdownHandlerCalls, LifecycleHandlerEmitter.Emit); diff --git a/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs new file mode 100644 index 00000000..67775a67 --- /dev/null +++ b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs @@ -0,0 +1,737 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using LayeredCraft.SourceGeneratorTools.Types; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Operations; +using MinimalLambda.SourceGenerators.Extensions; +using WellKnownType = MinimalLambda.SourceGenerators.WellKnownTypes.WellKnownTypeData.WellKnownType; + +namespace MinimalLambda.SourceGenerators.Models; + +internal enum EventHandlerFamily +{ + N1, + N2, + N3, + R1, + R2, +} + +internal record EventHandlerCallbackInfo(string Name, string Type); + +internal record EventHandlerMethodInfo( + string InterceptableLocationAttribute, + EquatableArray CallbackParameters, + EventHandlerFamily Family, + bool HasResponse, + bool HasOnError, + bool CollectsValues, + bool CollectsSourceItems, + bool CollectsMappedFailures, + bool HandleReturnsResult, + string EventType, + string ItemType, + string CollectedType, + string ValueType, + string? ResponseType, + EquatableArray HandlerParameters, + string HandlerArguments, + bool HasAnyFromKeyedServices, + LocationInfo MapCallLocation, + LocationInfo HandlerArgumentLocation, + int TreeOrdinal, + int SourceSpanStart, + EquatableArray DiagnosticInfos, + MethodType MethodType = MethodType.MapEventHandler) : IMethodInfo; + +internal static class EventHandlerMethodInfoExtensions +{ + extension(EventHandlerMethodInfo) + { + internal static EventHandlerMethodInfo Create( + IInvocationOperation invocation, + GeneratorContext context) + { + if (!InterceptableLocationInfo.TryGet(context, out var interceptableLocation)) + throw new InvalidOperationException("Unable to get interceptable location"); + + var diagnostics = new List(); + var method = invocation.TargetMethod; + var compilation = context.SemanticModel.Compilation; + var invocationLocation = + LocationInfo.Create(context.Node) + ?? throw new InvalidOperationException("Event mapping has no source location"); + var handleArgument = GetArgument(invocation, "handle"); + var handlerSyntax = handleArgument is null + ? context.Node + : GetHandlerSyntax(handleArgument); + var handlerArgumentLocation = LocationInfo.Create(handlerSyntax) ?? invocationLocation; + var genericTypes = GetGenericTypes(method); + + if (!genericTypes.TryGetValue("TEvent", out var eventType)) + diagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerSignature, + handlerArgumentLocation, + "TEvent")); + if (!genericTypes.TryGetValue("TItem", out var itemType)) + diagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerSignature, + handlerArgumentLocation, + "TItem")); + + ValidateAccessibleType(eventType, "TEvent", handlerArgumentLocation, diagnostics); + ValidateAccessibleType(itemType, "TItem", handlerArgumentLocation, diagnostics); + + if (eventType is not null && IsStream(eventType, context)) + diagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerSignature, + handlerArgumentLocation, + "stream TEvent")); + + var handleDelegate = handleArgument?.Parameter?.Type as INamedTypeSymbol; + var handleReturn = handleDelegate?.DelegateInvokeMethod?.ReturnType; + var handleReturnsResult = TryUnwrapTask( + handleReturn, + context, + out var handleResultType); + + var onErrorArgument = GetArgument(invocation, "onError"); + var createResponseArgument = GetArgument(invocation, "createResponse"); + var family = DetermineFamily( + handleReturnsResult, + onErrorArgument is not null, + createResponseArgument is not null); + var hasResponse = family is not EventHandlerFamily.N1; + var hasOnError = family is EventHandlerFamily.N3 or EventHandlerFamily.R2; + var collectValues = family is not EventHandlerFamily.N1; + var collectsSourceItems = family is EventHandlerFamily.N2; + var collectsMappedFailures = family is EventHandlerFamily.N3; + + string? collectedType = null; + switch (family) + { + case EventHandlerFamily.N2: + collectedType = itemType?.QualifiedNullableName; + break; + case EventHandlerFamily.N3: + { + genericTypes.TryGetValue("TFailure", out var failureType); + ValidateAccessibleType( + failureType, + "TFailure", + handlerArgumentLocation, + diagnostics); + collectedType = failureType?.QualifiedNullableName; + break; + } + case EventHandlerFamily.R1: + case EventHandlerFamily.R2: + ValidateAccessibleType( + handleResultType, + "TResult", + handlerArgumentLocation, + diagnostics); + collectedType = handleResultType?.QualifiedNullableName; + break; + } + + string? responseType = null; + if (hasResponse) + { + genericTypes.TryGetValue("TResponse", out var declaredResponseType); + ValidateAccessibleType( + declaredResponseType, + "TResponse", + handlerArgumentLocation, + diagnostics); + + if (declaredResponseType is not null) + { + if (IsAwaitable(declaredResponseType)) + diagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerSignature, + handlerArgumentLocation, + "awaitable TResponse")); + + if (IsStream(declaredResponseType, context)) + diagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerSignature, + handlerArgumentLocation, + "stream TResponse")); + } + + responseType = declaredResponseType?.QualifiedNullableName; + } + + var reassigned = false; + IMethodSymbol? handlerMethod = null; + if (handleArgument is not null) + handlerMethod = ResolveHandlerMethod( + handleArgument.Value, + context.SemanticModel, + context.CancellationToken, + out reassigned); + + if (handlerMethod is null) + diagnostics.Add( + CreateDiagnostic( + Diagnostics.UnresolvedEventHandler, + handlerArgumentLocation, + reassigned + ? $"{handleArgument?.Parameter?.Name ?? "handle"} (reassigned local)" + : handleArgument?.Parameter?.Name ?? "handle")); + else if (family is EventHandlerFamily.N1 + or EventHandlerFamily.N2 + or EventHandlerFamily.N3 + && TryUnwrapTask(handlerMethod.ReturnType, context, out _)) + diagnostics.Add( + CreateDiagnostic( + Diagnostics.DiscardedEventHandlerResult, + handlerArgumentLocation, + handlerMethod.Name)); + + var parameters = handlerMethod is null + ? [] + : CreateParameters(handlerMethod, itemType, context, diagnostics); + + var valueType = family switch + { + EventHandlerFamily.N1 => "MinimalLambda.Generated.NoData", + EventHandlerFamily.N2 => itemType?.QualifiedNullableName ?? "global::System.Object", + _ => collectedType ?? "global::System.Object", + }; + + var hasAnyKeyed = parameters.Any(parameter => + parameter.Kind is EventHandlerParameterKind.KeyedService); + + var callbackParameters = new List(4); + AddCallback(invocation, "split", callbackParameters); + AddCallback(invocation, "handle", callbackParameters); + if (hasOnError) + AddCallback(invocation, "onError", callbackParameters); + if (hasResponse) + AddCallback(invocation, "createResponse", callbackParameters); + + return new EventHandlerMethodInfo( + InterceptableLocationAttribute: interceptableLocation.Attribute, + CallbackParameters: callbackParameters.ToEquatableArray(), + Family: family, + HasResponse: hasResponse, + HasOnError: hasOnError, + CollectsValues: collectValues, + CollectsSourceItems: collectsSourceItems, + CollectsMappedFailures: collectsMappedFailures, + HandleReturnsResult: handleReturnsResult, + EventType: eventType?.QualifiedNullableName ?? "global::System.Object", + ItemType: itemType?.QualifiedNullableName ?? "global::System.Object", + CollectedType: collectedType ?? "global::System.Object", + ValueType: valueType, + ResponseType: responseType, + HandlerParameters: parameters.ToEquatableArray(), + HandlerArguments: string.Join( + ", ", + parameters.Select(parameter => $"arg{parameter.Ordinal}")), + HasAnyFromKeyedServices: hasAnyKeyed, + MapCallLocation: invocationLocation, + HandlerArgumentLocation: handlerArgumentLocation, + TreeOrdinal: DurableMethodInfoExtensions.GetTreeOrdinal( + context.Node.SyntaxTree, + compilation), + SourceSpanStart: context.Node.SpanStart, + DiagnosticInfos: diagnostics.ToEquatableArray()); + } + } + + private static void AddCallback( + IInvocationOperation invocation, + string name, + List callbacks) + { + var argument = GetArgument(invocation, name); + if (argument?.Parameter is { } parameter) + callbacks.Add( + new EventHandlerCallbackInfo(parameter.Name, parameter.Type.QualifiedNullableName)); + } + + private static EventHandlerFamily DetermineFamily( + bool handleReturnsResult, + bool hasOnError, + bool hasCreateResponse) + { + if (handleReturnsResult) + return hasOnError ? EventHandlerFamily.R2 : EventHandlerFamily.R1; + + if (!hasCreateResponse) + return EventHandlerFamily.N1; + + return hasOnError ? EventHandlerFamily.N3 : EventHandlerFamily.N2; + } + + private static List CreateParameters( + IMethodSymbol handlerMethod, + ITypeSymbol? itemType, + GeneratorContext context, + List diagnostics) + { + var parameters = new List(handlerMethod.Parameters.Length); + var contextCount = 0; + var processingCount = 0; + var tokenCount = 0; + + for (var index = 0; index < handlerMethod.Parameters.Length; index++) + { + var parameter = handlerMethod.Parameters[index]; + var location = GetParameterLocation(parameter, handlerMethod); + var parameterDiagnostics = new List(); + + if (parameter.RefKind != RefKind.None) + parameterDiagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerSignature, + location, + $"{parameter.RefKind.ToString().ToLowerInvariant()} {parameter.Name}")); + + ValidateAccessibleType(parameter.Type, parameter.Name, location, parameterDiagnostics); + + var isEventAttribute = IsEventAttribute(parameter, context); + var isServiceAttribute = parameter.IsServiceBindingAttribute(context); + + if (isEventAttribute) + parameterDiagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerBinding, + location, + $"[FromEvent] {parameter.Name}")); + + var kind = EventHandlerParameterKind.Service; + var assignment = string.Empty; + var isOptional = parameter.IsOptional + || parameter.NullableAnnotation == NullableAnnotation.Annotated; + string? keyedKey = null; + + if (index == 0) + { + kind = EventHandlerParameterKind.Item; + assignment = "item"; + if (isServiceAttribute) + parameterDiagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerBinding, + location, + $"service attribute on item parameter '{parameter.Name}'")); + if (itemType is not null + && !SymbolEqualityComparer.Default.Equals(itemType, parameter.Type)) + parameterDiagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerSignature, + location, + $"item parameter '{parameter.Name}'")); + } + else if (context.WellKnownTypes.IsType( + parameter.Type, + WellKnownType.Amazon_Lambda_Core_ILambdaContext, + WellKnownType.MinimalLambda_ILambdaInvocationContext)) + { + kind = EventHandlerParameterKind.Context; + assignment = "processingContext.Invocation"; + contextCount++; + if (contextCount > 1) + parameterDiagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerBinding, + location, + $"duplicate context parameter '{parameter.Name}'")); + if (isServiceAttribute) + parameterDiagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerBinding, + location, + $"service attribute on context parameter '{parameter.Name}'")); + } + else if (context.WellKnownTypes.IsType( + parameter.Type, + WellKnownType.MinimalLambda_IEventProcessingContext)) + { + kind = EventHandlerParameterKind.ProcessingContext; + assignment = "processingContext"; + processingCount++; + if (processingCount > 1) + parameterDiagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerBinding, + location, + $"duplicate processing context parameter '{parameter.Name}'")); + if (isServiceAttribute) + parameterDiagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerBinding, + location, + $"service attribute on processing context parameter '{parameter.Name}'")); + } + else if (context.WellKnownTypes.IsType( + parameter.Type, + WellKnownType.System_Threading_CancellationToken)) + { + kind = EventHandlerParameterKind.CancellationToken; + assignment = "processingContext.CancellationToken"; + tokenCount++; + if (tokenCount > 1) + parameterDiagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerBinding, + location, + $"duplicate cancellation token parameter '{parameter.Name}'")); + if (isServiceAttribute) + parameterDiagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerBinding, + location, + $"service attribute on cancellation token parameter '{parameter.Name}'")); + } + else + { + var diResult = parameter.GetDiParameterAssignment(context, "serviceProvider"); + if (diResult.IsSuccess) + { + if (diResult.Value!.Key is not null) + { + kind = EventHandlerParameterKind.KeyedService; + keyedKey = diResult.Value.Key; + } + + assignment = diResult.Value.Assignment; + } + else if (diResult.Error is { } error) + parameterDiagnostics.Add(error); + } + + parameters.Add( + new EventHandlerParameterInfo( + parameter.Ordinal, + parameter.Name, + parameter.Type.QualifiedNullableName, + kind, + assignment, + isOptional, + keyedKey, + location, + parameterDiagnostics.ToEquatableArray())); + + diagnostics.AddRange(parameterDiagnostics); + } + + if (handlerMethod.Parameters.Length is < 1 or > 11) + diagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerSignature, + GetParameterLocationOrNull(handlerMethod.Parameters.LastOrDefault(), null) + ?? LocationInfo.Create(handlerMethod) + ?? new LocationInfo(string.Empty, default, default), + $"{handlerMethod.Name} parameter count {handlerMethod.Parameters.Length}")); + + return parameters; + } + + private static void ValidateAccessibleType( + ITypeSymbol? type, + string component, + LocationInfo location, + List diagnostics) + { + if (type is not null && !IsAccessibleFromGeneratedAdapter(type)) + diagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerSignature, + location, + component)); + } + + private static bool IsAccessibleFromGeneratedAdapter(ITypeSymbol type) => + !ContainsTypeParameter(type) && IsAccessibleFromGeneratedAdapterCore(type); + + private static bool IsAccessibleFromGeneratedAdapterCore(ITypeSymbol type) => + type switch + { + IArrayTypeSymbol array => IsAccessibleFromGeneratedAdapterCore(array.ElementType), + IPointerTypeSymbol => false, + IFunctionPointerTypeSymbol => false, + ITypeParameterSymbol => false, + IDynamicTypeSymbol => false, + INamedTypeSymbol named => IsNamedTypeAccessibleFromGeneratedAdapter(named), + _ => !type.IsRefLikeType, + }; + + private static bool IsNamedTypeAccessibleFromGeneratedAdapter(INamedTypeSymbol type) + { + if (type.IsAnonymousType || type.IsRefLikeType) + return false; + + for (INamedTypeSymbol? current = type; + current is not null; + current = current.ContainingType) + if (current.IsFileLocal + || current.DeclaredAccessibility is not (Accessibility.Public + or Accessibility.Internal + or Accessibility.ProtectedOrInternal)) + return false; + + return type.TypeArguments.All(IsAccessibleFromGeneratedAdapter); + } + + private static bool ContainsTypeParameter(ITypeSymbol type) => + type switch + { + ITypeParameterSymbol => true, + IArrayTypeSymbol array => ContainsTypeParameter(array.ElementType), + IPointerTypeSymbol pointer => ContainsTypeParameter(pointer.PointedAtType), + IFunctionPointerTypeSymbol => true, + INamedTypeSymbol named => (named.ContainingType is not null + && ContainsTypeParameter(named.ContainingType)) + || named.TypeArguments.Any(ContainsTypeParameter), + _ => false, + }; + + private static bool IsEventAttribute(IParameterSymbol parameter, GeneratorContext context) => + parameter + .GetAttributes() + .Any(attribute => attribute.AttributeClass is not null + && context.WellKnownTypes.IsType( + attribute.AttributeClass, + WellKnownType.MinimalLambda_Builder_EventAttribute, + WellKnownType.MinimalLambda_Builder_FromEventAttribute)); + + private static bool IsStream(ITypeSymbol type, GeneratorContext context) => + context.WellKnownTypes.IsType(type, WellKnownType.System_IO_Stream); + + private static bool IsAwaitable(ITypeSymbol type) + { + if (type is not INamedTypeSymbol named) + return false; + + var metadataName = named.OriginalDefinition.ToDisplayString(); + return metadataName is "System.Threading.Tasks.Task" + or "System.Threading.Tasks.Task" + or "System.Threading.Tasks.ValueTask" + or "System.Threading.Tasks.ValueTask" + || named + .GetMembers("GetAwaiter") + .OfType() + .Any(method => method.Parameters.Length == 0 && !method.IsStatic); + } + + private static bool TryUnwrapTask( + ITypeSymbol? type, + GeneratorContext context, + out ITypeSymbol? resultType) + { + resultType = null; + if (type is not INamedTypeSymbol named) + return false; + + var taskOfT = context.WellKnownTypes.Get(WellKnownType.System_Threading_Tasks_Task_T); + if (!SymbolEqualityComparer.Default.Equals(named.OriginalDefinition, taskOfT)) + return false; + + resultType = named.TypeArguments[0]; + return true; + } + + private static Dictionary GetGenericTypes(IMethodSymbol method) + { + var types = new Dictionary(StringComparer.Ordinal); + var original = method.OriginalDefinition; + for (var index = 0; index < original.TypeParameters.Length; index++) + types[original.TypeParameters[index].Name] = method.TypeArguments[index]; + return types; + } + + private static IArgumentOperation? GetArgument(IInvocationOperation invocation, string name) + { + foreach (var argument in invocation.Arguments) + if (argument.Parameter?.Name == name) + return argument; + + return null; + } + + private static IMethodSymbol? ResolveHandlerMethod( + IOperation operation, + SemanticModel semanticModel, + CancellationToken cancellationToken, + out bool reassigned) + { + reassigned = false; + var wasReassigned = false; + var result = Resolve(operation); + reassigned = wasReassigned; + return result; + + IMethodSymbol? Resolve(IOperation current) + { + switch (current) + { + case IArgumentOperation argument: + return Resolve(argument.Value); + case IConversionOperation conversion: + return Resolve(conversion.Operand); + case IDelegateCreationOperation delegateCreation: + return Resolve(delegateCreation.Target); + case IFieldReferenceOperation { Field.IsReadOnly: true } field + when GetFieldInitializerOperation( + field.Field, + semanticModel.Compilation, + cancellationToken) is { } initializer: + return Resolve(initializer); + case ILocalReferenceOperation local: + if (HasAdditionalWrite( + local.Local, + semanticModel.Compilation, + cancellationToken)) + { + wasReassigned = true; + return null; + } + + return GetLocalInitializerOperation( + local.Local, + semanticModel.Compilation, + cancellationToken) is { } localInitializer + ? Resolve(localInitializer) + : null; + case IAnonymousFunctionOperation anonymous: + return anonymous.Symbol; + case ILocalFunctionOperation localFunction: + return localFunction.Symbol; + case IMethodReferenceOperation methodReference: + return methodReference.Method; + case IParenthesizedOperation parenthesized: + return Resolve(parenthesized.Operand); + default: + return null; + } + } + } + + private static IOperation? GetLocalInitializerOperation( + ILocalSymbol local, + Compilation compilation, + CancellationToken cancellationToken) => + local + .DeclaringSyntaxReferences + .Select(reference => reference.GetSyntax(cancellationToken)) + .OfType() + .Where(declarator => declarator.Initializer is not null) + .Select(declarator => + compilation + .GetSemanticModel(declarator.SyntaxTree) + .GetOperation(declarator.Initializer!.Value, cancellationToken)) + .FirstOrDefault(operation => operation is not null); + + private static bool HasAdditionalWrite( + ILocalSymbol local, + Compilation compilation, + CancellationToken cancellationToken) + { + foreach (var reference in local.DeclaringSyntaxReferences) + { + var declaration = reference.GetSyntax(cancellationToken); + var tree = declaration.SyntaxTree; + var model = compilation.GetSemanticModel(tree); + foreach (var node in tree.GetRoot(cancellationToken).DescendantNodes()) + { + if (node is not IdentifierNameSyntax identifier + || identifier.Identifier.ValueText != local.Name) + continue; + + if (!SymbolEqualityComparer.Default.Equals( + model.GetSymbolInfo(identifier, cancellationToken).Symbol, + local)) + continue; + + var isWrite = identifier.Parent switch + { + AssignmentExpressionSyntax assignment when assignment.Left == identifier => + true, + PrefixUnaryExpressionSyntax prefix => prefix.IsKind( + SyntaxKind.PreIncrementExpression) + || prefix.IsKind(SyntaxKind.PreDecrementExpression), + PostfixUnaryExpressionSyntax postfix => postfix.IsKind( + SyntaxKind.PostIncrementExpression) + || postfix.IsKind(SyntaxKind.PostDecrementExpression), + ArgumentSyntax argument => !argument.RefKindKeyword.IsKind(SyntaxKind.None), + RefExpressionSyntax => true, + _ => false, + }; + + if (isWrite) + return true; + } + } + + return false; + } + + private static IOperation? GetFieldInitializerOperation( + IFieldSymbol field, + Compilation compilation, + CancellationToken cancellationToken) => + field + .DeclaringSyntaxReferences + .Select(reference => reference.GetSyntax(cancellationToken)) + .OfType() + .Where(declarator => declarator.Initializer is not null) + .Select(declarator => + compilation + .GetSemanticModel(declarator.SyntaxTree) + .GetOperation(declarator.Initializer!.Value, cancellationToken)) + .FirstOrDefault(operation => operation is not null); + + private static LocationInfo GetParameterLocation( + IParameterSymbol parameter, + IMethodSymbol method) + { + var location = parameter + .DeclaringSyntaxReferences + .Select(reference => LocationInfo.Create(reference.GetSyntax())) + .FirstOrDefault(candidate => candidate is not null); + + if (location is not null) + return location.Value; + + var methodLocation = method + .DeclaringSyntaxReferences + .Select(reference => LocationInfo.Create(reference.GetSyntax())) + .FirstOrDefault(candidate => candidate is not null); + + return methodLocation ?? new LocationInfo(string.Empty, default, default); + } + + private static LocationInfo? GetParameterLocationOrNull( + IParameterSymbol? parameter, + LocationInfo? fallback) => + parameter + ?.DeclaringSyntaxReferences + .Select(reference => LocationInfo.Create(reference.GetSyntax())) + .FirstOrDefault(candidate => candidate is not null) + ?? fallback; + + private static SyntaxNode GetHandlerSyntax(IArgumentOperation argument) => + argument.Syntax is ArgumentSyntax argumentSyntax + ? argumentSyntax.Expression + : argument.Syntax; + + private static DiagnosticInfo CreateDiagnostic( + DiagnosticDescriptor descriptor, + LocationInfo location, + params object?[] arguments) => + new(descriptor, location, arguments); +} diff --git a/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerParameterInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerParameterInfo.cs new file mode 100644 index 00000000..b8b82da4 --- /dev/null +++ b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerParameterInfo.cs @@ -0,0 +1,24 @@ +using LayeredCraft.SourceGeneratorTools.Types; + +namespace MinimalLambda.SourceGenerators.Models; + +internal enum EventHandlerParameterKind +{ + Item, + Context, + ProcessingContext, + CancellationToken, + Service, + KeyedService, +} + +internal record EventHandlerParameterInfo( + int Ordinal, + string Name, + string Type, + EventHandlerParameterKind Kind, + string Assignment, + bool IsOptional, + string? KeyedServiceKey, + LocationInfo Location, + EquatableArray DiagnosticInfos); diff --git a/src/MinimalLambda.SourceGenerators/Models/Handlers/MethodType.cs b/src/MinimalLambda.SourceGenerators/Models/Handlers/MethodType.cs index a92f2fde..6eaf4c2f 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Handlers/MethodType.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Handlers/MethodType.cs @@ -3,6 +3,7 @@ namespace MinimalLambda.SourceGenerators.Models; internal enum MethodType { MapHandler, + MapEventHandler, MapDurableHandler, OnInit, OnShutdown, diff --git a/src/MinimalLambda.SourceGenerators/Models/Shared/ParameterSource.cs b/src/MinimalLambda.SourceGenerators/Models/Shared/ParameterSource.cs index 55f93db5..762bbbf8 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Shared/ParameterSource.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Shared/ParameterSource.cs @@ -6,6 +6,7 @@ internal enum ParameterSource Context, DurableContext, CancellationToken, + ProcessingContext, KeyedServices, Services, } diff --git a/src/MinimalLambda.SourceGenerators/SyntaxProviders/HandlerSyntaxProvider.cs b/src/MinimalLambda.SourceGenerators/SyntaxProviders/HandlerSyntaxProvider.cs index 2e9850d0..f107f0e1 100644 --- a/src/MinimalLambda.SourceGenerators/SyntaxProviders/HandlerSyntaxProvider.cs +++ b/src/MinimalLambda.SourceGenerators/SyntaxProviders/HandlerSyntaxProvider.cs @@ -22,7 +22,7 @@ internal static class HandlerSyntaxProvider { private static readonly string[] TargetMethodNames = [ - "MapHandler", "MapDurableHandler", "OnInit", "OnShutdown" + "MapHandler", "MapEventHandler", "MapDurableHandler", "OnInit", "OnShutdown" ]; internal static bool Predicate(SyntaxNode node, CancellationToken _) => @@ -45,6 +45,9 @@ internal static bool Predicate(SyntaxNode node, CancellationToken _) => if (!TryGetInvocationOperation(context, out var targetOperation)) return null; + if (targetOperation.TargetMethod.Name == "MapEventHandler") + return EventHandlerMethodInfo.Create(targetOperation, context); + if (!targetOperation.TryGetHandlerMethod( context.SemanticModel, out var method, @@ -72,10 +75,11 @@ private static bool TryGetInvocationOperation( if (operation is IInvocationOperation targetOperation && targetOperation.TargetMethod.GetDeclaredMethod() is { } declaredMethod && IsKnownTarget(declaredMethod) - && targetOperation.TryGetRouteHandlerArgument( - declaredMethod, - context.WellKnownTypes.Get(WellKnownType.System_Delegate), - out _)) + && (declaredMethod.Name == "MapEventHandler" + || targetOperation.TryGetRouteHandlerArgument( + declaredMethod, + context.WellKnownTypes.Get(WellKnownType.System_Delegate), + out _))) { invocationOperation = targetOperation; return true; @@ -181,9 +185,15 @@ method.ContainingNamespace is == "MapDurableHandlerLambdaApplicationExtensions"), "MapHandler" or "OnInit" or "OnShutdown" => method.ContainingAssembly.Name == "MinimalLambda", + "MapEventHandler" => method.ContainingAssembly.Name == "MinimalLambda" + && IsEventMapContainingType(method.ContainingType), _ => false, }); + private static bool IsEventMapContainingType(INamedTypeSymbol type) => + type.Name == "MapEventHandlerLambdaApplicationExtensions" + || type.ContainingType?.Name == "MapEventHandlerLambdaApplicationExtensions"; + private static IOperation? ResolveDeclarationOperation( ISymbol symbol, SemanticModel? semanticModel) => diff --git a/src/MinimalLambda.SourceGenerators/Templates/MapEventHandler.scriban b/src/MinimalLambda.SourceGenerators/Templates/MapEventHandler.scriban new file mode 100644 index 00000000..3308a8b8 --- /dev/null +++ b/src/MinimalLambda.SourceGenerators/Templates/MapEventHandler.scriban @@ -0,0 +1,654 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +#nullable enable + +namespace System.Runtime.CompilerServices +{ + using System.CodeDom.Compiler; + + {{ generated_code_attribute.value }} + [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] + file sealed class InterceptsLocationAttribute : Attribute + { + public InterceptsLocationAttribute(int version, string data) { } + } +} + +namespace MinimalLambda.Generated +{ + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Runtime.ExceptionServices; + using System.Runtime.CompilerServices; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Logging; + using Microsoft.Extensions.Options; + using MinimalLambda.Builder; + using MinimalLambda.Options; + + {{ generated_code_attribute.value }} + file static class GeneratedEventProcessorExtensions + { + private const string EventFeatureProviderKey = "__EventFeatureProvider"; + private const string ResponseFeatureProviderKey = "__ResponseFeatureProvider"; + + {{~ for call in event_handler_calls ~}} + {{ call.interceptable_location_attribute }} + internal static ILambdaInvocationBuilder MapEventHandlerInterceptor{{ for.index }}( + this ILambdaInvocationBuilder application{{ for p in call.callback_parameters }}, + {{ p.type }} {{ p.name }}{{ end }}) + { + ArgumentNullException.ThrowIfNull(application); + {{~ for p in call.callback_parameters ~}} + ArgumentNullException.ThrowIfNull({{ p.name }}); + {{~ end ~}} + + var options = application.Services.GetRequiredService>().Value; + var effectiveConcurrency = options.EnableConcurrency + ? options.MaxConcurrentExecutions + : 1; + var scopeFactory = application.Services.GetRequiredService(); + var logger = application + .Services.GetService() + ?.CreateLogger("MinimalLambda.EventProcessor"); + + application.Handle(InvocationDelegate); + + if (!application.Properties.ContainsKey(EventFeatureProviderKey)) + application.Properties[EventFeatureProviderKey] = application + .Services.GetRequiredService() + .Create<{{ call.event_type }}>(); + {{~ if call.has_response ~}} + + if (!application.Properties.ContainsKey(ResponseFeatureProviderKey)) + application.Properties[ResponseFeatureProviderKey] = application + .Services.GetRequiredService() + .Create<{{ call.response_type }}>(); + {{~ end ~}} + + return application; + + async Task InvocationDelegate(ILambdaInvocationContext context) + { + if (context.CancellationToken.IsCancellationRequested) + throw new OperationCanceledException(context.CancellationToken); + + _ = context.ServiceProvider; + + var lambdaEvent = context.GetRequiredEvent<{{ call.event_type }}>(); + var splitItems = split(lambdaEvent, context); + if (splitItems is null) + throw new InvalidOperationException("The event splitter 'split' returned null."); + + var items = new List<{{ call.item_type }}>(); + using (var enumerator = splitItems.GetEnumerator()) + { + while (enumerator.MoveNext()) + { + context.CancellationToken.ThrowIfCancellationRequested(); + items.Add(enumerator.Current); + } + } + + var itemArray = items.ToArray(); + + if (context.CancellationToken.IsCancellationRequested) + throw new OperationCanceledException(context.CancellationToken); + + using var state = new EventProcessingState( + context, + logger, + itemArray.Length); + var outcomes = await EventProcessorRuntime + .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, {{ if call.collects_values }}true{{ else }}false{{ end }}) + .ConfigureAwait(false); + {{~ if call.collects_values ~}} + + var contributions = new List<{{ call.value_type }}>(outcomes!.Length); + foreach (var outcome in outcomes) + if (outcome.HasValue) + contributions.Add(outcome.Value!); + + var response = createResponse( + new ReadOnlyCollection<{{ call.value_type }}>(contributions), + context); + {{~ if call.has_response ~}} + + if (context.Features.Get() is not IResponseFeature<{{ call.response_type }}> responseFeature) + throw new InvalidOperationException( + "Response feature for type '{{ call.response_type }}' is not available in the collection."); + responseFeature.SetResponse(response); + {{~ end ~}} + {{~ end ~}} + } + + async Task> Adapt( + {{ call.item_type }} item, + IServiceProvider serviceProvider, + EventProcessingState processingContext) + { + {{~ if call.has_any_from_keyed_services ~}} + if (serviceProvider.GetService() is not IServiceProviderIsKeyedService) + throw new InvalidOperationException( + $"Unable to resolve service referenced by {nameof(FromKeyedServicesAttribute)}. The service provider doesn't support keyed services."); + {{~ end ~}} + {{~ for parameter in call.handler_parameters ~}} + var arg{{ parameter.ordinal }} = {{ parameter.assignment }}; + {{~ end ~}} + + var invocationToken = processingContext.Invocation.CancellationToken; + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException(invocationToken); + if (processingContext.CancellationToken.IsCancellationRequested) + return ItemOutcome<{{ call.value_type }}>.Cancelled; + + {{ if call.handle_returns_result }}Task<{{ call.collected_type }}>?{{ else }}Task?{{ end }} handlerTask = null; + {{ if call.handle_returns_result }}{{ call.collected_type }} handlerResult = default!;{{ end }} + Exception? synchronousFault = null; + try + { + handlerTask = handle({{ call.handler_arguments }}); + } + catch (Exception ex) + { + synchronousFault = ex; + } + + if (synchronousFault is null && handlerTask is null) + throw new InvalidOperationException("The event handler 'handle' returned a null task."); + + try + { + if (synchronousFault is not null) + ExceptionDispatchInfo.Capture(synchronousFault).Throw(); + + {{ if call.handle_returns_result }}handlerResult = {{ end }}await handlerTask!.ConfigureAwait(false); + } + catch (Exception ex) + { + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while processing an item.", + ex, + invocationToken); + + if (ex is OperationCanceledException + && processingContext.CancellationToken.IsCancellationRequested) + return ItemOutcome<{{ call.value_type }}>.Cancelled; + {{~ if call.has_on_error ~}} + + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException(invocationToken); + + var mapped = onError(item, ex, processingContext); + + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while mapping an item error.", + invocationToken); + + return ItemOutcome<{{ call.value_type }}>.FromMappedValue(mapped); + {{~ else ~}} + + throw; + {{~ end ~}} + } + + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while processing an item.", + invocationToken); + {{~ if call.collects_source_items ~}} + + return ItemOutcome<{{ call.value_type }}>.FromValue(item); + {{~ else if call.handle_returns_result ~}} + + return ItemOutcome<{{ call.value_type }}>.FromValue(handlerResult); + {{~ else ~}} + + return ItemOutcome<{{ call.value_type }}>.NoValue; + {{~ end ~}} + } + } + {{~ end ~}} + } + + file readonly struct NoData; + + file enum ItemExecutionState + { + Unstarted, + Succeeded, + MappedError, + Cancelled, + } + + file readonly struct ItemOutcome + { + private ItemOutcome(ItemExecutionState state, bool hasValue, TValue? value) + { + State = state; + HasValue = hasValue; + Value = value; + } + + internal ItemExecutionState State { get; } + + internal bool HasValue { get; } + + internal TValue? Value { get; } + + internal static ItemOutcome FromValue(TValue? value) => + new(ItemExecutionState.Succeeded, true, value); + + internal static ItemOutcome FromMappedValue(TValue? value) => + new(ItemExecutionState.MappedError, true, value); + + internal static ItemOutcome NoValue => + new(ItemExecutionState.Succeeded, false, default); + + internal static ItemOutcome Cancelled => + new(ItemExecutionState.Cancelled, false, default); + } + + file sealed class EventProcessingState : IEventProcessingContext, IDisposable + { + private readonly object _gate = new(); + private readonly ILambdaInvocationContext _invocation; + private readonly ILogger? _logger; + private readonly int _itemCount; + private readonly CancellationTokenSource _processingSource = new(); + private readonly CancellationTokenRegistration _invocationRegistration; + + private int _nextIndex; + private int _admitted; + private bool _stopRequested; + private bool _cancelRequested; + private bool _handlingClosed; + private bool _completed; + private bool _invocationCancelled; + private bool _disposed; + private ExceptionDispatchInfo? _firstFatal; + private List? _additionalFatal; + private TaskCompletionSource? _dispatchCompletion; + + internal EventProcessingState( + ILambdaInvocationContext invocation, + ILogger? logger, + int itemCount) + { + _invocation = invocation; + _logger = logger; + _itemCount = itemCount; + _invocationRegistration = invocation.CancellationToken.Register( + static state => ((EventProcessingState)state!).OnInvocationTokenCancelled(), + this); + } + + public ILambdaInvocationContext Invocation => _invocation; + + public CancellationToken CancellationToken => _processingSource.Token; + + public void StopProcessing() + { + lock (_gate) + { + if (_completed || _handlingClosed) + return; + + _stopRequested = true; + TryCloseHandlingCore(); + } + } + + public void CancelProcessing() => RequestProcessingCancellation(false); + + internal bool TryClaim(out int index) + { + TaskCompletionSource? dispatch = null; + var claimed = false; + index = -1; + + lock (_gate) + { + if (_completed) + return false; + + ObserveInvocationCancellationCore(ref dispatch); + + if (_handlingClosed + || _stopRequested + || _firstFatal is not null + || _nextIndex >= _itemCount) + { + TryCloseHandlingCore(); + } + else + { + index = _nextIndex++; + _admitted++; + claimed = true; + } + } + + if (dispatch is not null) + StartDispatch(dispatch); + + return claimed; + } + + internal bool IsInvocationCancellationLatched + { + get + { + lock (_gate) + return _invocationCancelled; + } + } + + internal void CompleteAdmission() + { + lock (_gate) + { + if (_admitted > 0) + _admitted--; + + TryCloseHandlingCore(); + } + } + + internal bool TryLatchInvocationCancellation() + { + if (!_invocation.CancellationToken.IsCancellationRequested) + return false; + + RequestProcessingCancellation(true); + + lock (_gate) + return _invocationCancelled; + } + + internal void RecordFatal(Exception exception) + { + lock (_gate) + { + if (_completed) + return; + + _stopRequested = true; + var fatal = ExceptionDispatchInfo.Capture(exception); + if (_firstFatal is null) + _firstFatal = fatal; + else + (_additionalFatal ??= []).Add(exception); + + TryCloseHandlingCore(); + } + } + + internal void TryCloseHandling() + { + lock (_gate) + TryCloseHandlingCore(); + } + + internal async Task JoinAsync() + { + Task? dispatch; + lock (_gate) + { + TryCloseHandlingCore(); + dispatch = _dispatchCompletion?.Task; + } + + if (dispatch is not null) + await dispatch.ConfigureAwait(false); + + Completion completion; + lock (_gate) + { + TryCloseHandlingCore(); + _completed = true; + completion = new Completion( + _invocationCancelled, + _firstFatal, + _additionalFatal); + } + + completion.LogAdditional(_logger); + + if (completion.InvocationCancelled) + throw new OperationCanceledException( + "The Lambda invocation was cancelled during item processing.", + _invocation.CancellationToken); + + if (completion.FirstFatal is not null) + { + completion.FirstFatal.Throw(); + throw new InvalidOperationException("Unreachable"); + } + } + + public void Dispose() + { + if (_disposed) + return; + + _disposed = true; + _invocationRegistration.Dispose(); + _processingSource.Dispose(); + } + + private void OnInvocationTokenCancelled() => RequestProcessingCancellation(true); + + private void RequestProcessingCancellation(bool invocationCancelled) + { + TaskCompletionSource? dispatch = null; + lock (_gate) + { + if (_completed || _handlingClosed) + return; + + if (invocationCancelled) + _invocationCancelled = true; + + _stopRequested = true; + + if (!_cancelRequested) + { + _cancelRequested = true; + _dispatchCompletion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + dispatch = _dispatchCompletion; + } + + TryCloseHandlingCore(); + } + + if (dispatch is not null) + StartDispatch(dispatch); + } + + private void ObserveInvocationCancellationCore(ref TaskCompletionSource? dispatch) + { + if (_handlingClosed || !_invocation.CancellationToken.IsCancellationRequested) + return; + + _invocationCancelled = true; + _stopRequested = true; + + if (_cancelRequested) + return; + + _cancelRequested = true; + _dispatchCompletion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + dispatch = _dispatchCompletion; + } + + private void TryCloseHandlingCore() + { + if (_handlingClosed) + return; + + if (_admitted > 0) + return; + + if (_nextIndex < _itemCount + && !_stopRequested + && _firstFatal is null + && !_invocation.CancellationToken.IsCancellationRequested) + return; + + if (_invocation.CancellationToken.IsCancellationRequested) + { + _invocationCancelled = true; + _stopRequested = true; + } + + _handlingClosed = true; + } + + private void StartDispatch(TaskCompletionSource completion) => + _ = DispatchCancellationAsync(completion); + + private async Task DispatchCancellationAsync(TaskCompletionSource completion) + { + try + { + await _processingSource.CancelAsync().ConfigureAwait(false); + } + catch (Exception ex) + { + RecordFatal(ex); + } + finally + { + completion.TrySetResult(); + } + } + + private readonly struct Completion( + bool invocationCancelled, + ExceptionDispatchInfo? firstFatal, + List? additionalFatal) + { + internal bool InvocationCancelled { get; } = invocationCancelled; + + internal ExceptionDispatchInfo? FirstFatal { get; } = firstFatal; + + internal void LogAdditional(ILogger? logger) + { + if (logger is null || additionalFatal is null) + return; + + foreach (var exception in additionalFatal) + try + { + logger.LogError( + exception, + "Event processor observed an additional failure while draining item work."); + } + catch + { + // Logging must not replace the selected invocation error. + } + } + } + } + + file static class EventProcessorRuntime + { + internal static async Task[]?> RunAsync( + TItem[] items, + int effectiveConcurrency, + IServiceScopeFactory scopeFactory, + EventProcessingState state, + Func>> adapter, + bool collectValues) + { + if (items.Length == 0) + state.TryCloseHandling(); + + var outcomes = collectValues ? new ItemOutcome[items.Length] : null; + var workerCount = Math.Min(items.Length, Math.Max(1, effectiveConcurrency)); + var workers = new Task[workerCount]; + + for (var index = 0; index < workerCount; index++) + workers[index] = RunWorkerAsync(); + + await Task.WhenAll(workers).ConfigureAwait(false); + await state.JoinAsync().ConfigureAwait(false); + + return outcomes; + + async Task RunWorkerAsync() + { + while (state.TryClaim(out var index)) + { + if (state.IsInvocationCancellationLatched) + { + state.CompleteAdmission(); + continue; + } + + AsyncServiceScope scope; + try + { + scope = scopeFactory.CreateAsyncScope(); + } + catch (Exception ex) + { + state.RecordFatal(ex); + state.CompleteAdmission(); + continue; + } + + ItemOutcome outcome = default; + var hasOutcome = false; + + try + { + try + { + outcome = await adapter(items[index], scope.ServiceProvider, state) + .ConfigureAwait(false); + hasOutcome = true; + } + catch (Exception ex) + { + if (!state.TryLatchInvocationCancellation()) + state.RecordFatal(ex); + } + } + finally + { + state.CompleteAdmission(); + } + + try + { + await scope.DisposeAsync().ConfigureAwait(false); + } + catch (Exception ex) + { + state.RecordFatal(ex); + } + + if (collectValues && hasOutcome && outcome.HasValue) + outcomes![index] = outcome; + } + } + } + } +} diff --git a/src/MinimalLambda.SourceGenerators/WellKnownTypes/WellKnownTypeData.cs b/src/MinimalLambda.SourceGenerators/WellKnownTypes/WellKnownTypeData.cs index b0cbd214..37231bfe 100644 --- a/src/MinimalLambda.SourceGenerators/WellKnownTypes/WellKnownTypeData.cs +++ b/src/MinimalLambda.SourceGenerators/WellKnownTypes/WellKnownTypeData.cs @@ -53,6 +53,7 @@ public enum WellKnownType System_IServiceProvider, System_Void, MinimalLambda_ILambdaInvocationContext, + MinimalLambda_IEventProcessingContext, MinimalLambda_ILambdaLifecycleContext, MinimalLambda_Builder_EventAttribute, MinimalLambda_Builder_FromArgumentsAttribute, @@ -111,6 +112,7 @@ public enum WellKnownType "System.IServiceProvider", "System.Void", "MinimalLambda.ILambdaInvocationContext", + "MinimalLambda.IEventProcessingContext", "MinimalLambda.ILambdaLifecycleContext", "MinimalLambda.Builder.EventAttribute", "MinimalLambda.Builder.FromArgumentsAttribute", diff --git a/src/MinimalLambda/Builder/Extensions/ServiceCollectionExtensions.cs b/src/MinimalLambda/Builder/Extensions/ServiceCollectionExtensions.cs index 6aff9dd2..ea4b528e 100644 --- a/src/MinimalLambda/Builder/Extensions/ServiceCollectionExtensions.cs +++ b/src/MinimalLambda/Builder/Extensions/ServiceCollectionExtensions.cs @@ -39,6 +39,11 @@ public IServiceCollection AddLambdaHostCoreServices() services.AddHostedService(); // Register options related services + services.AddOptions().ValidateOnStart(); + services.TryAddEnumerable( + ServiceDescriptor + .Singleton, + EventHandlerOptionsValidator>()); services.AddSingleton, HostOptionsPostConfiguration>(); services.AddSingleton, diff --git a/src/MinimalLambda/Builder/InterceptionTargets/MapEventHandlerLambdaApplicationExtensions.cs b/src/MinimalLambda/Builder/InterceptionTargets/MapEventHandlerLambdaApplicationExtensions.cs new file mode 100644 index 00000000..6ebe0190 --- /dev/null +++ b/src/MinimalLambda/Builder/InterceptionTargets/MapEventHandlerLambdaApplicationExtensions.cs @@ -0,0 +1,1562 @@ +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using Amazon.Lambda.Core; + +namespace MinimalLambda.Builder; + +/// +/// Overloads for +/// that process a batch of source items with generated dependency injection and optional +/// response construction. +/// +/// +/// +/// Source generation creates the wiring code, using compile-time interceptors to replace +/// these calls. Each started item receives its own asynchronous dependency injection scope. +/// Item handlers are asynchronous and return or +/// . +/// +/// +/// Handler parameters are item-first. After the item, , +/// , , and +/// receive framework values; all other +/// parameters resolve from the item scope. A handler accepts at most ten parameters after +/// the item, including framework context and cancellation-token parameters. +/// +/// +/// The response builder receives only completed contributions in source order. +/// Unstarted or locally cancelled items contribute nothing; the processor does not add +/// placeholder results, validate response completeness, or retry items. These overloads +/// are mutually exclusive with each other and with MapHandler for the same +/// invocation handler at runtime. +/// +/// +/// Method groups do not supply dependency parameter types for generic inference. Use an +/// explicitly typed lambda, a typed delegate local, or specify every generic argument. +/// +/// +[ExcludeFromCodeCoverage] +public static class MapEventHandlerLambdaApplicationExtensions +{ + /// Registers an event-processor handler (N1, 0 additional parameters). + /// No result. Handler errors fail the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N1, 1 additional parameter). + /// No result. Handler errors fail the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N1, 2 additional parameters). + /// No result. Handler errors fail the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N1, 3 additional parameters). + /// No result. Handler errors fail the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N1, 4 additional parameters). + /// No result. Handler errors fail the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N1, 5 additional parameters). + /// No result. Handler errors fail the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N1, 6 additional parameters). + /// No result. Handler errors fail the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N1, 7 additional parameters). + /// No result. Handler errors fail the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N1, 8 additional parameters). + /// No result. Handler errors fail the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N1, 9 additional parameters). + /// No result. Handler errors fail the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N1, 10 additional parameters). + /// No result. Handler errors fail the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N2, 0 additional parameters). + /// No result. createResponse receives successfully handled source items. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The Lambda response type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N2, 1 additional parameter). + /// No result. createResponse receives successfully handled source items. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N2, 2 additional parameters). + /// No result. createResponse receives successfully handled source items. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N2, 3 additional parameters). + /// No result. createResponse receives successfully handled source items. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N2, 4 additional parameters). + /// No result. createResponse receives successfully handled source items. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N2, 5 additional parameters). + /// No result. createResponse receives successfully handled source items. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N2, 6 additional parameters). + /// No result. createResponse receives successfully handled source items. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N2, 7 additional parameters). + /// No result. createResponse receives successfully handled source items. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N2, 8 additional parameters). + /// No result. createResponse receives successfully handled source items. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N2, 9 additional parameters). + /// No result. createResponse receives successfully handled source items. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N2, 10 additional parameters). + /// No result. createResponse receives successfully handled source items. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N3, 0 additional parameters). + /// No result with recovery. createResponse receives mapped failures. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The mapped failure value type. + /// The Lambda response type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N3, 1 additional parameter). + /// No result with recovery. createResponse receives mapped failures. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The mapped failure value type. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N3, 2 additional parameters). + /// No result with recovery. createResponse receives mapped failures. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The mapped failure value type. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N3, 3 additional parameters). + /// No result with recovery. createResponse receives mapped failures. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The mapped failure value type. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N3, 4 additional parameters). + /// No result with recovery. createResponse receives mapped failures. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The mapped failure value type. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N3, 5 additional parameters). + /// No result with recovery. createResponse receives mapped failures. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The mapped failure value type. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N3, 6 additional parameters). + /// No result with recovery. createResponse receives mapped failures. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The mapped failure value type. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N3, 7 additional parameters). + /// No result with recovery. createResponse receives mapped failures. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The mapped failure value type. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N3, 8 additional parameters). + /// No result with recovery. createResponse receives mapped failures. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The mapped failure value type. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N3, 9 additional parameters). + /// No result with recovery. createResponse receives mapped failures. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The mapped failure value type. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N3, 10 additional parameters). + /// No result with recovery. createResponse receives mapped failures. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The mapped failure value type. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R1, 0 additional parameters). + /// Result. createResponse receives successful results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R1, 1 additional parameter). + /// Result. createResponse receives successful results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R1, 2 additional parameters). + /// Result. createResponse receives successful results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R1, 3 additional parameters). + /// Result. createResponse receives successful results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R1, 4 additional parameters). + /// Result. createResponse receives successful results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R1, 5 additional parameters). + /// Result. createResponse receives successful results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R1, 6 additional parameters). + /// Result. createResponse receives successful results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R1, 7 additional parameters). + /// Result. createResponse receives successful results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R1, 8 additional parameters). + /// Result. createResponse receives successful results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R1, 9 additional parameters). + /// Result. createResponse receives successful results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R1, 10 additional parameters). + /// Result. createResponse receives successful results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R2, 0 additional parameters). + /// Result with recovery. createResponse receives successful and mapped results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R2, 1 additional parameter). + /// Result with recovery. createResponse receives successful and mapped results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R2, 2 additional parameters). + /// Result with recovery. createResponse receives successful and mapped results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R2, 3 additional parameters). + /// Result with recovery. createResponse receives successful and mapped results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R2, 4 additional parameters). + /// Result with recovery. createResponse receives successful and mapped results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R2, 5 additional parameters). + /// Result with recovery. createResponse receives successful and mapped results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R2, 6 additional parameters). + /// Result with recovery. createResponse receives successful and mapped results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R2, 7 additional parameters). + /// Result with recovery. createResponse receives successful and mapped results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R2, 8 additional parameters). + /// Result with recovery. createResponse receives successful and mapped results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R2, 9 additional parameters). + /// Result with recovery. createResponse receives successful and mapped results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (R2, 10 additional parameters). + /// Result with recovery. createResponse receives successful and mapped results. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The shared result type for successful and mapped items. + /// The Lambda response type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Maps a handler exception for one item to a result value. + /// Builds the response from completed contributions in source order. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func> handle, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + 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/Core/Options/EventHandlerOptions.cs b/src/MinimalLambda/Core/Options/EventHandlerOptions.cs new file mode 100644 index 00000000..c581026a --- /dev/null +++ b/src/MinimalLambda/Core/Options/EventHandlerOptions.cs @@ -0,0 +1,34 @@ +namespace MinimalLambda.Options; + +/// Provides default event-processor behavior for the Lambda host. +/// +/// +/// Options are captured when an event handler is mapped. Changes made after registration do +/// not affect that handler. Sequential processing is selected with +/// ; is the upper bound +/// when concurrency is enabled. +/// +/// +public sealed class EventHandlerOptions +{ + /// + /// Gets or sets a value indicating whether source items may be processed concurrently. + /// Defaults to . + /// + /// + /// When disabled, each item finishes handling, error mapping, and scope disposal before the + /// next item starts. Asynchronous handlers are still awaited; the flag does not make + /// asynchronous work synchronous. + /// + public bool EnableConcurrency { get; set; } = true; + + /// + /// Gets or sets the maximum number of item operations that may be active at once. Defaults to + /// 10. + /// + /// + /// The value must be positive, including when is + /// . There is no unlimited sentinel. + /// + public int MaxConcurrentExecutions { get; set; } = 10; +} diff --git a/src/MinimalLambda/Core/Options/EventHandlerOptionsValidator.cs b/src/MinimalLambda/Core/Options/EventHandlerOptionsValidator.cs new file mode 100644 index 00000000..51773654 --- /dev/null +++ b/src/MinimalLambda/Core/Options/EventHandlerOptionsValidator.cs @@ -0,0 +1,16 @@ +using Microsoft.Extensions.Options; + +namespace MinimalLambda.Options; + +internal sealed class EventHandlerOptionsValidator : IValidateOptions +{ + public ValidateOptionsResult Validate(string? name, EventHandlerOptions options) + { + ArgumentNullException.ThrowIfNull(options); + + return options.MaxConcurrentExecutions < 1 + ? ValidateOptionsResult.Fail( + $"{nameof(EventHandlerOptions)}.{nameof(EventHandlerOptions.MaxConcurrentExecutions)} must be greater than zero.") + : ValidateOptionsResult.Success; + } +} From 028910529bbb392bdcac0ad625925971c90bc117 Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Wed, 28 Oct 2026 16:11:31 -0400 Subject: [PATCH 05/21] test(event-processor): cover runtime, generation, and package consumers - EventProcessorTests drive real generated registrations with controlled task coordination: ordering, concurrency caps, sequential mode, fatal admission boundaries, stop/cancel, invocation cancellation, scope isolation, response inputs, context bindings, and options validation. - EventHandlerDiscoveryTests, EventHandlerDiagnosticTests, and EventHandlerEmitterTests cover every overload arity, supported delegate forms, LH0008-LH0011 with source locations, deterministic snapshots, and mixed valid and invalid registrations. - EventProcessorLambdaTests run an SQS partial-batch fixture through the existing test server, serializer composer, and JSON round trip. - Add an EventProcessorConsumer package-compatibility fixture and extend the compatibility script to assert its generated file and warning-free build. --- MinimalLambda.sln | 15 + scripts/test-package-compatibility.sh | 22 +- .../EventHandlerDiagnosticTests.cs | 275 ++++ .../EventHandlerDiscoveryTests.cs | 304 +++++ .../EventHandlerEmitterTests.cs | 156 +++ .../GeneratorTestHelpers.cs | 2 + ...#MinimalLambda.EventHandlers.g.verified.cs | 639 +++++++++ ...#MinimalLambda.EventHandlers.g.verified.cs | 1194 +++++++++++++++++ ...ting.UnitTests.EventProcessorLambda.csproj | 33 + .../Program.cs | 64 + .../appsettings.json | 2 + .../EventProcessorLambdaTests.cs | 111 ++ .../MinimalLambda.Testing.UnitTests.csproj | 3 + .../ServiceCollectionExtensionsTests.cs | 6 +- .../Core/Runtime/EventProcessorTests.cs | 791 +++++++++++ .../MinimalLambda.UnitTests.csproj | 57 +- .../EventProcessorConsumer.csproj | 19 + .../EventProcessorConsumer/Program.cs | 55 + 18 files changed, 3714 insertions(+), 34 deletions(-) create mode 100644 tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs create mode 100644 tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs create mode 100644 tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs create mode 100644 tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsContextTokenAndKeyedServiceBindings#MinimalLambda.EventHandlers.g.verified.cs create mode 100644 tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsRepresentativeAdapterForEveryFamily#MinimalLambda.EventHandlers.g.verified.cs create mode 100644 tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/MinimalLambda.Testing.UnitTests.EventProcessorLambda.csproj create mode 100644 tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/Program.cs create mode 100644 tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/appsettings.json create mode 100644 tests/MinimalLambda.Testing.UnitTests/Tests/MinimalLambda.Testing.UnitTests/EventProcessorLambdaTests.cs create mode 100644 tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs create mode 100644 tests/package-compatibility/EventProcessorConsumer/EventProcessorConsumer.csproj create mode 100644 tests/package-compatibility/EventProcessorConsumer/Program.cs diff --git a/MinimalLambda.sln b/MinimalLambda.sln index 07685ece..d5a87daa 100644 --- a/MinimalLambda.sln +++ b/MinimalLambda.sln @@ -107,6 +107,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MinimalLambda.Example.Durab EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MinimalLambda.Example.EventProcessor", "examples\MinimalLambda.Example.EventProcessor\MinimalLambda.Example.EventProcessor.csproj", "{42070274-45C6-4939-87D9-AD7E70F419F9}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MinimalLambda.Testing.UnitTests.EventProcessorLambda", "tests\MinimalLambda.Testing.UnitTests\Lambdas\MinimalLambda.Testing.UnitTests.EventProcessorLambda\MinimalLambda.Testing.UnitTests.EventProcessorLambda.csproj", "{5BFFA5F3-9A74-4574-80B5-27968203E2F9}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -561,6 +563,18 @@ Global {42070274-45C6-4939-87D9-AD7E70F419F9}.Release|x64.Build.0 = Release|Any CPU {42070274-45C6-4939-87D9-AD7E70F419F9}.Release|x86.ActiveCfg = Release|Any CPU {42070274-45C6-4939-87D9-AD7E70F419F9}.Release|x86.Build.0 = Release|Any CPU + {5BFFA5F3-9A74-4574-80B5-27968203E2F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5BFFA5F3-9A74-4574-80B5-27968203E2F9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5BFFA5F3-9A74-4574-80B5-27968203E2F9}.Debug|x64.ActiveCfg = Debug|Any CPU + {5BFFA5F3-9A74-4574-80B5-27968203E2F9}.Debug|x64.Build.0 = Debug|Any CPU + {5BFFA5F3-9A74-4574-80B5-27968203E2F9}.Debug|x86.ActiveCfg = Debug|Any CPU + {5BFFA5F3-9A74-4574-80B5-27968203E2F9}.Debug|x86.Build.0 = Debug|Any CPU + {5BFFA5F3-9A74-4574-80B5-27968203E2F9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5BFFA5F3-9A74-4574-80B5-27968203E2F9}.Release|Any CPU.Build.0 = Release|Any CPU + {5BFFA5F3-9A74-4574-80B5-27968203E2F9}.Release|x64.ActiveCfg = Release|Any CPU + {5BFFA5F3-9A74-4574-80B5-27968203E2F9}.Release|x64.Build.0 = Release|Any CPU + {5BFFA5F3-9A74-4574-80B5-27968203E2F9}.Release|x86.ActiveCfg = Release|Any CPU + {5BFFA5F3-9A74-4574-80B5-27968203E2F9}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -606,5 +620,6 @@ Global {189636EE-6C05-46DB-8AEB-256F2617025C} = {D9109C8A-AFA8-49C8-A19C-381500902B4D} {998085AA-AEC6-45D9-9E51-26F09BD5138C} = {B36A84DF-456D-A817-6EDD-3EC3E7F6E11F} {42070274-45C6-4939-87D9-AD7E70F419F9} = {B36A84DF-456D-A817-6EDD-3EC3E7F6E11F} + {5BFFA5F3-9A74-4574-80B5-27968203E2F9} = {D9109C8A-AFA8-49C8-A19C-381500902B4D} EndGlobalSection EndGlobal diff --git a/scripts/test-package-compatibility.sh b/scripts/test-package-compatibility.sh index 37231d1a..0433b996 100755 --- a/scripts/test-package-compatibility.sh +++ b/scripts/test-package-compatibility.sh @@ -49,10 +49,11 @@ assert_warning_free() { assert_generated_once() { local project_dir=$1 local target=$2 + local generated=${3:-MinimalLambda.DurableHandlers.g.cs} local count [ -d "$project_dir/obj/generated/$target" ] || fail "generated output missing for $(basename "$project_dir")/$target" - count=$(find "$project_dir/obj/generated/$target" -type f -name 'MinimalLambda.DurableHandlers.g.cs' | wc -l | tr -d ' ') - [ "$count" = "1" ] || fail "expected one durable generated file for $(basename "$project_dir")/$target, found $count" + count=$(find "$project_dir/obj/generated/$target" -type f -name "$generated" | wc -l | tr -d ' ') + [ "$count" = "1" ] || fail "expected one $generated for $(basename "$project_dir")/$target, found $count" } pack() { @@ -95,6 +96,7 @@ restore_consumer() { build_consumer() { local name=$1 local project=$2 + local generated=${3:-MinimalLambda.DurableHandlers.g.cs} local project_dir project_dir=$(dirname "$project") run_logged "build-$name-net10.0" dotnet build "$project" \ @@ -107,7 +109,7 @@ build_consumer() { "/p:EmitCompilerGeneratedFiles=true" \ "/p:CompilerGeneratedFilesOutputPath=$project_dir/obj/generated/net10.0" assert_warning_free "$LOGS/build-$name-net10.0.log" - assert_generated_once "$project_dir" net10.0 + assert_generated_once "$project_dir" net10.0 "$generated" } case "${PACKAGE_COMPAT_RID:-}" in @@ -278,8 +280,8 @@ from xml.etree import ElementTree as ET root = Path(sys.argv[1]) projects = sorted(root.glob("*/*.csproj")) -if len(projects) != 5: - raise SystemExit(f"expected five copied consumer projects, found {len(projects)}") +if len(projects) != 6: + raise SystemExit(f"expected six copied consumer projects, found {len(projects)}") for project in projects: tree = ET.parse(project) references = [ @@ -290,6 +292,8 @@ for project in projects: expected = ["MinimalLambda", "MinimalLambda.DurableExecution"] if project.parent.name != "TaskConsumer": expected.append("Amazon.Lambda.DurableExecution") + if project.parent.name == "EventProcessorConsumer": + expected.append("Amazon.Lambda.SQSEvents") if references != expected: raise SystemExit(f"{project}: unexpected package references {references}") print("Copied consumers contain package references only.") @@ -322,17 +326,20 @@ PY TYPED="$CONSUMERS/TypedConsumer/TypedConsumer.csproj" TASK="$CONSUMERS/TaskConsumer/TaskConsumer.csproj" +EVENT="$CONSUMERS/EventProcessorConsumer/EventProcessorConsumer.csproj" OLD="$CONSUMERS/OldCoreConsumer/OldCoreConsumer.csproj" AOT="$CONSUMERS/AotConsumer/AotConsumer.csproj" INVALID="$CONSUMERS/InvalidSignatureConsumer/InvalidSignatureConsumer.csproj" restore_consumer typed "$TYPED" "$CORE_VERSION" restore_consumer task "$TASK" "$CORE_VERSION" +restore_consumer event-processor "$EVENT" "$CORE_VERSION" restore_consumer invalid-signature "$INVALID" "$CORE_VERSION" python3 - "$NUGET_PACKAGES" "$CORE_VERSION" "$DURABLE_VERSION" \ "$CONSUMERS/TypedConsumer/obj/project.assets.json" \ - "$CONSUMERS/TaskConsumer/obj/project.assets.json" <<'PY' + "$CONSUMERS/TaskConsumer/obj/project.assets.json" \ + "$CONSUMERS/EventProcessorConsumer/obj/project.assets.json" <<'PY' import json import sys from pathlib import Path @@ -352,9 +359,10 @@ for filename in sys.argv[4:]: print("Positive consumers resolved exact synthetic versions from isolated cache.") PY -rm -rf "$CONSUMERS/TypedConsumer/obj/generated" "$CONSUMERS/TaskConsumer/obj/generated" +rm -rf "$CONSUMERS/TypedConsumer/obj/generated" "$CONSUMERS/TaskConsumer/obj/generated" "$CONSUMERS/EventProcessorConsumer/obj/generated" build_consumer typed "$TYPED" build_consumer task "$TASK" +build_consumer event-processor "$EVENT" MinimalLambda.EventHandlers.g.cs rm -f "$LOGS/build-invalid-signature-net10.0.log" set +e diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs new file mode 100644 index 00000000..71c403ee --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs @@ -0,0 +1,275 @@ +using AwesomeAssertions; +using Microsoft.CodeAnalysis; + +namespace MinimalLambda.SourceGenerators.UnitTests; + +public class EventHandlerDiagnosticTests +{ + [Fact] + public void ReportsUnsupportedSignatureForInaccessibleItemType() + { + var result = RunGenerator( + """ + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + internal static class Program + { + private sealed class Item; + + public static void Main() + { + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => GetItems(), + handle: (Item item) => Task.CompletedTask); + } + + private static Item[] GetItems() => []; + } + + internal sealed class Batch; + """); + + result + .Diagnostics + .Should() + .NotBeEmpty() + .And + .OnlyContain(diagnostic => + diagnostic.Id == "LH0008" + && diagnostic.Severity == DiagnosticSeverity.Error + && diagnostic.Location.GetLineSpan().Path == "InputFile.cs"); + result + .GeneratedTrees + .Should() + .NotContain(tree => tree.FilePath.EndsWith( + "MinimalLambda.EventHandlers.g.cs", + StringComparison.Ordinal)); + } + + [Fact] + public void ReportsUnsupportedSignatureForRefParameter() + { + var result = RunGenerator( + """ + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item, ref int count) => count++; + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + """); + + result.Diagnostics.Should().OnlyContain(diagnostic => diagnostic.Id == "LH0008"); + } + + [Fact] + public void ReportsUnsupportedSignatureForStreamEventAndAwaitableResponse() + { + var result = RunGenerator( + """ + using System.Collections.Generic; + using System.IO; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Stream stream, ILambdaInvocationContext _) => System.Linq.Enumerable.Empty(), + handle: (Item item) => Task.CompletedTask, + createResponse: (IEnumerable items, ILambdaInvocationContext _) => Task.FromResult(new Response())); + + internal sealed class Item; + + internal sealed class Response; + """); + + result.Diagnostics.Should().OnlyContain(diagnostic => diagnostic.Id == "LH0008"); + } + + [Fact] + public void ReportsUnsupportedBindingForEventAttributeOnItemParameter() + { + var result = RunGenerator( + """ + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: ([FromEvent] Item item) => Task.CompletedTask); + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + """); + + var diagnostic = result.Diagnostics.Should().ContainSingle().Subject; + diagnostic.Id.Should().Be("LH0009"); + diagnostic.Location.GetLineSpan().Path.Should().Be("InputFile.cs"); + } + + [Fact] + public void ReportsUnsupportedBindingForDuplicateProcessingContext() + { + var result = RunGenerator( + """ + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item, IEventProcessingContext first, IEventProcessingContext second) => + Task.CompletedTask); + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + """); + + var diagnostic = result.Diagnostics.Should().ContainSingle().Subject; + diagnostic.Id.Should().Be("LH0009"); + diagnostic.Location.GetLineSpan().Path.Should().Be("InputFile.cs"); + } + + [Fact] + public void ReportsUnresolvedHandlerForReassignedDelegateLocal() + { + var result = RunGenerator( + """ + using System; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + Func handle = Handle; + handle = Handle; + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: handle); + + static Task Handle(Item item) => Task.CompletedTask; + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + """); + + var diagnostic = result.Diagnostics.Should().ContainSingle().Subject; + diagnostic.Id.Should().Be("LH0010"); + diagnostic.Location.GetLineSpan().Path.Should().Be("InputFile.cs"); + } + + [Fact] + public void ReportsDiscardedResultWhenMethodGroupReturnsTaskOfTForNoResultOverload() + { + var result = RunGenerator( + """ + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: Handle); + + static Task Handle(Item item) => Task.FromResult(item.Id); + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item + { + public int Id { get; set; } + } + """); + + var diagnostic = result.Diagnostics.Should().ContainSingle().Subject; + diagnostic.Id.Should().Be("LH0011"); + diagnostic.Location.GetLineSpan().Path.Should().Be("InputFile.cs"); + } + + [Fact] + public void InvalidRegistrationDoesNotSuppressValidRegistration() + { + var result = RunGenerator( + """ + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: ([FromEvent] Item item) => Task.CompletedTask); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => Task.CompletedTask); + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + """); + + result.Diagnostics.Select(diagnostic => diagnostic.Id).Should().Equal("LH0009"); + var tree = result + .GeneratedTrees + .Should() + .ContainSingle(generated => generated.FilePath.EndsWith( + "MinimalLambda.EventHandlers.g.cs", + StringComparison.Ordinal)) + .Subject; + CountOccurrences(tree.ToString(), "MapEventHandlerInterceptor").Should().Be(1); + } + + private static int CountOccurrences(string text, string value) + { + var count = 0; + var index = 0; + while ((index = text.IndexOf(value, index, StringComparison.Ordinal)) >= 0) + { + count++; + index += value.Length; + } + + return count; + } + + private static GeneratorDriverRunResult RunGenerator(string source) + { + var (driver, _) = GeneratorTestHelpers.GenerateFromSource(source); + return driver.GetRunResult(); + } +} diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs new file mode 100644 index 00000000..41be19b3 --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs @@ -0,0 +1,304 @@ +using System.Text; +using AwesomeAssertions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace MinimalLambda.SourceGenerators.UnitTests; + +public class EventHandlerDiscoveryTests +{ + [Fact] + public void GeneratesInterceptorsForAllFiftyFiveOverloads() + { + var source = BuildAllOverloadsSource(); + + var (driver, compilation) = GeneratorTestHelpers.GenerateFromSource(source); + var result = driver.GetRunResult(); + + result + .Diagnostics + .Should() + .BeEmpty( + "all supported overloads should generate, but found:\n" + + string.Join( + "\n", + result.Diagnostics.Select(diagnostic => + $" - {diagnostic.Id}: {diagnostic.GetMessage()}"))); + + var tree = result + .GeneratedTrees + .Should() + .ContainSingle(generated => generated.FilePath.EndsWith( + "MinimalLambda.EventHandlers.g.cs", + StringComparison.Ordinal)) + .Subject; + CountOccurrences(tree.ToString(), "MapEventHandlerInterceptor").Should().Be(55); + + var errors = CompileWithGenerated(compilation, result) + .GetDiagnostics(TestContext.Current.CancellationToken) + .Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) + .ToList(); + errors + .Should() + .BeEmpty( + "generated interceptors should compile, but found:\n" + + string.Join( + "\n", + errors.Select(error => $" - {error.Id}: {error.GetMessage()}"))); + } + + [Theory] + [InlineData("(Item item) => Task.CompletedTask")] + [InlineData("Handle")] + [InlineData("handler")] + [InlineData("LocalHandler")] + public void RecognizesSupportedHandlerForms(string handler) + { + var source = $$""" + using System; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + internal static class Program + { + private static readonly Func handler = Handle; + + private static Task Handle(Item item) => Task.CompletedTask; + + public static void Main() + { + Task LocalHandler(Item item) => Task.CompletedTask; + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: {{handler}}); + } + } + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + """; + + RunGenerator(source).Diagnostics.Should().BeEmpty(); + } + + [Fact] + public void RecognizesTypedDelegateLocalAndExplicitGenericArguments() + { + var result = RunGenerator( + """ + using System; + using System.Collections.Generic; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + + Func> handle = Handle; + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: handle, + createResponse: (IEnumerable results, ILambdaInvocationContext _) => new Response()); + + app.MapEventHandler( + (Batch batch, ILambdaInvocationContext _) => batch.Items, + Handle); + + static Task Handle(Item item, Probe probe) => Task.FromResult(probe.Value); + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + + internal sealed class Probe + { + public int Value => 1; + } + + internal sealed class Response; + """); + + result.Diagnostics.Should().BeEmpty(); + result + .GeneratedTrees + .Should() + .ContainSingle(tree => tree.FilePath.EndsWith( + "MinimalLambda.EventHandlers.g.cs", + StringComparison.Ordinal)); + } + + [Fact] + public void IgnoresSameNamedMapEventHandlerFromConsumerAssembly() + { + var result = RunGenerator( + """ + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + namespace MinimalLambda.Builder + { + internal static class MapEventHandlerLambdaApplicationExtensions + { + extension(ILambdaInvocationBuilder builder) + { + public void MapEventHandler( + System.Func> split, + System.Func handle) { } + } + } + } + + internal static class Program + { + public static void Main() + { + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => Task.CompletedTask); + } + } + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + """); + + result.Diagnostics.Should().BeEmpty(); + result.GeneratedTrees.Should().BeEmpty(); + } + + private static GeneratorDriverRunResult RunGenerator(string source) + { + var (driver, _) = GeneratorTestHelpers.GenerateFromSource(source); + return driver.GetRunResult(); + } + + private static Compilation CompileWithGenerated( + Compilation originalCompilation, + GeneratorDriverRunResult result) + { + var parseOptions = originalCompilation.SyntaxTrees.First().Options; + var generatedTrees = result + .GeneratedTrees + .Select(tree => CSharpSyntaxTree.ParseText( + tree.GetText(), + (CSharpParseOptions)parseOptions, + tree.FilePath)) + .ToArray(); + return originalCompilation.AddSyntaxTrees(generatedTrees); + } + + private static int CountOccurrences(string text, string value) + { + var count = 0; + var index = 0; + while ((index = text.IndexOf(value, index, StringComparison.Ordinal)) >= 0) + { + count++; + index += value.Length; + } + + return count; + } + + private static string BuildAllOverloadsSource() + { + var builder = new StringBuilder(); + builder.AppendLine( + """ + using System; + using System.Collections.Generic; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item + { + public int Id { get; set; } + } + + internal sealed class Response; + """); + for (var index = 0; index < 10; index++) + builder.AppendLine($"internal sealed class Probe{index};"); + + builder.AppendLine("internal static class Program"); + builder.AppendLine("{"); + builder.AppendLine(" public static void Main()"); + builder.AppendLine(" {"); + builder.AppendLine(" var app = LambdaApplication.CreateBuilder().Build();"); + + for (var arity = 0; arity <= 10; arity++) + { + var parameters = BuildProbeParameters(arity); + + builder.AppendLine( + $$""" + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item{{parameters}}) => Task.CompletedTask); + """); + builder.AppendLine( + $$""" + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item{{parameters}}) => Task.CompletedTask, + createResponse: (IEnumerable items, ILambdaInvocationContext _) => new Response()); + """); + builder.AppendLine( + $$""" + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item{{parameters}}) => Task.CompletedTask, + onError: (Item item, Exception exception, IEventProcessingContext processing) => item.Id, + createResponse: (IEnumerable failures, ILambdaInvocationContext _) => new Response()); + """); + builder.AppendLine( + $$""" + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item{{parameters}}) => Task.FromResult(item.Id), + createResponse: (IEnumerable results, ILambdaInvocationContext _) => new Response()); + """); + builder.AppendLine( + $$""" + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item{{parameters}}) => Task.FromResult(item.Id), + onError: (Item item, Exception exception, IEventProcessingContext processing) => item.Id, + createResponse: (IEnumerable results, ILambdaInvocationContext _) => new Response()); + """); + } + + builder.AppendLine(" }"); + builder.AppendLine("}"); + return builder.ToString(); + } + + private static string BuildProbeParameters(int arity) + { + var builder = new StringBuilder(); + for (var index = 0; index < arity; index++) + builder.Append($", Probe{index} probe{index}"); + return builder.ToString(); + } +} diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs new file mode 100644 index 00000000..90f106b0 --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs @@ -0,0 +1,156 @@ +using AwesomeAssertions; +using Microsoft.CodeAnalysis; + +namespace MinimalLambda.SourceGenerators.UnitTests; + +public class EventHandlerEmitterTests +{ + [Fact] + public Task EmitsRepresentativeAdapterForEveryFamily() => + GeneratorTestHelpers.Verify( + """ + using System; + using System.Collections.Generic; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => Task.CompletedTask); + + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => Task.CompletedTask, + createResponse: (IEnumerable items, ILambdaInvocationContext _) => new Response()); + + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => Task.CompletedTask, + onError: (Item item, Exception exception, IEventProcessingContext _) => item.Id, + createResponse: (IEnumerable failures, ILambdaInvocationContext _) => new Response()); + + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => Task.FromResult(item.Id), + createResponse: (IEnumerable results, ILambdaInvocationContext _) => new Response()); + + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => Task.FromResult(item.Id), + onError: (Item item, Exception exception, IEventProcessingContext _) => item.Id, + createResponse: (IEnumerable results, ILambdaInvocationContext _) => new Response()); + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item + { + public int Id { get; set; } + } + + internal sealed class Response; + """); + + [Fact] + public Task EmitsContextTokenAndKeyedServiceBindings() => + GeneratorTestHelpers.Verify( + """ + using System; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using Amazon.Lambda.Core; + using Microsoft.Extensions.DependencyInjection; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: async Task ( + Item item, + ILambdaContext lambdaContext, + IEventProcessingContext processing, + CancellationToken token, + [FromServices] Service service, + [FromKeyedServices("primary")] Service keyed) => + { + await Task.Yield(); + _ = lambdaContext.AwsRequestId; + _ = processing.CancellationToken; + token.ThrowIfCancellationRequested(); + return item.Id + service.Value + keyed.Value; + }, + onError: (item, _, _) => item.Id, + createResponse: (IEnumerable results, ILambdaInvocationContext _) => new Response()); + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item + { + public int Id { get; set; } + } + + internal sealed class Service + { + public int Value => 1; + } + + internal sealed class Response; + """); + + [Fact] + public void EmitsSingleDeterministicFileForMultipleSites() + { + const string source = """ + using System.Collections.Generic; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => Task.CompletedTask); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => Task.CompletedTask, + createResponse: (IEnumerable items, ILambdaInvocationContext _) => new Response()); + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + + internal sealed class Response; + """; + + var (driver, _) = GeneratorTestHelpers.GenerateFromSource(source); + var result = driver.GetRunResult(); + + result.Diagnostics.Should().BeEmpty(); + result + .GeneratedTrees + .Should() + .ContainSingle(tree => tree.FilePath.EndsWith( + "MinimalLambda.EventHandlers.g.cs", + StringComparison.Ordinal)); + + var generated = result.GeneratedTrees.Single().ToString(); + generated + .IndexOf("MapEventHandlerInterceptor0", StringComparison.Ordinal) + .Should() + .BeLessThan(generated.IndexOf("MapEventHandlerInterceptor1", StringComparison.Ordinal)); + } +} diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/GeneratorTestHelpers.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/GeneratorTestHelpers.cs index bfd64e05..8a39f34f 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/GeneratorTestHelpers.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/GeneratorTestHelpers.cs @@ -12,6 +12,7 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using MinimalLambda.Builder; @@ -160,6 +161,7 @@ .. Net80.References.All.ToList(), MetadataReference.CreateFromFile(typeof(DefaultLambdaJsonSerializer).Assembly.Location), MetadataReference.CreateFromFile(typeof(LambdaBootstrapBuilder).Assembly.Location), MetadataReference.CreateFromFile(typeof(IOptions<>).Assembly.Location), + MetadataReference.CreateFromFile(typeof(ILogger<>).Assembly.Location), MetadataReference.CreateFromFile(typeof(ILambdaInvocationContext).Assembly.Location), ]; diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsContextTokenAndKeyedServiceBindings#MinimalLambda.EventHandlers.g.verified.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsContextTokenAndKeyedServiceBindings#MinimalLambda.EventHandlers.g.verified.cs new file mode 100644 index 00000000..dee2de77 --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsContextTokenAndKeyedServiceBindings#MinimalLambda.EventHandlers.g.verified.cs @@ -0,0 +1,639 @@ +//HintName: MinimalLambda.EventHandlers.g.cs +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +#nullable enable + +namespace System.Runtime.CompilerServices +{ + using System.CodeDom.Compiler; + + [global::System.CodeDom.Compiler.GeneratedCode("MinimalLambda.SourceGenerators", "REPLACED")] + [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] + file sealed class InterceptsLocationAttribute : Attribute + { + public InterceptsLocationAttribute(int version, string data) { } + } +} + +namespace MinimalLambda.Generated +{ + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Runtime.ExceptionServices; + using System.Runtime.CompilerServices; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Logging; + using Microsoft.Extensions.Options; + using MinimalLambda.Builder; + using MinimalLambda.Options; + + [global::System.CodeDom.Compiler.GeneratedCode("MinimalLambda.SourceGenerators", "REPLACED")] + file static class GeneratedEventProcessorExtensions + { + private const string EventFeatureProviderKey = "__EventFeatureProvider"; + private const string ResponseFeatureProviderKey = "__ResponseFeatureProvider"; + + [InterceptsLocation(1, "REPLACED")] + internal static ILambdaInvocationBuilder MapEventHandlerInterceptor0( + this ILambdaInvocationBuilder application, + global::System.Func> split, + global::System.Func> handle, + global::System.Func onError, + global::System.Func, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) + { + ArgumentNullException.ThrowIfNull(application); + ArgumentNullException.ThrowIfNull(split); + ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(onError); + ArgumentNullException.ThrowIfNull(createResponse); + + var options = application.Services.GetRequiredService>().Value; + var effectiveConcurrency = options.EnableConcurrency + ? options.MaxConcurrentExecutions + : 1; + var scopeFactory = application.Services.GetRequiredService(); + var logger = application + .Services.GetService() + ?.CreateLogger("MinimalLambda.EventProcessor"); + + application.Handle(InvocationDelegate); + + if (!application.Properties.ContainsKey(EventFeatureProviderKey)) + application.Properties[EventFeatureProviderKey] = application + .Services.GetRequiredService() + .Create(); + + if (!application.Properties.ContainsKey(ResponseFeatureProviderKey)) + application.Properties[ResponseFeatureProviderKey] = application + .Services.GetRequiredService() + .Create(); + + return application; + + async Task InvocationDelegate(ILambdaInvocationContext context) + { + if (context.CancellationToken.IsCancellationRequested) + throw new OperationCanceledException(context.CancellationToken); + + _ = context.ServiceProvider; + + var lambdaEvent = context.GetRequiredEvent(); + var splitItems = split(lambdaEvent, context); + if (splitItems is null) + throw new InvalidOperationException("The event splitter 'split' returned null."); + + var items = new List(); + using (var enumerator = splitItems.GetEnumerator()) + { + while (enumerator.MoveNext()) + { + context.CancellationToken.ThrowIfCancellationRequested(); + items.Add(enumerator.Current); + } + } + + var itemArray = items.ToArray(); + + if (context.CancellationToken.IsCancellationRequested) + throw new OperationCanceledException(context.CancellationToken); + + using var state = new EventProcessingState( + context, + logger, + itemArray.Length); + var outcomes = await EventProcessorRuntime + .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, true) + .ConfigureAwait(false); + + var contributions = new List(outcomes!.Length); + foreach (var outcome in outcomes) + if (outcome.HasValue) + contributions.Add(outcome.Value!); + + var response = createResponse( + new ReadOnlyCollection(contributions), + context); + + if (context.Features.Get() is not IResponseFeature responseFeature) + throw new InvalidOperationException( + "Response feature for type 'global::Response' is not available in the collection."); + responseFeature.SetResponse(response); + } + + async Task> Adapt( + global::Item item, + IServiceProvider serviceProvider, + EventProcessingState processingContext) + { + if (serviceProvider.GetService() is not IServiceProviderIsKeyedService) + throw new InvalidOperationException( + $"Unable to resolve service referenced by {nameof(FromKeyedServicesAttribute)}. The service provider doesn't support keyed services."); + var arg0 = item; + var arg1 = processingContext.Invocation; + var arg2 = processingContext; + var arg3 = processingContext.CancellationToken; + var arg4 = serviceProvider.GetRequiredService(); + var arg5 = serviceProvider.GetRequiredKeyedService("primary"); + + var invocationToken = processingContext.Invocation.CancellationToken; + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException(invocationToken); + if (processingContext.CancellationToken.IsCancellationRequested) + return ItemOutcome.Cancelled; + + Task? handlerTask = null; + int handlerResult = default!; + Exception? synchronousFault = null; + try + { + handlerTask = handle(arg0, arg1, arg2, arg3, arg4, arg5); + } + catch (Exception ex) + { + synchronousFault = ex; + } + + if (synchronousFault is null && handlerTask is null) + throw new InvalidOperationException("The event handler 'handle' returned a null task."); + + try + { + if (synchronousFault is not null) + ExceptionDispatchInfo.Capture(synchronousFault).Throw(); + + handlerResult = await handlerTask!.ConfigureAwait(false); + } + catch (Exception ex) + { + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while processing an item.", + ex, + invocationToken); + + if (ex is OperationCanceledException + && processingContext.CancellationToken.IsCancellationRequested) + return ItemOutcome.Cancelled; + + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException(invocationToken); + + var mapped = onError(item, ex, processingContext); + + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while mapping an item error.", + invocationToken); + + return ItemOutcome.FromMappedValue(mapped); + } + + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while processing an item.", + invocationToken); + + return ItemOutcome.FromValue(handlerResult); + } + } + } + + file readonly struct NoData; + + file enum ItemExecutionState + { + Unstarted, + Succeeded, + MappedError, + Cancelled, + } + + file readonly struct ItemOutcome + { + private ItemOutcome(ItemExecutionState state, bool hasValue, TValue? value) + { + State = state; + HasValue = hasValue; + Value = value; + } + + internal ItemExecutionState State { get; } + + internal bool HasValue { get; } + + internal TValue? Value { get; } + + internal static ItemOutcome FromValue(TValue? value) => + new(ItemExecutionState.Succeeded, true, value); + + internal static ItemOutcome FromMappedValue(TValue? value) => + new(ItemExecutionState.MappedError, true, value); + + internal static ItemOutcome NoValue => + new(ItemExecutionState.Succeeded, false, default); + + internal static ItemOutcome Cancelled => + new(ItemExecutionState.Cancelled, false, default); + } + + file sealed class EventProcessingState : IEventProcessingContext, IDisposable + { + private readonly object _gate = new(); + private readonly ILambdaInvocationContext _invocation; + private readonly ILogger? _logger; + private readonly int _itemCount; + private readonly CancellationTokenSource _processingSource = new(); + private readonly CancellationTokenRegistration _invocationRegistration; + + private int _nextIndex; + private int _admitted; + private bool _stopRequested; + private bool _cancelRequested; + private bool _handlingClosed; + private bool _completed; + private bool _invocationCancelled; + private bool _disposed; + private ExceptionDispatchInfo? _firstFatal; + private List? _additionalFatal; + private TaskCompletionSource? _dispatchCompletion; + + internal EventProcessingState( + ILambdaInvocationContext invocation, + ILogger? logger, + int itemCount) + { + _invocation = invocation; + _logger = logger; + _itemCount = itemCount; + _invocationRegistration = invocation.CancellationToken.Register( + static state => ((EventProcessingState)state!).OnInvocationTokenCancelled(), + this); + } + + public ILambdaInvocationContext Invocation => _invocation; + + public CancellationToken CancellationToken => _processingSource.Token; + + public void StopProcessing() + { + lock (_gate) + { + if (_completed || _handlingClosed) + return; + + _stopRequested = true; + TryCloseHandlingCore(); + } + } + + public void CancelProcessing() => RequestProcessingCancellation(false); + + internal bool TryClaim(out int index) + { + TaskCompletionSource? dispatch = null; + var claimed = false; + index = -1; + + lock (_gate) + { + if (_completed) + return false; + + ObserveInvocationCancellationCore(ref dispatch); + + if (_handlingClosed + || _stopRequested + || _firstFatal is not null + || _nextIndex >= _itemCount) + { + TryCloseHandlingCore(); + } + else + { + index = _nextIndex++; + _admitted++; + claimed = true; + } + } + + if (dispatch is not null) + StartDispatch(dispatch); + + return claimed; + } + + internal bool IsInvocationCancellationLatched + { + get + { + lock (_gate) + return _invocationCancelled; + } + } + + internal void CompleteAdmission() + { + lock (_gate) + { + if (_admitted > 0) + _admitted--; + + TryCloseHandlingCore(); + } + } + + internal bool TryLatchInvocationCancellation() + { + if (!_invocation.CancellationToken.IsCancellationRequested) + return false; + + RequestProcessingCancellation(true); + + lock (_gate) + return _invocationCancelled; + } + + internal void RecordFatal(Exception exception) + { + lock (_gate) + { + if (_completed) + return; + + _stopRequested = true; + var fatal = ExceptionDispatchInfo.Capture(exception); + if (_firstFatal is null) + _firstFatal = fatal; + else + (_additionalFatal ??= []).Add(exception); + + TryCloseHandlingCore(); + } + } + + internal void TryCloseHandling() + { + lock (_gate) + TryCloseHandlingCore(); + } + + internal async Task JoinAsync() + { + Task? dispatch; + lock (_gate) + { + TryCloseHandlingCore(); + dispatch = _dispatchCompletion?.Task; + } + + if (dispatch is not null) + await dispatch.ConfigureAwait(false); + + Completion completion; + lock (_gate) + { + TryCloseHandlingCore(); + _completed = true; + completion = new Completion( + _invocationCancelled, + _firstFatal, + _additionalFatal); + } + + completion.LogAdditional(_logger); + + if (completion.InvocationCancelled) + throw new OperationCanceledException( + "The Lambda invocation was cancelled during item processing.", + _invocation.CancellationToken); + + if (completion.FirstFatal is not null) + { + completion.FirstFatal.Throw(); + throw new InvalidOperationException("Unreachable"); + } + } + + public void Dispose() + { + if (_disposed) + return; + + _disposed = true; + _invocationRegistration.Dispose(); + _processingSource.Dispose(); + } + + private void OnInvocationTokenCancelled() => RequestProcessingCancellation(true); + + private void RequestProcessingCancellation(bool invocationCancelled) + { + TaskCompletionSource? dispatch = null; + lock (_gate) + { + if (_completed || _handlingClosed) + return; + + if (invocationCancelled) + _invocationCancelled = true; + + _stopRequested = true; + + if (!_cancelRequested) + { + _cancelRequested = true; + _dispatchCompletion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + dispatch = _dispatchCompletion; + } + + TryCloseHandlingCore(); + } + + if (dispatch is not null) + StartDispatch(dispatch); + } + + private void ObserveInvocationCancellationCore(ref TaskCompletionSource? dispatch) + { + if (_handlingClosed || !_invocation.CancellationToken.IsCancellationRequested) + return; + + _invocationCancelled = true; + _stopRequested = true; + + if (_cancelRequested) + return; + + _cancelRequested = true; + _dispatchCompletion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + dispatch = _dispatchCompletion; + } + + private void TryCloseHandlingCore() + { + if (_handlingClosed) + return; + + if (_admitted > 0) + return; + + if (_nextIndex < _itemCount + && !_stopRequested + && _firstFatal is null + && !_invocation.CancellationToken.IsCancellationRequested) + return; + + if (_invocation.CancellationToken.IsCancellationRequested) + { + _invocationCancelled = true; + _stopRequested = true; + } + + _handlingClosed = true; + } + + private void StartDispatch(TaskCompletionSource completion) => + _ = DispatchCancellationAsync(completion); + + private async Task DispatchCancellationAsync(TaskCompletionSource completion) + { + try + { + await _processingSource.CancelAsync().ConfigureAwait(false); + } + catch (Exception ex) + { + RecordFatal(ex); + } + finally + { + completion.TrySetResult(); + } + } + + private readonly struct Completion( + bool invocationCancelled, + ExceptionDispatchInfo? firstFatal, + List? additionalFatal) + { + internal bool InvocationCancelled { get; } = invocationCancelled; + + internal ExceptionDispatchInfo? FirstFatal { get; } = firstFatal; + + internal void LogAdditional(ILogger? logger) + { + if (logger is null || additionalFatal is null) + return; + + foreach (var exception in additionalFatal) + try + { + logger.LogError( + exception, + "Event processor observed an additional failure while draining item work."); + } + catch + { + // Logging must not replace the selected invocation error. + } + } + } + } + + file static class EventProcessorRuntime + { + internal static async Task[]?> RunAsync( + TItem[] items, + int effectiveConcurrency, + IServiceScopeFactory scopeFactory, + EventProcessingState state, + Func>> adapter, + bool collectValues) + { + if (items.Length == 0) + state.TryCloseHandling(); + + var outcomes = collectValues ? new ItemOutcome[items.Length] : null; + var workerCount = Math.Min(items.Length, Math.Max(1, effectiveConcurrency)); + var workers = new Task[workerCount]; + + for (var index = 0; index < workerCount; index++) + workers[index] = RunWorkerAsync(); + + await Task.WhenAll(workers).ConfigureAwait(false); + await state.JoinAsync().ConfigureAwait(false); + + return outcomes; + + async Task RunWorkerAsync() + { + while (state.TryClaim(out var index)) + { + if (state.IsInvocationCancellationLatched) + { + state.CompleteAdmission(); + continue; + } + + AsyncServiceScope scope; + try + { + scope = scopeFactory.CreateAsyncScope(); + } + catch (Exception ex) + { + state.RecordFatal(ex); + state.CompleteAdmission(); + continue; + } + + ItemOutcome outcome = default; + var hasOutcome = false; + + try + { + try + { + outcome = await adapter(items[index], scope.ServiceProvider, state) + .ConfigureAwait(false); + hasOutcome = true; + } + catch (Exception ex) + { + if (!state.TryLatchInvocationCancellation()) + state.RecordFatal(ex); + } + } + finally + { + state.CompleteAdmission(); + } + + try + { + await scope.DisposeAsync().ConfigureAwait(false); + } + catch (Exception ex) + { + state.RecordFatal(ex); + } + + if (collectValues && hasOutcome && outcome.HasValue) + outcomes![index] = outcome; + } + } + } + } +} diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsRepresentativeAdapterForEveryFamily#MinimalLambda.EventHandlers.g.verified.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsRepresentativeAdapterForEveryFamily#MinimalLambda.EventHandlers.g.verified.cs new file mode 100644 index 00000000..69a39fa8 --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsRepresentativeAdapterForEveryFamily#MinimalLambda.EventHandlers.g.verified.cs @@ -0,0 +1,1194 @@ +//HintName: MinimalLambda.EventHandlers.g.cs +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +#nullable enable + +namespace System.Runtime.CompilerServices +{ + using System.CodeDom.Compiler; + + [global::System.CodeDom.Compiler.GeneratedCode("MinimalLambda.SourceGenerators", "REPLACED")] + [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] + file sealed class InterceptsLocationAttribute : Attribute + { + public InterceptsLocationAttribute(int version, string data) { } + } +} + +namespace MinimalLambda.Generated +{ + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Runtime.ExceptionServices; + using System.Runtime.CompilerServices; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Logging; + using Microsoft.Extensions.Options; + using MinimalLambda.Builder; + using MinimalLambda.Options; + + [global::System.CodeDom.Compiler.GeneratedCode("MinimalLambda.SourceGenerators", "REPLACED")] + file static class GeneratedEventProcessorExtensions + { + private const string EventFeatureProviderKey = "__EventFeatureProvider"; + private const string ResponseFeatureProviderKey = "__ResponseFeatureProvider"; + + [InterceptsLocation(1, "REPLACED")] + internal static ILambdaInvocationBuilder MapEventHandlerInterceptor0( + this ILambdaInvocationBuilder application, + global::System.Func> split, + global::System.Func handle) + { + ArgumentNullException.ThrowIfNull(application); + ArgumentNullException.ThrowIfNull(split); + ArgumentNullException.ThrowIfNull(handle); + + var options = application.Services.GetRequiredService>().Value; + var effectiveConcurrency = options.EnableConcurrency + ? options.MaxConcurrentExecutions + : 1; + var scopeFactory = application.Services.GetRequiredService(); + var logger = application + .Services.GetService() + ?.CreateLogger("MinimalLambda.EventProcessor"); + + application.Handle(InvocationDelegate); + + if (!application.Properties.ContainsKey(EventFeatureProviderKey)) + application.Properties[EventFeatureProviderKey] = application + .Services.GetRequiredService() + .Create(); + + return application; + + async Task InvocationDelegate(ILambdaInvocationContext context) + { + if (context.CancellationToken.IsCancellationRequested) + throw new OperationCanceledException(context.CancellationToken); + + _ = context.ServiceProvider; + + var lambdaEvent = context.GetRequiredEvent(); + var splitItems = split(lambdaEvent, context); + if (splitItems is null) + throw new InvalidOperationException("The event splitter 'split' returned null."); + + var items = new List(); + using (var enumerator = splitItems.GetEnumerator()) + { + while (enumerator.MoveNext()) + { + context.CancellationToken.ThrowIfCancellationRequested(); + items.Add(enumerator.Current); + } + } + + var itemArray = items.ToArray(); + + if (context.CancellationToken.IsCancellationRequested) + throw new OperationCanceledException(context.CancellationToken); + + using var state = new EventProcessingState( + context, + logger, + itemArray.Length); + var outcomes = await EventProcessorRuntime + .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, false) + .ConfigureAwait(false); + } + + async Task> Adapt( + global::Item item, + IServiceProvider serviceProvider, + EventProcessingState processingContext) + { + var arg0 = item; + + var invocationToken = processingContext.Invocation.CancellationToken; + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException(invocationToken); + if (processingContext.CancellationToken.IsCancellationRequested) + return ItemOutcome.Cancelled; + + Task? handlerTask = null; + + Exception? synchronousFault = null; + try + { + handlerTask = handle(arg0); + } + catch (Exception ex) + { + synchronousFault = ex; + } + + if (synchronousFault is null && handlerTask is null) + throw new InvalidOperationException("The event handler 'handle' returned a null task."); + + try + { + if (synchronousFault is not null) + ExceptionDispatchInfo.Capture(synchronousFault).Throw(); + + await handlerTask!.ConfigureAwait(false); + } + catch (Exception ex) + { + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while processing an item.", + ex, + invocationToken); + + if (ex is OperationCanceledException + && processingContext.CancellationToken.IsCancellationRequested) + return ItemOutcome.Cancelled; + + throw; + } + + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while processing an item.", + invocationToken); + + return ItemOutcome.NoValue; + } + } + [InterceptsLocation(1, "REPLACED")] + internal static ILambdaInvocationBuilder MapEventHandlerInterceptor1( + this ILambdaInvocationBuilder application, + global::System.Func> split, + global::System.Func handle, + global::System.Func, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) + { + ArgumentNullException.ThrowIfNull(application); + ArgumentNullException.ThrowIfNull(split); + ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(createResponse); + + var options = application.Services.GetRequiredService>().Value; + var effectiveConcurrency = options.EnableConcurrency + ? options.MaxConcurrentExecutions + : 1; + var scopeFactory = application.Services.GetRequiredService(); + var logger = application + .Services.GetService() + ?.CreateLogger("MinimalLambda.EventProcessor"); + + application.Handle(InvocationDelegate); + + if (!application.Properties.ContainsKey(EventFeatureProviderKey)) + application.Properties[EventFeatureProviderKey] = application + .Services.GetRequiredService() + .Create(); + + if (!application.Properties.ContainsKey(ResponseFeatureProviderKey)) + application.Properties[ResponseFeatureProviderKey] = application + .Services.GetRequiredService() + .Create(); + + return application; + + async Task InvocationDelegate(ILambdaInvocationContext context) + { + if (context.CancellationToken.IsCancellationRequested) + throw new OperationCanceledException(context.CancellationToken); + + _ = context.ServiceProvider; + + var lambdaEvent = context.GetRequiredEvent(); + var splitItems = split(lambdaEvent, context); + if (splitItems is null) + throw new InvalidOperationException("The event splitter 'split' returned null."); + + var items = new List(); + using (var enumerator = splitItems.GetEnumerator()) + { + while (enumerator.MoveNext()) + { + context.CancellationToken.ThrowIfCancellationRequested(); + items.Add(enumerator.Current); + } + } + + var itemArray = items.ToArray(); + + if (context.CancellationToken.IsCancellationRequested) + throw new OperationCanceledException(context.CancellationToken); + + using var state = new EventProcessingState( + context, + logger, + itemArray.Length); + var outcomes = await EventProcessorRuntime + .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, true) + .ConfigureAwait(false); + + var contributions = new List(outcomes!.Length); + foreach (var outcome in outcomes) + if (outcome.HasValue) + contributions.Add(outcome.Value!); + + var response = createResponse( + new ReadOnlyCollection(contributions), + context); + + if (context.Features.Get() is not IResponseFeature responseFeature) + throw new InvalidOperationException( + "Response feature for type 'global::Response' is not available in the collection."); + responseFeature.SetResponse(response); + } + + async Task> Adapt( + global::Item item, + IServiceProvider serviceProvider, + EventProcessingState processingContext) + { + var arg0 = item; + + var invocationToken = processingContext.Invocation.CancellationToken; + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException(invocationToken); + if (processingContext.CancellationToken.IsCancellationRequested) + return ItemOutcome.Cancelled; + + Task? handlerTask = null; + + Exception? synchronousFault = null; + try + { + handlerTask = handle(arg0); + } + catch (Exception ex) + { + synchronousFault = ex; + } + + if (synchronousFault is null && handlerTask is null) + throw new InvalidOperationException("The event handler 'handle' returned a null task."); + + try + { + if (synchronousFault is not null) + ExceptionDispatchInfo.Capture(synchronousFault).Throw(); + + await handlerTask!.ConfigureAwait(false); + } + catch (Exception ex) + { + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while processing an item.", + ex, + invocationToken); + + if (ex is OperationCanceledException + && processingContext.CancellationToken.IsCancellationRequested) + return ItemOutcome.Cancelled; + + throw; + } + + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while processing an item.", + invocationToken); + + return ItemOutcome.FromValue(item); + } + } + [InterceptsLocation(1, "REPLACED")] + internal static ILambdaInvocationBuilder MapEventHandlerInterceptor2( + this ILambdaInvocationBuilder application, + global::System.Func> split, + global::System.Func handle, + global::System.Func onError, + global::System.Func, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) + { + ArgumentNullException.ThrowIfNull(application); + ArgumentNullException.ThrowIfNull(split); + ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(onError); + ArgumentNullException.ThrowIfNull(createResponse); + + var options = application.Services.GetRequiredService>().Value; + var effectiveConcurrency = options.EnableConcurrency + ? options.MaxConcurrentExecutions + : 1; + var scopeFactory = application.Services.GetRequiredService(); + var logger = application + .Services.GetService() + ?.CreateLogger("MinimalLambda.EventProcessor"); + + application.Handle(InvocationDelegate); + + if (!application.Properties.ContainsKey(EventFeatureProviderKey)) + application.Properties[EventFeatureProviderKey] = application + .Services.GetRequiredService() + .Create(); + + if (!application.Properties.ContainsKey(ResponseFeatureProviderKey)) + application.Properties[ResponseFeatureProviderKey] = application + .Services.GetRequiredService() + .Create(); + + return application; + + async Task InvocationDelegate(ILambdaInvocationContext context) + { + if (context.CancellationToken.IsCancellationRequested) + throw new OperationCanceledException(context.CancellationToken); + + _ = context.ServiceProvider; + + var lambdaEvent = context.GetRequiredEvent(); + var splitItems = split(lambdaEvent, context); + if (splitItems is null) + throw new InvalidOperationException("The event splitter 'split' returned null."); + + var items = new List(); + using (var enumerator = splitItems.GetEnumerator()) + { + while (enumerator.MoveNext()) + { + context.CancellationToken.ThrowIfCancellationRequested(); + items.Add(enumerator.Current); + } + } + + var itemArray = items.ToArray(); + + if (context.CancellationToken.IsCancellationRequested) + throw new OperationCanceledException(context.CancellationToken); + + using var state = new EventProcessingState( + context, + logger, + itemArray.Length); + var outcomes = await EventProcessorRuntime + .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, true) + .ConfigureAwait(false); + + var contributions = new List(outcomes!.Length); + foreach (var outcome in outcomes) + if (outcome.HasValue) + contributions.Add(outcome.Value!); + + var response = createResponse( + new ReadOnlyCollection(contributions), + context); + + if (context.Features.Get() is not IResponseFeature responseFeature) + throw new InvalidOperationException( + "Response feature for type 'global::Response' is not available in the collection."); + responseFeature.SetResponse(response); + } + + async Task> Adapt( + global::Item item, + IServiceProvider serviceProvider, + EventProcessingState processingContext) + { + var arg0 = item; + + var invocationToken = processingContext.Invocation.CancellationToken; + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException(invocationToken); + if (processingContext.CancellationToken.IsCancellationRequested) + return ItemOutcome.Cancelled; + + Task? handlerTask = null; + + Exception? synchronousFault = null; + try + { + handlerTask = handle(arg0); + } + catch (Exception ex) + { + synchronousFault = ex; + } + + if (synchronousFault is null && handlerTask is null) + throw new InvalidOperationException("The event handler 'handle' returned a null task."); + + try + { + if (synchronousFault is not null) + ExceptionDispatchInfo.Capture(synchronousFault).Throw(); + + await handlerTask!.ConfigureAwait(false); + } + catch (Exception ex) + { + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while processing an item.", + ex, + invocationToken); + + if (ex is OperationCanceledException + && processingContext.CancellationToken.IsCancellationRequested) + return ItemOutcome.Cancelled; + + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException(invocationToken); + + var mapped = onError(item, ex, processingContext); + + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while mapping an item error.", + invocationToken); + + return ItemOutcome.FromMappedValue(mapped); + } + + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while processing an item.", + invocationToken); + + return ItemOutcome.NoValue; + } + } + [InterceptsLocation(1, "REPLACED")] + internal static ILambdaInvocationBuilder MapEventHandlerInterceptor3( + this ILambdaInvocationBuilder application, + global::System.Func> split, + global::System.Func> handle, + global::System.Func, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) + { + ArgumentNullException.ThrowIfNull(application); + ArgumentNullException.ThrowIfNull(split); + ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(createResponse); + + var options = application.Services.GetRequiredService>().Value; + var effectiveConcurrency = options.EnableConcurrency + ? options.MaxConcurrentExecutions + : 1; + var scopeFactory = application.Services.GetRequiredService(); + var logger = application + .Services.GetService() + ?.CreateLogger("MinimalLambda.EventProcessor"); + + application.Handle(InvocationDelegate); + + if (!application.Properties.ContainsKey(EventFeatureProviderKey)) + application.Properties[EventFeatureProviderKey] = application + .Services.GetRequiredService() + .Create(); + + if (!application.Properties.ContainsKey(ResponseFeatureProviderKey)) + application.Properties[ResponseFeatureProviderKey] = application + .Services.GetRequiredService() + .Create(); + + return application; + + async Task InvocationDelegate(ILambdaInvocationContext context) + { + if (context.CancellationToken.IsCancellationRequested) + throw new OperationCanceledException(context.CancellationToken); + + _ = context.ServiceProvider; + + var lambdaEvent = context.GetRequiredEvent(); + var splitItems = split(lambdaEvent, context); + if (splitItems is null) + throw new InvalidOperationException("The event splitter 'split' returned null."); + + var items = new List(); + using (var enumerator = splitItems.GetEnumerator()) + { + while (enumerator.MoveNext()) + { + context.CancellationToken.ThrowIfCancellationRequested(); + items.Add(enumerator.Current); + } + } + + var itemArray = items.ToArray(); + + if (context.CancellationToken.IsCancellationRequested) + throw new OperationCanceledException(context.CancellationToken); + + using var state = new EventProcessingState( + context, + logger, + itemArray.Length); + var outcomes = await EventProcessorRuntime + .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, true) + .ConfigureAwait(false); + + var contributions = new List(outcomes!.Length); + foreach (var outcome in outcomes) + if (outcome.HasValue) + contributions.Add(outcome.Value!); + + var response = createResponse( + new ReadOnlyCollection(contributions), + context); + + if (context.Features.Get() is not IResponseFeature responseFeature) + throw new InvalidOperationException( + "Response feature for type 'global::Response' is not available in the collection."); + responseFeature.SetResponse(response); + } + + async Task> Adapt( + global::Item item, + IServiceProvider serviceProvider, + EventProcessingState processingContext) + { + var arg0 = item; + + var invocationToken = processingContext.Invocation.CancellationToken; + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException(invocationToken); + if (processingContext.CancellationToken.IsCancellationRequested) + return ItemOutcome.Cancelled; + + Task? handlerTask = null; + int handlerResult = default!; + Exception? synchronousFault = null; + try + { + handlerTask = handle(arg0); + } + catch (Exception ex) + { + synchronousFault = ex; + } + + if (synchronousFault is null && handlerTask is null) + throw new InvalidOperationException("The event handler 'handle' returned a null task."); + + try + { + if (synchronousFault is not null) + ExceptionDispatchInfo.Capture(synchronousFault).Throw(); + + handlerResult = await handlerTask!.ConfigureAwait(false); + } + catch (Exception ex) + { + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while processing an item.", + ex, + invocationToken); + + if (ex is OperationCanceledException + && processingContext.CancellationToken.IsCancellationRequested) + return ItemOutcome.Cancelled; + + throw; + } + + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while processing an item.", + invocationToken); + + return ItemOutcome.FromValue(handlerResult); + } + } + [InterceptsLocation(1, "REPLACED")] + internal static ILambdaInvocationBuilder MapEventHandlerInterceptor4( + this ILambdaInvocationBuilder application, + global::System.Func> split, + global::System.Func> handle, + global::System.Func onError, + global::System.Func, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) + { + ArgumentNullException.ThrowIfNull(application); + ArgumentNullException.ThrowIfNull(split); + ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(onError); + ArgumentNullException.ThrowIfNull(createResponse); + + var options = application.Services.GetRequiredService>().Value; + var effectiveConcurrency = options.EnableConcurrency + ? options.MaxConcurrentExecutions + : 1; + var scopeFactory = application.Services.GetRequiredService(); + var logger = application + .Services.GetService() + ?.CreateLogger("MinimalLambda.EventProcessor"); + + application.Handle(InvocationDelegate); + + if (!application.Properties.ContainsKey(EventFeatureProviderKey)) + application.Properties[EventFeatureProviderKey] = application + .Services.GetRequiredService() + .Create(); + + if (!application.Properties.ContainsKey(ResponseFeatureProviderKey)) + application.Properties[ResponseFeatureProviderKey] = application + .Services.GetRequiredService() + .Create(); + + return application; + + async Task InvocationDelegate(ILambdaInvocationContext context) + { + if (context.CancellationToken.IsCancellationRequested) + throw new OperationCanceledException(context.CancellationToken); + + _ = context.ServiceProvider; + + var lambdaEvent = context.GetRequiredEvent(); + var splitItems = split(lambdaEvent, context); + if (splitItems is null) + throw new InvalidOperationException("The event splitter 'split' returned null."); + + var items = new List(); + using (var enumerator = splitItems.GetEnumerator()) + { + while (enumerator.MoveNext()) + { + context.CancellationToken.ThrowIfCancellationRequested(); + items.Add(enumerator.Current); + } + } + + var itemArray = items.ToArray(); + + if (context.CancellationToken.IsCancellationRequested) + throw new OperationCanceledException(context.CancellationToken); + + using var state = new EventProcessingState( + context, + logger, + itemArray.Length); + var outcomes = await EventProcessorRuntime + .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, true) + .ConfigureAwait(false); + + var contributions = new List(outcomes!.Length); + foreach (var outcome in outcomes) + if (outcome.HasValue) + contributions.Add(outcome.Value!); + + var response = createResponse( + new ReadOnlyCollection(contributions), + context); + + if (context.Features.Get() is not IResponseFeature responseFeature) + throw new InvalidOperationException( + "Response feature for type 'global::Response' is not available in the collection."); + responseFeature.SetResponse(response); + } + + async Task> Adapt( + global::Item item, + IServiceProvider serviceProvider, + EventProcessingState processingContext) + { + var arg0 = item; + + var invocationToken = processingContext.Invocation.CancellationToken; + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException(invocationToken); + if (processingContext.CancellationToken.IsCancellationRequested) + return ItemOutcome.Cancelled; + + Task? handlerTask = null; + int handlerResult = default!; + Exception? synchronousFault = null; + try + { + handlerTask = handle(arg0); + } + catch (Exception ex) + { + synchronousFault = ex; + } + + if (synchronousFault is null && handlerTask is null) + throw new InvalidOperationException("The event handler 'handle' returned a null task."); + + try + { + if (synchronousFault is not null) + ExceptionDispatchInfo.Capture(synchronousFault).Throw(); + + handlerResult = await handlerTask!.ConfigureAwait(false); + } + catch (Exception ex) + { + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while processing an item.", + ex, + invocationToken); + + if (ex is OperationCanceledException + && processingContext.CancellationToken.IsCancellationRequested) + return ItemOutcome.Cancelled; + + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException(invocationToken); + + var mapped = onError(item, ex, processingContext); + + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while mapping an item error.", + invocationToken); + + return ItemOutcome.FromMappedValue(mapped); + } + + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while processing an item.", + invocationToken); + + return ItemOutcome.FromValue(handlerResult); + } + } + } + + file readonly struct NoData; + + file enum ItemExecutionState + { + Unstarted, + Succeeded, + MappedError, + Cancelled, + } + + file readonly struct ItemOutcome + { + private ItemOutcome(ItemExecutionState state, bool hasValue, TValue? value) + { + State = state; + HasValue = hasValue; + Value = value; + } + + internal ItemExecutionState State { get; } + + internal bool HasValue { get; } + + internal TValue? Value { get; } + + internal static ItemOutcome FromValue(TValue? value) => + new(ItemExecutionState.Succeeded, true, value); + + internal static ItemOutcome FromMappedValue(TValue? value) => + new(ItemExecutionState.MappedError, true, value); + + internal static ItemOutcome NoValue => + new(ItemExecutionState.Succeeded, false, default); + + internal static ItemOutcome Cancelled => + new(ItemExecutionState.Cancelled, false, default); + } + + file sealed class EventProcessingState : IEventProcessingContext, IDisposable + { + private readonly object _gate = new(); + private readonly ILambdaInvocationContext _invocation; + private readonly ILogger? _logger; + private readonly int _itemCount; + private readonly CancellationTokenSource _processingSource = new(); + private readonly CancellationTokenRegistration _invocationRegistration; + + private int _nextIndex; + private int _admitted; + private bool _stopRequested; + private bool _cancelRequested; + private bool _handlingClosed; + private bool _completed; + private bool _invocationCancelled; + private bool _disposed; + private ExceptionDispatchInfo? _firstFatal; + private List? _additionalFatal; + private TaskCompletionSource? _dispatchCompletion; + + internal EventProcessingState( + ILambdaInvocationContext invocation, + ILogger? logger, + int itemCount) + { + _invocation = invocation; + _logger = logger; + _itemCount = itemCount; + _invocationRegistration = invocation.CancellationToken.Register( + static state => ((EventProcessingState)state!).OnInvocationTokenCancelled(), + this); + } + + public ILambdaInvocationContext Invocation => _invocation; + + public CancellationToken CancellationToken => _processingSource.Token; + + public void StopProcessing() + { + lock (_gate) + { + if (_completed || _handlingClosed) + return; + + _stopRequested = true; + TryCloseHandlingCore(); + } + } + + public void CancelProcessing() => RequestProcessingCancellation(false); + + internal bool TryClaim(out int index) + { + TaskCompletionSource? dispatch = null; + var claimed = false; + index = -1; + + lock (_gate) + { + if (_completed) + return false; + + ObserveInvocationCancellationCore(ref dispatch); + + if (_handlingClosed + || _stopRequested + || _firstFatal is not null + || _nextIndex >= _itemCount) + { + TryCloseHandlingCore(); + } + else + { + index = _nextIndex++; + _admitted++; + claimed = true; + } + } + + if (dispatch is not null) + StartDispatch(dispatch); + + return claimed; + } + + internal bool IsInvocationCancellationLatched + { + get + { + lock (_gate) + return _invocationCancelled; + } + } + + internal void CompleteAdmission() + { + lock (_gate) + { + if (_admitted > 0) + _admitted--; + + TryCloseHandlingCore(); + } + } + + internal bool TryLatchInvocationCancellation() + { + if (!_invocation.CancellationToken.IsCancellationRequested) + return false; + + RequestProcessingCancellation(true); + + lock (_gate) + return _invocationCancelled; + } + + internal void RecordFatal(Exception exception) + { + lock (_gate) + { + if (_completed) + return; + + _stopRequested = true; + var fatal = ExceptionDispatchInfo.Capture(exception); + if (_firstFatal is null) + _firstFatal = fatal; + else + (_additionalFatal ??= []).Add(exception); + + TryCloseHandlingCore(); + } + } + + internal void TryCloseHandling() + { + lock (_gate) + TryCloseHandlingCore(); + } + + internal async Task JoinAsync() + { + Task? dispatch; + lock (_gate) + { + TryCloseHandlingCore(); + dispatch = _dispatchCompletion?.Task; + } + + if (dispatch is not null) + await dispatch.ConfigureAwait(false); + + Completion completion; + lock (_gate) + { + TryCloseHandlingCore(); + _completed = true; + completion = new Completion( + _invocationCancelled, + _firstFatal, + _additionalFatal); + } + + completion.LogAdditional(_logger); + + if (completion.InvocationCancelled) + throw new OperationCanceledException( + "The Lambda invocation was cancelled during item processing.", + _invocation.CancellationToken); + + if (completion.FirstFatal is not null) + { + completion.FirstFatal.Throw(); + throw new InvalidOperationException("Unreachable"); + } + } + + public void Dispose() + { + if (_disposed) + return; + + _disposed = true; + _invocationRegistration.Dispose(); + _processingSource.Dispose(); + } + + private void OnInvocationTokenCancelled() => RequestProcessingCancellation(true); + + private void RequestProcessingCancellation(bool invocationCancelled) + { + TaskCompletionSource? dispatch = null; + lock (_gate) + { + if (_completed || _handlingClosed) + return; + + if (invocationCancelled) + _invocationCancelled = true; + + _stopRequested = true; + + if (!_cancelRequested) + { + _cancelRequested = true; + _dispatchCompletion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + dispatch = _dispatchCompletion; + } + + TryCloseHandlingCore(); + } + + if (dispatch is not null) + StartDispatch(dispatch); + } + + private void ObserveInvocationCancellationCore(ref TaskCompletionSource? dispatch) + { + if (_handlingClosed || !_invocation.CancellationToken.IsCancellationRequested) + return; + + _invocationCancelled = true; + _stopRequested = true; + + if (_cancelRequested) + return; + + _cancelRequested = true; + _dispatchCompletion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + dispatch = _dispatchCompletion; + } + + private void TryCloseHandlingCore() + { + if (_handlingClosed) + return; + + if (_admitted > 0) + return; + + if (_nextIndex < _itemCount + && !_stopRequested + && _firstFatal is null + && !_invocation.CancellationToken.IsCancellationRequested) + return; + + if (_invocation.CancellationToken.IsCancellationRequested) + { + _invocationCancelled = true; + _stopRequested = true; + } + + _handlingClosed = true; + } + + private void StartDispatch(TaskCompletionSource completion) => + _ = DispatchCancellationAsync(completion); + + private async Task DispatchCancellationAsync(TaskCompletionSource completion) + { + try + { + await _processingSource.CancelAsync().ConfigureAwait(false); + } + catch (Exception ex) + { + RecordFatal(ex); + } + finally + { + completion.TrySetResult(); + } + } + + private readonly struct Completion( + bool invocationCancelled, + ExceptionDispatchInfo? firstFatal, + List? additionalFatal) + { + internal bool InvocationCancelled { get; } = invocationCancelled; + + internal ExceptionDispatchInfo? FirstFatal { get; } = firstFatal; + + internal void LogAdditional(ILogger? logger) + { + if (logger is null || additionalFatal is null) + return; + + foreach (var exception in additionalFatal) + try + { + logger.LogError( + exception, + "Event processor observed an additional failure while draining item work."); + } + catch + { + // Logging must not replace the selected invocation error. + } + } + } + } + + file static class EventProcessorRuntime + { + internal static async Task[]?> RunAsync( + TItem[] items, + int effectiveConcurrency, + IServiceScopeFactory scopeFactory, + EventProcessingState state, + Func>> adapter, + bool collectValues) + { + if (items.Length == 0) + state.TryCloseHandling(); + + var outcomes = collectValues ? new ItemOutcome[items.Length] : null; + var workerCount = Math.Min(items.Length, Math.Max(1, effectiveConcurrency)); + var workers = new Task[workerCount]; + + for (var index = 0; index < workerCount; index++) + workers[index] = RunWorkerAsync(); + + await Task.WhenAll(workers).ConfigureAwait(false); + await state.JoinAsync().ConfigureAwait(false); + + return outcomes; + + async Task RunWorkerAsync() + { + while (state.TryClaim(out var index)) + { + if (state.IsInvocationCancellationLatched) + { + state.CompleteAdmission(); + continue; + } + + AsyncServiceScope scope; + try + { + scope = scopeFactory.CreateAsyncScope(); + } + catch (Exception ex) + { + state.RecordFatal(ex); + state.CompleteAdmission(); + continue; + } + + ItemOutcome outcome = default; + var hasOutcome = false; + + try + { + try + { + outcome = await adapter(items[index], scope.ServiceProvider, state) + .ConfigureAwait(false); + hasOutcome = true; + } + catch (Exception ex) + { + if (!state.TryLatchInvocationCancellation()) + state.RecordFatal(ex); + } + } + finally + { + state.CompleteAdmission(); + } + + try + { + await scope.DisposeAsync().ConfigureAwait(false); + } + catch (Exception ex) + { + state.RecordFatal(ex); + } + + if (collectValues && hasOutcome && outcome.HasValue) + outcomes![index] = outcome; + } + } + } + } +} diff --git a/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/MinimalLambda.Testing.UnitTests.EventProcessorLambda.csproj b/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/MinimalLambda.Testing.UnitTests.EventProcessorLambda.csproj new file mode 100644 index 00000000..4dff3634 --- /dev/null +++ b/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/MinimalLambda.Testing.UnitTests.EventProcessorLambda.csproj @@ -0,0 +1,33 @@ + + + Exe + net8.0;net9.0;net10.0 + preview + enable + enable + true + Lambda + true + true + $(InterceptorsNamespaces);MinimalLambda.Generated + false + + + + + + + + + + + + + + PreserveNewest + + + \ No newline at end of file diff --git a/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/Program.cs b/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/Program.cs new file mode 100644 index 00000000..d78dc67d --- /dev/null +++ b/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/Program.cs @@ -0,0 +1,64 @@ +using System.Collections.Concurrent; +using System.Text.Json.Serialization; +using Amazon.Lambda.SQSEvents; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using MinimalLambda; +using MinimalLambda.Builder; + +var builder = LambdaApplication.CreateBuilder(); + +builder.Services.AddLambdaSerializerWithContext(); +builder.Services.AddSingleton(); + +await using var lambda = builder.Build(); + +lambda.MapEventHandler( + split: (SQSEvent batch, ILambdaInvocationContext _) => batch.Records, + handle: async Task ( + SQSEvent.SQSMessage item, + RecordProbe probe, + CancellationToken token) => + { + token.ThrowIfCancellationRequested(); + probe.Record(item.MessageId); + + if (item.Body is "retry" or "fatal") + throw new InvalidOperationException("retry requested"); + + await Task.Yield(); + return new Success(item.MessageId); + }, + onError: (item, _, _) => + item.Body == "fatal" + ? throw new InvalidOperationException("mapper failed") + : new Retry(item.MessageId), + createResponse: (results, _) => new SQSBatchResponse( + results + .OfType() + .Select(result => + new SQSBatchResponse.BatchItemFailure { ItemIdentifier = result.MessageId, }) + .ToList())); + +await lambda.RunAsync(); + +internal abstract record ImportResult; + +internal sealed record Success(string MessageId) : ImportResult; + +internal sealed record Retry(string MessageId) : ImportResult; + +internal sealed class RecordProbe +{ + private readonly ConcurrentQueue messageIds = new(); + + public IReadOnlyCollection MessageIds => messageIds.ToArray(); + + public void Record(string messageId) => messageIds.Enqueue(messageId); +} + +public class EventProcessorLambda; + +[JsonSerializable(typeof(SQSEvent))] +[JsonSerializable(typeof(SQSBatchResponse))] +internal partial class EventProcessorLambdaJsonContext : JsonSerializerContext; diff --git a/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/appsettings.json b/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/appsettings.json new file mode 100644 index 00000000..7a73a41b --- /dev/null +++ b/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/appsettings.json @@ -0,0 +1,2 @@ +{ +} \ No newline at end of file diff --git a/tests/MinimalLambda.Testing.UnitTests/Tests/MinimalLambda.Testing.UnitTests/EventProcessorLambdaTests.cs b/tests/MinimalLambda.Testing.UnitTests/Tests/MinimalLambda.Testing.UnitTests/EventProcessorLambdaTests.cs new file mode 100644 index 00000000..57e722e7 --- /dev/null +++ b/tests/MinimalLambda.Testing.UnitTests/Tests/MinimalLambda.Testing.UnitTests/EventProcessorLambdaTests.cs @@ -0,0 +1,111 @@ +using Amazon.Lambda.SQSEvents; +using Microsoft.Extensions.DependencyInjection; + +namespace MinimalLambda.Testing.UnitTests; + +public class EventProcessorLambdaTests +{ + [Fact] + public async Task EventProcessorLambda_BuildsPartialBatchResponseInSourceOrder() + { + // Arrange + await using var factory = + LambdaTestFactory + .Create() + .WithCancellationToken(TestContext.Current.CancellationToken); + var request = CreateEvent(("id-1", "retry"), ("id-2", "ok"), ("id-3", "retry")); + + // Act + var response = await factory.TestServer.InvokeAsync( + request, + TestContext.Current.CancellationToken); + + // Assert + response.Error.Should().BeNull(); + response.WasSuccess.Should().BeTrue(); + response.Response.Should().NotBeNull(); + response + .Response + .BatchItemFailures + .Select(failure => failure.ItemIdentifier) + .Should() + .Equal("id-1", "id-3"); + } + + [Fact] + public async Task EventProcessorLambda_ProcessesEveryRecordThroughItsOwnScope() + { + // Arrange + await using var factory = + LambdaTestFactory + .Create() + .WithCancellationToken(TestContext.Current.CancellationToken); + var request = CreateEvent(("id-1", "ok"), ("id-2", "ok"), ("id-3", "ok")); + + // Act + await factory.TestServer.InvokeAsync( + request, + TestContext.Current.CancellationToken); + + // Assert + factory + .Services + .GetRequiredService() + .MessageIds + .Should() + .BeEquivalentTo("id-1", "id-2", "id-3"); + } + + [Fact] + public async Task EventProcessorLambda_EmptyEventStillBuildsEmptyResponse() + { + // Arrange + await using var factory = + LambdaTestFactory + .Create() + .WithCancellationToken(TestContext.Current.CancellationToken); + + // Act + var response = await factory.TestServer.InvokeAsync( + CreateEvent(), + TestContext.Current.CancellationToken); + + // Assert + response.WasSuccess.Should().BeTrue(); + response.Response.Should().NotBeNull(); + response.Response.BatchItemFailures.Should().BeEmpty(); + } + + [Fact] + public async Task EventProcessorLambda_ErrorMapperFailureFailsInvocationWithoutResponse() + { + // Arrange + await using var factory = + LambdaTestFactory + .Create() + .WithCancellationToken(TestContext.Current.CancellationToken); + var request = CreateEvent(("id-1", "fatal")); + + // Act + var response = await factory.TestServer.InvokeAsync( + request, + TestContext.Current.CancellationToken); + + // Assert + response.WasSuccess.Should().BeFalse(); + response.Error.Should().NotBeNull(); + response.Response.Should().BeNull(); + } + + private static SQSEvent CreateEvent(params (string MessageId, string Body)[] records) => + new() + { + Records = + [ + .. records.Select(record => new SQSEvent.SQSMessage + { + MessageId = record.MessageId, Body = record.Body, + }), + ], + }; +} 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 f4938350..3ff8c730 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 @@ -16,6 +16,7 @@ + @@ -42,6 +43,8 @@ + batch.Items, + handle: (Item _) => Task.CompletedTask, + createResponse: (items, _) => + { + responseCalls++; + var ids = items.Select(item => item.Id).ToList(); + captured = new Response(ids); + return captured; + }); + + var harness = CreateHarness(app, new Batch([])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + responseCalls.Should().Be(1); + captured!.Ids.Should().BeEmpty(); + harness.ResponseFeature.Received(1).SetResponse(captured!); + } + + [Fact] + public async Task ProcessesItemsConcurrentlyAndPreservesSourceOrder() + { + // Arrange + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var allStarted = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var active = 0; + var maxActive = 0; + var started = 0; + var sync = new object(); + + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: async (Item item) => + { + lock (sync) + { + active++; + started++; + maxActive = Math.Max(maxActive, active); + if (started == 3) + allStarted.TrySetResult(); + } + + await gate.Task.ConfigureAwait(false); + + lock (sync) + active--; + + return item.Id; + }, + createResponse: (ids, _) => new Response(ids.ToList())); + + var harness = CreateHarness(app, new Batch([new Item(1), new Item(2), new Item(3)])); + var handler = app.Build(); + + // Act + var invocation = handler(harness.Context); + await allStarted.Task.WaitAsync( + TimeSpan.FromSeconds(10), + TestContext.Current.CancellationToken); + gate.SetResult(); + await invocation; + + // Assert + maxActive.Should().Be(3); + harness + .ResponseFeature + .Received(1) + .SetResponse( + Arg.Is(response => response.Ids.SequenceEqual(new[] { 1, 2, 3 }))); + } + + [Fact] + public async Task DisabledConcurrencyForcesSequentialExecutionDespiteConfiguredLimit() + { + // Arrange + var firstStarted = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var secondStarted = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseFirst = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + var builder = LambdaApplication.CreateBuilder(); + builder.Services.Configure(options => + { + options.EnableConcurrency = false; + options.MaxConcurrentExecutions = 10; + }); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: async (Item item) => + { + if (item.Id == 1) + { + firstStarted.TrySetResult(); + await releaseFirst.Task.ConfigureAwait(false); + } + else + { + secondStarted.TrySetResult(); + } + }); + + var harness = CreateHarness(app, new Batch([new Item(1), new Item(2)])); + var handler = app.Build(); + + // Act + var invocation = handler(harness.Context); + await firstStarted.Task.WaitAsync( + TimeSpan.FromSeconds(10), + TestContext.Current.CancellationToken); + + // Assert + secondStarted.Task.IsCompleted.Should().BeFalse(); + releaseFirst.SetResult(); + await invocation; + secondStarted.Task.IsCompleted.Should().BeTrue(); + } + + [Fact] + public async Task MapsFailuresAndCollectsResultsInSourceOrder() + { + // Arrange + var errorCalls = 0; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: async (Item item) => + { + await Task.Yield(); + if (item.Id == 2) + throw new InvalidOperationException("item failed"); + return item.Id; + }, + onError: (item, exception, _) => + { + errorCalls++; + exception.Message.Should().Be("item failed"); + return -item.Id; + }, + createResponse: (results, _) => new Response(results.ToList())); + + var harness = CreateHarness(app, new Batch([new Item(1), new Item(2), new Item(3)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + errorCalls.Should().Be(1); + harness + .ResponseFeature + .Received(1) + .SetResponse( + Arg.Is(response => response.Ids.SequenceEqual(new[] { 1, -2, 3 }))); + } + + [Fact] + public async Task UnhandledHandlerErrorFailsInvocationAndSkipsResponse() + { + // Arrange + var responseCalls = 0; + var expected = new InvalidOperationException("unhandled"); + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => item.Id == 2 ? Task.FromException(expected) : Task.CompletedTask, + createResponse: (items, _) => + { + responseCalls++; + return new Response(items.Select(item => item.Id).ToList()); + }); + + var harness = CreateHarness(app, new Batch([new Item(1), new Item(2), new Item(3)])); + var handler = app.Build(); + + // Act + var act = () => handler(harness.Context); + + // Assert + await act.Should().ThrowAsync().WithMessage("unhandled"); + responseCalls.Should().Be(0); + } + + [Fact] + public async Task NullHandlerTaskFailsInvocationWithoutErrorMapping() + { + // Arrange + var errorCalls = 0; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _) => (Task)null!, + onError: (item, _, _) => + { + errorCalls++; + return item.Id; + }, + createResponse: (results, _) => new Response(results.ToList())); + + var harness = CreateHarness(app, new Batch([new Item(1)])); + var handler = app.Build(); + + // Act + var act = () => handler(harness.Context); + + // Assert + await act.Should().ThrowAsync().WithMessage("*null task*"); + errorCalls.Should().Be(0); + } + + [Fact] + public async Task NullSplitterResultFailsBeforeHandling() + { + // Arrange + var handleCalls = 0; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch _, ILambdaInvocationContext _) => null!, + handle: (Item _) => + { + handleCalls++; + return Task.CompletedTask; + }); + + var harness = CreateHarness(app, new Batch([new Item(1)])); + var handler = app.Build(); + + // Act + var act = () => handler(harness.Context); + + // Assert + await act.Should().ThrowAsync().WithMessage("*split*null*"); + handleCalls.Should().Be(0); + } + + [Fact] + public async Task StopProcessingPreventsNewClaimsAndBuildsCompletedResponse() + { + // Arrange + var handled = new ConcurrentBag(); + Response? captured = null; + var builder = LambdaApplication.CreateBuilder(); + builder.Services.Configure(options => + options.EnableConcurrency = false); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item, IEventProcessingContext processing) => + { + handled.Add(item.Id); + processing.StopProcessing(); + return Task.CompletedTask; + }, + createResponse: (items, _) => + { + captured = new Response(items.Select(item => item.Id).ToList()); + return captured; + }); + + var harness = CreateHarness(app, new Batch([new Item(1), new Item(2), new Item(3)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + handled.Should().Equal(1); + captured!.Ids.Should().Equal(1); + harness.ResponseFeature.Received(1).SetResponse(captured!); + } + + [Fact] + public async Task CancelProcessingSignalsProcessingTokenAndPreventsNewClaims() + { + // Arrange + var handled = new ConcurrentBag(); + var tokenCancelled = false; + var builder = LambdaApplication.CreateBuilder(); + builder.Services.Configure(options => + options.EnableConcurrency = false); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item, IEventProcessingContext processing, CancellationToken token) => + { + handled.Add(item.Id); + processing.CancelProcessing(); + tokenCancelled = token.IsCancellationRequested; + return Task.CompletedTask; + }); + + var harness = CreateHarness(app, new Batch([new Item(1), new Item(2)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + handled.Should().Equal(1); + tokenCancelled.Should().BeTrue(); + harness.InvocationCancellation.IsCancellationRequested.Should().BeFalse(); + } + + [Fact] + public async Task CancelledRunningHandlerSkipsErrorMappingAndOmitsContribution() + { + // Arrange + var errorCalls = 0; + Response? captured = null; + var thirdStarted = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: async ( + Item item, + IEventProcessingContext processing, + CancellationToken token) => + { + if (item.Id == 3) + thirdStarted.TrySetResult(); + + if (item.Id == 2) + { + await thirdStarted.Task.ConfigureAwait(false); + processing.CancelProcessing(); + await Task.Delay(Timeout.InfiniteTimeSpan, token).ConfigureAwait(false); + } + + return item.Id; + }, + onError: (item, _, _) => + { + errorCalls++; + return item.Id; + }, + createResponse: (results, _) => + { + captured = new Response(results.ToList()); + return captured; + }); + + var harness = CreateHarness(app, new Batch([new Item(1), new Item(2), new Item(3)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + errorCalls.Should().Be(0); + captured!.Ids.Should().Equal(1, 3); + } + + [Fact] + public async Task InvocationCancellationDuringHandlingSuppressesResponse() + { + // Arrange + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var responseCalls = 0; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: async (Item item, CancellationToken token) => + { + entered.TrySetResult(); + await Task.Delay(Timeout.InfiniteTimeSpan, token).ConfigureAwait(false); + return item.Id; + }, + createResponse: (results, _) => + { + responseCalls++; + return new Response(results.ToList()); + }); + + var harness = CreateHarness(app, new Batch([new Item(1)])); + var handler = app.Build(); + + // Act + var invocation = handler(harness.Context); + await entered.Task.WaitAsync( + TimeSpan.FromSeconds(10), + TestContext.Current.CancellationToken); + harness.InvocationCancellation.Cancel(); + var act = () => invocation; + + // Assert + await act.Should().ThrowAsync(); + responseCalls.Should().Be(0); + } + + [Fact] + public async Task LateInvocationCancellationDuringResponseDoesNotAddFailure() + { + // Arrange + Response? captured = null; + var invocationCancellation = new CancellationTokenSource(); + var builder = LambdaApplication.CreateBuilder(); + builder.Services.AddScoped(_ => new CancelOnDispose(invocationCancellation)); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item, CancelOnDispose _) => Task.FromResult(item.Id), + createResponse: (ids, _) => + { + captured = new Response(ids.ToList()); + return captured; + }); + + var harness = CreateHarness(app, new Batch([new Item(1)]), invocationCancellation); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + invocationCancellation.IsCancellationRequested.Should().BeTrue(); + harness.ResponseFeature.Received(1).SetResponse(captured!); + } + + [Fact] + public async Task CreatesAndDisposesAnIsolatedScopeForEachStartedItem() + { + // Arrange + ScopeProbe.Reset(); + var builder = LambdaApplication.CreateBuilder(); + builder.Services.AddScoped(); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _, ScopeProbe probe) => + { + ScopeProbe.Record(probe); + return Task.CompletedTask; + }); + + var harness = CreateHarness(app, new Batch([new Item(1), new Item(2), new Item(3)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + ScopeProbe.Created.Should().Be(3); + ScopeProbe.Disposed.Should().Be(3); + ScopeProbe.InstanceIds.Should().OnlyHaveUniqueItems().And.HaveCount(3); + } + + [Fact] + public void InvalidOptionsFailBeforeCallbacksRun() + { + // Arrange + var builder = LambdaApplication.CreateBuilder(); + builder.Services.Configure(options => + options.MaxConcurrentExecutions = 0); + using var app = builder.Build(); + var callbackCalls = 0; + + // Act + var act = () => app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _) => + { + callbackCalls++; + return Task.CompletedTask; + }); + + // Assert + act.Should().Throw(); + callbackCalls.Should().Be(0); + } + + [Fact] + public void DefaultOptionsEnableConcurrencyWithLimitTen() + { + // Arrange + var options = new EventHandlerOptions(); + + // Act & Assert + options.EnableConcurrency.Should().BeTrue(); + options.MaxConcurrentExecutions.Should().Be(10); + new EventHandlerOptionsValidator().Validate(null, options).Succeeded.Should().BeTrue(); + new EventHandlerOptionsValidator() + .Validate(null, new EventHandlerOptions { MaxConcurrentExecutions = 0 }) + .Failed + .Should() + .BeTrue(); + } + + [Fact] + public async Task ResolvesInvocationAndLambdaContextParametersFromTheProcessingContext() + { + // Arrange + ILambdaInvocationContext? invocation = null; + var tokenMatched = false; + await using var invocationContextApp = LambdaApplication.CreateBuilder().Build(); + invocationContextApp.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: ( + Item _, + ILambdaInvocationContext invocationContext, + IEventProcessingContext processing, + CancellationToken token) => + { + invocation = invocationContext; + tokenMatched = token == processing.CancellationToken; + return Task.CompletedTask; + }); + + ILambdaContext? lambda = null; + await using var lambdaContextApp = LambdaApplication.CreateBuilder().Build(); + lambdaContextApp.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _, ILambdaContext lambdaContext) => + { + lambda = lambdaContext; + return Task.CompletedTask; + }); + + var invocationHarness = CreateHarness(invocationContextApp, new Batch([new Item(1)])); + var lambdaHarness = CreateHarness(lambdaContextApp, new Batch([new Item(1)])); + + // Act + await invocationContextApp.Build()(invocationHarness.Context); + await lambdaContextApp.Build()(lambdaHarness.Context); + + // Assert + invocation.Should().BeSameAs(invocationHarness.Context); + lambda.Should().BeSameAs(lambdaHarness.Context); + tokenMatched.Should().BeTrue(); + } + + [Fact] + public async Task FatalErrorDrainsAdmittedItemsWithoutClaimingMoreOrBuildingResponse() + { + // Arrange + ScopeProbe.Reset(); + FatalObserver.Reset(); + var blockedItems = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseFailingItem = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var started = 0; + var handled = new ConcurrentBag(); + var responseCalls = 0; + + var builder = LambdaApplication.CreateBuilder(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.Configure(options => + options.MaxConcurrentExecutions = 3); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: async (Item item, ScopeProbe _, FatalObserver observer) => + { + observer.Observe(item); + handled.Add(item.Id); + Interlocked.Increment(ref started); + + if (item.Id == 2) + { + await releaseFailingItem.Task.ConfigureAwait(false); + throw new InvalidOperationException("fatal"); + } + + await blockedItems.Task.ConfigureAwait(false); + }, + createResponse: (IEnumerable _, ILambdaInvocationContext _) => + { + responseCalls++; + return new Response([]); + }); + + var harness = CreateHarness( + app, + new Batch([new Item(1), new Item(2), new Item(3), new Item(4)])); + var handler = app.Build(); + + // Act + var invocation = handler(harness.Context); + await WaitForAsync(() => Volatile.Read(ref started) >= 3); + releaseFailingItem.SetResult(); + + // The failing item's scope disposes only after the scheduler records the fatal error, so + // this signal proves the claim boundary is closed before the remaining items are released. + await FatalObserver.FatalRecorded.WaitAsync( + TimeSpan.FromSeconds(10), + TestContext.Current.CancellationToken); + + // Assert + handled.Should().BeEquivalentTo(new[] { 1, 2, 3 }); + + blockedItems.SetResult(); + var act = () => invocation; + await act.Should().ThrowAsync(); + responseCalls.Should().Be(0); + ScopeProbe.Created.Should().Be(3); + ScopeProbe.Disposed.Should().Be(3); + } + + [Fact] + public void ReachingASecondMappingThrowsRegardlessOfMappingApi() + { + // Arrange + using var handlerFirst = LambdaApplication.CreateBuilder().Build(); + handlerFirst.MapHandler(() => Task.CompletedTask); + + // Act + var mapEventAfterHandler = () => handlerFirst.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _) => Task.CompletedTask); + + // Assert + mapEventAfterHandler.Should().Throw(); + + // Arrange + using var eventFirst = LambdaApplication.CreateBuilder().Build(); + eventFirst.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _) => Task.CompletedTask); + + // Act + var mapHandlerAfterEvent = () => eventFirst.MapHandler(() => Task.CompletedTask); + var mapEventTwice = () => eventFirst.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _) => Task.CompletedTask); + + // Assert + mapHandlerAfterEvent.Should().Throw(); + mapEventTwice.Should().Throw(); + } + + [Fact] + public async Task ResponseInputIsRepeatablyEnumerableInSourceOrder() + { + // Arrange + IReadOnlyList? firstPass = null; + IReadOnlyList? secondPass = null; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => Task.FromResult(item.Id), + createResponse: (results, _) => + { + firstPass = results.ToList(); + secondPass = results.ToList(); + return new Response(firstPass); + }); + + var harness = CreateHarness(app, new Batch([new Item(3), new Item(1), new Item(2)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + firstPass.Should().Equal(3, 1, 2); + secondPass.Should().Equal(3, 1, 2); + } + + private static async Task WaitForAsync(Func condition) + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + while (!condition()) + await Task.Delay(10, timeout.Token); + } + + private static Harness CreateHarness( + LambdaApplication app, + Batch batch, + CancellationTokenSource? invocationCancellation = null) + { + var features = new DefaultFeatureCollection([]); + features.Set(new TestEventFeature(batch)); + var responseFeature = Substitute.For>(); + features.Set(responseFeature); + invocationCancellation ??= new CancellationTokenSource(); + + var context = Substitute.For(); + context.Features.Returns(features); + context.ServiceProvider.Returns(app.Services); + context.CancellationToken.Returns(invocationCancellation.Token); + context.Items.Returns(new Dictionary()); + + return new Harness(context, responseFeature, invocationCancellation); + } + + private sealed record Harness( + ILambdaInvocationContext Context, + IResponseFeature ResponseFeature, + CancellationTokenSource InvocationCancellation); + + private sealed class TestEventFeature(T value) : IEventFeature + { + public T GetEvent(ILambdaInvocationContext context) => value; + + object? IEventFeature.GetEvent(ILambdaInvocationContext context) => value; + } + + internal sealed class ScopeProbe : IDisposable + { + private static readonly ConcurrentBag Ids = []; + private static int _nextId; + private static int _created; + private static int _disposed; + + public ScopeProbe() + { + Id = Interlocked.Increment(ref _nextId); + Interlocked.Increment(ref _created); + } + + public int Id { get; } + + public static int Created => _created; + + public static int Disposed => _disposed; + + public static IReadOnlyCollection InstanceIds => Ids; + + public void Dispose() => Interlocked.Increment(ref _disposed); + + public static void Reset() + { + while (Ids.TryTake(out _)) { } + + _nextId = 0; + _created = 0; + _disposed = 0; + } + + public static void Record(ScopeProbe probe) => Ids.Add(probe.Id); + } + + internal sealed class CancelOnDispose(CancellationTokenSource cancellation) : IDisposable + { + public void Dispose() => cancellation.Cancel(); + } + + internal sealed class FatalObserver : IDisposable + { + private static TaskCompletionSource fatalRecorded = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + private int itemId; + + public static Task FatalRecorded => fatalRecorded.Task; + + public void Observe(Item item) => itemId = item.Id; + + public void Dispose() + { + if (itemId == 2) + fatalRecorded.TrySetResult(); + } + + public static void Reset() => + fatalRecorded = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + } + + internal sealed record Batch(IReadOnlyList Items); + + internal sealed record Item(int Id); + + public sealed record Response(IReadOnlyList Ids); +} diff --git a/tests/MinimalLambda.UnitTests/MinimalLambda.UnitTests.csproj b/tests/MinimalLambda.UnitTests/MinimalLambda.UnitTests.csproj index 13a2fa61..52f25dc2 100644 --- a/tests/MinimalLambda.UnitTests/MinimalLambda.UnitTests.csproj +++ b/tests/MinimalLambda.UnitTests/MinimalLambda.UnitTests.csproj @@ -7,33 +7,34 @@ true false 14 + $(InterceptorsNamespaces);MinimalLambda.Generated - - - - - - - - - - - + + + + + + + + + + + - - - - - - - - - - - - + + + + + + + + + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive @@ -42,12 +43,16 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + - + + - + diff --git a/tests/package-compatibility/EventProcessorConsumer/EventProcessorConsumer.csproj b/tests/package-compatibility/EventProcessorConsumer/EventProcessorConsumer.csproj new file mode 100644 index 00000000..4304a220 --- /dev/null +++ b/tests/package-compatibility/EventProcessorConsumer/EventProcessorConsumer.csproj @@ -0,0 +1,19 @@ + + + Exe + net10.0 + preview + enable + enable + true + false + + + + + + + + \ No newline at end of file diff --git a/tests/package-compatibility/EventProcessorConsumer/Program.cs b/tests/package-compatibility/EventProcessorConsumer/Program.cs new file mode 100644 index 00000000..a768fb6f --- /dev/null +++ b/tests/package-compatibility/EventProcessorConsumer/Program.cs @@ -0,0 +1,55 @@ +using System.Text.Json.Serialization; +using Amazon.Lambda.Core; +using Amazon.Lambda.SQSEvents; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using MinimalLambda; +using MinimalLambda.Builder; +using MinimalLambda.Options; + +var builder = LambdaApplication.CreateBuilder(); +builder.Services.AddLambdaSerializerWithContext(); +builder.Services.ConfigureEnvelopeOptions(options => + options.JsonOptions.TypeInfoResolver = EventProcessorJsonContext.Default); +builder.Services.AddScoped(); +builder.Services.Configure(options => options.MaxConcurrentExecutions = 5); + +await using var lambda = builder.Build(); +lambda.MapEventHandler( + split: (SQSEvent batch, ILambdaInvocationContext _) => batch.Records, + handle: async Task ( + SQSEvent.SQSMessage item, + RecordHandler handler, + IEventProcessingContext processing, + CancellationToken token) => await handler.HandleAsync(item, processing, token), + onError: (item, _, _) => new Retry(item.MessageId), + createResponse: (results, _) => new SQSBatchResponse( + results + .OfType() + .Select(result => + new SQSBatchResponse.BatchItemFailure { ItemIdentifier = result.MessageId, }) + .ToList())); +await lambda.RunAsync(); + +internal sealed class RecordHandler +{ + public Task HandleAsync( + SQSEvent.SQSMessage item, + IEventProcessingContext processing, + CancellationToken token) + { + token.ThrowIfCancellationRequested(); + _ = processing.Invocation.AwsRequestId; + return Task.FromResult(new Success(item.MessageId)); + } +} + +internal abstract record ImportResult; + +internal sealed record Success(string MessageId) : ImportResult; + +internal sealed record Retry(string MessageId) : ImportResult; + +[JsonSerializable(typeof(SQSEvent))] +[JsonSerializable(typeof(SQSBatchResponse))] +internal partial class EventProcessorJsonContext : JsonSerializerContext; From 1e53553ca2bac226cdec0fe1e0e702be169d2e96 Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Wed, 28 Oct 2026 16:11:37 -0400 Subject: [PATCH 06/21] docs(event-processor): document batch processing and update skills Add docs/features/event-processor.md covering the callback families, handler parameters and arities, concurrency options, stopping and cancelling, the completed-contributions-only response contract, SQS partial batch responses, overload selection, diagnostics, and Native AOT metadata. Wire it into the MkDocs navigation and feature index, cross-link it from handler registration, and add a matching skill reference so client-project guidance stays in sync. --- docs/features/event-processor.md | 268 ++++++++++++++++++ docs/features/index.md | 6 + docs/guides/handler-registration.md | 1 + mkdocs.yml | 1 + skills/minimal-lambda/SKILL.md | 5 + skills/minimal-lambda/references/envelopes.md | 3 + .../references/event-processor.md | 179 ++++++++++++ 7 files changed, 463 insertions(+) create mode 100644 docs/features/event-processor.md create mode 100644 skills/minimal-lambda/references/event-processor.md diff --git a/docs/features/event-processor.md b/docs/features/event-processor.md new file mode 100644 index 00000000..034d8a68 --- /dev/null +++ b/docs/features/event-processor.md @@ -0,0 +1,268 @@ +# Event Processor + +`MapEventHandler` splits one Lambda event into items and processes them concurrently. It replaces +the loop-and-try/catch code most batch handlers write by hand. + +```csharp +builder.Services.AddScoped(); + +lambda.MapEventHandler( + split: (S3Event batch, ILambdaInvocationContext _) => batch.Records, + handle: (S3Event.S3EventNotificationRecord item, DocumentImporter importer, CancellationToken token) => + importer.IndexAsync(item.S3.Object.Key, token)); +``` + +Registration is source-generated, like `MapHandler`. The generator emits the whole processor, so +there is no runtime reflection and no public runtime bridge. + +## What it is not + +- It is not Lambda invocation concurrency. Item concurrency happens inside one invocation; the + runtime still runs one invocation per execution environment by default. +- It is not a retry engine. Unstarted or cancelled items contribute nothing to the response, and the + processor never invents results for them. +- It is not a task queue. The splitter output is materialized before any handler starts, bounded by + the event size. + +## Callback families + +`split` always runs first, once, and serial. It returns `IEnumerable`. + +| Family | Callbacks after `split` | Response input | Error behavior | +| ------ | ------------------------------------- | -------------------------------- | --------------------------------------------- | +| N1 | `handle` | none | An unhandled item error fails the invocation. | +| N2 | `handle`, `createResponse` | successful source items | Any item error prevents the response. | +| N3 | `handle`, `onError`, `createResponse` | values returned by `onError` | Successful items contribute nothing. | +| R1 | `handle`, `createResponse` | successful `TResult` values | Any item error prevents the response. | +| R2 | `handle`, `onError`, `createResponse` | one `TResult` per completed item | Mapped errors contribute a result. | + +`handle` returns `Task` for N1/N2/N3 and `Task` for R1/R2. `onError` is a synchronous value +mapper, not an observer. Log and rethrow inside `handle` when you only want observation. + +Every family has arities 0 through 10 for parameters after the item, using `TD0` through `TD9`: + +```csharp +lambda.MapEventHandler(...); // two extra handler inputs +``` + +The count includes framework parameters. The item is always first. + +## Handler parameters + +`handle` is resolved with a fresh asynchronous DI scope per item: + +- the source item, first; +- `ILambdaInvocationContext` or `ILambdaContext`; +- `IEventProcessingContext`; +- `CancellationToken`, which is the *processing* token; +- anything else from DI, including `[FromServices]` and `[FromKeyedServices]`. + +Each may appear at most once, and at most ten parameters follow the item. Framework parameters +cannot carry service or event attributes. Scopes are disposed after each item exits, and results +must remain valid after disposal. + +```csharp +lambda.MapEventHandler( + split: (SqsEnvelope batch, ILambdaInvocationContext _) => batch.Records, + handle: async Task ( + SqsEnvelope.SqsMessageEnvelope item, + OrderProcessor processor, + IEventProcessingContext processing, + CancellationToken token) => + { + if (item.BodyContent is null) + return new Retry(item.MessageId); + + return await processor.ProcessAsync(item.BodyContent, token); + }, + onError: (item, _, _) => new Retry(item.MessageId), + createResponse: (results, _) => new SQSBatchResponse(/* ... */)); +``` + +`split` and `createResponse` keep their explicit `ILambdaInvocationContext` parameter. + +## Ordering and contributions + +Handlers may finish in any order; contributions stay in source order. `createResponse` receives a +materialized, repeatably enumerable, read-only collection. Duplicate items stay separate entries. +An empty event still calls the response builder once, with an empty collection. + +Only completed contributions reach the builder: + +- N1 never builds a response; +- N2 supplies items whose handlers succeeded; +- N3 supplies only `onError` values; +- R1 and R2 supply one `TResult` per completed item, mapped errors included. + +Nullable values are legitimate contributions. Null items are not filtered. + +## Concurrency options + +Concurrency is on by default with a cap of 10. It is captured when the handler is mapped. + +```csharp +builder.Services.Configure(options => +{ + options.MaxConcurrentExecutions = 5; // default 10 + options.EnableConcurrency = false; // force sequential +}); +``` + +`MaxConcurrentExecutions` must be positive in both modes. Invalid values fail before any callback +runs, at application build time. `EnableConcurrency = false` forces sequential execution even when a +larger cap is configured. + +Use sequential processing when order matters, such as FIFO queues or stream shards. + +## Stopping and cancelling + +`IEventProcessingContext` is one object per invocation, shared by item handlers and error mappers. + +| Call | New work | Active work | Response | +| ------------------------------------------ | -------- | ------------------------------------------- | ------------------ | +| `StopProcessing()` | blocked | finishes with the current token | may still be built | +| `CancelProcessing()` | blocked | processing token is signalled, then drained | may still be built | +| invocation token cancelled during handling | blocked | processing token is signalled, then drained | suppressed | + +Both calls are thread-safe and idempotent, and stop escalates to cancellation but never reverses. +Calling either after handling completes does nothing. + +```csharp +handle: async (Item item, IEventProcessingContext processing, CancellationToken token) => +{ + if (item.IsPoisonPill) + processing.StopProcessing(); + + await handler.ProcessAsync(item, token); +} +``` + +Handlers receive the *processing* token. Read +`processingContext.Invocation.CancellationToken` when you need the original invocation token. +Cancellation is cooperative: passing the token downstream is what makes work stop. Successful +handlers that finish despite cancellation keep their results. + +Once handling closes, fan-in and response construction add no new framework cancellation checks. +An invocation cancellation observed *during* handling still suppresses the response; one that +arrives later does not invalidate completed work. + +## Response input limitations + +The processor does not track which items are "missing". A response builder that needs to report +unprocessed identities must do that work in application code, for example by recording identities +inside `onError` or by comparing the response against the original event: + +```csharp +createResponse: (results, context) => + new SQSBatchResponse( + context.GetRequiredEvent().Records + .Select(record => record.MessageId) + .Except(results.OfType().Select(result => result.MessageId)) + .Select(id => new SQSBatchResponse.BatchItemFailure { ItemIdentifier = id }) + .ToList()) +``` + +Treat omission as "no claim", not as "safe to retry". Applications own acknowledgement, idempotency, +and rollback. Retried messages may already have partial side effects. + +## SQS partial batch responses + +Return `SQSBatchResponse` with `ReportBatchItemFailures` enabled on the event source mapping. +Families R2 and N3 fit this shape best: successful messages contribute a success value, mapped +failures contribute a retry value. + +```csharp +lambda.MapEventHandler( + split: (SQSEvent batch, ILambdaInvocationContext _) => batch.Records, + handle: async Task ( + SQSEvent.SQSMessage item, DocumentImporter importer, CancellationToken token) => + { + await importer.ImportAsync(item.Body, token); + return new Success(item.MessageId); + }, + onError: (item, _, _) => new Retry(item.MessageId), + createResponse: (results, _) => new SQSBatchResponse( + results.OfType() + .Select(result => new SQSBatchResponse.BatchItemFailure + { + ItemIdentifier = result.MessageId, + }) + .ToList())); +``` + +The handler's declared `Task` return type fixes the shared result type. A +`Task` handler is not a `Task` handler. + +## Choosing the overload + +`Task` derives from `Task`, so several families can bind the same lambda. Disambiguate +explicitly: + +- declare the handler return type, `async Task (...) => ...`; +- pass a typed delegate local when using a method group; +- pass `onError` only when you want recovery; +- specify all generic arguments when nothing else works. + +A method group does not supply dependency parameter types for generic inference. This does not +compile: + +```csharp +lambda.MapEventHandler(split, EventHandlers.HandleAsync); // CS0411 +``` + +Use a typed lambda, a typed delegate local, or explicit generic arguments: + +```csharp +Func handle = EventHandlers.HandleAsync; +lambda.MapEventHandler(split, handle); + +lambda.MapEventHandler(split, EventHandlers.HandleAsync); +``` + +A result-returning handler bound to a no-result overload is a compile error (`LH0011`), not a silent +discard. + +## One handler per run + +`MapEventHandler` consumes the single invocation handler slot, like `MapHandler`. Multiple mapping +sites are allowed and all compile; the error only happens when execution reaches a second mapping. +That keeps conditional registration and multi-mode samples working, while a genuinely duplicated +registration still throws the existing `InvalidOperationException`. + +## Diagnostics + +| ID | Meaning | +| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `LH0008` | Unsupported signature: non-`Task` handler, wrong item type, inaccessible type, `ref`/`out`, stream or awaitable event/response, wrong parameter count. | +| `LH0009` | Unsupported binding: event attribute on the item, duplicate context/token parameters, service attribute on a framework parameter. | +| `LH0010` | Handler cannot be resolved to one analyzable method, typically a reassigned delegate local. | +| `LH0011` | A `Task` handler bound to a no-result overload would discard its result. | + +## Native AOT + +The processor is generated into the consumer assembly with concrete closed signatures, so it is +trim- and AOT-safe. Add serializer metadata for the event, response, envelope payloads, and any +result type you serialize yourself: + +```csharp +builder.Services.AddLambdaSerializerWithContext(); +builder.Services.ConfigureEnvelopeOptions(options => + options.JsonOptions.TypeInfoResolver = SerializerContext.Default); + +[JsonSerializable(typeof(SQSEvent))] +[JsonSerializable(typeof(SQSBatchResponse))] +[JsonSerializable(typeof(Order))] +internal partial class SerializerContext : JsonSerializerContext; +``` + +Intermediate union results only need metadata when they are serialized. + +## Limits + +- The event is materialized into memory; item count is bounded by event size, not by an unbounded + task queue. +- Worker count is bounded by `min(itemCount, effectiveConcurrency)`. +- Concurrency does not preserve order. Use `EnableConcurrency = false` for FIFO and ordered stream + processing. +- Cancellation is cooperative and never undoes side effects. Poison pills that repeatedly fail will + repeatedly re-deliver unless the application records progress. diff --git a/docs/features/index.md b/docs/features/index.md index ce4c0292..89cf9ba4 100644 --- a/docs/features/index.md +++ b/docs/features/index.md @@ -8,6 +8,12 @@ ______________________________________________________________________ ## Feature Categories +### [Event Processor](./event-processor.md) + +`MapEventHandler` splits one event into items and processes them concurrently with a per-item +asynchronous DI scope. Choose from five callback families for response building, error mapping, and +graceful stopping. + ### [Envelope Pattern](./envelopes.md) The Envelope pattern provides type-safe wrappers for various AWS event sources like SQS, SNS, and API Gateway. Instead of manually parsing JSON, you can work with strongly-typed objects, improving code quality and developer productivity. diff --git a/docs/guides/handler-registration.md b/docs/guides/handler-registration.md index 66d353e9..fae9cfb9 100644 --- a/docs/guides/handler-registration.md +++ b/docs/guides/handler-registration.md @@ -35,6 +35,7 @@ interface IGreetingService - While you can have multiple `MapHandler` calls in your code, only one can be registered at runtime (see [Multiple MapHandler Calls](#multiple-maphandler-calls) below). - The generated handler feeds into the normal invocation builder, so all middleware, features, and diagnostics apply equally to handlers created via `Handle` or `MapHandler`. +- For batch events, [`MapEventHandler`](event-processor.md) consumes the same single handler slot and splits one event into concurrently processed items. ## Multiple MapHandler Calls diff --git a/mkdocs.yml b/mkdocs.yml index 2db8e269..7d6db51a 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -119,6 +119,7 @@ nav: - examples/index.md - Features: - features/index.md + - Event Processor: features/event-processor.md - Envelopes: features/envelopes.md - Durable Execution: features/durable-execution.md - OpenTelemetry: features/open_telemetry.md diff --git a/skills/minimal-lambda/SKILL.md b/skills/minimal-lambda/SKILL.md index f15560fa..4ee26de7 100644 --- a/skills/minimal-lambda/SKILL.md +++ b/skills/minimal-lambda/SKILL.md @@ -14,6 +14,8 @@ Use this skill to give agents enough MinimalLambda project context without loadi - app setup/handler/DI/lifecycle → read `references/core-hosting.md` and `references/best-practices.md` - AWS Lambda Durable Execution, `MapDurableHandler`, `IDurableContext`, replay, or checkpoints → read `references/durable-execution.md` before general handler/cancellation advice - handler shape/unit-testable handlers → read `references/patterns/handler-patterns.md` + - batch/fan-out event processing, per-item DI, partial batch responses, `MapEventHandler`, + `IEventProcessingContext`, `EventHandlerOptions` → read `references/event-processor.md` - middleware/features/context → read `references/core-hosting.md` and `references/patterns/middleware-patterns.md` - lifecycle hooks (`OnInit`/`OnShutdown`) → read `references/core-hosting.md` and `references/patterns/lifecycle-hook-patterns.md` @@ -46,6 +48,8 @@ Core pieces: - `LambdaApplication.CreateBuilder()` creates standard .NET host/config/DI defaults. - `MapHandler(...)` registers one ordinary Lambda handler. Source generator intercepts it at compile time. +- `MapEventHandler(...)` registers one batch processor: split the event, run one scope per item + concurrently, then build one response. Read `references/event-processor.md`. - `MapDurableHandler(...)` registers one durable workflow with stricter signature, cancellation, replay, middleware, and serializer rules; read `references/durable-execution.md`. - `[FromEvent]` marks deserialized event payload. Ordinary handlers allow at most one; durable handlers allow zero or one. `IDurableContext` is optional for durable handlers. - Other handler parameters resolve from DI/context/keyed services/cancellation token. @@ -87,6 +91,7 @@ Read `references/best-practices.md` before giving architectural advice. Before final answer or patch: - Does code compile with source generation? `MapHandler` has 0 or 1 `[FromEvent]`; `MapDurableHandler` has 0 or 1 `[FromEvent]`, 0 or 1 `IDurableContext`, and returns `Task`/`Task`. +- For batch handlers: `MapEventHandler` family matches the handler return type (no `Task` on a no-result overload), arity is at most 10 after the item, concurrency mode suits the event source, and `createResponse` tolerates an empty collection. - Does durable code treat optional root `CancellationToken` as physical invocation cancellation, use SDK operation-callback tokens for durable steps, register explicit serializer roots, and obey replay-safe middleware rules? - Does runtime call only one handler mapping path? - Are packages matched (`MinimalLambda.Testing` same version as `MinimalLambda`)? diff --git a/skills/minimal-lambda/references/envelopes.md b/skills/minimal-lambda/references/envelopes.md index b7e89a14..9cc0681d 100644 --- a/skills/minimal-lambda/references/envelopes.md +++ b/skills/minimal-lambda/references/envelopes.md @@ -67,6 +67,9 @@ When exact type/member names matter, inspect target package README/source if ava projects/global installs where source is unavailable, rely on bundled references plus installed package docs/IntelliSense. Names vary by trigger. +For batch processing of envelope records (per-item DI, partial batch responses, graceful stop), use +`MapEventHandler` with the envelope as `TEvent`; see `event-processor.md`. + ## AOT / serialization guidance - Prefer explicit records/classes with predictable JSON contracts. diff --git a/skills/minimal-lambda/references/event-processor.md b/skills/minimal-lambda/references/event-processor.md new file mode 100644 index 00000000..fa1880ce --- /dev/null +++ b/skills/minimal-lambda/references/event-processor.md @@ -0,0 +1,179 @@ +# Event Processor + +Read when the task processes one Lambda event as a batch: SQS/SNS records, S3 records, stream +shards, fan-out per item, per-item DI, partial batch responses (`ReportBatchItemFailures`), +`MapEventHandler`, `IEventProcessingContext`, `EventHandlerOptions`, or `StopProcessing` / +`CancelProcessing`. + +## Portability note + +This reference is self-contained for client-project use. Do not assume MinimalLambda source or tests +exist in the workspace. For repo contributions, read `repo-workflow.md` first. + +## Mental model + +`MapEventHandler` replaces the hand-written loop + `try/catch` in a batch handler. One call: + +1. runs `split` once to materialize items; +2. runs one asynchronous DI scope per item, concurrently; +3. collects contributions in source order; +4. builds one response through `createResponse`. + +It is source-generated. Never add a runtime helper or reflection fallback to replace it. + +`MapEventHandler` consumes the same single invocation handler slot as `MapHandler`. Multiple mapping +sites are fine and all compile; reaching a second mapping for one handler throws at runtime. + +## Signature shape + +```csharp +lambda.MapEventHandler( + split: (SQSEvent batch, ILambdaInvocationContext _) => batch.Records, + handle: (SQSEvent.SQSMessage item, IOrderService service, CancellationToken token) => + service.HandleAsync(item, token)); +``` + +- `split`: `Func>`, called once, serial. +- `handle`: item first. Returns `Task` (N1/N2/N3) or `Task` (R1/R2). +- `onError`: synchronous value mapper, `(item, exception, IEventProcessingContext) => TValue`. + Present in N3/R2 only. +- `createResponse`: `(IEnumerable, ILambdaInvocationContext) => TResponse`. +- Arities 0-10 after the item, via `TD0`-`TD9`. Framework parameters count toward ten. + +Handler parameters after the item: `ILambdaInvocationContext`/`ILambdaContext`, +`IEventProcessingContext`, `CancellationToken` (the processing token), then anything from DI +(`[FromServices]`, `[FromKeyedServices]`). Each framework parameter may appear once. + +## Families + +| Family | Callbacks | Response input | Unhandled item error | +| ------ | ------------------------------------- | -------------------------------- | -------------------- | +| N1 | `handle` | none | fails invocation | +| N2 | `handle`, `createResponse` | successful source items | fails, no response | +| N3 | `handle`, `onError`, `createResponse` | `onError` values | mapped values | +| R1 | `handle`, `createResponse` | successful `TResult` | fails, no response | +| R2 | `handle`, `onError`, `createResponse` | one `TResult` per completed item | mapped | + +Pick N1 when nothing is returned. Pick N3/R2 when you need a partial response. Never bind a +`Task` handler to N1/N2/N3 - the generator reports `LH0011`. + +## Concurrency and ordering + +Concurrency is on by default, cap 10, captured at registration: + +```csharp +builder.Services.Configure(options => +{ + options.MaxConcurrentExecutions = 5; + options.EnableConcurrency = false; // sequential +}); +``` + +`MaxConcurrentExecutions` must be positive in both modes or the app fails at build time. +Contributions stay in **source order** regardless of completion order. Use +`EnableConcurrency = false` for FIFO queues and ordered stream shards. + +Item concurrency is not Lambda invocation concurrency. The runtime still handles one invocation per +environment by default. + +## Stopping and cancelling + +`IEventProcessingContext` (namespace `MinimalLambda`) is per invocation, shared by handlers and +error mappers. + +- `StopProcessing()` - block new items, let active ones finish with the current token. A response may + still be built. +- `CancelProcessing()` - same, plus signal the processing token, then drain. +- Invocation cancellation observed *during* handling - blocks new items, signals the processing + token, suppresses the response. + +Both are thread-safe and idempotent; stop escalates to cancel but never reverses. `handle` receives +the processing token; read `processingContext.Invocation.CancellationToken` for the original. After +handling closes, fan-in and response construction add no new cancellation checks. + +## Response contract + +`createResponse` receives only completed contributions, source order, materialized and repeatably +enumerable. Unstarted or cancelled items contribute nothing - not a null, not a placeholder. The +processor does not validate completeness or retry items. + +An empty event still calls the builder once with an empty collection. Nullable values are valid +contributions; null items are not filtered. + +## Partial batch responses (SQS) + +```csharp +lambda.MapEventHandler( + split: (SQSEvent batch, ILambdaInvocationContext _) => batch.Records, + handle: async Task ( + SQSEvent.SQSMessage item, Importer importer, CancellationToken token) => + { + await importer.ImportAsync(item.Body, token); + return new Success(item.MessageId); + }, + onError: (item, _, _) => new Retry(item.MessageId), + createResponse: (results, _) => new SQSBatchResponse( + results.OfType() + .Select(result => new SQSBatchResponse.BatchItemFailure + { + ItemIdentifier = result.MessageId, + }) + .ToList())); +``` + +Requirements and limits: + +- Enable `ReportBatchItemFailures` on the event source mapping. +- The declared handler return type fixes the shared union type. `Task` is not + `Task`. +- Success values carry identity so the response can be computed; use `Success`/`Retry` records. +- Omitted items mean "no claim", never "safe to retry". Partial imports may already have side + effects. Applications own idempotency and rollback. +- When a response must report *unprocessed* identities, compute them in application code from the + original event, for example + `except`-ing completed identities against `context.GetRequiredEvent().Records`. +- FIFO queues need `EnableConcurrency = false` plus `StopProcessing()` on a poison pill. Otherwise + later messages may be committed before an earlier failure is retried. + +## Overload selection + +`Task` derives from `Task`, so bindings can be ambiguous. In order: + +1. declare the handler return type: `async Task (item, dep, token) => ...`; +2. pass a typed delegate local when using a method group + (`Func> handle = Handler;`); +3. pass all generic arguments: + `lambda.MapEventHandler(split, Handler);`. + +A method group alone cannot supply DI parameter types - it produces `CS0411`. Do not add a `Delegate` +catch-all. + +## Diagnostics + +| ID | Meaning | +| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `LH0008` | Unsupported signature: not `Task`-returning, wrong item type, inaccessible type, `ref`/`out`, stream/awaitable event or response, bad parameter count. | +| `LH0009` | Unsupported binding: event attribute on the item, duplicate context/token parameters, service attribute on a framework parameter. | +| `LH0010` | Handler not resolvable to one analyzable method, usually a reassigned delegate local. | +| `LH0011` | `Task` handler bound to a no-result overload. | + +## AOT + +Generated code uses concrete closed signatures, so the processor itself is trim-safe. Add serializer +metadata for the event, response, envelope payloads, and any result type you serialize: + +```csharp +builder.Services.AddLambdaSerializerWithContext(); +builder.Services.ConfigureEnvelopeOptions(options => + options.JsonOptions.TypeInfoResolver = SerializerContext.Default); +``` + +## Checklist + +- Family matches the return type; no `Task` handler on a no-result overload. +- Dependencies resolve from DI; the item is first; at most ten parameters after the item. +- Concurrency setting works for the event source (sequential for FIFO/ordered streams). +- `createResponse` handles an empty collection and only relies on completed contributions. +- SQS: `ReportBatchItemFailures` configured, identity carried in results, unprocessed identities + computed by application code. +- Envelope payload types are in the serializer context. From 2f919bcbd60128ad0de3375eb4887767fe32a7b5 Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Wed, 28 Oct 2026 16:11:42 -0400 Subject: [PATCH 07/21] feat(examples): add event processor sample with Native AOT coverage Replace the example's placeholder API with real registrations for every family, selected by EVENT_PROCESSOR_SAMPLE so each run maps exactly one processor. The sample covers per-item DI, SQS partial batch responses, graceful stop, envelopes, and typed delegate locals. Publish the sample as a trimmed Native AOT app with source-generated serializer metadata and a registration smoke path, and root a real event-processor mapping in the AOT compatibility app so the generated processor is analyzed and linked. --- ...inimalLambda.Example.EventProcessor.csproj | 48 +-- .../Program.cs | 277 ++++++++++-------- .../README.md | 127 ++------ .../AotCompatibility.TestApp.csproj | 7 + src/AotCompatibility.TestApp/Program.cs | 57 +++- 5 files changed, 266 insertions(+), 250 deletions(-) diff --git a/examples/MinimalLambda.Example.EventProcessor/MinimalLambda.Example.EventProcessor.csproj b/examples/MinimalLambda.Example.EventProcessor/MinimalLambda.Example.EventProcessor.csproj index 3c990c69..e13a1d9d 100644 --- a/examples/MinimalLambda.Example.EventProcessor/MinimalLambda.Example.EventProcessor.csproj +++ b/examples/MinimalLambda.Example.EventProcessor/MinimalLambda.Example.EventProcessor.csproj @@ -1,30 +1,36 @@ - - Exe - net8.0 - latest - enable - enable - true - Lambda - - true - - true - $(InterceptorsNamespaces);MinimalLambda.Generated - false - + + Exe + net8.0 + latest + enable + enable + true + Lambda + + true + + true + true + full + true + false + $(InterceptorsNamespaces);MinimalLambda.Generated + false + - + - - - + OutputItemType="Analyzer" /> + + + diff --git a/examples/MinimalLambda.Example.EventProcessor/Program.cs b/examples/MinimalLambda.Example.EventProcessor/Program.cs index fc7ae8b4..c43f45a7 100644 --- a/examples/MinimalLambda.Example.EventProcessor/Program.cs +++ b/examples/MinimalLambda.Example.EventProcessor/Program.cs @@ -1,156 +1,185 @@ -using Amazon.Lambda.S3Events; +using Amazon.Lambda.SQSEvents; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using MinimalLambda; using MinimalLambda.Builder; using MinimalLambda.Envelopes.Sqs; +using MinimalLambda.Options; +using System.Text.Json.Serialization; var builder = LambdaApplication.CreateBuilder(); -var lambda = builder.Build(); +builder.Services.AddLambdaSerializerWithContext(); +builder.Services.ConfigureEnvelopeOptions(options => + options.JsonOptions.TypeInfoResolver = EventProcessorJsonContext.Default); +builder.Services.AddScoped(); +builder.Services.Configure(options => options.MaxConcurrentExecutions = 5); -// No per-item result or Lambda response. -lambda.MapEventHandler( - (S3Event input, ILambdaInvocationContext _) => input.Records, - (S3Event.S3EventNotificationRecord item) => Task.CompletedTask); +await using var lambda = builder.Build(); -// One injected dependency. The splitter's TItem is the handler's first parameter. -lambda.MapEventHandler( - (S3Event input, ILambdaInvocationContext _) => input.Records, - (S3Event.S3EventNotificationRecord item, MyService service) => - { - service.DoStuff(item.S3.Object.Key); - return Task.CompletedTask; - }); +// The sample registers exactly one processor per run because MapEventHandler consumes the +// single invocation handler slot. Select a family with EVENT_PROCESSOR_SAMPLE. +switch (Environment.GetEnvironmentVariable("EVENT_PROCESSOR_SAMPLE")) +{ + case "n1": + RegisterNoResult(lambda); + break; + case "n2": + RegisterNoResultWithResponse(lambda); + break; + case "n3": + RegisterNoResultWithFailures(lambda); + break; + case "r1": + RegisterResults(lambda); + break; + default: + RegisterResultsWithRecovery(lambda); + break; +} -// Two injected dependencies. The item remains the first handler parameter. -lambda.MapEventHandler( - (S3Event input, ILambdaInvocationContext _) => input.Records, - EventHandlers.HandleS3RecordAsync); +// Registration alone roots the generated processor. This smoke path proves the Native AOT image +// boots, registers the processor, and validates options without a Lambda runtime present. +if (Environment.GetEnvironmentVariable("EVENT_PROCESSOR_SMOKE") == "1") +{ + Console.WriteLine("event processor registered"); + return; +} -// A per-item result and a typed batch response. -lambda.MapEventHandler( - (SqsEnvelope input, ILambdaInvocationContext _) => input.Records, - (SqsEnvelope.SqsMessageEnvelope item, MyService service) => - { - service.DoStuff(item.BodyContent?.Message ?? string.Empty); - return Task.FromResult(EventOutcome.Success); - }, - (result, _) - => new ExampleResponse( - result - .Items - .Where(item => item.Result == EventOutcome.Retry) - .Select(item => item.Item.MessageId) - .ToList())); +await lambda.RunAsync(); -// The error interceptor returns the same TItemResult as the item handler. -lambda.MapEventHandler( - (SqsEnvelope input, ILambdaInvocationContext _) => input.Records, - (SqsEnvelope.SqsMessageEnvelope item, MyService service) => - { - service.DoStuff(item.BodyContent?.Message ?? string.Empty); - return Task.FromResult(EventOutcome.Success); - }, - ( _, _, _) - => EventOutcome.Retry, - (result, _) - => new ExampleResponse( - result - .Items - .Where(item => item.Result == EventOutcome.Retry) - .Select(item => item.Item.MessageId) +// N1: no per-item value and no response. An unhandled item error fails the invocation. +static void RegisterNoResult(LambdaApplication lambda) => + lambda.MapEventHandler( + split: (SqsEnvelope batch, ILambdaInvocationContext _) => batch.Records, + handle: ( + SqsEnvelope.SqsMessageEnvelope item, + DocumentImporter importer, + IEventProcessingContext processing, + CancellationToken token) => + { + if (item.BodyContent is null) + return Task.CompletedTask; + + if (item.BodyContent.StopProcessing) + processing.StopProcessing(); + + return importer.ImportAsync(item.BodyContent, token); + }); + +// N2: createResponse receives only successfully handled source items, in source order. +static void RegisterNoResultWithResponse(LambdaApplication lambda) => + lambda.MapEventHandler( + split: (ImportBatch batch, ILambdaInvocationContext _) => batch.Items, + handle: (ImportDocument item, DocumentImporter importer, CancellationToken token) => + importer.ImportAsync(item.Event, token), + createResponse: (items, _) => new BatchSummary(items.Count())); + +// N3: successful items contribute nothing; only mapped failures reach createResponse. +static void RegisterNoResultWithFailures(LambdaApplication lambda) => + lambda.MapEventHandler( + split: (SqsEnvelope batch, ILambdaInvocationContext _) => batch.Records, + handle: ( + SqsEnvelope.SqsMessageEnvelope item, + DocumentImporter importer, + CancellationToken token) => + item.BodyContent is null + ? Task.CompletedTask + : importer.ImportAsync(item.BodyContent, token), + onError: (item, _, _) => + new SQSBatchResponse.BatchItemFailure { ItemIdentifier = item.MessageId, }, + createResponse: (failures, _) => new SQSBatchResponse(failures.ToList())); + +// R1: every completed item contributes one TResult; any unhandled error prevents the response. +// A typed delegate local supplies dependency types that a bare method group cannot infer. +static void RegisterResults(LambdaApplication lambda) +{ + Func> handle = + EventHandlers.HandleImportAsync; + + lambda.MapEventHandler( + split: (ImportBatch batch, ILambdaInvocationContext _) => batch.Items, + handle: handle, + createResponse: (results, _) => + new BatchSummary(results.Count(result => result is Success))); +} + +// R2: SQS partial batch response. An async lambda block makes the result family unambiguous. +// Stopping omits unstarted items from the response. +static void RegisterResultsWithRecovery(LambdaApplication lambda) => + lambda.MapEventHandler( + split: (SqsEnvelope batch, ILambdaInvocationContext _) => batch.Records, + handle: async Task ( + SqsEnvelope.SqsMessageEnvelope item, + DocumentImporter importer, + IEventProcessingContext processing, + CancellationToken token) => + await EventHandlers.HandleSqsMessageAsync(item, importer, processing, token), + onError: (item, _, _) => new Retry(item.MessageId), + createResponse: (results, _) => new SQSBatchResponse( + results + .OfType() + .Select(result => + new SQSBatchResponse.BatchItemFailure { ItemIdentifier = result.MessageId, }) .ToList())); -// Start the Lambda runtime loop. -await lambda.RunAsync(); +public sealed record MyEvent(string Message, bool StopProcessing = false); -public record MyEvent(string Message); +public sealed record ImportBatch(IReadOnlyList Items); -public enum EventOutcome -{ - Success, - Retry, -} +public sealed record ImportDocument(MyEvent Event); -public sealed record EventItemResult(TItem Item, TItemResult Result); +public sealed record BatchSummary(int Count); -public sealed class EventBatchResult -{ - public IReadOnlyList> Items { get; } = []; -} +public abstract record ImportItemResult; -public sealed record ExampleResponse(IReadOnlyList RetryMessageIds); +public sealed record Success(string MessageId) : ImportItemResult; -// Required so the generated test project can reference this top-level Program. -public partial class Program; +public sealed record Retry(string MessageId) : ImportItemResult; -public static class Extension +public sealed class DocumentImporter { - extension(LambdaApplication lambda) + public Task ImportAsync(MyEvent message, CancellationToken token) { - public LambdaApplication MapEventHandler( - Func> split, - Func handle, - EventHandlerOptions? options = null) - => lambda; - - public LambdaApplication MapEventHandler( - Func> split, - Func handle, - EventHandlerOptions? options = null) - => lambda; - - public LambdaApplication MapEventHandler( - Func> split, - Func handle, - EventHandlerOptions? options = null) - => lambda; - - public LambdaApplication - MapEventHandler( - Func> split, - Func> handle, - Func, ILambdaInvocationContext, TResponse> - createResponse, - EventHandlerOptions? options = null) - => lambda; - - public LambdaApplication - MapEventHandler( - Func> split, - Func> handle, - Func onError, - Func, ILambdaInvocationContext, TResponse> - createResponse, - EventHandlerOptions? options = null) - => lambda; + token.ThrowIfCancellationRequested(); + return Task.CompletedTask; } -} - -public sealed class EventHandlerOptions -{ - public int MaxConcurrentExecutions { get; init; } = 10; -} -public class MyService -{ - public void DoStuff(string input) { } -} - -public class MyOtherService -{ - public void DoStuff(string input) { } + public Task ImportResultAsync(MyEvent message, CancellationToken token) + { + token.ThrowIfCancellationRequested(); + return Task.FromResult(new Success(message.Message)); + } } public static class EventHandlers { - public static Task HandleS3RecordAsync( - S3Event.S3EventNotificationRecord item, - MyService service, - MyOtherService otherService) + public static Task HandleImportAsync( + ImportDocument item, + DocumentImporter importer, + CancellationToken token) => + importer.ImportResultAsync(item.Event, token); + + public static async Task HandleSqsMessageAsync( + SqsEnvelope.SqsMessageEnvelope item, + DocumentImporter importer, + IEventProcessingContext processing, + CancellationToken token) { - service.DoStuff(item.S3.Object.Key); - otherService.DoStuff(item.EventName); - return Task.CompletedTask; + if (item.BodyContent is null) + return new Retry(item.MessageId); + + if (item.BodyContent.StopProcessing) + processing.StopProcessing(); + + return await importer.ImportResultAsync(item.BodyContent, token); } } + +[JsonSerializable(typeof(SqsEnvelope))] +[JsonSerializable(typeof(SQSBatchResponse))] +[JsonSerializable(typeof(MyEvent))] +internal partial class EventProcessorJsonContext : JsonSerializerContext; + +// Required so the generated test project can reference this top-level Program. +public partial class Program; diff --git a/examples/MinimalLambda.Example.EventProcessor/README.md b/examples/MinimalLambda.Example.EventProcessor/README.md index 9e156426..26cbe0c8 100644 --- a/examples/MinimalLambda.Example.EventProcessor/README.md +++ b/examples/MinimalLambda.Example.EventProcessor/README.md @@ -1,15 +1,24 @@ # MinimalLambda.Example.EventProcessor -MinimalLambda AWS Lambda function project. - -This starter project contains: - -- `Program.cs` - Lambda host setup and sample handler. -- `MinimalLambda.Example.EventProcessor.csproj` - .NET project configured for AWS Lambda deployment. -- `aws-lambda-tools-defaults.json` - default settings used by Visual Studio and `dotnet lambda` commands. -- `../../test/MinimalLambda.Example.EventProcessor.Tests` - integration tests using `MinimalLambda.Testing`. - -The generated handler accepts a `string` Lambda event and returns the uppercase equivalent. Replace the event type, return type, and handler body in `Program.cs` to match your Lambda trigger. +Sample event-processor registrations. `MapEventHandler` consumes the single invocation handler slot, +so this project registers exactly one family per run and selects it with `EVENT_PROCESSOR_SAMPLE`. + +| Value | Family | Shows | +| -------------- | ------ | --------------------------------------------------------------------- | +| `n1` | N1 | per-item DI scope, processing token, `StopProcessing()` | +| `n2` | N2 | `createResponse` from successfully handled source items | +| `n3` | N3 | `onError` mapping failures and building an SQS partial batch response | +| `r1` | R1 | per-item `TResult` contributions through a typed delegate local | +| `r2` (default) | R2 | success and retry contributions, graceful stop, method-group shape | + +## Program.cs + +- `RegisterNoResult` - no result, no response. +- `RegisterNoResultWithResponse` - response from completed source items. +- `RegisterNoResultWithFailures` - successes contribute nothing, failures map to SQS batch item + failures. +- `RegisterResults` - every completed item contributes one result. +- `RegisterResultsWithRecovery` - the SQS partial batch response shape. ## Prerequisites @@ -17,108 +26,18 @@ The generated handler accepts a `string` Lambda event and returns the uppercase - AWS credentials configured locally if you plan to deploy. - Amazon.Lambda.Tools for command-line deployment. -Install Amazon.Lambda.Tools if needed: - -```bash -dotnet tool install -g Amazon.Lambda.Tools -``` - -Update Amazon.Lambda.Tools if already installed: - -```bash -dotnet tool update -g Amazon.Lambda.Tools -``` - ## Restore and build -From this project directory: - ```bash dotnet restore dotnet build ``` -## Run tests - -From this project directory: - -```bash -dotnet test ../../test/MinimalLambda.Example.EventProcessor.Tests/MinimalLambda.Example.EventProcessor.Tests.csproj -``` - -Or from the generated repository/folder root: +## Run a sample locally ```bash -dotnet test test/MinimalLambda.Example.EventProcessor.Tests/MinimalLambda.Example.EventProcessor.Tests.csproj +EVENT_PROCESSOR_SAMPLE=r2 dotnet run ``` -## Central Package Management - -This template emits versioned `PackageReference` items. If your repository uses Central Package Management, move those versions into `Directory.Packages.props` and remove `Version="..."` from the generated app and test project references. - -Add or update these entries at the repository root: - -```xml - - - - - - - -``` - -## Configure AWS deployment defaults - -`aws-lambda-tools-defaults.json` contains deployment defaults for `dotnet lambda` and the AWS Toolkit for Visual Studio: - -- `profile` - AWS credentials profile. -- `region` - AWS region. -- `function-runtime` - Lambda runtime. -- `function-memory-size` - memory in MB. -- `function-timeout` - timeout in seconds. -- `function-handler` - executable assembly name for this MinimalLambda app. - -You can set profile and region when creating the project: - -```bash -dotnet new mlambda -n MinimalLambda.Example.EventProcessor --profile default --region us-east-1 -``` - -Or edit `aws-lambda-tools-defaults.json` before deployment. - -## Deploy from the command line - -From this project directory: - -```bash -dotnet lambda deploy-function -``` - -The AWS Lambda .NET CLI reads `aws-lambda-tools-defaults.json` for default deployment settings and prompts for any missing values. - -Useful commands: - -```bash -dotnet lambda help -dotnet lambda list-functions -dotnet lambda invoke-function MinimalLambda.Example.EventProcessor --payload "hello world" -``` - -## Deploy from Visual Studio - -With the AWS Toolkit for Visual Studio installed: - -1. Right-click the project in Solution Explorer. -2. Select **Publish to AWS Lambda**. -3. Review values from `aws-lambda-tools-defaults.json`. -4. Publish the function. - -After deployment, use the AWS Explorer Lambda Function View to test invocations, configure event sources, update runtime configuration, and view CloudWatch logs. - -## Next steps - -- Replace the sample `string` handler with your event type. -- Register services with `builder.Services` in `Program.cs`. -- Add middleware with `lambda.UseMiddleware(...)` for logging, validation, or error handling. -- Update tests in `../../test/MinimalLambda.Example.EventProcessor.Tests` to cover your handler behavior. +Deploying an R2/N3 SQS sample requires `ReportBatchItemFailures` on the event source mapping, and +the FIFO/SQS limits described in `docs/features/event-processor.md`. diff --git a/src/AotCompatibility.TestApp/AotCompatibility.TestApp.csproj b/src/AotCompatibility.TestApp/AotCompatibility.TestApp.csproj index 39ba9afc..fafe9402 100644 --- a/src/AotCompatibility.TestApp/AotCompatibility.TestApp.csproj +++ b/src/AotCompatibility.TestApp/AotCompatibility.TestApp.csproj @@ -10,7 +10,14 @@ true IL2026;IL2087;IL2091;IL3050;IL3051 false + $(InterceptorsNamespaces);MinimalLambda.Generated + + + (); +builder.Services.ConfigureEnvelopeOptions(options => + options.JsonOptions.TypeInfoResolver = EventProcessorAotJsonContext.Default); +builder.Services.AddScoped(); + +await using var lambda = builder.Build(); + +// One mapping site only: reaching a second mapping for the same invocation handler throws. +lambda.MapEventHandler( + split: (SQSEvent batch, ILambdaInvocationContext _) => batch.Records, + handle: async Task ( + SQSEvent.SQSMessage item, + RecordHandler handler, + CancellationToken token) => await handler.HandleAsync(item, token), + onError: (item, _, _) => new Retry(item.MessageId), + createResponse: (results, _) => new SQSBatchResponse( + results + .OfType() + .Select(result => + new SQSBatchResponse.BatchItemFailure { ItemIdentifier = result.MessageId, }) + .ToList())); + +// Registration alone roots the generated processor. The runtime loop is intentionally not started +// because this project exists for publish analysis, not execution. return; + +internal sealed class RecordHandler +{ + public Task HandleAsync(SQSEvent.SQSMessage item, CancellationToken token) + { + token.ThrowIfCancellationRequested(); + return Task.FromResult(new Success(item.MessageId)); + } +} + +internal abstract record ImportResult; + +internal sealed record Success(string MessageId) : ImportResult; + +internal sealed record Retry(string MessageId) : ImportResult; + +[JsonSerializable(typeof(SQSEvent))] +[JsonSerializable(typeof(SQSBatchResponse))] +internal partial class EventProcessorAotJsonContext : JsonSerializerContext; From 9c5964ec64c63f932eebdf07031abd318f3a25b6 Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Wed, 28 Oct 2026 16:18:54 -0400 Subject: [PATCH 08/21] test(event-processor): pin method-group and union-result binding failures Add compilation tests for the two binding limits the API relies on: a method group cannot supply dependency parameter types (the compiler reports CS1503/CS0411), and a Task handler cannot satisfy a Task result family. Align the docs and skill reference with the observed compiler diagnostics. --- docs/features/event-processor.md | 3 +- .../references/event-processor.md | 4 +- .../EventHandlerDiscoveryTests.cs | 81 +++++++++++++++++++ 3 files changed, 85 insertions(+), 3 deletions(-) diff --git a/docs/features/event-processor.md b/docs/features/event-processor.md index 034d8a68..e3f2ae82 100644 --- a/docs/features/event-processor.md +++ b/docs/features/event-processor.md @@ -204,7 +204,8 @@ explicitly: - specify all generic arguments when nothing else works. A method group does not supply dependency parameter types for generic inference. This does not -compile: +compile (the compiler reports a method-group conversion or type-inference failure, `CS1503` or +`CS0411`): ```csharp lambda.MapEventHandler(split, EventHandlers.HandleAsync); // CS0411 diff --git a/skills/minimal-lambda/references/event-processor.md b/skills/minimal-lambda/references/event-processor.md index fa1880ce..546eccdf 100644 --- a/skills/minimal-lambda/references/event-processor.md +++ b/skills/minimal-lambda/references/event-processor.md @@ -145,8 +145,8 @@ Requirements and limits: 3. pass all generic arguments: `lambda.MapEventHandler(split, Handler);`. -A method group alone cannot supply DI parameter types - it produces `CS0411`. Do not add a `Delegate` -catch-all. +A method group alone cannot supply DI parameter types - it fails to compile (`CS1503` or `CS0411`). +Do not add a `Delegate` catch-all. ## Diagnostics diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs index 41be19b3..8b3527ad 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs @@ -136,6 +136,76 @@ internal sealed class Response; StringComparison.Ordinal)); } + [Fact] + public void ReportsCompileErrorForUntypedMethodGroupWithUnknownDependency() + { + var errors = CompileErrors( + """ + using System.Collections.Generic; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: Handle); + + static Task Handle(Item item, Probe probe) => Task.CompletedTask; + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + + internal sealed class Probe; + """); + + // Method groups cannot supply the dependency input type. The compiler reports the failed + // method-group conversion (CS1503) instead of the bare inference failure (CS0411) once the + // full overload set is visible, so both are accepted here. + errors.Should().Contain(id => id == "CS0411" || id == "CS1503"); + } + + [Fact] + public void RejectsConcreteTaskResultWhereAUnionResultIsRequired() + { + var errors = CompileErrors( + """ + using System.Collections.Generic; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: HandleSuccess, + createResponse: (IEnumerable results, ILambdaInvocationContext _) => new Response()); + + static Task HandleSuccess(Item item) => Task.FromResult(new Success()); + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + + internal abstract class Outcome; + + internal sealed class Success : Outcome; + + internal sealed class Retry : Outcome; + + internal sealed class Response; + """); + + errors.Should().NotBeEmpty(); + } + [Fact] public void IgnoresSameNamedMapEventHandlerFromConsumerAssembly() { @@ -187,6 +257,17 @@ private static GeneratorDriverRunResult RunGenerator(string source) return driver.GetRunResult(); } + private static IReadOnlyList CompileErrors(string source) + { + var (_, compilation) = GeneratorTestHelpers.GenerateFromSource(source); + return compilation + .GetDiagnostics(TestContext.Current.CancellationToken) + .Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) + .Select(diagnostic => diagnostic.Id) + .Distinct() + .ToList(); + } + private static Compilation CompileWithGenerated( Compilation originalCompilation, GeneratorDriverRunResult result) From faa207908413ae5feb3e5de2c373beb695b9116e Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Wed, 28 Oct 2026 16:32:37 -0400 Subject: [PATCH 09/21] test(event-processor): cover concurrency caps, DI inputs, and provider stability Close the remaining acceptance gaps in the runtime and generator suites: custom concurrency caps and cap 1, single split enumeration completed before handlers start, duplicate items, keyed and unregistered nullable services, results used after their item scope is disposed, missing dependencies failing without a response, rejected second mappings leaving registered providers untouched, positional/reordered argument syntax, invalid keyed keys (LH0003), and single-validator plus user-configuration preservation for the options. --- .../EventHandlerDiscoveryTests.cs | 74 +++++ .../ServiceCollectionExtensionsTests.cs | 37 +++ .../Core/Runtime/EventProcessorTests.cs | 300 ++++++++++++++++++ 3 files changed, 411 insertions(+) diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs index 8b3527ad..5d62efd6 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs @@ -206,6 +206,80 @@ internal sealed class Response; errors.Should().NotBeEmpty(); } + [Fact] + public void RecognizesPositionalAndReorderedArguments() + { + var result = RunGenerator( + """ + using System.Collections.Generic; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + + app.MapEventHandler( + (Batch batch, ILambdaInvocationContext _) => batch.Items, + Handle, + (IEnumerable items, ILambdaInvocationContext _) => new Response()); + + app.MapEventHandler( + createResponse: (IEnumerable items, ILambdaInvocationContext _) => new Response(), + handle: Handle, + split: (Batch batch, ILambdaInvocationContext _) => batch.Items); + + static Task Handle(Item item) => Task.CompletedTask; + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + + internal sealed class Response; + """); + + result.Diagnostics.Should().BeEmpty(); + var generated = result + .GeneratedTrees + .Should() + .ContainSingle(tree => tree.FilePath.EndsWith( + "MinimalLambda.EventHandlers.g.cs", + StringComparison.Ordinal)) + .Subject + .ToString(); + generated.Split("MapEventHandlerInterceptor").Length.Should().Be(3); + } + + [Fact] + public void ReportsInvalidKeyedServiceKeyOnHandlerParameter() + { + var result = RunGenerator( + """ + using System.Threading.Tasks; + using Microsoft.Extensions.DependencyInjection; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _, [FromKeyedServices(new[] { "a", "b" })] Service _) => Task.CompletedTask); + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + + internal sealed class Service; + """); + + result.Diagnostics.Should().ContainSingle().Which.Id.Should().Be("LH0003"); + } + [Fact] public void IgnoresSameNamedMapEventHandlerFromConsumerAssembly() { diff --git a/tests/MinimalLambda.UnitTests/Builder/Extensions/ServiceCollectionExtensionsTests.cs b/tests/MinimalLambda.UnitTests/Builder/Extensions/ServiceCollectionExtensionsTests.cs index b5238dc2..a3786ec6 100644 --- a/tests/MinimalLambda.UnitTests/Builder/Extensions/ServiceCollectionExtensionsTests.cs +++ b/tests/MinimalLambda.UnitTests/Builder/Extensions/ServiceCollectionExtensionsTests.cs @@ -45,6 +45,43 @@ public void AddLambdaHostCoreServices_DoesNotRequireLambdaSerializerUntilInvocat act.Should().NotThrow(); } + [Fact] + public void AddLambdaHostCoreServices_RegistersSingleEventHandlerOptionsValidator() + { + // Arrange + using var serviceProvider = new ServiceCollection() + .AddLambdaHostCoreServices() + .AddLambdaHostCoreServices() + .BuildServiceProvider(); + + // Act + var validators = serviceProvider.GetServices>(); + + // Assert + validators.Should().ContainSingle(); + } + + [Fact] + public void AddLambdaHostCoreServices_PreservesUserEventHandlerConfiguration() + { + // Arrange + using var serviceProvider = new ServiceCollection() + .AddLambdaHostCoreServices() + .Configure(options => + { + options.EnableConcurrency = false; + options.MaxConcurrentExecutions = 3; + }) + .BuildServiceProvider(); + + // Act + var options = serviceProvider.GetRequiredService>().Value; + + // Assert + options.EnableConcurrency.Should().BeFalse(); + options.MaxConcurrentExecutions.Should().Be(3); + } + [Theory] #if NET11_0_OR_GREATER [InlineData(24)] diff --git a/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs b/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs index 6c4b1dc6..1acce11d 100644 --- a/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs +++ b/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs @@ -682,6 +682,279 @@ public async Task ResponseInputIsRepeatablyEnumerableInSourceOrder() secondPass.Should().Equal(3, 1, 2); } + [Fact] + public async Task CustomConcurrencyCapLimitsActiveOperations() + { + // Arrange + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var active = 0; + var maxActive = 0; + var started = 0; + var sync = new object(); + + var builder = LambdaApplication.CreateBuilder(); + builder.Services.Configure(options => + options.MaxConcurrentExecutions = 2); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: async (Item _) => + { + lock (sync) + { + active++; + started++; + maxActive = Math.Max(maxActive, active); + } + + await gate.Task.ConfigureAwait(false); + + lock (sync) + active--; + }); + + var harness = CreateHarness( + app, + new Batch([new Item(1), new Item(2), new Item(3), new Item(4)])); + var handler = app.Build(); + + // Act + var invocation = handler(harness.Context); + await WaitForAsync(() => + { + lock (sync) + return started >= 2; + }); + gate.SetResult(); + await invocation; + + // Assert + lock (sync) + maxActive.Should().Be(2); + } + + [Fact] + public async Task ConcurrencyLimitOfOneRunsSequentially() + { + // Arrange + var firstStarted = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var secondStarted = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseFirst = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + var builder = LambdaApplication.CreateBuilder(); + builder.Services.Configure(options => + options.MaxConcurrentExecutions = 1); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: async (Item item) => + { + if (item.Id == 1) + { + firstStarted.TrySetResult(); + await releaseFirst.Task.ConfigureAwait(false); + return; + } + + secondStarted.TrySetResult(); + }); + + var harness = CreateHarness(app, new Batch([new Item(1), new Item(2)])); + var handler = app.Build(); + + // Act + var invocation = handler(harness.Context); + await firstStarted.Task.WaitAsync( + TimeSpan.FromSeconds(10), + TestContext.Current.CancellationToken); + + // Assert + secondStarted.Task.IsCompleted.Should().BeFalse(); + releaseFirst.SetResult(); + await invocation; + secondStarted.Task.IsCompleted.Should().BeTrue(); + } + + [Fact] + public async Task SplitIsEnumeratedOnceAndFinishesBeforeHandlersStart() + { + // Arrange + var enumerationCount = 0; + var enumerationFinished = false; + var handlerRanBeforeEnumerationFinished = false; + + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => Enumerate(), + handle: (Item _) => + { + if (!enumerationFinished) + handlerRanBeforeEnumerationFinished = true; + + return Task.CompletedTask; + }); + + IEnumerable Enumerate() + { + enumerationCount++; + yield return new Item(1); + yield return new Item(2); + enumerationFinished = true; + } + + var harness = CreateHarness(app, new Batch([])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + enumerationCount.Should().Be(1); + enumerationFinished.Should().BeTrue(); + handlerRanBeforeEnumerationFinished.Should().BeFalse(); + } + + [Fact] + public async Task DuplicateItemsRemainSeparateOrderedContributions() + { + // Arrange + Response? captured = null; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => Task.FromResult(item.Id), + createResponse: (results, _) => + { + captured = new Response(results.ToList()); + return captured; + }); + + var harness = CreateHarness( + app, + new Batch([new Item(7), new Item(7), new Item(1), new Item(7)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + captured!.Ids.Should().Equal(7, 7, 1, 7); + } + + [Fact] + public async Task ResolvesKeyedServicesAndToleratesUnregisteredNullableServices() + { + // Arrange + KeyedValue? keyed = null; + OptionalValue? optional = null; + var builder = LambdaApplication.CreateBuilder(); + builder.Services.AddKeyedScoped("primary", (_, _) => new KeyedValue(42)); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: ( + Item _, + [FromKeyedServices("primary")] KeyedValue keyedValue, + OptionalValue? optionalValue) => + { + keyed = keyedValue; + optional = optionalValue; + return Task.CompletedTask; + }); + + var harness = CreateHarness(app, new Batch([new Item(1)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + keyed!.Value.Should().Be(42); + optional.Should().BeNull(); + } + + [Fact] + public async Task KeepsScopedResultsValidAfterTheItemScopeIsDisposed() + { + // Arrange + Response? captured = null; + var builder = LambdaApplication.CreateBuilder(); + builder.Services.AddScoped(); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item, ScopedValue value) => + Task.FromResult(new ResultDto(item.Id, value.InstanceId)), + createResponse: (results, _) => + { + captured = new Response(results.Select(result => result.ItemId).ToList()); + return captured; + }); + + var harness = CreateHarness(app, new Batch([new Item(5)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + captured!.Ids.Should().Equal(5); + ScopedValue.Disposed.Should().BeTrue(); + } + + [Fact] + public async Task MissingDependencyFailsInvocationWithoutBuildingResponse() + { + // Arrange + var responseCalls = 0; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _, UnregisteredValue _) => Task.CompletedTask, + createResponse: (IEnumerable _, ILambdaInvocationContext _) => + { + responseCalls++; + return new Response([]); + }); + + var harness = CreateHarness(app, new Batch([new Item(1)])); + var handler = app.Build(); + + // Act + var act = () => handler(harness.Context); + + // Assert + await act.Should().ThrowAsync(); + responseCalls.Should().Be(0); + } + + [Fact] + public async Task RejectedSecondMappingLeavesRegisteredProvidersInPlace() + { + // Arrange + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _) => Task.CompletedTask, + createResponse: (IEnumerable _, ILambdaInvocationContext _) => new Response([])); + var propertiesAfterFirst = app.Properties.Count; + + // Act + var act = () => app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _) => Task.CompletedTask); + + // Assert + act.Should().Throw(); + app.Properties.Count.Should().Be(propertiesAfterFirst); + + var handler = app.Build(); + await handler(CreateHarness(app, new Batch([new Item(1)])).Context); + } + private static async Task WaitForAsync(Func condition) { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); @@ -787,5 +1060,32 @@ internal sealed record Batch(IReadOnlyList Items); internal sealed record Item(int Id); + internal sealed record KeyedValue(int Value); + + internal sealed record OptionalValue(int Value); + + internal sealed record ResultDto(int ItemId, int ScopeId); + + internal sealed class UnregisteredValue; + + internal sealed class ScopedValue : IDisposable + { + private static readonly ConcurrentBag Ids = []; + private static int _nextId; + private static int _disposed; + + public ScopedValue() + { + InstanceId = Interlocked.Increment(ref _nextId); + Ids.Add(InstanceId); + } + + public int InstanceId { get; } + + public static bool Disposed => Volatile.Read(ref _disposed) > 0; + + public void Dispose() => Interlocked.Increment(ref _disposed); + } + public sealed record Response(IReadOnlyList Ids); } From 4a950ae620d7db3234fe930122b58765a3a20948 Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Wed, 28 Oct 2026 16:39:09 -0400 Subject: [PATCH 10/21] test(event-processor): cover split, family, control, and coexistence edges Add the remaining acceptance coverage: nullable item retention, enumeration failure with enumerator disposal, N3 mapped-failures-only contributions, synchronous throws mapped once, unrelated OperationCanceledException mapping, response-builder failure, feature providers registered only for the family in use, singleton sharing, stop requested from an error mapper, repeated and escalated control requests, fresh state across invocations, Release-only stub failure, async-void compile rejection, and coexistence with invocation and lifecycle generated files. --- .../EventHandlerDiscoveryTests.cs | 27 ++ .../EventHandlerEmitterTests.cs | 43 +++ ...HandlerLambdaApplicationExtensionsTests.cs | 41 ++ .../Core/Runtime/EventProcessorTests.cs | 359 ++++++++++++++++++ 4 files changed, 470 insertions(+) create mode 100644 tests/MinimalLambda.UnitTests/Builder/InterceptionTargets/MapEventHandlerLambdaApplicationExtensionsTests.cs diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs index 5d62efd6..1c1232af 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs @@ -206,6 +206,33 @@ internal sealed class Response; errors.Should().NotBeEmpty(); } + [Fact] + public void RejectsAsyncVoidHandlerAtCompileTime() + { + var errors = CompileErrors( + """ + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: Handle); + + static async void Handle(Item item) => await Task.CompletedTask; + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + """); + + errors.Should().NotBeEmpty(); + } + [Fact] public void RecognizesPositionalAndReorderedArguments() { diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs index 90f106b0..b795fd44 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs @@ -108,6 +108,49 @@ internal sealed class Service internal sealed class Response; """); + [Fact] + public void CoexistsWithInvocationLifecycleAndMiddlewareGeneratedFiles() + { + const string source = """ + using System.Collections.Generic; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + app.OnInit(() => Task.CompletedTask); + app.MapHandler(() => "hello"); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => Task.CompletedTask, + createResponse: (IEnumerable items, ILambdaInvocationContext _) => new Response()); + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + + internal sealed class Response; + """; + + var (driver, _) = GeneratorTestHelpers.GenerateFromSource(source); + var result = driver.GetRunResult(); + + result.Diagnostics.Should().BeEmpty(); + result + .GeneratedTrees + .Select(tree => tree.FilePath.Split('/').Last()) + .Should() + .Contain( + [ + "MinimalLambda.InvocationHandlers.g.cs", + "MinimalLambda.EventHandlers.g.cs", + "MinimalLambda.OnInitHandlers.g.cs", + ]); + } + [Fact] public void EmitsSingleDeterministicFileForMultipleSites() { diff --git a/tests/MinimalLambda.UnitTests/Builder/InterceptionTargets/MapEventHandlerLambdaApplicationExtensionsTests.cs b/tests/MinimalLambda.UnitTests/Builder/InterceptionTargets/MapEventHandlerLambdaApplicationExtensionsTests.cs new file mode 100644 index 00000000..94aaca28 --- /dev/null +++ b/tests/MinimalLambda.UnitTests/Builder/InterceptionTargets/MapEventHandlerLambdaApplicationExtensionsTests.cs @@ -0,0 +1,41 @@ +#if !DEBUG +using System.Reflection; +using MinimalLambda.Builder; + +namespace MinimalLambda.UnitTests.Builder.InterceptionTargets; + +public class MapEventHandlerLambdaApplicationExtensionsTests +{ + // Debug.Fail in the stub contract FailFasts under a Debug build, so this executes in Release + // only. + [Fact] + public void StubFailsClearlyWhenInterceptionDoesNotOccur() + { + // Arrange + var application = Substitute.For(); + var split = (StubBatch batch, ILambdaInvocationContext _) => batch.Items; + Func handle = _ => Task.CompletedTask; + var stub = typeof(MapEventHandlerLambdaApplicationExtensions) + .GetMethods(BindingFlags.Public | BindingFlags.Static) + .Single(method => + method.Name == "MapEventHandler" + && method.IsGenericMethodDefinition + && method.GetGenericArguments().Length == 2); + var closed = stub.MakeGenericMethod(typeof(StubBatch), typeof(StubItem)); + + // Act + var act = () => closed.Invoke(null, [application, split, handle]); + + // Assert + act + .Should() + .Throw() + .WithInnerException() + .WithMessage("*compile time*"); + } + + private sealed record StubBatch(IReadOnlyList Items); + + private sealed record StubItem(int Id); +} +#endif diff --git a/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs b/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs index 1acce11d..f801db38 100644 --- a/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs +++ b/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs @@ -1,3 +1,4 @@ +using System.Collections; using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; @@ -955,6 +956,331 @@ public async Task RejectedSecondMappingLeavesRegisteredProvidersInPlace() await handler(CreateHarness(app, new Batch([new Item(1)])).Context); } + [Fact] + public async Task RetainsNullableItemsAndDoesNotFilterNulls() + { + // Arrange + IReadOnlyList? contributions = null; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item? _) => Task.CompletedTask, + createResponse: (items, _) => + { + contributions = items.ToList(); + return new Response([]); + }); + + var harness = CreateHarness(app, new Batch([null!, new Item(1)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + contributions.Should().HaveCount(2); + contributions!.Count(item => item is null).Should().Be(1); + } + + [Fact] + public async Task EnumerationFailureFailsBeforeHandlingAndDisposesTheEnumerator() + { + // Arrange + var enumerable = new ThrowingEnumerable(); + var handlerCalls = 0; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch _, ILambdaInvocationContext _) => enumerable, + handle: (Item _) => + { + handlerCalls++; + return Task.CompletedTask; + }); + + var harness = CreateHarness(app, new Batch([])); + var handler = app.Build(); + + // Act + var act = () => handler(harness.Context); + + // Assert + await act.Should().ThrowAsync(); + handlerCalls.Should().Be(0); + enumerable.Disposed.Should().BeTrue(); + } + + [Fact] + public async Task CollectsOnlyMappedFailuresForTheNoResultRecoveryFamily() + { + // Arrange + Response? captured = null; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => + item.Id == 2 + ? Task.FromException(new InvalidOperationException("failed")) + : Task.CompletedTask, + onError: (item, _, _) => item.Id, + createResponse: (failures, _) => + { + captured = new Response(failures.ToList()); + return captured; + }); + + var harness = CreateHarness(app, new Batch([new Item(1), new Item(2), new Item(3)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + captured!.Ids.Should().Equal(2); + } + + [Fact] + public async Task SynchronousHandlerThrowIsMappedOnce() + { + // Arrange + var mapperCalls = 0; + Response? captured = null; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => SyncThrow(item), + onError: (item, _, _) => + { + mapperCalls++; + return item.Id; + }, + createResponse: (results, _) => + { + captured = new Response(results.ToList()); + return captured; + }); + + static Task SyncThrow(Item item) => + throw new InvalidOperationException($"synchronous failure for {item.Id}"); + + var harness = CreateHarness(app, new Batch([new Item(4)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + mapperCalls.Should().Be(1); + captured!.Ids.Should().Equal(4); + } + + [Fact] + public async Task UnrelatedCancellationExceptionIsMappedNormally() + { + // Arrange + Response? captured = null; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _) => Task.FromException(new OperationCanceledException()), + onError: (item, _, _) => item.Id, + createResponse: (results, _) => + { + captured = new Response(results.ToList()); + return captured; + }); + + var harness = CreateHarness(app, new Batch([new Item(8)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + captured!.Ids.Should().Equal(8); + } + + [Fact] + public async Task ResponseBuilderFailureFailsInvocation() + { + // Arrange + await using var app = LambdaApplication.CreateBuilder().Build(); + Func, ILambdaInvocationContext, Response> builder = (_, _) => + throw new InvalidOperationException("builder failed"); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => Task.FromResult(item.Id), + createResponse: builder); + + var harness = CreateHarness(app, new Batch([new Item(1)])); + var handler = app.Build(); + + // Act + var act = () => handler(harness.Context); + + // Assert + await act.Should().ThrowAsync(); + harness.ResponseFeature.DidNotReceiveWithAnyArgs().SetResponse(default(Response)!); + } + + [Fact] + public async Task RegistersOnlyTheFeatureProvidersTheFamilyNeeds() + { + // Arrange + await using var noResult = LambdaApplication.CreateBuilder().Build(); + noResult.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _) => Task.CompletedTask); + var noResultProperties = noResult.Properties.Count; + + await using var withResult = LambdaApplication.CreateBuilder().Build(); + withResult.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => Task.FromResult(item.Id), + createResponse: (results, _) => new Response(results.ToList())); + var withResultProperties = withResult.Properties.Count; + + // Assert + noResultProperties.Should().Be(1); + withResultProperties.Should().Be(noResultProperties + 1); + } + + [Fact] + public async Task SharesSingletonServicesAcrossItems() + { + // Arrange + var seen = new ConcurrentBag(); + var builder = LambdaApplication.CreateBuilder(); + builder.Services.AddSingleton(); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _, SingletonProbe probe) => + { + seen.Add(probe); + return Task.CompletedTask; + }); + + var harness = CreateHarness(app, new Batch([new Item(1), new Item(2), new Item(3)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + seen.Should().HaveCount(3); + seen.Distinct().Should().ContainSingle(); + } + + [Fact] + public async Task StopRequestedFromErrorMapperPreventsFurtherClaimsAndKeepsMappedValues() + { + // Arrange + var handled = new ConcurrentBag(); + Response? captured = null; + var builder = LambdaApplication.CreateBuilder(); + builder.Services.Configure(options => + options.MaxConcurrentExecutions = 1); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => + { + handled.Add(item.Id); + return Task.FromException(new InvalidOperationException("failed")); + }, + onError: (item, _, processing) => + { + processing.StopProcessing(); + return item.Id; + }, + createResponse: (failures, _) => + { + captured = new Response(failures.ToList()); + return captured; + }); + + var harness = CreateHarness(app, new Batch([new Item(1), new Item(2), new Item(3)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + handled.Should().BeEquivalentTo(new[] { 1 }); + captured!.Ids.Should().Equal(1); + } + + [Fact] + public async Task RepeatedAndEscalatedControlRequestsAreHarmless() + { + // Arrange + var tokenCancelled = false; + var tokenAfterCancellation = false; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _, IEventProcessingContext processing, CancellationToken token) => + { + processing.StopProcessing(); + processing.StopProcessing(); + processing.CancelProcessing(); + processing.CancelProcessing(); + tokenCancelled = token.IsCancellationRequested; + processing.CancelProcessing(); + tokenAfterCancellation = token.IsCancellationRequested; + return Task.CompletedTask; + }); + + var harness = CreateHarness(app, new Batch([new Item(1)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + tokenCancelled.Should().BeTrue(); + tokenAfterCancellation.Should().BeTrue(); + harness.InvocationCancellation.IsCancellationRequested.Should().BeFalse(); + } + + [Fact] + public async Task EachInvocationStartsWithFreshProcessingState() + { + // Arrange + var handled = new ConcurrentBag(); + var tokensCancelledAtEntry = new ConcurrentBag(); + var handledPerInvocation = new List(); + var builder = LambdaApplication.CreateBuilder(); + builder.Services.Configure(options => + options.MaxConcurrentExecutions = 1); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item, IEventProcessingContext processing, CancellationToken token) => + { + handled.Add(item.Id); + tokensCancelledAtEntry.Add(token.IsCancellationRequested); + + if (item.Id == 1) + processing.StopProcessing(); + + return Task.CompletedTask; + }); + + var handler = app.Build(); + + // Act + await handler(CreateHarness(app, new Batch([new Item(1), new Item(2)])).Context); + handledPerInvocation.Add(handled.Count); + + await handler(CreateHarness(app, new Batch([new Item(3), new Item(4)])).Context); + handledPerInvocation.Add(handled.Count); + + // Assert + handledPerInvocation.Should().Equal(1, 3); + tokensCancelledAtEntry.Should().OnlyContain(cancelled => cancelled == false); + } + private static async Task WaitForAsync(Func condition) { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); @@ -1068,6 +1394,39 @@ internal sealed record ResultDto(int ItemId, int ScopeId); internal sealed class UnregisteredValue; + internal sealed class SingletonProbe; + + private sealed class ThrowingEnumerable : IEnumerable + { + public bool Disposed { get; private set; } + + public IEnumerator GetEnumerator() => new Enumerator(this); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + private sealed class Enumerator(ThrowingEnumerable owner) : IEnumerator + { + private int index = -1; + + public Item Current => new(1); + + object IEnumerator.Current => Current; + + public bool MoveNext() + { + index++; + if (index == 2) + throw new InvalidOperationException("enumeration failed"); + + return index < 2; + } + + public void Reset() => index = -1; + + public void Dispose() => owner.Disposed = true; + } + } + internal sealed class ScopedValue : IDisposable { private static readonly ConcurrentBag Ids = []; From 85df7d6fb9b1df551c219e2f2f344bd7ecdcab09 Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Wed, 28 Oct 2026 16:46:41 -0400 Subject: [PATCH 11/21] test(event-processor): cover options, disposal, and stop boundaries Add non-positive limit validation in both concurrency modes, mapper cancellation failures, scope-disposal failures after successful handling, empty responses after local cancellation, slow async disposal counting toward the concurrency cap, and a graceful stop with admitted peers that keeps completed values and omits the pending item. The stop test records the stop before releasing admitted work so the pending item can never be claimed. --- .../Core/Runtime/EventProcessorTests.cs | 221 ++++++++++++++++++ 1 file changed, 221 insertions(+) diff --git a/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs b/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs index f801db38..7b6425a2 100644 --- a/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs +++ b/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs @@ -1281,6 +1281,217 @@ public async Task EachInvocationStartsWithFreshProcessingState() tokensCancelledAtEntry.Should().OnlyContain(cancelled => cancelled == false); } + [Theory] + [InlineData(0, false)] + [InlineData(-1, false)] + [InlineData(0, true)] + [InlineData(-3, true)] + public void InvalidOptionsRejectNonPositiveLimitsInBothModes(int limit, bool concurrencyEnabled) + { + // Arrange + var builder = LambdaApplication.CreateBuilder(); + builder.Services.Configure(options => + { + options.EnableConcurrency = concurrencyEnabled; + options.MaxConcurrentExecutions = limit; + }); + using var app = builder.Build(); + + // Act + var act = () => app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _) => Task.CompletedTask); + + // Assert + act.Should().Throw(); + } + + [Fact] + public async Task MapperCancellationExceptionFailsInvocationWithoutResponse() + { + // Arrange + var responseCalls = 0; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _) => Task.FromException(new InvalidOperationException("failed")), + onError: (_, _, _) => throw new OperationCanceledException(), + createResponse: (results, _) => + { + responseCalls++; + return new Response(results.ToList()); + }); + + var harness = CreateHarness(app, new Batch([new Item(1)])); + var handler = app.Build(); + + // Act + var act = () => handler(harness.Context); + + // Assert + await act.Should().ThrowAsync(); + responseCalls.Should().Be(0); + } + + [Fact] + public async Task ScopeDisposalFailureFailsInvocationAfterSuccessfulHandling() + { + // Arrange + var responseCalls = 0; + var builder = LambdaApplication.CreateBuilder(); + builder.Services.AddScoped(); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item, ThrowingDisposable _) => Task.FromResult(item.Id), + createResponse: (results, _) => + { + responseCalls++; + return new Response(results.ToList()); + }); + + var harness = CreateHarness(app, new Batch([new Item(1)])); + var handler = app.Build(); + + // Act + var act = () => handler(harness.Context); + + // Assert + await act.Should().ThrowAsync(); + responseCalls.Should().Be(0); + } + + [Fact] + public async Task BuildsEmptyResponseWhenLocalCancellationLeavesNoContributions() + { + // Arrange + Response? captured = null; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: async (Item _, IEventProcessingContext processing, CancellationToken token) => + { + processing.CancelProcessing(); + await Task.Delay(Timeout.InfiniteTimeSpan, token).ConfigureAwait(false); + }, + createResponse: (items, _) => + { + captured = new Response(items.Select(item => item.Id).ToList()); + return captured; + }); + + var harness = CreateHarness(app, new Batch([new Item(1)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + captured!.Ids.Should().BeEmpty(); + harness.ResponseFeature.Received(1).SetResponse(captured); + } + + [Fact] + public async Task SlowAsyncDisposalCountsTowardTheConcurrencyCap() + { + // Arrange + var disposalGate = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var started = 0; + var handlersExited = 0; + var builder = LambdaApplication.CreateBuilder(); + builder.Services.Configure(options => + options.MaxConcurrentExecutions = 2); + builder.Services.AddScoped(_ => new SlowDisposable(disposalGate.Task)); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _, SlowDisposable _) => + { + Interlocked.Increment(ref started); + Interlocked.Increment(ref handlersExited); + return Task.CompletedTask; + }); + + var harness = CreateHarness(app, new Batch([new Item(1), new Item(2), new Item(3)])); + var handler = app.Build(); + + // Act + var invocation = handler(harness.Context); + await WaitForAsync(() => Volatile.Read(ref handlersExited) == 2); + + // Both workers exited their handlers and are parked in scope disposal, so neither can claim + // the third item until disposal completes. + // Assert + Volatile.Read(ref started).Should().Be(2); + disposalGate.SetResult(); + await invocation; + Volatile.Read(ref started).Should().Be(3); + } + + [Fact] + public async Task StopWithPeersAdmittedKeepsCompletedValuesAndOmitsUnstarted() + { + // Arrange + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var allStarted = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var stopRequested = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var started = 0; + Response? captured = null; + var builder = LambdaApplication.CreateBuilder(); + builder.Services.Configure(options => + options.MaxConcurrentExecutions = 3); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: async (Item item, IEventProcessingContext processing) => + { + if (Interlocked.Increment(ref started) == 3) + allStarted.TrySetResult(); + + if (item.Id == 2) + { + await allStarted.Task.ConfigureAwait(false); + processing.StopProcessing(); + stopRequested.TrySetResult(); + return item.Id; + } + + await gate.Task.ConfigureAwait(false); + return item.Id; + }, + createResponse: (results, _) => + { + captured = new Response(results.ToList()); + return captured; + }); + + var harness = CreateHarness( + app, + new Batch([new Item(1), new Item(2), new Item(3), new Item(4)])); + var handler = app.Build(); + + // Act + var invocation = handler(harness.Context); + await allStarted.Task.WaitAsync( + TimeSpan.FromSeconds(10), + TestContext.Current.CancellationToken); + + // The stop is recorded before the admitted peers are released, so the pending fourth item + // can never be claimed. + await stopRequested.Task.WaitAsync( + TimeSpan.FromSeconds(10), + TestContext.Current.CancellationToken); + gate.SetResult(); + await invocation; + + // Assert + Volatile.Read(ref started).Should().Be(3); + captured!.Ids.Should().Equal(1, 2, 3); + } + private static async Task WaitForAsync(Func condition) { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); @@ -1394,6 +1605,16 @@ internal sealed record ResultDto(int ItemId, int ScopeId); internal sealed class UnregisteredValue; + internal sealed class ThrowingDisposable : IDisposable + { + public void Dispose() => throw new InvalidOperationException("scope disposal failed"); + } + + internal sealed class SlowDisposable(Task disposalGate) : IAsyncDisposable + { + public async ValueTask DisposeAsync() => await disposalGate.ConfigureAwait(false); + } + internal sealed class SingletonProbe; private sealed class ThrowingEnumerable : IEnumerable From 31c8d9ec0afc1433ee891efdc81aa4cdb9978104 Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Wed, 28 Oct 2026 19:14:36 -0400 Subject: [PATCH 12/21] test(event-processor): verify cancellation callbacks and fault precedence Cover the remaining cancellation and fatal-fault acceptance criteria: - throwing processing-token callbacks become recorded infrastructure failures on both the CancelProcessing and invocation-cancellation paths, never escaping the cancellation thread or being mapped; - cancellation callbacks are joined before the invocation completes, reentrant control calls from callbacks do not deadlock, invocation cancellation before the first admission skips split and handlers, and concurrent stop/cancel requests drain deterministically; - the execution error stays primary when scope disposal also fails, additional failures are logged without replacing it, a throwing logger cannot mask it, and dependency-resolution failures bypass onError. Scope-factory failure is not separately testable because MS DI always resolves IServiceScopeFactory to the container. --- .../Core/Runtime/EventProcessorTests.cs | 467 ++++++++++++++++++ 1 file changed, 467 insertions(+) diff --git a/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs b/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs index 7b6425a2..85ea5db3 100644 --- a/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs +++ b/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs @@ -1,6 +1,8 @@ using System.Collections; using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace MinimalLambda.UnitTests.Core.Runtime; @@ -1492,6 +1494,451 @@ await stopRequested.Task.WaitAsync( captured!.Ids.Should().Equal(1, 2, 3); } + [Fact] + public async Task ThrowingProcessingTokenCallbackFromCancelProcessingIsFatalAndNotMapped() + { + // Arrange + var errorCalls = 0; + var responseCalls = 0; + var handlerCompleted = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var builder = LambdaApplication.CreateBuilder(); + builder.Services.Configure(options => + options.MaxConcurrentExecutions = 1); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _, IEventProcessingContext processing) => + { + processing.CancellationToken.Register(() => + throw new InvalidOperationException("callback fault")); + processing.CancelProcessing(); + handlerCompleted.TrySetResult(); + return Task.CompletedTask; + }, + onError: (Item item, Exception _, IEventProcessingContext _) => + { + errorCalls++; + return item.Id; + }, + createResponse: (results, _) => + { + responseCalls++; + return new Response(results.ToList()); + }); + + var harness = CreateHarness(app, new Batch([new Item(1), new Item(2)])); + var handler = app.Build(); + + // Act + var act = () => handler(harness.Context); + + // Assert + // CancelAsync faults with the callback's AggregateException; the processor records it as + // the primary infrastructure failure instead of letting it escape the cancellation thread. + var thrown = await act.Should().ThrowAsync(); + Unwrap(thrown.Which) + .Should() + .BeOfType() + .Which + .Message + .Should() + .Be("callback fault"); + + // The cancelling handler must not observe the callback fault. + await handlerCompleted.Task.WaitAsync( + TimeSpan.FromSeconds(10), + TestContext.Current.CancellationToken); + errorCalls.Should().Be(0); + responseCalls.Should().Be(0); + } + + [Fact] + public async Task ThrowingProcessingTokenCallbackFromInvocationCancellationIsFatal() + { + // Arrange + var responseCalls = 0; + var callbackRan = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var registered = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: async (Item _, IEventProcessingContext processing) => + { + processing.CancellationToken.Register(() => + { + callbackRan.TrySetResult(); + throw new InvalidOperationException("callback fault"); + }); + registered.TrySetResult(); + await release.Task.ConfigureAwait(false); + }, + createResponse: (items, _) => + { + responseCalls++; + return new Response(items.Select(item => item.Id).ToList()); + }); + + var harness = CreateHarness(app, new Batch([new Item(1)])); + var handler = app.Build(); + + // Act + var invocation = handler(harness.Context); + await registered.Task.WaitAsync( + TimeSpan.FromSeconds(10), + TestContext.Current.CancellationToken); + harness.InvocationCancellation.Cancel(); + release.SetResult(); + var act = () => invocation; + + // Assert + // The callback fault is recorded as the primary fatal, but a latched invocation + // cancellation still wins at fan-in, so the cancellation result surfaces and the fault + // never escapes the cancellation thread. + await act.Should().ThrowAsync(); + await callbackRan.Task.WaitAsync( + TimeSpan.FromSeconds(10), + TestContext.Current.CancellationToken); + responseCalls.Should().Be(0); + } + + [Fact] + public async Task CancellationCallbacksAreAwaitedBeforeCompletion() + { + // Arrange + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var callbackEntered = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + Response? captured = null; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _, IEventProcessingContext processing) => + { + processing.CancellationToken.Register(() => + { + callbackEntered.TrySetResult(); + gate.Task.GetAwaiter().GetResult(); + }); + processing.CancelProcessing(); + return Task.CompletedTask; + }, + createResponse: (items, _) => + { + captured = new Response(items.Select(item => item.Id).ToList()); + return captured; + }); + + var harness = CreateHarness(app, new Batch([new Item(1)])); + var handler = app.Build(); + + // Act + var invocation = handler(harness.Context); + await callbackEntered.Task.WaitAsync( + TimeSpan.FromSeconds(10), + TestContext.Current.CancellationToken); + + // Assert + // The callback is still parked, so cancellation dispatch has not joined and the + // invocation cannot have completed. + invocation.IsCompleted.Should().BeFalse(); + gate.SetResult(); + await invocation; + captured!.Ids.Should().Equal(1); + } + + [Fact] + public async Task ReentrantControlCallsFromCancellationCallbacksDoNotDeadlock() + { + // Arrange + Response? captured = null; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _, IEventProcessingContext processing) => + { + processing.CancellationToken.Register(() => + { + processing.CancelProcessing(); + processing.StopProcessing(); + }); + processing.CancellationToken.Register(() => processing.StopProcessing()); + processing.CancelProcessing(); + return Task.CompletedTask; + }, + createResponse: (items, _) => + { + captured = new Response(items.Select(item => item.Id).ToList()); + return captured; + }); + + var harness = CreateHarness(app, new Batch([new Item(1)])); + var handler = app.Build(); + + // Act + await handler(harness.Context) + .WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + + // Assert + captured!.Ids.Should().Equal(1); + harness.InvocationCancellation.IsCancellationRequested.Should().BeFalse(); + } + + [Fact] + public async Task InvocationCancellationBeforeAdmissionThrowsAndSkipsSplitAndHandlers() + { + // Arrange + var splitCalls = 0; + var handleCalls = 0; + using var invocationCancellation = new CancellationTokenSource(); + invocationCancellation.Cancel(); + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => + { + splitCalls++; + return batch.Items; + }, + handle: (Item _) => + { + handleCalls++; + return Task.CompletedTask; + }); + + var harness = CreateHarness(app, new Batch([new Item(1)]), invocationCancellation); + var handler = app.Build(); + + // Act + var act = () => handler(harness.Context); + + // Assert + await act.Should().ThrowAsync(); + splitCalls.Should().Be(0); + handleCalls.Should().Be(0); + } + + [Fact] + public async Task ConcurrentControlRequestsFromManyHandlersDrainDeterministically() + { + // Arrange + ScopeProbe.Reset(); + var allAdmitted = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var controlsApplied = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var entered = 0; + var applied = 0; + var handled = new ConcurrentBag(); + Response? captured = null; + var builder = LambdaApplication.CreateBuilder(); + builder.Services.Configure(options => + options.MaxConcurrentExecutions = 3); + builder.Services.AddScoped(); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: async (Item item, IEventProcessingContext processing, ScopeProbe _) => + { + if (Interlocked.Increment(ref entered) == 3) + allAdmitted.TrySetResult(); + + await allAdmitted.Task.ConfigureAwait(false); + + if (item.Id % 2 == 0) + processing.CancelProcessing(); + else + processing.StopProcessing(); + + if (Interlocked.Increment(ref applied) == 3) + controlsApplied.TrySetResult(); + + // Hold every admitted handler until all control requests are recorded, so no + // worker can race a claim for the next item while a peer is still outside the + // stop boundary. + await controlsApplied.Task.ConfigureAwait(false); + handled.Add(item.Id); + }, + createResponse: (items, _) => + { + captured = new Response(items.Select(item => item.Id).ToList()); + return captured; + }); + + var harness = CreateHarness( + app, + new Batch( + [new Item(1), new Item(2), new Item(3), new Item(4), new Item(5), new Item(6),])); + var handler = app.Build(); + + // Act + await handler(harness.Context) + .WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + + // Assert + handled.Should().BeEquivalentTo(new[] { 1, 2, 3 }); + captured!.Ids.Should().Equal(1, 2, 3); + ScopeProbe.Created.Should().Be(3); + ScopeProbe.Disposed.Should().Be(3); + } + + [Fact] + public async Task ExecutionErrorIsPrimaryWhenScopeDisposalAlsoFails() + { + // Arrange + var responseCalls = 0; + var builder = LambdaApplication.CreateBuilder(); + builder.Services.AddScoped(); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _, FaultingDisposable _) => + Task.FromException(new InvalidOperationException("handler failed")), + createResponse: (items, _) => + { + responseCalls++; + return new Response(items.Select(item => item.Id).ToList()); + }); + + var harness = CreateHarness(app, new Batch([new Item(1)])); + var handler = app.Build(); + + // Act + var act = () => handler(harness.Context); + + // Assert + // The handler fault is recorded before the scope dispose fault, so it remains primary. + var thrown = await act.Should().ThrowAsync(); + Unwrap(thrown.Which) + .Should() + .BeOfType() + .Which + .Message + .Should() + .Be("handler failed"); + responseCalls.Should().Be(0); + } + + [Fact] + public async Task AdditionalFailuresAreLoggedWithoutReplacingThePrimary() + { + // Arrange + var logger = Substitute.For(); + var loggerFactory = Substitute.For(); + loggerFactory.CreateLogger("MinimalLambda.EventProcessor").Returns(logger); + + var builder = LambdaApplication.CreateBuilder(); + builder.Services.RemoveAll(); + builder.Services.AddSingleton(loggerFactory); + builder.Services.AddScoped(); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _, FaultingDisposable _) => + Task.FromException(new InvalidOperationException("handler failed"))); + + var harness = CreateHarness(app, new Batch([new Item(1)])); + var handler = app.Build(); + + // Act + var act = () => handler(harness.Context); + + // Assert + var thrown = await act.Should().ThrowAsync(); + Unwrap(thrown.Which) + .Should() + .BeOfType() + .Which + .Message + .Should() + .Be("handler failed"); + + var calls = logger.ReceivedCalls().ToList(); + calls.Should().ContainSingle(); + calls[0].GetArguments()[3] + .Should() + .BeOfType() + .Which + .Message + .Should() + .Be("scope disposal failed"); + } + + [Fact] + public async Task ThrowingLoggerDoesNotMaskThePrimaryFailure() + { + // Arrange + var loggerFactory = Substitute.For(); + loggerFactory.CreateLogger("MinimalLambda.EventProcessor").Returns(new ThrowingLogger()); + + var builder = LambdaApplication.CreateBuilder(); + builder.Services.RemoveAll(); + builder.Services.AddSingleton(loggerFactory); + builder.Services.AddScoped(); + await using var app = builder.Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _, FaultingDisposable _) => + Task.FromException(new InvalidOperationException("handler failed"))); + + var harness = CreateHarness(app, new Batch([new Item(1)])); + var handler = app.Build(); + + // Act + var act = () => handler(harness.Context); + + // Assert + var thrown = await act.Should().ThrowAsync(); + Unwrap(thrown.Which) + .Should() + .BeOfType() + .Which + .Message + .Should() + .Be("handler failed"); + } + + [Fact] + public async Task MissingDependencyResolutionFailureIsNotMappedByErrorMapper() + { + // Arrange + var errorCalls = 0; + var responseCalls = 0; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item, UnregisteredValue _) => Task.FromResult(item.Id), + onError: (Item item, Exception _, IEventProcessingContext _) => + { + errorCalls++; + return item.Id; + }, + createResponse: (results, _) => + { + responseCalls++; + return new Response(results.ToList()); + }); + + var harness = CreateHarness(app, new Batch([new Item(1)])); + var handler = app.Build(); + + // Act + var act = () => handler(harness.Context); + + // Assert + await act.Should().ThrowAsync(); + errorCalls.Should().Be(0); + responseCalls.Should().Be(0); + } + + private static Exception Unwrap(Exception exception) => + exception is AggregateException { InnerExceptions.Count: 1 } aggregate + ? aggregate.InnerExceptions[0] + : exception; + private static async Task WaitForAsync(Func condition) { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); @@ -1610,6 +2057,26 @@ internal sealed class ThrowingDisposable : IDisposable public void Dispose() => throw new InvalidOperationException("scope disposal failed"); } + internal sealed class FaultingDisposable : IDisposable + { + public void Dispose() => throw new NotSupportedException("scope disposal failed"); + } + + internal sealed class ThrowingLogger : Microsoft.Extensions.Logging.ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true; + + public void Log( + Microsoft.Extensions.Logging.LogLevel logLevel, + EventId eventId, + TState state, + Exception? exception, + Func formatter) => + throw new InvalidOperationException("logger failed"); + } + internal sealed class SlowDisposable(Task disposalGate) : IAsyncDisposable { public async ValueTask DisposeAsync() => await disposalGate.ConfigureAwait(false); From d6c021304dc57d374bca6de4cf0b41a4dbb9592c Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Wed, 28 Oct 2026 19:26:26 -0400 Subject: [PATCH 13/21] test(event-processor): verify source identity, FIFO stop, and stream checkpoints - The SQS fixture now carries distinct receipt handles and the response is asserted as exact JSON, proving only original message ids are reported. - The fixture gained a `stop` body path and the suite configures sequential processing, so a FIFO-style test proves later records are abandoned while the earlier identity is still reported. - Stream tests carry sequence numbers through R2 results in source order, surface only mapped failures, and document the lowest-failing-checkpoint and repeat-success semantics. - Cancellation requested during response construction still delivers exactly one response. - Give the integration fixture 30 seconds of function timeout, since the shared test server's 3-second AWS default is too tight when all test assemblies run in parallel; the deadline is not what these tests assert. --- docs/features/event-processor.md | 17 +- .../Program.cs | 7 + .../EventProcessorLambdaTests.cs | 90 ++++++++++- .../Core/Runtime/EventProcessorTests.cs | 151 ++++++++++++++++++ 4 files changed, 262 insertions(+), 3 deletions(-) diff --git a/docs/features/event-processor.md b/docs/features/event-processor.md index e3f2ae82..0880bf7f 100644 --- a/docs/features/event-processor.md +++ b/docs/features/event-processor.md @@ -112,7 +112,9 @@ builder.Services.Configure(options => runs, at application build time. `EnableConcurrency = false` forces sequential execution even when a larger cap is configured. -Use sequential processing when order matters, such as FIFO queues or stream shards. +Use sequential processing when order matters, such as FIFO queues or stream shards. For a FIFO +queue, combine `EnableConcurrency = false` with `StopProcessing()` to keep ordered processing: +records completed before the stop commit normally while later records are intentionally abandoned. ## Stopping and cancelling @@ -144,7 +146,10 @@ handlers that finish despite cancellation keep their results. Once handling closes, fan-in and response construction add no new framework cancellation checks. An invocation cancellation observed *during* handling still suppresses the response; one that -arrives later does not invalidate completed work. +arrives later does not invalidate completed work. Completion is not a completeness guarantee: an +absent item is one the processor never produced a result for, not a claim that it was processed. +Cancellation requested during response construction is observed past the handling boundary, so the +completed response is still delivered. ## Response input limitations @@ -193,6 +198,14 @@ lambda.MapEventHandler( The handler's declared `Task` return type fixes the shared result type. A `Task` handler is not a `Task` handler. +## Stream checkpoints (Kinesis and DynamoDB) + +Stream sources report a checkpoint, not individual record identities. Each result carries the +record's sequence number, and with `ReportBatchItemFailures` the checkpoint you return is the lowest +failing sequence number. The source resumes from that checkpoint, so already-processed successes +before it are re-delivered and the application must be idempotent. Kinesis and DynamoDB do not +support per-record acknowledgement. + ## Choosing the overload `Task` derives from `Task`, so several families can bind the same lambda. Disambiguate diff --git a/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/Program.cs b/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/Program.cs index d78dc67d..795d9011 100644 --- a/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/Program.cs +++ b/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/Program.cs @@ -18,11 +18,18 @@ handle: async Task ( SQSEvent.SQSMessage item, RecordProbe probe, + IEventProcessingContext processing, CancellationToken token) => { token.ThrowIfCancellationRequested(); probe.Record(item.MessageId); + if (item.Body is "stop") + { + processing.StopProcessing(); + return new Success(item.MessageId); + } + if (item.Body is "retry" or "fatal") throw new InvalidOperationException("retry requested"); diff --git a/tests/MinimalLambda.Testing.UnitTests/Tests/MinimalLambda.Testing.UnitTests/EventProcessorLambdaTests.cs b/tests/MinimalLambda.Testing.UnitTests/Tests/MinimalLambda.Testing.UnitTests/EventProcessorLambdaTests.cs index 57e722e7..54d332db 100644 --- a/tests/MinimalLambda.Testing.UnitTests/Tests/MinimalLambda.Testing.UnitTests/EventProcessorLambdaTests.cs +++ b/tests/MinimalLambda.Testing.UnitTests/Tests/MinimalLambda.Testing.UnitTests/EventProcessorLambdaTests.cs @@ -1,10 +1,17 @@ +using System.Text.Json; using Amazon.Lambda.SQSEvents; using Microsoft.Extensions.DependencyInjection; +using MinimalLambda.Options; namespace MinimalLambda.Testing.UnitTests; public class EventProcessorLambdaTests { + // The default server function timeout is AWS Lambda's 3 seconds, which is too tight when the + // whole solution runs all test assemblies in parallel. The processor behaviour under test is + // not the deadline, so give every invocation headroom inside the shared test server. + private static readonly TimeSpan TestFunctionTimeout = TimeSpan.FromSeconds(30); + [Fact] public async Task EventProcessorLambda_BuildsPartialBatchResponseInSourceOrder() { @@ -13,6 +20,7 @@ public async Task EventProcessorLambda_BuildsPartialBatchResponseInSourceOrder() LambdaTestFactory .Create() .WithCancellationToken(TestContext.Current.CancellationToken); + factory.ServerOptions.FunctionTimeout = TestFunctionTimeout; var request = CreateEvent(("id-1", "retry"), ("id-2", "ok"), ("id-3", "retry")); // Act @@ -40,6 +48,7 @@ public async Task EventProcessorLambda_ProcessesEveryRecordThroughItsOwnScope() LambdaTestFactory .Create() .WithCancellationToken(TestContext.Current.CancellationToken); + factory.ServerOptions.FunctionTimeout = TestFunctionTimeout; var request = CreateEvent(("id-1", "ok"), ("id-2", "ok"), ("id-3", "ok")); // Act @@ -64,6 +73,7 @@ public async Task EventProcessorLambda_EmptyEventStillBuildsEmptyResponse() LambdaTestFactory .Create() .WithCancellationToken(TestContext.Current.CancellationToken); + factory.ServerOptions.FunctionTimeout = TestFunctionTimeout; // Act var response = await factory.TestServer.InvokeAsync( @@ -84,6 +94,7 @@ public async Task EventProcessorLambda_ErrorMapperFailureFailsInvocationWithoutR LambdaTestFactory .Create() .WithCancellationToken(TestContext.Current.CancellationToken); + factory.ServerOptions.FunctionTimeout = TestFunctionTimeout; var request = CreateEvent(("id-1", "fatal")); // Act @@ -97,6 +108,81 @@ public async Task EventProcessorLambda_ErrorMapperFailureFailsInvocationWithoutR response.Response.Should().BeNull(); } + [Fact] + public async Task EventProcessorLambda_SerializesFailureResponseWithMessageIdsOnly() + { + // Arrange + await using var factory = + LambdaTestFactory + .Create() + .WithCancellationToken(TestContext.Current.CancellationToken); + factory.ServerOptions.FunctionTimeout = TestFunctionTimeout; + var request = CreateEvent(("id-1", "retry"), ("id-2", "ok"), ("id-3", "retry")); + + // Act + var response = await factory.TestServer.InvokeAsync( + request, + TestContext.Current.CancellationToken); + + // Assert + response.WasSuccess.Should().BeTrue(); + response.Response.Should().NotBeNull(); + + var json = JsonSerializer.Serialize( + response.Response!, + EventProcessorLambdaJsonContext.Default.SQSBatchResponse); + json + .Should() + .Be("""{"batchItemFailures":[{"itemIdentifier":"id-1"},{"itemIdentifier":"id-3"}]}"""); + json.Should().NotContain("receipt-"); + json.Should().NotContain("retry"); + } + + [Fact] + public async Task + EventProcessorLambda_SequentialStopAbandonsLaterRecordsAndKeepsEarlierIdentity() + { + // Arrange + await using var factory = LambdaTestFactory + .Create() + .WithCancellationToken(TestContext.Current.CancellationToken) + .WithHostBuilder(builder => builder.ConfigureServices((_, services) => + services.Configure(options => + options.EnableConcurrency = false))); + factory.ServerOptions.FunctionTimeout = TestFunctionTimeout; + var request = CreateEvent( + ("id-1", "retry"), + ("id-2", "stop"), + ("id-3", "retry"), + ("id-4", "retry")); + + // Act + var response = await factory.TestServer.InvokeAsync( + request, + TestContext.Current.CancellationToken); + + // Assert + response.WasSuccess.Should().BeTrue(); + response.Response.Should().NotBeNull(); + + // The stop record succeeds and commits; records after it are abandoned, so the response + // only + // reports the failure that completed before the stop and never claims the omitted + // identities. + response + .Response + .BatchItemFailures + .Select(failure => failure.ItemIdentifier) + .Should() + .Equal("id-1"); + factory + .Services + .GetRequiredService() + .MessageIds + .Should() + .Equal("id-1", "id-2"); + } + private static SQSEvent CreateEvent(params (string MessageId, string Body)[] records) => new() { @@ -104,7 +190,9 @@ private static SQSEvent CreateEvent(params (string MessageId, string Body)[] rec [ .. records.Select(record => new SQSEvent.SQSMessage { - MessageId = record.MessageId, Body = record.Body, + MessageId = record.MessageId, + ReceiptHandle = "receipt-" + record.MessageId, + Body = record.Body, }), ], }; diff --git a/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs b/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs index 85ea5db3..75c5f2dd 100644 --- a/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs +++ b/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs @@ -1934,6 +1934,126 @@ public async Task MissingDependencyResolutionFailureIsNotMappedByErrorMapper() responseCalls.Should().Be(0); } + [Fact] + public async Task StreamResultsCarrySequenceNumbersInSourceOrderAndOnlyFailuresSurface() + { + // Arrange + StreamResponse? captured = null; + IReadOnlyList? contributed = null; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => + batch.Items.Select(item => new StreamRecord($"seq-{item.Id}", item.Id == 2)), + handle: (StreamRecord record) => + record.ShouldFail + ? Task.FromException( + new InvalidOperationException("stream failed")) + : Task.FromResult(new StreamResult(record.SequenceNumber, Failed: false)), + onError: (record, _, _) => new StreamResult(record.SequenceNumber, Failed: true), + createResponse: (results, _) => + { + contributed = results.Select(result => result.SequenceNumber).ToList(); + captured = new StreamResponse( + results + .Where(result => result.Failed) + .Select(result => result.SequenceNumber) + .ToList()); + return captured; + }); + + var harness = CreateStreamHarness( + app, + new Batch([new Item(1), new Item(2), new Item(3)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + // One result per completed item, in source order, with the original sequence numbers, so + // successful records are still counted alongside the mapped failure. + contributed.Should().Equal("seq-1", "seq-2", "seq-3"); + captured!.SequenceNumbers.Should().Equal("seq-2"); + harness.ResponseFeature.Received(1).SetResponse(captured); + } + + [Fact] + public async Task StreamResponseUsesLowestFailingSequenceNumberAsCheckpoint() + { + // Arrange + StreamResponse? captured = null; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => + batch.Items.Select(item => new StreamRecord($"seq-{item.Id}", item.Id is 2 or 3)), + handle: (StreamRecord record) => + record.ShouldFail + ? Task.FromException( + new InvalidOperationException("stream failed")) + : Task.FromResult(new StreamResult(record.SequenceNumber, Failed: false)), + onError: (record, _, _) => new StreamResult(record.SequenceNumber, Failed: true), + createResponse: (results, _) => + { + captured = new StreamResponse( + results + .Where(result => result.Failed) + .Select(result => result.SequenceNumber) + .OrderBy(sequenceNumber => sequenceNumber, StringComparer.Ordinal) + .Take(1) + .ToList()); + return captured; + }); + + var harness = CreateStreamHarness( + app, + new Batch([new Item(1), new Item(2), new Item(3)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + // Kinesis and DynamoDB acknowledge from the supplied checkpoint forward, so reporting the + // lowest failing sequence number also re-delivers already-processed successes. Applications + // must stay idempotent. This is the documented semantic, not a processor guarantee. + captured!.SequenceNumbers.Should().Equal("seq-2"); + } + + [Fact] + public async Task InvocationCancellationDuringResponseConstructionStillDeliversResponseOnce() + { + // Arrange + var responseCalls = 0; + Response? captured = null; + var invocationCancellation = new CancellationTokenSource(); + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => Task.FromResult(item.Id), + createResponse: (results, _) => + { + responseCalls++; + invocationCancellation.Cancel(); + captured = new Response(results.ToList()); + return captured; + }); + + var harness = CreateHarness(app, new Batch([new Item(1)]), invocationCancellation); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + // Response construction sits past the handling boundary, so cancelling while the response + // is + // being built neither suppresses nor duplicates the delivered response and adds no failure. + invocationCancellation.IsCancellationRequested.Should().BeTrue(); + responseCalls.Should().Be(1); + captured!.Ids.Should().Equal(1); + harness.ResponseFeature.Received(1).SetResponse(captured); + } + private static Exception Unwrap(Exception exception) => exception is AggregateException { InnerExceptions.Count: 1 } aggregate ? aggregate.InnerExceptions[0] @@ -1966,11 +2086,36 @@ private static Harness CreateHarness( return new Harness(context, responseFeature, invocationCancellation); } + private static StreamHarness CreateStreamHarness( + LambdaApplication app, + Batch batch, + CancellationTokenSource? invocationCancellation = null) + { + var features = new DefaultFeatureCollection([]); + features.Set(new TestEventFeature(batch)); + var responseFeature = Substitute.For>(); + features.Set(responseFeature); + invocationCancellation ??= new CancellationTokenSource(); + + var context = Substitute.For(); + context.Features.Returns(features); + context.ServiceProvider.Returns(app.Services); + context.CancellationToken.Returns(invocationCancellation.Token); + context.Items.Returns(new Dictionary()); + + return new StreamHarness(context, responseFeature, invocationCancellation); + } + private sealed record Harness( ILambdaInvocationContext Context, IResponseFeature ResponseFeature, CancellationTokenSource InvocationCancellation); + private sealed record StreamHarness( + ILambdaInvocationContext Context, + IResponseFeature ResponseFeature, + CancellationTokenSource InvocationCancellation); + private sealed class TestEventFeature(T value) : IEventFeature { public T GetEvent(ILambdaInvocationContext context) => value; @@ -2050,6 +2195,12 @@ internal sealed record OptionalValue(int Value); internal sealed record ResultDto(int ItemId, int ScopeId); + internal sealed record StreamRecord(string SequenceNumber, bool ShouldFail); + + internal sealed record StreamResult(string SequenceNumber, bool Failed); + + public sealed record StreamResponse(IReadOnlyList SequenceNumbers); + internal sealed class UnregisteredValue; internal sealed class ThrowingDisposable : IDisposable From cdf6b7e423be991e07d3e873b7d316b5bd2572f1 Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Wed, 28 Oct 2026 21:28:19 -0400 Subject: [PATCH 14/21] fix(source-generators): correct event bindings --- docs/features/event-processor.md | 4 ++ .../references/event-processor.md | 4 ++ .../Models/Handlers/EventHandlerMethodInfo.cs | 18 +++++-- .../EventHandlerDiagnosticTests.cs | 52 +++++++++++++++++++ .../EventHandlerDiscoveryTests.cs | 47 +++++++++++++++++ 5 files changed, 121 insertions(+), 4 deletions(-) diff --git a/docs/features/event-processor.md b/docs/features/event-processor.md index 0880bf7f..692e188f 100644 --- a/docs/features/event-processor.md +++ b/docs/features/event-processor.md @@ -233,6 +233,10 @@ lambda.MapEventHandler(split, handle); lambda.MapEventHandler(split, EventHandlers.HandleAsync); ``` +A typed delegate can refer to a method whose first parameter accepts a base class or interface of +the item type. Keep delegate locals unchanged after initialization. Reassignment, including tuple +deconstruction, reports `LH0010` because the generator needs one method's binding attributes. + A result-returning handler bound to a no-result overload is a compile error (`LH0011`), not a silent discard. diff --git a/skills/minimal-lambda/references/event-processor.md b/skills/minimal-lambda/references/event-processor.md index 546eccdf..68eb9829 100644 --- a/skills/minimal-lambda/references/event-processor.md +++ b/skills/minimal-lambda/references/event-processor.md @@ -148,6 +148,10 @@ Requirements and limits: A method group alone cannot supply DI parameter types - it fails to compile (`CS1503` or `CS0411`). Do not add a `Delegate` catch-all. +Typed delegates may refer to methods accepting a base item class or interface. Keep delegate locals +unchanged after initialization. Reassignment, including tuple deconstruction, reports `LH0010` so +the generator cannot apply stale service-binding attributes. + ## Diagnostics | ID | Meaning | diff --git a/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs index 67775a67..0fdab75d 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs @@ -329,7 +329,9 @@ private static List CreateParameters( location, $"service attribute on item parameter '{parameter.Name}'")); if (itemType is not null - && !SymbolEqualityComparer.Default.Equals(itemType, parameter.Type)) + && !context.SemanticModel.Compilation + .ClassifyCommonConversion(itemType, parameter.Type) + .IsImplicit) parameterDiagnostics.Add( CreateDiagnostic( Diagnostics.UnsupportedEventHandlerSignature, @@ -657,10 +659,18 @@ private static bool HasAdditionalWrite( local)) continue; - var isWrite = identifier.Parent switch + SyntaxNode target = identifier; + while (true) + if (target.Parent is ArgumentSyntax { Parent: TupleExpressionSyntax tuple }) + target = tuple; + else if (target.Parent is ParenthesizedExpressionSyntax parenthesized) + target = parenthesized; + else + break; + + var isWrite = target.Parent switch { - AssignmentExpressionSyntax assignment when assignment.Left == identifier => - true, + AssignmentExpressionSyntax assignment when assignment.Left == target => true, PrefixUnaryExpressionSyntax prefix => prefix.IsKind( SyntaxKind.PreIncrementExpression) || prefix.IsKind(SyntaxKind.PreDecrementExpression), diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs index 71c403ee..77401f55 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs @@ -186,6 +186,58 @@ internal sealed class Item; diagnostic.Location.GetLineSpan().Path.Should().Be("InputFile.cs"); } + [Theory] + [InlineData("(handle, replacement) = (replacement, handle);")] + [InlineData("(unused, (handle, replacement)) = (0, (replacement, handle));")] + public void ReportsUnresolvedHandlerForDeconstructionReassignment(string assignment) + { + var (driver, compilation) = GeneratorTestHelpers.GenerateFromSource( + $$""" + using System; + using System.Threading.Tasks; + using Microsoft.Extensions.DependencyInjection; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + Func handle = First; + Func replacement = Second; + int unused; + {{assignment}} + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: handle); + + static Task First(Item item, [FromKeyedServices("blue")] Probe probe) => Task.CompletedTask; + static Task Second(Item item, Probe probe) => Task.CompletedTask; + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + internal sealed class Probe; + """); + + compilation + .GetDiagnostics(TestContext.Current.CancellationToken) + .Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) + .Should() + .BeEmpty(); + var result = driver.GetRunResult(); + var diagnostic = result.Diagnostics.Should().ContainSingle().Subject; + diagnostic.Id.Should().Be("LH0010"); + diagnostic.Location.GetLineSpan().Path.Should().Be("InputFile.cs"); + result + .GeneratedTrees + .Should() + .NotContain(tree => + tree.FilePath.EndsWith( + "MinimalLambda.EventHandlers.g.cs", + StringComparison.Ordinal)); + } + [Fact] public void ReportsDiscardedResultWhenMethodGroupReturnsTaskOfTForNoResultOverload() { diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs index 1c1232af..5448d3e8 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs @@ -87,6 +87,53 @@ internal sealed class Item; RunGenerator(source).Diagnostics.Should().BeEmpty(); } + [Theory] + [InlineData("object")] + [InlineData("BaseItem")] + [InlineData("IItem")] + public void RecognizesTypedDelegateWhoseMethodAcceptsABaseItemType(string parameterType) + { + var (driver, compilation) = GeneratorTestHelpers.GenerateFromSource( + $$""" + using System; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + Func handle = Handle; + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: handle); + + static Task Handle({{parameterType}} item) => Task.CompletedTask; + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal interface IItem; + internal class BaseItem; + internal sealed class Item : BaseItem, IItem; + """); + + var result = driver.GetRunResult(); + result.Diagnostics.Should().BeEmpty(); + result + .GeneratedTrees + .Should() + .ContainSingle(tree => + tree.FilePath.EndsWith( + "MinimalLambda.EventHandlers.g.cs", + StringComparison.Ordinal)); + CompileWithGenerated(compilation, result) + .GetDiagnostics(TestContext.Current.CancellationToken) + .Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) + .Should() + .BeEmpty(); + } + [Fact] public void RecognizesTypedDelegateLocalAndExplicitGenericArguments() { From 4fd45cfa7cab4f446b06d0242712c10de71a030d Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Thu, 29 Oct 2026 15:59:43 -0400 Subject: [PATCH 15/21] refactor: move event processing into library code --- docs/features/event-processor.md | 8 +- .../references/event-processor.md | 5 +- .../Models/Handlers/EventHandlerMethodInfo.cs | 2 +- .../Templates/MapEventHandler.scriban | 608 +-------- .../Runtime/EventHandlerRegistration.cs | 242 ++++ .../Runtime/EventProcessingState.cs | 307 +++++ .../Runtime/EventProcessorRuntime.cs | 148 +++ .../Runtime/EventProcessorWorkers.cs | 124 ++ .../EventHandlerDiagnosticTests.cs | 90 +- .../EventHandlerDiscoveryTests.cs | 12 +- .../EventHandlerEmitterTests.cs | 68 + ...nTokensAndDiscardedTaskResult.verified.txt | 22 + ...#MinimalLambda.EventHandlers.g.verified.cs | 590 +-------- ...#MinimalLambda.EventHandlers.g.verified.cs | 61 + ...#MinimalLambda.EventHandlers.g.verified.cs | 1133 +---------------- ...#MinimalLambda.EventHandlers.g.verified.cs | 86 ++ .../Runtime/EventHandlerRegistrationTests.cs | 367 ++++++ .../Runtime/EventProcessorRuntimeTests.cs | 205 +++ 18 files changed, 1803 insertions(+), 2275 deletions(-) create mode 100644 src/MinimalLambda/Runtime/EventHandlerRegistration.cs create mode 100644 src/MinimalLambda/Runtime/EventProcessingState.cs create mode 100644 src/MinimalLambda/Runtime/EventProcessorRuntime.cs create mode 100644 src/MinimalLambda/Runtime/EventProcessorWorkers.cs create mode 100644 tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerDiagnosticTests.SnapshotsDuplicateCancellationTokensAndDiscardedTaskResult.verified.txt create mode 100644 tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsNullableAndOptionalServiceResolution#MinimalLambda.EventHandlers.g.verified.cs create mode 100644 tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsTypedDelegateAndExplicitGenericMethodGroupBindings#MinimalLambda.EventHandlers.g.verified.cs create mode 100644 tests/MinimalLambda.UnitTests/Core/Runtime/EventHandlerRegistrationTests.cs create mode 100644 tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorRuntimeTests.cs diff --git a/docs/features/event-processor.md b/docs/features/event-processor.md index 692e188f..f8e6491d 100644 --- a/docs/features/event-processor.md +++ b/docs/features/event-processor.md @@ -12,8 +12,10 @@ lambda.MapEventHandler( importer.IndexAsync(item.S3.Object.Key, token)); ``` -Registration is source-generated, like `MapHandler`. The generator emits the whole processor, so -there is no runtime reflection and no public runtime bridge. +Handler argument binding is source-generated, like `MapHandler`. The generated adapter forwards +callbacks to library code, which registers a normal `LambdaInvocationDelegate` as the terminal +handler in the middleware pipeline. The library owns feature setup, item scheduling, scopes, +cancellation, error handling, and response construction, without runtime reflection. ## What it is not @@ -258,7 +260,7 @@ registration still throws the existing `InvalidOperationException`. ## Native AOT -The processor is generated into the consumer assembly with concrete closed signatures, so it is +Generated wrappers call the library runtime with concrete closed generic types, so processing is trim- and AOT-safe. Add serializer metadata for the event, response, envelope payloads, and any result type you serialize yourself: diff --git a/skills/minimal-lambda/references/event-processor.md b/skills/minimal-lambda/references/event-processor.md index 68eb9829..fb16d676 100644 --- a/skills/minimal-lambda/references/event-processor.md +++ b/skills/minimal-lambda/references/event-processor.md @@ -19,7 +19,10 @@ exist in the workspace. For repo contributions, read `repo-workflow.md` first. 3. collects contributions in source order; 4. builds one response through `createResponse`. -It is source-generated. Never add a runtime helper or reflection fallback to replace it. +Only typed handler bindings and forwarding adapters are source-generated. Library code registers +the normal terminal `LambdaInvocationDelegate` and owns feature setup, item scheduling, scopes, +cancellation, error handling, and response construction. Keep application code on `MapEventHandler`; +do not call the generated-code registration helper directly or add reflection fallbacks. `MapEventHandler` consumes the same single invocation handler slot as `MapHandler`. Multiple mapping sites are fine and all compile; reaching a second mapping for one handler throws at runtime. diff --git a/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs index 0fdab75d..eba74d29 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs @@ -205,7 +205,7 @@ or EventHandlerFamily.N3 var valueType = family switch { - EventHandlerFamily.N1 => "MinimalLambda.Generated.NoData", + EventHandlerFamily.N1 => "global::System.Object", EventHandlerFamily.N2 => itemType?.QualifiedNullableName ?? "global::System.Object", _ => collectedType ?? "global::System.Object", }; diff --git a/src/MinimalLambda.SourceGenerators/Templates/MapEventHandler.scriban b/src/MinimalLambda.SourceGenerators/Templates/MapEventHandler.scriban index 3308a8b8..2a6a91ac 100644 --- a/src/MinimalLambda.SourceGenerators/Templates/MapEventHandler.scriban +++ b/src/MinimalLambda.SourceGenerators/Templates/MapEventHandler.scriban @@ -24,118 +24,33 @@ namespace System.Runtime.CompilerServices namespace MinimalLambda.Generated { using System; - using System.Collections.Generic; - using System.Collections.ObjectModel; - using System.Runtime.ExceptionServices; using System.Runtime.CompilerServices; - using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Logging; - using Microsoft.Extensions.Options; using MinimalLambda.Builder; - using MinimalLambda.Options; + using MinimalLambda.Runtime; {{ generated_code_attribute.value }} file static class GeneratedEventProcessorExtensions { - private const string EventFeatureProviderKey = "__EventFeatureProvider"; - private const string ResponseFeatureProviderKey = "__ResponseFeatureProvider"; - {{~ for call in event_handler_calls ~}} {{ call.interceptable_location_attribute }} internal static ILambdaInvocationBuilder MapEventHandlerInterceptor{{ for.index }}( this ILambdaInvocationBuilder application{{ for p in call.callback_parameters }}, {{ p.type }} {{ p.name }}{{ end }}) { - ArgumentNullException.ThrowIfNull(application); - {{~ for p in call.callback_parameters ~}} - ArgumentNullException.ThrowIfNull({{ p.name }}); - {{~ end ~}} - - var options = application.Services.GetRequiredService>().Value; - var effectiveConcurrency = options.EnableConcurrency - ? options.MaxConcurrentExecutions - : 1; - var scopeFactory = application.Services.GetRequiredService(); - var logger = application - .Services.GetService() - ?.CreateLogger("MinimalLambda.EventProcessor"); - - application.Handle(InvocationDelegate); - - if (!application.Properties.ContainsKey(EventFeatureProviderKey)) - application.Properties[EventFeatureProviderKey] = application - .Services.GetRequiredService() - .Create<{{ call.event_type }}>(); - {{~ if call.has_response ~}} - - if (!application.Properties.ContainsKey(ResponseFeatureProviderKey)) - application.Properties[ResponseFeatureProviderKey] = application - .Services.GetRequiredService() - .Create<{{ call.response_type }}>(); - {{~ end ~}} - - return application; - - async Task InvocationDelegate(ILambdaInvocationContext context) - { - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - _ = context.ServiceProvider; - - var lambdaEvent = context.GetRequiredEvent<{{ call.event_type }}>(); - var splitItems = split(lambdaEvent, context); - if (splitItems is null) - throw new InvalidOperationException("The event splitter 'split' returned null."); - - var items = new List<{{ call.item_type }}>(); - using (var enumerator = splitItems.GetEnumerator()) - { - while (enumerator.MoveNext()) - { - context.CancellationToken.ThrowIfCancellationRequested(); - items.Add(enumerator.Current); - } - } - - var itemArray = items.ToArray(); + return EventHandlerRegistration.Register<{{ call.event_type }}, {{ call.item_type }}{{ if call.has_response }}{{ if call.has_on_error || call.handle_returns_result }}, {{ call.value_type }}{{ end }}, {{ call.response_type }}{{ end }}>( + application, + split, + handle, + Bind{{ if call.has_on_error }}, + onError{{ end }}{{ if call.has_response }}, + createResponse{{ end }}); - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - using var state = new EventProcessingState( - context, - logger, - itemArray.Length); - var outcomes = await EventProcessorRuntime - .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, {{ if call.collects_values }}true{{ else }}false{{ end }}) - .ConfigureAwait(false); - {{~ if call.collects_values ~}} - - var contributions = new List<{{ call.value_type }}>(outcomes!.Length); - foreach (var outcome in outcomes) - if (outcome.HasValue) - contributions.Add(outcome.Value!); - - var response = createResponse( - new ReadOnlyCollection<{{ call.value_type }}>(contributions), - context); - {{~ if call.has_response ~}} - - if (context.Features.Get() is not IResponseFeature<{{ call.response_type }}> responseFeature) - throw new InvalidOperationException( - "Response feature for type '{{ call.response_type }}' is not available in the collection."); - responseFeature.SetResponse(response); - {{~ end ~}} - {{~ end ~}} - } - - async Task> Adapt( + Func<{{ if call.handle_returns_result }}Task<{{ call.collected_type }}>{{ else }}Task{{ end }}> Bind( {{ call.item_type }} item, IServiceProvider serviceProvider, - EventProcessingState processingContext) + IEventProcessingContext processingContext) { {{~ if call.has_any_from_keyed_services ~}} if (serviceProvider.GetService() is not IServiceProviderIsKeyedService) @@ -145,510 +60,9 @@ namespace MinimalLambda.Generated {{~ for parameter in call.handler_parameters ~}} var arg{{ parameter.ordinal }} = {{ parameter.assignment }}; {{~ end ~}} - - var invocationToken = processingContext.Invocation.CancellationToken; - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - if (processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome<{{ call.value_type }}>.Cancelled; - - {{ if call.handle_returns_result }}Task<{{ call.collected_type }}>?{{ else }}Task?{{ end }} handlerTask = null; - {{ if call.handle_returns_result }}{{ call.collected_type }} handlerResult = default!;{{ end }} - Exception? synchronousFault = null; - try - { - handlerTask = handle({{ call.handler_arguments }}); - } - catch (Exception ex) - { - synchronousFault = ex; - } - - if (synchronousFault is null && handlerTask is null) - throw new InvalidOperationException("The event handler 'handle' returned a null task."); - - try - { - if (synchronousFault is not null) - ExceptionDispatchInfo.Capture(synchronousFault).Throw(); - - {{ if call.handle_returns_result }}handlerResult = {{ end }}await handlerTask!.ConfigureAwait(false); - } - catch (Exception ex) - { - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - ex, - invocationToken); - - if (ex is OperationCanceledException - && processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome<{{ call.value_type }}>.Cancelled; - {{~ if call.has_on_error ~}} - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - - var mapped = onError(item, ex, processingContext); - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while mapping an item error.", - invocationToken); - - return ItemOutcome<{{ call.value_type }}>.FromMappedValue(mapped); - {{~ else ~}} - - throw; - {{~ end ~}} - } - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - invocationToken); - {{~ if call.collects_source_items ~}} - - return ItemOutcome<{{ call.value_type }}>.FromValue(item); - {{~ else if call.handle_returns_result ~}} - - return ItemOutcome<{{ call.value_type }}>.FromValue(handlerResult); - {{~ else ~}} - - return ItemOutcome<{{ call.value_type }}>.NoValue; - {{~ end ~}} + return () => handle({{ call.handler_arguments }}); } } {{~ end ~}} } - - file readonly struct NoData; - - file enum ItemExecutionState - { - Unstarted, - Succeeded, - MappedError, - Cancelled, - } - - file readonly struct ItemOutcome - { - private ItemOutcome(ItemExecutionState state, bool hasValue, TValue? value) - { - State = state; - HasValue = hasValue; - Value = value; - } - - internal ItemExecutionState State { get; } - - internal bool HasValue { get; } - - internal TValue? Value { get; } - - internal static ItemOutcome FromValue(TValue? value) => - new(ItemExecutionState.Succeeded, true, value); - - internal static ItemOutcome FromMappedValue(TValue? value) => - new(ItemExecutionState.MappedError, true, value); - - internal static ItemOutcome NoValue => - new(ItemExecutionState.Succeeded, false, default); - - internal static ItemOutcome Cancelled => - new(ItemExecutionState.Cancelled, false, default); - } - - file sealed class EventProcessingState : IEventProcessingContext, IDisposable - { - private readonly object _gate = new(); - private readonly ILambdaInvocationContext _invocation; - private readonly ILogger? _logger; - private readonly int _itemCount; - private readonly CancellationTokenSource _processingSource = new(); - private readonly CancellationTokenRegistration _invocationRegistration; - - private int _nextIndex; - private int _admitted; - private bool _stopRequested; - private bool _cancelRequested; - private bool _handlingClosed; - private bool _completed; - private bool _invocationCancelled; - private bool _disposed; - private ExceptionDispatchInfo? _firstFatal; - private List? _additionalFatal; - private TaskCompletionSource? _dispatchCompletion; - - internal EventProcessingState( - ILambdaInvocationContext invocation, - ILogger? logger, - int itemCount) - { - _invocation = invocation; - _logger = logger; - _itemCount = itemCount; - _invocationRegistration = invocation.CancellationToken.Register( - static state => ((EventProcessingState)state!).OnInvocationTokenCancelled(), - this); - } - - public ILambdaInvocationContext Invocation => _invocation; - - public CancellationToken CancellationToken => _processingSource.Token; - - public void StopProcessing() - { - lock (_gate) - { - if (_completed || _handlingClosed) - return; - - _stopRequested = true; - TryCloseHandlingCore(); - } - } - - public void CancelProcessing() => RequestProcessingCancellation(false); - - internal bool TryClaim(out int index) - { - TaskCompletionSource? dispatch = null; - var claimed = false; - index = -1; - - lock (_gate) - { - if (_completed) - return false; - - ObserveInvocationCancellationCore(ref dispatch); - - if (_handlingClosed - || _stopRequested - || _firstFatal is not null - || _nextIndex >= _itemCount) - { - TryCloseHandlingCore(); - } - else - { - index = _nextIndex++; - _admitted++; - claimed = true; - } - } - - if (dispatch is not null) - StartDispatch(dispatch); - - return claimed; - } - - internal bool IsInvocationCancellationLatched - { - get - { - lock (_gate) - return _invocationCancelled; - } - } - - internal void CompleteAdmission() - { - lock (_gate) - { - if (_admitted > 0) - _admitted--; - - TryCloseHandlingCore(); - } - } - - internal bool TryLatchInvocationCancellation() - { - if (!_invocation.CancellationToken.IsCancellationRequested) - return false; - - RequestProcessingCancellation(true); - - lock (_gate) - return _invocationCancelled; - } - - internal void RecordFatal(Exception exception) - { - lock (_gate) - { - if (_completed) - return; - - _stopRequested = true; - var fatal = ExceptionDispatchInfo.Capture(exception); - if (_firstFatal is null) - _firstFatal = fatal; - else - (_additionalFatal ??= []).Add(exception); - - TryCloseHandlingCore(); - } - } - - internal void TryCloseHandling() - { - lock (_gate) - TryCloseHandlingCore(); - } - - internal async Task JoinAsync() - { - Task? dispatch; - lock (_gate) - { - TryCloseHandlingCore(); - dispatch = _dispatchCompletion?.Task; - } - - if (dispatch is not null) - await dispatch.ConfigureAwait(false); - - Completion completion; - lock (_gate) - { - TryCloseHandlingCore(); - _completed = true; - completion = new Completion( - _invocationCancelled, - _firstFatal, - _additionalFatal); - } - - completion.LogAdditional(_logger); - - if (completion.InvocationCancelled) - throw new OperationCanceledException( - "The Lambda invocation was cancelled during item processing.", - _invocation.CancellationToken); - - if (completion.FirstFatal is not null) - { - completion.FirstFatal.Throw(); - throw new InvalidOperationException("Unreachable"); - } - } - - public void Dispose() - { - if (_disposed) - return; - - _disposed = true; - _invocationRegistration.Dispose(); - _processingSource.Dispose(); - } - - private void OnInvocationTokenCancelled() => RequestProcessingCancellation(true); - - private void RequestProcessingCancellation(bool invocationCancelled) - { - TaskCompletionSource? dispatch = null; - lock (_gate) - { - if (_completed || _handlingClosed) - return; - - if (invocationCancelled) - _invocationCancelled = true; - - _stopRequested = true; - - if (!_cancelRequested) - { - _cancelRequested = true; - _dispatchCompletion = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously); - dispatch = _dispatchCompletion; - } - - TryCloseHandlingCore(); - } - - if (dispatch is not null) - StartDispatch(dispatch); - } - - private void ObserveInvocationCancellationCore(ref TaskCompletionSource? dispatch) - { - if (_handlingClosed || !_invocation.CancellationToken.IsCancellationRequested) - return; - - _invocationCancelled = true; - _stopRequested = true; - - if (_cancelRequested) - return; - - _cancelRequested = true; - _dispatchCompletion = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously); - dispatch = _dispatchCompletion; - } - - private void TryCloseHandlingCore() - { - if (_handlingClosed) - return; - - if (_admitted > 0) - return; - - if (_nextIndex < _itemCount - && !_stopRequested - && _firstFatal is null - && !_invocation.CancellationToken.IsCancellationRequested) - return; - - if (_invocation.CancellationToken.IsCancellationRequested) - { - _invocationCancelled = true; - _stopRequested = true; - } - - _handlingClosed = true; - } - - private void StartDispatch(TaskCompletionSource completion) => - _ = DispatchCancellationAsync(completion); - - private async Task DispatchCancellationAsync(TaskCompletionSource completion) - { - try - { - await _processingSource.CancelAsync().ConfigureAwait(false); - } - catch (Exception ex) - { - RecordFatal(ex); - } - finally - { - completion.TrySetResult(); - } - } - - private readonly struct Completion( - bool invocationCancelled, - ExceptionDispatchInfo? firstFatal, - List? additionalFatal) - { - internal bool InvocationCancelled { get; } = invocationCancelled; - - internal ExceptionDispatchInfo? FirstFatal { get; } = firstFatal; - - internal void LogAdditional(ILogger? logger) - { - if (logger is null || additionalFatal is null) - return; - - foreach (var exception in additionalFatal) - try - { - logger.LogError( - exception, - "Event processor observed an additional failure while draining item work."); - } - catch - { - // Logging must not replace the selected invocation error. - } - } - } - } - - file static class EventProcessorRuntime - { - internal static async Task[]?> RunAsync( - TItem[] items, - int effectiveConcurrency, - IServiceScopeFactory scopeFactory, - EventProcessingState state, - Func>> adapter, - bool collectValues) - { - if (items.Length == 0) - state.TryCloseHandling(); - - var outcomes = collectValues ? new ItemOutcome[items.Length] : null; - var workerCount = Math.Min(items.Length, Math.Max(1, effectiveConcurrency)); - var workers = new Task[workerCount]; - - for (var index = 0; index < workerCount; index++) - workers[index] = RunWorkerAsync(); - - await Task.WhenAll(workers).ConfigureAwait(false); - await state.JoinAsync().ConfigureAwait(false); - - return outcomes; - - async Task RunWorkerAsync() - { - while (state.TryClaim(out var index)) - { - if (state.IsInvocationCancellationLatched) - { - state.CompleteAdmission(); - continue; - } - - AsyncServiceScope scope; - try - { - scope = scopeFactory.CreateAsyncScope(); - } - catch (Exception ex) - { - state.RecordFatal(ex); - state.CompleteAdmission(); - continue; - } - - ItemOutcome outcome = default; - var hasOutcome = false; - - try - { - try - { - outcome = await adapter(items[index], scope.ServiceProvider, state) - .ConfigureAwait(false); - hasOutcome = true; - } - catch (Exception ex) - { - if (!state.TryLatchInvocationCancellation()) - state.RecordFatal(ex); - } - } - finally - { - state.CompleteAdmission(); - } - - try - { - await scope.DisposeAsync().ConfigureAwait(false); - } - catch (Exception ex) - { - state.RecordFatal(ex); - } - - if (collectValues && hasOutcome && outcome.HasValue) - outcomes![index] = outcome; - } - } - } - } } diff --git a/src/MinimalLambda/Runtime/EventHandlerRegistration.cs b/src/MinimalLambda/Runtime/EventHandlerRegistration.cs new file mode 100644 index 00000000..e5c75e3e --- /dev/null +++ b/src/MinimalLambda/Runtime/EventHandlerRegistration.cs @@ -0,0 +1,242 @@ +using System.ComponentModel; +using Microsoft.Extensions.DependencyInjection; + +namespace MinimalLambda.Runtime; + +/// Registers generated event-handler adapters with a Lambda invocation builder. +[EditorBrowsable(EditorBrowsableState.Never)] +public static class EventHandlerRegistration +{ + /// Registers an event handler that produces no response contributions. + /// The deserialized Lambda event type. + /// The item type produced by . + /// The invocation builder. + /// Splits the event into source items. + /// The original handler delegate, used to validate the registration. + /// Resolves item-handler arguments and returns the handler. + /// The same invocation builder. + public static ILambdaInvocationBuilder Register( + ILambdaInvocationBuilder application, + Func> split, + Delegate handle, + Func> bind) + { + ArgumentNullException.ThrowIfNull(application); + ArgumentNullException.ThrowIfNull(split); + ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(bind); + + var runtime = new EventProcessorRuntime(application.Services); + application.Handle(InvokeAsync); + EnsureEventFeatureProvider(application); + return application; + + Task InvokeAsync(ILambdaInvocationContext context) => + runtime.RunAsync( + context, + split, + bind, + selectSuccess: null, + onError: null, + complete: null); + } + + /// Registers an event handler that contributes each successful source item. + /// The deserialized Lambda event type. + /// The item type produced by . + /// The Lambda response type. + /// The invocation builder. + /// Splits the event into source items. + /// The original handler delegate, used to validate the registration. + /// Resolves item-handler arguments and returns the handler. + /// Builds a response from successful source items. + /// The same invocation builder. + public static ILambdaInvocationBuilder Register( + ILambdaInvocationBuilder application, + Func> split, + Delegate handle, + Func> bind, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + ArgumentNullException.ThrowIfNull(application); + ArgumentNullException.ThrowIfNull(split); + ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(bind); + ArgumentNullException.ThrowIfNull(createResponse); + + var runtime = new EventProcessorRuntime(application.Services); + application.Handle(InvokeAsync); + EnsureEventFeatureProvider(application); + EnsureResponseFeatureProvider(application); + return application; + + Task InvokeAsync(ILambdaInvocationContext context) => + runtime.RunAsync( + context, + split, + bind, + static (item, _) => item, + onError: null, + values => SetResponse(context, values, createResponse)); + } + + /// Registers an event handler that contributes mapped failures. + /// The deserialized Lambda event type. + /// The item type produced by . + /// The mapped failure type. + /// The Lambda response type. + /// The invocation builder. + /// Splits the event into source items. + /// The original handler delegate, used to validate the registration. + /// Resolves item-handler arguments and returns the handler. + /// Maps an item-handler failure to a response contribution. + /// Builds a response from mapped failures. + /// The same invocation builder. + public static ILambdaInvocationBuilder Register( + ILambdaInvocationBuilder application, + Func> split, + Delegate handle, + Func> bind, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + ArgumentNullException.ThrowIfNull(application); + ArgumentNullException.ThrowIfNull(split); + ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(bind); + ArgumentNullException.ThrowIfNull(onError); + ArgumentNullException.ThrowIfNull(createResponse); + + var runtime = new EventProcessorRuntime(application.Services); + application.Handle(InvokeAsync); + EnsureEventFeatureProvider(application); + EnsureResponseFeatureProvider(application); + return application; + + Task InvokeAsync(ILambdaInvocationContext context) => + runtime.RunAsync( + context, + split, + bind, + selectSuccess: null, + onError: onError, + complete: values => SetResponse(context, values, createResponse)); + } + + /// Registers an event handler that contributes successful results. + /// The deserialized Lambda event type. + /// The item type produced by . + /// The handler result type. + /// The Lambda response type. + /// The invocation builder. + /// Splits the event into source items. + /// The original handler delegate, used to validate the registration. + /// Resolves item-handler arguments and returns the handler. + /// Builds a response from successful handler results. + /// The same invocation builder. + public static ILambdaInvocationBuilder Register( + ILambdaInvocationBuilder application, + Func> split, + Delegate handle, + Func>> bind, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + ArgumentNullException.ThrowIfNull(application); + ArgumentNullException.ThrowIfNull(split); + ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(bind); + ArgumentNullException.ThrowIfNull(createResponse); + + var runtime = new EventProcessorRuntime(application.Services); + application.Handle(InvokeAsync); + EnsureEventFeatureProvider(application); + EnsureResponseFeatureProvider(application); + return application; + + Task InvokeAsync(ILambdaInvocationContext context) => + runtime.RunAsync( + context, + split, + bind, + static (_, task) => ((Task)task).GetAwaiter().GetResult(), + onError: null, + values => SetResponse(context, values, createResponse)); + } + + /// Registers an event handler that contributes successful and mapped results. + /// The deserialized Lambda event type. + /// The item type produced by . + /// The handler result and mapped failure type. + /// The Lambda response type. + /// The invocation builder. + /// Splits the event into source items. + /// The original handler delegate, used to validate the registration. + /// Resolves item-handler arguments and returns the handler. + /// Maps an item-handler failure to a response contribution. + /// Builds a response from successful and mapped results. + /// The same invocation builder. + public static ILambdaInvocationBuilder Register( + ILambdaInvocationBuilder application, + Func> split, + Delegate handle, + Func>> bind, + Func onError, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + ArgumentNullException.ThrowIfNull(application); + ArgumentNullException.ThrowIfNull(split); + ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(bind); + ArgumentNullException.ThrowIfNull(onError); + ArgumentNullException.ThrowIfNull(createResponse); + + var runtime = new EventProcessorRuntime(application.Services); + application.Handle(InvokeAsync); + EnsureEventFeatureProvider(application); + EnsureResponseFeatureProvider(application); + return application; + + Task InvokeAsync(ILambdaInvocationContext context) => + runtime.RunAsync( + context, + split, + bind, + static (_, task) => ((Task)task).GetAwaiter().GetResult(), + onError: onError, + complete: values => SetResponse(context, values, createResponse)); + } + + private static void EnsureEventFeatureProvider(ILambdaInvocationBuilder application) + { + if (!application.Properties.ContainsKey(LambdaInvocationBuilder.EventFeatureProviderKey)) + application.Properties[LambdaInvocationBuilder.EventFeatureProviderKey] = + application + .Services + .GetRequiredService() + .Create(); + } + + private static void EnsureResponseFeatureProvider( + ILambdaInvocationBuilder application) + { + if (!application.Properties.ContainsKey(LambdaInvocationBuilder.ResponseFeatureProviderKey)) + application.Properties[LambdaInvocationBuilder.ResponseFeatureProviderKey] = + application + .Services + .GetRequiredService() + .Create(); + } + + private static void SetResponse( + ILambdaInvocationContext context, + IEnumerable values, + Func, ILambdaInvocationContext, TResponse> createResponse) + { + var response = createResponse(values, context); + if (context.Features.Get() is not IResponseFeature + responseFeature) + throw new InvalidOperationException( + $"Response feature for type '{typeof(TResponse)}' is not available in the collection."); + responseFeature.SetResponse(response); + } +} diff --git a/src/MinimalLambda/Runtime/EventProcessingState.cs b/src/MinimalLambda/Runtime/EventProcessingState.cs new file mode 100644 index 00000000..4bd6c144 --- /dev/null +++ b/src/MinimalLambda/Runtime/EventProcessingState.cs @@ -0,0 +1,307 @@ +using System.Runtime.ExceptionServices; +using Microsoft.Extensions.Logging; + +namespace MinimalLambda.Runtime; + +internal sealed class EventProcessingState : IEventProcessingContext, IDisposable +{ + private readonly object _gate = new(); + private readonly ILambdaInvocationContext _invocation; + private readonly ILogger? _logger; + private readonly int _itemCount; + private readonly CancellationTokenSource _processingSource = new(); + private readonly CancellationTokenRegistration _invocationRegistration; + + private int _nextIndex; + private int _admitted; + private bool _stopRequested; + private bool _cancelRequested; + private bool _handlingClosed; + private bool _completed; + private bool _invocationCancelled; + private bool _disposed; + private ExceptionDispatchInfo? _firstFatal; + private List? _additionalFatal; + private TaskCompletionSource? _dispatchCompletion; + + internal EventProcessingState( + ILambdaInvocationContext invocation, + ILogger? logger, + int itemCount) + { + _invocation = invocation; + _logger = logger; + _itemCount = itemCount; + _invocationRegistration = invocation.CancellationToken.Register( + static state => ((EventProcessingState)state!).OnInvocationTokenCancelled(), + this); + } + + public ILambdaInvocationContext Invocation => _invocation; + + public CancellationToken CancellationToken => _processingSource.Token; + + public void StopProcessing() + { + lock (_gate) + { + if (_completed || _handlingClosed) + return; + + _stopRequested = true; + TryCloseHandlingCore(); + } + } + + public void CancelProcessing() => RequestProcessingCancellation(false); + + internal bool TryClaim(out int index) + { + TaskCompletionSource? dispatch = null; + var claimed = false; + index = -1; + + lock (_gate) + { + if (_completed) + return false; + + ObserveInvocationCancellationCore(ref dispatch); + + if (_handlingClosed + || _stopRequested + || _firstFatal is not null + || _nextIndex >= _itemCount) + { + TryCloseHandlingCore(); + } + else + { + index = _nextIndex++; + _admitted++; + claimed = true; + } + } + + if (dispatch is not null) + StartDispatch(dispatch); + + return claimed; + } + + internal bool IsInvocationCancellationLatched + { + get + { + lock (_gate) + return _invocationCancelled; + } + } + + internal void CompleteAdmission() + { + lock (_gate) + { + if (_admitted > 0) + _admitted--; + + TryCloseHandlingCore(); + } + } + + internal bool TryLatchInvocationCancellation() + { + if (!_invocation.CancellationToken.IsCancellationRequested) + return false; + + RequestProcessingCancellation(true); + + lock (_gate) + return _invocationCancelled; + } + + internal void RecordFatal(Exception exception) + { + lock (_gate) + { + if (_completed) + return; + + _stopRequested = true; + var fatal = ExceptionDispatchInfo.Capture(exception); + if (_firstFatal is null) + _firstFatal = fatal; + else + (_additionalFatal ??= []).Add(exception); + + TryCloseHandlingCore(); + } + } + + internal void TryCloseHandling() + { + lock (_gate) + TryCloseHandlingCore(); + } + + internal async Task JoinAsync() + { + Task? dispatch; + lock (_gate) + { + TryCloseHandlingCore(); + dispatch = _dispatchCompletion?.Task; + } + + if (dispatch is not null) + await dispatch.ConfigureAwait(false); + + Completion completion; + lock (_gate) + { + TryCloseHandlingCore(); + _completed = true; + completion = new Completion(_invocationCancelled, _firstFatal, _additionalFatal); + } + + completion.LogAdditional(_logger); + + if (completion.InvocationCancelled) + throw new OperationCanceledException( + "The Lambda invocation was cancelled during item processing.", + _invocation.CancellationToken); + + if (completion.FirstFatal is not null) + { + completion.FirstFatal.Throw(); + throw new InvalidOperationException("Unreachable"); + } + } + + public void Dispose() + { + if (_disposed) + return; + + _disposed = true; + _invocationRegistration.Dispose(); + _processingSource.Dispose(); + } + + private void OnInvocationTokenCancelled() => RequestProcessingCancellation(true); + + private void RequestProcessingCancellation(bool invocationCancelled) + { + TaskCompletionSource? dispatch = null; + lock (_gate) + { + if (_completed || _handlingClosed) + return; + + if (invocationCancelled) + _invocationCancelled = true; + + _stopRequested = true; + + if (!_cancelRequested) + { + _cancelRequested = true; + _dispatchCompletion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + dispatch = _dispatchCompletion; + } + + TryCloseHandlingCore(); + } + + if (dispatch is not null) + StartDispatch(dispatch); + } + + private void ObserveInvocationCancellationCore(ref TaskCompletionSource? dispatch) + { + if (_handlingClosed || !_invocation.CancellationToken.IsCancellationRequested) + return; + + _invocationCancelled = true; + _stopRequested = true; + + if (_cancelRequested) + return; + + _cancelRequested = true; + _dispatchCompletion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + dispatch = _dispatchCompletion; + } + + private void TryCloseHandlingCore() + { + if (_handlingClosed) + return; + + if (_admitted > 0) + return; + + if (_nextIndex < _itemCount + && !_stopRequested + && _firstFatal is null + && !_invocation.CancellationToken.IsCancellationRequested) + return; + + if (_invocation.CancellationToken.IsCancellationRequested) + { + _invocationCancelled = true; + _stopRequested = true; + } + + _handlingClosed = true; + } + + private void StartDispatch(TaskCompletionSource completion) => + _ = DispatchCancellationAsync(completion); + + private async Task DispatchCancellationAsync(TaskCompletionSource completion) + { + try + { + await _processingSource.CancelAsync().ConfigureAwait(false); + } + catch (Exception ex) + { + RecordFatal(ex); + } + finally + { + completion.TrySetResult(); + } + } + + private readonly struct Completion( + bool invocationCancelled, + ExceptionDispatchInfo? firstFatal, + List? additionalFatal) + { + internal bool InvocationCancelled { get; } = invocationCancelled; + + internal ExceptionDispatchInfo? FirstFatal { get; } = firstFatal; + + internal void LogAdditional(ILogger? logger) + { + if (logger is null || additionalFatal is null) + return; + + foreach (var exception in additionalFatal) + try + { + logger.LogError( + exception, + "Event processor observed an additional failure while draining item work."); + } + catch + { + // Logging must not replace the selected invocation error. + } + } + } +} diff --git a/src/MinimalLambda/Runtime/EventProcessorRuntime.cs b/src/MinimalLambda/Runtime/EventProcessorRuntime.cs new file mode 100644 index 00000000..97e2ded9 --- /dev/null +++ b/src/MinimalLambda/Runtime/EventProcessorRuntime.cs @@ -0,0 +1,148 @@ +using System.Collections.ObjectModel; +using System.Runtime.ExceptionServices; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace MinimalLambda.Runtime; + +/// Provides the runtime used by generated event-handler registrations. +internal sealed class EventProcessorRuntime +{ + private readonly int _concurrency; + private readonly IServiceScopeFactory _scopeFactory; + private readonly ILogger? _logger; + + /// Captures event-handler options and services at registration time. + /// The application's service provider. + internal EventProcessorRuntime(IServiceProvider services) + { + ArgumentNullException.ThrowIfNull(services); + var options = services.GetRequiredService>().Value; + _concurrency = options.EnableConcurrency ? options.MaxConcurrentExecutions : 1; + _scopeFactory = services.GetRequiredService(); + _logger = services + .GetService() + ?.CreateLogger("MinimalLambda.EventProcessor"); + } + + /// Runs a generated event adapter with per-item scopes and ordered response contributions. + /// The invocation event type. + /// The source item type. + /// The response contribution type. + /// The original invocation context. + /// The source item splitter. + /// Resolves handler arguments and returns the bound handler. + /// Selects a successful contribution, or null to discard successes. + /// Maps handler failures, or null to fail the invocation. + /// Builds and stores the response, or null for handlers without a response. + internal async Task RunAsync( + ILambdaInvocationContext context, + Func> split, + Func> bind, + Func? selectSuccess, + Func? onError, + Action>? complete) + { + context.CancellationToken.ThrowIfCancellationRequested(); + _ = context.ServiceProvider; + var splitItems = split(context.GetRequiredEvent(), context); + if (splitItems is null) + throw new InvalidOperationException("The event splitter 'split' returned null."); + + var items = new List(); + using (var enumerator = splitItems.GetEnumerator()) + while (enumerator.MoveNext()) + { + context.CancellationToken.ThrowIfCancellationRequested(); + items.Add(enumerator.Current); + } + + var itemArray = items.ToArray(); + context.CancellationToken.ThrowIfCancellationRequested(); + using var state = new EventProcessingState(context, _logger, itemArray.Length); + var outcomes = + await EventProcessorWorkers + .RunAsync( + itemArray, + _concurrency, + _scopeFactory, + state, + Adapt, + complete is not null) + .ConfigureAwait(false); + + if (complete is not null) + { + var contributions = new List(outcomes!.Length); + foreach (var outcome in outcomes) + if (outcome.HasValue) + contributions.Add(outcome.Value!); + complete(new ReadOnlyCollection(contributions)); + } + + async Task> Adapt( + TItem item, + IServiceProvider services, + EventProcessingState processing) + { + // Binding failures are fatal and must not be passed to the handler error mapper. + var handle = bind(item, services, processing); + var invocationToken = processing.Invocation.CancellationToken; + invocationToken.ThrowIfCancellationRequested(); + if (processing.CancellationToken.IsCancellationRequested) + return ItemOutcome.Cancelled; + + Task? handlerTask = null; + Exception? synchronousFault = null; + try + { + handlerTask = handle(); + } + catch (Exception ex) + { + synchronousFault = ex; + } + + if (synchronousFault is null && handlerTask is null) + throw new InvalidOperationException( + "The event handler 'handle' returned a null task."); + + try + { + if (synchronousFault is not null) + ExceptionDispatchInfo.Capture(synchronousFault).Throw(); + await handlerTask!.ConfigureAwait(false); + } + catch (Exception ex) + { + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while processing an item.", + ex, + invocationToken); + if (ex is OperationCanceledException + && processing.CancellationToken.IsCancellationRequested) + return ItemOutcome.Cancelled; + if (onError is null) + throw; + + invocationToken.ThrowIfCancellationRequested(); + var mapped = onError(item, ex, processing); + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while mapping an item error.", + invocationToken); + return ItemOutcome.FromMappedValue(mapped); + } + + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while processing an item.", + invocationToken); + return selectSuccess is null + ? ItemOutcome.NoValue + : ItemOutcome.FromValue(selectSuccess(item, handlerTask!)); + } + } +} diff --git a/src/MinimalLambda/Runtime/EventProcessorWorkers.cs b/src/MinimalLambda/Runtime/EventProcessorWorkers.cs new file mode 100644 index 00000000..f49124cf --- /dev/null +++ b/src/MinimalLambda/Runtime/EventProcessorWorkers.cs @@ -0,0 +1,124 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace MinimalLambda.Runtime; + +internal enum ItemExecutionState +{ + Unstarted, + Succeeded, + MappedError, + Cancelled, +} + +internal readonly struct ItemOutcome +{ + private ItemOutcome(ItemExecutionState state, bool hasValue, TValue? value) + { + State = state; + HasValue = hasValue; + Value = value; + } + + internal ItemExecutionState State { get; } + + internal bool HasValue { get; } + + internal TValue? Value { get; } + + internal static ItemOutcome FromValue(TValue? value) => + new(ItemExecutionState.Succeeded, true, value); + + internal static ItemOutcome FromMappedValue(TValue? value) => + new(ItemExecutionState.MappedError, true, value); + + internal static ItemOutcome NoValue => + new(ItemExecutionState.Succeeded, false, default); + + internal static ItemOutcome Cancelled => + new(ItemExecutionState.Cancelled, false, default); +} + +internal static class EventProcessorWorkers +{ + internal static async Task[]?> RunAsync( + TItem[] items, + int effectiveConcurrency, + IServiceScopeFactory scopeFactory, + EventProcessingState state, + Func>> adapter, + bool collectValues) + { + if (items.Length == 0) + state.TryCloseHandling(); + + var outcomes = collectValues ? new ItemOutcome[items.Length] : null; + var workerCount = Math.Min(items.Length, Math.Max(1, effectiveConcurrency)); + var workers = new Task[workerCount]; + + for (var index = 0; index < workerCount; index++) + workers[index] = RunWorkerAsync(); + + await Task.WhenAll(workers).ConfigureAwait(false); + await state.JoinAsync().ConfigureAwait(false); + + return outcomes; + + async Task RunWorkerAsync() + { + while (state.TryClaim(out var index)) + { + if (state.IsInvocationCancellationLatched) + { + state.CompleteAdmission(); + continue; + } + + AsyncServiceScope scope; + try + { + scope = scopeFactory.CreateAsyncScope(); + } + catch (Exception ex) + { + state.RecordFatal(ex); + state.CompleteAdmission(); + continue; + } + + ItemOutcome outcome = default; + var hasOutcome = false; + + try + { + try + { + outcome = await adapter(items[index], scope.ServiceProvider, state) + .ConfigureAwait(false); + hasOutcome = true; + } + catch (Exception ex) + { + if (!state.TryLatchInvocationCancellation()) + state.RecordFatal(ex); + } + } + finally + { + state.CompleteAdmission(); + } + + try + { + await scope.DisposeAsync().ConfigureAwait(false); + } + catch (Exception ex) + { + state.RecordFatal(ex); + } + + if (collectValues && hasOutcome && outcome.HasValue) + outcomes![index] = outcome; + } + } + } +} diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs index 77401f55..786beee3 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs @@ -50,18 +50,18 @@ internal sealed class Batch; } [Fact] - public void ReportsUnsupportedSignatureForRefParameter() + public void ReportsCompilerErrorForRefLambdaParameter() { - var result = RunGenerator( + var (_, compilation) = GeneratorTestHelpers.GenerateFromSource( """ using System.Threading.Tasks; using MinimalLambda; using MinimalLambda.Builder; var app = LambdaApplication.CreateBuilder().Build(); - app.MapEventHandler( + app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, - handle: (Item item, ref int count) => count++; + handle: (Item item, ref int count) => Task.CompletedTask); internal sealed class Batch { @@ -71,7 +71,11 @@ internal sealed class Batch internal sealed class Item; """); - result.Diagnostics.Should().OnlyContain(diagnostic => diagnostic.Id == "LH0008"); + compilation + .GetDiagnostics(TestContext.Current.CancellationToken) + .Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) + .Should() + .Contain(diagnostic => diagnostic.Id == "CS1677"); } [Fact] @@ -96,7 +100,12 @@ internal sealed class Item; internal sealed class Response; """); - result.Diagnostics.Should().OnlyContain(diagnostic => diagnostic.Id == "LH0008"); + result + .Diagnostics + .Should() + .NotBeEmpty() + .And + .OnlyContain(diagnostic => diagnostic.Id == "LH0008"); } [Fact] @@ -154,6 +163,75 @@ internal sealed class Item; diagnostic.Location.GetLineSpan().Path.Should().Be("InputFile.cs"); } + [Fact] + public Task SnapshotsDuplicateCancellationTokensAndDiscardedTaskResult() + { + const string source = """ + using System.Threading; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: Handle); + + static Task Handle(Item item, CancellationToken first, CancellationToken second) => + Task.FromResult(item.Id); + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item + { + public int Id { get; set; } + } + """; + var (driver, compilation) = GeneratorTestHelpers.GenerateFromSource(source); + + compilation + .GetDiagnostics(TestContext.Current.CancellationToken) + .Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) + .Should() + .BeEmpty("the diagnostic snapshot should use compiler-valid source"); + + var diagnostics = driver + .GetRunResult() + .Diagnostics + .Select(diagnostic => + { + var span = diagnostic.Location.GetLineSpan(); + return new + { + diagnostic.Id, + Severity = diagnostic.Severity.ToString(), + Message = diagnostic.GetMessage(), + FilePath = span.Path, + StartLine = span.StartLinePosition.Line + 1, + StartColumn = span.StartLinePosition.Character + 1, + EndLine = span.EndLinePosition.Line + 1, + EndColumn = span.EndLinePosition.Character + 1, + }; + }) + .OrderBy(diagnostic => diagnostic.Id, StringComparer.Ordinal) + .ToArray(); + + diagnostics.Select(diagnostic => diagnostic.Id).Should().Equal("LH0009", "LH0011"); + diagnostics + .Select(diagnostic => diagnostic.Severity) + .Should() + .OnlyContain(severity => severity == DiagnosticSeverity.Error.ToString()); + diagnostics + .Select(diagnostic => diagnostic.FilePath) + .Should() + .OnlyContain(path => path == "InputFile.cs"); + + return Verifier.Verify(diagnostics).UseDirectory("Snapshots").DisableDiff(); + } + [Fact] public void ReportsUnresolvedHandlerForReassignedDelegateLocal() { diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs index 5448d3e8..569a1b30 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs @@ -137,7 +137,7 @@ internal sealed class Item : BaseItem, IItem; [Fact] public void RecognizesTypedDelegateLocalAndExplicitGenericArguments() { - var result = RunGenerator( + var (driver, compilation) = GeneratorTestHelpers.GenerateFromSource( """ using System; using System.Collections.Generic; @@ -155,7 +155,8 @@ public void RecognizesTypedDelegateLocalAndExplicitGenericArguments() app.MapEventHandler( (Batch batch, ILambdaInvocationContext _) => batch.Items, - Handle); + Handle, + (IEnumerable results, ILambdaInvocationContext _) => new Response()); static Task Handle(Item item, Probe probe) => Task.FromResult(probe.Value); @@ -173,6 +174,7 @@ internal sealed class Probe internal sealed class Response; """); + var result = driver.GetRunResult(); result.Diagnostics.Should().BeEmpty(); result @@ -181,6 +183,12 @@ internal sealed class Response; .ContainSingle(tree => tree.FilePath.EndsWith( "MinimalLambda.EventHandlers.g.cs", StringComparison.Ordinal)); + + CompileWithGenerated(compilation, result) + .GetDiagnostics(TestContext.Current.CancellationToken) + .Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) + .Should() + .BeEmpty(); } [Fact] diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs index b795fd44..c92db2ed 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs @@ -108,6 +108,74 @@ internal sealed class Service internal sealed class Response; """); + [Fact] + public Task EmitsTypedDelegateAndExplicitGenericMethodGroupBindings() => + GeneratorTestHelpers.Verify( + """ + using System; + using System.Collections.Generic; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + Func> handle = Handle; + + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: handle, + createResponse: (IEnumerable results, ILambdaInvocationContext _) => new Response()); + + app.MapEventHandler( + (Batch batch, ILambdaInvocationContext _) => batch.Items, + Handle, + (IEnumerable results, ILambdaInvocationContext _) => new Response()); + + static Task Handle(Item item, Probe probe) => Task.FromResult(probe.Value); + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + + internal sealed class Probe + { + public int Value => 1; + } + + internal sealed class Response; + """); + + [Fact] + public Task EmitsNullableAndOptionalServiceResolution() => + GeneratorTestHelpers.Verify( + """ + using System.Collections.Generic; + using System.Threading.Tasks; + using Microsoft.Extensions.DependencyInjection; + using MinimalLambda; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: ( + Item item, + NullableService? nullableService, + [FromServices] string? optionalService = null) => Task.CompletedTask); + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + + internal sealed class NullableService; + """); + [Fact] public void CoexistsWithInvocationLifecycleAndMiddlewareGeneratedFiles() { diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerDiagnosticTests.SnapshotsDuplicateCancellationTokensAndDiscardedTaskResult.verified.txt b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerDiagnosticTests.SnapshotsDuplicateCancellationTokensAndDiscardedTaskResult.verified.txt new file mode 100644 index 00000000..ed3f8001 --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerDiagnosticTests.SnapshotsDuplicateCancellationTokensAndDiscardedTaskResult.verified.txt @@ -0,0 +1,22 @@ +[ + { + Id: LH0009, + Severity: Error, + Message: Event handler binding 'duplicate cancellation token parameter 'second'' is not supported; the first parameter is the source item, and framework context or cancellation-token parameters cannot use service or event attributes., + FilePath: InputFile.cs, + StartLine: 11, + StartColumn: 61, + EndLine: 11, + EndColumn: 85 + }, + { + Id: LH0011, + Severity: Error, + Message: The event handler 'Handle' returns a result but is bound to a no-result overload; use a result overload with a response builder or wrap the handler so it intentionally returns Task., + FilePath: InputFile.cs, + StartLine: 9, + StartColumn: 13, + EndLine: 9, + EndColumn: 19 + } +] \ No newline at end of file diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsContextTokenAndKeyedServiceBindings#MinimalLambda.EventHandlers.g.verified.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsContextTokenAndKeyedServiceBindings#MinimalLambda.EventHandlers.g.verified.cs index dee2de77..141d7369 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsContextTokenAndKeyedServiceBindings#MinimalLambda.EventHandlers.g.verified.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsContextTokenAndKeyedServiceBindings#MinimalLambda.EventHandlers.g.verified.cs @@ -25,24 +25,15 @@ public InterceptsLocationAttribute(int version, string data) { } namespace MinimalLambda.Generated { using System; - using System.Collections.Generic; - using System.Collections.ObjectModel; - using System.Runtime.ExceptionServices; using System.Runtime.CompilerServices; - using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Logging; - using Microsoft.Extensions.Options; using MinimalLambda.Builder; - using MinimalLambda.Options; + using MinimalLambda.Runtime; [global::System.CodeDom.Compiler.GeneratedCode("MinimalLambda.SourceGenerators", "REPLACED")] file static class GeneratedEventProcessorExtensions { - private const string EventFeatureProviderKey = "__EventFeatureProvider"; - private const string ResponseFeatureProviderKey = "__ResponseFeatureProvider"; - [InterceptsLocation(1, "REPLACED")] internal static ILambdaInvocationBuilder MapEventHandlerInterceptor0( this ILambdaInvocationBuilder application, @@ -51,89 +42,18 @@ internal static ILambdaInvocationBuilder MapEventHandlerInterceptor0( global::System.Func onError, global::System.Func, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) { - ArgumentNullException.ThrowIfNull(application); - ArgumentNullException.ThrowIfNull(split); - ArgumentNullException.ThrowIfNull(handle); - ArgumentNullException.ThrowIfNull(onError); - ArgumentNullException.ThrowIfNull(createResponse); - - var options = application.Services.GetRequiredService>().Value; - var effectiveConcurrency = options.EnableConcurrency - ? options.MaxConcurrentExecutions - : 1; - var scopeFactory = application.Services.GetRequiredService(); - var logger = application - .Services.GetService() - ?.CreateLogger("MinimalLambda.EventProcessor"); - - application.Handle(InvocationDelegate); - - if (!application.Properties.ContainsKey(EventFeatureProviderKey)) - application.Properties[EventFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - - if (!application.Properties.ContainsKey(ResponseFeatureProviderKey)) - application.Properties[ResponseFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - - return application; - - async Task InvocationDelegate(ILambdaInvocationContext context) - { - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - _ = context.ServiceProvider; - - var lambdaEvent = context.GetRequiredEvent(); - var splitItems = split(lambdaEvent, context); - if (splitItems is null) - throw new InvalidOperationException("The event splitter 'split' returned null."); - - var items = new List(); - using (var enumerator = splitItems.GetEnumerator()) - { - while (enumerator.MoveNext()) - { - context.CancellationToken.ThrowIfCancellationRequested(); - items.Add(enumerator.Current); - } - } - - var itemArray = items.ToArray(); + return EventHandlerRegistration.Register( + application, + split, + handle, + Bind, + onError, + createResponse); - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - using var state = new EventProcessingState( - context, - logger, - itemArray.Length); - var outcomes = await EventProcessorRuntime - .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, true) - .ConfigureAwait(false); - - var contributions = new List(outcomes!.Length); - foreach (var outcome in outcomes) - if (outcome.HasValue) - contributions.Add(outcome.Value!); - - var response = createResponse( - new ReadOnlyCollection(contributions), - context); - - if (context.Features.Get() is not IResponseFeature responseFeature) - throw new InvalidOperationException( - "Response feature for type 'global::Response' is not available in the collection."); - responseFeature.SetResponse(response); - } - - async Task> Adapt( + Func> Bind( global::Item item, IServiceProvider serviceProvider, - EventProcessingState processingContext) + IEventProcessingContext processingContext) { if (serviceProvider.GetService() is not IServiceProviderIsKeyedService) throw new InvalidOperationException( @@ -144,495 +64,7 @@ async Task> Adapt( var arg3 = processingContext.CancellationToken; var arg4 = serviceProvider.GetRequiredService(); var arg5 = serviceProvider.GetRequiredKeyedService("primary"); - - var invocationToken = processingContext.Invocation.CancellationToken; - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - if (processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - Task? handlerTask = null; - int handlerResult = default!; - Exception? synchronousFault = null; - try - { - handlerTask = handle(arg0, arg1, arg2, arg3, arg4, arg5); - } - catch (Exception ex) - { - synchronousFault = ex; - } - - if (synchronousFault is null && handlerTask is null) - throw new InvalidOperationException("The event handler 'handle' returned a null task."); - - try - { - if (synchronousFault is not null) - ExceptionDispatchInfo.Capture(synchronousFault).Throw(); - - handlerResult = await handlerTask!.ConfigureAwait(false); - } - catch (Exception ex) - { - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - ex, - invocationToken); - - if (ex is OperationCanceledException - && processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - - var mapped = onError(item, ex, processingContext); - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while mapping an item error.", - invocationToken); - - return ItemOutcome.FromMappedValue(mapped); - } - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - invocationToken); - - return ItemOutcome.FromValue(handlerResult); - } - } - } - - file readonly struct NoData; - - file enum ItemExecutionState - { - Unstarted, - Succeeded, - MappedError, - Cancelled, - } - - file readonly struct ItemOutcome - { - private ItemOutcome(ItemExecutionState state, bool hasValue, TValue? value) - { - State = state; - HasValue = hasValue; - Value = value; - } - - internal ItemExecutionState State { get; } - - internal bool HasValue { get; } - - internal TValue? Value { get; } - - internal static ItemOutcome FromValue(TValue? value) => - new(ItemExecutionState.Succeeded, true, value); - - internal static ItemOutcome FromMappedValue(TValue? value) => - new(ItemExecutionState.MappedError, true, value); - - internal static ItemOutcome NoValue => - new(ItemExecutionState.Succeeded, false, default); - - internal static ItemOutcome Cancelled => - new(ItemExecutionState.Cancelled, false, default); - } - - file sealed class EventProcessingState : IEventProcessingContext, IDisposable - { - private readonly object _gate = new(); - private readonly ILambdaInvocationContext _invocation; - private readonly ILogger? _logger; - private readonly int _itemCount; - private readonly CancellationTokenSource _processingSource = new(); - private readonly CancellationTokenRegistration _invocationRegistration; - - private int _nextIndex; - private int _admitted; - private bool _stopRequested; - private bool _cancelRequested; - private bool _handlingClosed; - private bool _completed; - private bool _invocationCancelled; - private bool _disposed; - private ExceptionDispatchInfo? _firstFatal; - private List? _additionalFatal; - private TaskCompletionSource? _dispatchCompletion; - - internal EventProcessingState( - ILambdaInvocationContext invocation, - ILogger? logger, - int itemCount) - { - _invocation = invocation; - _logger = logger; - _itemCount = itemCount; - _invocationRegistration = invocation.CancellationToken.Register( - static state => ((EventProcessingState)state!).OnInvocationTokenCancelled(), - this); - } - - public ILambdaInvocationContext Invocation => _invocation; - - public CancellationToken CancellationToken => _processingSource.Token; - - public void StopProcessing() - { - lock (_gate) - { - if (_completed || _handlingClosed) - return; - - _stopRequested = true; - TryCloseHandlingCore(); - } - } - - public void CancelProcessing() => RequestProcessingCancellation(false); - - internal bool TryClaim(out int index) - { - TaskCompletionSource? dispatch = null; - var claimed = false; - index = -1; - - lock (_gate) - { - if (_completed) - return false; - - ObserveInvocationCancellationCore(ref dispatch); - - if (_handlingClosed - || _stopRequested - || _firstFatal is not null - || _nextIndex >= _itemCount) - { - TryCloseHandlingCore(); - } - else - { - index = _nextIndex++; - _admitted++; - claimed = true; - } - } - - if (dispatch is not null) - StartDispatch(dispatch); - - return claimed; - } - - internal bool IsInvocationCancellationLatched - { - get - { - lock (_gate) - return _invocationCancelled; - } - } - - internal void CompleteAdmission() - { - lock (_gate) - { - if (_admitted > 0) - _admitted--; - - TryCloseHandlingCore(); - } - } - - internal bool TryLatchInvocationCancellation() - { - if (!_invocation.CancellationToken.IsCancellationRequested) - return false; - - RequestProcessingCancellation(true); - - lock (_gate) - return _invocationCancelled; - } - - internal void RecordFatal(Exception exception) - { - lock (_gate) - { - if (_completed) - return; - - _stopRequested = true; - var fatal = ExceptionDispatchInfo.Capture(exception); - if (_firstFatal is null) - _firstFatal = fatal; - else - (_additionalFatal ??= []).Add(exception); - - TryCloseHandlingCore(); - } - } - - internal void TryCloseHandling() - { - lock (_gate) - TryCloseHandlingCore(); - } - - internal async Task JoinAsync() - { - Task? dispatch; - lock (_gate) - { - TryCloseHandlingCore(); - dispatch = _dispatchCompletion?.Task; - } - - if (dispatch is not null) - await dispatch.ConfigureAwait(false); - - Completion completion; - lock (_gate) - { - TryCloseHandlingCore(); - _completed = true; - completion = new Completion( - _invocationCancelled, - _firstFatal, - _additionalFatal); - } - - completion.LogAdditional(_logger); - - if (completion.InvocationCancelled) - throw new OperationCanceledException( - "The Lambda invocation was cancelled during item processing.", - _invocation.CancellationToken); - - if (completion.FirstFatal is not null) - { - completion.FirstFatal.Throw(); - throw new InvalidOperationException("Unreachable"); - } - } - - public void Dispose() - { - if (_disposed) - return; - - _disposed = true; - _invocationRegistration.Dispose(); - _processingSource.Dispose(); - } - - private void OnInvocationTokenCancelled() => RequestProcessingCancellation(true); - - private void RequestProcessingCancellation(bool invocationCancelled) - { - TaskCompletionSource? dispatch = null; - lock (_gate) - { - if (_completed || _handlingClosed) - return; - - if (invocationCancelled) - _invocationCancelled = true; - - _stopRequested = true; - - if (!_cancelRequested) - { - _cancelRequested = true; - _dispatchCompletion = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously); - dispatch = _dispatchCompletion; - } - - TryCloseHandlingCore(); - } - - if (dispatch is not null) - StartDispatch(dispatch); - } - - private void ObserveInvocationCancellationCore(ref TaskCompletionSource? dispatch) - { - if (_handlingClosed || !_invocation.CancellationToken.IsCancellationRequested) - return; - - _invocationCancelled = true; - _stopRequested = true; - - if (_cancelRequested) - return; - - _cancelRequested = true; - _dispatchCompletion = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously); - dispatch = _dispatchCompletion; - } - - private void TryCloseHandlingCore() - { - if (_handlingClosed) - return; - - if (_admitted > 0) - return; - - if (_nextIndex < _itemCount - && !_stopRequested - && _firstFatal is null - && !_invocation.CancellationToken.IsCancellationRequested) - return; - - if (_invocation.CancellationToken.IsCancellationRequested) - { - _invocationCancelled = true; - _stopRequested = true; - } - - _handlingClosed = true; - } - - private void StartDispatch(TaskCompletionSource completion) => - _ = DispatchCancellationAsync(completion); - - private async Task DispatchCancellationAsync(TaskCompletionSource completion) - { - try - { - await _processingSource.CancelAsync().ConfigureAwait(false); - } - catch (Exception ex) - { - RecordFatal(ex); - } - finally - { - completion.TrySetResult(); - } - } - - private readonly struct Completion( - bool invocationCancelled, - ExceptionDispatchInfo? firstFatal, - List? additionalFatal) - { - internal bool InvocationCancelled { get; } = invocationCancelled; - - internal ExceptionDispatchInfo? FirstFatal { get; } = firstFatal; - - internal void LogAdditional(ILogger? logger) - { - if (logger is null || additionalFatal is null) - return; - - foreach (var exception in additionalFatal) - try - { - logger.LogError( - exception, - "Event processor observed an additional failure while draining item work."); - } - catch - { - // Logging must not replace the selected invocation error. - } - } - } - } - - file static class EventProcessorRuntime - { - internal static async Task[]?> RunAsync( - TItem[] items, - int effectiveConcurrency, - IServiceScopeFactory scopeFactory, - EventProcessingState state, - Func>> adapter, - bool collectValues) - { - if (items.Length == 0) - state.TryCloseHandling(); - - var outcomes = collectValues ? new ItemOutcome[items.Length] : null; - var workerCount = Math.Min(items.Length, Math.Max(1, effectiveConcurrency)); - var workers = new Task[workerCount]; - - for (var index = 0; index < workerCount; index++) - workers[index] = RunWorkerAsync(); - - await Task.WhenAll(workers).ConfigureAwait(false); - await state.JoinAsync().ConfigureAwait(false); - - return outcomes; - - async Task RunWorkerAsync() - { - while (state.TryClaim(out var index)) - { - if (state.IsInvocationCancellationLatched) - { - state.CompleteAdmission(); - continue; - } - - AsyncServiceScope scope; - try - { - scope = scopeFactory.CreateAsyncScope(); - } - catch (Exception ex) - { - state.RecordFatal(ex); - state.CompleteAdmission(); - continue; - } - - ItemOutcome outcome = default; - var hasOutcome = false; - - try - { - try - { - outcome = await adapter(items[index], scope.ServiceProvider, state) - .ConfigureAwait(false); - hasOutcome = true; - } - catch (Exception ex) - { - if (!state.TryLatchInvocationCancellation()) - state.RecordFatal(ex); - } - } - finally - { - state.CompleteAdmission(); - } - - try - { - await scope.DisposeAsync().ConfigureAwait(false); - } - catch (Exception ex) - { - state.RecordFatal(ex); - } - - if (collectValues && hasOutcome && outcome.HasValue) - outcomes![index] = outcome; - } + return () => handle(arg0, arg1, arg2, arg3, arg4, arg5); } } } diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsNullableAndOptionalServiceResolution#MinimalLambda.EventHandlers.g.verified.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsNullableAndOptionalServiceResolution#MinimalLambda.EventHandlers.g.verified.cs new file mode 100644 index 00000000..e31aae9c --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsNullableAndOptionalServiceResolution#MinimalLambda.EventHandlers.g.verified.cs @@ -0,0 +1,61 @@ +//HintName: MinimalLambda.EventHandlers.g.cs +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +#nullable enable + +namespace System.Runtime.CompilerServices +{ + using System.CodeDom.Compiler; + + [global::System.CodeDom.Compiler.GeneratedCode("MinimalLambda.SourceGenerators", "REPLACED")] + [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] + file sealed class InterceptsLocationAttribute : Attribute + { + public InterceptsLocationAttribute(int version, string data) { } + } +} + +namespace MinimalLambda.Generated +{ + using System; + using System.Runtime.CompilerServices; + using System.Threading.Tasks; + using Microsoft.Extensions.DependencyInjection; + using MinimalLambda.Builder; + using MinimalLambda.Runtime; + + [global::System.CodeDom.Compiler.GeneratedCode("MinimalLambda.SourceGenerators", "REPLACED")] + file static class GeneratedEventProcessorExtensions + { + [InterceptsLocation(1, "REPLACED")] + internal static ILambdaInvocationBuilder MapEventHandlerInterceptor0( + this ILambdaInvocationBuilder application, + global::System.Func> split, + global::System.Func handle) + { + return EventHandlerRegistration.Register( + application, + split, + handle, + Bind); + + Func Bind( + global::Item item, + IServiceProvider serviceProvider, + IEventProcessingContext processingContext) + { + var arg0 = item; + var arg1 = serviceProvider.GetService(); + var arg2 = serviceProvider.GetService(); + return () => handle(arg0, arg1, arg2); + } + } + } +} diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsRepresentativeAdapterForEveryFamily#MinimalLambda.EventHandlers.g.verified.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsRepresentativeAdapterForEveryFamily#MinimalLambda.EventHandlers.g.verified.cs index 69a39fa8..2c982a6d 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsRepresentativeAdapterForEveryFamily#MinimalLambda.EventHandlers.g.verified.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsRepresentativeAdapterForEveryFamily#MinimalLambda.EventHandlers.g.verified.cs @@ -25,144 +25,34 @@ public InterceptsLocationAttribute(int version, string data) { } namespace MinimalLambda.Generated { using System; - using System.Collections.Generic; - using System.Collections.ObjectModel; - using System.Runtime.ExceptionServices; using System.Runtime.CompilerServices; - using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Logging; - using Microsoft.Extensions.Options; using MinimalLambda.Builder; - using MinimalLambda.Options; + using MinimalLambda.Runtime; [global::System.CodeDom.Compiler.GeneratedCode("MinimalLambda.SourceGenerators", "REPLACED")] file static class GeneratedEventProcessorExtensions { - private const string EventFeatureProviderKey = "__EventFeatureProvider"; - private const string ResponseFeatureProviderKey = "__ResponseFeatureProvider"; - [InterceptsLocation(1, "REPLACED")] internal static ILambdaInvocationBuilder MapEventHandlerInterceptor0( this ILambdaInvocationBuilder application, global::System.Func> split, global::System.Func handle) { - ArgumentNullException.ThrowIfNull(application); - ArgumentNullException.ThrowIfNull(split); - ArgumentNullException.ThrowIfNull(handle); - - var options = application.Services.GetRequiredService>().Value; - var effectiveConcurrency = options.EnableConcurrency - ? options.MaxConcurrentExecutions - : 1; - var scopeFactory = application.Services.GetRequiredService(); - var logger = application - .Services.GetService() - ?.CreateLogger("MinimalLambda.EventProcessor"); - - application.Handle(InvocationDelegate); - - if (!application.Properties.ContainsKey(EventFeatureProviderKey)) - application.Properties[EventFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - - return application; - - async Task InvocationDelegate(ILambdaInvocationContext context) - { - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - _ = context.ServiceProvider; - - var lambdaEvent = context.GetRequiredEvent(); - var splitItems = split(lambdaEvent, context); - if (splitItems is null) - throw new InvalidOperationException("The event splitter 'split' returned null."); + return EventHandlerRegistration.Register( + application, + split, + handle, + Bind); - var items = new List(); - using (var enumerator = splitItems.GetEnumerator()) - { - while (enumerator.MoveNext()) - { - context.CancellationToken.ThrowIfCancellationRequested(); - items.Add(enumerator.Current); - } - } - - var itemArray = items.ToArray(); - - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - using var state = new EventProcessingState( - context, - logger, - itemArray.Length); - var outcomes = await EventProcessorRuntime - .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, false) - .ConfigureAwait(false); - } - - async Task> Adapt( + Func Bind( global::Item item, IServiceProvider serviceProvider, - EventProcessingState processingContext) + IEventProcessingContext processingContext) { var arg0 = item; - - var invocationToken = processingContext.Invocation.CancellationToken; - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - if (processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - Task? handlerTask = null; - - Exception? synchronousFault = null; - try - { - handlerTask = handle(arg0); - } - catch (Exception ex) - { - synchronousFault = ex; - } - - if (synchronousFault is null && handlerTask is null) - throw new InvalidOperationException("The event handler 'handle' returned a null task."); - - try - { - if (synchronousFault is not null) - ExceptionDispatchInfo.Capture(synchronousFault).Throw(); - - await handlerTask!.ConfigureAwait(false); - } - catch (Exception ex) - { - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - ex, - invocationToken); - - if (ex is OperationCanceledException - && processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - throw; - } - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - invocationToken); - - return ItemOutcome.NoValue; + return () => handle(arg0); } } [InterceptsLocation(1, "REPLACED")] @@ -172,140 +62,20 @@ internal static ILambdaInvocationBuilder MapEventHandlerInterceptor1( global::System.Func handle, global::System.Func, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) { - ArgumentNullException.ThrowIfNull(application); - ArgumentNullException.ThrowIfNull(split); - ArgumentNullException.ThrowIfNull(handle); - ArgumentNullException.ThrowIfNull(createResponse); - - var options = application.Services.GetRequiredService>().Value; - var effectiveConcurrency = options.EnableConcurrency - ? options.MaxConcurrentExecutions - : 1; - var scopeFactory = application.Services.GetRequiredService(); - var logger = application - .Services.GetService() - ?.CreateLogger("MinimalLambda.EventProcessor"); - - application.Handle(InvocationDelegate); - - if (!application.Properties.ContainsKey(EventFeatureProviderKey)) - application.Properties[EventFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - - if (!application.Properties.ContainsKey(ResponseFeatureProviderKey)) - application.Properties[ResponseFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - - return application; - - async Task InvocationDelegate(ILambdaInvocationContext context) - { - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - _ = context.ServiceProvider; - - var lambdaEvent = context.GetRequiredEvent(); - var splitItems = split(lambdaEvent, context); - if (splitItems is null) - throw new InvalidOperationException("The event splitter 'split' returned null."); - - var items = new List(); - using (var enumerator = splitItems.GetEnumerator()) - { - while (enumerator.MoveNext()) - { - context.CancellationToken.ThrowIfCancellationRequested(); - items.Add(enumerator.Current); - } - } - - var itemArray = items.ToArray(); - - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); + return EventHandlerRegistration.Register( + application, + split, + handle, + Bind, + createResponse); - using var state = new EventProcessingState( - context, - logger, - itemArray.Length); - var outcomes = await EventProcessorRuntime - .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, true) - .ConfigureAwait(false); - - var contributions = new List(outcomes!.Length); - foreach (var outcome in outcomes) - if (outcome.HasValue) - contributions.Add(outcome.Value!); - - var response = createResponse( - new ReadOnlyCollection(contributions), - context); - - if (context.Features.Get() is not IResponseFeature responseFeature) - throw new InvalidOperationException( - "Response feature for type 'global::Response' is not available in the collection."); - responseFeature.SetResponse(response); - } - - async Task> Adapt( + Func Bind( global::Item item, IServiceProvider serviceProvider, - EventProcessingState processingContext) + IEventProcessingContext processingContext) { var arg0 = item; - - var invocationToken = processingContext.Invocation.CancellationToken; - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - if (processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - Task? handlerTask = null; - - Exception? synchronousFault = null; - try - { - handlerTask = handle(arg0); - } - catch (Exception ex) - { - synchronousFault = ex; - } - - if (synchronousFault is null && handlerTask is null) - throw new InvalidOperationException("The event handler 'handle' returned a null task."); - - try - { - if (synchronousFault is not null) - ExceptionDispatchInfo.Capture(synchronousFault).Throw(); - - await handlerTask!.ConfigureAwait(false); - } - catch (Exception ex) - { - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - ex, - invocationToken); - - if (ex is OperationCanceledException - && processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - throw; - } - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - invocationToken); - - return ItemOutcome.FromValue(item); + return () => handle(arg0); } } [InterceptsLocation(1, "REPLACED")] @@ -316,151 +86,21 @@ internal static ILambdaInvocationBuilder MapEventHandlerInterceptor2( global::System.Func onError, global::System.Func, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) { - ArgumentNullException.ThrowIfNull(application); - ArgumentNullException.ThrowIfNull(split); - ArgumentNullException.ThrowIfNull(handle); - ArgumentNullException.ThrowIfNull(onError); - ArgumentNullException.ThrowIfNull(createResponse); - - var options = application.Services.GetRequiredService>().Value; - var effectiveConcurrency = options.EnableConcurrency - ? options.MaxConcurrentExecutions - : 1; - var scopeFactory = application.Services.GetRequiredService(); - var logger = application - .Services.GetService() - ?.CreateLogger("MinimalLambda.EventProcessor"); - - application.Handle(InvocationDelegate); - - if (!application.Properties.ContainsKey(EventFeatureProviderKey)) - application.Properties[EventFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - - if (!application.Properties.ContainsKey(ResponseFeatureProviderKey)) - application.Properties[ResponseFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); + return EventHandlerRegistration.Register( + application, + split, + handle, + Bind, + onError, + createResponse); - return application; - - async Task InvocationDelegate(ILambdaInvocationContext context) - { - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - _ = context.ServiceProvider; - - var lambdaEvent = context.GetRequiredEvent(); - var splitItems = split(lambdaEvent, context); - if (splitItems is null) - throw new InvalidOperationException("The event splitter 'split' returned null."); - - var items = new List(); - using (var enumerator = splitItems.GetEnumerator()) - { - while (enumerator.MoveNext()) - { - context.CancellationToken.ThrowIfCancellationRequested(); - items.Add(enumerator.Current); - } - } - - var itemArray = items.ToArray(); - - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - using var state = new EventProcessingState( - context, - logger, - itemArray.Length); - var outcomes = await EventProcessorRuntime - .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, true) - .ConfigureAwait(false); - - var contributions = new List(outcomes!.Length); - foreach (var outcome in outcomes) - if (outcome.HasValue) - contributions.Add(outcome.Value!); - - var response = createResponse( - new ReadOnlyCollection(contributions), - context); - - if (context.Features.Get() is not IResponseFeature responseFeature) - throw new InvalidOperationException( - "Response feature for type 'global::Response' is not available in the collection."); - responseFeature.SetResponse(response); - } - - async Task> Adapt( + Func Bind( global::Item item, IServiceProvider serviceProvider, - EventProcessingState processingContext) + IEventProcessingContext processingContext) { var arg0 = item; - - var invocationToken = processingContext.Invocation.CancellationToken; - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - if (processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - Task? handlerTask = null; - - Exception? synchronousFault = null; - try - { - handlerTask = handle(arg0); - } - catch (Exception ex) - { - synchronousFault = ex; - } - - if (synchronousFault is null && handlerTask is null) - throw new InvalidOperationException("The event handler 'handle' returned a null task."); - - try - { - if (synchronousFault is not null) - ExceptionDispatchInfo.Capture(synchronousFault).Throw(); - - await handlerTask!.ConfigureAwait(false); - } - catch (Exception ex) - { - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - ex, - invocationToken); - - if (ex is OperationCanceledException - && processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - - var mapped = onError(item, ex, processingContext); - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while mapping an item error.", - invocationToken); - - return ItemOutcome.FromMappedValue(mapped); - } - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - invocationToken); - - return ItemOutcome.NoValue; + return () => handle(arg0); } } [InterceptsLocation(1, "REPLACED")] @@ -470,140 +110,20 @@ internal static ILambdaInvocationBuilder MapEventHandlerInterceptor3( global::System.Func> handle, global::System.Func, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) { - ArgumentNullException.ThrowIfNull(application); - ArgumentNullException.ThrowIfNull(split); - ArgumentNullException.ThrowIfNull(handle); - ArgumentNullException.ThrowIfNull(createResponse); - - var options = application.Services.GetRequiredService>().Value; - var effectiveConcurrency = options.EnableConcurrency - ? options.MaxConcurrentExecutions - : 1; - var scopeFactory = application.Services.GetRequiredService(); - var logger = application - .Services.GetService() - ?.CreateLogger("MinimalLambda.EventProcessor"); - - application.Handle(InvocationDelegate); - - if (!application.Properties.ContainsKey(EventFeatureProviderKey)) - application.Properties[EventFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - - if (!application.Properties.ContainsKey(ResponseFeatureProviderKey)) - application.Properties[ResponseFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - - return application; - - async Task InvocationDelegate(ILambdaInvocationContext context) - { - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - _ = context.ServiceProvider; - - var lambdaEvent = context.GetRequiredEvent(); - var splitItems = split(lambdaEvent, context); - if (splitItems is null) - throw new InvalidOperationException("The event splitter 'split' returned null."); - - var items = new List(); - using (var enumerator = splitItems.GetEnumerator()) - { - while (enumerator.MoveNext()) - { - context.CancellationToken.ThrowIfCancellationRequested(); - items.Add(enumerator.Current); - } - } + return EventHandlerRegistration.Register( + application, + split, + handle, + Bind, + createResponse); - var itemArray = items.ToArray(); - - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - using var state = new EventProcessingState( - context, - logger, - itemArray.Length); - var outcomes = await EventProcessorRuntime - .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, true) - .ConfigureAwait(false); - - var contributions = new List(outcomes!.Length); - foreach (var outcome in outcomes) - if (outcome.HasValue) - contributions.Add(outcome.Value!); - - var response = createResponse( - new ReadOnlyCollection(contributions), - context); - - if (context.Features.Get() is not IResponseFeature responseFeature) - throw new InvalidOperationException( - "Response feature for type 'global::Response' is not available in the collection."); - responseFeature.SetResponse(response); - } - - async Task> Adapt( + Func> Bind( global::Item item, IServiceProvider serviceProvider, - EventProcessingState processingContext) + IEventProcessingContext processingContext) { var arg0 = item; - - var invocationToken = processingContext.Invocation.CancellationToken; - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - if (processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - Task? handlerTask = null; - int handlerResult = default!; - Exception? synchronousFault = null; - try - { - handlerTask = handle(arg0); - } - catch (Exception ex) - { - synchronousFault = ex; - } - - if (synchronousFault is null && handlerTask is null) - throw new InvalidOperationException("The event handler 'handle' returned a null task."); - - try - { - if (synchronousFault is not null) - ExceptionDispatchInfo.Capture(synchronousFault).Throw(); - - handlerResult = await handlerTask!.ConfigureAwait(false); - } - catch (Exception ex) - { - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - ex, - invocationToken); - - if (ex is OperationCanceledException - && processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - throw; - } - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - invocationToken); - - return ItemOutcome.FromValue(handlerResult); + return () => handle(arg0); } } [InterceptsLocation(1, "REPLACED")] @@ -614,580 +134,21 @@ internal static ILambdaInvocationBuilder MapEventHandlerInterceptor4( global::System.Func onError, global::System.Func, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) { - ArgumentNullException.ThrowIfNull(application); - ArgumentNullException.ThrowIfNull(split); - ArgumentNullException.ThrowIfNull(handle); - ArgumentNullException.ThrowIfNull(onError); - ArgumentNullException.ThrowIfNull(createResponse); - - var options = application.Services.GetRequiredService>().Value; - var effectiveConcurrency = options.EnableConcurrency - ? options.MaxConcurrentExecutions - : 1; - var scopeFactory = application.Services.GetRequiredService(); - var logger = application - .Services.GetService() - ?.CreateLogger("MinimalLambda.EventProcessor"); + return EventHandlerRegistration.Register( + application, + split, + handle, + Bind, + onError, + createResponse); - application.Handle(InvocationDelegate); - - if (!application.Properties.ContainsKey(EventFeatureProviderKey)) - application.Properties[EventFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - - if (!application.Properties.ContainsKey(ResponseFeatureProviderKey)) - application.Properties[ResponseFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - - return application; - - async Task InvocationDelegate(ILambdaInvocationContext context) - { - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - _ = context.ServiceProvider; - - var lambdaEvent = context.GetRequiredEvent(); - var splitItems = split(lambdaEvent, context); - if (splitItems is null) - throw new InvalidOperationException("The event splitter 'split' returned null."); - - var items = new List(); - using (var enumerator = splitItems.GetEnumerator()) - { - while (enumerator.MoveNext()) - { - context.CancellationToken.ThrowIfCancellationRequested(); - items.Add(enumerator.Current); - } - } - - var itemArray = items.ToArray(); - - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - using var state = new EventProcessingState( - context, - logger, - itemArray.Length); - var outcomes = await EventProcessorRuntime - .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, true) - .ConfigureAwait(false); - - var contributions = new List(outcomes!.Length); - foreach (var outcome in outcomes) - if (outcome.HasValue) - contributions.Add(outcome.Value!); - - var response = createResponse( - new ReadOnlyCollection(contributions), - context); - - if (context.Features.Get() is not IResponseFeature responseFeature) - throw new InvalidOperationException( - "Response feature for type 'global::Response' is not available in the collection."); - responseFeature.SetResponse(response); - } - - async Task> Adapt( + Func> Bind( global::Item item, IServiceProvider serviceProvider, - EventProcessingState processingContext) + IEventProcessingContext processingContext) { var arg0 = item; - - var invocationToken = processingContext.Invocation.CancellationToken; - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - if (processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - Task? handlerTask = null; - int handlerResult = default!; - Exception? synchronousFault = null; - try - { - handlerTask = handle(arg0); - } - catch (Exception ex) - { - synchronousFault = ex; - } - - if (synchronousFault is null && handlerTask is null) - throw new InvalidOperationException("The event handler 'handle' returned a null task."); - - try - { - if (synchronousFault is not null) - ExceptionDispatchInfo.Capture(synchronousFault).Throw(); - - handlerResult = await handlerTask!.ConfigureAwait(false); - } - catch (Exception ex) - { - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - ex, - invocationToken); - - if (ex is OperationCanceledException - && processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - - var mapped = onError(item, ex, processingContext); - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while mapping an item error.", - invocationToken); - - return ItemOutcome.FromMappedValue(mapped); - } - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - invocationToken); - - return ItemOutcome.FromValue(handlerResult); - } - } - } - - file readonly struct NoData; - - file enum ItemExecutionState - { - Unstarted, - Succeeded, - MappedError, - Cancelled, - } - - file readonly struct ItemOutcome - { - private ItemOutcome(ItemExecutionState state, bool hasValue, TValue? value) - { - State = state; - HasValue = hasValue; - Value = value; - } - - internal ItemExecutionState State { get; } - - internal bool HasValue { get; } - - internal TValue? Value { get; } - - internal static ItemOutcome FromValue(TValue? value) => - new(ItemExecutionState.Succeeded, true, value); - - internal static ItemOutcome FromMappedValue(TValue? value) => - new(ItemExecutionState.MappedError, true, value); - - internal static ItemOutcome NoValue => - new(ItemExecutionState.Succeeded, false, default); - - internal static ItemOutcome Cancelled => - new(ItemExecutionState.Cancelled, false, default); - } - - file sealed class EventProcessingState : IEventProcessingContext, IDisposable - { - private readonly object _gate = new(); - private readonly ILambdaInvocationContext _invocation; - private readonly ILogger? _logger; - private readonly int _itemCount; - private readonly CancellationTokenSource _processingSource = new(); - private readonly CancellationTokenRegistration _invocationRegistration; - - private int _nextIndex; - private int _admitted; - private bool _stopRequested; - private bool _cancelRequested; - private bool _handlingClosed; - private bool _completed; - private bool _invocationCancelled; - private bool _disposed; - private ExceptionDispatchInfo? _firstFatal; - private List? _additionalFatal; - private TaskCompletionSource? _dispatchCompletion; - - internal EventProcessingState( - ILambdaInvocationContext invocation, - ILogger? logger, - int itemCount) - { - _invocation = invocation; - _logger = logger; - _itemCount = itemCount; - _invocationRegistration = invocation.CancellationToken.Register( - static state => ((EventProcessingState)state!).OnInvocationTokenCancelled(), - this); - } - - public ILambdaInvocationContext Invocation => _invocation; - - public CancellationToken CancellationToken => _processingSource.Token; - - public void StopProcessing() - { - lock (_gate) - { - if (_completed || _handlingClosed) - return; - - _stopRequested = true; - TryCloseHandlingCore(); - } - } - - public void CancelProcessing() => RequestProcessingCancellation(false); - - internal bool TryClaim(out int index) - { - TaskCompletionSource? dispatch = null; - var claimed = false; - index = -1; - - lock (_gate) - { - if (_completed) - return false; - - ObserveInvocationCancellationCore(ref dispatch); - - if (_handlingClosed - || _stopRequested - || _firstFatal is not null - || _nextIndex >= _itemCount) - { - TryCloseHandlingCore(); - } - else - { - index = _nextIndex++; - _admitted++; - claimed = true; - } - } - - if (dispatch is not null) - StartDispatch(dispatch); - - return claimed; - } - - internal bool IsInvocationCancellationLatched - { - get - { - lock (_gate) - return _invocationCancelled; - } - } - - internal void CompleteAdmission() - { - lock (_gate) - { - if (_admitted > 0) - _admitted--; - - TryCloseHandlingCore(); - } - } - - internal bool TryLatchInvocationCancellation() - { - if (!_invocation.CancellationToken.IsCancellationRequested) - return false; - - RequestProcessingCancellation(true); - - lock (_gate) - return _invocationCancelled; - } - - internal void RecordFatal(Exception exception) - { - lock (_gate) - { - if (_completed) - return; - - _stopRequested = true; - var fatal = ExceptionDispatchInfo.Capture(exception); - if (_firstFatal is null) - _firstFatal = fatal; - else - (_additionalFatal ??= []).Add(exception); - - TryCloseHandlingCore(); - } - } - - internal void TryCloseHandling() - { - lock (_gate) - TryCloseHandlingCore(); - } - - internal async Task JoinAsync() - { - Task? dispatch; - lock (_gate) - { - TryCloseHandlingCore(); - dispatch = _dispatchCompletion?.Task; - } - - if (dispatch is not null) - await dispatch.ConfigureAwait(false); - - Completion completion; - lock (_gate) - { - TryCloseHandlingCore(); - _completed = true; - completion = new Completion( - _invocationCancelled, - _firstFatal, - _additionalFatal); - } - - completion.LogAdditional(_logger); - - if (completion.InvocationCancelled) - throw new OperationCanceledException( - "The Lambda invocation was cancelled during item processing.", - _invocation.CancellationToken); - - if (completion.FirstFatal is not null) - { - completion.FirstFatal.Throw(); - throw new InvalidOperationException("Unreachable"); - } - } - - public void Dispose() - { - if (_disposed) - return; - - _disposed = true; - _invocationRegistration.Dispose(); - _processingSource.Dispose(); - } - - private void OnInvocationTokenCancelled() => RequestProcessingCancellation(true); - - private void RequestProcessingCancellation(bool invocationCancelled) - { - TaskCompletionSource? dispatch = null; - lock (_gate) - { - if (_completed || _handlingClosed) - return; - - if (invocationCancelled) - _invocationCancelled = true; - - _stopRequested = true; - - if (!_cancelRequested) - { - _cancelRequested = true; - _dispatchCompletion = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously); - dispatch = _dispatchCompletion; - } - - TryCloseHandlingCore(); - } - - if (dispatch is not null) - StartDispatch(dispatch); - } - - private void ObserveInvocationCancellationCore(ref TaskCompletionSource? dispatch) - { - if (_handlingClosed || !_invocation.CancellationToken.IsCancellationRequested) - return; - - _invocationCancelled = true; - _stopRequested = true; - - if (_cancelRequested) - return; - - _cancelRequested = true; - _dispatchCompletion = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously); - dispatch = _dispatchCompletion; - } - - private void TryCloseHandlingCore() - { - if (_handlingClosed) - return; - - if (_admitted > 0) - return; - - if (_nextIndex < _itemCount - && !_stopRequested - && _firstFatal is null - && !_invocation.CancellationToken.IsCancellationRequested) - return; - - if (_invocation.CancellationToken.IsCancellationRequested) - { - _invocationCancelled = true; - _stopRequested = true; - } - - _handlingClosed = true; - } - - private void StartDispatch(TaskCompletionSource completion) => - _ = DispatchCancellationAsync(completion); - - private async Task DispatchCancellationAsync(TaskCompletionSource completion) - { - try - { - await _processingSource.CancelAsync().ConfigureAwait(false); - } - catch (Exception ex) - { - RecordFatal(ex); - } - finally - { - completion.TrySetResult(); - } - } - - private readonly struct Completion( - bool invocationCancelled, - ExceptionDispatchInfo? firstFatal, - List? additionalFatal) - { - internal bool InvocationCancelled { get; } = invocationCancelled; - - internal ExceptionDispatchInfo? FirstFatal { get; } = firstFatal; - - internal void LogAdditional(ILogger? logger) - { - if (logger is null || additionalFatal is null) - return; - - foreach (var exception in additionalFatal) - try - { - logger.LogError( - exception, - "Event processor observed an additional failure while draining item work."); - } - catch - { - // Logging must not replace the selected invocation error. - } - } - } - } - - file static class EventProcessorRuntime - { - internal static async Task[]?> RunAsync( - TItem[] items, - int effectiveConcurrency, - IServiceScopeFactory scopeFactory, - EventProcessingState state, - Func>> adapter, - bool collectValues) - { - if (items.Length == 0) - state.TryCloseHandling(); - - var outcomes = collectValues ? new ItemOutcome[items.Length] : null; - var workerCount = Math.Min(items.Length, Math.Max(1, effectiveConcurrency)); - var workers = new Task[workerCount]; - - for (var index = 0; index < workerCount; index++) - workers[index] = RunWorkerAsync(); - - await Task.WhenAll(workers).ConfigureAwait(false); - await state.JoinAsync().ConfigureAwait(false); - - return outcomes; - - async Task RunWorkerAsync() - { - while (state.TryClaim(out var index)) - { - if (state.IsInvocationCancellationLatched) - { - state.CompleteAdmission(); - continue; - } - - AsyncServiceScope scope; - try - { - scope = scopeFactory.CreateAsyncScope(); - } - catch (Exception ex) - { - state.RecordFatal(ex); - state.CompleteAdmission(); - continue; - } - - ItemOutcome outcome = default; - var hasOutcome = false; - - try - { - try - { - outcome = await adapter(items[index], scope.ServiceProvider, state) - .ConfigureAwait(false); - hasOutcome = true; - } - catch (Exception ex) - { - if (!state.TryLatchInvocationCancellation()) - state.RecordFatal(ex); - } - } - finally - { - state.CompleteAdmission(); - } - - try - { - await scope.DisposeAsync().ConfigureAwait(false); - } - catch (Exception ex) - { - state.RecordFatal(ex); - } - - if (collectValues && hasOutcome && outcome.HasValue) - outcomes![index] = outcome; - } + return () => handle(arg0); } } } diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsTypedDelegateAndExplicitGenericMethodGroupBindings#MinimalLambda.EventHandlers.g.verified.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsTypedDelegateAndExplicitGenericMethodGroupBindings#MinimalLambda.EventHandlers.g.verified.cs new file mode 100644 index 00000000..203524ee --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsTypedDelegateAndExplicitGenericMethodGroupBindings#MinimalLambda.EventHandlers.g.verified.cs @@ -0,0 +1,86 @@ +//HintName: MinimalLambda.EventHandlers.g.cs +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +#nullable enable + +namespace System.Runtime.CompilerServices +{ + using System.CodeDom.Compiler; + + [global::System.CodeDom.Compiler.GeneratedCode("MinimalLambda.SourceGenerators", "REPLACED")] + [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] + file sealed class InterceptsLocationAttribute : Attribute + { + public InterceptsLocationAttribute(int version, string data) { } + } +} + +namespace MinimalLambda.Generated +{ + using System; + using System.Runtime.CompilerServices; + using System.Threading.Tasks; + using Microsoft.Extensions.DependencyInjection; + using MinimalLambda.Builder; + using MinimalLambda.Runtime; + + [global::System.CodeDom.Compiler.GeneratedCode("MinimalLambda.SourceGenerators", "REPLACED")] + file static class GeneratedEventProcessorExtensions + { + [InterceptsLocation(1, "REPLACED")] + internal static ILambdaInvocationBuilder MapEventHandlerInterceptor0( + this ILambdaInvocationBuilder application, + global::System.Func> split, + global::System.Func> handle, + global::System.Func, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) + { + return EventHandlerRegistration.Register( + application, + split, + handle, + Bind, + createResponse); + + Func> Bind( + global::Item item, + IServiceProvider serviceProvider, + IEventProcessingContext processingContext) + { + var arg0 = item; + var arg1 = serviceProvider.GetRequiredService(); + return () => handle(arg0, arg1); + } + } + [InterceptsLocation(1, "REPLACED")] + internal static ILambdaInvocationBuilder MapEventHandlerInterceptor1( + this ILambdaInvocationBuilder application, + global::System.Func> split, + global::System.Func> handle, + global::System.Func, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) + { + return EventHandlerRegistration.Register( + application, + split, + handle, + Bind, + createResponse); + + Func> Bind( + global::Item item, + IServiceProvider serviceProvider, + IEventProcessingContext processingContext) + { + var arg0 = item; + var arg1 = serviceProvider.GetRequiredService(); + return () => handle(arg0, arg1); + } + } + } +} diff --git a/tests/MinimalLambda.UnitTests/Core/Runtime/EventHandlerRegistrationTests.cs b/tests/MinimalLambda.UnitTests/Core/Runtime/EventHandlerRegistrationTests.cs new file mode 100644 index 00000000..fb13ed28 --- /dev/null +++ b/tests/MinimalLambda.UnitTests/Core/Runtime/EventHandlerRegistrationTests.cs @@ -0,0 +1,367 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +namespace MinimalLambda.UnitTests.Core.Runtime; + +public class EventHandlerRegistrationTests +{ + [Fact] + public async Task N1RegistersOrdinaryHandlerAndRunsMiddleware() + { + // Arrange + var calls = new List(); + await using var app = LambdaApplication.CreateBuilder().Build(); + Func handle = _ => + { + calls.Add("handle"); + return Task.CompletedTask; + }; + + EventHandlerRegistration.Register( + app, + (batch, _) => batch.Items, + handle, + (item, _, _) => () => handle(item)); + app.UseMiddleware(async (context, next) => + { + calls.Add("before"); + await next(context); + calls.Add("after"); + }); + + var harness = CreateHarness(app, new Batch([new Item(1)])); + var handler = app.Build(); + + // Act + await handler(harness.Context); + + // Assert + calls.Should().Equal("before", "handle", "after"); + } + + [Fact] + public async Task N2BuildsResponseFromSuccessfulSourceItems() + { + // Arrange + Response? captured = null; + await using var app = LambdaApplication.CreateBuilder().Build(); + Func handle = _ => Task.CompletedTask; + EventHandlerRegistration.Register( + app, + (batch, _) => batch.Items, + handle, + (item, _, _) => () => handle(item), + (items, _) => captured = new Response(items.Select(item => item.Id).ToArray())); + + var responseFeature = Substitute.For>(); + var harness = CreateHarness( + app, + new Batch([new Item(1), new Item(2)]), + responseFeature); + + // Act + await app.Build()(harness.Context); + + // Assert + captured!.Ids.Should().Equal(1, 2); + harness.ResponseFeature.Received(1).SetResponse(captured); + } + + [Fact] + public async Task N3BuildsResponseFromMappedFailures() + { + // Arrange + Response? captured = null; + await using var app = LambdaApplication.CreateBuilder().Build(); + Func handle = item => item.Id == 2 + ? Task.FromException(new InvalidOperationException("item failed")) + : Task.CompletedTask; + EventHandlerRegistration.Register( + app, + (batch, _) => batch.Items, + handle, + (item, _, _) => () => handle(item), + (item, exception, _) => item.Id + exception.Message.Length, + (failures, _) => captured = new Response(failures.ToArray())); + + var responseFeature = Substitute.For>(); + var harness = CreateHarness( + app, + new Batch([new Item(1), new Item(2)]), + responseFeature); + + // Act + await app.Build()(harness.Context); + + // Assert + captured!.Ids.Should().Equal(2 + "item failed".Length); + harness.ResponseFeature.Received(1).SetResponse(captured); + } + + [Fact] + public async Task R1BuildsResponseFromSuccessfulHandlerResults() + { + // Arrange + Response? captured = null; + await using var app = LambdaApplication.CreateBuilder().Build(); + Func> handle = item => Task.FromResult(item.Id * 2); + EventHandlerRegistration.Register( + app, + (batch, _) => batch.Items, + handle, + (item, _, _) => () => handle(item), + (results, _) => captured = new Response(results.ToArray())); + + var responseFeature = Substitute.For>(); + var harness = CreateHarness( + app, + new Batch([new Item(3), new Item(4)]), + responseFeature); + + // Act + await app.Build()(harness.Context); + + // Assert + captured!.Ids.Should().Equal(6, 8); + harness.ResponseFeature.Received(1).SetResponse(captured); + } + + [Fact] + public async Task R2BuildsResponseFromSuccessfulAndMappedResults() + { + // Arrange + Response? captured = null; + await using var app = LambdaApplication.CreateBuilder().Build(); + Func> handle = item => item.Id == 2 + ? Task.FromException(new InvalidOperationException("item failed")) + : Task.FromResult(item.Id * 2); + EventHandlerRegistration.Register( + app, + (batch, _) => batch.Items, + handle, + (item, _, _) => () => handle(item), + (item, exception, _) => item.Id + exception.Message.Length, + (results, _) => captured = new Response(results.ToArray())); + + var responseFeature = Substitute.For>(); + var harness = CreateHarness( + app, + new Batch([new Item(1), new Item(2), new Item(3)]), + responseFeature); + + // Act + await app.Build()(harness.Context); + + // Assert + captured!.Ids.Should().Equal(2, 2 + "item failed".Length, 6); + harness.ResponseFeature.Received(1).SetResponse(captured); + } + + [Fact] + public void NullArgumentsFailBeforeReadingBuilderServices() + { + // Arrange + var split = (Batch batch, ILambdaInvocationContext _) => batch.Items; + Func handle = _ => Task.CompletedTask; + Func> bind = (item, _, _) => + () => handle(item); + Func onError = (_, _, _) => 0; + Func, ILambdaInvocationContext, Response> valueResponse = (values, _) => + new Response(values.ToArray()); + var builder = Substitute.For(); + + // Act / Assert + AssertNullArgument( + () => EventHandlerRegistration.Register(null!, split, handle, bind), + "application"); + AssertNullArgument( + () => EventHandlerRegistration.Register(builder, null!, handle, bind), + "split"); + AssertNullArgument( + () => EventHandlerRegistration.Register(builder, split, null!, bind), + "handle"); + AssertNullArgument( + () => EventHandlerRegistration.Register(builder, split, handle, null!), + "bind"); + AssertNullArgument( + () => EventHandlerRegistration.Register( + builder, + split, + handle, + bind, + null!), + "createResponse"); + AssertNullArgument( + () => EventHandlerRegistration.Register( + builder, + split, + handle, + bind, + null!, + valueResponse), + "onError"); + AssertNullArgument( + () => EventHandlerRegistration.Register( + builder, + split, + handle, + bind, + onError, + null!), + "createResponse"); + Func>> resultBind = + (item, _, _) => () => Task.FromResult(item.Id); + Func> resultHandle = item => Task.FromResult(item.Id); + AssertNullArgument( + () => EventHandlerRegistration.Register( + builder, + split, + resultHandle, + resultBind, + null!), + "createResponse"); + AssertNullArgument( + () => EventHandlerRegistration.Register( + builder, + split, + resultHandle, + resultBind, + null!, + valueResponse), + "onError"); + AssertNullArgument( + () => EventHandlerRegistration.Register( + builder, + split, + resultHandle, + resultBind, + onError, + null!), + "createResponse"); + + builder.ReceivedCalls().Should().BeEmpty(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ResponseFeatureErrorsOccurAfterResponseConstruction(bool useWrongFeature) + { + // Arrange + var responseCalls = 0; + await using var app = LambdaApplication.CreateBuilder().Build(); + Func handle = _ => Task.CompletedTask; + EventHandlerRegistration.Register( + app, + (batch, _) => batch.Items, + handle, + (item, _, _) => () => handle(item), + (items, _) => + { + responseCalls++; + return new Response(items.Select(item => item.Id).ToArray()); + }); + + var context = useWrongFeature + ? CreateHarness( + app, + new Batch([new Item(1)]), + Substitute.For>()) + .Context + : CreateHarness(app, new Batch([new Item(1)])).Context; + + // Act + var act = () => app.Build()(context); + + // Assert + await act + .Should() + .ThrowAsync() + .WithMessage("*Response*feature*"); + responseCalls.Should().Be(1); + } + + [Fact] + public async Task ReadsOptionsOnceWhenRegistrationCapturesRuntime() + { + // Arrange + var options = new CountingOptions(new EventHandlerOptions()); + var builder = LambdaApplication.CreateBuilder(); + builder.Services.AddSingleton>(options); + await using var app = builder.Build(); + Func handle = _ => Task.CompletedTask; + EventHandlerRegistration.Register( + app, + (batch, _) => batch.Items, + handle, + (item, _, _) => () => handle(item)); + options.Reads.Should().Be(1); + + // Act + var handler = app.Build(); + await handler(CreateHarness(app, new Batch([new Item(1)])).Context); + await handler(CreateHarness(app, new Batch([new Item(2)])).Context); + + // Assert + options.Reads.Should().Be(1); + } + + private static void AssertNullArgument( + Func action, + string parameterName) => + action.Should().Throw().WithParameterName(parameterName); + + private static Harness CreateHarness( + LambdaApplication app, + Batch batch, + IResponseFeature? responseFeature = null) + { + var features = new DefaultFeatureCollection([]); + features.Set(new TestEventFeature(batch)); + if (responseFeature is not null) + features.Set(responseFeature); + + var context = Substitute.For(); + context.Features.Returns(features); + context.ServiceProvider.Returns(app.Services); + context.CancellationToken.Returns(CancellationToken.None); + context.Items.Returns(new Dictionary()); + + return new Harness(context, responseFeature!); + } + + private sealed record Batch(Item[] Items); + + private sealed record Item(int Id); + + public sealed record Response(int[] Ids); + + public sealed record OtherResponse(string Value); + + private sealed record Harness( + ILambdaInvocationContext Context, + IResponseFeature ResponseFeature); + + private sealed class TestEventFeature(T value) : IEventFeature + { + public T GetEvent(ILambdaInvocationContext context) => value; + + object? IEventFeature.GetEvent(ILambdaInvocationContext context) => value; + } + + private sealed class CountingOptions(EventHandlerOptions value) : IOptions + { + private int _reads; + + public int Reads => _reads; + + public EventHandlerOptions Value + { + get + { + Interlocked.Increment(ref _reads); + return value; + } + } + } +} diff --git a/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorRuntimeTests.cs b/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorRuntimeTests.cs new file mode 100644 index 00000000..f4a00280 --- /dev/null +++ b/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorRuntimeTests.cs @@ -0,0 +1,205 @@ +using System.Collections.ObjectModel; +using Microsoft.Extensions.DependencyInjection; + +namespace MinimalLambda.UnitTests.Core.Runtime; + +public sealed class EventProcessorRuntimeTests +{ + [Fact] + public async Task CollectsMaterializedContributionsInSourceOrder() + { + // Arrange + await using var services = CreateServices(); + var runtime = new EventProcessorRuntime(services); + var context = CreateContext(services, new Batch([new Item(3), new Item(1), new Item(2)])); + var completions = + Enumerable + .Range(1, 3) + .ToDictionary( + id => id, + _ => new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously)); + IEnumerable? captured = null; + + // Act + var run = runtime.RunAsync( + context, + static (batch, _) => batch.Items, + (item, _, _) => () => completions[item.Id].Task, + static (_, task) => ((Task)task).GetAwaiter().GetResult(), + onError: null, + complete: values => captured = values); + completions[2].SetResult(2); + completions[1].SetResult(1); + completions[3].SetResult(3); + await run; + + // Assert + captured.Should().BeOfType>(); + captured.Should().Equal(3, 1, 2); + } + + [Fact] + public async Task DisposesEachItemScopeBeforeCompleting() + { + // Arrange + var tracker = new ScopeTracker(); + await using var services = CreateServices(serviceCollection => + { + serviceCollection.AddSingleton(tracker); + serviceCollection.AddScoped(); + }); + var runtime = new EventProcessorRuntime(services); + var context = CreateContext(services, new Batch([new Item(1), new Item(2), new Item(3)])); + var scopeIds = new List(); + var allScopesDisposedAtCompletion = false; + + // Act + await runtime.RunAsync( + context, + static (batch, _) => batch.Items, + (item, itemServices, _) => + { + scopeIds.Add(itemServices.GetRequiredService().Id); + return static () => Task.CompletedTask; + }, + static (item, _) => item.Id, + onError: null, + complete: _ => allScopesDisposedAtCompletion = + tracker.Created == 3 && tracker.Disposed == 3); + + // Assert + scopeIds.Should().OnlyHaveUniqueItems(); + allScopesDisposedAtCompletion.Should().BeTrue(); + } + + [Fact] + public async Task BindingExceptionFailsInvocationWithoutCallingErrorMapper() + { + // Arrange + await using var services = CreateServices(); + var runtime = new EventProcessorRuntime(services); + var context = CreateContext(services, new Batch([new Item(1)])); + var expected = new InvalidOperationException("binding failed"); + var errorCalls = 0; + + // Act + var act = () => runtime.RunAsync( + context, + static (batch, _) => batch.Items, + (_, _, _) => throw expected, + static (item, _) => item.Id, + (_, _, _) => + { + errorCalls++; + return -1; + }, + complete: _ => { }); + + // Assert + var exception = await act.Should().ThrowAsync(); + exception.Which.Should().BeSameAs(expected); + errorCalls.Should().Be(0); + } + + [Fact] + public async Task SynchronousHandlerExceptionIsMapped() + { + // Arrange + await using var services = CreateServices(); + var runtime = new EventProcessorRuntime(services); + var context = CreateContext(services, new Batch([new Item(4)])); + var expected = new InvalidOperationException("handler failed"); + var contributions = new List(); + + // Act + await runtime.RunAsync( + context, + static (batch, _) => batch.Items, + (_, _, _) => () => throw expected, + static (item, _) => item.Id, + (item, exception, _) => + { + exception.Should().BeSameAs(expected); + return -item.Id; + }, + values => contributions.AddRange(values)); + + // Assert + contributions.Should().Equal(-4); + } + + [Fact] + public async Task NullHandlerTaskFailsInvocationWithoutCallingErrorMapper() + { + // Arrange + await using var services = CreateServices(); + var runtime = new EventProcessorRuntime(services); + var context = CreateContext(services, new Batch([new Item(1)])); + var errorCalls = 0; + + // Act + var act = () => runtime.RunAsync( + context, + static (batch, _) => batch.Items, + static (_, _, _) => static () => null!, + static (item, _) => item.Id, + (_, _, _) => + { + errorCalls++; + return -1; + }, + complete: _ => { }); + + // Assert + await act.Should().ThrowAsync().WithMessage("*null task*"); + errorCalls.Should().Be(0); + } + + private static ServiceProvider CreateServices(Action? configure = null) + { + var services = new ServiceCollection(); + services.AddOptions(); + configure?.Invoke(services); + return services.BuildServiceProvider(); + } + + private static ILambdaInvocationContext CreateContext( + IServiceProvider services, + TEvent value) + { + var features = new DefaultFeatureCollection([]); + features.Set(new TestEventFeature(value)); + var context = Substitute.For(); + context.Features.Returns(features); + context.ServiceProvider.Returns(services); + context.CancellationToken.Returns(CancellationToken.None); + context.Items.Returns(new Dictionary()); + return context; + } + + private sealed record Batch(Item[] Items); + + private sealed record Item(int Id); + + private sealed class TestEventFeature(T value) : IEventFeature + { + public T GetEvent(ILambdaInvocationContext context) => value; + + object? IEventFeature.GetEvent(ILambdaInvocationContext context) => value; + } + + private sealed class ScopeTracker + { + public int Created; + + public int Disposed; + } + + private sealed class ScopeProbe(ScopeTracker tracker) : IDisposable + { + public int Id { get; } = Interlocked.Increment(ref tracker.Created); + + public void Dispose() => Interlocked.Increment(ref tracker.Disposed); + } +} From 22ee3fa92bede45c77a250cb68344e7c94807c56 Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Thu, 29 Oct 2026 16:11:43 -0400 Subject: [PATCH 16/21] refactor: simplify event processor internals --- .../Models/Handlers/EventHandlerMethodInfo.cs | 93 +++---------------- .../Handlers/EventHandlerParameterInfo.cs | 23 +---- .../Templates/MapEventHandler.scriban | 2 +- .../Runtime/EventProcessorRuntime.cs | 8 +- .../Runtime/EventProcessorWorkers.cs | 31 +------ .../Runtime/EventHandlerRegistrationTests.cs | 62 +++++-------- .../Runtime/EventProcessorRuntimeTests.cs | 8 +- 7 files changed, 50 insertions(+), 177 deletions(-) diff --git a/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs index eba74d29..198b0050 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs @@ -26,24 +26,17 @@ internal record EventHandlerCallbackInfo(string Name, string Type); internal record EventHandlerMethodInfo( string InterceptableLocationAttribute, EquatableArray CallbackParameters, - EventHandlerFamily Family, bool HasResponse, bool HasOnError, - bool CollectsValues, - bool CollectsSourceItems, - bool CollectsMappedFailures, bool HandleReturnsResult, string EventType, string ItemType, - string CollectedType, string ValueType, string? ResponseType, EquatableArray HandlerParameters, string HandlerArguments, bool HasAnyFromKeyedServices, LocationInfo MapCallLocation, - LocationInfo HandlerArgumentLocation, - int TreeOrdinal, int SourceSpanStart, EquatableArray DiagnosticInfos, MethodType MethodType = MethodType.MapEventHandler) : IMethodInfo; @@ -61,7 +54,6 @@ internal static EventHandlerMethodInfo Create( var diagnostics = new List(); var method = invocation.TargetMethod; - var compilation = context.SemanticModel.Compilation; var invocationLocation = LocationInfo.Create(context.Node) ?? throw new InvalidOperationException("Event mapping has no source location"); @@ -110,9 +102,6 @@ internal static EventHandlerMethodInfo Create( createResponseArgument is not null); var hasResponse = family is not EventHandlerFamily.N1; var hasOnError = family is EventHandlerFamily.N3 or EventHandlerFamily.R2; - var collectValues = family is not EventHandlerFamily.N1; - var collectsSourceItems = family is EventHandlerFamily.N2; - var collectsMappedFailures = family is EventHandlerFamily.N3; string? collectedType = null; switch (family) @@ -203,15 +192,7 @@ or EventHandlerFamily.N3 ? [] : CreateParameters(handlerMethod, itemType, context, diagnostics); - var valueType = family switch - { - EventHandlerFamily.N1 => "global::System.Object", - EventHandlerFamily.N2 => itemType?.QualifiedNullableName ?? "global::System.Object", - _ => collectedType ?? "global::System.Object", - }; - - var hasAnyKeyed = parameters.Any(parameter => - parameter.Kind is EventHandlerParameterKind.KeyedService); + var hasAnyKeyed = parameters.Any(parameter => parameter.IsKeyedService); var callbackParameters = new List(4); AddCallback(invocation, "split", callbackParameters); @@ -224,17 +205,12 @@ or EventHandlerFamily.N3 return new EventHandlerMethodInfo( InterceptableLocationAttribute: interceptableLocation.Attribute, CallbackParameters: callbackParameters.ToEquatableArray(), - Family: family, HasResponse: hasResponse, HasOnError: hasOnError, - CollectsValues: collectValues, - CollectsSourceItems: collectsSourceItems, - CollectsMappedFailures: collectsMappedFailures, HandleReturnsResult: handleReturnsResult, EventType: eventType?.QualifiedNullableName ?? "global::System.Object", ItemType: itemType?.QualifiedNullableName ?? "global::System.Object", - CollectedType: collectedType ?? "global::System.Object", - ValueType: valueType, + ValueType: collectedType ?? "global::System.Object", ResponseType: responseType, HandlerParameters: parameters.ToEquatableArray(), HandlerArguments: string.Join( @@ -242,10 +218,6 @@ or EventHandlerFamily.N3 parameters.Select(parameter => $"arg{parameter.Ordinal}")), HasAnyFromKeyedServices: hasAnyKeyed, MapCallLocation: invocationLocation, - HandlerArgumentLocation: handlerArgumentLocation, - TreeOrdinal: DurableMethodInfoExtensions.GetTreeOrdinal( - context.Node.SyntaxTree, - compilation), SourceSpanStart: context.Node.SpanStart, DiagnosticInfos: diagnostics.ToEquatableArray()); } @@ -302,7 +274,7 @@ private static List CreateParameters( ValidateAccessibleType(parameter.Type, parameter.Name, location, parameterDiagnostics); - var isEventAttribute = IsEventAttribute(parameter, context); + var isEventAttribute = parameter.IsFromEvent(context); var isServiceAttribute = parameter.IsServiceBindingAttribute(context); if (isEventAttribute) @@ -312,15 +284,11 @@ private static List CreateParameters( location, $"[FromEvent] {parameter.Name}")); - var kind = EventHandlerParameterKind.Service; var assignment = string.Empty; - var isOptional = parameter.IsOptional - || parameter.NullableAnnotation == NullableAnnotation.Annotated; - string? keyedKey = null; + var isKeyedService = false; if (index == 0) { - kind = EventHandlerParameterKind.Item; assignment = "item"; if (isServiceAttribute) parameterDiagnostics.Add( @@ -343,7 +311,6 @@ private static List CreateParameters( WellKnownType.Amazon_Lambda_Core_ILambdaContext, WellKnownType.MinimalLambda_ILambdaInvocationContext)) { - kind = EventHandlerParameterKind.Context; assignment = "processingContext.Invocation"; contextCount++; if (contextCount > 1) @@ -363,7 +330,6 @@ private static List CreateParameters( parameter.Type, WellKnownType.MinimalLambda_IEventProcessingContext)) { - kind = EventHandlerParameterKind.ProcessingContext; assignment = "processingContext"; processingCount++; if (processingCount > 1) @@ -383,7 +349,6 @@ private static List CreateParameters( parameter.Type, WellKnownType.System_Threading_CancellationToken)) { - kind = EventHandlerParameterKind.CancellationToken; assignment = "processingContext.CancellationToken"; tokenCount++; if (tokenCount > 1) @@ -405,10 +370,7 @@ private static List CreateParameters( if (diResult.IsSuccess) { if (diResult.Value!.Key is not null) - { - kind = EventHandlerParameterKind.KeyedService; - keyedKey = diResult.Value.Key; - } + isKeyedService = true; assignment = diResult.Value.Assignment; } @@ -417,16 +379,7 @@ private static List CreateParameters( } parameters.Add( - new EventHandlerParameterInfo( - parameter.Ordinal, - parameter.Name, - parameter.Type.QualifiedNullableName, - kind, - assignment, - isOptional, - keyedKey, - location, - parameterDiagnostics.ToEquatableArray())); + new EventHandlerParameterInfo(parameter.Ordinal, assignment, isKeyedService)); diagnostics.AddRange(parameterDiagnostics); } @@ -502,15 +455,6 @@ private static bool ContainsTypeParameter(ITypeSymbol type) => _ => false, }; - private static bool IsEventAttribute(IParameterSymbol parameter, GeneratorContext context) => - parameter - .GetAttributes() - .Any(attribute => attribute.AttributeClass is not null - && context.WellKnownTypes.IsType( - attribute.AttributeClass, - WellKnownType.MinimalLambda_Builder_EventAttribute, - WellKnownType.MinimalLambda_Builder_FromEventAttribute)); - private static bool IsStream(ITypeSymbol type, GeneratorContext context) => context.WellKnownTypes.IsType(type, WellKnownType.System_IO_Stream); @@ -588,7 +532,7 @@ private static Dictionary GetGenericTypes(IMethodSymbol met case IDelegateCreationOperation delegateCreation: return Resolve(delegateCreation.Target); case IFieldReferenceOperation { Field.IsReadOnly: true } field - when GetFieldInitializerOperation( + when GetVariableInitializerOperation( field.Field, semanticModel.Compilation, cancellationToken) is { } initializer: @@ -603,7 +547,7 @@ when GetFieldInitializerOperation( return null; } - return GetLocalInitializerOperation( + return GetVariableInitializerOperation( local.Local, semanticModel.Compilation, cancellationToken) is { } localInitializer @@ -623,11 +567,11 @@ when GetFieldInitializerOperation( } } - private static IOperation? GetLocalInitializerOperation( - ILocalSymbol local, + private static IOperation? GetVariableInitializerOperation( + ISymbol variable, Compilation compilation, CancellationToken cancellationToken) => - local + variable .DeclaringSyntaxReferences .Select(reference => reference.GetSyntax(cancellationToken)) .OfType() @@ -690,21 +634,6 @@ private static bool HasAdditionalWrite( return false; } - private static IOperation? GetFieldInitializerOperation( - IFieldSymbol field, - Compilation compilation, - CancellationToken cancellationToken) => - field - .DeclaringSyntaxReferences - .Select(reference => reference.GetSyntax(cancellationToken)) - .OfType() - .Where(declarator => declarator.Initializer is not null) - .Select(declarator => - compilation - .GetSemanticModel(declarator.SyntaxTree) - .GetOperation(declarator.Initializer!.Value, cancellationToken)) - .FirstOrDefault(operation => operation is not null); - private static LocationInfo GetParameterLocation( IParameterSymbol parameter, IMethodSymbol method) diff --git a/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerParameterInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerParameterInfo.cs index b8b82da4..e1e9d177 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerParameterInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerParameterInfo.cs @@ -1,24 +1,3 @@ -using LayeredCraft.SourceGeneratorTools.Types; - namespace MinimalLambda.SourceGenerators.Models; -internal enum EventHandlerParameterKind -{ - Item, - Context, - ProcessingContext, - CancellationToken, - Service, - KeyedService, -} - -internal record EventHandlerParameterInfo( - int Ordinal, - string Name, - string Type, - EventHandlerParameterKind Kind, - string Assignment, - bool IsOptional, - string? KeyedServiceKey, - LocationInfo Location, - EquatableArray DiagnosticInfos); +internal record EventHandlerParameterInfo(int Ordinal, string Assignment, bool IsKeyedService); diff --git a/src/MinimalLambda.SourceGenerators/Templates/MapEventHandler.scriban b/src/MinimalLambda.SourceGenerators/Templates/MapEventHandler.scriban index 2a6a91ac..d1e7a6a5 100644 --- a/src/MinimalLambda.SourceGenerators/Templates/MapEventHandler.scriban +++ b/src/MinimalLambda.SourceGenerators/Templates/MapEventHandler.scriban @@ -47,7 +47,7 @@ namespace MinimalLambda.Generated onError{{ end }}{{ if call.has_response }}, createResponse{{ end }}); - Func<{{ if call.handle_returns_result }}Task<{{ call.collected_type }}>{{ else }}Task{{ end }}> Bind( + Func<{{ if call.handle_returns_result }}Task<{{ call.value_type }}>{{ else }}Task{{ end }}> Bind( {{ call.item_type }} item, IServiceProvider serviceProvider, IEventProcessingContext processingContext) diff --git a/src/MinimalLambda/Runtime/EventProcessorRuntime.cs b/src/MinimalLambda/Runtime/EventProcessorRuntime.cs index 97e2ded9..383ed6d1 100644 --- a/src/MinimalLambda/Runtime/EventProcessorRuntime.cs +++ b/src/MinimalLambda/Runtime/EventProcessorRuntime.cs @@ -91,7 +91,7 @@ async Task> Adapt( var invocationToken = processing.Invocation.CancellationToken; invocationToken.ThrowIfCancellationRequested(); if (processing.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; + return default; Task? handlerTask = null; Exception? synchronousFault = null; @@ -123,7 +123,7 @@ async Task> Adapt( invocationToken); if (ex is OperationCanceledException && processing.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; + return default; if (onError is null) throw; @@ -133,7 +133,7 @@ async Task> Adapt( throw new OperationCanceledException( "The Lambda invocation was cancelled while mapping an item error.", invocationToken); - return ItemOutcome.FromMappedValue(mapped); + return ItemOutcome.FromValue(mapped); } if (invocationToken.IsCancellationRequested) @@ -141,7 +141,7 @@ async Task> Adapt( "The Lambda invocation was cancelled while processing an item.", invocationToken); return selectSuccess is null - ? ItemOutcome.NoValue + ? default : ItemOutcome.FromValue(selectSuccess(item, handlerTask!)); } } diff --git a/src/MinimalLambda/Runtime/EventProcessorWorkers.cs b/src/MinimalLambda/Runtime/EventProcessorWorkers.cs index f49124cf..b437f509 100644 --- a/src/MinimalLambda/Runtime/EventProcessorWorkers.cs +++ b/src/MinimalLambda/Runtime/EventProcessorWorkers.cs @@ -2,40 +2,19 @@ namespace MinimalLambda.Runtime; -internal enum ItemExecutionState -{ - Unstarted, - Succeeded, - MappedError, - Cancelled, -} - internal readonly struct ItemOutcome { - private ItemOutcome(ItemExecutionState state, bool hasValue, TValue? value) + private ItemOutcome(TValue? value) { - State = state; - HasValue = hasValue; + HasValue = true; Value = value; } - internal ItemExecutionState State { get; } - internal bool HasValue { get; } internal TValue? Value { get; } - internal static ItemOutcome FromValue(TValue? value) => - new(ItemExecutionState.Succeeded, true, value); - - internal static ItemOutcome FromMappedValue(TValue? value) => - new(ItemExecutionState.MappedError, true, value); - - internal static ItemOutcome NoValue => - new(ItemExecutionState.Succeeded, false, default); - - internal static ItemOutcome Cancelled => - new(ItemExecutionState.Cancelled, false, default); + internal static ItemOutcome FromValue(TValue? value) => new(value); } internal static class EventProcessorWorkers @@ -86,7 +65,6 @@ async Task RunWorkerAsync() } ItemOutcome outcome = default; - var hasOutcome = false; try { @@ -94,7 +72,6 @@ async Task RunWorkerAsync() { outcome = await adapter(items[index], scope.ServiceProvider, state) .ConfigureAwait(false); - hasOutcome = true; } catch (Exception ex) { @@ -116,7 +93,7 @@ async Task RunWorkerAsync() state.RecordFatal(ex); } - if (collectValues && hasOutcome && outcome.HasValue) + if (collectValues && outcome.HasValue) outcomes![index] = outcome; } } diff --git a/tests/MinimalLambda.UnitTests/Core/Runtime/EventHandlerRegistrationTests.cs b/tests/MinimalLambda.UnitTests/Core/Runtime/EventHandlerRegistrationTests.cs index fb13ed28..4bfc1ef8 100644 --- a/tests/MinimalLambda.UnitTests/Core/Runtime/EventHandlerRegistrationTests.cs +++ b/tests/MinimalLambda.UnitTests/Core/Runtime/EventHandlerRegistrationTests.cs @@ -29,11 +29,11 @@ public async Task N1RegistersOrdinaryHandlerAndRunsMiddleware() calls.Add("after"); }); - var harness = CreateHarness(app, new Batch([new Item(1)])); + var context = CreateContext(app, new Batch([new Item(1)])); var handler = app.Build(); // Act - await handler(harness.Context); + await handler(context); // Assert calls.Should().Equal("before", "handle", "after"); @@ -54,17 +54,14 @@ public async Task N2BuildsResponseFromSuccessfulSourceItems() (items, _) => captured = new Response(items.Select(item => item.Id).ToArray())); var responseFeature = Substitute.For>(); - var harness = CreateHarness( - app, - new Batch([new Item(1), new Item(2)]), - responseFeature); + var context = CreateContext(app, new Batch([new Item(1), new Item(2)]), responseFeature); // Act - await app.Build()(harness.Context); + await app.Build()(context); // Assert captured!.Ids.Should().Equal(1, 2); - harness.ResponseFeature.Received(1).SetResponse(captured); + responseFeature.Received(1).SetResponse(captured); } [Fact] @@ -85,17 +82,14 @@ public async Task N3BuildsResponseFromMappedFailures() (failures, _) => captured = new Response(failures.ToArray())); var responseFeature = Substitute.For>(); - var harness = CreateHarness( - app, - new Batch([new Item(1), new Item(2)]), - responseFeature); + var context = CreateContext(app, new Batch([new Item(1), new Item(2)]), responseFeature); // Act - await app.Build()(harness.Context); + await app.Build()(context); // Assert captured!.Ids.Should().Equal(2 + "item failed".Length); - harness.ResponseFeature.Received(1).SetResponse(captured); + responseFeature.Received(1).SetResponse(captured); } [Fact] @@ -113,17 +107,14 @@ public async Task R1BuildsResponseFromSuccessfulHandlerResults() (results, _) => captured = new Response(results.ToArray())); var responseFeature = Substitute.For>(); - var harness = CreateHarness( - app, - new Batch([new Item(3), new Item(4)]), - responseFeature); + var context = CreateContext(app, new Batch([new Item(3), new Item(4)]), responseFeature); // Act - await app.Build()(harness.Context); + await app.Build()(context); // Assert captured!.Ids.Should().Equal(6, 8); - harness.ResponseFeature.Received(1).SetResponse(captured); + responseFeature.Received(1).SetResponse(captured); } [Fact] @@ -144,17 +135,17 @@ public async Task R2BuildsResponseFromSuccessfulAndMappedResults() (results, _) => captured = new Response(results.ToArray())); var responseFeature = Substitute.For>(); - var harness = CreateHarness( + var context = CreateContext( app, new Batch([new Item(1), new Item(2), new Item(3)]), responseFeature); // Act - await app.Build()(harness.Context); + await app.Build()(context); // Assert captured!.Ids.Should().Equal(2, 2 + "item failed".Length, 6); - harness.ResponseFeature.Received(1).SetResponse(captured); + responseFeature.Received(1).SetResponse(captured); } [Fact] @@ -263,12 +254,11 @@ public async Task ResponseFeatureErrorsOccurAfterResponseConstruction(bool useWr }); var context = useWrongFeature - ? CreateHarness( - app, - new Batch([new Item(1)]), - Substitute.For>()) - .Context - : CreateHarness(app, new Batch([new Item(1)])).Context; + ? CreateContext( + app, + new Batch([new Item(1)]), + Substitute.For>()) + : CreateContext(app, new Batch([new Item(1)])); // Act var act = () => app.Build()(context); @@ -299,8 +289,8 @@ public async Task ReadsOptionsOnceWhenRegistrationCapturesRuntime() // Act var handler = app.Build(); - await handler(CreateHarness(app, new Batch([new Item(1)])).Context); - await handler(CreateHarness(app, new Batch([new Item(2)])).Context); + await handler(CreateContext(app, new Batch([new Item(1)]))); + await handler(CreateContext(app, new Batch([new Item(2)]))); // Assert options.Reads.Should().Be(1); @@ -311,10 +301,10 @@ private static void AssertNullArgument( string parameterName) => action.Should().Throw().WithParameterName(parameterName); - private static Harness CreateHarness( + private static ILambdaInvocationContext CreateContext( LambdaApplication app, Batch batch, - IResponseFeature? responseFeature = null) + IResponseFeature? responseFeature = null) { var features = new DefaultFeatureCollection([]); features.Set(new TestEventFeature(batch)); @@ -327,7 +317,7 @@ private static Harness CreateHarness( context.CancellationToken.Returns(CancellationToken.None); context.Items.Returns(new Dictionary()); - return new Harness(context, responseFeature!); + return context; } private sealed record Batch(Item[] Items); @@ -338,10 +328,6 @@ public sealed record Response(int[] Ids); public sealed record OtherResponse(string Value); - private sealed record Harness( - ILambdaInvocationContext Context, - IResponseFeature ResponseFeature); - private sealed class TestEventFeature(T value) : IEventFeature { public T GetEvent(ILambdaInvocationContext context) => value; diff --git a/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorRuntimeTests.cs b/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorRuntimeTests.cs index f4a00280..f430eb1d 100644 --- a/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorRuntimeTests.cs +++ b/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorRuntimeTests.cs @@ -1,4 +1,3 @@ -using System.Collections.ObjectModel; using Microsoft.Extensions.DependencyInjection; namespace MinimalLambda.UnitTests.Core.Runtime; @@ -35,8 +34,11 @@ public async Task CollectsMaterializedContributionsInSourceOrder() await run; // Assert - captured.Should().BeOfType>(); - captured.Should().Equal(3, 1, 2); + var contributions = captured.Should().BeAssignableTo>().Subject; + contributions.IsReadOnly.Should().BeTrue(); + var firstEnumeration = contributions.ToArray(); + firstEnumeration.Should().Equal(3, 1, 2); + contributions.Should().Equal(firstEnumeration); } [Fact] From c4f3c31b55d1e413fd4204ff8d6254286109edb5 Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Thu, 29 Oct 2026 16:49:21 -0400 Subject: [PATCH 17/21] refactor: streamline event processor execution --- .../Models/Handlers/EventHandlerMethodInfo.cs | 4 +- .../Runtime/EventProcessorRuntime.cs | 11 +---- .../Runtime/EventProcessorWorkers.cs | 8 ++-- .../EventHandlerDiagnosticTests.cs | 48 +++++++++++-------- .../Core/Runtime/EventProcessorTests.cs | 35 ++++---------- 5 files changed, 45 insertions(+), 61 deletions(-) diff --git a/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs index 198b0050..14cbb452 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs @@ -592,7 +592,9 @@ private static bool HasAdditionalWrite( var declaration = reference.GetSyntax(cancellationToken); var tree = declaration.SyntaxTree; var model = compilation.GetSemanticModel(tree); - foreach (var node in tree.GetRoot(cancellationToken).DescendantNodes()) + var scope = declaration.Ancestors().OfType().FirstOrDefault() + ?? (SyntaxNode)tree.GetRoot(cancellationToken); + foreach (var node in scope.DescendantNodes()) { if (node is not IdentifierNameSyntax identifier || identifier.Identifier.ValueText != local.Name) diff --git a/src/MinimalLambda/Runtime/EventProcessorRuntime.cs b/src/MinimalLambda/Runtime/EventProcessorRuntime.cs index 383ed6d1..ea076c51 100644 --- a/src/MinimalLambda/Runtime/EventProcessorRuntime.cs +++ b/src/MinimalLambda/Runtime/EventProcessorRuntime.cs @@ -58,18 +58,11 @@ internal async Task RunAsync( items.Add(enumerator.Current); } - var itemArray = items.ToArray(); context.CancellationToken.ThrowIfCancellationRequested(); - using var state = new EventProcessingState(context, _logger, itemArray.Length); + using var state = new EventProcessingState(context, _logger, items.Count); var outcomes = await EventProcessorWorkers - .RunAsync( - itemArray, - _concurrency, - _scopeFactory, - state, - Adapt, - complete is not null) + .RunAsync(items, _concurrency, _scopeFactory, state, Adapt, complete is not null) .ConfigureAwait(false); if (complete is not null) diff --git a/src/MinimalLambda/Runtime/EventProcessorWorkers.cs b/src/MinimalLambda/Runtime/EventProcessorWorkers.cs index b437f509..d6efd4aa 100644 --- a/src/MinimalLambda/Runtime/EventProcessorWorkers.cs +++ b/src/MinimalLambda/Runtime/EventProcessorWorkers.cs @@ -20,18 +20,18 @@ private ItemOutcome(TValue? value) internal static class EventProcessorWorkers { internal static async Task[]?> RunAsync( - TItem[] items, + List items, int effectiveConcurrency, IServiceScopeFactory scopeFactory, EventProcessingState state, Func>> adapter, bool collectValues) { - if (items.Length == 0) + if (items.Count == 0) state.TryCloseHandling(); - var outcomes = collectValues ? new ItemOutcome[items.Length] : null; - var workerCount = Math.Min(items.Length, Math.Max(1, effectiveConcurrency)); + var outcomes = collectValues ? new ItemOutcome[items.Count] : null; + var workerCount = Math.Min(items.Count, Math.Max(1, effectiveConcurrency)); var workers = new Task[workerCount]; for (var index = 0; index < workerCount; index++) diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs index 786beee3..31a195e9 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs @@ -232,32 +232,40 @@ internal sealed class Item return Verifier.Verify(diagnostics).UseDirectory("Snapshots").DisableDiff(); } - [Fact] - public void ReportsUnresolvedHandlerForReassignedDelegateLocal() + [Theory] + [InlineData("", "", "handle = Handle;")] + [InlineData("{", "}", "handle = Handle;")] + [InlineData("{", "}", "Action reassign = () => handle = Handle;")] + public void ReportsUnresolvedHandlerForReassignedDelegateLocal( + string scopeStart, + string scopeEnd, + string assignment) { var result = RunGenerator( - """ - using System; - using System.Threading.Tasks; - using MinimalLambda; - using MinimalLambda.Builder; + $$""" + using System; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; - var app = LambdaApplication.CreateBuilder().Build(); - Func handle = Handle; - handle = Handle; - app.MapEventHandler( - split: (Batch batch, ILambdaInvocationContext _) => batch.Items, - handle: handle); + {{scopeStart}} + var app = LambdaApplication.CreateBuilder().Build(); + Func handle = Handle; + {{assignment}} + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: handle); - static Task Handle(Item item) => Task.CompletedTask; + static Task Handle(Item item) => Task.CompletedTask; + {{scopeEnd}} - internal sealed class Batch - { - public Item[] Items => []; - } + internal sealed class Batch + { + public Item[] Items => []; + } - internal sealed class Item; - """); + internal sealed class Item; + """); var diagnostic = result.Diagnostics.Should().ContainSingle().Subject; diagnostic.Id.Should().Be("LH0010"); diff --git a/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs b/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs index 75c5f2dd..9a5a1912 100644 --- a/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs +++ b/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs @@ -1961,7 +1961,7 @@ public async Task StreamResultsCarrySequenceNumbersInSourceOrderAndOnlyFailuresS return captured; }); - var harness = CreateStreamHarness( + var harness = CreateHarness( app, new Batch([new Item(1), new Item(2), new Item(3)])); var handler = app.Build(); @@ -2004,7 +2004,7 @@ public async Task StreamResponseUsesLowestFailingSequenceNumberAsCheckpoint() return captured; }); - var harness = CreateStreamHarness( + var harness = CreateHarness( app, new Batch([new Item(1), new Item(2), new Item(3)])); var handler = app.Build(); @@ -2066,27 +2066,13 @@ private static async Task WaitForAsync(Func condition) await Task.Delay(10, timeout.Token); } - private static Harness CreateHarness( + private static Harness CreateHarness( LambdaApplication app, Batch batch, - CancellationTokenSource? invocationCancellation = null) - { - var features = new DefaultFeatureCollection([]); - features.Set(new TestEventFeature(batch)); - var responseFeature = Substitute.For>(); - features.Set(responseFeature); - invocationCancellation ??= new CancellationTokenSource(); + CancellationTokenSource? invocationCancellation = null) => + CreateHarness(app, batch, invocationCancellation); - var context = Substitute.For(); - context.Features.Returns(features); - context.ServiceProvider.Returns(app.Services); - context.CancellationToken.Returns(invocationCancellation.Token); - context.Items.Returns(new Dictionary()); - - return new Harness(context, responseFeature, invocationCancellation); - } - - private static StreamHarness CreateStreamHarness( + private static Harness CreateHarness( LambdaApplication app, Batch batch, CancellationTokenSource? invocationCancellation = null) @@ -2103,15 +2089,10 @@ private static StreamHarness CreateStreamHarness( context.CancellationToken.Returns(invocationCancellation.Token); context.Items.Returns(new Dictionary()); - return new StreamHarness(context, responseFeature, invocationCancellation); + return new Harness(context, responseFeature, invocationCancellation); } - private sealed record Harness( - ILambdaInvocationContext Context, - IResponseFeature ResponseFeature, - CancellationTokenSource InvocationCancellation); - - private sealed record StreamHarness( + private sealed record Harness( ILambdaInvocationContext Context, IResponseFeature ResponseFeature, CancellationTokenSource InvocationCancellation); From 6cbf02b96488ac41925671362061a09c5f23c1be Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Fri, 30 Oct 2026 20:13:55 -0400 Subject: [PATCH 18/21] refactor: extract optional event processing Keep core applications free of event-processing APIs and services. Use complete ordered outcomes so response builders can include skipped and cancelled items in source-specific retry decisions. --- .github/AGENTS.md | 1 + MinimalLambda.Packages.slnf | 3 +- MinimalLambda.sln | 14 +- designs/event-processing-contracts.md | 104 ++ designs/event-processor.md | 208 +-- docs/features/event-processor.md | 361 ++--- docs/features/index.md | 2 +- docs/guides/handler-registration.md | 2 +- ...inimalLambda.Example.EventProcessor.csproj | 1 + .../Program.cs | 46 +- .../README.md | 17 +- scripts/test-package-compatibility.sh | 84 +- skills/minimal-lambda/SKILL.md | 4 +- .../references/event-processor.md | 251 +--- .../AotCompatibility.TestApp.csproj | 4 +- src/AotCompatibility.TestApp/Program.cs | 20 +- .../EventHandlerFactory.cs | 193 +++ .../EventHandlerOptions.cs | 2 +- .../EventHandlerOptionsValidator.cs | 2 +- .../EventItemOutcome.cs | 57 + .../EventProcessingState.cs | 307 +++++ .../EventProcessorRuntime.cs | 125 ++ .../EventProcessorWorkers.cs | 123 ++ .../IEventProcessingContext.cs | 2 +- ...EventHandlerLambdaApplicationExtensions.cs | 251 ++-- .../MinimalLambda.EventProcessing.csproj | 26 + src/MinimalLambda.EventProcessing/README.md | 18 + .../Extensions/ParameterSymbolExtensions.cs | 8 +- .../Models/Handlers/EventHandlerMethodInfo.cs | 100 +- .../SyntaxProviders/HandlerSyntaxProvider.cs | 2 +- .../Templates/MapEventHandler.scriban | 614 +-------- .../WellKnownTypes/WellKnownTypeData.cs | 4 +- .../Extensions/ServiceCollectionExtensions.cs | 6 +- src/MinimalLambda/MinimalLambda.csproj | 3 +- .../EventHandlerRegistrationTests.cs | 106 ++ .../EventProcessorRuntimeTests.cs | 314 +++++ .../EventProcessorTests.cs | 193 ++- ...HandlerLambdaApplicationExtensionsTests.cs | 0 ...malLambda.EventProcessing.UnitTests.csproj | 58 + .../xunit.runner.json | 3 + .../EventHandlerCallbackShapeTests.cs | 62 + .../EventHandlerDiagnosticTests.cs | 133 +- .../EventHandlerDiscoveryTests.cs | 135 +- .../EventHandlerEmitterTests.cs | 88 +- .../GeneratorTestHelpers.cs | 2 + ...alLambda.SourceGenerators.UnitTests.csproj | 1 + ...nTokensAndDiscardedTaskResult.verified.txt | 22 + ...#MinimalLambda.EventHandlers.g.verified.cs | 602 +-------- ...#MinimalLambda.EventHandlers.g.verified.cs | 68 + ...#MinimalLambda.EventHandlers.g.verified.cs | 1168 ++--------------- ...#MinimalLambda.EventHandlers.g.verified.cs | 105 ++ ...ting.UnitTests.EventProcessorLambda.csproj | 4 +- .../Program.cs | 104 +- .../EventProcessorLambdaTests.cs | 74 +- .../ServiceCollectionExtensionsTests.cs | 55 +- .../CoreOnlyConsumer/CoreOnlyConsumer.csproj | 1 + .../CoreOnlyConsumer/Program.cs | 7 + .../EventProcessorConsumer.csproj | 7 +- .../EventProcessorConsumer/Program.cs | 138 +- .../TypedConsumer/Program.cs | 8 + .../TypedConsumer/TypedConsumer.csproj | 1 + 61 files changed, 3203 insertions(+), 3221 deletions(-) create mode 100644 designs/event-processing-contracts.md create mode 100644 src/MinimalLambda.EventProcessing/EventHandlerFactory.cs rename src/{MinimalLambda/Core/Options => MinimalLambda.EventProcessing}/EventHandlerOptions.cs (97%) rename src/{MinimalLambda/Core/Options => MinimalLambda.EventProcessing}/EventHandlerOptionsValidator.cs (93%) create mode 100644 src/MinimalLambda.EventProcessing/EventItemOutcome.cs create mode 100644 src/MinimalLambda.EventProcessing/EventProcessingState.cs create mode 100644 src/MinimalLambda.EventProcessing/EventProcessorRuntime.cs create mode 100644 src/MinimalLambda.EventProcessing/EventProcessorWorkers.cs rename src/{MinimalLambda.Abstractions/Core => MinimalLambda.EventProcessing}/IEventProcessingContext.cs (98%) rename src/{MinimalLambda/Builder/InterceptionTargets => MinimalLambda.EventProcessing}/MapEventHandlerLambdaApplicationExtensions.cs (91%) create mode 100644 src/MinimalLambda.EventProcessing/MinimalLambda.EventProcessing.csproj create mode 100644 src/MinimalLambda.EventProcessing/README.md create mode 100644 tests/MinimalLambda.EventProcessing.UnitTests/EventHandlerRegistrationTests.cs create mode 100644 tests/MinimalLambda.EventProcessing.UnitTests/EventProcessorRuntimeTests.cs rename tests/{MinimalLambda.UnitTests/Core/Runtime => MinimalLambda.EventProcessing.UnitTests}/EventProcessorTests.cs (91%) rename tests/{MinimalLambda.UnitTests/Builder/InterceptionTargets => MinimalLambda.EventProcessing.UnitTests}/MapEventHandlerLambdaApplicationExtensionsTests.cs (100%) create mode 100644 tests/MinimalLambda.EventProcessing.UnitTests/MinimalLambda.EventProcessing.UnitTests.csproj create mode 100644 tests/MinimalLambda.EventProcessing.UnitTests/xunit.runner.json create mode 100644 tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerCallbackShapeTests.cs create mode 100644 tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerDiagnosticTests.SnapshotsDuplicateCancellationTokensAndDiscardedTaskResult.verified.txt create mode 100644 tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsNullableAndOptionalServiceResolution#MinimalLambda.EventHandlers.g.verified.cs create mode 100644 tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsTypedDelegateAndExplicitGenericMethodGroupBindings#MinimalLambda.EventHandlers.g.verified.cs create mode 100644 tests/package-compatibility/CoreOnlyConsumer/CoreOnlyConsumer.csproj create mode 100644 tests/package-compatibility/CoreOnlyConsumer/Program.cs diff --git a/.github/AGENTS.md b/.github/AGENTS.md index 8c531cae..d9dfe5ac 100644 --- a/.github/AGENTS.md +++ b/.github/AGENTS.md @@ -61,6 +61,7 @@ Core packages version synchronously: - `MinimalLambda` - `MinimalLambda.Abstractions` - `MinimalLambda.DurableExecution` +- `MinimalLambda.EventProcessing` - `MinimalLambda.Envelopes` - `MinimalLambda.Envelopes.Alb` - `MinimalLambda.Envelopes.ApiGateway` diff --git a/MinimalLambda.Packages.slnf b/MinimalLambda.Packages.slnf index 6297694f..83d7cb9a 100644 --- a/MinimalLambda.Packages.slnf +++ b/MinimalLambda.Packages.slnf @@ -16,7 +16,8 @@ "src/MinimalLambda.OpenTelemetry/MinimalLambda.OpenTelemetry.csproj", "src/MinimalLambda.Templates/MinimalLambda.Templates.csproj", "src/MinimalLambda.Testing/MinimalLambda.Testing.csproj", - "src/MinimalLambda/MinimalLambda.csproj" + "src/MinimalLambda/MinimalLambda.csproj", + "src/MinimalLambda.EventProcessing/MinimalLambda.EventProcessing.csproj" ] } } diff --git a/MinimalLambda.sln b/MinimalLambda.sln index d5a87daa..f86c41c4 100644 --- a/MinimalLambda.sln +++ b/MinimalLambda.sln @@ -1,4 +1,4 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "examples", "examples", "{B36A84DF-456D-A817-6EDD-3EC3E7F6E11F}" EndProject @@ -109,6 +109,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MinimalLambda.Example.Event EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MinimalLambda.Testing.UnitTests.EventProcessorLambda", "tests\MinimalLambda.Testing.UnitTests\Lambdas\MinimalLambda.Testing.UnitTests.EventProcessorLambda\MinimalLambda.Testing.UnitTests.EventProcessorLambda.csproj", "{5BFFA5F3-9A74-4574-80B5-27968203E2F9}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MinimalLambda.EventProcessing", "src\MinimalLambda.EventProcessing\MinimalLambda.EventProcessing.csproj", "{3D7592CE-9F18-4967-8F11-34C99ADBC454}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MinimalLambda.EventProcessing.UnitTests", "tests\MinimalLambda.EventProcessing.UnitTests\MinimalLambda.EventProcessing.UnitTests.csproj", "{CE4F650D-C942-4695-9CC3-93C9A6BFF78D}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -575,6 +579,14 @@ Global {5BFFA5F3-9A74-4574-80B5-27968203E2F9}.Release|x64.Build.0 = Release|Any CPU {5BFFA5F3-9A74-4574-80B5-27968203E2F9}.Release|x86.ActiveCfg = Release|Any CPU {5BFFA5F3-9A74-4574-80B5-27968203E2F9}.Release|x86.Build.0 = Release|Any CPU + {3D7592CE-9F18-4967-8F11-34C99ADBC454}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3D7592CE-9F18-4967-8F11-34C99ADBC454}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3D7592CE-9F18-4967-8F11-34C99ADBC454}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3D7592CE-9F18-4967-8F11-34C99ADBC454}.Release|Any CPU.Build.0 = Release|Any CPU + {CE4F650D-C942-4695-9CC3-93C9A6BFF78D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CE4F650D-C942-4695-9CC3-93C9A6BFF78D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CE4F650D-C942-4695-9CC3-93C9A6BFF78D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CE4F650D-C942-4695-9CC3-93C9A6BFF78D}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/designs/event-processing-contracts.md b/designs/event-processing-contracts.md new file mode 100644 index 00000000..26b489e2 --- /dev/null +++ b/designs/event-processing-contracts.md @@ -0,0 +1,104 @@ +# Event-processing contracts + +Accepted for ml-ny2.1 on 2026-10-30. The epic's locked decisions are unchanged. + +## Ownership and delivery + +`MinimalLambda.EventProcessing` depends on the matching core version. Public processing types +use `MinimalLambda.EventProcessing`; interception extensions remain in `MinimalLambda.Builder` +for discoverability. The existing core-delivered generator recognizes the optional assembly. +The optional package ships no second analyzer. Core and general abstractions contain no processing APIs, +options registrations, or processing features. All four core TFMs are supported. + +## Outcomes + +`EventItemOutcome` is immutable and contains `Index`, `Item`, `Status`, +`HasValue`, `Value`, and `Exception`. Status is `Succeeded`, `MappedError`, `Skipped`, or +`Cancelled`. Index is zero-based source position. Equal or identical items remain distinct entries. +`HasValue` distinguishes a genuine null contribution from no contribution. `Exception` is set +only for mapped errors. A handler returning a domain failure is still `Succeeded`; only the +application understands domain success. Invocation failure produces no response or outcome callback. + +Split output is materialized once before handlers start. Null enumerables fail the invocation; +nullable items and values are retained. Empty input calls the response builder once with an empty list. +A response builder may return null when its response type allows it; core serializes that typed null normally. +The builder receives `IReadOnlyList>` in source order after all +admitted work and cleanup finish. It may enumerate repeatedly. Unstarted items are `Skipped`; +admitted work interrupted by processing cancellation is `Cancelled`. Successful work remains successful +even if cancellation was requested concurrently. Application code owns acknowledgement and retry. + +## Callback families + +Each mapping takes `Func> split` and an +item-first handler returning `Task` or `Task`. Up to ten additional parameters bind +services or framework values. The five compiler-selected families are: + +| Family | Handler | Mapper | Outcome value | +| --- | --- | --- | --- | +| No response | Task | absent | no response callback | +| Source item | Task | absent | source item on success | +| Failures only | Task | TFailure | value only on mapped errors | +| Results | Task | absent | handler result | +| Results with errors | Task | TResult | handler or mapper result | + +Response callbacks are synchronous `Func>, +ILambdaInvocationContext, TResponse>`. Error callbacks are synchronous +`Func`. Awaitable mapper contributions, +nested handler task results, and awaitable responses are rejected with an actionable generator +diagnostic. Async error mappers are deliberately unsupported; put async recovery in the handler. +Required callbacks cannot be null. A null task from a handler is an item error eligible for mapping. + +Example response policies: + +```csharp +// Source-item family +createResponse: (outcomes, _) => outcomes.Where(x => x.Status != EventItemStatus.Succeeded) + .Select(x => x.Item.Id).ToArray() +// Failures-only and result families can inspect HasValue before reading Value. +// The no-response family omits both response and error callbacks. +``` + +## Binding, errors, and lifetime + +Each item gets an asynchronous scope, alive through argument resolution, execution, and error mapping. +Scope creation is an invocation failure because no item provider exists. DI resolution, synchronous +handler throws, asynchronous faults, and null handler tasks reach onError with the original exception. +Absent or throwing mappers fail the invocation; mapper failures are never recursively mapped. +Scope disposal always fails the invocation. Drain admitted work and cleanup before propagating errors; +preserve the first fatal exception and log additional failures. Invocation cancellation takes precedence. +Optional nullable services retain null fallback. Declared optional defaults are honored, including keyed +and value-type defaults; generated resolution distinguishes missing services from default-valued services. + +StopProcessing stops admission without cancelling admitted items. CancelProcessing also cancels the +processing token. Invocation cancellation suppresses response construction through cleanup, including +cancellation callback draining. Check immediately before and after the synchronous response builder; +cancellation during construction suppresses storing its response. Once stored, core owns serialization. + +## Factory and generated output + +`EventHandlerFactory.Create` accepts the built `IServiceProvider`, split, the typed wrapper, +optional mapper, and optional response callback. Its five overloads mirror the families above. +Wrappers are `Func` or the corresponding +`Task` shape. The factory validates callbacks and effective options at mapping time, +resolves scope/logging dependencies, and constructs an internal processor once. No required +AddEventProcessing call or processor DI registration exists. Configure is optional. +Configuration failures propagate. Options are copied at mapping time. + +```csharp +ArgumentNullException.ThrowIfNull(handle); +var terminal = EventHandlerFactory.Create( + application.Services, split, HandleItem, onError, createResponse); +application.Handle(terminal); // Reject duplicates before changing provider properties. +// Same conditional provider registration as MapHandler, for Batch and Response only. +return application; + +Task HandleItem(Item item, IServiceProvider itemServices, IEventProcessingContext processing) +{ + var importer = itemServices.GetRequiredKeyedService("primary"); + return handle(item, importer, processing.CancellationToken); +} +``` + +The runtime invokes and awaits HandleItem inside item-error handling. There is no generated binder, +BoundArguments, worker loop, or cancellation state machine. The splitter determines Batch; the final +response callback determines Response. Core serialization and middleware remain unchanged. diff --git a/designs/event-processor.md b/designs/event-processor.md index 4dc3c537..103efd07 100644 --- a/designs/event-processor.md +++ b/designs/event-processor.md @@ -1,195 +1,25 @@ -# Event processor API proposal +# Event-processing design -**Status:** Draft -**Scope:** Public API only +The accepted API and error/cancellation policies are in [event-processing-contracts.md](event-processing-contracts.md). +This replaces the earlier unshipped design. Beads epic `ml-ny2` tracks implementation and validation. -## Context +`MinimalLambda.EventProcessing` owns public mapping contracts, options, outcomes, the generated-code +factory, and internal scheduling/runtime code. It depends on matching core; core has no processing +services or APIs. The existing core analyzer recognizes the optional package and emits one item wrapper. -Lambda receives one event that may contain many independently processable records. SQS is the motivating case: each message may succeed or need retry, while Lambda expects one batch response containing the failed message IDs. +The interceptor calls the public factory with application services and typed callbacks, registers the +returned terminal using `application.Handle`, then conditionally registers normal event/final-response +providers. It rejects duplicate mappings before mutating providers. The splitter selects the full event +type. Intermediate item results never select the response provider. -`MapHandler` handles one Lambda invocation. This API adds a batch layer that splits the event, invokes one handler per item, collects results, and optionally creates the invocation response. +The factory validates effective options at mapping time, resolves scope/logging dependencies, and +constructs the internal processor once. Each invocation gets fresh state. Each admitted item gets an +async scope alive through argument resolution, handler execution, error mapping, and awaited disposal. +Service resolution and handler errors reach onError; creation/disposal failures fail the invocation. -## Goal +Response callbacks receive immutable ordered outcomes for every source position. Skipped and cancelled +items remain visible. Application code decides acknowledgements and retries. Invocation cancellation +remains effective through cleanup and is checked before constructing and storing the response. -Process each item in a Lambda event batch, optionally in parallel, and let an event-source-specific callback build the final Lambda response. - -The processor must not know SQS, Kinesis, DynamoDB Streams, or a response format. - -## API roles - -| Callback | Job | -| --- | --- | -| `split` | Turns the incoming event into source items. | -| `handle` | Processes one source item with injected services. | -| `onError` | Optionally converts an item exception into a value. | -| `createResponse` | Converts collected values into the Lambda response. | - -`onError` receives the source item. It can use source-specific metadata, such as an SQS `MessageId`, before returning a value for `createResponse`. - -## Proposed API - -```csharp -lambda.MapEventHandler( - split: (SqsEnvelope batch, ILambdaInvocationContext _) => - batch.Records, - - handle: async ( - SqsEnvelope.SqsMessageEnvelope item, - DocumentImporter importer) => - { - await importer.ImportAsync(item.BodyContent!); - }, - - onError: (item, exception, ILambdaInvocationContext _) => - new SQSBatchResponse.BatchItemFailure - { - ItemIdentifier = item.MessageId, - }, - - createResponse: (failures, ILambdaInvocationContext _) => - new SQSBatchResponse(failures.ToList())); -``` - -For event sources that do not return a batch response: - -```csharp -lambda.MapEventHandler( - split: (S3Event batch, ILambdaInvocationContext _) => batch.Records, - handle: async (S3Event.S3EventNotificationRecord item, DocumentIndexer indexer) => - { - await indexer.IndexAsync(item.S3.Object.Key); - }); -``` - -For a response after every item succeeds: - -```csharp -lambda.MapEventHandler( - split: (S3Event batch, ILambdaInvocationContext _) => batch.Records, - handle: async (S3Event.S3EventNotificationRecord item, DocumentIndexer indexer) => - { - await indexer.IndexAsync(item.S3.Object.Key); - }, - createResponse: (items, ILambdaInvocationContext _) => - new BatchSummary(items.Count())); -``` - -## Type flow - -Without error mapping: - -```text -TEvent -> IEnumerable -> handle every item -> IEnumerable -> TResponse -``` - -```csharp -Func> split - -Func handle - -Func, ILambdaInvocationContext, TResponse> createResponse -``` - -If a handler throws, `createResponse` is not called. - -With error mapping: - -```text -TEvent -> IEnumerable -> TFailure -> TResponse -``` - -```csharp -Func> split - -Func handle - -Func onError - -Func, - ILambdaInvocationContext, - TResponse> createResponse -``` - -`TItem` is always the first handler parameter. This keeps the processed source record available to `onError`. - -`TFailure` can be any type. SQS may return `SQSBatchResponse.BatchItemFailure`; another source may return an identifier, an error record, or a custom type. `createResponse` receives the collected failures only. - -## Unified item results - -When both `handle` and `onError` produce values for one response builder, they must return the same type: - -```csharp -Func> handle - -Func onError - -Func, ILambdaInvocationContext, TResponse> createResponse -``` - -```text -TEvent -> IEnumerable -> TResult -> IEnumerable -> TResponse -``` - -If `handle` returns `Task` or no value, it does not contribute a result to `createResponse`. The SQS failure example above uses this shape: only `onError` returns `TFailure`. - -If success and failure need different data, use one shared union type for `TResult`: - -```csharp -public abstract record ImportItemResult; - -public sealed record Imported(ImportResult Value) : ImportItemResult; - -public sealed record Retry(SQSBatchResponse.BatchItemFailure Value) : ImportItemResult; -``` - -`handle` returns `Imported`, `onError` returns `Retry`, and `createResponse` accepts `IEnumerable`. - -## Overloads - -Provide handler overloads for zero through ten injected dependencies. The only changing part is the handler delegate: - -```csharp -Func -Func -Func -``` - -Use separate overloads for each meaningful callback combination. Do not require callers to pass `null`. - -```csharp -MapEventHandler(split, handle) -MapEventHandler(split, handle, onError) -MapEventHandler(split, handle, createResponse) -MapEventHandler(split, handle, onError, createResponse) -``` - -`onError` without `createResponse` is an error observer and returns `Task`. The processor invokes it before following the default error policy. - -The response-only overload receives successful source items. The error-and-response overload receives failure values when `handle` has no result. When both callbacks return values, the builder receives their shared result type. - -## Boundaries - -This proposal defines callback signatures and type relationships. It does not yet define: - -- how generated code resolves handler dependencies; -- concurrency, cancellation, or item-service scopes; -- logging, metrics, or exception policy; -- event-source configuration such as SQS `ReportBatchItemFailures`. - -## Static methods - -An inline lambda can infer dependency types. A static method group cannot infer generic dependency parameters from this API: - -```csharp -lambda.MapEventHandler(split, EventHandlers.HandleAsync); -``` - -Static handlers need explicit generic arguments or a typed local delegate. Decide whether that trade-off is acceptable before committing to generic dependency overloads. - -## Not decided - -- `Task` only, or `ValueTask` and synchronous handler overloads. -- Whether `onError` can be asynchronous or receive injected dependencies. -- Default behavior when `onError` is omitted. -- FIFO ordering and stop-on-failure behavior. -- Global and named `EventHandlerOptions` registration through DI. +Core serialization, features, envelopes, and middleware remain unchanged. There is no processing +feature, required service-registration call, generated worker algorithm, or separate binding stage. diff --git a/docs/features/event-processor.md b/docs/features/event-processor.md index 0880bf7f..f75f80f1 100644 --- a/docs/features/event-processor.md +++ b/docs/features/event-processor.md @@ -1,282 +1,155 @@ -# Event Processor +# Event processing -`MapEventHandler` splits one Lambda event into items and processes them concurrently. It replaces -the loop-and-try/catch code most batch handlers write by hand. +Install `MinimalLambda.EventProcessing` to process items from one Lambda event with separate DI +scopes. Core-only applications do not expose these APIs or register processing services. + +```bash +dotnet add package MinimalLambda.EventProcessing +``` ```csharp -builder.Services.AddScoped(); +using MinimalLambda; +using MinimalLambda.Builder; +using MinimalLambda.EventProcessing; +builder.Services.AddScoped(); +await using var lambda = builder.Build(); lambda.MapEventHandler( - split: (S3Event batch, ILambdaInvocationContext _) => batch.Records, - handle: (S3Event.S3EventNotificationRecord item, DocumentImporter importer, CancellationToken token) => - importer.IndexAsync(item.S3.Object.Key, token)); + split: (ImportBatch batch, ILambdaInvocationContext _) => batch.Items, + handle: (ImportDocument item, DocumentImporter importer, CancellationToken token) => + importer.ImportAsync(item.Event, token)); ``` -Registration is source-generated, like `MapHandler`. The generator emits the whole processor, so -there is no runtime reflection and no public runtime bridge. - -## What it is not - -- It is not Lambda invocation concurrency. Item concurrency happens inside one invocation; the - runtime still runs one invocation per execution environment by default. -- It is not a retry engine. Unstarted or cancelled items contribute nothing to the response, and the - processor never invents results for them. -- It is not a task queue. The splitter output is materialized before any handler starts, bounded by - the event size. +No `AddEventProcessing` call or processor registration is required. The package supports the same +.NET target frameworks as core. Its matching core dependency supplies the source generator; the +optional package does not ship another analyzer. ## Callback families -`split` always runs first, once, and serial. It returns `IEnumerable`. - -| Family | Callbacks after `split` | Response input | Error behavior | -| ------ | ------------------------------------- | -------------------------------- | --------------------------------------------- | -| N1 | `handle` | none | An unhandled item error fails the invocation. | -| N2 | `handle`, `createResponse` | successful source items | Any item error prevents the response. | -| N3 | `handle`, `onError`, `createResponse` | values returned by `onError` | Successful items contribute nothing. | -| R1 | `handle`, `createResponse` | successful `TResult` values | Any item error prevents the response. | -| R2 | `handle`, `onError`, `createResponse` | one `TResult` per completed item | Mapped errors contribute a result. | - -`handle` returns `Task` for N1/N2/N3 and `Task` for R1/R2. `onError` is a synchronous value -mapper, not an observer. Log and rethrow inside `handle` when you only want observation. - -Every family has arities 0 through 10 for parameters after the item, using `TD0` through `TD9`: - -```csharp -lambda.MapEventHandler(...); // two extra handler inputs -``` - -The count includes framework parameters. The item is always first. - -## Handler parameters - -`handle` is resolved with a fresh asynchronous DI scope per item: - -- the source item, first; -- `ILambdaInvocationContext` or `ILambdaContext`; -- `IEventProcessingContext`; -- `CancellationToken`, which is the *processing* token; -- anything else from DI, including `[FromServices]` and `[FromKeyedServices]`. - -Each may appear at most once, and at most ten parameters follow the item. Framework parameters -cannot carry service or event attributes. Scopes are disposed after each item exits, and results -must remain valid after disposal. +The splitter runs once and returns `IEnumerable`. The processor materializes it before any +handler starts. Null enumerable results and enumeration failures fail the invocation. + +| Handler | Error mapper | Successful contribution | Response | +| --- | --- | --- | --- | +| `Task` | absent | absent | absent | +| `Task` | absent | source item | required | +| `Task` | `TFailure` | absent | required | +| `Task` | absent | result | required | +| `Task` | `TResult` | result | required | + +`onError` is synchronous `(item, exception, processing) => value`. It maps errors from service +resolution and handler execution. A mapper that throws fails the invocation. Without a mapper, +item errors fail the invocation. Nullable response types may return null for normal core serialization. +A null returned handler task is an item error eligible for mapping. +Async mappers, nested awaitable handler results, and awaitable responses receive a generator diagnostic. +Put asynchronous recovery inside the item handler. + +## Complete outcomes + +Every response callback receives `IReadOnlyList>` plus the invocation +context. There is one immutable outcome per source position, in source order, regardless of completion +order. Duplicate items remain separate. Empty input calls the builder once with an empty list. + +| Property | Meaning | +| --- | --- | +| `Index` | Zero-based source position | +| `Item` | Original source item, including null where the source type allows it | +| `Status` | `Succeeded`, `MappedError`, `Skipped`, or `Cancelled` | +| `HasValue` | A contribution exists, even if its value is null | +| `Value` | Handler, source-item, or mapped contribution | +| `Exception` | Original error for `MappedError`, otherwise null | + +A handler-returned domain failure still has `Succeeded` status. The framework does not interpret +application result types. `Skipped` means the item never started; `Cancelled` means processing +cancellation interrupted admitted work. A successfully completed handler retains its result. + +Applications own acknowledgement and retry. For example, this SQS response includes both mapped +failures and items that never completed: ```csharp lambda.MapEventHandler( split: (SqsEnvelope batch, ILambdaInvocationContext _) => batch.Records, - handle: async Task ( + handle: async Task ( SqsEnvelope.SqsMessageEnvelope item, - OrderProcessor processor, - IEventProcessingContext processing, - CancellationToken token) => - { - if (item.BodyContent is null) - return new Retry(item.MessageId); - - return await processor.ProcessAsync(item.BodyContent, token); - }, - onError: (item, _, _) => new Retry(item.MessageId), - createResponse: (results, _) => new SQSBatchResponse(/* ... */)); -``` - -`split` and `createResponse` keep their explicit `ILambdaInvocationContext` parameter. - -## Ordering and contributions - -Handlers may finish in any order; contributions stay in source order. `createResponse` receives a -materialized, repeatably enumerable, read-only collection. Duplicate items stay separate entries. -An empty event still calls the response builder once, with an empty collection. - -Only completed contributions reach the builder: - -- N1 never builds a response; -- N2 supplies items whose handlers succeeded; -- N3 supplies only `onError` values; -- R1 and R2 supply one `TResult` per completed item, mapped errors included. - -Nullable values are legitimate contributions. Null items are not filtered. - -## Concurrency options - -Concurrency is on by default with a cap of 10. It is captured when the handler is mapped. - -```csharp -builder.Services.Configure(options => -{ - options.MaxConcurrentExecutions = 5; // default 10 - options.EnableConcurrency = false; // force sequential -}); -``` - -`MaxConcurrentExecutions` must be positive in both modes. Invalid values fail before any callback -runs, at application build time. `EnableConcurrency = false` forces sequential execution even when a -larger cap is configured. - -Use sequential processing when order matters, such as FIFO queues or stream shards. For a FIFO -queue, combine `EnableConcurrency = false` with `StopProcessing()` to keep ordered processing: -records completed before the stop commit normally while later records are intentionally abandoned. - -## Stopping and cancelling - -`IEventProcessingContext` is one object per invocation, shared by item handlers and error mappers. - -| Call | New work | Active work | Response | -| ------------------------------------------ | -------- | ------------------------------------------- | ------------------ | -| `StopProcessing()` | blocked | finishes with the current token | may still be built | -| `CancelProcessing()` | blocked | processing token is signalled, then drained | may still be built | -| invocation token cancelled during handling | blocked | processing token is signalled, then drained | suppressed | - -Both calls are thread-safe and idempotent, and stop escalates to cancellation but never reverses. -Calling either after handling completes does nothing. - -```csharp -handle: async (Item item, IEventProcessingContext processing, CancellationToken token) => -{ - if (item.IsPoisonPill) - processing.StopProcessing(); - - await handler.ProcessAsync(item, token); -} -``` - -Handlers receive the *processing* token. Read -`processingContext.Invocation.CancellationToken` when you need the original invocation token. -Cancellation is cooperative: passing the token downstream is what makes work stop. Successful -handlers that finish despite cancellation keep their results. - -Once handling closes, fan-in and response construction add no new framework cancellation checks. -An invocation cancellation observed *during* handling still suppresses the response; one that -arrives later does not invalidate completed work. Completion is not a completeness guarantee: an -absent item is one the processor never produced a result for, not a claim that it was processed. -Cancellation requested during response construction is observed past the handling boundary, so the -completed response is still delivered. - -## Response input limitations - -The processor does not track which items are "missing". A response builder that needs to report -unprocessed identities must do that work in application code, for example by recording identities -inside `onError` or by comparing the response against the original event: - -```csharp -createResponse: (results, context) => - new SQSBatchResponse( - context.GetRequiredEvent().Records - .Select(record => record.MessageId) - .Except(results.OfType().Select(result => result.MessageId)) - .Select(id => new SQSBatchResponse.BatchItemFailure { ItemIdentifier = id }) - .ToList()) -``` - -Treat omission as "no claim", not as "safe to retry". Applications own acknowledgement, idempotency, -and rollback. Retried messages may already have partial side effects. - -## SQS partial batch responses - -Return `SQSBatchResponse` with `ReportBatchItemFailures` enabled on the event source mapping. -Families R2 and N3 fit this shape best: successful messages contribute a success value, mapped -failures contribute a retry value. - -```csharp -lambda.MapEventHandler( - split: (SQSEvent batch, ILambdaInvocationContext _) => batch.Records, - handle: async Task ( - SQSEvent.SQSMessage item, DocumentImporter importer, CancellationToken token) => - { - await importer.ImportAsync(item.Body, token); - return new Success(item.MessageId); - }, - onError: (item, _, _) => new Retry(item.MessageId), - createResponse: (results, _) => new SQSBatchResponse( - results.OfType() - .Select(result => new SQSBatchResponse.BatchItemFailure + OrderImporter importer, + CancellationToken token) => await importer.ImportAsync(item.BodyContent, token), + onError: (item, error, processing) => new Retry(item.MessageId), + createResponse: (outcomes, _) => new SQSBatchResponse( + outcomes + .Where(outcome => outcome.Status != EventItemStatus.Succeeded || outcome.Value is Retry) + .Select(outcome => new SQSBatchResponse.BatchItemFailure { - ItemIdentifier = result.MessageId, + ItemIdentifier = outcome.Item.MessageId, }) .ToList())); ``` -The handler's declared `Task` return type fixes the shared result type. A -`Task` handler is not a `Task` handler. +Configure the SQS event source mapping to report partial batch failures. For FIFO ordering, use +sequential processing and stop when the application decides later records must wait. Include the +failed and unstarted records in the response. For stream sources, construct the source-specific +checkpoint from the complete outcomes. The package never chooses acknowledgements or retries. -## Stream checkpoints (Kinesis and DynamoDB) +## Binding and scopes -Stream sources report a checkpoint, not individual record identities. Each result carries the -record's sequence number, and with `ReportBatchItemFailures` the checkpoint you return is the lowest -failing sequence number. The source resumes from that checkpoint, so already-processed successes -before it are re-delivered and the application must be idempotent. Kinesis and DynamoDB do not -support per-record acknowledgement. +The item is the handler's first argument. Up to ten further parameters bind as follows: -## Choosing the overload +- `ILambdaInvocationContext` or `ILambdaContext` receives the invocation context. +- `IEventProcessingContext` receives shared per-invocation processing controls. +- `CancellationToken` receives the processing token. +- Other arguments resolve from a fresh asynchronous item scope, including required, nullable, + `[FromServices]`, and `[FromKeyedServices]` arguments. -`Task` derives from `Task`, so several families can bind the same lambda. Disambiguate -explicitly: +A declared optional default applies when the service is missing. A registered zero or empty string +is retained. Each framework argument may appear once and cannot have service/event attributes. +The full incoming event type comes from the splitter, not `[FromEvent]` on a handler argument. -- declare the handler return type, `async Task (...) => ...`; -- pass a typed delegate local when using a method group; -- pass `onError` only when you want recovery; -- specify all generic arguments when nothing else works. +The scope remains alive through argument resolution, execution, and error mapping. Scope creation +or disposal failure fails the invocation. The processor stops admission and drains admitted handlers, +cancellation callbacks, and scope cleanup before returning. Return DTOs that remain usable after +scope disposal. -A method group does not supply dependency parameter types for generic inference. This does not -compile (the compiler reports a method-group conversion or type-inference failure, `CS1503` or -`CS0411`): +Typed delegates supply the parameter types used for binding. Attributes on the underlying handler +method still apply when its parameters accept broader types. -```csharp -lambda.MapEventHandler(split, EventHandlers.HandleAsync); // CS0411 -``` +Method groups cannot infer dependency types for these overloads. Use a typed lambda, a typed delegate +local, or explicit generic arguments. A `Task` handler cannot be passed to a no-result family. -Use a typed lambda, a typed delegate local, or explicit generic arguments: +## Options and cancellation -```csharp -Func handle = EventHandlers.HandleAsync; -lambda.MapEventHandler(split, handle); +Defaults enable concurrency with at most ten active items per invocation. Scope disposal counts +against that limit. This is item concurrency inside one invocation. -lambda.MapEventHandler(split, EventHandlers.HandleAsync); +```csharp +builder.Services.Configure(options => +{ + options.EnableConcurrency = false; + options.MaxConcurrentExecutions = 1; +}); ``` -A result-returning handler bound to a no-result overload is a compile error (`LH0011`), not a silent -discard. - -## One handler per run - -`MapEventHandler` consumes the single invocation handler slot, like `MapHandler`. Multiple mapping -sites are allowed and all compile; the error only happens when execution reaches a second mapping. -That keeps conditional registration and multi-mode samples working, while a genuinely duplicated -registration still throws the existing `InvalidOperationException`. +Options are captured and validated when mapping, after `Build()`. The maximum must be positive even +when concurrency is disabled. Configuration and options-validation exceptions propagate before any +callback runs. -## Diagnostics +`StopProcessing()` stops new admissions and lets admitted items finish. `CancelProcessing()` also +cancels the processing token. Both allow a response built from complete outcomes. Repeated calls are +safe. Pass the processing token into cancellable item work. -| ID | Meaning | -| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `LH0008` | Unsupported signature: non-`Task` handler, wrong item type, inaccessible type, `ref`/`out`, stream or awaitable event/response, wrong parameter count. | -| `LH0009` | Unsupported binding: event attribute on the item, duplicate context/token parameters, service attribute on a framework parameter. | -| `LH0010` | Handler cannot be resolved to one analyzable method, typically a reassigned delegate local. | -| `LH0011` | A `Task` handler bound to a no-result overload would discard its result. | +Invocation cancellation is separate and fails the invocation. It remains effective through cleanup. +The processor checks it immediately before response construction and before storing the response, so +cancellation during a synchronous response builder also suppresses its response. Invocation cancellation +takes precedence over concurrent item errors. Once the response is stored, core owns serialization. -## Native AOT - -The processor is generated into the consumer assembly with concrete closed signatures, so it is -trim- and AOT-safe. Add serializer metadata for the event, response, envelope payloads, and any -result type you serialize yourself: - -```csharp -builder.Services.AddLambdaSerializerWithContext(); -builder.Services.ConfigureEnvelopeOptions(options => - options.JsonOptions.TypeInfoResolver = SerializerContext.Default); - -[JsonSerializable(typeof(SQSEvent))] -[JsonSerializable(typeof(SQSBatchResponse))] -[JsonSerializable(typeof(Order))] -internal partial class SerializerContext : JsonSerializerContext; -``` +## Registration and middleware -Intermediate union results only need metadata when they are serialized. +`MapEventHandler` consumes the same terminal-handler slot as `MapHandler`. A second mapping throws +before replacing provider properties. Existing custom providers retain precedence. -## Limits +The generated interceptor creates one `HandleItem(item, itemServices, processing)` wrapper, calls +`EventHandlerFactory.Create(application.Services, ...)`, registers its terminal through `Handle`, +and emits normal event/final-response provider setup. Scheduling and error/cancellation state remain +internal package code. Core middleware, envelope extraction/packing, deserialization, and serialization +use their existing pipeline. Intermediate result types are not registered as response types. -- The event is materialized into memory; item count is bounded by event size, not by an unbounded - task queue. -- Worker count is bounded by `min(itemCount, effectiveConcurrency)`. -- Concurrency does not preserve order. Use `EnableConcurrency = false` for FIFO and ordered stream - processing. -- Cancellation is cooperative and never undoes side effects. Poison pills that repeatedly fail will - repeatedly re-deliver unless the application records progress. +See the [example project](https://github.com/LayeredCraft/minimal-lambda/tree/main/examples/MinimalLambda.Example.EventProcessor) +for all five families. diff --git a/docs/features/index.md b/docs/features/index.md index 89cf9ba4..63ca2847 100644 --- a/docs/features/index.md +++ b/docs/features/index.md @@ -10,7 +10,7 @@ ______________________________________________________________________ ### [Event Processor](./event-processor.md) -`MapEventHandler` splits one event into items and processes them concurrently with a per-item +The optional `MinimalLambda.EventProcessing` package provides `MapEventHandler`, which splits one event into items and processes them concurrently with a per-item asynchronous DI scope. Choose from five callback families for response building, error mapping, and graceful stopping. diff --git a/docs/guides/handler-registration.md b/docs/guides/handler-registration.md index fae9cfb9..0712e277 100644 --- a/docs/guides/handler-registration.md +++ b/docs/guides/handler-registration.md @@ -35,7 +35,7 @@ interface IGreetingService - While you can have multiple `MapHandler` calls in your code, only one can be registered at runtime (see [Multiple MapHandler Calls](#multiple-maphandler-calls) below). - The generated handler feeds into the normal invocation builder, so all middleware, features, and diagnostics apply equally to handlers created via `Handle` or `MapHandler`. -- For batch events, [`MapEventHandler`](event-processor.md) consumes the same single handler slot and splits one event into concurrently processed items. +- For batch events, [`MapEventHandler`](../features/event-processor.md) consumes the same single handler slot and splits one event into concurrently processed items. ## Multiple MapHandler Calls diff --git a/examples/MinimalLambda.Example.EventProcessor/MinimalLambda.Example.EventProcessor.csproj b/examples/MinimalLambda.Example.EventProcessor/MinimalLambda.Example.EventProcessor.csproj index e13a1d9d..e3bec06b 100644 --- a/examples/MinimalLambda.Example.EventProcessor/MinimalLambda.Example.EventProcessor.csproj +++ b/examples/MinimalLambda.Example.EventProcessor/MinimalLambda.Example.EventProcessor.csproj @@ -36,4 +36,5 @@ + \ No newline at end of file diff --git a/examples/MinimalLambda.Example.EventProcessor/Program.cs b/examples/MinimalLambda.Example.EventProcessor/Program.cs index c43f45a7..076376ba 100644 --- a/examples/MinimalLambda.Example.EventProcessor/Program.cs +++ b/examples/MinimalLambda.Example.EventProcessor/Program.cs @@ -1,3 +1,4 @@ +using MinimalLambda.EventProcessing; using Amazon.Lambda.SQSEvents; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -55,27 +56,25 @@ static void RegisterNoResult(LambdaApplication lambda) => handle: ( SqsEnvelope.SqsMessageEnvelope item, DocumentImporter importer, - IEventProcessingContext processing, CancellationToken token) => { if (item.BodyContent is null) return Task.CompletedTask; - if (item.BodyContent.StopProcessing) - processing.StopProcessing(); - return importer.ImportAsync(item.BodyContent, token); }); -// N2: createResponse receives only successfully handled source items, in source order. +// N2: every source position has an outcome; count successful handling. static void RegisterNoResultWithResponse(LambdaApplication lambda) => lambda.MapEventHandler( split: (ImportBatch batch, ILambdaInvocationContext _) => batch.Items, handle: (ImportDocument item, DocumentImporter importer, CancellationToken token) => importer.ImportAsync(item.Event, token), - createResponse: (items, _) => new BatchSummary(items.Count())); + createResponse: (outcomes, _) => + new BatchSummary( + outcomes.Count(outcome => outcome.Status == EventItemStatus.Succeeded))); -// N3: successful items contribute nothing; only mapped failures reach createResponse. +// N3: only mapped errors have values; every source position still has an outcome. static void RegisterNoResultWithFailures(LambdaApplication lambda) => lambda.MapEventHandler( split: (SqsEnvelope batch, ILambdaInvocationContext _) => batch.Records, @@ -88,7 +87,15 @@ item.BodyContent is null : importer.ImportAsync(item.BodyContent, token), onError: (item, _, _) => new SQSBatchResponse.BatchItemFailure { ItemIdentifier = item.MessageId, }, - createResponse: (failures, _) => new SQSBatchResponse(failures.ToList())); + createResponse: (outcomes, _) => new SQSBatchResponse( + outcomes + .Where(outcome => outcome.Status != EventItemStatus.Succeeded) + .Select(outcome => + new SQSBatchResponse.BatchItemFailure + { + ItemIdentifier = outcome.Item.MessageId + }) + .ToList())); // R1: every completed item contributes one TResult; any unhandled error prevents the response. // A typed delegate local supplies dependency types that a bare method group cannot infer. @@ -100,12 +107,15 @@ static void RegisterResults(LambdaApplication lambda) lambda.MapEventHandler( split: (ImportBatch batch, ILambdaInvocationContext _) => batch.Items, handle: handle, - createResponse: (results, _) => - new BatchSummary(results.Count(result => result is Success))); + createResponse: (outcomes, _) => new BatchSummary( + outcomes + .Where(outcome => outcome.HasValue) + .Select(outcome => outcome.Value!) + .Count(result => result is Success))); } // R2: SQS partial batch response. An async lambda block makes the result family unambiguous. -// Stopping omits unstarted items from the response. +// Include unstarted and cancelled items in the application retry response. static void RegisterResultsWithRecovery(LambdaApplication lambda) => lambda.MapEventHandler( split: (SqsEnvelope batch, ILambdaInvocationContext _) => batch.Records, @@ -116,11 +126,15 @@ static void RegisterResultsWithRecovery(LambdaApplication lambda) => CancellationToken token) => await EventHandlers.HandleSqsMessageAsync(item, importer, processing, token), onError: (item, _, _) => new Retry(item.MessageId), - createResponse: (results, _) => new SQSBatchResponse( - results - .OfType() - .Select(result => - new SQSBatchResponse.BatchItemFailure { ItemIdentifier = result.MessageId, }) + createResponse: (outcomes, _) => new SQSBatchResponse( + outcomes + .Where(outcome => + outcome.Status != EventItemStatus.Succeeded || outcome.Value is Retry) + .Select(outcome => + new SQSBatchResponse.BatchItemFailure + { + ItemIdentifier = outcome.Item.MessageId, + }) .ToList())); public sealed record MyEvent(string Message, bool StopProcessing = false); diff --git a/examples/MinimalLambda.Example.EventProcessor/README.md b/examples/MinimalLambda.Example.EventProcessor/README.md index 26cbe0c8..abb5d4d1 100644 --- a/examples/MinimalLambda.Example.EventProcessor/README.md +++ b/examples/MinimalLambda.Example.EventProcessor/README.md @@ -1,20 +1,20 @@ # MinimalLambda.Example.EventProcessor -Sample event-processor registrations. `MapEventHandler` consumes the single invocation handler slot, +Sample registrations for the optional `MinimalLambda.EventProcessing` package. `MapEventHandler` consumes the single invocation handler slot, so this project registers exactly one family per run and selects it with `EVENT_PROCESSOR_SAMPLE`. | Value | Family | Shows | | -------------- | ------ | --------------------------------------------------------------------- | -| `n1` | N1 | per-item DI scope, processing token, `StopProcessing()` | -| `n2` | N2 | `createResponse` from successfully handled source items | +| `n1` | N1 | per-item DI scope and processing token | +| `n2` | N2 | complete source-item outcomes and success counts | | `n3` | N3 | `onError` mapping failures and building an SQS partial batch response | | `r1` | R1 | per-item `TResult` contributions through a typed delegate local | -| `r2` (default) | R2 | success and retry contributions, graceful stop, method-group shape | +| `r2` (default) | R2 | complete outcomes and retries for skipped/cancelled items | ## Program.cs - `RegisterNoResult` - no result, no response. -- `RegisterNoResultWithResponse` - response from completed source items. +- `RegisterNoResultWithResponse` - response from ordered outcomes for every source item. - `RegisterNoResultWithFailures` - successes contribute nothing, failures map to SQS batch item failures. - `RegisterResults` - every completed item contributes one result. @@ -41,3 +41,10 @@ EVENT_PROCESSOR_SAMPLE=r2 dotnet run Deploying an R2/N3 SQS sample requires `ReportBatchItemFailures` on the event source mapping, and the FIFO/SQS limits described in `docs/features/event-processor.md`. + +Response builders receive `IReadOnlyList>`. Check status and +HasValue before using contributions. The SQS examples explicitly retry unstarted/cancelled records. +DI/handler errors reach onError; scope cleanup failure fails the invocation. Invocation cancellation +through cleanup suppresses the response. No required event-processing service registration exists. + +Only R2 demonstrates stopping early; it includes unstarted messages in its retry response. diff --git a/scripts/test-package-compatibility.sh b/scripts/test-package-compatibility.sh index 0433b996..2a459cc6 100755 --- a/scripts/test-package-compatibility.sh +++ b/scripts/test-package-compatibility.sh @@ -141,6 +141,7 @@ pack core-old "$ROOT/src/MinimalLambda/MinimalLambda.csproj" "$OLD_CORE_VERSION" pack abstractions-compatible "$ROOT/src/MinimalLambda.Abstractions/MinimalLambda.Abstractions.csproj" "$CORE_VERSION" pack core-compatible "$ROOT/src/MinimalLambda/MinimalLambda.csproj" "$CORE_VERSION" pack durable "$ROOT/src/MinimalLambda.DurableExecution/MinimalLambda.DurableExecution.csproj" "$DURABLE_VERSION" +pack event "$ROOT/src/MinimalLambda.EventProcessing/MinimalLambda.EventProcessing.csproj" "$CORE_VERSION" python3 - "$FEED" "$OLD_CORE_VERSION" "$CORE_VERSION" "$DURABLE_VERSION" <<'PY' import sys @@ -155,6 +156,7 @@ expected = { f"MinimalLambda.{old}.nupkg": ("MinimalLambda", old, "core"), f"MinimalLambda.Abstractions.{core}.nupkg": ("MinimalLambda.Abstractions", core, "abstractions"), f"MinimalLambda.{core}.nupkg": ("MinimalLambda", core, "core"), + f"MinimalLambda.EventProcessing.{core}.nupkg": ("MinimalLambda.EventProcessing", core, "event"), f"MinimalLambda.DurableExecution.{durable}.nupkg": ("MinimalLambda.DurableExecution", durable, "durable"), } actual = {path.name for path in feed.glob("*.nupkg") if not path.name.endswith(".snupkg")} @@ -213,7 +215,7 @@ for filename, (package_id, version, kind) in expected.items(): f"{generator_assets}/{build_assets}" ) - if kind in {"core", "abstractions"}: + if kind in {"core", "abstractions", "event"}: assert_libs(names, package_id, ("net8.0", "net9.0", "net10.0", "net11.0")) else: assert_libs(names, package_id, ("net10.0",)) @@ -247,6 +249,15 @@ for filename, (package_id, version, kind) in expected.items(): raise AssertionError(f"durable AWS dependency version mismatch: {aws.attrib}") if aws.attrib.get("exclude") != "Build,Analyzers": raise AssertionError(f"durable AWS dependency exclusion mismatch: {aws.attrib}") + elif kind == "event": + if {group.attrib.get("targetFramework") for group in dependency_groups} != {"net8.0", "net9.0", "net10.0", "net11.0"}: + raise AssertionError("event dependency TFMs mismatch") + for group in dependency_groups: + dependencies = children(group, "dependency") + if len(dependencies) != 1 or dependencies[0].attrib.get("id") != "MinimalLambda" or dependencies[0].attrib.get("version") != core: + raise AssertionError("event minimum core dependency mismatch") + if dependencies[0].attrib.get("exclude"): + raise AssertionError("event must propagate core analyzer assets to optional-only consumers") elif kind == "core": if {group.attrib.get("targetFramework") for group in dependency_groups} != { "net8.0", "net9.0", "net10.0", "net11.0" @@ -280,8 +291,8 @@ from xml.etree import ElementTree as ET root = Path(sys.argv[1]) projects = sorted(root.glob("*/*.csproj")) -if len(projects) != 6: - raise SystemExit(f"expected six copied consumer projects, found {len(projects)}") +if len(projects) != 7: + raise SystemExit(f"expected seven copied consumer projects, found {len(projects)}") for project in projects: tree = ET.parse(project) references = [ @@ -289,11 +300,16 @@ for project in projects: for element in tree.iter() if element.tag.rsplit("}", 1)[-1] == "PackageReference" ] - expected = ["MinimalLambda", "MinimalLambda.DurableExecution"] - if project.parent.name != "TaskConsumer": - expected.append("Amazon.Lambda.DurableExecution") - if project.parent.name == "EventProcessorConsumer": - expected.append("Amazon.Lambda.SQSEvents") + if project.parent.name == "CoreOnlyConsumer": + expected = ["MinimalLambda"] + elif project.parent.name == "EventProcessorConsumer": + expected = ["MinimalLambda", "MinimalLambda.EventProcessing", "Amazon.Lambda.SQSEvents"] + else: + expected = ["MinimalLambda", "MinimalLambda.DurableExecution"] + if project.parent.name != "TaskConsumer": + expected.append("Amazon.Lambda.DurableExecution") + if project.parent.name == "TypedConsumer": + expected.append("MinimalLambda.EventProcessing") if references != expected: raise SystemExit(f"{project}: unexpected package references {references}") print("Copied consumers contain package references only.") @@ -327,6 +343,7 @@ PY TYPED="$CONSUMERS/TypedConsumer/TypedConsumer.csproj" TASK="$CONSUMERS/TaskConsumer/TaskConsumer.csproj" EVENT="$CONSUMERS/EventProcessorConsumer/EventProcessorConsumer.csproj" +CORE_ONLY="$CONSUMERS/CoreOnlyConsumer/CoreOnlyConsumer.csproj" OLD="$CONSUMERS/OldCoreConsumer/OldCoreConsumer.csproj" AOT="$CONSUMERS/AotConsumer/AotConsumer.csproj" INVALID="$CONSUMERS/InvalidSignatureConsumer/InvalidSignatureConsumer.csproj" @@ -334,6 +351,7 @@ INVALID="$CONSUMERS/InvalidSignatureConsumer/InvalidSignatureConsumer.csproj" restore_consumer typed "$TYPED" "$CORE_VERSION" restore_consumer task "$TASK" "$CORE_VERSION" restore_consumer event-processor "$EVENT" "$CORE_VERSION" +restore_consumer core-only "$CORE_ONLY" "$CORE_VERSION" restore_consumer invalid-signature "$INVALID" "$CORE_VERSION" python3 - "$NUGET_PACKAGES" "$CORE_VERSION" "$DURABLE_VERSION" \ @@ -352,7 +370,7 @@ for filename in sys.argv[4:]: package_folders = {str(Path(folder.rstrip("/\\")).resolve()) for folder in data["packageFolders"]} if package_folders != {str(packages)}: raise SystemExit(f"{path}: package cache is not isolated: {package_folders}") - expected = {f"MinimalLambda/{core}", f"MinimalLambda.DurableExecution/{durable}"} + expected = {f"MinimalLambda/{core}", f"MinimalLambda.EventProcessing/{core}"} if path.parts[-3] == "EventProcessorConsumer" else {f"MinimalLambda/{core}", f"MinimalLambda.DurableExecution/{durable}"} targets = [value for name, value in data["targets"].items() if name == "net10.0"] if not targets or not any(expected <= set(target) for target in targets): raise SystemExit(f"{path}: wrong MinimalLambda versions for net10.0") @@ -363,6 +381,54 @@ rm -rf "$CONSUMERS/TypedConsumer/obj/generated" "$CONSUMERS/TaskConsumer/obj/gen build_consumer typed "$TYPED" build_consumer task "$TASK" build_consumer event-processor "$EVENT" MinimalLambda.EventHandlers.g.cs +assert_generated_once "$CONSUMERS/TypedConsumer" net10.0 MinimalLambda.EventHandlers.g.cs +build_consumer core-only "$CORE_ONLY" MinimalLambda.InvocationHandlers.g.cs +python3 - "$CONSUMERS/CoreOnlyConsumer/obj/project.assets.json" <<'PYCORE' +import json, sys +assets = json.load(open(sys.argv[1])) +assert not any(name.startswith("MinimalLambda.EventProcessing/") for name in assets["libraries"]) +PYCORE +set +e +dotnet build "$CORE_ONLY" -c Release --no-restore /p:CorePackageVersion="$CORE_VERSION" /p:DefineConstants=EXPECT_EVENT_API >"$LOGS/core-only-negative.log" 2>&1 +core_only_status=$? +set -e +[ "$core_only_status" -ne 0 ] || fail "core-only exposed event APIs" +grep -q 'CS0234' "$LOGS/core-only-negative.log" || fail "core-only negative failed unexpectedly" +for tfm in net8.0 net9.0 net11.0; do + run_logged "build-event-$tfm" dotnet build "$EVENT" -c Release -f "$tfm" --no-restore /p:CorePackageVersion="$CORE_VERSION" + assert_warning_free "$LOGS/build-event-$tfm.log" +done +run_logged run-event dotnet "$CONSUMERS/EventProcessorConsumer/bin/Release/net10.0/EventProcessorConsumer.dll" +# A package-only opt-in must also receive the core-delivered analyzer transitively. +cp -R "$CONSUMERS/EventProcessorConsumer" "$CONSUMERS/OptionalOnlyConsumer" +rm -rf "$CONSUMERS/OptionalOnlyConsumer/bin" "$CONSUMERS/OptionalOnlyConsumer/obj" +python3 - "$CONSUMERS/OptionalOnlyConsumer/EventProcessorConsumer.csproj" <<'PYOPTIONAL' +import sys +from pathlib import Path +from xml.etree import ElementTree as ET +project = Path(sys.argv[1]) +tree = ET.parse(project) +for group in tree.getroot(): + for item in list(group): + if item.tag == "PackageReference" and item.attrib.get("Include") == "MinimalLambda": + group.remove(item) +tree.write(project, encoding="unicode") +PYOPTIONAL +restore_consumer optional-only "$CONSUMERS/OptionalOnlyConsumer/EventProcessorConsumer.csproj" "$CORE_VERSION" +build_consumer optional-only "$CONSUMERS/OptionalOnlyConsumer/EventProcessorConsumer.csproj" MinimalLambda.EventHandlers.g.cs +run_logged run-optional-only dotnet "$CONSUMERS/OptionalOnlyConsumer/bin/Release/net10.0/EventProcessorConsumer.dll" + +set +e +dotnet restore "$EVENT" --configfile "$CONFIG" --force --no-cache /p:CorePackageVersion="$OLD_CORE_VERSION" /p:EventPackageVersion="$CORE_VERSION" >"$LOGS/restore-old-event-core.log" 2>&1 +old_event_status=$? +set -e +[ "$old_event_status" -ne 0 ] || fail "event accepted an old core" +grep -q NU1605 "$LOGS/restore-old-event-core.log" || fail "event minimum-version check failed unexpectedly" +restore_consumer event-aot "$EVENT" "$CORE_VERSION" --runtime "$RID" /p:PublishAot=true +run_logged publish-event-aot dotnet publish "$EVENT" -c Release -f net10.0 -r "$RID" --self-contained true --no-restore /p:CorePackageVersion="$CORE_VERSION" /p:PublishAot=true /p:TrimmerSingleWarn=false /p:UseLdClassicXCodeLinker=false +assert_warning_free "$LOGS/publish-event-aot.log" +run_logged run-event-aot "$CONSUMERS/EventProcessorConsumer/bin/Release/net10.0/$RID/publish/EventProcessorConsumer" + rm -f "$LOGS/build-invalid-signature-net10.0.log" set +e diff --git a/skills/minimal-lambda/SKILL.md b/skills/minimal-lambda/SKILL.md index 4ee26de7..9c5e1676 100644 --- a/skills/minimal-lambda/SKILL.md +++ b/skills/minimal-lambda/SKILL.md @@ -48,7 +48,7 @@ Core pieces: - `LambdaApplication.CreateBuilder()` creates standard .NET host/config/DI defaults. - `MapHandler(...)` registers one ordinary Lambda handler. Source generator intercepts it at compile time. -- `MapEventHandler(...)` registers one batch processor: split the event, run one scope per item +- Optional `MinimalLambda.EventProcessing`: `MapEventHandler(...)` registers one batch processor: split the event, run one scope per item concurrently, then build one response. Read `references/event-processor.md`. - `MapDurableHandler(...)` registers one durable workflow with stricter signature, cancellation, replay, middleware, and serializer rules; read `references/durable-execution.md`. - `[FromEvent]` marks deserialized event payload. Ordinary handlers allow at most one; durable handlers allow zero or one. `IDurableContext` is optional for durable handlers. @@ -91,7 +91,7 @@ Read `references/best-practices.md` before giving architectural advice. Before final answer or patch: - Does code compile with source generation? `MapHandler` has 0 or 1 `[FromEvent]`; `MapDurableHandler` has 0 or 1 `[FromEvent]`, 0 or 1 `IDurableContext`, and returns `Task`/`Task`. -- For batch handlers: `MapEventHandler` family matches the handler return type (no `Task` on a no-result overload), arity is at most 10 after the item, concurrency mode suits the event source, and `createResponse` tolerates an empty collection. +- For batch handlers: `MapEventHandler` family matches the handler return type (no `Task` on a no-result overload), arity is at most 10 after the item, concurrency mode suits the event source, and `createResponse` handles complete ordered outcomes, including skipped/cancelled items and empty input. - Does durable code treat optional root `CancellationToken` as physical invocation cancellation, use SDK operation-callback tokens for durable steps, register explicit serializer roots, and obey replay-safe middleware rules? - Does runtime call only one handler mapping path? - Are packages matched (`MinimalLambda.Testing` same version as `MinimalLambda`)? diff --git a/skills/minimal-lambda/references/event-processor.md b/skills/minimal-lambda/references/event-processor.md index 546eccdf..ed76b55e 100644 --- a/skills/minimal-lambda/references/event-processor.md +++ b/skills/minimal-lambda/references/event-processor.md @@ -1,179 +1,72 @@ -# Event Processor - -Read when the task processes one Lambda event as a batch: SQS/SNS records, S3 records, stream -shards, fan-out per item, per-item DI, partial batch responses (`ReportBatchItemFailures`), -`MapEventHandler`, `IEventProcessingContext`, `EventHandlerOptions`, or `StopProcessing` / -`CancelProcessing`. - -## Portability note - -This reference is self-contained for client-project use. Do not assume MinimalLambda source or tests -exist in the workspace. For repo contributions, read `repo-workflow.md` first. - -## Mental model - -`MapEventHandler` replaces the hand-written loop + `try/catch` in a batch handler. One call: - -1. runs `split` once to materialize items; -2. runs one asynchronous DI scope per item, concurrently; -3. collects contributions in source order; -4. builds one response through `createResponse`. - -It is source-generated. Never add a runtime helper or reflection fallback to replace it. - -`MapEventHandler` consumes the same single invocation handler slot as `MapHandler`. Multiple mapping -sites are fine and all compile; reaching a second mapping for one handler throws at runtime. - -## Signature shape - -```csharp -lambda.MapEventHandler( - split: (SQSEvent batch, ILambdaInvocationContext _) => batch.Records, - handle: (SQSEvent.SQSMessage item, IOrderService service, CancellationToken token) => - service.HandleAsync(item, token)); -``` - -- `split`: `Func>`, called once, serial. -- `handle`: item first. Returns `Task` (N1/N2/N3) or `Task` (R1/R2). -- `onError`: synchronous value mapper, `(item, exception, IEventProcessingContext) => TValue`. - Present in N3/R2 only. -- `createResponse`: `(IEnumerable, ILambdaInvocationContext) => TResponse`. -- Arities 0-10 after the item, via `TD0`-`TD9`. Framework parameters count toward ten. - -Handler parameters after the item: `ILambdaInvocationContext`/`ILambdaContext`, -`IEventProcessingContext`, `CancellationToken` (the processing token), then anything from DI -(`[FromServices]`, `[FromKeyedServices]`). Each framework parameter may appear once. - -## Families - -| Family | Callbacks | Response input | Unhandled item error | -| ------ | ------------------------------------- | -------------------------------- | -------------------- | -| N1 | `handle` | none | fails invocation | -| N2 | `handle`, `createResponse` | successful source items | fails, no response | -| N3 | `handle`, `onError`, `createResponse` | `onError` values | mapped values | -| R1 | `handle`, `createResponse` | successful `TResult` | fails, no response | -| R2 | `handle`, `onError`, `createResponse` | one `TResult` per completed item | mapped | - -Pick N1 when nothing is returned. Pick N3/R2 when you need a partial response. Never bind a -`Task` handler to N1/N2/N3 - the generator reports `LH0011`. - -## Concurrency and ordering - -Concurrency is on by default, cap 10, captured at registration: - -```csharp -builder.Services.Configure(options => -{ - options.MaxConcurrentExecutions = 5; - options.EnableConcurrency = false; // sequential -}); -``` - -`MaxConcurrentExecutions` must be positive in both modes or the app fails at build time. -Contributions stay in **source order** regardless of completion order. Use -`EnableConcurrency = false` for FIFO queues and ordered stream shards. - -Item concurrency is not Lambda invocation concurrency. The runtime still handles one invocation per -environment by default. - -## Stopping and cancelling - -`IEventProcessingContext` (namespace `MinimalLambda`) is per invocation, shared by handlers and -error mappers. - -- `StopProcessing()` - block new items, let active ones finish with the current token. A response may - still be built. -- `CancelProcessing()` - same, plus signal the processing token, then drain. -- Invocation cancellation observed *during* handling - blocks new items, signals the processing - token, suppresses the response. - -Both are thread-safe and idempotent; stop escalates to cancel but never reverses. `handle` receives -the processing token; read `processingContext.Invocation.CancellationToken` for the original. After -handling closes, fan-in and response construction add no new cancellation checks. - -## Response contract - -`createResponse` receives only completed contributions, source order, materialized and repeatably -enumerable. Unstarted or cancelled items contribute nothing - not a null, not a placeholder. The -processor does not validate completeness or retry items. - -An empty event still calls the builder once with an empty collection. Nullable values are valid -contributions; null items are not filtered. - -## Partial batch responses (SQS) - -```csharp -lambda.MapEventHandler( - split: (SQSEvent batch, ILambdaInvocationContext _) => batch.Records, - handle: async Task ( - SQSEvent.SQSMessage item, Importer importer, CancellationToken token) => - { - await importer.ImportAsync(item.Body, token); - return new Success(item.MessageId); - }, - onError: (item, _, _) => new Retry(item.MessageId), - createResponse: (results, _) => new SQSBatchResponse( - results.OfType() - .Select(result => new SQSBatchResponse.BatchItemFailure - { - ItemIdentifier = result.MessageId, - }) - .ToList())); -``` - -Requirements and limits: - -- Enable `ReportBatchItemFailures` on the event source mapping. -- The declared handler return type fixes the shared union type. `Task` is not - `Task`. -- Success values carry identity so the response can be computed; use `Success`/`Retry` records. -- Omitted items mean "no claim", never "safe to retry". Partial imports may already have side - effects. Applications own idempotency and rollback. -- When a response must report *unprocessed* identities, compute them in application code from the - original event, for example - `except`-ing completed identities against `context.GetRequiredEvent().Records`. -- FIFO queues need `EnableConcurrency = false` plus `StopProcessing()` on a poison pill. Otherwise - later messages may be committed before an earlier failure is retried. - -## Overload selection - -`Task` derives from `Task`, so bindings can be ambiguous. In order: - -1. declare the handler return type: `async Task (item, dep, token) => ...`; -2. pass a typed delegate local when using a method group - (`Func> handle = Handler;`); -3. pass all generic arguments: - `lambda.MapEventHandler(split, Handler);`. - -A method group alone cannot supply DI parameter types - it fails to compile (`CS1503` or `CS0411`). -Do not add a `Delegate` catch-all. - -## Diagnostics - -| ID | Meaning | -| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `LH0008` | Unsupported signature: not `Task`-returning, wrong item type, inaccessible type, `ref`/`out`, stream/awaitable event or response, bad parameter count. | -| `LH0009` | Unsupported binding: event attribute on the item, duplicate context/token parameters, service attribute on a framework parameter. | -| `LH0010` | Handler not resolvable to one analyzable method, usually a reassigned delegate local. | -| `LH0011` | `Task` handler bound to a no-result overload. | - -## AOT - -Generated code uses concrete closed signatures, so the processor itself is trim-safe. Add serializer -metadata for the event, response, envelope payloads, and any result type you serialize: - -```csharp -builder.Services.AddLambdaSerializerWithContext(); -builder.Services.ConfigureEnvelopeOptions(options => - options.JsonOptions.TypeInfoResolver = SerializerContext.Default); -``` - -## Checklist - -- Family matches the return type; no `Task` handler on a no-result overload. -- Dependencies resolve from DI; the item is first; at most ten parameters after the item. -- Concurrency setting works for the event source (sequential for FIFO/ordered streams). -- `createResponse` handles an empty collection and only relies on completed contributions. -- SQS: `ReportBatchItemFailures` configured, identity carried in results, unprocessed identities - computed by application code. -- Envelope payload types are in the serializer context. +# Event processing + +Use for MapEventHandler, per-item DI, batch responses, processing controls, and EventHandlerOptions. + +Install `MinimalLambda.EventProcessing`. Import `MinimalLambda.EventProcessing` for context, options, +factory, and outcomes; mapping extensions remain in `MinimalLambda.Builder`. Core alone has no event +processing APIs or registration. No AddEventProcessing call or processor DI registration is required. +The matching core package supplies the generator. Do not add a second analyzer. + +## Mapping + +The splitter is `Func>`, called once. Its output +is materialized before handling. The splitter selects the full event type. Null output fails invocation. +The handler is item-first, returning Task or Task, with up to ten further parameters. + +Framework bindings are ILambdaInvocationContext/ILambdaContext, IEventProcessingContext, and the +processing CancellationToken. Other arguments resolve from the item scope, including keyed/nullable +services. Declared optional defaults apply only when a service is missing. Do not use FromEvent to +select the incoming batch. Use a typed lambda/delegate or explicit generics for method groups. + +Five families: no response; Task plus source-item response; Task plus mapped-failure response; +Task plus response; Task plus synchronous error mapper and response. +The error mapper is `(item, exception, processing) => TValue`. Async mapper contributions, nested +awaitable handler results, and awaitable responses are diagnostic errors. + +Typed delegates supply binding types. Attributes on the underlying handler method still apply +when its parameters accept broader types. + +## Complete outcomes + +Response callback: `(IReadOnlyList>, ILambdaInvocationContext) => TResponse`. +Every source position appears once in order, including duplicates and nullable items. Outcomes expose +Index, Item, Status, HasValue, Value, Exception. HasValue distinguishes a null value from no contribution. +Statuses are Succeeded, MappedError, Skipped, Cancelled. Handler domain results are not interpreted. +A mapped error retains the original exception. Empty batches build one response with an empty list. + +Applications own acknowledgement/retry decisions. For SQS, include mapped/domain failures and +skipped/cancelled items as appropriate, using original Item.MessageId. Configure partial batch failure +reporting. For FIFO use sequential handling and StopProcessing when later records must wait; include +unstarted records in the retry response. For stream checkpoints inspect complete outcomes and choose +the checkpoint in application code. Never compact outcomes into values before deciding retries. + +## Runtime policies + +Fresh async scope per admitted item, alive through DI, handling, mapper, and awaited cleanup. DI +resolution/constructor failures and sync/async handler failures reach onError. Null handler tasks are +item errors. Missing/throwing mapper fails invocation; never recursively map mapper failures. +Scope creation/disposal failures fail invocation. Drain admitted work and cleanup before returning. +Return DTOs that survive scope disposal. First fatal error wins; additional failures are logged. +Invocation cancellation takes precedence. + +Options default to concurrency enabled, maximum 10. Optional Configure before +Build changes them. Mapping after Build captures and validates effective options, including defaults; +positive maximum required even in sequential mode. Never hide configuration exceptions. + +StopProcessing stops admission; CancelProcessing also cancels admitted work through the processing +token. Both can yield partial responses with complete outcomes. Invocation cancellation fails the +invocation through cleanup and suppresses response construction/storage. Cleanup counts toward the +concurrency cap. Repeated controls and reentrant cancellation callbacks must drain safely. + +## Generated boundary + +One HandleItem(item, itemServices, processing) wrapper, called and awaited inside item error handling. +Public EventHandlerFactory.Create accepts built IServiceProvider and typed callbacks, constructs the +internal processor once, returns LambdaInvocationDelegate. Interceptor calls application.Handle before +normal conditional event/final-response provider setup. Duplicate mappings preserve prior providers. +Keep scheduling, batching, state and response construction in package code. No new core feature APIs, +processing feature, Bind/Invoke stages, BoundArguments, runtime reflection, or generated algorithms. + +Validate real serialization/envelopes/middleware, keyed/optional/framework bindings, ordered outcomes, +DI mapping, fatal cleanup, cancellation races, packed consumers and Native AOT. See +`docs/features/event-processor.md` and `designs/event-processing-contracts.md` for full contracts. diff --git a/src/AotCompatibility.TestApp/AotCompatibility.TestApp.csproj b/src/AotCompatibility.TestApp/AotCompatibility.TestApp.csproj index fafe9402..e394292a 100644 --- a/src/AotCompatibility.TestApp/AotCompatibility.TestApp.csproj +++ b/src/AotCompatibility.TestApp/AotCompatibility.TestApp.csproj @@ -1,4 +1,4 @@ - + Exe net10.0 @@ -23,7 +23,7 @@ Include="MinimalLambda.Envelopes.Alb;MinimalLambda.Envelopes.ApiGateway;MinimalLambda.Envelopes.CloudWatchLogs;MinimalLambda.Envelopes.Kafka;MinimalLambda.Envelopes.KinesisFirehose;MinimalLambda.Envelopes.Kinesis;MinimalLambda.Envelopes.Sns;MinimalLambda.Envelopes.Sqs;MinimalLambda.Envelopes" ProjectPath="$(MSBuildThisFileDirectory)..\..\src\Envelopes\%(Identity)\%(Identity).csproj" /> diff --git a/src/AotCompatibility.TestApp/Program.cs b/src/AotCompatibility.TestApp/Program.cs index 03b903b7..1f71de56 100644 --- a/src/AotCompatibility.TestApp/Program.cs +++ b/src/AotCompatibility.TestApp/Program.cs @@ -9,6 +9,7 @@ using MinimalLambda; using MinimalLambda.Builder; using MinimalLambda.Options; +using MinimalLambda.EventProcessing; var builder = LambdaApplication.CreateBuilder(); @@ -22,16 +23,17 @@ // One mapping site only: reaching a second mapping for the same invocation handler throws. lambda.MapEventHandler( split: (SQSEvent batch, ILambdaInvocationContext _) => batch.Records, - handle: async Task ( - SQSEvent.SQSMessage item, - RecordHandler handler, - CancellationToken token) => await handler.HandleAsync(item, token), + handle: async + Task ( + SQSEvent.SQSMessage item, + RecordHandler handler, + CancellationToken token) => await handler.HandleAsync(item, token), onError: (item, _, _) => new Retry(item.MessageId), - createResponse: (results, _) => new SQSBatchResponse( - results - .OfType() - .Select(result => - new SQSBatchResponse.BatchItemFailure { ItemIdentifier = result.MessageId, }) + createResponse: (outcomes, _) => new SQSBatchResponse( + outcomes + .Where(outcome => outcome.Status != EventItemStatus.Succeeded || outcome.Value is Retry) + .Select(outcome => + new SQSBatchResponse.BatchItemFailure { ItemIdentifier = outcome.Item.MessageId, }) .ToList())); // Registration alone roots the generated processor. The runtime loop is intentionally not started diff --git a/src/MinimalLambda.EventProcessing/EventHandlerFactory.cs b/src/MinimalLambda.EventProcessing/EventHandlerFactory.cs new file mode 100644 index 00000000..ede8c45f --- /dev/null +++ b/src/MinimalLambda.EventProcessing/EventHandlerFactory.cs @@ -0,0 +1,193 @@ +using System.ComponentModel; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace MinimalLambda.EventProcessing; + +/// Constructs terminal delegates used by generated event mappings. +[EditorBrowsable(EditorBrowsableState.Never)] +public static class EventHandlerFactory +{ + /// Creates an event terminal and validates its callbacks and effective options. + /// The Event type. + /// The Item type. + /// The mapping services. + /// The mapping split. + /// The mapping handle. + /// A terminal invocation delegate. + public static LambdaInvocationDelegate Create( + IServiceProvider services, + Func> split, + Func handle) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(split); + ArgumentNullException.ThrowIfNull(handle); + var runtime = CreateRuntime(services); + return context => runtime.RunAsync( + context, + split, + (item, provider, processing) => handle(item, provider, processing), + null, + null, + null); + } + + /// Creates an event terminal and validates its callbacks and effective options. + /// The Event type. + /// The Item type. + /// The Response type. + /// The mapping services. + /// The mapping split. + /// The mapping handle. + /// The mapping createResponse. + /// A terminal invocation delegate. + public static LambdaInvocationDelegate Create( + IServiceProvider services, + Func> split, + Func handle, + Func>, ILambdaInvocationContext, TResponse> + createResponse) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(split); + ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(createResponse); + var runtime = CreateRuntime(services); + return context => runtime.RunAsync( + context, + split, + (item, provider, processing) => handle(item, provider, processing), + static (item, _) => item, + null, + values => SetResponse(context, createResponse(values, context))); + } + + /// Creates an event terminal and validates its callbacks and effective options. + /// The Event type. + /// The Item type. + /// The Failure type. + /// The Response type. + /// The mapping services. + /// The mapping split. + /// The mapping handle. + /// The mapping onError. + /// The mapping createResponse. + /// A terminal invocation delegate. + public static LambdaInvocationDelegate Create( + IServiceProvider services, + Func> split, + Func handle, + Func onError, + Func>, ILambdaInvocationContext, TResponse> + createResponse) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(split); + ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(onError); + ArgumentNullException.ThrowIfNull(createResponse); + var runtime = CreateRuntime(services); + return context => runtime.RunAsync( + context, + split, + (item, provider, processing) => handle(item, provider, processing), + null, + onError, + values => SetResponse(context, createResponse(values, context))); + } + + /// Creates an event terminal and validates its callbacks and effective options. + /// The Event type. + /// The Item type. + /// The Result type. + /// The Response type. + /// The mapping services. + /// The mapping split. + /// The mapping handle. + /// The mapping createResponse. + /// A terminal invocation delegate. + public static LambdaInvocationDelegate Create( + IServiceProvider services, + Func> split, + Func> handle, + Func>, ILambdaInvocationContext, TResponse> + createResponse) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(split); + ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(createResponse); + var runtime = CreateRuntime(services); + return context => runtime.RunAsync( + context, + split, + (item, provider, processing) => handle(item, provider, processing), + static (_, task) => ((Task)task).GetAwaiter().GetResult(), + null, + values => SetResponse(context, createResponse(values, context))); + } + + /// Creates an event terminal and validates its callbacks and effective options. + /// The Event type. + /// The Item type. + /// The Result type. + /// The Response type. + /// The mapping services. + /// The mapping split. + /// The mapping handle. + /// The mapping onError. + /// The mapping createResponse. + /// A terminal invocation delegate. + public static LambdaInvocationDelegate Create( + IServiceProvider services, + Func> split, + Func> handle, + Func onError, + Func>, ILambdaInvocationContext, TResponse> + createResponse) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(split); + ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(onError); + ArgumentNullException.ThrowIfNull(createResponse); + var runtime = CreateRuntime(services); + return context => runtime.RunAsync( + context, + split, + (item, provider, processing) => handle(item, provider, processing), + static (_, task) => ((Task)task).GetAwaiter().GetResult(), + onError, + values => SetResponse(context, createResponse(values, context))); + } + + private static EventProcessorRuntime CreateRuntime(IServiceProvider services) + { + var configured = services.GetService>(); + var options = configured is null ? new EventHandlerOptions() : configured.Value; + ArgumentNullException.ThrowIfNull(options); + var validation = new EventHandlerOptionsValidator().Validate( + Microsoft.Extensions.Options.Options.DefaultName, + options); + if (validation.Failed) + throw new OptionsValidationException( + Microsoft.Extensions.Options.Options.DefaultName, + typeof(EventHandlerOptions), + validation.Failures); + return new EventProcessorRuntime( + options.EnableConcurrency ? options.MaxConcurrentExecutions : 1, + services.GetRequiredService(), + services.GetService()?.CreateLogger("MinimalLambda.EventProcessing")); + } + + private static void SetResponse(ILambdaInvocationContext context, TResponse response) + { + context.CancellationToken.ThrowIfCancellationRequested(); + if (context.Features.Get() is not IResponseFeature feature) + throw new InvalidOperationException( + $"Response feature for type '{typeof(TResponse)}' is not available in the collection."); + feature.SetResponse(response); + } +} diff --git a/src/MinimalLambda/Core/Options/EventHandlerOptions.cs b/src/MinimalLambda.EventProcessing/EventHandlerOptions.cs similarity index 97% rename from src/MinimalLambda/Core/Options/EventHandlerOptions.cs rename to src/MinimalLambda.EventProcessing/EventHandlerOptions.cs index c581026a..ab230d1b 100644 --- a/src/MinimalLambda/Core/Options/EventHandlerOptions.cs +++ b/src/MinimalLambda.EventProcessing/EventHandlerOptions.cs @@ -1,4 +1,4 @@ -namespace MinimalLambda.Options; +namespace MinimalLambda.EventProcessing; /// Provides default event-processor behavior for the Lambda host. /// diff --git a/src/MinimalLambda/Core/Options/EventHandlerOptionsValidator.cs b/src/MinimalLambda.EventProcessing/EventHandlerOptionsValidator.cs similarity index 93% rename from src/MinimalLambda/Core/Options/EventHandlerOptionsValidator.cs rename to src/MinimalLambda.EventProcessing/EventHandlerOptionsValidator.cs index 51773654..43c8c816 100644 --- a/src/MinimalLambda/Core/Options/EventHandlerOptionsValidator.cs +++ b/src/MinimalLambda.EventProcessing/EventHandlerOptionsValidator.cs @@ -1,6 +1,6 @@ using Microsoft.Extensions.Options; -namespace MinimalLambda.Options; +namespace MinimalLambda.EventProcessing; internal sealed class EventHandlerOptionsValidator : IValidateOptions { diff --git a/src/MinimalLambda.EventProcessing/EventItemOutcome.cs b/src/MinimalLambda.EventProcessing/EventItemOutcome.cs new file mode 100644 index 00000000..18199366 --- /dev/null +++ b/src/MinimalLambda.EventProcessing/EventItemOutcome.cs @@ -0,0 +1,57 @@ +namespace MinimalLambda.EventProcessing; + +/// Describes how processing ended for one source position. +public enum EventItemStatus +{ + /// The handler completed successfully. + Succeeded, + + /// The error mapper produced a contribution. + MappedError, + + /// The item was not started. + Skipped, + + /// Processing cancellation interrupted the admitted item. + Cancelled, +} + +/// An immutable outcome for one source position, including duplicate items. +/// The source item type. +/// The contribution type. +public sealed class EventItemOutcome +{ + internal EventItemOutcome( + int index, + TItem item, + EventItemStatus status, + bool hasValue = false, + TValue? value = default, + Exception? exception = null) + { + Index = index; + Item = item; + Status = status; + HasValue = hasValue; + Value = value; + Exception = exception; + } + + /// Gets the zero-based position in the materialized source. + public int Index { get; } + + /// Gets the original source item. + public TItem Item { get; } + + /// Gets the processing status. + public EventItemStatus Status { get; } + + /// Gets whether a contribution exists, including a null contribution. + public bool HasValue { get; } + + /// Gets the contribution; check HasValue to distinguish absent and null values. + public TValue? Value { get; } + + /// Gets the original error when Status is MappedError. + public Exception? Exception { get; } +} diff --git a/src/MinimalLambda.EventProcessing/EventProcessingState.cs b/src/MinimalLambda.EventProcessing/EventProcessingState.cs new file mode 100644 index 00000000..1025da72 --- /dev/null +++ b/src/MinimalLambda.EventProcessing/EventProcessingState.cs @@ -0,0 +1,307 @@ +using System.Runtime.ExceptionServices; +using Microsoft.Extensions.Logging; + +namespace MinimalLambda.EventProcessing; + +internal sealed class EventProcessingState : IEventProcessingContext, IDisposable +{ + private readonly object _gate = new(); + private readonly ILambdaInvocationContext _invocation; + private readonly ILogger? _logger; + private readonly int _itemCount; + private readonly CancellationTokenSource _processingSource = new(); + private readonly CancellationTokenRegistration _invocationRegistration; + + private int _nextIndex; + private int _admitted; + private bool _stopRequested; + private bool _cancelRequested; + private bool _handlingClosed; + private bool _completed; + private bool _invocationCancelled; + private bool _disposed; + private ExceptionDispatchInfo? _firstFatal; + private List? _additionalFatal; + private TaskCompletionSource? _dispatchCompletion; + + internal EventProcessingState( + ILambdaInvocationContext invocation, + ILogger? logger, + int itemCount) + { + _invocation = invocation; + _logger = logger; + _itemCount = itemCount; + _invocationRegistration = invocation.CancellationToken.Register( + static state => ((EventProcessingState)state!).OnInvocationTokenCancelled(), + this); + } + + public ILambdaInvocationContext Invocation => _invocation; + + public CancellationToken CancellationToken => _processingSource.Token; + + public void StopProcessing() + { + lock (_gate) + { + if (_completed || _handlingClosed) + return; + + _stopRequested = true; + TryCloseHandlingCore(); + } + } + + public void CancelProcessing() => RequestProcessingCancellation(false); + + internal bool TryClaim(out int index) + { + TaskCompletionSource? dispatch = null; + var claimed = false; + index = -1; + + lock (_gate) + { + if (_completed) + return false; + + ObserveInvocationCancellationCore(ref dispatch); + + if (_handlingClosed + || _stopRequested + || _firstFatal is not null + || _nextIndex >= _itemCount) + { + TryCloseHandlingCore(); + } + else + { + index = _nextIndex++; + _admitted++; + claimed = true; + } + } + + if (dispatch is not null) + StartDispatch(dispatch); + + return claimed; + } + + internal bool IsInvocationCancellationLatched + { + get + { + lock (_gate) + return _invocationCancelled; + } + } + + internal void CompleteAdmission() + { + lock (_gate) + { + if (_admitted > 0) + _admitted--; + + TryCloseHandlingCore(); + } + } + + internal bool TryLatchInvocationCancellation() + { + if (!_invocation.CancellationToken.IsCancellationRequested) + return false; + + RequestProcessingCancellation(true); + + lock (_gate) + return _invocationCancelled; + } + + internal void RecordFatal(Exception exception) + { + lock (_gate) + { + if (_completed) + return; + + _stopRequested = true; + var fatal = ExceptionDispatchInfo.Capture(exception); + if (_firstFatal is null) + _firstFatal = fatal; + else + (_additionalFatal ??= []).Add(exception); + + TryCloseHandlingCore(); + } + } + + internal void TryCloseHandling() + { + lock (_gate) + TryCloseHandlingCore(); + } + + internal async Task JoinAsync() + { + Task? dispatch; + lock (_gate) + { + TryCloseHandlingCore(); + dispatch = _dispatchCompletion?.Task; + } + + if (dispatch is not null) + await dispatch.ConfigureAwait(false); + + Completion completion; + lock (_gate) + { + TryCloseHandlingCore(); + _completed = true; + completion = new Completion(_invocationCancelled, _firstFatal, _additionalFatal); + } + + completion.LogAdditional(_logger); + + if (completion.InvocationCancelled) + throw new OperationCanceledException( + "The Lambda invocation was cancelled during item processing.", + _invocation.CancellationToken); + + if (completion.FirstFatal is not null) + { + completion.FirstFatal.Throw(); + throw new InvalidOperationException("Unreachable"); + } + } + + public void Dispose() + { + if (_disposed) + return; + + _disposed = true; + _invocationRegistration.Dispose(); + _processingSource.Dispose(); + } + + private void OnInvocationTokenCancelled() => RequestProcessingCancellation(true); + + private void RequestProcessingCancellation(bool invocationCancelled) + { + TaskCompletionSource? dispatch = null; + lock (_gate) + { + if (_completed || _handlingClosed) + return; + + if (invocationCancelled) + _invocationCancelled = true; + + _stopRequested = true; + + if (!_cancelRequested) + { + _cancelRequested = true; + _dispatchCompletion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + dispatch = _dispatchCompletion; + } + + TryCloseHandlingCore(); + } + + if (dispatch is not null) + StartDispatch(dispatch); + } + + private void ObserveInvocationCancellationCore(ref TaskCompletionSource? dispatch) + { + if (_handlingClosed || !_invocation.CancellationToken.IsCancellationRequested) + return; + + _invocationCancelled = true; + _stopRequested = true; + + if (_cancelRequested) + return; + + _cancelRequested = true; + _dispatchCompletion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + dispatch = _dispatchCompletion; + } + + private void TryCloseHandlingCore() + { + if (_handlingClosed) + return; + + if (_admitted > 0) + return; + + if (_nextIndex < _itemCount + && !_stopRequested + && _firstFatal is null + && !_invocation.CancellationToken.IsCancellationRequested) + return; + + if (_invocation.CancellationToken.IsCancellationRequested) + { + _invocationCancelled = true; + _stopRequested = true; + } + + _handlingClosed = true; + } + + private void StartDispatch(TaskCompletionSource completion) => + _ = DispatchCancellationAsync(completion); + + private async Task DispatchCancellationAsync(TaskCompletionSource completion) + { + try + { + await _processingSource.CancelAsync().ConfigureAwait(false); + } + catch (Exception ex) + { + RecordFatal(ex); + } + finally + { + completion.TrySetResult(); + } + } + + private readonly struct Completion( + bool invocationCancelled, + ExceptionDispatchInfo? firstFatal, + List? additionalFatal) + { + internal bool InvocationCancelled { get; } = invocationCancelled; + + internal ExceptionDispatchInfo? FirstFatal { get; } = firstFatal; + + internal void LogAdditional(ILogger? logger) + { + if (logger is null || additionalFatal is null) + return; + + foreach (var exception in additionalFatal) + try + { + logger.LogError( + exception, + "Event processor observed an additional failure while draining item work."); + } + catch + { + // Logging must not replace the selected invocation error. + } + } + } +} diff --git a/src/MinimalLambda.EventProcessing/EventProcessorRuntime.cs b/src/MinimalLambda.EventProcessing/EventProcessorRuntime.cs new file mode 100644 index 00000000..5cf575d0 --- /dev/null +++ b/src/MinimalLambda.EventProcessing/EventProcessorRuntime.cs @@ -0,0 +1,125 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace MinimalLambda.EventProcessing; + +/// Provides the runtime used by generated event-handler registrations. +internal sealed class EventProcessorRuntime +{ + private readonly int _concurrency; + private readonly IServiceScopeFactory _scopeFactory; + private readonly ILogger? _logger; + + internal EventProcessorRuntime( + int concurrency, + IServiceScopeFactory scopeFactory, + ILogger? logger) + { + _concurrency = concurrency; + _scopeFactory = scopeFactory; + _logger = logger; + } + + /// Runs a generated event adapter with per-item scopes and ordered response contributions. + /// The invocation event type. + /// The source item type. + /// The response contribution type. + /// The original invocation context. + /// The source item splitter. + /// Resolves arguments and runs the item handler. + /// Selects a successful contribution, or null to discard successes. + /// Maps handler failures, or null to fail the invocation. + /// Builds and stores the response, or null for handlers without a response. + internal async Task RunAsync( + ILambdaInvocationContext context, + Func> split, + Func handle, + Func? selectSuccess, + Func? onError, + Action>>? complete) + { + context.CancellationToken.ThrowIfCancellationRequested(); + _ = context.ServiceProvider; + var splitItems = split(context.GetRequiredEvent(), context); + if (splitItems is null) + throw new InvalidOperationException("The event splitter 'split' returned null."); + + var items = new List(); + using (var enumerator = splitItems.GetEnumerator()) + while (enumerator.MoveNext()) + { + context.CancellationToken.ThrowIfCancellationRequested(); + items.Add(enumerator.Current); + } + + var itemArray = items.ToArray(); + context.CancellationToken.ThrowIfCancellationRequested(); + using var state = new EventProcessingState(context, _logger, itemArray.Length); + var outcomes = + await EventProcessorWorkers + .RunAsync( + itemArray, + _concurrency, + _scopeFactory, + state, + Adapt, + complete is not null) + .ConfigureAwait(false); + + context.CancellationToken.ThrowIfCancellationRequested(); + if (complete is not null) + { + complete(Array.AsReadOnly(outcomes!)); + } + + async Task> Adapt( + TItem item, + IServiceProvider services, + EventProcessingState processing) + { + var invocationToken = processing.Invocation.CancellationToken; + invocationToken.ThrowIfCancellationRequested(); + if (processing.CancellationToken.IsCancellationRequested) + return ItemOutcome.Cancelled; + + Task? handlerTask = null; + try + { + handlerTask = handle(item, services, processing); + if (handlerTask is null) + throw new InvalidOperationException( + "The event handler 'handle' returned a null task."); + await handlerTask.ConfigureAwait(false); + } + catch (Exception ex) + { + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while processing an item.", + ex, + invocationToken); + if (ex is OperationCanceledException + && processing.CancellationToken.IsCancellationRequested) + return ItemOutcome.Cancelled; + if (onError is null) + throw; + + invocationToken.ThrowIfCancellationRequested(); + var mapped = onError(item, ex, processing); + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while mapping an item error.", + invocationToken); + return ItemOutcome.FromError(mapped, ex); + } + + if (invocationToken.IsCancellationRequested) + throw new OperationCanceledException( + "The Lambda invocation was cancelled while processing an item.", + invocationToken); + return selectSuccess is null + ? default + : ItemOutcome.FromValue(selectSuccess(item, handlerTask!)); + } + } +} diff --git a/src/MinimalLambda.EventProcessing/EventProcessorWorkers.cs b/src/MinimalLambda.EventProcessing/EventProcessorWorkers.cs new file mode 100644 index 00000000..6a79bb0f --- /dev/null +++ b/src/MinimalLambda.EventProcessing/EventProcessorWorkers.cs @@ -0,0 +1,123 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace MinimalLambda.EventProcessing; + +internal readonly struct ItemOutcome +{ + private ItemOutcome(EventItemStatus status, bool hasValue, TValue? value, Exception? error) + { + Status = status; + HasValue = hasValue; + Value = value; + Exception = error; + } + + internal EventItemStatus Status { get; } + internal bool HasValue { get; } + internal TValue? Value { get; } + internal Exception? Exception { get; } + + internal static ItemOutcome FromValue(TValue? value) => + new(EventItemStatus.Succeeded, true, value, null); + + internal static ItemOutcome FromError(TValue? value, Exception error) => + new(EventItemStatus.MappedError, true, value, error); + + internal static ItemOutcome Cancelled => + new(EventItemStatus.Cancelled, false, default, null); +} + +internal static class EventProcessorWorkers +{ + internal static async Task[]?> RunAsync( + TItem[] items, + int effectiveConcurrency, + IServiceScopeFactory scopeFactory, + EventProcessingState state, + Func>> adapter, + bool collectValues) + { + if (items.Length == 0) + state.TryCloseHandling(); + + var outcomes = + collectValues + ? items + .Select((item, index) => + new EventItemOutcome(index, item, EventItemStatus.Skipped)) + .ToArray() + : null; + var workerCount = Math.Min(items.Length, Math.Max(1, effectiveConcurrency)); + var workers = new Task[workerCount]; + + for (var index = 0; index < workerCount; index++) + workers[index] = RunWorkerAsync(); + + await Task.WhenAll(workers).ConfigureAwait(false); + await state.JoinAsync().ConfigureAwait(false); + + return outcomes; + + async Task RunWorkerAsync() + { + while (state.TryClaim(out var index)) + { + if (state.IsInvocationCancellationLatched) + { + state.CompleteAdmission(); + continue; + } + + AsyncServiceScope scope; + try + { + scope = scopeFactory.CreateAsyncScope(); + } + catch (Exception ex) + { + state.RecordFatal(ex); + state.CompleteAdmission(); + continue; + } + + ItemOutcome outcome = default; + + try + { + try + { + outcome = await adapter(items[index], scope.ServiceProvider, state) + .ConfigureAwait(false); + } + catch (Exception ex) + { + if (!state.TryLatchInvocationCancellation()) + state.RecordFatal(ex); + } + + try + { + await scope.DisposeAsync().ConfigureAwait(false); + } + catch (Exception ex) + { + state.RecordFatal(ex); + } + } + finally + { + state.CompleteAdmission(); + } + + if (collectValues) + outcomes![index] = new EventItemOutcome( + index, + items[index], + outcome.Status, + outcome.HasValue, + outcome.Value, + outcome.Exception); + } + } + } +} diff --git a/src/MinimalLambda.Abstractions/Core/IEventProcessingContext.cs b/src/MinimalLambda.EventProcessing/IEventProcessingContext.cs similarity index 98% rename from src/MinimalLambda.Abstractions/Core/IEventProcessingContext.cs rename to src/MinimalLambda.EventProcessing/IEventProcessingContext.cs index e4a08d01..5e346cbc 100644 --- a/src/MinimalLambda.Abstractions/Core/IEventProcessingContext.cs +++ b/src/MinimalLambda.EventProcessing/IEventProcessingContext.cs @@ -1,4 +1,4 @@ -namespace MinimalLambda; +namespace MinimalLambda.EventProcessing; /// /// Provides processing controls and cancellation state for one event-processor invocation. diff --git a/src/MinimalLambda/Builder/InterceptionTargets/MapEventHandlerLambdaApplicationExtensions.cs b/src/MinimalLambda.EventProcessing/MapEventHandlerLambdaApplicationExtensions.cs similarity index 91% rename from src/MinimalLambda/Builder/InterceptionTargets/MapEventHandlerLambdaApplicationExtensions.cs rename to src/MinimalLambda.EventProcessing/MapEventHandlerLambdaApplicationExtensions.cs index 6ebe0190..a27138be 100644 --- a/src/MinimalLambda/Builder/InterceptionTargets/MapEventHandlerLambdaApplicationExtensions.cs +++ b/src/MinimalLambda.EventProcessing/MapEventHandlerLambdaApplicationExtensions.cs @@ -24,8 +24,8 @@ namespace MinimalLambda.Builder; /// the item, including framework context and cancellation-token parameters. /// /// -/// The response builder receives only completed contributions in source order. -/// Unstarted or locally cancelled items contribute nothing; the processor does not add +/// The response builder receives outcomes for every source position in source order. +/// Unstarted and locally cancelled items have explicit statuses; the processor does not add /// placeholder results, validate response completeness, or retry items. These overloads /// are mutually exclusive with each other and with MapHandler for the same /// invocation handler at runtime. @@ -304,14 +304,15 @@ public static ILambdaInvocationBuilder /// The builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder MapEventHandler( this ILambdaInvocationBuilder application, Func> split, Func handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -326,14 +327,15 @@ public static ILambdaInvocationBuilder MapEventHandler /// The builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder MapEventHandler( this ILambdaInvocationBuilder application, Func> split, Func handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -349,14 +351,15 @@ public static ILambdaInvocationBuilder MapEventHandlerThe builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder MapEventHandler( this ILambdaInvocationBuilder application, Func> split, Func handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -373,14 +376,15 @@ public static ILambdaInvocationBuilder MapEventHandlerThe builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder MapEventHandler( this ILambdaInvocationBuilder application, Func> split, Func handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -398,7 +402,7 @@ public static ILambdaInvocationBuilder MapEventHandlerThe builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -406,7 +410,8 @@ public static ILambdaInvocationBuilder this ILambdaInvocationBuilder application, Func> split, Func handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -425,7 +430,7 @@ public static ILambdaInvocationBuilder /// The builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -433,7 +438,8 @@ public static ILambdaInvocationBuilder this ILambdaInvocationBuilder application, Func> split, Func handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -453,7 +459,7 @@ public static ILambdaInvocationBuilder /// The builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -461,7 +467,8 @@ public static ILambdaInvocationBuilder this ILambdaInvocationBuilder application, Func> split, Func handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -482,7 +489,7 @@ public static ILambdaInvocationBuilder /// The builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -490,7 +497,8 @@ public static ILambdaInvocationBuilder this ILambdaInvocationBuilder application, Func> split, Func handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -512,7 +520,7 @@ public static ILambdaInvocationBuilder /// The builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -520,7 +528,8 @@ public static ILambdaInvocationBuilder this ILambdaInvocationBuilder application, Func> split, Func handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -543,7 +552,7 @@ public static ILambdaInvocationBuilder /// The builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -551,7 +560,8 @@ public static ILambdaInvocationBuilder this ILambdaInvocationBuilder application, Func> split, Func handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -575,7 +585,7 @@ public static ILambdaInvocationBuilder /// The builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -583,7 +593,8 @@ public static ILambdaInvocationBuilder this ILambdaInvocationBuilder application, Func> split, Func handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -599,7 +610,7 @@ public static ILambdaInvocationBuilder /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder MapEventHandler( @@ -607,7 +618,8 @@ public static ILambdaInvocationBuilder MapEventHandler> split, Func handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -624,7 +636,7 @@ public static ILambdaInvocationBuilder MapEventHandlerSplits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder MapEventHandler( @@ -632,7 +644,8 @@ public static ILambdaInvocationBuilder MapEventHandler> split, Func handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -650,7 +663,7 @@ public static ILambdaInvocationBuilder MapEventHandlerSplits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -659,7 +672,9 @@ public static ILambdaInvocationBuilder Func> split, Func handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -678,7 +693,7 @@ public static ILambdaInvocationBuilder /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -687,7 +702,9 @@ public static ILambdaInvocationBuilder Func> split, Func handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -707,7 +724,7 @@ public static ILambdaInvocationBuilder /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -716,7 +733,9 @@ public static ILambdaInvocationBuilder Func> split, Func handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -737,7 +756,7 @@ public static ILambdaInvocationBuilder /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -746,7 +765,9 @@ public static ILambdaInvocationBuilder Func> split, Func handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -768,7 +789,7 @@ public static ILambdaInvocationBuilder /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -777,7 +798,9 @@ public static ILambdaInvocationBuilder Func> split, Func handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -800,7 +823,7 @@ public static ILambdaInvocationBuilder /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -809,7 +832,9 @@ public static ILambdaInvocationBuilder Func> split, Func handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -833,7 +858,7 @@ public static ILambdaInvocationBuilder /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -842,7 +867,9 @@ public static ILambdaInvocationBuilder Func> split, Func handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -867,7 +894,7 @@ public static ILambdaInvocationBuilder /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -877,7 +904,9 @@ public static ILambdaInvocationBuilder Func> split, Func handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -903,7 +932,7 @@ public static ILambdaInvocationBuilder /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -914,7 +943,9 @@ public static ILambdaInvocationBuilder Func> split, Func handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -929,14 +960,15 @@ public static ILambdaInvocationBuilder /// The builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder MapEventHandler( this ILambdaInvocationBuilder application, Func> split, Func> handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -952,14 +984,15 @@ public static ILambdaInvocationBuilder MapEventHandlerThe builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder MapEventHandler( this ILambdaInvocationBuilder application, Func> split, Func> handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -976,7 +1009,7 @@ public static ILambdaInvocationBuilder MapEventHandlerThe builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -984,7 +1017,9 @@ public static ILambdaInvocationBuilder this ILambdaInvocationBuilder application, Func> split, Func> handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1002,7 +1037,7 @@ public static ILambdaInvocationBuilder /// The builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -1010,7 +1045,9 @@ public static ILambdaInvocationBuilder this ILambdaInvocationBuilder application, Func> split, Func> handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1029,7 +1066,7 @@ public static ILambdaInvocationBuilder /// The builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -1037,7 +1074,9 @@ public static ILambdaInvocationBuilder this ILambdaInvocationBuilder application, Func> split, Func> handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1057,7 +1096,7 @@ public static ILambdaInvocationBuilder /// The builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -1065,7 +1104,9 @@ public static ILambdaInvocationBuilder this ILambdaInvocationBuilder application, Func> split, Func> handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1086,7 +1127,7 @@ public static ILambdaInvocationBuilder /// The builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -1094,7 +1135,9 @@ public static ILambdaInvocationBuilder this ILambdaInvocationBuilder application, Func> split, Func> handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1116,7 +1159,7 @@ public static ILambdaInvocationBuilder /// The builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -1124,7 +1167,9 @@ public static ILambdaInvocationBuilder this ILambdaInvocationBuilder application, Func> split, Func> handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1147,7 +1192,7 @@ public static ILambdaInvocationBuilder /// The builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -1155,7 +1200,9 @@ public static ILambdaInvocationBuilder this ILambdaInvocationBuilder application, Func> split, Func> handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1179,7 +1226,7 @@ public static ILambdaInvocationBuilder /// The builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -1188,7 +1235,9 @@ public static ILambdaInvocationBuilder this ILambdaInvocationBuilder application, Func> split, Func> handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1213,7 +1262,7 @@ public static ILambdaInvocationBuilder /// The builder to register the handler with. /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -1223,7 +1272,9 @@ public static ILambdaInvocationBuilder this ILambdaInvocationBuilder application, Func> split, Func> handle, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1239,7 +1290,7 @@ public static ILambdaInvocationBuilder /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder MapEventHandler( @@ -1247,7 +1298,8 @@ public static ILambdaInvocationBuilder MapEventHandler> split, Func> handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1264,7 +1316,7 @@ public static ILambdaInvocationBuilder MapEventHandlerSplits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder MapEventHandler( @@ -1272,7 +1324,8 @@ public static ILambdaInvocationBuilder MapEventHandler> split, Func> handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1290,7 +1343,7 @@ public static ILambdaInvocationBuilder MapEventHandlerSplits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -1299,7 +1352,9 @@ public static ILambdaInvocationBuilder Func> split, Func> handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1318,7 +1373,7 @@ public static ILambdaInvocationBuilder /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -1327,7 +1382,9 @@ public static ILambdaInvocationBuilder Func> split, Func> handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1347,7 +1404,7 @@ public static ILambdaInvocationBuilder /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -1356,7 +1413,9 @@ public static ILambdaInvocationBuilder Func> split, Func> handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1377,7 +1436,7 @@ public static ILambdaInvocationBuilder /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -1386,7 +1445,9 @@ public static ILambdaInvocationBuilder Func> split, Func> handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1408,7 +1469,7 @@ public static ILambdaInvocationBuilder /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -1417,7 +1478,9 @@ public static ILambdaInvocationBuilder Func> split, Func> handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1440,7 +1503,7 @@ public static ILambdaInvocationBuilder /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -1449,7 +1512,9 @@ public static ILambdaInvocationBuilder Func> split, Func> handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1473,7 +1538,7 @@ public static ILambdaInvocationBuilder /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -1482,7 +1547,9 @@ public static ILambdaInvocationBuilder Func> split, Func> handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1507,7 +1574,7 @@ public static ILambdaInvocationBuilder /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -1517,7 +1584,9 @@ public static ILambdaInvocationBuilder Func> split, Func> handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { Debug.Fail("This method should have been intercepted at compile time!"); throw new InvalidOperationException("This method is replaced at compile time."); @@ -1543,7 +1612,7 @@ public static ILambdaInvocationBuilder /// Splits the event into source items. Called once per invocation. /// Processes one source item; the item is the first parameter. /// Maps a handler exception for one item to a result value. - /// Builds the response from completed contributions in source order. + /// Builds the response from outcomes for every source position in source order. /// The same instance. /// Thrown if interception does not occur. public static ILambdaInvocationBuilder @@ -1554,7 +1623,9 @@ public static ILambdaInvocationBuilder Func> split, Func> handle, Func onError, - Func, ILambdaInvocationContext, TResponse> createResponse) + Func>, ILambdaInvocationContext, + TResponse> + createResponse) { 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.EventProcessing/MinimalLambda.EventProcessing.csproj b/src/MinimalLambda.EventProcessing/MinimalLambda.EventProcessing.csproj new file mode 100644 index 00000000..9899d2ce --- /dev/null +++ b/src/MinimalLambda.EventProcessing/MinimalLambda.EventProcessing.csproj @@ -0,0 +1,26 @@ + + + net8.0;net9.0;net10.0;net11.0 + preview + enable + enable + true + true + Optional scoped event processing for MinimalLambda + README.md + + + + + + + + + + + + + + + + diff --git a/src/MinimalLambda.EventProcessing/README.md b/src/MinimalLambda.EventProcessing/README.md new file mode 100644 index 00000000..3a951cb5 --- /dev/null +++ b/src/MinimalLambda.EventProcessing/README.md @@ -0,0 +1,18 @@ +# MinimalLambda.EventProcessing + +Optional scoped event processing for MinimalLambda. Install this package and import +`MinimalLambda.EventProcessing` with `MinimalLambda.Builder`. + +MapEventHandler splits a full event into source items. Each item runs in its own asynchronous DI +scope. Response builders receive ordered outcomes for every source position, including skipped and +cancelled work. Application code chooses acknowledgement and retry policy. + +No AddEventProcessing call is required. Optional Configure before Build controls +concurrency. Effective options are validated at mapping time. The matching core dependency supplies +the source generator; this package does not duplicate the analyzer. + +DI and handler failures reach the synchronous error mapper. Scope creation/disposal failures fail the +invocation. Invocation cancellation remains effective through cleanup. Core handles normal +serialization, middleware, and envelopes. + +See https://layeredcraft.github.io/minimal-lambda/features/event-processor/ for usage and callback contracts. diff --git a/src/MinimalLambda.SourceGenerators/Extensions/ParameterSymbolExtensions.cs b/src/MinimalLambda.SourceGenerators/Extensions/ParameterSymbolExtensions.cs index 8c361c2a..755f2df0 100644 --- a/src/MinimalLambda.SourceGenerators/Extensions/ParameterSymbolExtensions.cs +++ b/src/MinimalLambda.SourceGenerators/Extensions/ParameterSymbolExtensions.cs @@ -31,12 +31,14 @@ internal bool IsFromEvent(GeneratorContext context) => internal DiagnosticResult<(string Assignment, string? Key)> GetDiParameterAssignment( GeneratorContext context, - string serviceProviderExpression = "context.ServiceProvider") + string serviceProviderExpression = "context.ServiceProvider", + ITypeSymbol? serviceType = null) { - var paramType = parameterSymbol.Type.QualifiedNullableName; + var type = serviceType ?? parameterSymbol.Type; + var paramType = type.QualifiedNullableName; var isRequired = parameterSymbol.IsOptional - || parameterSymbol.NullableAnnotation == NullableAnnotation.Annotated; + || type.NullableAnnotation == NullableAnnotation.Annotated; return parameterSymbol .IsFromKeyedService(context) diff --git a/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs index 67775a67..3f752c67 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs @@ -102,8 +102,42 @@ internal static EventHandlerMethodInfo Create( context, out var handleResultType); + if (handleResultType is not null && IsAwaitable(handleResultType)) + diagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerSignature, + handlerArgumentLocation, + "nested awaitable handler result")); + var onErrorArgument = GetArgument(invocation, "onError"); var createResponseArgument = GetArgument(invocation, "createResponse"); + var mapperMethod = + onErrorArgument is null + ? null + : ResolveHandlerMethod( + onErrorArgument.Value, + context.SemanticModel, + context.CancellationToken, + out _); + var mapperIsAwaitable = + mapperMethod is not null && IsAwaitable(mapperMethod.ReturnType); + if (mapperIsAwaitable) + diagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerSignature, + handlerArgumentLocation, + "awaitable onError contribution; use a synchronous mapper")); + var responseMethod = + createResponseArgument is null + ? null + : ResolveHandlerMethod( + createResponseArgument.Value, + context.SemanticModel, + context.CancellationToken, + out _); + var responseIsAwaitable = + responseMethod is not null && IsAwaitable(responseMethod.ReturnType); + var family = DetermineFamily( handleReturnsResult, onErrorArgument is not null, @@ -128,6 +162,12 @@ internal static EventHandlerMethodInfo Create( "TFailure", handlerArgumentLocation, diagnostics); + if (!mapperIsAwaitable && failureType is not null && IsAwaitable(failureType)) + diagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerSignature, + handlerArgumentLocation, + "awaitable onError contribution; use a synchronous mapper")); collectedType = failureType?.QualifiedNullableName; break; } @@ -154,7 +194,7 @@ internal static EventHandlerMethodInfo Create( if (declaredResponseType is not null) { - if (IsAwaitable(declaredResponseType)) + if (responseIsAwaitable || IsAwaitable(declaredResponseType)) diagnostics.Add( CreateDiagnostic( Diagnostics.UnsupportedEventHandlerSignature, @@ -201,7 +241,12 @@ or EventHandlerFamily.N3 var parameters = handlerMethod is null ? [] - : CreateParameters(handlerMethod, itemType, context, diagnostics); + : CreateParameters( + handlerMethod, + handleDelegate!.DelegateInvokeMethod!, + itemType, + context, + diagnostics); var valueType = family switch { @@ -278,6 +323,7 @@ private static EventHandlerFamily DetermineFamily( private static List CreateParameters( IMethodSymbol handlerMethod, + IMethodSymbol delegateInvokeMethod, ITypeSymbol? itemType, GeneratorContext context, List diagnostics) @@ -290,6 +336,7 @@ private static List CreateParameters( for (var index = 0; index < handlerMethod.Parameters.Length; index++) { var parameter = handlerMethod.Parameters[index]; + var parameterType = delegateInvokeMethod.Parameters[index].Type; var location = GetParameterLocation(parameter, handlerMethod); var parameterDiagnostics = new List(); @@ -300,7 +347,7 @@ private static List CreateParameters( location, $"{parameter.RefKind.ToString().ToLowerInvariant()} {parameter.Name}")); - ValidateAccessibleType(parameter.Type, parameter.Name, location, parameterDiagnostics); + ValidateAccessibleType(parameterType, parameter.Name, location, parameterDiagnostics); var isEventAttribute = IsEventAttribute(parameter, context); var isServiceAttribute = parameter.IsServiceBindingAttribute(context); @@ -315,7 +362,7 @@ private static List CreateParameters( var kind = EventHandlerParameterKind.Service; var assignment = string.Empty; var isOptional = parameter.IsOptional - || parameter.NullableAnnotation == NullableAnnotation.Annotated; + || parameterType.NullableAnnotation == NullableAnnotation.Annotated; string? keyedKey = null; if (index == 0) @@ -329,7 +376,7 @@ private static List CreateParameters( location, $"service attribute on item parameter '{parameter.Name}'")); if (itemType is not null - && !SymbolEqualityComparer.Default.Equals(itemType, parameter.Type)) + && !SymbolEqualityComparer.Default.Equals(itemType, parameterType)) parameterDiagnostics.Add( CreateDiagnostic( Diagnostics.UnsupportedEventHandlerSignature, @@ -337,7 +384,7 @@ private static List CreateParameters( $"item parameter '{parameter.Name}'")); } else if (context.WellKnownTypes.IsType( - parameter.Type, + parameterType, WellKnownType.Amazon_Lambda_Core_ILambdaContext, WellKnownType.MinimalLambda_ILambdaInvocationContext)) { @@ -358,8 +405,8 @@ private static List CreateParameters( $"service attribute on context parameter '{parameter.Name}'")); } else if (context.WellKnownTypes.IsType( - parameter.Type, - WellKnownType.MinimalLambda_IEventProcessingContext)) + parameterType, + WellKnownType.MinimalLambda_EventProcessing_IEventProcessingContext)) { kind = EventHandlerParameterKind.ProcessingContext; assignment = "processingContext"; @@ -378,7 +425,7 @@ private static List CreateParameters( $"service attribute on processing context parameter '{parameter.Name}'")); } else if (context.WellKnownTypes.IsType( - parameter.Type, + parameterType, WellKnownType.System_Threading_CancellationToken)) { kind = EventHandlerParameterKind.CancellationToken; @@ -399,7 +446,10 @@ private static List CreateParameters( } else { - var diResult = parameter.GetDiParameterAssignment(context, "serviceProvider"); + var diResult = parameter.GetDiParameterAssignment( + context, + "serviceProvider", + parameterType); if (diResult.IsSuccess) { if (diResult.Value!.Key is not null) @@ -409,6 +459,20 @@ private static List CreateParameters( } assignment = diResult.Value.Assignment; + if (parameter.IsOptional) + { + var typeName = parameterType.QualifiedNullableName; + var defaultValue = + parameter.HasExplicitDefaultValue + && parameter.ExplicitDefaultValue is not null + ? $"({typeName}){SymbolDisplay.FormatPrimitive(parameter.ExplicitDefaultValue, true, false)}" + : $"default({typeName})!"; + var lookup = diResult.Value.Key is { } key + ? $"((IKeyedServiceProvider)serviceProvider).GetKeyedService(typeof({(parameterType.IsValueType ? typeName : typeName.TrimEnd('?'))}), {key})" + : $"serviceProvider.GetService(typeof({(parameterType.IsValueType ? typeName : typeName.TrimEnd('?'))}))"; + assignment = + $"{lookup} is {{ }} service{parameter.Ordinal} ? ({typeName})service{parameter.Ordinal} : {defaultValue}"; + } } else if (diResult.Error is { } error) parameterDiagnostics.Add(error); @@ -418,7 +482,7 @@ private static List CreateParameters( new EventHandlerParameterInfo( parameter.Ordinal, parameter.Name, - parameter.Type.QualifiedNullableName, + parameterType.QualifiedNullableName, kind, assignment, isOptional, @@ -657,10 +721,18 @@ private static bool HasAdditionalWrite( local)) continue; - var isWrite = identifier.Parent switch + SyntaxNode target = identifier; + while (true) + if (target.Parent is ArgumentSyntax { Parent: TupleExpressionSyntax tuple }) + target = tuple; + else if (target.Parent is ParenthesizedExpressionSyntax parenthesized) + target = parenthesized; + else + break; + + var isWrite = target.Parent switch { - AssignmentExpressionSyntax assignment when assignment.Left == identifier => - true, + AssignmentExpressionSyntax assignment when assignment.Left == target => true, PrefixUnaryExpressionSyntax prefix => prefix.IsKind( SyntaxKind.PreIncrementExpression) || prefix.IsKind(SyntaxKind.PreDecrementExpression), diff --git a/src/MinimalLambda.SourceGenerators/SyntaxProviders/HandlerSyntaxProvider.cs b/src/MinimalLambda.SourceGenerators/SyntaxProviders/HandlerSyntaxProvider.cs index f107f0e1..fe55bc75 100644 --- a/src/MinimalLambda.SourceGenerators/SyntaxProviders/HandlerSyntaxProvider.cs +++ b/src/MinimalLambda.SourceGenerators/SyntaxProviders/HandlerSyntaxProvider.cs @@ -185,7 +185,7 @@ method.ContainingNamespace is == "MapDurableHandlerLambdaApplicationExtensions"), "MapHandler" or "OnInit" or "OnShutdown" => method.ContainingAssembly.Name == "MinimalLambda", - "MapEventHandler" => method.ContainingAssembly.Name == "MinimalLambda" + "MapEventHandler" => method.ContainingAssembly.Name == "MinimalLambda.EventProcessing" && IsEventMapContainingType(method.ContainingType), _ => false, }); diff --git a/src/MinimalLambda.SourceGenerators/Templates/MapEventHandler.scriban b/src/MinimalLambda.SourceGenerators/Templates/MapEventHandler.scriban index 3308a8b8..3779e8a0 100644 --- a/src/MinimalLambda.SourceGenerators/Templates/MapEventHandler.scriban +++ b/src/MinimalLambda.SourceGenerators/Templates/MapEventHandler.scriban @@ -24,118 +24,45 @@ namespace System.Runtime.CompilerServices namespace MinimalLambda.Generated { using System; - using System.Collections.Generic; - using System.Collections.ObjectModel; - using System.Runtime.ExceptionServices; using System.Runtime.CompilerServices; - using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Logging; - using Microsoft.Extensions.Options; using MinimalLambda.Builder; - using MinimalLambda.Options; + using MinimalLambda.EventProcessing; + using MinimalLambda; {{ generated_code_attribute.value }} file static class GeneratedEventProcessorExtensions { - private const string EventFeatureProviderKey = "__EventFeatureProvider"; - private const string ResponseFeatureProviderKey = "__ResponseFeatureProvider"; - {{~ for call in event_handler_calls ~}} {{ call.interceptable_location_attribute }} internal static ILambdaInvocationBuilder MapEventHandlerInterceptor{{ for.index }}( this ILambdaInvocationBuilder application{{ for p in call.callback_parameters }}, {{ p.type }} {{ p.name }}{{ end }}) { - ArgumentNullException.ThrowIfNull(application); - {{~ for p in call.callback_parameters ~}} - ArgumentNullException.ThrowIfNull({{ p.name }}); - {{~ end ~}} - - var options = application.Services.GetRequiredService>().Value; - var effectiveConcurrency = options.EnableConcurrency - ? options.MaxConcurrentExecutions - : 1; - var scopeFactory = application.Services.GetRequiredService(); - var logger = application - .Services.GetService() - ?.CreateLogger("MinimalLambda.EventProcessor"); - - application.Handle(InvocationDelegate); - - if (!application.Properties.ContainsKey(EventFeatureProviderKey)) - application.Properties[EventFeatureProviderKey] = application - .Services.GetRequiredService() - .Create<{{ call.event_type }}>(); + ArgumentNullException.ThrowIfNull(handle); + var terminal = EventHandlerFactory.Create<{{ call.event_type }}, {{ call.item_type }}{{ if call.has_response }}{{ if call.has_on_error || call.handle_returns_result }}, {{ call.value_type }}{{ end }}, {{ call.response_type }}{{ end }}>( + application.Services, + split, + HandleItem{{ if call.has_on_error }}, + onError{{ end }}{{ if call.has_response }}, + createResponse{{ end }}); + + application.Handle(terminal); + if (!application.Properties.ContainsKey("__EventFeatureProvider")) + application.Properties["__EventFeatureProvider"] = application.Services + .GetRequiredService().Create<{{ call.event_type }}>(); {{~ if call.has_response ~}} - - if (!application.Properties.ContainsKey(ResponseFeatureProviderKey)) - application.Properties[ResponseFeatureProviderKey] = application - .Services.GetRequiredService() - .Create<{{ call.response_type }}>(); + if (!application.Properties.ContainsKey("__ResponseFeatureProvider")) + application.Properties["__ResponseFeatureProvider"] = application.Services + .GetRequiredService().Create<{{ call.response_type }}>(); {{~ end ~}} - return application; - async Task InvocationDelegate(ILambdaInvocationContext context) - { - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - _ = context.ServiceProvider; - - var lambdaEvent = context.GetRequiredEvent<{{ call.event_type }}>(); - var splitItems = split(lambdaEvent, context); - if (splitItems is null) - throw new InvalidOperationException("The event splitter 'split' returned null."); - - var items = new List<{{ call.item_type }}>(); - using (var enumerator = splitItems.GetEnumerator()) - { - while (enumerator.MoveNext()) - { - context.CancellationToken.ThrowIfCancellationRequested(); - items.Add(enumerator.Current); - } - } - - var itemArray = items.ToArray(); - - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - using var state = new EventProcessingState( - context, - logger, - itemArray.Length); - var outcomes = await EventProcessorRuntime - .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, {{ if call.collects_values }}true{{ else }}false{{ end }}) - .ConfigureAwait(false); - {{~ if call.collects_values ~}} - - var contributions = new List<{{ call.value_type }}>(outcomes!.Length); - foreach (var outcome in outcomes) - if (outcome.HasValue) - contributions.Add(outcome.Value!); - - var response = createResponse( - new ReadOnlyCollection<{{ call.value_type }}>(contributions), - context); - {{~ if call.has_response ~}} - - if (context.Features.Get() is not IResponseFeature<{{ call.response_type }}> responseFeature) - throw new InvalidOperationException( - "Response feature for type '{{ call.response_type }}' is not available in the collection."); - responseFeature.SetResponse(response); - {{~ end ~}} - {{~ end ~}} - } - - async Task> Adapt( + {{ if call.handle_returns_result }}Task<{{ call.value_type }}>{{ else }}Task{{ end }} HandleItem( {{ call.item_type }} item, IServiceProvider serviceProvider, - EventProcessingState processingContext) + IEventProcessingContext processingContext) { {{~ if call.has_any_from_keyed_services ~}} if (serviceProvider.GetService() is not IServiceProviderIsKeyedService) @@ -145,510 +72,9 @@ namespace MinimalLambda.Generated {{~ for parameter in call.handler_parameters ~}} var arg{{ parameter.ordinal }} = {{ parameter.assignment }}; {{~ end ~}} - - var invocationToken = processingContext.Invocation.CancellationToken; - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - if (processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome<{{ call.value_type }}>.Cancelled; - - {{ if call.handle_returns_result }}Task<{{ call.collected_type }}>?{{ else }}Task?{{ end }} handlerTask = null; - {{ if call.handle_returns_result }}{{ call.collected_type }} handlerResult = default!;{{ end }} - Exception? synchronousFault = null; - try - { - handlerTask = handle({{ call.handler_arguments }}); - } - catch (Exception ex) - { - synchronousFault = ex; - } - - if (synchronousFault is null && handlerTask is null) - throw new InvalidOperationException("The event handler 'handle' returned a null task."); - - try - { - if (synchronousFault is not null) - ExceptionDispatchInfo.Capture(synchronousFault).Throw(); - - {{ if call.handle_returns_result }}handlerResult = {{ end }}await handlerTask!.ConfigureAwait(false); - } - catch (Exception ex) - { - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - ex, - invocationToken); - - if (ex is OperationCanceledException - && processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome<{{ call.value_type }}>.Cancelled; - {{~ if call.has_on_error ~}} - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - - var mapped = onError(item, ex, processingContext); - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while mapping an item error.", - invocationToken); - - return ItemOutcome<{{ call.value_type }}>.FromMappedValue(mapped); - {{~ else ~}} - - throw; - {{~ end ~}} - } - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - invocationToken); - {{~ if call.collects_source_items ~}} - - return ItemOutcome<{{ call.value_type }}>.FromValue(item); - {{~ else if call.handle_returns_result ~}} - - return ItemOutcome<{{ call.value_type }}>.FromValue(handlerResult); - {{~ else ~}} - - return ItemOutcome<{{ call.value_type }}>.NoValue; - {{~ end ~}} + return handle({{ call.handler_arguments }}); } } {{~ end ~}} } - - file readonly struct NoData; - - file enum ItemExecutionState - { - Unstarted, - Succeeded, - MappedError, - Cancelled, - } - - file readonly struct ItemOutcome - { - private ItemOutcome(ItemExecutionState state, bool hasValue, TValue? value) - { - State = state; - HasValue = hasValue; - Value = value; - } - - internal ItemExecutionState State { get; } - - internal bool HasValue { get; } - - internal TValue? Value { get; } - - internal static ItemOutcome FromValue(TValue? value) => - new(ItemExecutionState.Succeeded, true, value); - - internal static ItemOutcome FromMappedValue(TValue? value) => - new(ItemExecutionState.MappedError, true, value); - - internal static ItemOutcome NoValue => - new(ItemExecutionState.Succeeded, false, default); - - internal static ItemOutcome Cancelled => - new(ItemExecutionState.Cancelled, false, default); - } - - file sealed class EventProcessingState : IEventProcessingContext, IDisposable - { - private readonly object _gate = new(); - private readonly ILambdaInvocationContext _invocation; - private readonly ILogger? _logger; - private readonly int _itemCount; - private readonly CancellationTokenSource _processingSource = new(); - private readonly CancellationTokenRegistration _invocationRegistration; - - private int _nextIndex; - private int _admitted; - private bool _stopRequested; - private bool _cancelRequested; - private bool _handlingClosed; - private bool _completed; - private bool _invocationCancelled; - private bool _disposed; - private ExceptionDispatchInfo? _firstFatal; - private List? _additionalFatal; - private TaskCompletionSource? _dispatchCompletion; - - internal EventProcessingState( - ILambdaInvocationContext invocation, - ILogger? logger, - int itemCount) - { - _invocation = invocation; - _logger = logger; - _itemCount = itemCount; - _invocationRegistration = invocation.CancellationToken.Register( - static state => ((EventProcessingState)state!).OnInvocationTokenCancelled(), - this); - } - - public ILambdaInvocationContext Invocation => _invocation; - - public CancellationToken CancellationToken => _processingSource.Token; - - public void StopProcessing() - { - lock (_gate) - { - if (_completed || _handlingClosed) - return; - - _stopRequested = true; - TryCloseHandlingCore(); - } - } - - public void CancelProcessing() => RequestProcessingCancellation(false); - - internal bool TryClaim(out int index) - { - TaskCompletionSource? dispatch = null; - var claimed = false; - index = -1; - - lock (_gate) - { - if (_completed) - return false; - - ObserveInvocationCancellationCore(ref dispatch); - - if (_handlingClosed - || _stopRequested - || _firstFatal is not null - || _nextIndex >= _itemCount) - { - TryCloseHandlingCore(); - } - else - { - index = _nextIndex++; - _admitted++; - claimed = true; - } - } - - if (dispatch is not null) - StartDispatch(dispatch); - - return claimed; - } - - internal bool IsInvocationCancellationLatched - { - get - { - lock (_gate) - return _invocationCancelled; - } - } - - internal void CompleteAdmission() - { - lock (_gate) - { - if (_admitted > 0) - _admitted--; - - TryCloseHandlingCore(); - } - } - - internal bool TryLatchInvocationCancellation() - { - if (!_invocation.CancellationToken.IsCancellationRequested) - return false; - - RequestProcessingCancellation(true); - - lock (_gate) - return _invocationCancelled; - } - - internal void RecordFatal(Exception exception) - { - lock (_gate) - { - if (_completed) - return; - - _stopRequested = true; - var fatal = ExceptionDispatchInfo.Capture(exception); - if (_firstFatal is null) - _firstFatal = fatal; - else - (_additionalFatal ??= []).Add(exception); - - TryCloseHandlingCore(); - } - } - - internal void TryCloseHandling() - { - lock (_gate) - TryCloseHandlingCore(); - } - - internal async Task JoinAsync() - { - Task? dispatch; - lock (_gate) - { - TryCloseHandlingCore(); - dispatch = _dispatchCompletion?.Task; - } - - if (dispatch is not null) - await dispatch.ConfigureAwait(false); - - Completion completion; - lock (_gate) - { - TryCloseHandlingCore(); - _completed = true; - completion = new Completion( - _invocationCancelled, - _firstFatal, - _additionalFatal); - } - - completion.LogAdditional(_logger); - - if (completion.InvocationCancelled) - throw new OperationCanceledException( - "The Lambda invocation was cancelled during item processing.", - _invocation.CancellationToken); - - if (completion.FirstFatal is not null) - { - completion.FirstFatal.Throw(); - throw new InvalidOperationException("Unreachable"); - } - } - - public void Dispose() - { - if (_disposed) - return; - - _disposed = true; - _invocationRegistration.Dispose(); - _processingSource.Dispose(); - } - - private void OnInvocationTokenCancelled() => RequestProcessingCancellation(true); - - private void RequestProcessingCancellation(bool invocationCancelled) - { - TaskCompletionSource? dispatch = null; - lock (_gate) - { - if (_completed || _handlingClosed) - return; - - if (invocationCancelled) - _invocationCancelled = true; - - _stopRequested = true; - - if (!_cancelRequested) - { - _cancelRequested = true; - _dispatchCompletion = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously); - dispatch = _dispatchCompletion; - } - - TryCloseHandlingCore(); - } - - if (dispatch is not null) - StartDispatch(dispatch); - } - - private void ObserveInvocationCancellationCore(ref TaskCompletionSource? dispatch) - { - if (_handlingClosed || !_invocation.CancellationToken.IsCancellationRequested) - return; - - _invocationCancelled = true; - _stopRequested = true; - - if (_cancelRequested) - return; - - _cancelRequested = true; - _dispatchCompletion = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously); - dispatch = _dispatchCompletion; - } - - private void TryCloseHandlingCore() - { - if (_handlingClosed) - return; - - if (_admitted > 0) - return; - - if (_nextIndex < _itemCount - && !_stopRequested - && _firstFatal is null - && !_invocation.CancellationToken.IsCancellationRequested) - return; - - if (_invocation.CancellationToken.IsCancellationRequested) - { - _invocationCancelled = true; - _stopRequested = true; - } - - _handlingClosed = true; - } - - private void StartDispatch(TaskCompletionSource completion) => - _ = DispatchCancellationAsync(completion); - - private async Task DispatchCancellationAsync(TaskCompletionSource completion) - { - try - { - await _processingSource.CancelAsync().ConfigureAwait(false); - } - catch (Exception ex) - { - RecordFatal(ex); - } - finally - { - completion.TrySetResult(); - } - } - - private readonly struct Completion( - bool invocationCancelled, - ExceptionDispatchInfo? firstFatal, - List? additionalFatal) - { - internal bool InvocationCancelled { get; } = invocationCancelled; - - internal ExceptionDispatchInfo? FirstFatal { get; } = firstFatal; - - internal void LogAdditional(ILogger? logger) - { - if (logger is null || additionalFatal is null) - return; - - foreach (var exception in additionalFatal) - try - { - logger.LogError( - exception, - "Event processor observed an additional failure while draining item work."); - } - catch - { - // Logging must not replace the selected invocation error. - } - } - } - } - - file static class EventProcessorRuntime - { - internal static async Task[]?> RunAsync( - TItem[] items, - int effectiveConcurrency, - IServiceScopeFactory scopeFactory, - EventProcessingState state, - Func>> adapter, - bool collectValues) - { - if (items.Length == 0) - state.TryCloseHandling(); - - var outcomes = collectValues ? new ItemOutcome[items.Length] : null; - var workerCount = Math.Min(items.Length, Math.Max(1, effectiveConcurrency)); - var workers = new Task[workerCount]; - - for (var index = 0; index < workerCount; index++) - workers[index] = RunWorkerAsync(); - - await Task.WhenAll(workers).ConfigureAwait(false); - await state.JoinAsync().ConfigureAwait(false); - - return outcomes; - - async Task RunWorkerAsync() - { - while (state.TryClaim(out var index)) - { - if (state.IsInvocationCancellationLatched) - { - state.CompleteAdmission(); - continue; - } - - AsyncServiceScope scope; - try - { - scope = scopeFactory.CreateAsyncScope(); - } - catch (Exception ex) - { - state.RecordFatal(ex); - state.CompleteAdmission(); - continue; - } - - ItemOutcome outcome = default; - var hasOutcome = false; - - try - { - try - { - outcome = await adapter(items[index], scope.ServiceProvider, state) - .ConfigureAwait(false); - hasOutcome = true; - } - catch (Exception ex) - { - if (!state.TryLatchInvocationCancellation()) - state.RecordFatal(ex); - } - } - finally - { - state.CompleteAdmission(); - } - - try - { - await scope.DisposeAsync().ConfigureAwait(false); - } - catch (Exception ex) - { - state.RecordFatal(ex); - } - - if (collectValues && hasOutcome && outcome.HasValue) - outcomes![index] = outcome; - } - } - } - } } diff --git a/src/MinimalLambda.SourceGenerators/WellKnownTypes/WellKnownTypeData.cs b/src/MinimalLambda.SourceGenerators/WellKnownTypes/WellKnownTypeData.cs index 37231bfe..11255f65 100644 --- a/src/MinimalLambda.SourceGenerators/WellKnownTypes/WellKnownTypeData.cs +++ b/src/MinimalLambda.SourceGenerators/WellKnownTypes/WellKnownTypeData.cs @@ -53,7 +53,7 @@ public enum WellKnownType System_IServiceProvider, System_Void, MinimalLambda_ILambdaInvocationContext, - MinimalLambda_IEventProcessingContext, + MinimalLambda_EventProcessing_IEventProcessingContext, MinimalLambda_ILambdaLifecycleContext, MinimalLambda_Builder_EventAttribute, MinimalLambda_Builder_FromArgumentsAttribute, @@ -112,7 +112,7 @@ public enum WellKnownType "System.IServiceProvider", "System.Void", "MinimalLambda.ILambdaInvocationContext", - "MinimalLambda.IEventProcessingContext", + "MinimalLambda.EventProcessing.IEventProcessingContext", "MinimalLambda.ILambdaLifecycleContext", "MinimalLambda.Builder.EventAttribute", "MinimalLambda.Builder.FromArgumentsAttribute", diff --git a/src/MinimalLambda/Builder/Extensions/ServiceCollectionExtensions.cs b/src/MinimalLambda/Builder/Extensions/ServiceCollectionExtensions.cs index ea4b528e..ddb42681 100644 --- a/src/MinimalLambda/Builder/Extensions/ServiceCollectionExtensions.cs +++ b/src/MinimalLambda/Builder/Extensions/ServiceCollectionExtensions.cs @@ -39,11 +39,7 @@ public IServiceCollection AddLambdaHostCoreServices() services.AddHostedService(); // Register options related services - services.AddOptions().ValidateOnStart(); - services.TryAddEnumerable( - ServiceDescriptor - .Singleton, - EventHandlerOptionsValidator>()); + services.AddOptions(); services.AddSingleton, HostOptionsPostConfiguration>(); services.AddSingleton, diff --git a/src/MinimalLambda/MinimalLambda.csproj b/src/MinimalLambda/MinimalLambda.csproj index 5324aec0..ce7e1c68 100644 --- a/src/MinimalLambda/MinimalLambda.csproj +++ b/src/MinimalLambda/MinimalLambda.csproj @@ -1,4 +1,4 @@ - + net8.0;net9.0;net10.0;net11.0 preview @@ -31,6 +31,7 @@ + diff --git a/tests/MinimalLambda.EventProcessing.UnitTests/EventHandlerRegistrationTests.cs b/tests/MinimalLambda.EventProcessing.UnitTests/EventHandlerRegistrationTests.cs new file mode 100644 index 00000000..a84577cc --- /dev/null +++ b/tests/MinimalLambda.EventProcessing.UnitTests/EventHandlerRegistrationTests.cs @@ -0,0 +1,106 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +namespace MinimalLambda.EventProcessing.UnitTests; + +public sealed class EventHandlerFactoryTests +{ + [Fact] + public async Task DefaultsNeedNoRegistrationAndCallbacksAreLazy() + { + await using var app = LambdaApplication.CreateBuilder().Build(); + var called = false; + var terminal = EventHandlerFactory.Create( + app.Services, + (batch, _) => + { + called = true; + return batch; + }, + (_, _, _) => Task.CompletedTask); + terminal.Should().NotBeNull(); + called.Should().BeFalse(); + } + + [Fact] + public void RejectsInvalidOptionsBeforeCallbacks() + { + using var services = + new ServiceCollection() + .AddOptions() + .Configure(options => options.MaxConcurrentExecutions = 0) + .BuildServiceProvider(); + var create = () => EventHandlerFactory.Create( + services, + (batch, _) => throw new Exception("split must not run"), + (_, _, _) => Task.CompletedTask); + create.Should().Throw(); + } + + [Fact] + public void PreservesConfigurationException() + { + var original = new InvalidOperationException("configuration"); + using var services = + new ServiceCollection() + .AddOptions() + .Configure(_ => throw original) + .BuildServiceProvider(); + var create = () => EventHandlerFactory.Create( + services, + (batch, _) => batch, + (_, _, _) => Task.CompletedTask); + create.Should().Throw().Which.Should().BeSameAs(original); + } + + [Fact] + public void RejectsNullCallbacks() + { + using var services = new ServiceCollection().BuildServiceProvider(); + var create = () => + EventHandlerFactory.Create( + services, + null!, + (_, _, _) => Task.CompletedTask); + create.Should().Throw().WithParameterName("split"); + } + + [Fact] + public async Task NullOriginalHandlerFailsBeforeInstallingTerminal() + { + await using var app = LambdaApplication.CreateBuilder().Build(); + var map = () => app.MapEventHandler( + split: (string[] batch, ILambdaInvocationContext _) => batch, + handle: NullHandler.Value); + map.Should().Throw().WithParameterName("handle"); + var normal = () => app.MapHandler(() => Task.CompletedTask); + normal.Should().NotThrow(); + } + + [Fact] + public async Task MappingPreservesCustomFeatureProviders() + { + await using var app = LambdaApplication.CreateBuilder().Build(); + var invocationBuilder = (ILambdaInvocationBuilder)app; + var eventProvider = Substitute.For(); + var responseProvider = Substitute.For(); + invocationBuilder.Properties["__EventFeatureProvider"] = eventProvider; + invocationBuilder.Properties["__ResponseFeatureProvider"] = responseProvider; + app.MapEventHandler( + split: (string[] batch, ILambdaInvocationContext _) => batch, + handle: (string _) => Task.CompletedTask, + createResponse: (outcomes, _) => "response"); + invocationBuilder.Properties["__EventFeatureProvider"].Should().BeSameAs(eventProvider); + invocationBuilder + .Properties["__ResponseFeatureProvider"] + .Should() + .BeSameAs(responseProvider); + } + + internal static class NullHandler + { + public static readonly Func Value = Handle; + static NullHandler() => Value = null!; + private static Task Handle(string _) => Task.CompletedTask; + } +} diff --git a/tests/MinimalLambda.EventProcessing.UnitTests/EventProcessorRuntimeTests.cs b/tests/MinimalLambda.EventProcessing.UnitTests/EventProcessorRuntimeTests.cs new file mode 100644 index 00000000..4cad9a6b --- /dev/null +++ b/tests/MinimalLambda.EventProcessing.UnitTests/EventProcessorRuntimeTests.cs @@ -0,0 +1,314 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +namespace MinimalLambda.EventProcessing.UnitTests; + +public sealed class EventProcessorRuntimeTests +{ + [Fact] + public async Task OutcomesRetainDuplicatesNullValuesAndSkippedPositions() + { + var builder = LambdaApplication.CreateBuilder(); + builder.Services.Configure(o => o.MaxConcurrentExecutions = 1); + await using var app = builder.Build(); + IReadOnlyList>? captured = null; + app.MapEventHandler( + split: (string?[] batch, ILambdaInvocationContext _) => batch, + handle: (string? item, IEventProcessingContext processing) => + { + if (item == "stop") + { + processing.StopProcessing(); + throw new Exception("failed"); + } + + return Task.FromResult(null); + }, + onError: (item, error, processing) => "mapped", + createResponse: (outcomes, _) => + { + captured = outcomes; + return "response"; + }); + await app.Build()(Context(app, new string?[] { "a", "a", null, "stop", "later" })); + captured.Should().NotBeNull(); + captured!.Select(x => x.Index).Should().Equal(0, 1, 2, 3, 4); + captured.Select(x => x.Item).Should().Equal("a", "a", null, "stop", "later"); + captured + .Select(x => x.Status) + .Should() + .Equal( + EventItemStatus.Succeeded, + EventItemStatus.Succeeded, + EventItemStatus.Succeeded, + EventItemStatus.MappedError, + EventItemStatus.Skipped); + captured[0].HasValue.Should().BeTrue(); + captured[0].Value.Should().BeNull(); + captured[3].Exception!.Message.Should().Be("failed"); + captured[4].HasValue.Should().BeFalse(); + captured.ToArray().Should().Equal(captured.ToArray()); + ((ICollection>)captured).IsReadOnly.Should().BeTrue(); + } + + [Fact] + public async Task EmptyBatchBuildsResponseOnce() + { + await using var app = LambdaApplication.CreateBuilder().Build(); + var calls = 0; + app.MapEventHandler( + split: (string[] batch, ILambdaInvocationContext _) => batch, + handle: (string _) => Task.CompletedTask, + createResponse: (outcomes, _) => + { + outcomes.Should().BeEmpty(); + calls++; + return "empty"; + }); + await app.Build()(Context(app, Array.Empty())); + calls.Should().Be(1); + } + + [Fact] + public async Task ProcessingCancellationRetainsCancelledAndUnstartedItems() + { + var builder = LambdaApplication.CreateBuilder(); + builder.Services.Configure(o => o.MaxConcurrentExecutions = 1); + await using var app = builder.Build(); + IReadOnlyList>? captured = null; + app.MapEventHandler( + split: (string[] batch, ILambdaInvocationContext _) => batch, + handle: (string _, IEventProcessingContext processing) => + { + processing.CancelProcessing(); + return Task.FromCanceled(processing.CancellationToken); + }, + createResponse: (outcomes, _) => + { + captured = outcomes; + return "cancelled"; + }); + await app.Build()(Context(app, new[] { "first", "second" })); + captured! + .Select(x => x.Status) + .Should() + .Equal(EventItemStatus.Cancelled, EventItemStatus.Skipped); + } + + [Fact] + public async Task ScopeCreationFailureIsFatalAndDoesNotMapItemErrors() + { + await using var app = LambdaApplication.CreateBuilder().Build(); + var original = new InvalidOperationException("scope creation"); + var scopes = Substitute.For(); + scopes.CreateScope().Returns(_ => throw original); + var runtime = new EventProcessorRuntime(1, scopes, null); + var mapped = false; + var run = () => runtime.RunAsync( + Context(app, new[] { "item" }), + (batch, _) => batch, + (_, _, _) => Task.CompletedTask, + null, + (_, _, _) => + { + mapped = true; + return "mapped"; + }, + null); + (await run.Should().ThrowAsync()) + .Which + .Should() + .BeSameAs(original); + mapped.Should().BeFalse(); + } + + [Fact] + public async Task ConstructorFailureCanBeMappedWhileScopeIsAlive() + { + var builder = LambdaApplication.CreateBuilder(); + var original = new InvalidOperationException("constructor"); + builder.Services.AddScoped(_ => throw original); + await using var app = builder.Build(); + Exception? mapped = null; + app.MapEventHandler( + split: (string[] batch, ILambdaInvocationContext _) => batch, + handle: (string _, Broken _) => Task.CompletedTask, + onError: (_, error, _) => + { + mapped = error; + return "mapped"; + }, + createResponse: (outcomes, _) => outcomes.Single().Value!); + await app.Build()(Context(app, new[] { "item" })); + mapped.Should().BeSameAs(original); + } + + [Fact] + public async Task MissingKeyedDependencyIsMapped() + { + await using var app = LambdaApplication.CreateBuilder().Build(); + Exception? mapped = null; + app.MapEventHandler( + split: (string[] batch, ILambdaInvocationContext _) => batch, + handle: (string _, [FromKeyedServices("missing")] Broken _) => Task.CompletedTask, + onError: (_, error, _) => + { + mapped = error; + return "mapped"; + }, + createResponse: (outcomes, _) => outcomes.Single().Value!); + await app.Build()(Context(app, new[] { "item" })); + mapped.Should().BeOfType(); + } + + [Fact] + public async Task DisposalAfterMappedFailureStillFailsInvocation() + { + var builder = LambdaApplication.CreateBuilder(); + builder.Services.AddScoped(); + await using var app = builder.Build(); + var responseCalls = 0; + app.MapEventHandler( + split: (string[] batch, ILambdaInvocationContext _) => batch, + handle: (string _, DisposalFailure _) => Task.FromException(new Exception("handler")), + onError: (_, _, _) => "mapped", + createResponse: (outcomes, _) => + { + responseCalls++; + return "response"; + }); + var run = () => app.Build()(Context(app, new[] { "item" })); + await run.Should().ThrowAsync().WithMessage("disposal"); + responseCalls.Should().Be(0); + } + + internal sealed class DisposalFailure : IAsyncDisposable + { + public ValueTask DisposeAsync() => + ValueTask.FromException(new InvalidOperationException("disposal")); + } + + internal sealed class Broken; + + [Fact] + public async Task CancellationDuringSlowDisposalWaitsForCleanupAndSuppressesResponse() + { + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var cancellation = new CancellationTokenSource(); + var builder = LambdaApplication.CreateBuilder(); + builder.Services.AddScoped(_ => new GatedDisposal(entered, release.Task)); + await using var app = builder.Build(); + var responseCalls = 0; + app.MapEventHandler( + split: (string[] batch, ILambdaInvocationContext _) => batch, + handle: (string _, GatedDisposal _) => Task.CompletedTask, + createResponse: (outcomes, _) => + { + responseCalls++; + return "response"; + }); + var context = Context(app, new[] { "item" }); + context.CancellationToken.Returns(cancellation.Token); + var invocation = app.Build()(context); + await entered.Task.WaitAsync( + TimeSpan.FromSeconds(10), + TestContext.Current.CancellationToken); + cancellation.Cancel(); + invocation.IsCompleted.Should().BeFalse(); + release.SetResult(); + var run = () => invocation; + await run.Should().ThrowAsync(); + responseCalls.Should().Be(0); + } + + [Fact] + public async Task InvocationCancellationTakesPrecedenceOverResolutionError() + { + using var cancellation = new CancellationTokenSource(); + var builder = LambdaApplication.CreateBuilder(); + builder.Services.AddScoped(_ => + { + cancellation.Cancel(); + throw new Exception("resolution"); + }); + await using var app = builder.Build(); + var mapped = false; + app.MapEventHandler( + split: (string[] batch, ILambdaInvocationContext _) => batch, + handle: (string _, Broken _) => Task.CompletedTask, + onError: (_, _, _) => + { + mapped = true; + return "mapped"; + }, + createResponse: (outcomes, _) => "response"); + var context = Context(app, new[] { "item" }); + context.CancellationToken.Returns(cancellation.Token); + var run = () => app.Build()(context); + await run.Should().ThrowAsync(); + mapped.Should().BeFalse(); + } + + internal sealed class GatedDisposal(TaskCompletionSource entered, Task release) + : IAsyncDisposable + { + public async ValueTask DisposeAsync() + { + entered.SetResult(); + await release.ConfigureAwait(false); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task OptionalAndKeyedDefaultsDistinguishMissingAndDefaultValues(bool register) + { + var builder = LambdaApplication.CreateBuilder(); + if (register) + { + builder.Services.AddSingleton(typeof(int), 0); + builder.Services.AddKeyedSingleton("label", ""); + } + + await using var app = builder.Build(); + int? actualAmount = null; + string? actualLabel = null; + + Task Handle( + string _, + int amount = 42, + [FromKeyedServices("label")] string label = "fallback") + { + actualAmount = amount; + actualLabel = label; + return Task.CompletedTask; + } + + Func handle = Handle; + app.MapEventHandler( + split: (string[] batch, ILambdaInvocationContext _) => batch, + handle: handle); + await app.Build()(Context(app, new[] { "item" })); + actualAmount.Should().Be(register ? 0 : 42); + actualLabel.Should().Be(register ? "" : "fallback"); + } + + private static ILambdaInvocationContext Context(LambdaApplication app, T batch) + { + var features = Substitute.For(); + features.Get().Returns(new EventFeature(batch)); + features.Get().Returns(Substitute.For>()); + var context = Substitute.For(); + context.Features.Returns(features); + context.ServiceProvider.Returns(app.Services); + return context; + } + + private sealed class EventFeature(T batch) : IEventFeature + { + public T GetEvent(ILambdaInvocationContext context) => batch; + object? IEventFeature.GetEvent(ILambdaInvocationContext context) => batch; + } +} diff --git a/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs b/tests/MinimalLambda.EventProcessing.UnitTests/EventProcessorTests.cs similarity index 91% rename from tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs rename to tests/MinimalLambda.EventProcessing.UnitTests/EventProcessorTests.cs index 75c5f2dd..bc5cd75b 100644 --- a/tests/MinimalLambda.UnitTests/Core/Runtime/EventProcessorTests.cs +++ b/tests/MinimalLambda.EventProcessing.UnitTests/EventProcessorTests.cs @@ -19,8 +19,10 @@ public async Task ProcessesEmptyInputAndBuildsResponseOnce() app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item _) => Task.CompletedTask, - createResponse: (items, _) => + createResponse: (outcomes, _) => { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); responseCalls++; var ids = items.Select(item => item.Id).ToList(); captured = new Response(ids); @@ -72,7 +74,12 @@ public async Task ProcessesItemsConcurrentlyAndPreservesSourceOrder() return item.Id; }, - createResponse: (ids, _) => new Response(ids.ToList())); + createResponse: (outcomes, _) => + new Response( + outcomes + .Where(outcome => outcome.HasValue) + .Select(outcome => outcome.Value!) + .ToList())); var harness = CreateHarness(app, new Batch([new Item(1), new Item(2), new Item(3)])); var handler = app.Build(); @@ -164,7 +171,12 @@ public async Task MapsFailuresAndCollectsResultsInSourceOrder() exception.Message.Should().Be("item failed"); return -item.Id; }, - createResponse: (results, _) => new Response(results.ToList())); + createResponse: (outcomes, _) => + new Response( + outcomes + .Where(outcome => outcome.HasValue) + .Select(outcome => outcome.Value!) + .ToList())); var harness = CreateHarness(app, new Batch([new Item(1), new Item(2), new Item(3)])); var handler = app.Build(); @@ -191,8 +203,10 @@ public async Task UnhandledHandlerErrorFailsInvocationAndSkipsResponse() app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item) => item.Id == 2 ? Task.FromException(expected) : Task.CompletedTask, - createResponse: (items, _) => + createResponse: (outcomes, _) => { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); responseCalls++; return new Response(items.Select(item => item.Id).ToList()); }); @@ -209,7 +223,7 @@ public async Task UnhandledHandlerErrorFailsInvocationAndSkipsResponse() } [Fact] - public async Task NullHandlerTaskFailsInvocationWithoutErrorMapping() + public async Task NullHandlerTaskIsMappedAsItemError() { // Arrange var errorCalls = 0; @@ -222,7 +236,12 @@ public async Task NullHandlerTaskFailsInvocationWithoutErrorMapping() errorCalls++; return item.Id; }, - createResponse: (results, _) => new Response(results.ToList())); + createResponse: (outcomes, _) => + new Response( + outcomes + .Where(outcome => outcome.HasValue) + .Select(outcome => outcome.Value!) + .ToList())); var harness = CreateHarness(app, new Batch([new Item(1)])); var handler = app.Build(); @@ -231,8 +250,8 @@ public async Task NullHandlerTaskFailsInvocationWithoutErrorMapping() var act = () => handler(harness.Context); // Assert - await act.Should().ThrowAsync().WithMessage("*null task*"); - errorCalls.Should().Be(0); + await act.Should().NotThrowAsync(); + errorCalls.Should().Be(1); } [Fact] @@ -278,8 +297,10 @@ public async Task StopProcessingPreventsNewClaimsAndBuildsCompletedResponse() processing.StopProcessing(); return Task.CompletedTask; }, - createResponse: (items, _) => + createResponse: (outcomes, _) => { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); captured = new Response(items.Select(item => item.Id).ToList()); return captured; }); @@ -361,8 +382,10 @@ public async Task CancelledRunningHandlerSkipsErrorMappingAndOmitsContribution() errorCalls++; return item.Id; }, - createResponse: (results, _) => + createResponse: (outcomes, _) => { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); captured = new Response(results.ToList()); return captured; }); @@ -393,8 +416,10 @@ public async Task InvocationCancellationDuringHandlingSuppressesResponse() await Task.Delay(Timeout.InfiniteTimeSpan, token).ConfigureAwait(false); return item.Id; }, - createResponse: (results, _) => + createResponse: (outcomes, _) => { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); responseCalls++; return new Response(results.ToList()); }); @@ -416,7 +441,7 @@ await entered.Task.WaitAsync( } [Fact] - public async Task LateInvocationCancellationDuringResponseDoesNotAddFailure() + public async Task InvocationCancellationDuringDisposalSuppressesResponse() { // Arrange Response? captured = null; @@ -427,8 +452,11 @@ public async Task LateInvocationCancellationDuringResponseDoesNotAddFailure() app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item, CancelOnDispose _) => Task.FromResult(item.Id), - createResponse: (ids, _) => + createResponse: (outcomes, _) => { + var ids = outcomes + .Where(outcome => outcome.HasValue) + .Select(outcome => outcome.Value!); captured = new Response(ids.ToList()); return captured; }); @@ -437,11 +465,13 @@ public async Task LateInvocationCancellationDuringResponseDoesNotAddFailure() var handler = app.Build(); // Act - await handler(harness.Context); + var run = () => handler(harness.Context); + await run.Should().ThrowAsync(); // Assert invocationCancellation.IsCancellationRequested.Should().BeTrue(); - harness.ResponseFeature.Received(1).SetResponse(captured!); + captured.Should().BeNull(); + harness.ResponseFeature.DidNotReceive().SetResponse(Arg.Any()); } [Fact] @@ -592,7 +622,9 @@ public async Task FatalErrorDrainsAdmittedItemsWithoutClaimingMoreOrBuildingResp await blockedItems.Task.ConfigureAwait(false); }, - createResponse: (IEnumerable _, ILambdaInvocationContext _) => + createResponse: ( + IReadOnlyList> _, + ILambdaInvocationContext _) => { responseCalls++; return new Response([]); @@ -667,8 +699,10 @@ public async Task ResponseInputIsRepeatablyEnumerableInSourceOrder() app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item) => Task.FromResult(item.Id), - createResponse: (results, _) => + createResponse: (outcomes, _) => { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); firstPass = results.ToList(); secondPass = results.ToList(); return new Response(firstPass); @@ -829,8 +863,10 @@ public async Task DuplicateItemsRemainSeparateOrderedContributions() app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item) => Task.FromResult(item.Id), - createResponse: (results, _) => + createResponse: (outcomes, _) => { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); captured = new Response(results.ToList()); return captured; }); @@ -891,8 +927,10 @@ public async Task KeepsScopedResultsValidAfterTheItemScopeIsDisposed() split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item, ScopedValue value) => Task.FromResult(new ResultDto(item.Id, value.InstanceId)), - createResponse: (results, _) => + createResponse: (outcomes, _) => { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); captured = new Response(results.Select(result => result.ItemId).ToList()); return captured; }); @@ -917,7 +955,9 @@ public async Task MissingDependencyFailsInvocationWithoutBuildingResponse() app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item _, UnregisteredValue _) => Task.CompletedTask, - createResponse: (IEnumerable _, ILambdaInvocationContext _) => + createResponse: ( + IReadOnlyList> _, + ILambdaInvocationContext _) => { responseCalls++; return new Response([]); @@ -942,7 +982,9 @@ public async Task RejectedSecondMappingLeavesRegisteredProvidersInPlace() app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item _) => Task.CompletedTask, - createResponse: (IEnumerable _, ILambdaInvocationContext _) => new Response([])); + createResponse: ( + IReadOnlyList> _, + ILambdaInvocationContext _) => new Response([])); var propertiesAfterFirst = app.Properties.Count; // Act @@ -967,8 +1009,10 @@ public async Task RetainsNullableItemsAndDoesNotFilterNulls() app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item? _) => Task.CompletedTask, - createResponse: (items, _) => + createResponse: (outcomes, _) => { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); contributions = items.ToList(); return new Response([]); }); @@ -1024,8 +1068,10 @@ public async Task CollectsOnlyMappedFailuresForTheNoResultRecoveryFamily() ? Task.FromException(new InvalidOperationException("failed")) : Task.CompletedTask, onError: (item, _, _) => item.Id, - createResponse: (failures, _) => + createResponse: (outcomes, _) => { + var failures = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); captured = new Response(failures.ToList()); return captured; }); @@ -1055,8 +1101,10 @@ public async Task SynchronousHandlerThrowIsMappedOnce() mapperCalls++; return item.Id; }, - createResponse: (results, _) => + createResponse: (outcomes, _) => { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); captured = new Response(results.ToList()); return captured; }); @@ -1085,8 +1133,10 @@ public async Task UnrelatedCancellationExceptionIsMappedNormally() split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item _) => Task.FromException(new OperationCanceledException()), onError: (item, _, _) => item.Id, - createResponse: (results, _) => + createResponse: (outcomes, _) => { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); captured = new Response(results.ToList()); return captured; }); @@ -1106,8 +1156,8 @@ public async Task ResponseBuilderFailureFailsInvocation() { // Arrange await using var app = LambdaApplication.CreateBuilder().Build(); - Func, ILambdaInvocationContext, Response> builder = (_, _) => - throw new InvalidOperationException("builder failed"); + Func>, ILambdaInvocationContext, Response> + builder = (_, _) => throw new InvalidOperationException("builder failed"); app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item) => Task.FromResult(item.Id), @@ -1138,7 +1188,12 @@ public async Task RegistersOnlyTheFeatureProvidersTheFamilyNeeds() withResult.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item) => Task.FromResult(item.Id), - createResponse: (results, _) => new Response(results.ToList())); + createResponse: (outcomes, _) => + new Response( + outcomes + .Where(outcome => outcome.HasValue) + .Select(outcome => outcome.Value!) + .ToList())); var withResultProperties = withResult.Properties.Count; // Assert @@ -1195,8 +1250,10 @@ public async Task StopRequestedFromErrorMapperPreventsFurtherClaimsAndKeepsMappe processing.StopProcessing(); return item.Id; }, - createResponse: (failures, _) => + createResponse: (outcomes, _) => { + var failures = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); captured = new Response(failures.ToList()); return captured; }); @@ -1318,8 +1375,10 @@ public async Task MapperCancellationExceptionFailsInvocationWithoutResponse() split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item _) => Task.FromException(new InvalidOperationException("failed")), onError: (_, _, _) => throw new OperationCanceledException(), - createResponse: (results, _) => + createResponse: (outcomes, _) => { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); responseCalls++; return new Response(results.ToList()); }); @@ -1346,8 +1405,10 @@ public async Task ScopeDisposalFailureFailsInvocationAfterSuccessfulHandling() app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item, ThrowingDisposable _) => Task.FromResult(item.Id), - createResponse: (results, _) => + createResponse: (outcomes, _) => { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); responseCalls++; return new Response(results.ToList()); }); @@ -1376,8 +1437,10 @@ public async Task BuildsEmptyResponseWhenLocalCancellationLeavesNoContributions( processing.CancelProcessing(); await Task.Delay(Timeout.InfiniteTimeSpan, token).ConfigureAwait(false); }, - createResponse: (items, _) => + createResponse: (outcomes, _) => { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); captured = new Response(items.Select(item => item.Id).ToList()); return captured; }); @@ -1464,8 +1527,10 @@ public async Task StopWithPeersAdmittedKeepsCompletedValuesAndOmitsUnstarted() await gate.Task.ConfigureAwait(false); return item.Id; }, - createResponse: (results, _) => + createResponse: (outcomes, _) => { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); captured = new Response(results.ToList()); return captured; }); @@ -1521,8 +1586,10 @@ public async Task ThrowingProcessingTokenCallbackFromCancelProcessingIsFatalAndN errorCalls++; return item.Id; }, - createResponse: (results, _) => + createResponse: (outcomes, _) => { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); responseCalls++; return new Response(results.ToList()); }); @@ -1577,8 +1644,10 @@ public async Task ThrowingProcessingTokenCallbackFromInvocationCancellationIsFat registered.TrySetResult(); await release.Task.ConfigureAwait(false); }, - createResponse: (items, _) => + createResponse: (outcomes, _) => { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); responseCalls++; return new Response(items.Select(item => item.Id).ToList()); }); @@ -1627,8 +1696,10 @@ public async Task CancellationCallbacksAreAwaitedBeforeCompletion() processing.CancelProcessing(); return Task.CompletedTask; }, - createResponse: (items, _) => + createResponse: (outcomes, _) => { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); captured = new Response(items.Select(item => item.Id).ToList()); return captured; }); @@ -1670,8 +1741,10 @@ public async Task ReentrantControlCallsFromCancellationCallbacksDoNotDeadlock() processing.CancelProcessing(); return Task.CompletedTask; }, - createResponse: (items, _) => + createResponse: (outcomes, _) => { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); captured = new Response(items.Select(item => item.Id).ToList()); return captured; }); @@ -1762,8 +1835,10 @@ public async Task ConcurrentControlRequestsFromManyHandlersDrainDeterministicall await controlsApplied.Task.ConfigureAwait(false); handled.Add(item.Id); }, - createResponse: (items, _) => + createResponse: (outcomes, _) => { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); captured = new Response(items.Select(item => item.Id).ToList()); return captured; }); @@ -1797,8 +1872,10 @@ public async Task ExecutionErrorIsPrimaryWhenScopeDisposalAlsoFails() split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item _, FaultingDisposable _) => Task.FromException(new InvalidOperationException("handler failed")), - createResponse: (items, _) => + createResponse: (outcomes, _) => { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); responseCalls++; return new Response(items.Select(item => item.Id).ToList()); }); @@ -1828,7 +1905,7 @@ public async Task AdditionalFailuresAreLoggedWithoutReplacingThePrimary() // Arrange var logger = Substitute.For(); var loggerFactory = Substitute.For(); - loggerFactory.CreateLogger("MinimalLambda.EventProcessor").Returns(logger); + loggerFactory.CreateLogger("MinimalLambda.EventProcessing").Returns(logger); var builder = LambdaApplication.CreateBuilder(); builder.Services.RemoveAll(); @@ -1872,7 +1949,7 @@ public async Task ThrowingLoggerDoesNotMaskThePrimaryFailure() { // Arrange var loggerFactory = Substitute.For(); - loggerFactory.CreateLogger("MinimalLambda.EventProcessor").Returns(new ThrowingLogger()); + loggerFactory.CreateLogger("MinimalLambda.EventProcessing").Returns(new ThrowingLogger()); var builder = LambdaApplication.CreateBuilder(); builder.Services.RemoveAll(); @@ -1902,7 +1979,7 @@ public async Task ThrowingLoggerDoesNotMaskThePrimaryFailure() } [Fact] - public async Task MissingDependencyResolutionFailureIsNotMappedByErrorMapper() + public async Task MissingDependencyResolutionFailureIsMappedByErrorMapper() { // Arrange var errorCalls = 0; @@ -1916,8 +1993,10 @@ public async Task MissingDependencyResolutionFailureIsNotMappedByErrorMapper() errorCalls++; return item.Id; }, - createResponse: (results, _) => + createResponse: (outcomes, _) => { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); responseCalls++; return new Response(results.ToList()); }); @@ -1929,9 +2008,9 @@ public async Task MissingDependencyResolutionFailureIsNotMappedByErrorMapper() var act = () => handler(harness.Context); // Assert - await act.Should().ThrowAsync(); - errorCalls.Should().Be(0); - responseCalls.Should().Be(0); + await act.Should().NotThrowAsync(); + errorCalls.Should().Be(1); + responseCalls.Should().Be(1); } [Fact] @@ -1950,8 +2029,10 @@ public async Task StreamResultsCarrySequenceNumbersInSourceOrderAndOnlyFailuresS new InvalidOperationException("stream failed")) : Task.FromResult(new StreamResult(record.SequenceNumber, Failed: false)), onError: (record, _, _) => new StreamResult(record.SequenceNumber, Failed: true), - createResponse: (results, _) => + createResponse: (outcomes, _) => { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); contributed = results.Select(result => result.SequenceNumber).ToList(); captured = new StreamResponse( results @@ -1992,8 +2073,10 @@ public async Task StreamResponseUsesLowestFailingSequenceNumberAsCheckpoint() new InvalidOperationException("stream failed")) : Task.FromResult(new StreamResult(record.SequenceNumber, Failed: false)), onError: (record, _, _) => new StreamResult(record.SequenceNumber, Failed: true), - createResponse: (results, _) => + createResponse: (outcomes, _) => { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); captured = new StreamResponse( results .Where(result => result.Failed) @@ -2020,7 +2103,7 @@ public async Task StreamResponseUsesLowestFailingSequenceNumberAsCheckpoint() } [Fact] - public async Task InvocationCancellationDuringResponseConstructionStillDeliversResponseOnce() + public async Task InvocationCancellationDuringResponseConstructionSuppressesResponse() { // Arrange var responseCalls = 0; @@ -2030,8 +2113,10 @@ public async Task InvocationCancellationDuringResponseConstructionStillDeliversR app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item) => Task.FromResult(item.Id), - createResponse: (results, _) => + createResponse: (outcomes, _) => { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); responseCalls++; invocationCancellation.Cancel(); captured = new Response(results.ToList()); @@ -2042,16 +2127,14 @@ public async Task InvocationCancellationDuringResponseConstructionStillDeliversR var handler = app.Build(); // Act - await handler(harness.Context); + var run = () => handler(harness.Context); + await run.Should().ThrowAsync(); // Assert - // Response construction sits past the handling boundary, so cancelling while the response - // is - // being built neither suppresses nor duplicates the delivered response and adds no failure. invocationCancellation.IsCancellationRequested.Should().BeTrue(); responseCalls.Should().Be(1); captured!.Ids.Should().Equal(1); - harness.ResponseFeature.Received(1).SetResponse(captured); + harness.ResponseFeature.DidNotReceive().SetResponse(Arg.Any()); } private static Exception Unwrap(Exception exception) => diff --git a/tests/MinimalLambda.UnitTests/Builder/InterceptionTargets/MapEventHandlerLambdaApplicationExtensionsTests.cs b/tests/MinimalLambda.EventProcessing.UnitTests/MapEventHandlerLambdaApplicationExtensionsTests.cs similarity index 100% rename from tests/MinimalLambda.UnitTests/Builder/InterceptionTargets/MapEventHandlerLambdaApplicationExtensionsTests.cs rename to tests/MinimalLambda.EventProcessing.UnitTests/MapEventHandlerLambdaApplicationExtensionsTests.cs diff --git a/tests/MinimalLambda.EventProcessing.UnitTests/MinimalLambda.EventProcessing.UnitTests.csproj b/tests/MinimalLambda.EventProcessing.UnitTests/MinimalLambda.EventProcessing.UnitTests.csproj new file mode 100644 index 00000000..faad6e70 --- /dev/null +++ b/tests/MinimalLambda.EventProcessing.UnitTests/MinimalLambda.EventProcessing.UnitTests.csproj @@ -0,0 +1,58 @@ + + + net8.0;net9.0;net10.0;net11.0 + enable + enable + false + true + false + 14 + $(InterceptorsNamespaces);MinimalLambda.Generated + + + + + + + + + + + + + + + + + + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + diff --git a/tests/MinimalLambda.EventProcessing.UnitTests/xunit.runner.json b/tests/MinimalLambda.EventProcessing.UnitTests/xunit.runner.json new file mode 100644 index 00000000..c2f84268 --- /dev/null +++ b/tests/MinimalLambda.EventProcessing.UnitTests/xunit.runner.json @@ -0,0 +1,3 @@ +{ + "$schema": "https://xunit.net/schema/current/xunit.runner.schema.json" +} diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerCallbackShapeTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerCallbackShapeTests.cs new file mode 100644 index 00000000..cfc2ec4d --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerCallbackShapeTests.cs @@ -0,0 +1,62 @@ +using AwesomeAssertions; + +namespace MinimalLambda.SourceGenerators.UnitTests; + +public sealed class EventHandlerCallbackShapeTests +{ + [Theory] + [InlineData( + "(string item) => Task.CompletedTask", + "async (item, error, processing) => { await Task.Yield(); return 1; }")] + [InlineData( + "(string item) => Task.FromResult(Task.FromResult(1))", + "(item, error, processing) => Task.FromResult(1)")] + [InlineData("(string item) => Task.FromResult(new object())", "mapperDelegate")] + public void RejectsAwaitableContributions(string handler, string mapper) + { + var (driver, _) = GeneratorTestHelpers.GenerateFromSource( + $$""" + using System; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.EventProcessing; + using MinimalLambda.Builder; + using MinimalLambda.EventProcessing; + var app = LambdaApplication.CreateBuilder().Build(); + Func mapperDelegate = AsyncMapper; + app.MapEventHandler(split: (string[] batch, ILambdaInvocationContext _) => batch, + handle: {{handler}}, onError: {{mapper}}, createResponse: (outcomes, _) => "response"); + static Task AsyncMapper(string item, System.Exception error, IEventProcessingContext processing) => Task.FromResult(1); + """); + driver + .GetRunResult() + .Diagnostics + .Should() + .Contain(d => d.Id == "LH0008" && d.GetMessage().Contains("awaitable")); + } + + [Fact] + public void RejectsAsyncResponseHiddenByObjectDelegate() + { + var (driver, _) = GeneratorTestHelpers.GenerateFromSource( + """ + using System; + using System.Collections.Generic; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.EventProcessing; + using MinimalLambda.Builder; + using MinimalLambda.EventProcessing; + var app = LambdaApplication.CreateBuilder().Build(); + Func>, ILambdaInvocationContext, object> response = AsyncResponse; + app.MapEventHandler(split: (string[] batch, ILambdaInvocationContext _) => batch, + handle: (string _) => Task.CompletedTask, createResponse: response); + static Task AsyncResponse(IReadOnlyList> items, ILambdaInvocationContext context) => Task.FromResult("response"); + """); + driver + .GetRunResult() + .Diagnostics + .Should() + .Contain(d => d.Id == "LH0008" && d.GetMessage().Contains("awaitable TResponse")); + } +} diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs index 71c403ee..e433299c 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs @@ -12,6 +12,7 @@ public void ReportsUnsupportedSignatureForInaccessibleItemType() """ using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; internal static class Program @@ -56,6 +57,7 @@ public void ReportsUnsupportedSignatureForRefParameter() """ using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; var app = LambdaApplication.CreateBuilder().Build(); @@ -83,13 +85,14 @@ public void ReportsUnsupportedSignatureForStreamEventAndAwaitableResponse() using System.IO; using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; var app = LambdaApplication.CreateBuilder().Build(); app.MapEventHandler( split: (Stream stream, ILambdaInvocationContext _) => System.Linq.Enumerable.Empty(), handle: (Item item) => Task.CompletedTask, - createResponse: (IEnumerable items, ILambdaInvocationContext _) => Task.FromResult(new Response())); + createResponse: (IReadOnlyList> items, ILambdaInvocationContext _) => Task.FromResult(new Response())); internal sealed class Item; @@ -106,6 +109,7 @@ public void ReportsUnsupportedBindingForEventAttributeOnItemParameter() """ using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; var app = LambdaApplication.CreateBuilder().Build(); @@ -133,6 +137,7 @@ public void ReportsUnsupportedBindingForDuplicateProcessingContext() """ using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; var app = LambdaApplication.CreateBuilder().Build(); @@ -154,6 +159,76 @@ internal sealed class Item; diagnostic.Location.GetLineSpan().Path.Should().Be("InputFile.cs"); } + [Fact] + public Task SnapshotsDuplicateCancellationTokensAndDiscardedTaskResult() + { + const string source = """ + using System.Threading; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.EventProcessing; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: Handle); + + static Task Handle(Item item, CancellationToken first, CancellationToken second) => + Task.FromResult(item.Id); + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item + { + public int Id { get; set; } + } + """; + var (driver, compilation) = GeneratorTestHelpers.GenerateFromSource(source); + + compilation + .GetDiagnostics(TestContext.Current.CancellationToken) + .Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) + .Should() + .BeEmpty("the diagnostic snapshot should use compiler-valid source"); + + var diagnostics = driver + .GetRunResult() + .Diagnostics + .Select(diagnostic => + { + var span = diagnostic.Location.GetLineSpan(); + return new + { + diagnostic.Id, + Severity = diagnostic.Severity.ToString(), + Message = diagnostic.GetMessage(), + FilePath = span.Path, + StartLine = span.StartLinePosition.Line + 1, + StartColumn = span.StartLinePosition.Character + 1, + EndLine = span.EndLinePosition.Line + 1, + EndColumn = span.EndLinePosition.Character + 1, + }; + }) + .OrderBy(diagnostic => diagnostic.Id, StringComparer.Ordinal) + .ToArray(); + + diagnostics.Select(diagnostic => diagnostic.Id).Should().Equal("LH0009", "LH0011"); + diagnostics + .Select(diagnostic => diagnostic.Severity) + .Should() + .OnlyContain(severity => severity == DiagnosticSeverity.Error.ToString()); + diagnostics + .Select(diagnostic => diagnostic.FilePath) + .Should() + .OnlyContain(path => path == "InputFile.cs"); + + return Verifier.Verify(diagnostics).UseDirectory("Snapshots").DisableDiff(); + } + [Fact] public void ReportsUnresolvedHandlerForReassignedDelegateLocal() { @@ -162,6 +237,7 @@ public void ReportsUnresolvedHandlerForReassignedDelegateLocal() using System; using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; var app = LambdaApplication.CreateBuilder().Build(); @@ -186,6 +262,59 @@ internal sealed class Item; diagnostic.Location.GetLineSpan().Path.Should().Be("InputFile.cs"); } + [Theory] + [InlineData("(handle, replacement) = (replacement, handle);")] + [InlineData("(unused, (handle, replacement)) = (0, (replacement, handle));")] + public void ReportsUnresolvedHandlerForDeconstructionReassignment(string assignment) + { + var (driver, compilation) = GeneratorTestHelpers.GenerateFromSource( + $$""" + using System; + using System.Threading.Tasks; + using Microsoft.Extensions.DependencyInjection; + using MinimalLambda; + using MinimalLambda.EventProcessing; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + Func handle = First; + Func replacement = Second; + int unused; + {{assignment}} + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: handle); + + static Task First(Item item, [FromKeyedServices("blue")] Probe probe) => Task.CompletedTask; + static Task Second(Item item, Probe probe) => Task.CompletedTask; + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + internal sealed class Probe; + """); + + compilation + .GetDiagnostics(TestContext.Current.CancellationToken) + .Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) + .Should() + .BeEmpty(); + var result = driver.GetRunResult(); + var diagnostic = result.Diagnostics.Should().ContainSingle().Subject; + diagnostic.Id.Should().Be("LH0010"); + diagnostic.Location.GetLineSpan().Path.Should().Be("InputFile.cs"); + result + .GeneratedTrees + .Should() + .NotContain(tree => + tree.FilePath.EndsWith( + "MinimalLambda.EventHandlers.g.cs", + StringComparison.Ordinal)); + } + [Fact] public void ReportsDiscardedResultWhenMethodGroupReturnsTaskOfTForNoResultOverload() { @@ -193,6 +322,7 @@ public void ReportsDiscardedResultWhenMethodGroupReturnsTaskOfTForNoResultOverlo """ using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; var app = LambdaApplication.CreateBuilder().Build(); @@ -225,6 +355,7 @@ public void InvalidRegistrationDoesNotSuppressValidRegistration() """ using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; var app = LambdaApplication.CreateBuilder().Build(); diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs index 1c1232af..41ae10b3 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs @@ -58,6 +58,7 @@ public void RecognizesSupportedHandlerForms(string handler) using System; using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; internal static class Program @@ -87,6 +88,54 @@ internal sealed class Item; RunGenerator(source).Diagnostics.Should().BeEmpty(); } + [Theory] + [InlineData("object")] + [InlineData("BaseItem")] + [InlineData("IItem")] + public void RecognizesTypedDelegateWhoseMethodAcceptsABaseItemType(string parameterType) + { + var (driver, compilation) = GeneratorTestHelpers.GenerateFromSource( + $$""" + using System; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.EventProcessing; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + Func handle = Handle; + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: handle); + + static Task Handle({{parameterType}} item) => Task.CompletedTask; + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal interface IItem; + internal class BaseItem; + internal sealed class Item : BaseItem, IItem; + """); + + var result = driver.GetRunResult(); + result.Diagnostics.Should().BeEmpty(); + result + .GeneratedTrees + .Should() + .ContainSingle(tree => + tree.FilePath.EndsWith( + "MinimalLambda.EventHandlers.g.cs", + StringComparison.Ordinal)); + CompileWithGenerated(compilation, result) + .GetDiagnostics(TestContext.Current.CancellationToken) + .Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) + .Should() + .BeEmpty(); + } + [Fact] public void RecognizesTypedDelegateLocalAndExplicitGenericArguments() { @@ -96,6 +145,7 @@ public void RecognizesTypedDelegateLocalAndExplicitGenericArguments() using System.Collections.Generic; using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; var app = LambdaApplication.CreateBuilder().Build(); @@ -104,11 +154,12 @@ public void RecognizesTypedDelegateLocalAndExplicitGenericArguments() app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: handle, - createResponse: (IEnumerable results, ILambdaInvocationContext _) => new Response()); + createResponse: (IReadOnlyList> results, ILambdaInvocationContext _) => new Response()); app.MapEventHandler( (Batch batch, ILambdaInvocationContext _) => batch.Items, - Handle); + Handle, + (IReadOnlyList> results, ILambdaInvocationContext _) => new Response()); static Task Handle(Item item, Probe probe) => Task.FromResult(probe.Value); @@ -136,6 +187,65 @@ internal sealed class Response; StringComparison.Ordinal)); } + [Theory] + [InlineData( + "Service", + "[FromKeyedServices(\"probe\")]", + "GetRequiredKeyedService(\"probe\")")] + [InlineData("ILambdaInvocationContext", "", "processingContext.Invocation")] + [InlineData("IEventProcessingContext", "", "processingContext")] + public void BindsContravariantMethodUsingDelegateParameterTypes( + string dependencyType, + string attribute, + string expectedBinding) + { + // Arrange + var source = $$""" + using System; + using System.Threading.Tasks; + using Microsoft.Extensions.DependencyInjection; + using MinimalLambda; + using MinimalLambda.EventProcessing; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + Func handle = Handle; + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: handle); + + static Task Handle(object item, {{attribute}} object dependency) => Task.CompletedTask; + + internal sealed class Batch { public Item[] Items => []; } + internal sealed class Item; + internal sealed class Service; + """; + + // Act + var (driver, compilation) = GeneratorTestHelpers.GenerateFromSource(source); + var result = driver.GetRunResult(); + var generated = CompileWithGenerated(compilation, result); + + // Assert + compilation + .GetDiagnostics(TestContext.Current.CancellationToken) + .Should() + .NotContain(d => d.Severity == DiagnosticSeverity.Error); + result.Diagnostics.Should().BeEmpty(); + generated + .GetDiagnostics(TestContext.Current.CancellationToken) + .Should() + .NotContain(d => d.Severity == DiagnosticSeverity.Error); + result + .GeneratedTrees + .Should() + .ContainSingle() + .Subject + .ToString() + .Should() + .Contain(expectedBinding); + } + [Fact] public void ReportsCompileErrorForUntypedMethodGroupWithUnknownDependency() { @@ -144,6 +254,7 @@ public void ReportsCompileErrorForUntypedMethodGroupWithUnknownDependency() using System.Collections.Generic; using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; var app = LambdaApplication.CreateBuilder().Build(); @@ -177,13 +288,14 @@ public void RejectsConcreteTaskResultWhereAUnionResultIsRequired() using System.Collections.Generic; using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; var app = LambdaApplication.CreateBuilder().Build(); app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: HandleSuccess, - createResponse: (IEnumerable results, ILambdaInvocationContext _) => new Response()); + createResponse: (IReadOnlyList> results, ILambdaInvocationContext _) => new Response()); static Task HandleSuccess(Item item) => Task.FromResult(new Success()); @@ -213,6 +325,7 @@ public void RejectsAsyncVoidHandlerAtCompileTime() """ using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; var app = LambdaApplication.CreateBuilder().Build(); @@ -241,6 +354,7 @@ public void RecognizesPositionalAndReorderedArguments() using System.Collections.Generic; using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; var app = LambdaApplication.CreateBuilder().Build(); @@ -248,10 +362,10 @@ public void RecognizesPositionalAndReorderedArguments() app.MapEventHandler( (Batch batch, ILambdaInvocationContext _) => batch.Items, Handle, - (IEnumerable items, ILambdaInvocationContext _) => new Response()); + (IReadOnlyList> items, ILambdaInvocationContext _) => new Response()); app.MapEventHandler( - createResponse: (IEnumerable items, ILambdaInvocationContext _) => new Response(), + createResponse: (IReadOnlyList> items, ILambdaInvocationContext _) => new Response(), handle: Handle, split: (Batch batch, ILambdaInvocationContext _) => batch.Items); @@ -287,6 +401,7 @@ public void ReportsInvalidKeyedServiceKeyOnHandlerParameter() using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; var app = LambdaApplication.CreateBuilder().Build(); @@ -314,6 +429,7 @@ public void IgnoresSameNamedMapEventHandlerFromConsumerAssembly() """ using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; namespace MinimalLambda.Builder @@ -406,6 +522,7 @@ private static string BuildAllOverloadsSource() using System.Collections.Generic; using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; internal sealed class Batch @@ -444,7 +561,7 @@ internal sealed class Response; app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item{{parameters}}) => Task.CompletedTask, - createResponse: (IEnumerable items, ILambdaInvocationContext _) => new Response()); + createResponse: (IReadOnlyList> items, ILambdaInvocationContext _) => new Response()); """); builder.AppendLine( $$""" @@ -452,14 +569,14 @@ internal sealed class Response; split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item{{parameters}}) => Task.CompletedTask, onError: (Item item, Exception exception, IEventProcessingContext processing) => item.Id, - createResponse: (IEnumerable failures, ILambdaInvocationContext _) => new Response()); + createResponse: (IReadOnlyList> failures, ILambdaInvocationContext _) => new Response()); """); builder.AppendLine( $$""" app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item{{parameters}}) => Task.FromResult(item.Id), - createResponse: (IEnumerable results, ILambdaInvocationContext _) => new Response()); + createResponse: (IReadOnlyList> results, ILambdaInvocationContext _) => new Response()); """); builder.AppendLine( $$""" @@ -467,7 +584,7 @@ internal sealed class Response; split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item{{parameters}}) => Task.FromResult(item.Id), onError: (Item item, Exception exception, IEventProcessingContext processing) => item.Id, - createResponse: (IEnumerable results, ILambdaInvocationContext _) => new Response()); + createResponse: (IReadOnlyList> results, ILambdaInvocationContext _) => new Response()); """); } diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs index b795fd44..211a1843 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs @@ -13,6 +13,7 @@ public Task EmitsRepresentativeAdapterForEveryFamily() => using System.Collections.Generic; using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; var app = LambdaApplication.CreateBuilder().Build(); @@ -24,24 +25,24 @@ public Task EmitsRepresentativeAdapterForEveryFamily() => app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item) => Task.CompletedTask, - createResponse: (IEnumerable items, ILambdaInvocationContext _) => new Response()); + createResponse: (IReadOnlyList> items, ILambdaInvocationContext _) => new Response()); app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item) => Task.CompletedTask, onError: (Item item, Exception exception, IEventProcessingContext _) => item.Id, - createResponse: (IEnumerable failures, ILambdaInvocationContext _) => new Response()); + createResponse: (IReadOnlyList> failures, ILambdaInvocationContext _) => new Response()); app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item) => Task.FromResult(item.Id), - createResponse: (IEnumerable results, ILambdaInvocationContext _) => new Response()); + createResponse: (IReadOnlyList> results, ILambdaInvocationContext _) => new Response()); app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item) => Task.FromResult(item.Id), onError: (Item item, Exception exception, IEventProcessingContext _) => item.Id, - createResponse: (IEnumerable results, ILambdaInvocationContext _) => new Response()); + createResponse: (IReadOnlyList> results, ILambdaInvocationContext _) => new Response()); internal sealed class Batch { @@ -67,6 +68,7 @@ public Task EmitsContextTokenAndKeyedServiceBindings() => using Amazon.Lambda.Core; using Microsoft.Extensions.DependencyInjection; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; var app = LambdaApplication.CreateBuilder().Build(); @@ -88,7 +90,7 @@ public Task EmitsContextTokenAndKeyedServiceBindings() => return item.Id + service.Value + keyed.Value; }, onError: (item, _, _) => item.Id, - createResponse: (IEnumerable results, ILambdaInvocationContext _) => new Response()); + createResponse: (IReadOnlyList> results, ILambdaInvocationContext _) => new Response()); internal sealed class Batch { @@ -108,6 +110,76 @@ internal sealed class Service internal sealed class Response; """); + [Fact] + public Task EmitsTypedDelegateAndExplicitGenericMethodGroupBindings() => + GeneratorTestHelpers.Verify( + """ + using System; + using System.Collections.Generic; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.EventProcessing; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + Func> handle = Handle; + + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: handle, + createResponse: (IReadOnlyList> results, ILambdaInvocationContext _) => new Response()); + + app.MapEventHandler( + (Batch batch, ILambdaInvocationContext _) => batch.Items, + Handle, + (IReadOnlyList> results, ILambdaInvocationContext _) => new Response()); + + static Task Handle(Item item, Probe probe) => Task.FromResult(probe.Value); + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + + internal sealed class Probe + { + public int Value => 1; + } + + internal sealed class Response; + """); + + [Fact] + public Task EmitsNullableAndOptionalServiceResolution() => + GeneratorTestHelpers.Verify( + """ + using System.Collections.Generic; + using System.Threading.Tasks; + using Microsoft.Extensions.DependencyInjection; + using MinimalLambda; + using MinimalLambda.EventProcessing; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: ( + Item item, + NullableService? nullableService, + [FromServices] string? optionalService = null) => Task.CompletedTask); + + internal sealed class Batch + { + public Item[] Items => []; + } + + internal sealed class Item; + + internal sealed class NullableService; + """); + [Fact] public void CoexistsWithInvocationLifecycleAndMiddlewareGeneratedFiles() { @@ -115,6 +187,7 @@ public void CoexistsWithInvocationLifecycleAndMiddlewareGeneratedFiles() using System.Collections.Generic; using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; var app = LambdaApplication.CreateBuilder().Build(); @@ -123,7 +196,7 @@ public void CoexistsWithInvocationLifecycleAndMiddlewareGeneratedFiles() app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item) => Task.CompletedTask, - createResponse: (IEnumerable items, ILambdaInvocationContext _) => new Response()); + createResponse: (IReadOnlyList> items, ILambdaInvocationContext _) => new Response()); internal sealed class Batch { @@ -158,6 +231,7 @@ public void EmitsSingleDeterministicFileForMultipleSites() using System.Collections.Generic; using System.Threading.Tasks; using MinimalLambda; + using MinimalLambda.EventProcessing; using MinimalLambda.Builder; var app = LambdaApplication.CreateBuilder().Build(); @@ -167,7 +241,7 @@ public void EmitsSingleDeterministicFileForMultipleSites() app.MapEventHandler( split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item) => Task.CompletedTask, - createResponse: (IEnumerable items, ILambdaInvocationContext _) => new Response()); + createResponse: (IReadOnlyList> items, ILambdaInvocationContext _) => new Response()); internal sealed class Batch { diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/GeneratorTestHelpers.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/GeneratorTestHelpers.cs index 8a39f34f..c1ec7896 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/GeneratorTestHelpers.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/GeneratorTestHelpers.cs @@ -1,3 +1,4 @@ +using MinimalLambda.EventProcessing; using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; using Amazon.Lambda.Core; @@ -154,6 +155,7 @@ .. Net90.References.All.ToList(), .. Net80.References.All.ToList(), #endif MetadataReference.CreateFromFile(typeof(LambdaApplication).Assembly.Location), + MetadataReference.CreateFromFile(typeof(EventHandlerOptions).Assembly.Location), MetadataReference.CreateFromFile(typeof(FromKeyedServicesAttribute).Assembly.Location), MetadataReference.CreateFromFile(typeof(ILambdaContext).Assembly.Location), MetadataReference.CreateFromFile(typeof(IHost).Assembly.Location), diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/MinimalLambda.SourceGenerators.UnitTests.csproj b/tests/MinimalLambda.SourceGenerators.UnitTests/MinimalLambda.SourceGenerators.UnitTests.csproj index 7cbe72bc..5d2ffda4 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/MinimalLambda.SourceGenerators.UnitTests.csproj +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/MinimalLambda.SourceGenerators.UnitTests.csproj @@ -55,4 +55,5 @@ + \ No newline at end of file diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerDiagnosticTests.SnapshotsDuplicateCancellationTokensAndDiscardedTaskResult.verified.txt b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerDiagnosticTests.SnapshotsDuplicateCancellationTokensAndDiscardedTaskResult.verified.txt new file mode 100644 index 00000000..ff035296 --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerDiagnosticTests.SnapshotsDuplicateCancellationTokensAndDiscardedTaskResult.verified.txt @@ -0,0 +1,22 @@ +[ + { + Id: LH0009, + Severity: Error, + Message: Event handler binding 'duplicate cancellation token parameter 'second'' is not supported; the first parameter is the source item, and framework context or cancellation-token parameters cannot use service or event attributes., + FilePath: InputFile.cs, + StartLine: 12, + StartColumn: 61, + EndLine: 12, + EndColumn: 85 + }, + { + Id: LH0011, + Severity: Error, + Message: The event handler 'Handle' returns a result but is bound to a no-result overload; use a result overload with a response builder or wrap the handler so it intentionally returns Task., + FilePath: InputFile.cs, + StartLine: 10, + StartColumn: 13, + EndLine: 10, + EndColumn: 19 + } +] \ No newline at end of file diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsContextTokenAndKeyedServiceBindings#MinimalLambda.EventHandlers.g.verified.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsContextTokenAndKeyedServiceBindings#MinimalLambda.EventHandlers.g.verified.cs index dee2de77..a2bbfb43 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsContextTokenAndKeyedServiceBindings#MinimalLambda.EventHandlers.g.verified.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsContextTokenAndKeyedServiceBindings#MinimalLambda.EventHandlers.g.verified.cs @@ -25,115 +25,45 @@ public InterceptsLocationAttribute(int version, string data) { } namespace MinimalLambda.Generated { using System; - using System.Collections.Generic; - using System.Collections.ObjectModel; - using System.Runtime.ExceptionServices; using System.Runtime.CompilerServices; - using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Logging; - using Microsoft.Extensions.Options; using MinimalLambda.Builder; - using MinimalLambda.Options; + using MinimalLambda.EventProcessing; + using MinimalLambda; [global::System.CodeDom.Compiler.GeneratedCode("MinimalLambda.SourceGenerators", "REPLACED")] file static class GeneratedEventProcessorExtensions { - private const string EventFeatureProviderKey = "__EventFeatureProvider"; - private const string ResponseFeatureProviderKey = "__ResponseFeatureProvider"; - [InterceptsLocation(1, "REPLACED")] internal static ILambdaInvocationBuilder MapEventHandlerInterceptor0( this ILambdaInvocationBuilder application, global::System.Func> split, - global::System.Func> handle, - global::System.Func onError, - global::System.Func, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) + global::System.Func> handle, + global::System.Func onError, + global::System.Func>, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) { - ArgumentNullException.ThrowIfNull(application); - ArgumentNullException.ThrowIfNull(split); ArgumentNullException.ThrowIfNull(handle); - ArgumentNullException.ThrowIfNull(onError); - ArgumentNullException.ThrowIfNull(createResponse); - - var options = application.Services.GetRequiredService>().Value; - var effectiveConcurrency = options.EnableConcurrency - ? options.MaxConcurrentExecutions - : 1; - var scopeFactory = application.Services.GetRequiredService(); - var logger = application - .Services.GetService() - ?.CreateLogger("MinimalLambda.EventProcessor"); - - application.Handle(InvocationDelegate); - - if (!application.Properties.ContainsKey(EventFeatureProviderKey)) - application.Properties[EventFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - - if (!application.Properties.ContainsKey(ResponseFeatureProviderKey)) - application.Properties[ResponseFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - + var terminal = EventHandlerFactory.Create( + application.Services, + split, + HandleItem, + onError, + createResponse); + + application.Handle(terminal); + if (!application.Properties.ContainsKey("__EventFeatureProvider")) + application.Properties["__EventFeatureProvider"] = application.Services + .GetRequiredService().Create(); + if (!application.Properties.ContainsKey("__ResponseFeatureProvider")) + application.Properties["__ResponseFeatureProvider"] = application.Services + .GetRequiredService().Create(); return application; - async Task InvocationDelegate(ILambdaInvocationContext context) - { - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - _ = context.ServiceProvider; - - var lambdaEvent = context.GetRequiredEvent(); - var splitItems = split(lambdaEvent, context); - if (splitItems is null) - throw new InvalidOperationException("The event splitter 'split' returned null."); - - var items = new List(); - using (var enumerator = splitItems.GetEnumerator()) - { - while (enumerator.MoveNext()) - { - context.CancellationToken.ThrowIfCancellationRequested(); - items.Add(enumerator.Current); - } - } - - var itemArray = items.ToArray(); - - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - using var state = new EventProcessingState( - context, - logger, - itemArray.Length); - var outcomes = await EventProcessorRuntime - .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, true) - .ConfigureAwait(false); - - var contributions = new List(outcomes!.Length); - foreach (var outcome in outcomes) - if (outcome.HasValue) - contributions.Add(outcome.Value!); - - var response = createResponse( - new ReadOnlyCollection(contributions), - context); - - if (context.Features.Get() is not IResponseFeature responseFeature) - throw new InvalidOperationException( - "Response feature for type 'global::Response' is not available in the collection."); - responseFeature.SetResponse(response); - } - - async Task> Adapt( + Task HandleItem( global::Item item, IServiceProvider serviceProvider, - EventProcessingState processingContext) + IEventProcessingContext processingContext) { if (serviceProvider.GetService() is not IServiceProviderIsKeyedService) throw new InvalidOperationException( @@ -144,495 +74,7 @@ async Task> Adapt( var arg3 = processingContext.CancellationToken; var arg4 = serviceProvider.GetRequiredService(); var arg5 = serviceProvider.GetRequiredKeyedService("primary"); - - var invocationToken = processingContext.Invocation.CancellationToken; - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - if (processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - Task? handlerTask = null; - int handlerResult = default!; - Exception? synchronousFault = null; - try - { - handlerTask = handle(arg0, arg1, arg2, arg3, arg4, arg5); - } - catch (Exception ex) - { - synchronousFault = ex; - } - - if (synchronousFault is null && handlerTask is null) - throw new InvalidOperationException("The event handler 'handle' returned a null task."); - - try - { - if (synchronousFault is not null) - ExceptionDispatchInfo.Capture(synchronousFault).Throw(); - - handlerResult = await handlerTask!.ConfigureAwait(false); - } - catch (Exception ex) - { - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - ex, - invocationToken); - - if (ex is OperationCanceledException - && processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - - var mapped = onError(item, ex, processingContext); - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while mapping an item error.", - invocationToken); - - return ItemOutcome.FromMappedValue(mapped); - } - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - invocationToken); - - return ItemOutcome.FromValue(handlerResult); - } - } - } - - file readonly struct NoData; - - file enum ItemExecutionState - { - Unstarted, - Succeeded, - MappedError, - Cancelled, - } - - file readonly struct ItemOutcome - { - private ItemOutcome(ItemExecutionState state, bool hasValue, TValue? value) - { - State = state; - HasValue = hasValue; - Value = value; - } - - internal ItemExecutionState State { get; } - - internal bool HasValue { get; } - - internal TValue? Value { get; } - - internal static ItemOutcome FromValue(TValue? value) => - new(ItemExecutionState.Succeeded, true, value); - - internal static ItemOutcome FromMappedValue(TValue? value) => - new(ItemExecutionState.MappedError, true, value); - - internal static ItemOutcome NoValue => - new(ItemExecutionState.Succeeded, false, default); - - internal static ItemOutcome Cancelled => - new(ItemExecutionState.Cancelled, false, default); - } - - file sealed class EventProcessingState : IEventProcessingContext, IDisposable - { - private readonly object _gate = new(); - private readonly ILambdaInvocationContext _invocation; - private readonly ILogger? _logger; - private readonly int _itemCount; - private readonly CancellationTokenSource _processingSource = new(); - private readonly CancellationTokenRegistration _invocationRegistration; - - private int _nextIndex; - private int _admitted; - private bool _stopRequested; - private bool _cancelRequested; - private bool _handlingClosed; - private bool _completed; - private bool _invocationCancelled; - private bool _disposed; - private ExceptionDispatchInfo? _firstFatal; - private List? _additionalFatal; - private TaskCompletionSource? _dispatchCompletion; - - internal EventProcessingState( - ILambdaInvocationContext invocation, - ILogger? logger, - int itemCount) - { - _invocation = invocation; - _logger = logger; - _itemCount = itemCount; - _invocationRegistration = invocation.CancellationToken.Register( - static state => ((EventProcessingState)state!).OnInvocationTokenCancelled(), - this); - } - - public ILambdaInvocationContext Invocation => _invocation; - - public CancellationToken CancellationToken => _processingSource.Token; - - public void StopProcessing() - { - lock (_gate) - { - if (_completed || _handlingClosed) - return; - - _stopRequested = true; - TryCloseHandlingCore(); - } - } - - public void CancelProcessing() => RequestProcessingCancellation(false); - - internal bool TryClaim(out int index) - { - TaskCompletionSource? dispatch = null; - var claimed = false; - index = -1; - - lock (_gate) - { - if (_completed) - return false; - - ObserveInvocationCancellationCore(ref dispatch); - - if (_handlingClosed - || _stopRequested - || _firstFatal is not null - || _nextIndex >= _itemCount) - { - TryCloseHandlingCore(); - } - else - { - index = _nextIndex++; - _admitted++; - claimed = true; - } - } - - if (dispatch is not null) - StartDispatch(dispatch); - - return claimed; - } - - internal bool IsInvocationCancellationLatched - { - get - { - lock (_gate) - return _invocationCancelled; - } - } - - internal void CompleteAdmission() - { - lock (_gate) - { - if (_admitted > 0) - _admitted--; - - TryCloseHandlingCore(); - } - } - - internal bool TryLatchInvocationCancellation() - { - if (!_invocation.CancellationToken.IsCancellationRequested) - return false; - - RequestProcessingCancellation(true); - - lock (_gate) - return _invocationCancelled; - } - - internal void RecordFatal(Exception exception) - { - lock (_gate) - { - if (_completed) - return; - - _stopRequested = true; - var fatal = ExceptionDispatchInfo.Capture(exception); - if (_firstFatal is null) - _firstFatal = fatal; - else - (_additionalFatal ??= []).Add(exception); - - TryCloseHandlingCore(); - } - } - - internal void TryCloseHandling() - { - lock (_gate) - TryCloseHandlingCore(); - } - - internal async Task JoinAsync() - { - Task? dispatch; - lock (_gate) - { - TryCloseHandlingCore(); - dispatch = _dispatchCompletion?.Task; - } - - if (dispatch is not null) - await dispatch.ConfigureAwait(false); - - Completion completion; - lock (_gate) - { - TryCloseHandlingCore(); - _completed = true; - completion = new Completion( - _invocationCancelled, - _firstFatal, - _additionalFatal); - } - - completion.LogAdditional(_logger); - - if (completion.InvocationCancelled) - throw new OperationCanceledException( - "The Lambda invocation was cancelled during item processing.", - _invocation.CancellationToken); - - if (completion.FirstFatal is not null) - { - completion.FirstFatal.Throw(); - throw new InvalidOperationException("Unreachable"); - } - } - - public void Dispose() - { - if (_disposed) - return; - - _disposed = true; - _invocationRegistration.Dispose(); - _processingSource.Dispose(); - } - - private void OnInvocationTokenCancelled() => RequestProcessingCancellation(true); - - private void RequestProcessingCancellation(bool invocationCancelled) - { - TaskCompletionSource? dispatch = null; - lock (_gate) - { - if (_completed || _handlingClosed) - return; - - if (invocationCancelled) - _invocationCancelled = true; - - _stopRequested = true; - - if (!_cancelRequested) - { - _cancelRequested = true; - _dispatchCompletion = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously); - dispatch = _dispatchCompletion; - } - - TryCloseHandlingCore(); - } - - if (dispatch is not null) - StartDispatch(dispatch); - } - - private void ObserveInvocationCancellationCore(ref TaskCompletionSource? dispatch) - { - if (_handlingClosed || !_invocation.CancellationToken.IsCancellationRequested) - return; - - _invocationCancelled = true; - _stopRequested = true; - - if (_cancelRequested) - return; - - _cancelRequested = true; - _dispatchCompletion = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously); - dispatch = _dispatchCompletion; - } - - private void TryCloseHandlingCore() - { - if (_handlingClosed) - return; - - if (_admitted > 0) - return; - - if (_nextIndex < _itemCount - && !_stopRequested - && _firstFatal is null - && !_invocation.CancellationToken.IsCancellationRequested) - return; - - if (_invocation.CancellationToken.IsCancellationRequested) - { - _invocationCancelled = true; - _stopRequested = true; - } - - _handlingClosed = true; - } - - private void StartDispatch(TaskCompletionSource completion) => - _ = DispatchCancellationAsync(completion); - - private async Task DispatchCancellationAsync(TaskCompletionSource completion) - { - try - { - await _processingSource.CancelAsync().ConfigureAwait(false); - } - catch (Exception ex) - { - RecordFatal(ex); - } - finally - { - completion.TrySetResult(); - } - } - - private readonly struct Completion( - bool invocationCancelled, - ExceptionDispatchInfo? firstFatal, - List? additionalFatal) - { - internal bool InvocationCancelled { get; } = invocationCancelled; - - internal ExceptionDispatchInfo? FirstFatal { get; } = firstFatal; - - internal void LogAdditional(ILogger? logger) - { - if (logger is null || additionalFatal is null) - return; - - foreach (var exception in additionalFatal) - try - { - logger.LogError( - exception, - "Event processor observed an additional failure while draining item work."); - } - catch - { - // Logging must not replace the selected invocation error. - } - } - } - } - - file static class EventProcessorRuntime - { - internal static async Task[]?> RunAsync( - TItem[] items, - int effectiveConcurrency, - IServiceScopeFactory scopeFactory, - EventProcessingState state, - Func>> adapter, - bool collectValues) - { - if (items.Length == 0) - state.TryCloseHandling(); - - var outcomes = collectValues ? new ItemOutcome[items.Length] : null; - var workerCount = Math.Min(items.Length, Math.Max(1, effectiveConcurrency)); - var workers = new Task[workerCount]; - - for (var index = 0; index < workerCount; index++) - workers[index] = RunWorkerAsync(); - - await Task.WhenAll(workers).ConfigureAwait(false); - await state.JoinAsync().ConfigureAwait(false); - - return outcomes; - - async Task RunWorkerAsync() - { - while (state.TryClaim(out var index)) - { - if (state.IsInvocationCancellationLatched) - { - state.CompleteAdmission(); - continue; - } - - AsyncServiceScope scope; - try - { - scope = scopeFactory.CreateAsyncScope(); - } - catch (Exception ex) - { - state.RecordFatal(ex); - state.CompleteAdmission(); - continue; - } - - ItemOutcome outcome = default; - var hasOutcome = false; - - try - { - try - { - outcome = await adapter(items[index], scope.ServiceProvider, state) - .ConfigureAwait(false); - hasOutcome = true; - } - catch (Exception ex) - { - if (!state.TryLatchInvocationCancellation()) - state.RecordFatal(ex); - } - } - finally - { - state.CompleteAdmission(); - } - - try - { - await scope.DisposeAsync().ConfigureAwait(false); - } - catch (Exception ex) - { - state.RecordFatal(ex); - } - - if (collectValues && hasOutcome && outcome.HasValue) - outcomes![index] = outcome; - } + return handle(arg0, arg1, arg2, arg3, arg4, arg5); } } } diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsNullableAndOptionalServiceResolution#MinimalLambda.EventHandlers.g.verified.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsNullableAndOptionalServiceResolution#MinimalLambda.EventHandlers.g.verified.cs new file mode 100644 index 00000000..05c5b1cc --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsNullableAndOptionalServiceResolution#MinimalLambda.EventHandlers.g.verified.cs @@ -0,0 +1,68 @@ +//HintName: MinimalLambda.EventHandlers.g.cs +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +#nullable enable + +namespace System.Runtime.CompilerServices +{ + using System.CodeDom.Compiler; + + [global::System.CodeDom.Compiler.GeneratedCode("MinimalLambda.SourceGenerators", "REPLACED")] + [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] + file sealed class InterceptsLocationAttribute : Attribute + { + public InterceptsLocationAttribute(int version, string data) { } + } +} + +namespace MinimalLambda.Generated +{ + using System; + using System.Runtime.CompilerServices; + using System.Threading.Tasks; + using Microsoft.Extensions.DependencyInjection; + using MinimalLambda.Builder; + using MinimalLambda.EventProcessing; + using MinimalLambda; + + [global::System.CodeDom.Compiler.GeneratedCode("MinimalLambda.SourceGenerators", "REPLACED")] + file static class GeneratedEventProcessorExtensions + { + [InterceptsLocation(1, "REPLACED")] + internal static ILambdaInvocationBuilder MapEventHandlerInterceptor0( + this ILambdaInvocationBuilder application, + global::System.Func> split, + global::System.Func handle) + { + ArgumentNullException.ThrowIfNull(handle); + var terminal = EventHandlerFactory.Create( + application.Services, + split, + HandleItem); + + application.Handle(terminal); + if (!application.Properties.ContainsKey("__EventFeatureProvider")) + application.Properties["__EventFeatureProvider"] = application.Services + .GetRequiredService().Create(); + return application; + + Task HandleItem( + global::Item item, + IServiceProvider serviceProvider, + IEventProcessingContext processingContext) + { + var arg0 = item; + var arg1 = serviceProvider.GetService(); + var arg2 = serviceProvider.GetService(typeof(string)) is { } service2 ? (string?)service2 : default(string?)!; + return handle(arg0, arg1, arg2); + } + } + } +} diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsRepresentativeAdapterForEveryFamily#MinimalLambda.EventHandlers.g.verified.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsRepresentativeAdapterForEveryFamily#MinimalLambda.EventHandlers.g.verified.cs index 69a39fa8..8ed5d16c 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsRepresentativeAdapterForEveryFamily#MinimalLambda.EventHandlers.g.verified.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsRepresentativeAdapterForEveryFamily#MinimalLambda.EventHandlers.g.verified.cs @@ -25,144 +25,41 @@ public InterceptsLocationAttribute(int version, string data) { } namespace MinimalLambda.Generated { using System; - using System.Collections.Generic; - using System.Collections.ObjectModel; - using System.Runtime.ExceptionServices; using System.Runtime.CompilerServices; - using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Logging; - using Microsoft.Extensions.Options; using MinimalLambda.Builder; - using MinimalLambda.Options; + using MinimalLambda.EventProcessing; + using MinimalLambda; [global::System.CodeDom.Compiler.GeneratedCode("MinimalLambda.SourceGenerators", "REPLACED")] file static class GeneratedEventProcessorExtensions { - private const string EventFeatureProviderKey = "__EventFeatureProvider"; - private const string ResponseFeatureProviderKey = "__ResponseFeatureProvider"; - [InterceptsLocation(1, "REPLACED")] internal static ILambdaInvocationBuilder MapEventHandlerInterceptor0( this ILambdaInvocationBuilder application, global::System.Func> split, global::System.Func handle) { - ArgumentNullException.ThrowIfNull(application); - ArgumentNullException.ThrowIfNull(split); ArgumentNullException.ThrowIfNull(handle); - - var options = application.Services.GetRequiredService>().Value; - var effectiveConcurrency = options.EnableConcurrency - ? options.MaxConcurrentExecutions - : 1; - var scopeFactory = application.Services.GetRequiredService(); - var logger = application - .Services.GetService() - ?.CreateLogger("MinimalLambda.EventProcessor"); - - application.Handle(InvocationDelegate); - - if (!application.Properties.ContainsKey(EventFeatureProviderKey)) - application.Properties[EventFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - + var terminal = EventHandlerFactory.Create( + application.Services, + split, + HandleItem); + + application.Handle(terminal); + if (!application.Properties.ContainsKey("__EventFeatureProvider")) + application.Properties["__EventFeatureProvider"] = application.Services + .GetRequiredService().Create(); return application; - async Task InvocationDelegate(ILambdaInvocationContext context) - { - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - _ = context.ServiceProvider; - - var lambdaEvent = context.GetRequiredEvent(); - var splitItems = split(lambdaEvent, context); - if (splitItems is null) - throw new InvalidOperationException("The event splitter 'split' returned null."); - - var items = new List(); - using (var enumerator = splitItems.GetEnumerator()) - { - while (enumerator.MoveNext()) - { - context.CancellationToken.ThrowIfCancellationRequested(); - items.Add(enumerator.Current); - } - } - - var itemArray = items.ToArray(); - - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - using var state = new EventProcessingState( - context, - logger, - itemArray.Length); - var outcomes = await EventProcessorRuntime - .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, false) - .ConfigureAwait(false); - } - - async Task> Adapt( + Task HandleItem( global::Item item, IServiceProvider serviceProvider, - EventProcessingState processingContext) + IEventProcessingContext processingContext) { var arg0 = item; - - var invocationToken = processingContext.Invocation.CancellationToken; - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - if (processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - Task? handlerTask = null; - - Exception? synchronousFault = null; - try - { - handlerTask = handle(arg0); - } - catch (Exception ex) - { - synchronousFault = ex; - } - - if (synchronousFault is null && handlerTask is null) - throw new InvalidOperationException("The event handler 'handle' returned a null task."); - - try - { - if (synchronousFault is not null) - ExceptionDispatchInfo.Capture(synchronousFault).Throw(); - - await handlerTask!.ConfigureAwait(false); - } - catch (Exception ex) - { - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - ex, - invocationToken); - - if (ex is OperationCanceledException - && processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - throw; - } - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - invocationToken); - - return ItemOutcome.NoValue; + return handle(arg0); } } [InterceptsLocation(1, "REPLACED")] @@ -170,142 +67,31 @@ internal static ILambdaInvocationBuilder MapEventHandlerInterceptor1( this ILambdaInvocationBuilder application, global::System.Func> split, global::System.Func handle, - global::System.Func, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) + global::System.Func>, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) { - ArgumentNullException.ThrowIfNull(application); - ArgumentNullException.ThrowIfNull(split); ArgumentNullException.ThrowIfNull(handle); - ArgumentNullException.ThrowIfNull(createResponse); - - var options = application.Services.GetRequiredService>().Value; - var effectiveConcurrency = options.EnableConcurrency - ? options.MaxConcurrentExecutions - : 1; - var scopeFactory = application.Services.GetRequiredService(); - var logger = application - .Services.GetService() - ?.CreateLogger("MinimalLambda.EventProcessor"); - - application.Handle(InvocationDelegate); - - if (!application.Properties.ContainsKey(EventFeatureProviderKey)) - application.Properties[EventFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - - if (!application.Properties.ContainsKey(ResponseFeatureProviderKey)) - application.Properties[ResponseFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - + var terminal = EventHandlerFactory.Create( + application.Services, + split, + HandleItem, + createResponse); + + application.Handle(terminal); + if (!application.Properties.ContainsKey("__EventFeatureProvider")) + application.Properties["__EventFeatureProvider"] = application.Services + .GetRequiredService().Create(); + if (!application.Properties.ContainsKey("__ResponseFeatureProvider")) + application.Properties["__ResponseFeatureProvider"] = application.Services + .GetRequiredService().Create(); return application; - async Task InvocationDelegate(ILambdaInvocationContext context) - { - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - _ = context.ServiceProvider; - - var lambdaEvent = context.GetRequiredEvent(); - var splitItems = split(lambdaEvent, context); - if (splitItems is null) - throw new InvalidOperationException("The event splitter 'split' returned null."); - - var items = new List(); - using (var enumerator = splitItems.GetEnumerator()) - { - while (enumerator.MoveNext()) - { - context.CancellationToken.ThrowIfCancellationRequested(); - items.Add(enumerator.Current); - } - } - - var itemArray = items.ToArray(); - - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - using var state = new EventProcessingState( - context, - logger, - itemArray.Length); - var outcomes = await EventProcessorRuntime - .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, true) - .ConfigureAwait(false); - - var contributions = new List(outcomes!.Length); - foreach (var outcome in outcomes) - if (outcome.HasValue) - contributions.Add(outcome.Value!); - - var response = createResponse( - new ReadOnlyCollection(contributions), - context); - - if (context.Features.Get() is not IResponseFeature responseFeature) - throw new InvalidOperationException( - "Response feature for type 'global::Response' is not available in the collection."); - responseFeature.SetResponse(response); - } - - async Task> Adapt( + Task HandleItem( global::Item item, IServiceProvider serviceProvider, - EventProcessingState processingContext) + IEventProcessingContext processingContext) { var arg0 = item; - - var invocationToken = processingContext.Invocation.CancellationToken; - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - if (processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - Task? handlerTask = null; - - Exception? synchronousFault = null; - try - { - handlerTask = handle(arg0); - } - catch (Exception ex) - { - synchronousFault = ex; - } - - if (synchronousFault is null && handlerTask is null) - throw new InvalidOperationException("The event handler 'handle' returned a null task."); - - try - { - if (synchronousFault is not null) - ExceptionDispatchInfo.Capture(synchronousFault).Throw(); - - await handlerTask!.ConfigureAwait(false); - } - catch (Exception ex) - { - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - ex, - invocationToken); - - if (ex is OperationCanceledException - && processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - throw; - } - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - invocationToken); - - return ItemOutcome.FromValue(item); + return handle(arg0); } } [InterceptsLocation(1, "REPLACED")] @@ -313,154 +99,33 @@ internal static ILambdaInvocationBuilder MapEventHandlerInterceptor2( this ILambdaInvocationBuilder application, global::System.Func> split, global::System.Func handle, - global::System.Func onError, - global::System.Func, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) + global::System.Func onError, + global::System.Func>, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) { - ArgumentNullException.ThrowIfNull(application); - ArgumentNullException.ThrowIfNull(split); ArgumentNullException.ThrowIfNull(handle); - ArgumentNullException.ThrowIfNull(onError); - ArgumentNullException.ThrowIfNull(createResponse); - - var options = application.Services.GetRequiredService>().Value; - var effectiveConcurrency = options.EnableConcurrency - ? options.MaxConcurrentExecutions - : 1; - var scopeFactory = application.Services.GetRequiredService(); - var logger = application - .Services.GetService() - ?.CreateLogger("MinimalLambda.EventProcessor"); - - application.Handle(InvocationDelegate); - - if (!application.Properties.ContainsKey(EventFeatureProviderKey)) - application.Properties[EventFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - - if (!application.Properties.ContainsKey(ResponseFeatureProviderKey)) - application.Properties[ResponseFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - + var terminal = EventHandlerFactory.Create( + application.Services, + split, + HandleItem, + onError, + createResponse); + + application.Handle(terminal); + if (!application.Properties.ContainsKey("__EventFeatureProvider")) + application.Properties["__EventFeatureProvider"] = application.Services + .GetRequiredService().Create(); + if (!application.Properties.ContainsKey("__ResponseFeatureProvider")) + application.Properties["__ResponseFeatureProvider"] = application.Services + .GetRequiredService().Create(); return application; - async Task InvocationDelegate(ILambdaInvocationContext context) - { - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - _ = context.ServiceProvider; - - var lambdaEvent = context.GetRequiredEvent(); - var splitItems = split(lambdaEvent, context); - if (splitItems is null) - throw new InvalidOperationException("The event splitter 'split' returned null."); - - var items = new List(); - using (var enumerator = splitItems.GetEnumerator()) - { - while (enumerator.MoveNext()) - { - context.CancellationToken.ThrowIfCancellationRequested(); - items.Add(enumerator.Current); - } - } - - var itemArray = items.ToArray(); - - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - using var state = new EventProcessingState( - context, - logger, - itemArray.Length); - var outcomes = await EventProcessorRuntime - .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, true) - .ConfigureAwait(false); - - var contributions = new List(outcomes!.Length); - foreach (var outcome in outcomes) - if (outcome.HasValue) - contributions.Add(outcome.Value!); - - var response = createResponse( - new ReadOnlyCollection(contributions), - context); - - if (context.Features.Get() is not IResponseFeature responseFeature) - throw new InvalidOperationException( - "Response feature for type 'global::Response' is not available in the collection."); - responseFeature.SetResponse(response); - } - - async Task> Adapt( + Task HandleItem( global::Item item, IServiceProvider serviceProvider, - EventProcessingState processingContext) + IEventProcessingContext processingContext) { var arg0 = item; - - var invocationToken = processingContext.Invocation.CancellationToken; - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - if (processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - Task? handlerTask = null; - - Exception? synchronousFault = null; - try - { - handlerTask = handle(arg0); - } - catch (Exception ex) - { - synchronousFault = ex; - } - - if (synchronousFault is null && handlerTask is null) - throw new InvalidOperationException("The event handler 'handle' returned a null task."); - - try - { - if (synchronousFault is not null) - ExceptionDispatchInfo.Capture(synchronousFault).Throw(); - - await handlerTask!.ConfigureAwait(false); - } - catch (Exception ex) - { - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - ex, - invocationToken); - - if (ex is OperationCanceledException - && processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - - var mapped = onError(item, ex, processingContext); - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while mapping an item error.", - invocationToken); - - return ItemOutcome.FromMappedValue(mapped); - } - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - invocationToken); - - return ItemOutcome.NoValue; + return handle(arg0); } } [InterceptsLocation(1, "REPLACED")] @@ -468,142 +133,31 @@ internal static ILambdaInvocationBuilder MapEventHandlerInterceptor3( this ILambdaInvocationBuilder application, global::System.Func> split, global::System.Func> handle, - global::System.Func, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) + global::System.Func>, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) { - ArgumentNullException.ThrowIfNull(application); - ArgumentNullException.ThrowIfNull(split); ArgumentNullException.ThrowIfNull(handle); - ArgumentNullException.ThrowIfNull(createResponse); - - var options = application.Services.GetRequiredService>().Value; - var effectiveConcurrency = options.EnableConcurrency - ? options.MaxConcurrentExecutions - : 1; - var scopeFactory = application.Services.GetRequiredService(); - var logger = application - .Services.GetService() - ?.CreateLogger("MinimalLambda.EventProcessor"); - - application.Handle(InvocationDelegate); - - if (!application.Properties.ContainsKey(EventFeatureProviderKey)) - application.Properties[EventFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - - if (!application.Properties.ContainsKey(ResponseFeatureProviderKey)) - application.Properties[ResponseFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - + var terminal = EventHandlerFactory.Create( + application.Services, + split, + HandleItem, + createResponse); + + application.Handle(terminal); + if (!application.Properties.ContainsKey("__EventFeatureProvider")) + application.Properties["__EventFeatureProvider"] = application.Services + .GetRequiredService().Create(); + if (!application.Properties.ContainsKey("__ResponseFeatureProvider")) + application.Properties["__ResponseFeatureProvider"] = application.Services + .GetRequiredService().Create(); return application; - async Task InvocationDelegate(ILambdaInvocationContext context) - { - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - _ = context.ServiceProvider; - - var lambdaEvent = context.GetRequiredEvent(); - var splitItems = split(lambdaEvent, context); - if (splitItems is null) - throw new InvalidOperationException("The event splitter 'split' returned null."); - - var items = new List(); - using (var enumerator = splitItems.GetEnumerator()) - { - while (enumerator.MoveNext()) - { - context.CancellationToken.ThrowIfCancellationRequested(); - items.Add(enumerator.Current); - } - } - - var itemArray = items.ToArray(); - - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - using var state = new EventProcessingState( - context, - logger, - itemArray.Length); - var outcomes = await EventProcessorRuntime - .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, true) - .ConfigureAwait(false); - - var contributions = new List(outcomes!.Length); - foreach (var outcome in outcomes) - if (outcome.HasValue) - contributions.Add(outcome.Value!); - - var response = createResponse( - new ReadOnlyCollection(contributions), - context); - - if (context.Features.Get() is not IResponseFeature responseFeature) - throw new InvalidOperationException( - "Response feature for type 'global::Response' is not available in the collection."); - responseFeature.SetResponse(response); - } - - async Task> Adapt( + Task HandleItem( global::Item item, IServiceProvider serviceProvider, - EventProcessingState processingContext) + IEventProcessingContext processingContext) { var arg0 = item; - - var invocationToken = processingContext.Invocation.CancellationToken; - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - if (processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - Task? handlerTask = null; - int handlerResult = default!; - Exception? synchronousFault = null; - try - { - handlerTask = handle(arg0); - } - catch (Exception ex) - { - synchronousFault = ex; - } - - if (synchronousFault is null && handlerTask is null) - throw new InvalidOperationException("The event handler 'handle' returned a null task."); - - try - { - if (synchronousFault is not null) - ExceptionDispatchInfo.Capture(synchronousFault).Throw(); - - handlerResult = await handlerTask!.ConfigureAwait(false); - } - catch (Exception ex) - { - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - ex, - invocationToken); - - if (ex is OperationCanceledException - && processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - throw; - } - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - invocationToken); - - return ItemOutcome.FromValue(handlerResult); + return handle(arg0); } } [InterceptsLocation(1, "REPLACED")] @@ -611,583 +165,33 @@ internal static ILambdaInvocationBuilder MapEventHandlerInterceptor4( this ILambdaInvocationBuilder application, global::System.Func> split, global::System.Func> handle, - global::System.Func onError, - global::System.Func, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) + global::System.Func onError, + global::System.Func>, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) { - ArgumentNullException.ThrowIfNull(application); - ArgumentNullException.ThrowIfNull(split); ArgumentNullException.ThrowIfNull(handle); - ArgumentNullException.ThrowIfNull(onError); - ArgumentNullException.ThrowIfNull(createResponse); - - var options = application.Services.GetRequiredService>().Value; - var effectiveConcurrency = options.EnableConcurrency - ? options.MaxConcurrentExecutions - : 1; - var scopeFactory = application.Services.GetRequiredService(); - var logger = application - .Services.GetService() - ?.CreateLogger("MinimalLambda.EventProcessor"); - - application.Handle(InvocationDelegate); - - if (!application.Properties.ContainsKey(EventFeatureProviderKey)) - application.Properties[EventFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - - if (!application.Properties.ContainsKey(ResponseFeatureProviderKey)) - application.Properties[ResponseFeatureProviderKey] = application - .Services.GetRequiredService() - .Create(); - + var terminal = EventHandlerFactory.Create( + application.Services, + split, + HandleItem, + onError, + createResponse); + + application.Handle(terminal); + if (!application.Properties.ContainsKey("__EventFeatureProvider")) + application.Properties["__EventFeatureProvider"] = application.Services + .GetRequiredService().Create(); + if (!application.Properties.ContainsKey("__ResponseFeatureProvider")) + application.Properties["__ResponseFeatureProvider"] = application.Services + .GetRequiredService().Create(); return application; - async Task InvocationDelegate(ILambdaInvocationContext context) - { - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - _ = context.ServiceProvider; - - var lambdaEvent = context.GetRequiredEvent(); - var splitItems = split(lambdaEvent, context); - if (splitItems is null) - throw new InvalidOperationException("The event splitter 'split' returned null."); - - var items = new List(); - using (var enumerator = splitItems.GetEnumerator()) - { - while (enumerator.MoveNext()) - { - context.CancellationToken.ThrowIfCancellationRequested(); - items.Add(enumerator.Current); - } - } - - var itemArray = items.ToArray(); - - if (context.CancellationToken.IsCancellationRequested) - throw new OperationCanceledException(context.CancellationToken); - - using var state = new EventProcessingState( - context, - logger, - itemArray.Length); - var outcomes = await EventProcessorRuntime - .RunAsync(itemArray, effectiveConcurrency, scopeFactory, state, Adapt, true) - .ConfigureAwait(false); - - var contributions = new List(outcomes!.Length); - foreach (var outcome in outcomes) - if (outcome.HasValue) - contributions.Add(outcome.Value!); - - var response = createResponse( - new ReadOnlyCollection(contributions), - context); - - if (context.Features.Get() is not IResponseFeature responseFeature) - throw new InvalidOperationException( - "Response feature for type 'global::Response' is not available in the collection."); - responseFeature.SetResponse(response); - } - - async Task> Adapt( + Task HandleItem( global::Item item, IServiceProvider serviceProvider, - EventProcessingState processingContext) + IEventProcessingContext processingContext) { var arg0 = item; - - var invocationToken = processingContext.Invocation.CancellationToken; - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - if (processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - Task? handlerTask = null; - int handlerResult = default!; - Exception? synchronousFault = null; - try - { - handlerTask = handle(arg0); - } - catch (Exception ex) - { - synchronousFault = ex; - } - - if (synchronousFault is null && handlerTask is null) - throw new InvalidOperationException("The event handler 'handle' returned a null task."); - - try - { - if (synchronousFault is not null) - ExceptionDispatchInfo.Capture(synchronousFault).Throw(); - - handlerResult = await handlerTask!.ConfigureAwait(false); - } - catch (Exception ex) - { - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - ex, - invocationToken); - - if (ex is OperationCanceledException - && processingContext.CancellationToken.IsCancellationRequested) - return ItemOutcome.Cancelled; - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException(invocationToken); - - var mapped = onError(item, ex, processingContext); - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while mapping an item error.", - invocationToken); - - return ItemOutcome.FromMappedValue(mapped); - } - - if (invocationToken.IsCancellationRequested) - throw new OperationCanceledException( - "The Lambda invocation was cancelled while processing an item.", - invocationToken); - - return ItemOutcome.FromValue(handlerResult); - } - } - } - - file readonly struct NoData; - - file enum ItemExecutionState - { - Unstarted, - Succeeded, - MappedError, - Cancelled, - } - - file readonly struct ItemOutcome - { - private ItemOutcome(ItemExecutionState state, bool hasValue, TValue? value) - { - State = state; - HasValue = hasValue; - Value = value; - } - - internal ItemExecutionState State { get; } - - internal bool HasValue { get; } - - internal TValue? Value { get; } - - internal static ItemOutcome FromValue(TValue? value) => - new(ItemExecutionState.Succeeded, true, value); - - internal static ItemOutcome FromMappedValue(TValue? value) => - new(ItemExecutionState.MappedError, true, value); - - internal static ItemOutcome NoValue => - new(ItemExecutionState.Succeeded, false, default); - - internal static ItemOutcome Cancelled => - new(ItemExecutionState.Cancelled, false, default); - } - - file sealed class EventProcessingState : IEventProcessingContext, IDisposable - { - private readonly object _gate = new(); - private readonly ILambdaInvocationContext _invocation; - private readonly ILogger? _logger; - private readonly int _itemCount; - private readonly CancellationTokenSource _processingSource = new(); - private readonly CancellationTokenRegistration _invocationRegistration; - - private int _nextIndex; - private int _admitted; - private bool _stopRequested; - private bool _cancelRequested; - private bool _handlingClosed; - private bool _completed; - private bool _invocationCancelled; - private bool _disposed; - private ExceptionDispatchInfo? _firstFatal; - private List? _additionalFatal; - private TaskCompletionSource? _dispatchCompletion; - - internal EventProcessingState( - ILambdaInvocationContext invocation, - ILogger? logger, - int itemCount) - { - _invocation = invocation; - _logger = logger; - _itemCount = itemCount; - _invocationRegistration = invocation.CancellationToken.Register( - static state => ((EventProcessingState)state!).OnInvocationTokenCancelled(), - this); - } - - public ILambdaInvocationContext Invocation => _invocation; - - public CancellationToken CancellationToken => _processingSource.Token; - - public void StopProcessing() - { - lock (_gate) - { - if (_completed || _handlingClosed) - return; - - _stopRequested = true; - TryCloseHandlingCore(); - } - } - - public void CancelProcessing() => RequestProcessingCancellation(false); - - internal bool TryClaim(out int index) - { - TaskCompletionSource? dispatch = null; - var claimed = false; - index = -1; - - lock (_gate) - { - if (_completed) - return false; - - ObserveInvocationCancellationCore(ref dispatch); - - if (_handlingClosed - || _stopRequested - || _firstFatal is not null - || _nextIndex >= _itemCount) - { - TryCloseHandlingCore(); - } - else - { - index = _nextIndex++; - _admitted++; - claimed = true; - } - } - - if (dispatch is not null) - StartDispatch(dispatch); - - return claimed; - } - - internal bool IsInvocationCancellationLatched - { - get - { - lock (_gate) - return _invocationCancelled; - } - } - - internal void CompleteAdmission() - { - lock (_gate) - { - if (_admitted > 0) - _admitted--; - - TryCloseHandlingCore(); - } - } - - internal bool TryLatchInvocationCancellation() - { - if (!_invocation.CancellationToken.IsCancellationRequested) - return false; - - RequestProcessingCancellation(true); - - lock (_gate) - return _invocationCancelled; - } - - internal void RecordFatal(Exception exception) - { - lock (_gate) - { - if (_completed) - return; - - _stopRequested = true; - var fatal = ExceptionDispatchInfo.Capture(exception); - if (_firstFatal is null) - _firstFatal = fatal; - else - (_additionalFatal ??= []).Add(exception); - - TryCloseHandlingCore(); - } - } - - internal void TryCloseHandling() - { - lock (_gate) - TryCloseHandlingCore(); - } - - internal async Task JoinAsync() - { - Task? dispatch; - lock (_gate) - { - TryCloseHandlingCore(); - dispatch = _dispatchCompletion?.Task; - } - - if (dispatch is not null) - await dispatch.ConfigureAwait(false); - - Completion completion; - lock (_gate) - { - TryCloseHandlingCore(); - _completed = true; - completion = new Completion( - _invocationCancelled, - _firstFatal, - _additionalFatal); - } - - completion.LogAdditional(_logger); - - if (completion.InvocationCancelled) - throw new OperationCanceledException( - "The Lambda invocation was cancelled during item processing.", - _invocation.CancellationToken); - - if (completion.FirstFatal is not null) - { - completion.FirstFatal.Throw(); - throw new InvalidOperationException("Unreachable"); - } - } - - public void Dispose() - { - if (_disposed) - return; - - _disposed = true; - _invocationRegistration.Dispose(); - _processingSource.Dispose(); - } - - private void OnInvocationTokenCancelled() => RequestProcessingCancellation(true); - - private void RequestProcessingCancellation(bool invocationCancelled) - { - TaskCompletionSource? dispatch = null; - lock (_gate) - { - if (_completed || _handlingClosed) - return; - - if (invocationCancelled) - _invocationCancelled = true; - - _stopRequested = true; - - if (!_cancelRequested) - { - _cancelRequested = true; - _dispatchCompletion = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously); - dispatch = _dispatchCompletion; - } - - TryCloseHandlingCore(); - } - - if (dispatch is not null) - StartDispatch(dispatch); - } - - private void ObserveInvocationCancellationCore(ref TaskCompletionSource? dispatch) - { - if (_handlingClosed || !_invocation.CancellationToken.IsCancellationRequested) - return; - - _invocationCancelled = true; - _stopRequested = true; - - if (_cancelRequested) - return; - - _cancelRequested = true; - _dispatchCompletion = new TaskCompletionSource( - TaskCreationOptions.RunContinuationsAsynchronously); - dispatch = _dispatchCompletion; - } - - private void TryCloseHandlingCore() - { - if (_handlingClosed) - return; - - if (_admitted > 0) - return; - - if (_nextIndex < _itemCount - && !_stopRequested - && _firstFatal is null - && !_invocation.CancellationToken.IsCancellationRequested) - return; - - if (_invocation.CancellationToken.IsCancellationRequested) - { - _invocationCancelled = true; - _stopRequested = true; - } - - _handlingClosed = true; - } - - private void StartDispatch(TaskCompletionSource completion) => - _ = DispatchCancellationAsync(completion); - - private async Task DispatchCancellationAsync(TaskCompletionSource completion) - { - try - { - await _processingSource.CancelAsync().ConfigureAwait(false); - } - catch (Exception ex) - { - RecordFatal(ex); - } - finally - { - completion.TrySetResult(); - } - } - - private readonly struct Completion( - bool invocationCancelled, - ExceptionDispatchInfo? firstFatal, - List? additionalFatal) - { - internal bool InvocationCancelled { get; } = invocationCancelled; - - internal ExceptionDispatchInfo? FirstFatal { get; } = firstFatal; - - internal void LogAdditional(ILogger? logger) - { - if (logger is null || additionalFatal is null) - return; - - foreach (var exception in additionalFatal) - try - { - logger.LogError( - exception, - "Event processor observed an additional failure while draining item work."); - } - catch - { - // Logging must not replace the selected invocation error. - } - } - } - } - - file static class EventProcessorRuntime - { - internal static async Task[]?> RunAsync( - TItem[] items, - int effectiveConcurrency, - IServiceScopeFactory scopeFactory, - EventProcessingState state, - Func>> adapter, - bool collectValues) - { - if (items.Length == 0) - state.TryCloseHandling(); - - var outcomes = collectValues ? new ItemOutcome[items.Length] : null; - var workerCount = Math.Min(items.Length, Math.Max(1, effectiveConcurrency)); - var workers = new Task[workerCount]; - - for (var index = 0; index < workerCount; index++) - workers[index] = RunWorkerAsync(); - - await Task.WhenAll(workers).ConfigureAwait(false); - await state.JoinAsync().ConfigureAwait(false); - - return outcomes; - - async Task RunWorkerAsync() - { - while (state.TryClaim(out var index)) - { - if (state.IsInvocationCancellationLatched) - { - state.CompleteAdmission(); - continue; - } - - AsyncServiceScope scope; - try - { - scope = scopeFactory.CreateAsyncScope(); - } - catch (Exception ex) - { - state.RecordFatal(ex); - state.CompleteAdmission(); - continue; - } - - ItemOutcome outcome = default; - var hasOutcome = false; - - try - { - try - { - outcome = await adapter(items[index], scope.ServiceProvider, state) - .ConfigureAwait(false); - hasOutcome = true; - } - catch (Exception ex) - { - if (!state.TryLatchInvocationCancellation()) - state.RecordFatal(ex); - } - } - finally - { - state.CompleteAdmission(); - } - - try - { - await scope.DisposeAsync().ConfigureAwait(false); - } - catch (Exception ex) - { - state.RecordFatal(ex); - } - - if (collectValues && hasOutcome && outcome.HasValue) - outcomes![index] = outcome; - } + return handle(arg0); } } } diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsTypedDelegateAndExplicitGenericMethodGroupBindings#MinimalLambda.EventHandlers.g.verified.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsTypedDelegateAndExplicitGenericMethodGroupBindings#MinimalLambda.EventHandlers.g.verified.cs new file mode 100644 index 00000000..1802ba7d --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsTypedDelegateAndExplicitGenericMethodGroupBindings#MinimalLambda.EventHandlers.g.verified.cs @@ -0,0 +1,105 @@ +//HintName: MinimalLambda.EventHandlers.g.cs +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +#nullable enable + +namespace System.Runtime.CompilerServices +{ + using System.CodeDom.Compiler; + + [global::System.CodeDom.Compiler.GeneratedCode("MinimalLambda.SourceGenerators", "REPLACED")] + [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] + file sealed class InterceptsLocationAttribute : Attribute + { + public InterceptsLocationAttribute(int version, string data) { } + } +} + +namespace MinimalLambda.Generated +{ + using System; + using System.Runtime.CompilerServices; + using System.Threading.Tasks; + using Microsoft.Extensions.DependencyInjection; + using MinimalLambda.Builder; + using MinimalLambda.EventProcessing; + using MinimalLambda; + + [global::System.CodeDom.Compiler.GeneratedCode("MinimalLambda.SourceGenerators", "REPLACED")] + file static class GeneratedEventProcessorExtensions + { + [InterceptsLocation(1, "REPLACED")] + internal static ILambdaInvocationBuilder MapEventHandlerInterceptor0( + this ILambdaInvocationBuilder application, + global::System.Func> split, + global::System.Func> handle, + global::System.Func>, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) + { + ArgumentNullException.ThrowIfNull(handle); + var terminal = EventHandlerFactory.Create( + application.Services, + split, + HandleItem, + createResponse); + + application.Handle(terminal); + if (!application.Properties.ContainsKey("__EventFeatureProvider")) + application.Properties["__EventFeatureProvider"] = application.Services + .GetRequiredService().Create(); + if (!application.Properties.ContainsKey("__ResponseFeatureProvider")) + application.Properties["__ResponseFeatureProvider"] = application.Services + .GetRequiredService().Create(); + return application; + + Task HandleItem( + global::Item item, + IServiceProvider serviceProvider, + IEventProcessingContext processingContext) + { + var arg0 = item; + var arg1 = serviceProvider.GetRequiredService(); + return handle(arg0, arg1); + } + } + [InterceptsLocation(1, "REPLACED")] + internal static ILambdaInvocationBuilder MapEventHandlerInterceptor1( + this ILambdaInvocationBuilder application, + global::System.Func> split, + global::System.Func> handle, + global::System.Func>, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) + { + ArgumentNullException.ThrowIfNull(handle); + var terminal = EventHandlerFactory.Create( + application.Services, + split, + HandleItem, + createResponse); + + application.Handle(terminal); + if (!application.Properties.ContainsKey("__EventFeatureProvider")) + application.Properties["__EventFeatureProvider"] = application.Services + .GetRequiredService().Create(); + if (!application.Properties.ContainsKey("__ResponseFeatureProvider")) + application.Properties["__ResponseFeatureProvider"] = application.Services + .GetRequiredService().Create(); + return application; + + Task HandleItem( + global::Item item, + IServiceProvider serviceProvider, + IEventProcessingContext processingContext) + { + var arg0 = item; + var arg1 = serviceProvider.GetRequiredService(); + return handle(arg0, arg1); + } + } + } +} diff --git a/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/MinimalLambda.Testing.UnitTests.EventProcessorLambda.csproj b/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/MinimalLambda.Testing.UnitTests.EventProcessorLambda.csproj index 4dff3634..d3af1a50 100644 --- a/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/MinimalLambda.Testing.UnitTests.EventProcessorLambda.csproj +++ b/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/MinimalLambda.Testing.UnitTests.EventProcessorLambda.csproj @@ -1,4 +1,4 @@ - + Exe net8.0;net9.0;net10.0 @@ -30,4 +30,6 @@ PreserveNewest + + \ No newline at end of file diff --git a/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/Program.cs b/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/Program.cs index 795d9011..219f4426 100644 --- a/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/Program.cs +++ b/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/Program.cs @@ -1,51 +1,96 @@ -using System.Collections.Concurrent; +using MinimalLambda.EventProcessing; +using System.Collections.Concurrent; using System.Text.Json.Serialization; using Amazon.Lambda.SQSEvents; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using MinimalLambda; using MinimalLambda.Builder; +using MinimalLambda.Envelopes; +using MinimalLambda.Envelopes.Sqs; +using MinimalLambda.Options; var builder = LambdaApplication.CreateBuilder(); builder.Services.AddLambdaSerializerWithContext(); builder.Services.AddSingleton(); +builder.Services.AddScoped(); +builder.Services.AddKeyedSingleton("primary", "keyed"); +builder.Services.ConfigureEnvelopeOptions(options => + options.JsonOptions.TypeInfoResolver = EventProcessorLambdaJsonContext.Default); await using var lambda = builder.Build(); +lambda.UseMiddleware(async (context, next) => +{ + var probe = context.ServiceProvider.GetRequiredService(); + probe.MiddlewareEvent = context.GetRequiredEvent>(); + probe.Stages.Enqueue("before"); + await next(context); + probe.Packed = + ((IResponseFeature)context.Features.Get()!).GetResponse()! + .Packed; + probe.Stages.Enqueue("after"); +}); + lambda.MapEventHandler( - split: (SQSEvent batch, ILambdaInvocationContext _) => batch.Records, + split: (SqsEnvelope batch, ILambdaInvocationContext context) => + { + var probe = context.ServiceProvider.GetRequiredService(); + probe.SplitEvent = batch; + probe.Stages.Enqueue("split"); + return batch.Records; + }, handle: async Task ( - SQSEvent.SQSMessage item, + SqsEnvelope.SqsMessageEnvelope item, RecordProbe probe, + ItemScopeProbe scope, + [FromKeyedServices("primary")] string keyed, + OptionalMarker? optional, IEventProcessingContext processing, CancellationToken token) => { token.ThrowIfCancellationRequested(); + if (keyed != "keyed" || optional is not null || processing.Invocation is null) + throw new InvalidOperationException("incorrect argument binding"); + probe.ScopeIds.Enqueue(scope.Id); + probe.Stages.Enqueue("handle"); probe.Record(item.MessageId); - if (item.Body is "stop") + if (item.BodyContent is "stop") { processing.StopProcessing(); return new Success(item.MessageId); } - if (item.Body is "retry" or "fatal") + if (item.BodyContent is "retry" or "fatal") throw new InvalidOperationException("retry requested"); await Task.Yield(); return new Success(item.MessageId); }, onError: (item, _, _) => - item.Body == "fatal" + item.BodyContent == "fatal" ? throw new InvalidOperationException("mapper failed") : new Retry(item.MessageId), - createResponse: (results, _) => new SQSBatchResponse( - results - .OfType() - .Select(result => - new SQSBatchResponse.BatchItemFailure { ItemIdentifier = result.MessageId, }) - .ToList())); + createResponse: (outcomes, context) => + { + context.ServiceProvider.GetRequiredService().Stages.Enqueue("response"); + return new BatchResponse + { + BatchItemFailures = outcomes + .Where(outcome => + outcome.Status is EventItemStatus.MappedError + or EventItemStatus.Skipped + or EventItemStatus.Cancelled) + .Select(outcome => + new SQSBatchResponse.BatchItemFailure + { + ItemIdentifier = outcome.Item.MessageId + }) + .ToList(), + }; + }); await lambda.RunAsync(); @@ -58,6 +103,13 @@ internal sealed record Retry(string MessageId) : ImportResult; internal sealed class RecordProbe { private readonly ConcurrentQueue messageIds = new(); + public SqsEnvelope? MiddlewareEvent { get; set; } + public SqsEnvelope? SplitEvent { get; set; } + public ConcurrentQueue Stages { get; } = new(); + public ConcurrentQueue ScopeIds { get; } = new(); + public bool Packed { get; set; } + public bool ThrowOnDispose { get; set; } + public int Disposed; public IReadOnlyCollection MessageIds => messageIds.ToArray(); @@ -66,6 +118,32 @@ internal sealed class RecordProbe public class EventProcessorLambda; -[JsonSerializable(typeof(SQSEvent))] +internal sealed class OptionalMarker; + +internal sealed class ItemScopeProbe(RecordProbe probe) : IAsyncDisposable +{ + private static int nextId; + public int Id { get; } = Interlocked.Increment(ref nextId); + + public async ValueTask DisposeAsync() + { + await Task.Yield(); + Interlocked.Increment(ref probe.Disposed); + if (probe.ThrowOnDispose) + throw new InvalidOperationException("scope cleanup failed"); + } +} + +internal sealed class BatchResponse : SQSBatchResponse, IResponseEnvelope +{ + [JsonIgnore] + public bool Packed { get; private set; } + + public void PackPayload(EnvelopeOptions options) => Packed = true; +} + +[JsonSerializable(typeof(SqsEnvelope))] +[JsonSerializable(typeof(string))] +[JsonSerializable(typeof(BatchResponse))] [JsonSerializable(typeof(SQSBatchResponse))] internal partial class EventProcessorLambdaJsonContext : JsonSerializerContext; diff --git a/tests/MinimalLambda.Testing.UnitTests/Tests/MinimalLambda.Testing.UnitTests/EventProcessorLambdaTests.cs b/tests/MinimalLambda.Testing.UnitTests/Tests/MinimalLambda.Testing.UnitTests/EventProcessorLambdaTests.cs index 54d332db..87172fa5 100644 --- a/tests/MinimalLambda.Testing.UnitTests/Tests/MinimalLambda.Testing.UnitTests/EventProcessorLambdaTests.cs +++ b/tests/MinimalLambda.Testing.UnitTests/Tests/MinimalLambda.Testing.UnitTests/EventProcessorLambdaTests.cs @@ -1,7 +1,7 @@ using System.Text.Json; using Amazon.Lambda.SQSEvents; using Microsoft.Extensions.DependencyInjection; -using MinimalLambda.Options; +using MinimalLambda.EventProcessing; namespace MinimalLambda.Testing.UnitTests; @@ -139,8 +139,7 @@ public async Task EventProcessorLambda_SerializesFailureResponseWithMessageIdsOn } [Fact] - public async Task - EventProcessorLambda_SequentialStopAbandonsLaterRecordsAndKeepsEarlierIdentity() + public async Task EventProcessorLambda_SequentialStopReportsUnprocessedRecordsAsFailures() { // Arrange await using var factory = LambdaTestFactory @@ -165,16 +164,13 @@ public async Task response.WasSuccess.Should().BeTrue(); response.Response.Should().NotBeNull(); - // The stop record succeeds and commits; records after it are abandoned, so the response - // only - // reports the failure that completed before the stop and never claims the omitted - // identities. + // The application retries every failed or unstarted source position. response .Response .BatchItemFailures .Select(failure => failure.ItemIdentifier) .Should() - .Equal("id-1"); + .Equal("id-1", "id-3", "id-4"); factory .Services .GetRequiredService() @@ -183,6 +179,66 @@ public async Task .Equal("id-1", "id-2"); } + [Fact] + public async Task EventProcessorLambda_SharesFullEventAndPacksResponseThroughMiddleware() + { + await using var factory = + LambdaTestFactory + .Create() + .WithCancellationToken(TestContext.Current.CancellationToken); + factory.ServerOptions.FunctionTimeout = TestFunctionTimeout; + var response = await factory.TestServer.InvokeAsync( + CreateEvent(("id-1", "ok"), ("id-2", "ok")), + TestContext.Current.CancellationToken); + response.WasSuccess.Should().BeTrue(); + var probe = factory.Services.GetRequiredService(); + probe.MiddlewareEvent.Should().BeSameAs(probe.SplitEvent); + probe.SplitEvent!.Records.Select(item => item.BodyContent).Should().Equal("ok", "ok"); + probe.ScopeIds.Should().OnlyHaveUniqueItems().And.HaveCount(2); + probe.Disposed.Should().Be(2); + probe.Packed.Should().BeTrue(); + probe.Stages.Should().Equal("before", "split", "handle", "handle", "response", "after"); + } + + [Fact] + public async Task EventProcessorLambda_DisposalFailureSuppressesSerializedResponse() + { + await using var factory = + LambdaTestFactory + .Create() + .WithCancellationToken(TestContext.Current.CancellationToken); + factory.ServerOptions.FunctionTimeout = TestFunctionTimeout; + factory.Services.GetRequiredService().ThrowOnDispose = true; + var response = await factory.TestServer.InvokeAsync( + CreateEvent(("id-1", "ok")), + TestContext.Current.CancellationToken); + response.WasSuccess.Should().BeFalse(); + response.Error.Should().NotBeNull(); + factory.Services.GetRequiredService().Stages.Should().NotContain("response"); + } + + [Fact] + public async Task EventProcessorLambda_MapsItemResolutionFailuresIntoSerializedResponse() + { + await using var factory = + LambdaTestFactory + .Create() + .WithCancellationToken(TestContext.Current.CancellationToken) + .WithHostBuilder(builder => builder.ConfigureServices((_, services) => + services.AddScoped(_ => + throw new InvalidOperationException("item resolution")))); + factory.ServerOptions.FunctionTimeout = TestFunctionTimeout; + var response = await factory.TestServer.InvokeAsync( + CreateEvent(("id-1", "ok"), ("id-2", "ok")), + TestContext.Current.CancellationToken); + response.WasSuccess.Should().BeTrue(); + response.Response! + .BatchItemFailures + .Select(item => item.ItemIdentifier) + .Should() + .Equal("id-1", "id-2"); + } + private static SQSEvent CreateEvent(params (string MessageId, string Body)[] records) => new() { @@ -192,7 +248,7 @@ private static SQSEvent CreateEvent(params (string MessageId, string Body)[] rec { MessageId = record.MessageId, ReceiptHandle = "receipt-" + record.MessageId, - Body = record.Body, + Body = JsonSerializer.Serialize(record.Body), }), ], }; diff --git a/tests/MinimalLambda.UnitTests/Builder/Extensions/ServiceCollectionExtensionsTests.cs b/tests/MinimalLambda.UnitTests/Builder/Extensions/ServiceCollectionExtensionsTests.cs index a3786ec6..b73c51ca 100644 --- a/tests/MinimalLambda.UnitTests/Builder/Extensions/ServiceCollectionExtensionsTests.cs +++ b/tests/MinimalLambda.UnitTests/Builder/Extensions/ServiceCollectionExtensionsTests.cs @@ -46,58 +46,19 @@ public void AddLambdaHostCoreServices_DoesNotRequireLambdaSerializerUntilInvocat } [Fact] - public void AddLambdaHostCoreServices_RegistersSingleEventHandlerOptionsValidator() + public void AddLambdaHostCoreServices_RegistersExactlyNineteenCoreServices() { - // Arrange - using var serviceProvider = new ServiceCollection() - .AddLambdaHostCoreServices() - .AddLambdaHostCoreServices() - .BuildServiceProvider(); - - // Act - var validators = serviceProvider.GetServices>(); - - // Assert - validators.Should().ContainSingle(); + var serviceCollection = new ServiceCollection(); + serviceCollection.AddLambdaHostCoreServices(); + serviceCollection.Should().HaveCount(19); } [Fact] - public void AddLambdaHostCoreServices_PreservesUserEventHandlerConfiguration() + public void AddLambdaHostCoreServices_PreservesCoreOptionsWithoutEventProcessing() { - // Arrange - using var serviceProvider = new ServiceCollection() - .AddLambdaHostCoreServices() - .Configure(options => - { - options.EnableConcurrency = false; - options.MaxConcurrentExecutions = 3; - }) - .BuildServiceProvider(); - - // Act - var options = serviceProvider.GetRequiredService>().Value; - - // Assert - options.EnableConcurrency.Should().BeFalse(); - options.MaxConcurrentExecutions.Should().Be(3); - } - - [Theory] -#if NET11_0_OR_GREATER - [InlineData(24)] -#else - [InlineData(22)] -#endif - public void AddLambdaHostCoreServices_RegistersExactlyNServices(int servicesCount) - { - // Arrange - var serviceCollection = new ServiceCollection(); - - // Act - serviceCollection.AddLambdaHostCoreServices(); - - // Assert - serviceCollection.Should().HaveCount(servicesCount); + using var services = + new ServiceCollection().AddLambdaHostCoreServices().BuildServiceProvider(); + services.GetRequiredService>().Value.Should().NotBeNull(); } [Fact] diff --git a/tests/package-compatibility/CoreOnlyConsumer/CoreOnlyConsumer.csproj b/tests/package-compatibility/CoreOnlyConsumer/CoreOnlyConsumer.csproj new file mode 100644 index 00000000..3a7a91cf --- /dev/null +++ b/tests/package-compatibility/CoreOnlyConsumer/CoreOnlyConsumer.csproj @@ -0,0 +1 @@ +net10.0Exepreviewenableenabletrue \ No newline at end of file diff --git a/tests/package-compatibility/CoreOnlyConsumer/Program.cs b/tests/package-compatibility/CoreOnlyConsumer/Program.cs new file mode 100644 index 00000000..0f53f433 --- /dev/null +++ b/tests/package-compatibility/CoreOnlyConsumer/Program.cs @@ -0,0 +1,7 @@ +#if EXPECT_EVENT_API +using MinimalLambda.EventProcessing; +#endif +using MinimalLambda.Builder; +await using var app = LambdaApplication.CreateBuilder().Build(); +app.MapHandler(() => Task.CompletedTask); +Console.WriteLine("core-only mapped"); diff --git a/tests/package-compatibility/EventProcessorConsumer/EventProcessorConsumer.csproj b/tests/package-compatibility/EventProcessorConsumer/EventProcessorConsumer.csproj index 4304a220..21ec3e94 100644 --- a/tests/package-compatibility/EventProcessorConsumer/EventProcessorConsumer.csproj +++ b/tests/package-compatibility/EventProcessorConsumer/EventProcessorConsumer.csproj @@ -1,7 +1,8 @@ + $(CorePackageVersion) Exe - net10.0 + net8.0;net9.0;net10.0;net11.0 preview enable enable @@ -11,9 +12,7 @@ - - + \ No newline at end of file diff --git a/tests/package-compatibility/EventProcessorConsumer/Program.cs b/tests/package-compatibility/EventProcessorConsumer/Program.cs index a768fb6f..cbffcdad 100644 --- a/tests/package-compatibility/EventProcessorConsumer/Program.cs +++ b/tests/package-compatibility/EventProcessorConsumer/Program.cs @@ -1,55 +1,111 @@ +using System.Collections; +using System.Text; +using System.Text.Json; using System.Text.Json.Serialization; using Amazon.Lambda.Core; using Amazon.Lambda.SQSEvents; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; using MinimalLambda; using MinimalLambda.Builder; -using MinimalLambda.Options; +using MinimalLambda.EventProcessing; -var builder = LambdaApplication.CreateBuilder(); -builder.Services.AddLambdaSerializerWithContext(); -builder.Services.ConfigureEnvelopeOptions(options => - options.JsonOptions.TypeInfoResolver = EventProcessorJsonContext.Default); -builder.Services.AddScoped(); -builder.Services.Configure(options => options.MaxConcurrentExecutions = 5); +await RunFixture(false); +await RunFixture(true); +Console.WriteLine("Packed event fixture passed: defaults, configured options, middleware, JSON response, ordered outcomes, async scopes."); -await using var lambda = builder.Build(); -lambda.MapEventHandler( - split: (SQSEvent batch, ILambdaInvocationContext _) => batch.Records, - handle: async Task ( - SQSEvent.SQSMessage item, - RecordHandler handler, - IEventProcessingContext processing, - CancellationToken token) => await handler.HandleAsync(item, processing, token), - onError: (item, _, _) => new Retry(item.MessageId), - createResponse: (results, _) => new SQSBatchResponse( - results - .OfType() - .Select(result => - new SQSBatchResponse.BatchItemFailure { ItemIdentifier = result.MessageId, }) - .ToList())); -await lambda.RunAsync(); - -internal sealed class RecordHandler +static async Task RunFixture(bool configured) { - public Task HandleAsync( - SQSEvent.SQSMessage item, - IEventProcessingContext processing, - CancellationToken token) + var builder = LambdaApplication.CreateBuilder(); + builder.Services.AddLambdaSerializerWithContext(); + builder.Services.AddScoped(); + if (configured) { - token.ThrowIfCancellationRequested(); - _ = processing.Invocation.AwsRequestId; - return Task.FromResult(new Success(item.MessageId)); + builder.Services.Configure(o => o.MaxConcurrentExecutions = 1); + builder.Services.AddKeyedSingleton("label", ""); } -} - -internal abstract record ImportResult; - -internal sealed record Success(string MessageId) : ImportResult; + await using var app = builder.Build(); + SQSEvent? observed = null; + app.UseMiddleware(async (context, next) => + { + observed = context.GetRequiredEvent(); + await next(context); + }); + Func> handle = Handle; + Task Handle(SQSEvent.SQSMessage item, ScopeProbe _, IEventProcessingContext processing, int optional = 42, [FromKeyedServices("label")] string label = "fallback") + { + if (optional != 42 || label != (configured ? "" : "fallback")) throw new Exception("Optional default lost"); + if (item.Body == "retry") throw new InvalidOperationException("retry"); + if (item.Body == "stop") processing.StopProcessing(); + return Task.FromResult(item.MessageId); -internal sealed record Retry(string MessageId) : ImportResult; + } + app.MapEventHandler( + split: (SQSEvent batch, ILambdaInvocationContext _) => + { + if (!ReferenceEquals(batch, observed)) throw new Exception("Full event identity changed"); + return batch.Records; + }, + handle: handle, + onError: (item, _, _) => item.MessageId, + createResponse: (outcomes, _) => new Response(outcomes.Where(o => o.Status != EventItemStatus.Succeeded) + .Select(o => o.Item.MessageId).ToArray())); + using var data = new Data(configured + ? "{\"Records\":[{\"messageId\":\"a\",\"body\":\"ok\"},{\"messageId\":\"b\",\"body\":\"retry\"},{\"messageId\":\"c\",\"body\":\"stop\"},{\"messageId\":\"d\",\"body\":\"retry\"}]}" + : "{\"Records\":[{\"messageId\":\"a\",\"body\":\"ok\"},{\"messageId\":\"b\",\"body\":\"retry\"}]}"); + var features = new Features(); + features.Set(data); + foreach (var pair in app.Properties) + if (pair.Value is IFeatureProvider provider) + { + if (provider.TryCreate(typeof(IEventFeature), out var input)) features.Set((IEventFeature)input!); + if (provider.TryCreate(typeof(IResponseFeature), out var output)) features.Set((IResponseFeature)output!); + } + var invocation = new Invocation(app.Services, features); + await app.Build()(invocation); + features.Get()!.SerializeToStream(invocation); + var response = JsonSerializer.Deserialize(data.ResponseStream, EventJsonContext.Default.Response)!; + var expected = configured ? new[] { "b", "d" } : new[] { "b" }; + if (!response.Retry.SequenceEqual(expected)) throw new Exception("Incorrect serialized response"); +} +internal sealed record Response(string[] Retry); +internal sealed class ScopeProbe : IAsyncDisposable +{ + public async ValueTask DisposeAsync() => await Task.Yield(); +} +internal sealed class Data(string json) : IInvocationDataFeature +{ + public Stream EventStream { get; } = new MemoryStream(Encoding.UTF8.GetBytes(json)); + public Stream ResponseStream { get; set; } = new MemoryStream(); + public void Dispose() { EventStream.Dispose(); ResponseStream.Dispose(); } +} +internal sealed class Features : IFeatureCollection +{ + private readonly Dictionary values = new(); + public void Set(T instance) => values[typeof(T)] = instance!; + public T? Get() => values.TryGetValue(typeof(T), out var value) ? (T)value : default; + public IEnumerator> GetEnumerator() => values.GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); +} +internal sealed class Invocation(IServiceProvider services, IFeatureCollection features) : ILambdaInvocationContext +{ + public CancellationToken CancellationToken => default; + public IFeatureCollection Features => features; + public IDictionary Items { get; } = new Dictionary(); + public IDictionary Properties { get; } = new Dictionary(); + public IServiceProvider ServiceProvider => services; + public string AwsRequestId => "packed-event"; + public IClientContext ClientContext => null!; + public ICognitoIdentity Identity => null!; + public string InvokedFunctionArn => "arn:aws:lambda:us-east-1:123456789012:function:test"; + public string FunctionName => "test"; + public string FunctionVersion => "1"; + public ILambdaLogger Logger => null!; + public string LogGroupName => "test"; + public string LogStreamName => "test"; + public int MemoryLimitInMB => 128; + public TimeSpan RemainingTime => TimeSpan.FromMinutes(1); +} [JsonSerializable(typeof(SQSEvent))] -[JsonSerializable(typeof(SQSBatchResponse))] -internal partial class EventProcessorJsonContext : JsonSerializerContext; +[JsonSerializable(typeof(Response))] +internal partial class EventJsonContext : JsonSerializerContext; diff --git a/tests/package-compatibility/TypedConsumer/Program.cs b/tests/package-compatibility/TypedConsumer/Program.cs index ac081e07..693140ed 100644 --- a/tests/package-compatibility/TypedConsumer/Program.cs +++ b/tests/package-compatibility/TypedConsumer/Program.cs @@ -6,6 +6,7 @@ using MinimalLambda; using MinimalLambda.Builder; using MinimalLambda.DurableExecution; +using MinimalLambda.EventProcessing; var builder = LambdaApplication.CreateBuilder(); builder.Services.AddLambdaSerializerWithContext(); @@ -47,3 +48,10 @@ internal sealed class GreetingService : IGreetingService [JsonSerializable(typeof(WorkflowInput))] [JsonSerializable(typeof(WorkflowOutput))] internal partial class TypedJsonContext : JsonSerializerContext; + +internal static class EventCoexistence +{ + public static void Map(ILambdaInvocationBuilder app) => app.MapEventHandler( + split: (string[] batch, ILambdaInvocationContext _) => batch, + handle: (string _) => Task.CompletedTask); +} diff --git a/tests/package-compatibility/TypedConsumer/TypedConsumer.csproj b/tests/package-compatibility/TypedConsumer/TypedConsumer.csproj index 0d237b64..146690be 100644 --- a/tests/package-compatibility/TypedConsumer/TypedConsumer.csproj +++ b/tests/package-compatibility/TypedConsumer/TypedConsumer.csproj @@ -14,5 +14,6 @@ + \ No newline at end of file From cd1bb49e8c678d3199e5dbf7a4a067c0416518a1 Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Fri, 30 Oct 2026 20:41:15 -0400 Subject: [PATCH 19/21] fix: preserve event handler default values --- .../Models/Handlers/EventHandlerMethodInfo.cs | 18 ++++++--- .../EventProcessorRuntimeTests.cs | 38 +++++++++++++++++++ 2 files changed, 51 insertions(+), 5 deletions(-) diff --git a/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs index b1815120..ef5e4ccc 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Threading; using LayeredCraft.SourceGeneratorTools.Types; @@ -462,11 +463,18 @@ private static List CreateParameters( if (parameter.IsOptional) { var typeName = parameterType.QualifiedNullableName; - var defaultValue = - parameter.HasExplicitDefaultValue - && parameter.ExplicitDefaultValue is not null - ? $"({typeName}){SymbolDisplay.FormatPrimitive(parameter.ExplicitDefaultValue, true, false)}" - : $"default({typeName})!"; + var defaultValue = (parameter.HasExplicitDefaultValue + ? parameter.ExplicitDefaultValue + : null) switch + { + decimal value => + $"({typeName}){value.ToString(CultureInfo.InvariantCulture)}m", + DateTime value => + $"new global::System.DateTime({value.Ticks.ToString(CultureInfo.InvariantCulture)}L)", + { } value => + $"({typeName}){SymbolDisplay.FormatPrimitive(value, true, false)}", + _ => $"default({typeName})!", + }; var lookup = diResult.Value.Key is { } key ? $"((IKeyedServiceProvider)serviceProvider).GetKeyedService(typeof({(parameterType.IsValueType ? typeName : typeName.TrimEnd('?'))}), {key})" : $"serviceProvider.GetService(typeof({(parameterType.IsValueType ? typeName : typeName.TrimEnd('?'))}))"; diff --git a/tests/MinimalLambda.EventProcessing.UnitTests/EventProcessorRuntimeTests.cs b/tests/MinimalLambda.EventProcessing.UnitTests/EventProcessorRuntimeTests.cs index 4cad9a6b..eeea319f 100644 --- a/tests/MinimalLambda.EventProcessing.UnitTests/EventProcessorRuntimeTests.cs +++ b/tests/MinimalLambda.EventProcessing.UnitTests/EventProcessorRuntimeTests.cs @@ -1,3 +1,5 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; @@ -295,6 +297,42 @@ Task Handle( actualLabel.Should().Be(register ? "" : "fallback"); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task DecimalAndDateTimeDefaultsPreserveExactValues(bool register) + { + var builder = LambdaApplication.CreateBuilder(); + if (register) + { + builder.Services.AddSingleton(typeof(decimal), 0m); + builder.Services.AddKeyedSingleton(typeof(DateTime), "timestamp", default(DateTime)); + } + + await using var app = builder.Build(); + decimal? actualAmount = null; + DateTime? actualTimestamp = null; + + Task Handle( + string _, + [FromKeyedServices("timestamp"), Optional, DateTimeConstant(637000000000000000L)] + DateTime timestamp, + decimal amount = 1.2345678901234567890123456789m) + { + actualAmount = amount; + actualTimestamp = timestamp; + return Task.CompletedTask; + } + + Func handle = Handle; + app.MapEventHandler( + split: (string[] batch, ILambdaInvocationContext _) => batch, + handle: handle); + await app.Build()(Context(app, new[] { "item" })); + actualAmount.Should().Be(register ? 0m : 1.2345678901234567890123456789m); + actualTimestamp.Should().Be(register ? default : new DateTime(637000000000000000L)); + } + private static ILambdaInvocationContext Context(LambdaApplication app, T batch) { var features = Substitute.For(); From 7f468a9b7e0a26ff8e01d9eec14018ce77564dcf Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Sat, 31 Oct 2026 20:36:32 -0400 Subject: [PATCH 20/21] feat: add event error handling without responses --- designs/event-processing-contracts.md | 11 +- docs/features/event-processor.md | 24 +- docs/features/index.md | 2 +- .../references/event-processor.md | 12 +- .../EventHandlerFactory.cs | 32 ++ ...EventHandlerLambdaApplicationExtensions.cs | 280 ++++++++++++++++++ src/MinimalLambda.EventProcessing/README.md | 4 +- .../Models/Handlers/EventHandlerMethodInfo.cs | 16 +- .../EventHandlerRegistrationTests.cs | 12 + .../EventProcessorTests.cs | 159 ++++++++++ ...HandlerLambdaApplicationExtensionsTests.cs | 3 +- .../EventHandlerCallbackShapeTests.cs | 46 +++ .../EventHandlerDiscoveryTests.cs | 11 +- .../EventHandlerEmitterTests.cs | 18 ++ ...#MinimalLambda.EventHandlers.g.verified.cs | 70 +++++ 15 files changed, 678 insertions(+), 22 deletions(-) create mode 100644 tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsErrorCallbackWithoutResponse#MinimalLambda.EventHandlers.g.verified.cs diff --git a/designs/event-processing-contracts.md b/designs/event-processing-contracts.md index 26b489e2..d6bf6a3f 100644 --- a/designs/event-processing-contracts.md +++ b/designs/event-processing-contracts.md @@ -31,11 +31,12 @@ even if cancellation was requested concurrently. Application code owns acknowled Each mapping takes `Func> split` and an item-first handler returning `Task` or `Task`. Up to ten additional parameters bind -services or framework values. The five compiler-selected families are: +services or framework values. The six compiler-selected families are: | Family | Handler | Mapper | Outcome value | | --- | --- | --- | --- | | No response | Task | absent | no response callback | +| No response with errors | Task | synchronous action | no response callback | | Source item | Task | absent | source item on success | | Failures only | Task | TFailure | value only on mapped errors | | Results | Task | absent | handler result | @@ -43,7 +44,9 @@ services or framework values. The five compiler-selected families are: Response callbacks are synchronous `Func>, ILambdaInvocationContext, TResponse>`. Error callbacks are synchronous -`Func`. Awaitable mapper contributions, +`Func` or, without a response, +`Action`. The action handles an error by returning normally; +throwing fails the invocation. Async actions, including async void, are rejected. Awaitable mapper contributions, nested handler task results, and awaitable responses are rejected with an actionable generator diagnostic. Async error mappers are deliberately unsupported; put async recovery in the handler. Required callbacks cannot be null. A null task from a handler is an item error eligible for mapping. @@ -55,7 +58,7 @@ Example response policies: createResponse: (outcomes, _) => outcomes.Where(x => x.Status != EventItemStatus.Succeeded) .Select(x => x.Item.Id).ToArray() // Failures-only and result families can inspect HasValue before reading Value. -// The no-response family omits both response and error callbacks. +// No-response handlers may omit onError or supply a synchronous action. ``` ## Binding, errors, and lifetime @@ -77,7 +80,7 @@ cancellation during construction suppresses storing its response. Once stored, c ## Factory and generated output `EventHandlerFactory.Create` accepts the built `IServiceProvider`, split, the typed wrapper, -optional mapper, and optional response callback. Its five overloads mirror the families above. +optional mapper, and optional response callback. Its six overloads mirror the families above. Wrappers are `Func` or the corresponding `Task` shape. The factory validates callbacks and effective options at mapping time, resolves scope/logging dependencies, and constructs an internal processor once. No required diff --git a/docs/features/event-processor.md b/docs/features/event-processor.md index f75f80f1..a13dd8de 100644 --- a/docs/features/event-processor.md +++ b/docs/features/event-processor.md @@ -32,13 +32,31 @@ handler starts. Null enumerable results and enumeration failures fail the invoca | Handler | Error mapper | Successful contribution | Response | | --- | --- | --- | --- | | `Task` | absent | absent | absent | +| `Task` | synchronous action | absent | absent | | `Task` | absent | source item | required | | `Task` | `TFailure` | absent | required | | `Task` | absent | result | required | | `Task` | `TResult` | result | required | -`onError` is synchronous `(item, exception, processing) => value`. It maps errors from service -resolution and handler execution. A mapper that throws fails the invocation. Without a mapper, +For handlers without a response, `onError` can be a synchronous action: + +```csharp +lambda.MapEventHandler( + split: (ImportBatch batch, ILambdaInvocationContext _) => batch.Items, + handle: (ImportDocument item, DocumentImporter importer, CancellationToken token) => + importer.ImportAsync(item.Event, token), + onError: (item, exception, processing) => + { + // Log or recover. Return normally to handle the error, or throw to fail the invocation. + }); +``` + +The action handles dependency-resolution and handler errors while the item scope remains alive. +It may call `StopProcessing()` or `CancelProcessing()`. It produces no value or response. +Async actions, including `async void`, are unsupported; put asynchronous recovery in the handler. + +For handlers with a response, `onError` is synchronous `(item, exception, processing) => value`. +It maps errors from service resolution and handler execution. A mapper that throws fails the invocation. Without a mapper, item errors fail the invocation. Nullable response types may return null for normal core serialization. A null returned handler task is an item error eligible for mapping. Async mappers, nested awaitable handler results, and awaitable responses receive a generator diagnostic. @@ -152,4 +170,4 @@ internal package code. Core middleware, envelope extraction/packing, deserializa use their existing pipeline. Intermediate result types are not registered as response types. See the [example project](https://github.com/LayeredCraft/minimal-lambda/tree/main/examples/MinimalLambda.Example.EventProcessor) -for all five families. +for response and no-response examples. diff --git a/docs/features/index.md b/docs/features/index.md index 63ca2847..48fa1aa3 100644 --- a/docs/features/index.md +++ b/docs/features/index.md @@ -11,7 +11,7 @@ ______________________________________________________________________ ### [Event Processor](./event-processor.md) The optional `MinimalLambda.EventProcessing` package provides `MapEventHandler`, which splits one event into items and processes them concurrently with a per-item -asynchronous DI scope. Choose from five callback families for response building, error mapping, and +asynchronous DI scope. Choose from six callback families for response building, error mapping, and graceful stopping. ### [Envelope Pattern](./envelopes.md) diff --git a/skills/minimal-lambda/references/event-processor.md b/skills/minimal-lambda/references/event-processor.md index ed76b55e..fe2f2618 100644 --- a/skills/minimal-lambda/references/event-processor.md +++ b/skills/minimal-lambda/references/event-processor.md @@ -18,10 +18,14 @@ processing CancellationToken. Other arguments resolve from the item scope, inclu services. Declared optional defaults apply only when a service is missing. Do not use FromEvent to select the incoming batch. Use a typed lambda/delegate or explicit generics for method groups. -Five families: no response; Task plus source-item response; Task plus mapped-failure response; -Task plus response; Task plus synchronous error mapper and response. -The error mapper is `(item, exception, processing) => TValue`. Async mapper contributions, nested -awaitable handler results, and awaitable responses are diagnostic errors. +Six families: no response; Task plus synchronous error action without a response; Task plus source-item +response; Task plus mapped-failure response; Task plus response; Task plus synchronous +error mapper and response. +The error mapper is `(item, exception, processing) => TValue`. +Without a response, use `Action` instead. Returning normally +handles the error; throwing fails the invocation. The action can stop or cancel processing and covers +DI resolution and handler failures within the item scope. Async actions, including async void, are rejected. +Async mapper contributions, nested awaitable handler results, and awaitable responses are diagnostic errors. Typed delegates supply binding types. Attributes on the underlying handler method still apply when its parameters accept broader types. diff --git a/src/MinimalLambda.EventProcessing/EventHandlerFactory.cs b/src/MinimalLambda.EventProcessing/EventHandlerFactory.cs index ede8c45f..6049ac08 100644 --- a/src/MinimalLambda.EventProcessing/EventHandlerFactory.cs +++ b/src/MinimalLambda.EventProcessing/EventHandlerFactory.cs @@ -34,6 +34,38 @@ public static LambdaInvocationDelegate Create( null); } + /// Creates an event terminal with synchronous error handling and no response. + /// The event type. + /// The item type. + /// The mapping services. + /// Splits the event into source items. + /// Resolves arguments and processes an item. + /// Handles an item error; throwing fails the invocation. + /// A terminal invocation delegate. + public static LambdaInvocationDelegate Create( + IServiceProvider services, + Func> split, + Func handle, + Action onError) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(split); + ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(onError); + var runtime = CreateRuntime(services); + return context => runtime.RunAsync( + context, + split, + (item, provider, processing) => handle(item, provider, processing), + null, + (item, exception, processing) => + { + onError(item, exception, processing); + return null; + }, + null); + } + /// Creates an event terminal and validates its callbacks and effective options. /// The Event type. /// The Item type. diff --git a/src/MinimalLambda.EventProcessing/MapEventHandlerLambdaApplicationExtensions.cs b/src/MinimalLambda.EventProcessing/MapEventHandlerLambdaApplicationExtensions.cs index a27138be..f9a0711d 100644 --- a/src/MinimalLambda.EventProcessing/MapEventHandlerLambdaApplicationExtensions.cs +++ b/src/MinimalLambda.EventProcessing/MapEventHandlerLambdaApplicationExtensions.cs @@ -296,6 +296,286 @@ public static ILambdaInvocationBuilder throw new InvalidOperationException("This method is replaced at compile time."); } + /// Registers an event-processor handler (N4, 0 additional parameters). + /// No response. The synchronous error callback handles item errors; throwing fails the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Handles an item error without producing a value. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Action onError) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N4, 1 additional parameter). + /// No response. The synchronous error callback handles item errors; throwing fails the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Handles an item error without producing a value. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Action onError) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N4, 2 additional parameters). + /// No response. The synchronous error callback handles item errors; throwing fails the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Handles an item error without producing a value. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Action onError) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N4, 3 additional parameters). + /// No response. The synchronous error callback handles item errors; throwing fails the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Handles an item error without producing a value. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Action onError) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N4, 4 additional parameters). + /// No response. The synchronous error callback handles item errors; throwing fails the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Handles an item error without producing a value. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Action onError) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N4, 5 additional parameters). + /// No response. The synchronous error callback handles item errors; throwing fails the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Handles an item error without producing a value. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Action onError) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N4, 6 additional parameters). + /// No response. The synchronous error callback handles item errors; throwing fails the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Handles an item error without producing a value. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Action onError) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N4, 7 additional parameters). + /// No response. The synchronous error callback handles item errors; throwing fails the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Handles an item error without producing a value. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Action onError) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N4, 8 additional parameters). + /// No response. The synchronous error callback handles item errors; throwing fails the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Handles an item error without producing a value. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Action onError) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N4, 9 additional parameters). + /// No response. The synchronous error callback handles item errors; throwing fails the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Handles an item error without producing a value. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Action onError) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + + /// Registers an event-processor handler (N4, 10 additional parameters). + /// No response. The synchronous error callback handles item errors; throwing fails the invocation. + /// The deserialized Lambda event type. + /// The source item type returned by . + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// An additional handler input type. Framework context and token types are recognized by type. + /// The builder to register the handler with. + /// Splits the event into source items. Called once per invocation. + /// Processes one source item; the item is the first parameter. + /// Handles an item error without producing a value. + /// The same instance. + /// Thrown if interception does not occur. + public static ILambdaInvocationBuilder + MapEventHandler( + this ILambdaInvocationBuilder application, + Func> split, + Func handle, + Action onError) + { + Debug.Fail("This method should have been intercepted at compile time!"); + throw new InvalidOperationException("This method is replaced at compile time."); + } + /// Registers an event-processor handler (N2, 0 additional parameters). /// No result. createResponse receives successfully handled source items. /// The deserialized Lambda event type. diff --git a/src/MinimalLambda.EventProcessing/README.md b/src/MinimalLambda.EventProcessing/README.md index 3a951cb5..f0ccad39 100644 --- a/src/MinimalLambda.EventProcessing/README.md +++ b/src/MinimalLambda.EventProcessing/README.md @@ -11,7 +11,9 @@ No AddEventProcessing call is required. Optional Configure concurrency. Effective options are validated at mapping time. The matching core dependency supplies the source generator; this package does not duplicate the analyzer. -DI and handler failures reach the synchronous error mapper. Scope creation/disposal failures fail the +DI and handler failures reach the synchronous error callback. Without a response, pass an +`Action` to `onError`; returning normally handles the error, +and throwing fails the invocation. Async error callbacks are unsupported. Scope creation/disposal failures fail the invocation. Invocation cancellation remains effective through cleanup. Core handles normal serialization, middleware, and envelopes. diff --git a/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs index ef5e4ccc..5eb199cc 100644 --- a/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs +++ b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs @@ -18,6 +18,7 @@ internal enum EventHandlerFamily N1, N2, N3, + N4, R1, R2, } @@ -121,7 +122,8 @@ onErrorArgument is null context.CancellationToken, out _); var mapperIsAwaitable = - mapperMethod is not null && IsAwaitable(mapperMethod.ReturnType); + mapperMethod is not null + && (mapperMethod.IsAsync || IsAwaitable(mapperMethod.ReturnType)); if (mapperIsAwaitable) diagnostics.Add( CreateDiagnostic( @@ -143,9 +145,10 @@ createResponseArgument is null handleReturnsResult, onErrorArgument is not null, createResponseArgument is not null); - var hasResponse = family is not EventHandlerFamily.N1; - var hasOnError = family is EventHandlerFamily.N3 or EventHandlerFamily.R2; - var collectValues = family is not EventHandlerFamily.N1; + var hasResponse = family is not (EventHandlerFamily.N1 or EventHandlerFamily.N4); + var hasOnError = + family is EventHandlerFamily.N3 or EventHandlerFamily.N4 or EventHandlerFamily.R2; + var collectValues = family is not (EventHandlerFamily.N1 or EventHandlerFamily.N4); var collectsSourceItems = family is EventHandlerFamily.N2; var collectsMappedFailures = family is EventHandlerFamily.N3; @@ -233,6 +236,7 @@ createResponseArgument is null else if (family is EventHandlerFamily.N1 or EventHandlerFamily.N2 or EventHandlerFamily.N3 + or EventHandlerFamily.N4 && TryUnwrapTask(handlerMethod.ReturnType, context, out _)) diagnostics.Add( CreateDiagnostic( @@ -251,7 +255,7 @@ or EventHandlerFamily.N3 var valueType = family switch { - EventHandlerFamily.N1 => "MinimalLambda.Generated.NoData", + EventHandlerFamily.N1 or EventHandlerFamily.N4 => "MinimalLambda.Generated.NoData", EventHandlerFamily.N2 => itemType?.QualifiedNullableName ?? "global::System.Object", _ => collectedType ?? "global::System.Object", }; @@ -317,7 +321,7 @@ private static EventHandlerFamily DetermineFamily( return hasOnError ? EventHandlerFamily.R2 : EventHandlerFamily.R1; if (!hasCreateResponse) - return EventHandlerFamily.N1; + return hasOnError ? EventHandlerFamily.N4 : EventHandlerFamily.N1; return hasOnError ? EventHandlerFamily.N3 : EventHandlerFamily.N2; } diff --git a/tests/MinimalLambda.EventProcessing.UnitTests/EventHandlerRegistrationTests.cs b/tests/MinimalLambda.EventProcessing.UnitTests/EventHandlerRegistrationTests.cs index a84577cc..43fd1dda 100644 --- a/tests/MinimalLambda.EventProcessing.UnitTests/EventHandlerRegistrationTests.cs +++ b/tests/MinimalLambda.EventProcessing.UnitTests/EventHandlerRegistrationTests.cs @@ -5,6 +5,18 @@ namespace MinimalLambda.EventProcessing.UnitTests; public sealed class EventHandlerFactoryTests { + [Fact] + public void RejectsNullNoResponseErrorCallback() + { + using var services = new ServiceCollection().BuildServiceProvider(); + var create = () => EventHandlerFactory.Create( + services, + (batch, _) => batch, + (_, _, _) => Task.CompletedTask, + null!); + create.Should().Throw().WithParameterName("onError"); + } + [Fact] public async Task DefaultsNeedNoRegistrationAndCallbacksAreLazy() { diff --git a/tests/MinimalLambda.EventProcessing.UnitTests/EventProcessorTests.cs b/tests/MinimalLambda.EventProcessing.UnitTests/EventProcessorTests.cs index 50646b76..420026d7 100644 --- a/tests/MinimalLambda.EventProcessing.UnitTests/EventProcessorTests.cs +++ b/tests/MinimalLambda.EventProcessing.UnitTests/EventProcessorTests.cs @@ -9,6 +9,165 @@ namespace MinimalLambda.UnitTests.Core.Runtime; public class EventProcessorTests { + [Theory] + [InlineData("sync")] + [InlineData("async")] + [InlineData("null-task")] + [InlineData("resolution")] + public async Task HandlesItemErrorsWithoutResponseAndDisposesScopes(string failure) + { + // Arrange + ScopeProbe.Reset(); + var builder = LambdaApplication.CreateBuilder(); + builder.Services.Configure(options => + options.EnableConcurrency = false); + builder.Services.AddScoped(); + builder.Services.AddScoped(_ => failure == "resolution" + ? throw new InvalidOperationException("resolution failed") + : "dependency"); + await using var app = builder.Build(); + var handled = new List(); + var errors = new List(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item, ScopeProbe probe, string dependency) => + { + handled.Add(item.Id); + if (item.Id == 2) + return Task.CompletedTask; + return failure switch + { + "sync" => throw new InvalidOperationException("handler failed"), + "async" => Task.FromException(new InvalidOperationException("handler failed")), + _ => null!, + }; + }, + onError: (item, error, processing) => + { + errors.Add(error); + // The current item's scope remains alive during error handling. + ScopeProbe.Disposed.Should().Be(item.Id - 1); + processing.Invocation.Should().NotBeNull(); + }); + var harness = CreateHarness(app, new Batch([new Item(1), new Item(2)])); + + // Act + await app.Build()(harness.Context); + + // Assert + errors.Should().HaveCount(failure == "resolution" ? 2 : 1); + if (failure == "resolution") + handled.Should().BeEmpty(); + else + handled.Should().Equal(1, 2); + ScopeProbe.Created.Should().Be(2); + ScopeProbe.Disposed.Should().Be(2); + harness.ResponseFeature.DidNotReceive().SetResponse(Arg.Any()); + ((ILambdaInvocationBuilder)app) + .Properties + .Should() + .NotContainKey("__ResponseFeatureProvider"); + } + + [Fact] + public async Task ThrowingNoResponseErrorCallbackFailsInvocationAndDisposesScope() + { + // Arrange + ScopeProbe.Reset(); + var builder = LambdaApplication.CreateBuilder(); + builder.Services.AddScoped(); + await using var app = builder.Build(); + var original = new InvalidOperationException("recovery failed"); + var errorCalls = 0; + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item, ScopeProbe probe) => + Task.FromException(new Exception("item failed")), + onError: (item, error, processing) => + { + errorCalls++; + throw original; + }); + var harness = CreateHarness(app, new Batch([new Item(1)])); + + // Act + var act = () => app.Build()(harness.Context); + + // Assert + (await act.Should().ThrowAsync()) + .Which + .Should() + .BeSameAs(original); + errorCalls.Should().Be(1); + ScopeProbe.Disposed.Should().Be(1); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task NoResponseErrorCallbackCanStopOrCancelProcessing(bool cancel) + { + // Arrange + var builder = LambdaApplication.CreateBuilder(); + builder.Services.Configure(options => + options.EnableConcurrency = false); + await using var app = builder.Build(); + var started = new List(); + IEventProcessingContext? captured = null; + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => + { + started.Add(item.Id); + return Task.FromException(new Exception("item failed")); + }, + onError: (item, error, processing) => + { + captured = processing; + if (cancel) + processing.CancelProcessing(); + else + processing.StopProcessing(); + }); + var harness = CreateHarness(app, new Batch([new Item(1), new Item(2)])); + + // Act + await app.Build()(harness.Context); + + // Assert + started.Should().Equal(1); + captured.Should().NotBeNull(); + harness.ResponseFeature.DidNotReceive().SetResponse(Arg.Any()); + } + + [Fact] + public async Task InvocationCancellationCannotBeSwallowedByNoResponseErrorCallback() + { + // Arrange + using var cancellation = new CancellationTokenSource(); + await using var app = LambdaApplication.CreateBuilder().Build(); + var errorCalls = 0; + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => + { + cancellation.Cancel(); + return Task.FromException(new Exception("item failed")); + }, + onError: (item, error, processing) => + { + errorCalls++; + }); + var harness = CreateHarness(app, new Batch([new Item(1)]), cancellation); + + // Act + var act = () => app.Build()(harness.Context); + + // Assert + await act.Should().ThrowAsync(); + errorCalls.Should().Be(0); + } + [Fact] public async Task ProcessesEmptyInputAndBuildsResponseOnce() { diff --git a/tests/MinimalLambda.EventProcessing.UnitTests/MapEventHandlerLambdaApplicationExtensionsTests.cs b/tests/MinimalLambda.EventProcessing.UnitTests/MapEventHandlerLambdaApplicationExtensionsTests.cs index 94aaca28..02099b35 100644 --- a/tests/MinimalLambda.EventProcessing.UnitTests/MapEventHandlerLambdaApplicationExtensionsTests.cs +++ b/tests/MinimalLambda.EventProcessing.UnitTests/MapEventHandlerLambdaApplicationExtensionsTests.cs @@ -20,7 +20,8 @@ public void StubFailsClearlyWhenInterceptionDoesNotOccur() .Single(method => method.Name == "MapEventHandler" && method.IsGenericMethodDefinition - && method.GetGenericArguments().Length == 2); + && method.GetGenericArguments().Length == 2 + && method.GetParameters().Length == 3); var closed = stub.MakeGenericMethod(typeof(StubBatch), typeof(StubItem)); // Act diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerCallbackShapeTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerCallbackShapeTests.cs index cfc2ec4d..16efeefa 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerCallbackShapeTests.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerCallbackShapeTests.cs @@ -4,6 +4,52 @@ namespace MinimalLambda.SourceGenerators.UnitTests; public sealed class EventHandlerCallbackShapeTests { + [Theory] + [InlineData("async (item, error, processing) => { await Task.Yield(); }")] + [InlineData("AsyncError")] + [InlineData("callback")] + public void RejectsAsyncVoidErrorCallbacks(string callback) + { + var (driver, _) = GeneratorTestHelpers.GenerateFromSource( + $$""" + using System; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + using MinimalLambda.EventProcessing; + var app = LambdaApplication.CreateBuilder().Build(); + Action callback = AsyncError; + app.MapEventHandler(split: (string[] batch, ILambdaInvocationContext _) => batch, + handle: (string item) => Task.CompletedTask, onError: {{callback}}); + static async void AsyncError(string item, Exception error, IEventProcessingContext processing) + { + await Task.Yield(); + } + """); + driver + .GetRunResult() + .Diagnostics + .Should() + .Contain(d => d.Id == "LH0008" && d.GetMessage().Contains("synchronous")); + } + + [Fact] + public void RejectsDiscardedHandlerResultsWithNoResponseErrorCallback() + { + var (driver, _) = GeneratorTestHelpers.GenerateFromSource( + """ + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + using MinimalLambda.EventProcessing; + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler(split: (string[] batch, ILambdaInvocationContext _) => batch, + handle: Handle, onError: (item, error, processing) => { }); + static Task Handle(string item) => Task.FromResult(1); + """); + driver.GetRunResult().Diagnostics.Should().Contain(d => d.Id == "LH0011"); + } + [Theory] [InlineData( "(string item) => Task.CompletedTask", diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs index 41ae10b3..0cf5c2da 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs @@ -8,7 +8,7 @@ namespace MinimalLambda.SourceGenerators.UnitTests; public class EventHandlerDiscoveryTests { [Fact] - public void GeneratesInterceptorsForAllFiftyFiveOverloads() + public void GeneratesInterceptorsForAllSixtySixOverloads() { var source = BuildAllOverloadsSource(); @@ -32,7 +32,7 @@ public void GeneratesInterceptorsForAllFiftyFiveOverloads() "MinimalLambda.EventHandlers.g.cs", StringComparison.Ordinal)) .Subject; - CountOccurrences(tree.ToString(), "MapEventHandlerInterceptor").Should().Be(55); + CountOccurrences(tree.ToString(), "MapEventHandlerInterceptor").Should().Be(66); var errors = CompileWithGenerated(compilation, result) .GetDiagnostics(TestContext.Current.CancellationToken) @@ -556,6 +556,13 @@ internal sealed class Response; split: (Batch batch, ILambdaInvocationContext _) => batch.Items, handle: (Item item{{parameters}}) => Task.CompletedTask); """); + builder.AppendLine( + $$""" + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item{{parameters}}) => Task.CompletedTask, + onError: (item, exception, processing) => { }); + """); builder.AppendLine( $$""" app.MapEventHandler( diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs index 211a1843..1339fdea 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs @@ -5,6 +5,24 @@ namespace MinimalLambda.SourceGenerators.UnitTests; public class EventHandlerEmitterTests { + [Fact] + public Task EmitsErrorCallbackWithoutResponse() => + GeneratorTestHelpers.Verify( + """ + using System; + using System.Threading; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.Builder; + using MinimalLambda.EventProcessing; + + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (string[] batch, ILambdaInvocationContext _) => batch, + handle: (string item, IEventProcessingContext processing, CancellationToken token) => Task.CompletedTask, + onError: (item, error, processing) => { processing.StopProcessing(); }); + """); + [Fact] public Task EmitsRepresentativeAdapterForEveryFamily() => GeneratorTestHelpers.Verify( diff --git a/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsErrorCallbackWithoutResponse#MinimalLambda.EventHandlers.g.verified.cs b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsErrorCallbackWithoutResponse#MinimalLambda.EventHandlers.g.verified.cs new file mode 100644 index 00000000..34cdfd32 --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsErrorCallbackWithoutResponse#MinimalLambda.EventHandlers.g.verified.cs @@ -0,0 +1,70 @@ +//HintName: MinimalLambda.EventHandlers.g.cs +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +#nullable enable + +namespace System.Runtime.CompilerServices +{ + using System.CodeDom.Compiler; + + [global::System.CodeDom.Compiler.GeneratedCode("MinimalLambda.SourceGenerators", "REPLACED")] + [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] + file sealed class InterceptsLocationAttribute : Attribute + { + public InterceptsLocationAttribute(int version, string data) { } + } +} + +namespace MinimalLambda.Generated +{ + using System; + using System.Runtime.CompilerServices; + using System.Threading.Tasks; + using Microsoft.Extensions.DependencyInjection; + using MinimalLambda.Builder; + using MinimalLambda.EventProcessing; + using MinimalLambda; + + [global::System.CodeDom.Compiler.GeneratedCode("MinimalLambda.SourceGenerators", "REPLACED")] + file static class GeneratedEventProcessorExtensions + { + [InterceptsLocation(1, "REPLACED")] + internal static ILambdaInvocationBuilder MapEventHandlerInterceptor0( + this ILambdaInvocationBuilder application, + global::System.Func> split, + global::System.Func handle, + global::System.Action onError) + { + ArgumentNullException.ThrowIfNull(handle); + var terminal = EventHandlerFactory.Create( + application.Services, + split, + HandleItem, + onError); + + application.Handle(terminal); + if (!application.Properties.ContainsKey("__EventFeatureProvider")) + application.Properties["__EventFeatureProvider"] = application.Services + .GetRequiredService().Create(); + return application; + + Task HandleItem( + string item, + IServiceProvider serviceProvider, + IEventProcessingContext processingContext) + { + var arg0 = item; + var arg1 = processingContext; + var arg2 = processingContext.CancellationToken; + return handle(arg0, arg1, arg2); + } + } + } +} From f3f303c725194c20b5d2185713370d7c38488367 Mon Sep 17 00:00:00 2001 From: Jonas Ha Date: Sat, 31 Oct 2026 20:49:19 -0400 Subject: [PATCH 21/21] docs: align event processing docs and skill --- designs/event-processing-contracts.md | 2 +- docs/features/event-processor.md | 53 ++++++++++++++++--- .../README.md | 32 +++++++---- skills/minimal-lambda/SKILL.md | 4 +- .../references/event-processor.md | 17 ++++-- .../scripts/validate_references.py | 5 ++ 6 files changed, 91 insertions(+), 22 deletions(-) diff --git a/designs/event-processing-contracts.md b/designs/event-processing-contracts.md index d6bf6a3f..b5ecbc4b 100644 --- a/designs/event-processing-contracts.md +++ b/designs/event-processing-contracts.md @@ -67,7 +67,7 @@ Each item gets an asynchronous scope, alive through argument resolution, executi Scope creation is an invocation failure because no item provider exists. DI resolution, synchronous handler throws, asynchronous faults, and null handler tasks reach onError with the original exception. Absent or throwing mappers fail the invocation; mapper failures are never recursively mapped. -Scope disposal always fails the invocation. Drain admitted work and cleanup before propagating errors; +Scope disposal failures always fail the invocation. Drain admitted work and cleanup before propagating errors; preserve the first fatal exception and log additional failures. Invocation cancellation takes precedence. Optional nullable services retain null fallback. Declared optional defaults are honored, including keyed and value-type defaults; generated resolution distinguishes missing services from default-valued services. diff --git a/docs/features/event-processor.md b/docs/features/event-processor.md index a13dd8de..2d9f1ccc 100644 --- a/docs/features/event-processor.md +++ b/docs/features/event-processor.md @@ -8,18 +8,26 @@ dotnet add package MinimalLambda.EventProcessing ``` ```csharp +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using MinimalLambda; using MinimalLambda.Builder; using MinimalLambda.EventProcessing; +var builder = LambdaApplication.CreateBuilder(); builder.Services.AddScoped(); await using var lambda = builder.Build(); lambda.MapEventHandler( split: (ImportBatch batch, ILambdaInvocationContext _) => batch.Items, handle: (ImportDocument item, DocumentImporter importer, CancellationToken token) => importer.ImportAsync(item.Event, token)); + +await lambda.RunAsync(); ``` +This registration uses `ImportBatch`, `ImportDocument`, and `DocumentImporter` from the +[example project](https://github.com/LayeredCraft/minimal-lambda/tree/main/examples/MinimalLambda.Example.EventProcessor). + No `AddEventProcessing` call or processor registration is required. The package supports the same .NET target frameworks as core. Its matching core dependency supplies the source generator; the optional package does not ship another analyzer. @@ -82,15 +90,21 @@ application result types. `Skipped` means the item never started; `Cancelled` me cancellation interrupted admitted work. A successfully completed handler retains its result. Applications own acknowledgement and retry. For example, this SQS response includes both mapped -failures and items that never completed: +failures and items that never completed. Add `MinimalLambda.Envelopes.Sqs` and use the example +project's `MyEvent`, `ImportItemResult`, `Retry`, and `DocumentImporter` types: ```csharp +using Amazon.Lambda.SQSEvents; +using MinimalLambda.Envelopes.Sqs; + lambda.MapEventHandler( - split: (SqsEnvelope batch, ILambdaInvocationContext _) => batch.Records, - handle: async Task ( - SqsEnvelope.SqsMessageEnvelope item, - OrderImporter importer, - CancellationToken token) => await importer.ImportAsync(item.BodyContent, token), + split: (SqsEnvelope batch, ILambdaInvocationContext _) => batch.Records, + handle: async Task ( + SqsEnvelope.SqsMessageEnvelope item, + DocumentImporter importer, + CancellationToken token) => item.BodyContent is null + ? new Retry(item.MessageId) + : await importer.ImportResultAsync(item.BodyContent, token), onError: (item, error, processing) => new Retry(item.MessageId), createResponse: (outcomes, _) => new SQSBatchResponse( outcomes @@ -126,6 +140,9 @@ or disposal failure fails the invocation. The processor stops admission and drai cancellation callbacks, and scope cleanup before returning. Return DTOs that remain usable after scope disposal. +Item scopes are separate from the invocation scope. A scoped service resolved by middleware is +not the same instance injected into an item handler. + Typed delegates supply the parameter types used for binding. Attributes on the underlying handler method still apply when its parameters accept broader types. @@ -169,5 +186,29 @@ and emits normal event/final-response provider setup. Scheduling and error/cance internal package code. Core middleware, envelope extraction/packing, deserialization, and serialization use their existing pipeline. Intermediate result types are not registered as response types. +## Serialization and Native AOT + +For Native AOT, register a source-generated JSON serializer for the full event and final response. +With `SqsEnvelope`, include `SqsEnvelope`, `MyEvent`, and `SQSBatchResponse` in +the JSON context, and set `ConfigureEnvelopeOptions` to use that context's resolver for message bodies. +Item results such as `ImportItemResult` need no serializer metadata unless the final response contains them. +Register the serializer and envelope resolver before `Build()`: + +```csharp +builder.Services.AddLambdaSerializerWithContext(); +builder.Services.ConfigureEnvelopeOptions(options => + options.JsonOptions.TypeInfoResolver = EventProcessorJsonContext.Default); +``` + +Declare the context after the top-level statements: + +```csharp +[System.Text.Json.Serialization.JsonSerializable(typeof(SqsEnvelope))] +[System.Text.Json.Serialization.JsonSerializable(typeof(MyEvent))] +[System.Text.Json.Serialization.JsonSerializable(typeof(SQSBatchResponse))] +internal partial class EventProcessorJsonContext + : System.Text.Json.Serialization.JsonSerializerContext; +``` + See the [example project](https://github.com/LayeredCraft/minimal-lambda/tree/main/examples/MinimalLambda.Example.EventProcessor) for response and no-response examples. diff --git a/examples/MinimalLambda.Example.EventProcessor/README.md b/examples/MinimalLambda.Example.EventProcessor/README.md index abb5d4d1..b030e581 100644 --- a/examples/MinimalLambda.Example.EventProcessor/README.md +++ b/examples/MinimalLambda.Example.EventProcessor/README.md @@ -3,13 +3,16 @@ Sample registrations for the optional `MinimalLambda.EventProcessing` package. `MapEventHandler` consumes the single invocation handler slot, so this project registers exactly one family per run and selects it with `EVENT_PROCESSOR_SAMPLE`. -| Value | Family | Shows | -| -------------- | ------ | --------------------------------------------------------------------- | -| `n1` | N1 | per-item DI scope and processing token | -| `n2` | N2 | complete source-item outcomes and success counts | +| Value | Family | Shows | +| -------------- | ------ | ------------------------------------------------------------------ | +| `n1` | N1 | per-item DI scope and processing token | +| `n2` | N2 | complete source-item outcomes and success counts | | `n3` | N3 | `onError` mapping failures and building an SQS partial batch response | -| `r1` | R1 | per-item `TResult` contributions through a typed delegate local | -| `r2` (default) | R2 | complete outcomes and retries for skipped/cancelled items | +| `r1` | R1 | per-item `TResult` contributions through a typed delegate local | +| `r2` (default) | R2 | complete outcomes and retries for skipped/cancelled items | + +The no-response family with a synchronous `onError` action is documented in the +[event-processing guide](../../docs/features/event-processor.md#callback-families). ## Program.cs @@ -22,7 +25,7 @@ so this project registers exactly one family per run and selects it with `EVENT_ ## Prerequisites -- .NET SDK 8.0 or later. +- The .NET SDK selected by the repository's `global.json`, plus the .NET 8 runtime for local execution. - AWS credentials configured locally if you plan to deploy. - Amazon.Lambda.Tools for command-line deployment. @@ -33,14 +36,23 @@ dotnet restore dotnet build ``` -## Run a sample locally +## Validate registration locally + +Run these commands from this example's directory. The smoke mode validates registration and options, +then exits without processing an event: ```bash -EVENT_PROCESSOR_SAMPLE=r2 dotnet run +EVENT_PROCESSOR_SMOKE=1 EVENT_PROCESSOR_SAMPLE=r2 dotnet run ``` +To process events, omit `EVENT_PROCESSOR_SMOKE` and run under AWS Lambda or a local Lambda runtime +emulator that supplies `AWS_LAMBDA_RUNTIME_API`. A plain `dotnet run` requires that runtime endpoint. +Use `n2` and `r1` for `ImportBatch` events; the other samples expect SQS events. The sample's JSON +context includes SQS contracts. Before invoking `n2` or `r1`, add `ImportBatch` and `BatchSummary` +to `EventProcessorJsonContext`. + Deploying an R2/N3 SQS sample requires `ReportBatchItemFailures` on the event source mapping, and -the FIFO/SQS limits described in `docs/features/event-processor.md`. +the [FIFO/SQS guidance](../../docs/features/event-processor.md#complete-outcomes). Response builders receive `IReadOnlyList>`. Check status and HasValue before using contributions. The SQS examples explicitly retry unstarted/cancelled records. diff --git a/skills/minimal-lambda/SKILL.md b/skills/minimal-lambda/SKILL.md index 9c5e1676..717eb3b4 100644 --- a/skills/minimal-lambda/SKILL.md +++ b/skills/minimal-lambda/SKILL.md @@ -1,6 +1,6 @@ --- name: minimal-lambda -description: Work effectively with MinimalLambda, the Lambda-first .NET hosting framework in this repo and in client projects. Use this skill whenever the user asks to build, debug, migrate, test, document, scaffold, template, package, or review code using MinimalLambda APIs, `dotnet new mlambda` templates, envelopes, middleware, lifecycle hooks, source-generated handlers, AOT/trimming, OpenTelemetry, or MinimalLambda.Testing. Trigger even when the user only mentions AWS Lambda with Minimal API-style .NET patterns, MapHandler, FromEvent, LambdaApplication, MinimalLambda package names, MinimalLambda.Templates, Durable Execution, MapDurableHandler, IDurableContext, or adding a Lambda to an existing solution. +description: Work effectively with MinimalLambda, the Lambda-first .NET hosting framework in this repo and in client projects. Use this skill whenever the user asks to build, debug, migrate, test, document, scaffold, template, package, or review code using MinimalLambda APIs, `dotnet new mlambda` templates, envelopes, middleware, lifecycle hooks, source-generated handlers, AOT/trimming, OpenTelemetry, or MinimalLambda.Testing. Trigger even when the user only mentions AWS Lambda with Minimal API-style .NET patterns, MapHandler, MapEventHandler, FromEvent, LambdaApplication, MinimalLambda package names, MinimalLambda.Templates, Durable Execution, MapDurableHandler, IDurableContext, or adding a Lambda to an existing solution. --- # MinimalLambda skill @@ -49,7 +49,7 @@ Core pieces: - `LambdaApplication.CreateBuilder()` creates standard .NET host/config/DI defaults. - `MapHandler(...)` registers one ordinary Lambda handler. Source generator intercepts it at compile time. - Optional `MinimalLambda.EventProcessing`: `MapEventHandler(...)` registers one batch processor: split the event, run one scope per item - concurrently, then build one response. Read `references/event-processor.md`. + concurrently, with an optional final response. Read `references/event-processor.md`. - `MapDurableHandler(...)` registers one durable workflow with stricter signature, cancellation, replay, middleware, and serializer rules; read `references/durable-execution.md`. - `[FromEvent]` marks deserialized event payload. Ordinary handlers allow at most one; durable handlers allow zero or one. `IDurableContext` is optional for durable handlers. - Other handler parameters resolve from DI/context/keyed services/cancellation token. diff --git a/skills/minimal-lambda/references/event-processor.md b/skills/minimal-lambda/references/event-processor.md index fe2f2618..e647cd4b 100644 --- a/skills/minimal-lambda/references/event-processor.md +++ b/skills/minimal-lambda/references/event-processor.md @@ -53,6 +53,9 @@ Scope creation/disposal failures fail invocation. Drain admitted work and cleanu Return DTOs that survive scope disposal. First fatal error wins; additional failures are logged. Invocation cancellation takes precedence. +Item scopes are separate from the invocation scope. Scoped services resolved by middleware are +not shared with item handlers. Use injected handler services for per-item state. + Options default to concurrency enabled, maximum 10. Optional Configure before Build changes them. Mapping after Build captures and validates effective options, including defaults; positive maximum required even in sequential mode. Never hide configuration exceptions. @@ -71,6 +74,14 @@ normal conditional event/final-response provider setup. Duplicate mappings prese Keep scheduling, batching, state and response construction in package code. No new core feature APIs, processing feature, Bind/Invoke stages, BoundArguments, runtime reflection, or generated algorithms. -Validate real serialization/envelopes/middleware, keyed/optional/framework bindings, ordered outcomes, -DI mapping, fatal cleanup, cancellation races, packed consumers and Native AOT. See -`docs/features/event-processor.md` and `designs/event-processing-contracts.md` for full contracts. +## Serialization + +For Native AOT, register a source-generated JSON context for the full event and final response with +AddLambdaSerializerWithContext. Envelope body types also need metadata and ConfigureEnvelopeOptions +with the context's resolver. Intermediate item results need metadata only if the final response +contains them. See `patterns/aot-and-envelopes.md` for setup. + +For repo validation, cover serialization/envelopes/middleware, keyed/optional/framework bindings, +ordered outcomes, DI mapping, fatal cleanup, cancellation races, packed consumers and Native AOT. +The [event-processing guide](https://layeredcraft.github.io/minimal-lambda/features/event-processor/) +contains usage examples. Read `repo-workflow.md` for repository commands and source locations. diff --git a/skills/minimal-lambda/scripts/validate_references.py b/skills/minimal-lambda/scripts/validate_references.py index 350d51f0..0e339580 100755 --- a/skills/minimal-lambda/scripts/validate_references.py +++ b/skills/minimal-lambda/scripts/validate_references.py @@ -20,6 +20,7 @@ SKILL / "references" / "best-practices.md", SKILL / "references" / "client-project-setup.md", SKILL / "references" / "envelopes.md", + SKILL / "references" / "event-processor.md", SKILL / "references" / "testing.md", SKILL / "references" / "opentelemetry.md", SKILL / "references" / "troubleshooting.md", @@ -35,6 +36,10 @@ SYMBOL_CHECKS = { "LambdaApplication": "src/MinimalLambda/Builder/LambdaApplication.cs", "MapHandler": "src/MinimalLambda/Builder/InterceptionTargets/MapHandlerLambdaApplicationExtensions.cs", + "MapEventHandler": "src/MinimalLambda.EventProcessing/MapEventHandlerLambdaApplicationExtensions.cs", + "IEventProcessingContext": "src/MinimalLambda.EventProcessing/IEventProcessingContext.cs", + "EventHandlerOptions": "src/MinimalLambda.EventProcessing/EventHandlerOptions.cs", + "EventItemOutcome": "src/MinimalLambda.EventProcessing/EventItemOutcome.cs", "FromEventAttribute": "src/MinimalLambda.Abstractions/Attributes/FromEventAttribute.cs", "AddLambdaSerializerWithContext": "src/MinimalLambda/Builder/Extensions/SerializerServiceCollectionExtensions.cs", "ConfigureEnvelopeOptions": "src/MinimalLambda/Builder/Extensions/ConfigurationServiceCollectionExtensions.cs",