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