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/Directory.Packages.props b/Directory.Packages.props index e885e000..95fb0139 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -13,6 +13,7 @@ + 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 66aa3229..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 @@ -105,6 +105,14 @@ 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 +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 @@ -547,6 +555,38 @@ 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 + {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 + {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 @@ -591,5 +631,7 @@ 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} + {5BFFA5F3-9A74-4574-80B5-27968203E2F9} = {D9109C8A-AFA8-49C8-A19C-381500902B4D} EndGlobalSection EndGlobal diff --git a/designs/event-processing-contracts.md b/designs/event-processing-contracts.md new file mode 100644 index 00000000..b5ecbc4b --- /dev/null +++ b/designs/event-processing-contracts.md @@ -0,0 +1,107 @@ +# 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 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 | +| Results with errors | Task | TResult | handler or mapper result | + +Response callbacks are synchronous `Func>, +ILambdaInvocationContext, TResponse>`. Error callbacks are synchronous +`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. + +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. +// No-response handlers may omit onError or supply a synchronous action. +``` + +## 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 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. + +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 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 +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 new file mode 100644 index 00000000..103efd07 --- /dev/null +++ b/designs/event-processor.md @@ -0,0 +1,25 @@ +# Event-processing design + +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. + +`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. + +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. + +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. + +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. + +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 new file mode 100644 index 00000000..2d9f1ccc --- /dev/null +++ b/docs/features/event-processor.md @@ -0,0 +1,214 @@ +# Event processing + +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 +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. + +## Callback families + +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` | synchronous action | absent | absent | +| `Task` | absent | source item | required | +| `Task` | `TFailure` | absent | required | +| `Task` | absent | result | required | +| `Task` | `TResult` | result | required | + +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. +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. 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, + 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 + .Where(outcome => outcome.Status != EventItemStatus.Succeeded || outcome.Value is Retry) + .Select(outcome => new SQSBatchResponse.BatchItemFailure + { + ItemIdentifier = outcome.Item.MessageId, + }) + .ToList())); +``` + +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. + +## Binding and scopes + +The item is the handler's first argument. Up to ten further parameters bind as follows: + +- `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. + +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. + +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. + +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. + +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. + +## Options and cancellation + +Defaults enable concurrency with at most ten active items per invocation. Scope disposal counts +against that limit. This is item concurrency inside one invocation. + +```csharp +builder.Services.Configure(options => +{ + options.EnableConcurrency = false; + options.MaxConcurrentExecutions = 1; +}); +``` + +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. + +`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. + +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. + +## Registration and middleware + +`MapEventHandler` consumes the same terminal-handler slot as `MapHandler`. A second mapping throws +before replacing provider properties. Existing custom providers retain precedence. + +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. + +## 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/docs/features/index.md b/docs/features/index.md index ce4c0292..48fa1aa3 100644 --- a/docs/features/index.md +++ b/docs/features/index.md @@ -8,6 +8,12 @@ ______________________________________________________________________ ## Feature Categories +### [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 six 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..0712e277 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`](../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 new file mode 100644 index 00000000..e3bec06b --- /dev/null +++ b/examples/MinimalLambda.Example.EventProcessor/MinimalLambda.Example.EventProcessor.csproj @@ -0,0 +1,40 @@ + + + Exe + net8.0 + latest + enable + enable + true + Lambda + + true + + true + true + full + true + false + $(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..076376ba --- /dev/null +++ b/examples/MinimalLambda.Example.EventProcessor/Program.cs @@ -0,0 +1,199 @@ +using MinimalLambda.EventProcessing; +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(); + +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(); + +// 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; +} + +// 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; +} + +await lambda.RunAsync(); + +// 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, + CancellationToken token) => + { + if (item.BodyContent is null) + return Task.CompletedTask; + + return importer.ImportAsync(item.BodyContent, token); + }); + +// 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: (outcomes, _) => + new BatchSummary( + outcomes.Count(outcome => outcome.Status == EventItemStatus.Succeeded))); + +// 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, + 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: (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. +static void RegisterResults(LambdaApplication lambda) +{ + Func> handle = + EventHandlers.HandleImportAsync; + + lambda.MapEventHandler( + split: (ImportBatch batch, ILambdaInvocationContext _) => batch.Items, + handle: handle, + 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. +// Include unstarted and cancelled items in the application retry 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: (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); + +public sealed record ImportBatch(IReadOnlyList Items); + +public sealed record ImportDocument(MyEvent Event); + +public sealed record BatchSummary(int Count); + +public abstract record ImportItemResult; + +public sealed record Success(string MessageId) : ImportItemResult; + +public sealed record Retry(string MessageId) : ImportItemResult; + +public sealed class DocumentImporter +{ + public Task ImportAsync(MyEvent message, CancellationToken token) + { + token.ThrowIfCancellationRequested(); + return Task.CompletedTask; + } + + public Task ImportResultAsync(MyEvent message, CancellationToken token) + { + token.ThrowIfCancellationRequested(); + return Task.FromResult(new Success(message.Message)); + } +} + +public static class EventHandlers +{ + 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) + { + 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 new file mode 100644 index 00000000..b030e581 --- /dev/null +++ b/examples/MinimalLambda.Example.EventProcessor/README.md @@ -0,0 +1,62 @@ +# MinimalLambda.Example.EventProcessor + +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 | +| `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 | + +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 + +- `RegisterNoResult` - no result, no response. +- `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. +- `RegisterResultsWithRecovery` - the SQS partial batch response shape. + +## Prerequisites + +- 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. + +## Restore and build + +```bash +dotnet restore +dotnet build +``` + +## 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_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 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. +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/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" +} 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/scripts/test-package-compatibility.sh b/scripts/test-package-compatibility.sh index 37231d1a..2a459cc6 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 @@ -139,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 @@ -153,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")} @@ -211,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",)) @@ -245,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" @@ -278,8 +291,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) != 7: + raise SystemExit(f"expected seven copied consumer projects, found {len(projects)}") for project in projects: tree = ET.parse(project) references = [ @@ -287,9 +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 == "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.") @@ -322,17 +342,22 @@ 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" 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" \ "$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 @@ -345,16 +370,65 @@ 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") 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 +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 f15560fa..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 @@ -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. +- Optional `MinimalLambda.EventProcessing`: `MapEventHandler(...)` registers one batch processor: split the event, run one scope per item + 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. @@ -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` 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/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..e647cd4b --- /dev/null +++ b/skills/minimal-lambda/references/event-processor.md @@ -0,0 +1,87 @@ +# 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. + +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. + +## 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. + +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. + +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. + +## 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", diff --git a/src/AotCompatibility.TestApp/AotCompatibility.TestApp.csproj b/src/AotCompatibility.TestApp/AotCompatibility.TestApp.csproj index 39ba9afc..e394292a 100644 --- a/src/AotCompatibility.TestApp/AotCompatibility.TestApp.csproj +++ b/src/AotCompatibility.TestApp/AotCompatibility.TestApp.csproj @@ -1,4 +1,4 @@ - + Exe net10.0 @@ -10,13 +10,20 @@ true IL2026;IL2087;IL2091;IL3050;IL3051 false + $(InterceptorsNamespaces);MinimalLambda.Generated + + + diff --git a/src/AotCompatibility.TestApp/Program.cs b/src/AotCompatibility.TestApp/Program.cs index b1ed2f2c..1f71de56 100644 --- a/src/AotCompatibility.TestApp/Program.cs +++ b/src/AotCompatibility.TestApp/Program.cs @@ -1,3 +1,60 @@ -// This executable exists only to root MinimalLambda assemblies for Native AOT publish analysis. +// This executable roots MinimalLambda assemblies for Native AOT publish analysis. +// It also registers a real event-processor mapping so the generated processor is compiled, +// trimmed, and analyzed rather than discarded as unreachable code. +using System.Text.Json.Serialization; +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 = 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: (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 +// 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; diff --git a/src/MinimalLambda.EventProcessing/EventHandlerFactory.cs b/src/MinimalLambda.EventProcessing/EventHandlerFactory.cs new file mode 100644 index 00000000..6049ac08 --- /dev/null +++ b/src/MinimalLambda.EventProcessing/EventHandlerFactory.cs @@ -0,0 +1,225 @@ +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 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. + /// 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.EventProcessing/EventHandlerOptions.cs b/src/MinimalLambda.EventProcessing/EventHandlerOptions.cs new file mode 100644 index 00000000..ab230d1b --- /dev/null +++ b/src/MinimalLambda.EventProcessing/EventHandlerOptions.cs @@ -0,0 +1,34 @@ +namespace MinimalLambda.EventProcessing; + +/// 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.EventProcessing/EventHandlerOptionsValidator.cs b/src/MinimalLambda.EventProcessing/EventHandlerOptionsValidator.cs new file mode 100644 index 00000000..43c8c816 --- /dev/null +++ b/src/MinimalLambda.EventProcessing/EventHandlerOptionsValidator.cs @@ -0,0 +1,16 @@ +using Microsoft.Extensions.Options; + +namespace MinimalLambda.EventProcessing; + +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; + } +} 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..29c1857e --- /dev/null +++ b/src/MinimalLambda.EventProcessing/EventProcessorRuntime.cs @@ -0,0 +1,118 @@ +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); + } + + context.CancellationToken.ThrowIfCancellationRequested(); + using var state = new EventProcessingState(context, _logger, items.Count); + var outcomes = + await EventProcessorWorkers + .RunAsync(items, _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..8cd602ae --- /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( + List items, + int effectiveConcurrency, + IServiceScopeFactory scopeFactory, + EventProcessingState state, + Func>> adapter, + bool collectValues) + { + if (items.Count == 0) + state.TryCloseHandling(); + + var outcomes = + collectValues + ? items + .Select((item, index) => + new EventItemOutcome(index, item, EventItemStatus.Skipped)) + .ToArray() + : null; + var workerCount = Math.Min(items.Count, 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.EventProcessing/IEventProcessingContext.cs b/src/MinimalLambda.EventProcessing/IEventProcessingContext.cs new file mode 100644 index 00000000..5e346cbc --- /dev/null +++ b/src/MinimalLambda.EventProcessing/IEventProcessingContext.cs @@ -0,0 +1,56 @@ +namespace MinimalLambda.EventProcessing; + +/// +/// 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.EventProcessing/MapEventHandlerLambdaApplicationExtensions.cs b/src/MinimalLambda.EventProcessing/MapEventHandlerLambdaApplicationExtensions.cs new file mode 100644 index 00000000..f9a0711d --- /dev/null +++ b/src/MinimalLambda.EventProcessing/MapEventHandlerLambdaApplicationExtensions.cs @@ -0,0 +1,1913 @@ +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 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. +/// +/// +/// 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 (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. + /// 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 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) + { + 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 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) + { + 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 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) + { + 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 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) + { + 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 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) + { + 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 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) + { + 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 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) + { + 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 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) + { + 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 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) + { + 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 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) + { + 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 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) + { + 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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) + { + 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 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) + { + 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 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) + { + 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 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) + { + 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 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) + { + 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 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) + { + 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 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) + { + 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 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) + { + 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 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) + { + 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 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) + { + 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 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) + { + 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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.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..f0ccad39 --- /dev/null +++ b/src/MinimalLambda.EventProcessing/README.md @@ -0,0 +1,20 @@ +# 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 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. + +See https://layeredcraft.github.io/minimal-lambda/features/event-processor/ for usage and callback contracts. 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..755f2df0 100644 --- a/src/MinimalLambda.SourceGenerators/Extensions/ParameterSymbolExtensions.cs +++ b/src/MinimalLambda.SourceGenerators/Extensions/ParameterSymbolExtensions.cs @@ -30,12 +30,15 @@ internal bool IsFromEvent(GeneratorContext context) => WellKnownType.MinimalLambda_Builder_FromEventAttribute)); internal DiagnosticResult<(string Assignment, string? Key)> GetDiParameterAssignment( - GeneratorContext context) + GeneratorContext context, + 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) @@ -43,16 +46,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..5eb199cc --- /dev/null +++ b/src/MinimalLambda.SourceGenerators/Models/Handlers/EventHandlerMethodInfo.cs @@ -0,0 +1,823 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +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, + N4, + 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); + + 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 + && (mapperMethod.IsAsync || 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, + createResponseArgument is not null); + 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; + + 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); + 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; + } + 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 (responseIsAwaitable || 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 + or EventHandlerFamily.N4 + && TryUnwrapTask(handlerMethod.ReturnType, context, out _)) + diagnostics.Add( + CreateDiagnostic( + Diagnostics.DiscardedEventHandlerResult, + handlerArgumentLocation, + handlerMethod.Name)); + + var parameters = handlerMethod is null + ? [] + : CreateParameters( + handlerMethod, + handleDelegate!.DelegateInvokeMethod!, + itemType, + context, + diagnostics); + + var valueType = family switch + { + EventHandlerFamily.N1 or EventHandlerFamily.N4 => "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 hasOnError ? EventHandlerFamily.N4 : EventHandlerFamily.N1; + + return hasOnError ? EventHandlerFamily.N3 : EventHandlerFamily.N2; + } + + private static List CreateParameters( + IMethodSymbol handlerMethod, + IMethodSymbol delegateInvokeMethod, + 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 parameterType = delegateInvokeMethod.Parameters[index].Type; + 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(parameterType, 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 + || parameterType.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, parameterType)) + parameterDiagnostics.Add( + CreateDiagnostic( + Diagnostics.UnsupportedEventHandlerSignature, + location, + $"item parameter '{parameter.Name}'")); + } + else if (context.WellKnownTypes.IsType( + parameterType, + 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( + parameterType, + WellKnownType.MinimalLambda_EventProcessing_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( + parameterType, + 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", + parameterType); + if (diResult.IsSuccess) + { + if (diResult.Value!.Key is not null) + { + kind = EventHandlerParameterKind.KeyedService; + keyedKey = diResult.Value.Key; + } + + assignment = diResult.Value.Assignment; + if (parameter.IsOptional) + { + var typeName = parameterType.QualifiedNullableName; + 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('?'))}))"; + assignment = + $"{lookup} is {{ }} service{parameter.Ordinal} ? ({typeName})service{parameter.Ordinal} : {defaultValue}"; + } + } + else if (diResult.Error is { } error) + parameterDiagnostics.Add(error); + } + + parameters.Add( + new EventHandlerParameterInfo( + parameter.Ordinal, + parameter.Name, + parameterType.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); + 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) + continue; + + if (!SymbolEqualityComparer.Default.Equals( + model.GetSymbolInfo(identifier, cancellationToken).Symbol, + local)) + continue; + + 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 == target => 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..fe55bc75 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.EventProcessing" + && 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..3779e8a0 --- /dev/null +++ b/src/MinimalLambda.SourceGenerators/Templates/MapEventHandler.scriban @@ -0,0 +1,80 @@ +//------------------------------------------------------------------------------ +// +// 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.Runtime.CompilerServices; + using System.Threading.Tasks; + using Microsoft.Extensions.DependencyInjection; + using MinimalLambda.Builder; + using MinimalLambda.EventProcessing; + using MinimalLambda; + + {{ generated_code_attribute.value }} + file static class GeneratedEventProcessorExtensions + { + {{~ 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(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("__ResponseFeatureProvider")) + application.Properties["__ResponseFeatureProvider"] = application.Services + .GetRequiredService().Create<{{ call.response_type }}>(); + {{~ end ~}} + return application; + + {{ if call.handle_returns_result }}Task<{{ call.value_type }}>{{ else }}Task{{ end }} HandleItem( + {{ call.item_type }} item, + IServiceProvider serviceProvider, + IEventProcessingContext 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 ~}} + return handle({{ call.handler_arguments }}); + } + } + {{~ end ~}} + } +} diff --git a/src/MinimalLambda.SourceGenerators/WellKnownTypes/WellKnownTypeData.cs b/src/MinimalLambda.SourceGenerators/WellKnownTypes/WellKnownTypeData.cs index b0cbd214..11255f65 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_EventProcessing_IEventProcessingContext, MinimalLambda_ILambdaLifecycleContext, MinimalLambda_Builder_EventAttribute, MinimalLambda_Builder_FromArgumentsAttribute, @@ -111,6 +112,7 @@ public enum WellKnownType "System.IServiceProvider", "System.Void", "MinimalLambda.ILambdaInvocationContext", + "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 6aff9dd2..ddb42681 100644 --- a/src/MinimalLambda/Builder/Extensions/ServiceCollectionExtensions.cs +++ b/src/MinimalLambda/Builder/Extensions/ServiceCollectionExtensions.cs @@ -39,6 +39,7 @@ public IServiceCollection AddLambdaHostCoreServices() services.AddHostedService(); // Register options related services + 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..43fd1dda --- /dev/null +++ b/tests/MinimalLambda.EventProcessing.UnitTests/EventHandlerRegistrationTests.cs @@ -0,0 +1,118 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +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() + { + 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..eeea319f --- /dev/null +++ b/tests/MinimalLambda.EventProcessing.UnitTests/EventProcessorRuntimeTests.cs @@ -0,0 +1,352 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +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"); + } + + [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(); + 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.EventProcessing.UnitTests/EventProcessorTests.cs b/tests/MinimalLambda.EventProcessing.UnitTests/EventProcessorTests.cs new file mode 100644 index 00000000..420026d7 --- /dev/null +++ b/tests/MinimalLambda.EventProcessing.UnitTests/EventProcessorTests.cs @@ -0,0 +1,2512 @@ +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; + +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() + { + // Arrange + var responseCalls = 0; + Response? captured = null; + await using var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item _) => Task.CompletedTask, + 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); + 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: (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(); + + // 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: (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(); + + // 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: (outcomes, _) => + { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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 NullHandlerTaskIsMappedAsItemError() + { + // 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: (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(); + + // Act + var act = () => handler(harness.Context); + + // Assert + await act.Should().NotThrowAsync(); + errorCalls.Should().Be(1); + } + + [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: (outcomes, _) => + { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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: (outcomes, _) => + { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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: (outcomes, _) => + { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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 InvocationCancellationDuringDisposalSuppressesResponse() + { + // 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: (outcomes, _) => + { + var ids = outcomes + .Where(outcome => outcome.HasValue) + .Select(outcome => outcome.Value!); + captured = new Response(ids.ToList()); + return captured; + }); + + var harness = CreateHarness(app, new Batch([new Item(1)]), invocationCancellation); + var handler = app.Build(); + + // Act + var run = () => handler(harness.Context); + await run.Should().ThrowAsync(); + + // Assert + invocationCancellation.IsCancellationRequested.Should().BeTrue(); + captured.Should().BeNull(); + harness.ResponseFeature.DidNotReceive().SetResponse(Arg.Any()); + } + + [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: ( + IReadOnlyList> _, + 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: (outcomes, _) => + { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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); + } + + [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: (outcomes, _) => + { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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: (outcomes, _) => + { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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: ( + IReadOnlyList> _, + 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: ( + IReadOnlyList> _, + 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); + } + + [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: (outcomes, _) => + { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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: (outcomes, _) => + { + var failures = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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: (outcomes, _) => + { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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: (outcomes, _) => + { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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: (outcomes, _) => + new Response( + outcomes + .Where(outcome => outcome.HasValue) + .Select(outcome => outcome.Value!) + .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: (outcomes, _) => + { + var failures = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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); + } + + [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: (outcomes, _) => + { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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: (outcomes, _) => + { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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: (outcomes, _) => + { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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: (outcomes, _) => + { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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); + } + + [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: (outcomes, _) => + { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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: (outcomes, _) => + { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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: (outcomes, _) => + { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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: (outcomes, _) => + { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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: (outcomes, _) => + { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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: (outcomes, _) => + { + var items = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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.EventProcessing").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.EventProcessing").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 MissingDependencyResolutionFailureIsMappedByErrorMapper() + { + // 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: (outcomes, _) => + { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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().NotThrowAsync(); + errorCalls.Should().Be(1); + responseCalls.Should().Be(1); + } + + [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: (outcomes, _) => + { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + contributed = results.Select(result => result.SequenceNumber).ToList(); + captured = new StreamResponse( + results + .Where(result => result.Failed) + .Select(result => result.SequenceNumber) + .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 + // 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: (outcomes, _) => + { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + captured = new StreamResponse( + results + .Where(result => result.Failed) + .Select(result => result.SequenceNumber) + .OrderBy(sequenceNumber => sequenceNumber, StringComparer.Ordinal) + .Take(1) + .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 + // 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 InvocationCancellationDuringResponseConstructionSuppressesResponse() + { + // 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: (outcomes, _) => + { + var results = + outcomes.Where(outcome => outcome.HasValue).Select(outcome => outcome.Value!); + 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 + var run = () => handler(harness.Context); + await run.Should().ThrowAsync(); + + // Assert + invocationCancellation.IsCancellationRequested.Should().BeTrue(); + responseCalls.Should().Be(1); + captured!.Ids.Should().Equal(1); + harness.ResponseFeature.DidNotReceive().SetResponse(Arg.Any()); + } + + 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)); + while (!condition()) + await Task.Delay(10, timeout.Token); + } + + private static Harness CreateHarness( + LambdaApplication app, + Batch batch, + CancellationTokenSource? invocationCancellation = null) => + CreateHarness(app, batch, invocationCancellation); + + 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); + + internal sealed record KeyedValue(int Value); + + 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 + { + 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); + } + + 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 = []; + 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); +} diff --git a/tests/MinimalLambda.EventProcessing.UnitTests/MapEventHandlerLambdaApplicationExtensionsTests.cs b/tests/MinimalLambda.EventProcessing.UnitTests/MapEventHandlerLambdaApplicationExtensionsTests.cs new file mode 100644 index 00000000..02099b35 --- /dev/null +++ b/tests/MinimalLambda.EventProcessing.UnitTests/MapEventHandlerLambdaApplicationExtensionsTests.cs @@ -0,0 +1,42 @@ +#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 + && method.GetParameters().Length == 3); + 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.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..16efeefa --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerCallbackShapeTests.cs @@ -0,0 +1,108 @@ +using AwesomeAssertions; + +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", + "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 new file mode 100644 index 00000000..91bc977e --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiagnosticTests.cs @@ -0,0 +1,414 @@ +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.EventProcessing; + 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.EventProcessing; + 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.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: (IReadOnlyList> 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.EventProcessing; + 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.EventProcessing; + 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 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(); + } + + [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.EventProcessing; + using MinimalLambda.Builder; + + {{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; + {{scopeEnd}} + + 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"); + } + + [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() + { + var result = RunGenerator( + """ + 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) => 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.EventProcessing; + 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..0cf5c2da --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerDiscoveryTests.cs @@ -0,0 +1,610 @@ +using System.Text; +using AwesomeAssertions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace MinimalLambda.SourceGenerators.UnitTests; + +public class EventHandlerDiscoveryTests +{ + [Fact] + public void GeneratesInterceptorsForAllSixtySixOverloads() + { + 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(66); + + 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.EventProcessing; + 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(); + } + + [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() + { + var result = RunGenerator( + """ + 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; + """); + + result.Diagnostics.Should().BeEmpty(); + result + .GeneratedTrees + .Should() + .ContainSingle(tree => tree.FilePath.EndsWith( + "MinimalLambda.EventHandlers.g.cs", + 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() + { + var errors = CompileErrors( + """ + 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: 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.EventProcessing; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: HandleSuccess, + createResponse: (IReadOnlyList> 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 RejectsAsyncVoidHandlerAtCompileTime() + { + var errors = CompileErrors( + """ + 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 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() + { + var result = RunGenerator( + """ + using System.Collections.Generic; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.EventProcessing; + using MinimalLambda.Builder; + + var app = LambdaApplication.CreateBuilder().Build(); + + app.MapEventHandler( + (Batch batch, ILambdaInvocationContext _) => batch.Items, + Handle, + (IReadOnlyList> items, ILambdaInvocationContext _) => new Response()); + + app.MapEventHandler( + createResponse: (IReadOnlyList> 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.EventProcessing; + 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() + { + var result = RunGenerator( + """ + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.EventProcessing; + 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 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) + { + 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.EventProcessing; + 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, + onError: (item, exception, processing) => { }); + """); + builder.AppendLine( + $$""" + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item{{parameters}}) => Task.CompletedTask, + createResponse: (IReadOnlyList> 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: (IReadOnlyList> failures, ILambdaInvocationContext _) => new Response()); + """); + builder.AppendLine( + $$""" + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item{{parameters}}) => Task.FromResult(item.Id), + createResponse: (IReadOnlyList> 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: (IReadOnlyList> 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..1339fdea --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/EventHandlerEmitterTests.cs @@ -0,0 +1,291 @@ +using AwesomeAssertions; +using Microsoft.CodeAnalysis; + +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( + """ + using System; + 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: (Item item) => Task.CompletedTask); + + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => Task.CompletedTask, + 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: (IReadOnlyList> failures, ILambdaInvocationContext _) => new Response()); + + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => Task.FromResult(item.Id), + 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: (IReadOnlyList> 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.EventProcessing; + 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: (IReadOnlyList> 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 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() + { + const string source = """ + using System.Collections.Generic; + using System.Threading.Tasks; + using MinimalLambda; + using MinimalLambda.EventProcessing; + 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: (IReadOnlyList> 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() + { + const string source = """ + 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: (Item item) => Task.CompletedTask); + app.MapEventHandler( + split: (Batch batch, ILambdaInvocationContext _) => batch.Items, + handle: (Item item) => Task.CompletedTask, + createResponse: (IReadOnlyList> 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..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; @@ -12,6 +13,7 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using MinimalLambda.Builder; @@ -153,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), @@ -160,6 +163,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/MinimalLambda.SourceGenerators.UnitTests.csproj b/tests/MinimalLambda.SourceGenerators.UnitTests/MinimalLambda.SourceGenerators.UnitTests.csproj index 660bf889..b2b0ad19 100644 --- a/tests/MinimalLambda.SourceGenerators.UnitTests/MinimalLambda.SourceGenerators.UnitTests.csproj +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/MinimalLambda.SourceGenerators.UnitTests.csproj @@ -56,4 +56,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 new file mode 100644 index 00000000..a2bbfb43 --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsContextTokenAndKeyedServiceBindings#MinimalLambda.EventHandlers.g.verified.cs @@ -0,0 +1,81 @@ +//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 onError, + global::System.Func>, global::MinimalLambda.ILambdaInvocationContext, global::Response> createResponse) + { + ArgumentNullException.ThrowIfNull(handle); + 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; + + Task HandleItem( + global::Item item, + IServiceProvider serviceProvider, + IEventProcessingContext 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"); + return handle(arg0, arg1, arg2, arg3, arg4, arg5); + } + } + } +} 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); + } + } + } +} 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 new file mode 100644 index 00000000..8ed5d16c --- /dev/null +++ b/tests/MinimalLambda.SourceGenerators.UnitTests/Snapshots/EventHandlerEmitterTests.EmitsRepresentativeAdapterForEveryFamily#MinimalLambda.EventHandlers.g.verified.cs @@ -0,0 +1,198 @@ +//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; + return handle(arg0); + } + } + [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; + return handle(arg0); + } + } + [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(handle); + 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; + + Task HandleItem( + global::Item item, + IServiceProvider serviceProvider, + IEventProcessingContext processingContext) + { + var arg0 = item; + return handle(arg0); + } + } + [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(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; + return handle(arg0); + } + } + [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(handle); + 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; + + Task HandleItem( + global::Item item, + IServiceProvider serviceProvider, + IEventProcessingContext processingContext) + { + var arg0 = item; + 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 new file mode 100644 index 00000000..d3af1a50 --- /dev/null +++ b/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/MinimalLambda.Testing.UnitTests.EventProcessorLambda.csproj @@ -0,0 +1,35 @@ + + + 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..219f4426 --- /dev/null +++ b/tests/MinimalLambda.Testing.UnitTests/Lambdas/MinimalLambda.Testing.UnitTests.EventProcessorLambda/Program.cs @@ -0,0 +1,149 @@ +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: (SqsEnvelope batch, ILambdaInvocationContext context) => + { + var probe = context.ServiceProvider.GetRequiredService(); + probe.SplitEvent = batch; + probe.Stages.Enqueue("split"); + return batch.Records; + }, + handle: async Task ( + 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.BodyContent is "stop") + { + processing.StopProcessing(); + return new Success(item.MessageId); + } + + if (item.BodyContent is "retry" or "fatal") + throw new InvalidOperationException("retry requested"); + + await Task.Yield(); + return new Success(item.MessageId); + }, + onError: (item, _, _) => + item.BodyContent == "fatal" + ? throw new InvalidOperationException("mapper failed") + : new Retry(item.MessageId), + 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(); + +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 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(); + + public void Record(string messageId) => messageIds.Enqueue(messageId); +} + +public class EventProcessorLambda; + +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/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..87172fa5 --- /dev/null +++ b/tests/MinimalLambda.Testing.UnitTests/Tests/MinimalLambda.Testing.UnitTests/EventProcessorLambdaTests.cs @@ -0,0 +1,255 @@ +using System.Text.Json; +using Amazon.Lambda.SQSEvents; +using Microsoft.Extensions.DependencyInjection; +using MinimalLambda.EventProcessing; + +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() + { + // 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.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); + factory.ServerOptions.FunctionTimeout = TestFunctionTimeout; + 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); + factory.ServerOptions.FunctionTimeout = TestFunctionTimeout; + + // 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); + factory.ServerOptions.FunctionTimeout = TestFunctionTimeout; + 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(); + } + + [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_SequentialStopReportsUnprocessedRecordsAsFailures() + { + // 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 application retries every failed or unstarted source position. + response + .Response + .BatchItemFailures + .Select(failure => failure.ItemIdentifier) + .Should() + .Equal("id-1", "id-3", "id-4"); + factory + .Services + .GetRequiredService() + .MessageIds + .Should() + .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() + { + Records = + [ + .. records.Select(record => new SQSEvent.SQSMessage + { + MessageId = record.MessageId, + ReceiptHandle = "receipt-" + record.MessageId, + Body = JsonSerializer.Serialize(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 @@ + >().Value.Should().NotBeNull(); } [Fact] 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/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 new file mode 100644 index 00000000..21ec3e94 --- /dev/null +++ b/tests/package-compatibility/EventProcessorConsumer/EventProcessorConsumer.csproj @@ -0,0 +1,18 @@ + + + $(CorePackageVersion) + Exe + net8.0;net9.0;net10.0;net11.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..cbffcdad --- /dev/null +++ b/tests/package-compatibility/EventProcessorConsumer/Program.cs @@ -0,0 +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 MinimalLambda; +using MinimalLambda.Builder; +using MinimalLambda.EventProcessing; + +await RunFixture(false); +await RunFixture(true); +Console.WriteLine("Packed event fixture passed: defaults, configured options, middleware, JSON response, ordered outcomes, async scopes."); + +static async Task RunFixture(bool configured) +{ + var builder = LambdaApplication.CreateBuilder(); + builder.Services.AddLambdaSerializerWithContext(); + builder.Services.AddScoped(); + if (configured) + { + builder.Services.Configure(o => o.MaxConcurrentExecutions = 1); + builder.Services.AddKeyedSingleton("label", ""); + } + 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); + + } + 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(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