diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 925179e..825c443 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -40,6 +40,7 @@ jobs: mkdir -p nupkgs dotnet pack src/Interlink/Interlink.csproj -c Release -o ./nupkgs --no-build dotnet pack src/Interlink.Extensions.Logging/Interlink.Extensions.Logging.csproj -c Release -o ./nupkgs --no-build + dotnet pack src/Interlink.Extensions.Validation/Interlink.Extensions.Telemetry.csproj -c Release -o ./nupkgs --no-build dotnet pack src/Interlink.Extensions.Validation/Interlink.Extensions.Validation.csproj -c Release -o ./nupkgs --no-build dotnet pack src/Interlink.AspNetCore/Interlink.AspNetCore.csproj -c Release -o ./nupkgs --no-build dotnet pack src/Interlink.Analyzers/Interlink.Analyzers.csproj -c Release -o ./nupkgs --no-build diff --git a/CHANGELOG.md b/CHANGELOG.md index 2830b80..1ce684e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,131 +1,95 @@ # Changelog -## [1.5.2] - 2026-08-13 +All notable changes to **Interlink** are documented in this file. + +## [1.7.0] - 2026-11-08 ### Added -- **Unified `IMediator`** – new interface that inherits from both `ISender` and `IPublisher`. -- **`Mediator` implementation** – lightweight composition of the existing `Sender` and `Publisher`. -- `IMediator` is now registered by default in `AddInterlink()`. -### Changed -- Users can now inject `IMediator`, `ISender`, or `IPublisher` independently (full backward compatibility). +- **NotificationExceptionStrategy** on `InterlinkOptions`: + - `StopOnFirst` (default) — rethrow the first handler failure + - `Aggregate` — run all handlers, then throw `AggregateException` if any failed + - `Continue` — run all handlers; failures handled by exception handlers and not rethrown by default +- **`INotificationExceptionHandler`** — handle per-handler failures (logging, outbox, compensation) +- **`NotificationHandlerException`** — wraps a single handler failure with `NotificationType` and `HandlerType` +- **`Interlink.Extensions.Telemetry`** — Activity instrumentation for: + - `Send` → `Interlink.Send {Request}` + - `Publish` → `Interlink.Publish {Notification}` + - `CreateStream` → `Interlink.CreateStream {Request}` +- Registration: `services.AddInterlinkTelemetry()` +- Activity source name: **`Interlink`** +- Unit tests for Aggregate, Continue, StopOnFirst, and exception handler invocation ---- +### Changed -## [1.5.1] - 2026-08-XX +- `Publisher` applies `NotificationExceptionStrategy` and dispatches notification exception handlers before rethrowing or continuing +- Assembly scanning registers `INotificationExceptionHandler<,>` implementations -### Added -- **`Unit` support** – non-generic `IRequest` (equivalent to `IRequest`) for fire-and-forget / void commands. -- `Unit` struct with `Unit.Value`. -- Convenience overload `ISender.Send(IRequest request)` that maps to `Send()`. +### Packages -### Changed -- Documentation and examples updated to show `Unit` usage. +| Package | Version | +|---------|---------| +| Interlink | 1.7.0 | +| Interlink.Extensions.Telemetry | 1.7.0 | +| Interlink.Extensions.Logging | 1.7.0 | +| Interlink.Extensions.Validation | 1.7.0 | +| Interlink.AspNetCore | 1.7.0 | +| Interlink.Analyzers | 1.7.0 | --- -## [1.5.0] - 2026-07-31 +## [1.6.0] ### Added -- **HandlerNotFoundException** – dedicated exception type thrown when a request has no registered handler. -- **Pipeline ordering** – `PipelineOrderAttribute` is now respected; behaviors are sorted ascending (lowest order runs outermost). -- **Custom service factory** – fully wired via `InterlinkOptions.ServiceFactory`. -- **Interlink.Extensions.Logging** – `LoggingBehavior` + `AddInterlinkLogging()`. -- **Interlink.Extensions.Validation** – FluentValidation integration (`ValidationBehavior` + `AddInterlinkValidation()` with optional assembly scanning). -- **Interlink.AspNetCore** – `InterlinkExceptionFilter` (maps `HandlerNotFoundException` and optional FluentValidation exceptions to ProblemDetails) + `AddInterlinkAspNetCore()`. -- **Interlink.Analyzers** – Roslyn analyzer (`ILINK001`) that warns when an `IRequest` has no corresponding `IRequestHandler`. -- XML documentation comments on all public APIs. -### Fixed -- Pipeline behavior signature documentation now matches the actual `Handle(request, next, cancellationToken)` order. -- Removed dead / commented-out code in `ServiceCollectionExtensions`. -- Removed unused `HandlerResolver`. -- Consolidated type-scanning cache. -- Publisher now uses the same dynamic dispatch style as Sender (no reflection `Invoke`). -- `InterlinkOptions.AddBehavior` supports an optional explicit order parameter. -- Proper null checks and `ArgumentNullException` on public entry points. +- **Streaming requests** — `IStreamRequest`, `IStreamRequestHandler`, `ISender.CreateStream` / `IMediator.CreateStream` +- **Stream pipeline behaviors** — `IStreamPipelineBehavior`, `AddStreamBehavior` +- **Publish strategies** — `PublishStrategy.Sequential` (default) and `PublishStrategy.Parallel` +- **Notification pipeline behaviors** — `INotificationPipelineBehavior`, `AddNotificationBehavior` +- **Request timeout** — `InterlinkOptions.DefaultRequestTimeout` + built-in `TimeoutBehavior<,>` +- **ILINK002** analyzer — duplicate request handlers ### Changed -- Version bumped to 1.5.0. -- `Sender` and `Publisher` are now `sealed`. -- Pre-processors run before the pipeline; post-processors run after a successful pipeline. ---- - -## [1.4.0] - Previous - -### Changed -- Officially targets .NET Standard 2.0+ (improved multi-targeting and compatibility) - -### Fixed -- Minor packaging and target framework alignment issues +- `Publisher` supports publish strategies and notification pipelines +- Analyzer detects both `IRequestHandler` and `IRequestHandler` --- -## [1.3.1] - Previous - -### Changed -- Support .NET Standard 2.0+ (works in .NET Core, .NET 5+, .NET Framework 4.7.2+) - ---- - -## [1.3.0] — Performance & Customization +## [1.5.2] ### Added -- Handler resolution caching (delegate-based) -- Custom service factory injection support -- Pipeline ordering via attributes or configuration -- Assembly scanning filters by namespace or attribute ---- - -## [1.2.1] — Fix Critical Bugs - -### Fixed -- Critical bugs in `IPipelineBehavior` +- Unified **`IMediator`** interface (composes `ISender` + `IPublisher`) --- -## [1.2.0] — Pre/Post Processors +## [1.5.1] ### Added -- `IRequestPreProcessor` interface -- `IRequestPostProcessor` interface -- Pre and post hooks for request lifecycle -- Optional unit-of-work behaviors ---- +- **`Unit`** and non-generic **`IRequest`** / **`IRequestHandler`** for void-style commands +- **`ISender.Send(IRequest)`** convenience overload -## [1.1.0] — Notifications & Pipelines +### Fixed -### Added -- `INotification` and `INotificationHandler` -- `IPublisher` for event broadcasting -- `IPipelineBehavior` support -- Enhanced `AddInterlink()` with scanning and registration for notifications and pipelines -- Updated documentation and examples -- .NET 8+ support +- Analyzer packaging (`build/Interlink.Analyzers.props`) for reliable NuGet consumption --- -## [1.0.1] — Core Mediator Basics - -### Changed -- .NET 8+ support +## [1.5.0] ### Added -- Basic `IRequest` and `IRequestHandler` -- `ISender` for sending requests -- `AddInterlink()` for automatic DI registration -- Clean, lightweight design + +- `Interlink.Extensions.Logging` +- `Interlink.Extensions.Validation` (FluentValidation) +- `Interlink.AspNetCore` (exception filter → ProblemDetails) +- `Interlink.Analyzers` (**ILINK001** missing handler) +- `HandlerNotFoundException` +- Pipeline ordering via `PipelineOrderAttribute` / `AddBehavior(..., order)` --- -## [1.0.0] — Core Mediator Basics +## [1.4.x] and earlier -### Added -- Basic `IRequest` and `IRequestHandler` -- `ISender` for sending requests -- `AddInterlink()` for automatic DI registration -- Clean, lightweight design -- Only .NET 9 support \ No newline at end of file +- Core mediator: request/response, notifications, pipeline behaviors, pre/post processors, DI scanning diff --git a/Interlink-cqrs-library.sln b/Interlink-cqrs-library.sln index 166160e..71487f1 100644 --- a/Interlink-cqrs-library.sln +++ b/Interlink-cqrs-library.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 18 -VisualStudioVersion = 18.8.12023.21 stable +VisualStudioVersion = 18.8.12023.21 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Interlink", "src\Interlink\Interlink.csproj", "{7C8514FF-93EF-4044-BF83-56D9879EF68A}" EndProject @@ -23,6 +23,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Interlink.AspNetCore", "src EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Interlink.Analyzers", "src\Interlink.Analyzers\Interlink.Analyzers.csproj", "{B0809B2E-29E0-4190-B792-4EA7FB08A253}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Interlink.Extensions.Telemetry", "src\Interlink.Extensions.Telemetry\Interlink.Extensions.Telemetry.csproj", "{09B20002-CFB1-10AF-1C27-D32F01257280}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -57,6 +59,10 @@ Global {B0809B2E-29E0-4190-B792-4EA7FB08A253}.Debug|Any CPU.Build.0 = Debug|Any CPU {B0809B2E-29E0-4190-B792-4EA7FB08A253}.Release|Any CPU.ActiveCfg = Release|Any CPU {B0809B2E-29E0-4190-B792-4EA7FB08A253}.Release|Any CPU.Build.0 = Release|Any CPU + {09B20002-CFB1-10AF-1C27-D32F01257280}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {09B20002-CFB1-10AF-1C27-D32F01257280}.Debug|Any CPU.Build.0 = Debug|Any CPU + {09B20002-CFB1-10AF-1C27-D32F01257280}.Release|Any CPU.ActiveCfg = Release|Any CPU + {09B20002-CFB1-10AF-1C27-D32F01257280}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -69,6 +75,7 @@ Global {2343B677-D159-4E8F-86CD-48056172A8E8} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} {BB845504-4E55-494E-AD0F-277ED0CE170F} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} {B0809B2E-29E0-4190-B792-4EA7FB08A253} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {09B20002-CFB1-10AF-1C27-D32F01257280} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {F76D0B0E-B0AB-47F3-8546-94FFD16BC0AE} diff --git a/README.md b/README.md index 8c36edd..c411c3c 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,11 @@ ![NuGet Version](https://img.shields.io/nuget/v/Interlink.Extensions.Validation) ![NuGet Downloads](https://img.shields.io/nuget/dt/Interlink.Extensions.Validation) +![Static Badge](https://img.shields.io/badge/Interlink.Extensions.Telemetry-purple) +![NuGet Version](https://img.shields.io/nuget/v/Interlink.Extensions.Telemetry) +![NuGet Downloads](https://img.shields.io/nuget/dt/Interlink.Extensions.Telemetry) + + ![ChatGPT Image Apr 16, 2025, 12_32_44 AM (Custom)](https://github.com/user-attachments/assets/d7be3278-a115-47cf-b9e5-452a7d9a434d) --- @@ -45,10 +50,11 @@ * 🔍 Assembly scanning for automatic handler registration * 🧪 Custom service factory injection * 🔄 Pipeline ordering via attributes or configuration -* 🚨 Dedicated `HandlerNotFoundException` +* 🛡️ Notification exception strategies (`StopOnFirst` / `Aggregate` / `Continue`) +* 🧰 `INotificationExceptionHandler` for per-handler failure recovery (outbox-friendly) +* 🚨 Dedicated `HandlerNotFoundException` / `NotificationHandlerException` * ✅ Compatible with .NET Standard 2.0+ to .NET 10 -* 📦 Optional packages: Logging, FluentValidation, ASP.NET Core, Analyzer - +* 📦 Optional packages: Logging, FluentValidation, ASP.NET Core, Analyzer, **Telemetry** --- @@ -63,6 +69,7 @@ Optional packages: ```bash dotnet add package Interlink.Extensions.Logging dotnet add package Interlink.Extensions.Validation +dotnet add package Interlink.Extensions.Telemetry dotnet add package Interlink.AspNetCore dotnet add package Interlink.Analyzers ``` @@ -103,6 +110,7 @@ With the extension packages: builder.Services.AddInterlink(typeof(MyHandler).Assembly); builder.Services.AddInterlinkLogging(); builder.Services.AddInterlinkValidation(typeof(MyValidator).Assembly); +builder.Services.AddInterlinkTelemetry(); // Activity source "Interlink" builder.Services.AddInterlinkAspNetCore(); // registers exception filter ``` @@ -351,94 +359,6 @@ They are discovered automatically by `AddInterlink()`. --- ---- - -## 📡 Streaming requests (v1.6) - -```csharp -public sealed record ExportPetsStream : IStreamRequest; - -public sealed class ExportPetsStreamHandler : IStreamRequestHandler -{ - public async IAsyncEnumerable Handle( - ExportPetsStream request, - [EnumeratorCancellation] CancellationToken cancellationToken) - { - await foreach (var pet in _repository.StreamAllAsync(cancellationToken)) - yield return pet; - } -} - -// Consumer -await foreach (var pet in sender.CreateStream(new ExportPetsStream(), ct)) -{ - // process each item -} - -// or via IMediator -await foreach (var pet in mediator.CreateStream(new ExportPetsStream(), ct)) -{ - // ... -} -``` - -Register stream pipeline behaviors: - -```csharp -builder.Services.AddInterlink(options => -{ - options.AddStreamBehavior(typeof(MyStreamBehavior<,>)); -}, typeof(MyHandler).Assembly); -``` - -## ⚡ Notification publish strategies (v1.6) - -```csharp -builder.Services.AddInterlink(options => -{ - options.PublishStrategy = PublishStrategy.Parallel; // or Sequential (default) -}, typeof(MyHandler).Assembly); -``` - -- **Sequential** — handlers run one after another (ordering preserved). -- **Parallel** — handlers run concurrently via `Task.WhenAll`. - -## 🔔 Notification pipeline behaviors (v1.6) - -```csharp -public sealed class NotificationLoggingBehavior : INotificationPipelineBehavior - where TNotification : INotification -{ - public async Task Handle( - TNotification notification, - NotificationHandlerDelegate next, - CancellationToken cancellationToken) - { - // before - await next(cancellationToken); - // after - } -} - -builder.Services.AddInterlink(options => -{ - options.AddNotificationBehavior(typeof(NotificationLoggingBehavior<>)); -}); -``` - -## ⏱️ Request timeout (v1.6) - -```csharp -builder.Services.AddInterlink(options => -{ - options.DefaultRequestTimeout = TimeSpan.FromSeconds(30); -}, typeof(MyHandler).Assembly); -``` - -Registers `TimeoutBehavior<,>` automatically. Exceeding the timeout throws `TimeoutException`. - ---- - ## 📋 Built-in Logging Behavior ```bash @@ -507,16 +427,65 @@ The filter maps: --- -## 🔍 Analyzer (missing handler detection) +## 🔍 Analyzer (ILINK001 / ILINK002) ```bash dotnet add package Interlink.Analyzers +dotnet add package Interlink +``` + +| Id | Severity | Description | +|----|----------|-------------| +| **ILINK001** | Warning | Request has no matching handler | +| **ILINK002** | Warning | More than one handler for the same request type | + +These are compilation-end diagnostics — they show after **Build / Rebuild** (`dotnet build` or Error List **Build Only**). + +### ILINK001 — Missing request handler + +```csharp +using Interlink.Contracts; + +// Warning ILINK001: No handler found for request type 'GetAllPetsQuery' +public sealed record GetAllPetsQuery : IRequest>; +``` + +Clear it by adding a handler: + +```csharp +using Interlink; + +public sealed class GetAllPetsHandler : IRequestHandler> +{ + public Task> Handle(GetAllPetsQuery request, CancellationToken cancellationToken) + => Task.FromResult(new List { "Dog", "Cat" }); +} ``` -| Id | Meaning | -|----|---------| -| **ILINK001** | Request has no handler | -| **ILINK002** | Multiple handlers for the same request (v1.6) | +### ILINK002 — Duplicate request handler + +```csharp +using Interlink; +using Interlink.Contracts; + +public sealed record GetSomething : IRequest; + +public sealed class Handler1 : IRequestHandler +{ + public Task Handle(GetSomething request, CancellationToken cancellationToken) + => Unit.Task; +} + +// Warning ILINK002 on Handler1 and Handler2: +// Multiple handlers found for request type 'GetSomething' +public sealed class Handler2 : IRequestHandler +{ + public Task Handle(GetSomething request, CancellationToken cancellationToken) + => Unit.Task; +} +``` + +Keep **exactly one** handler per request type. --- @@ -611,25 +580,6 @@ public interface IRequestPostProcessor where TRequest } ``` -### Streaming requests -```csharp -public interface IStreamRequest { } - -public interface IStreamRequestHandler - where TRequest : IStreamRequest -{ - IAsyncEnumerable Handle(TRequest request, CancellationToken cancellationToken); -} -``` - -Register stream pipeline behaviors: -```csharp -builder.Services.AddInterlink(opt => -{ - opt.AddStreamBehavior(typeof(StreamLoggingBehavior<,>)); -}, typeof(MyHandler).Assembly); -``` - ### Exception ```csharp @@ -650,34 +600,181 @@ public class HandlerNotFoundException : InvalidOperationException | 1.4 | ✅ Released | .NET Standard 2.0+ | | 1.5 | ✅ Released | Logging, Validation, ASP.NET Core, Analyzer, exceptions, ordering fixes | | 1.5.1 | ✅ Released | `Unit` support for fire-and-forget / void commands (`IRequest` / `IRequest`) | -| 1.5.2 | ✅ Released | Added unified `IMediator` interface (composes `ISender` + `IPublisher`) | -| **1.6** | 🔄 Current | Streaming requests, notification publish strategies, notification pipeline behaviors, request timeout behavior | - +| 1.5.2 | ✅ Released | Unified `IMediator` (`ISender` + `IPublisher`) | +| 1.6.0 | ✅ Released | Streaming, publish strategies, notification pipelines, timeout, ILINK002 | +| **1.7.0** | ✅ Current | Notification exception strategies, exception handlers, Telemetry package | ### Future ideas -* Request cancellation -* Metrics & tracing support +* Request exception handlers (`IRequestExceptionHandler`) +* Constrained / filtered behaviors (command vs query vs stream) +* Minimal API helpers +* Source-generated handler registration (AOT-friendly) * Dynamic / externalized pipeline configuration --- -## 📜 License +## 📡 Streaming requests (v1.6) -MIT License © ManuHub +```csharp +public sealed record ExportPetsStream : IStreamRequest; ---- +public sealed class ExportPetsStreamHandler : IStreamRequestHandler +{ + public async IAsyncEnumerable Handle( + ExportPetsStream request, + [EnumeratorCancellation] CancellationToken cancellationToken) + { + await foreach (var pet in _repository.StreamAllAsync(cancellationToken)) + yield return pet; + } +} + +// Consumer +await foreach (var pet in sender.CreateStream(new ExportPetsStream(), ct)) +{ + // process each item +} +``` + +Register stream pipeline behaviors: + +```csharp +builder.Services.AddInterlink(options => +{ + options.AddStreamBehavior(typeof(MyStreamBehavior<,>)); +}, typeof(MyHandler).Assembly); +``` + +## ⚡ Notification publish strategies (v1.6) + +```csharp +builder.Services.AddInterlink(options => +{ + options.PublishStrategy = PublishStrategy.Parallel; // or Sequential (default) +}, typeof(MyHandler).Assembly); +``` + +- **Sequential** — handlers run one after another (ordering preserved). +- **Parallel** — handlers run concurrently via `Task.WhenAll`. + +## 🔔 Notification pipeline behaviors (v1.6) + +```csharp +public sealed class NotificationLoggingBehavior : INotificationPipelineBehavior + where TNotification : INotification +{ + public async Task Handle( + TNotification notification, + NotificationHandlerDelegate next, + CancellationToken cancellationToken) + { + // before + await next(cancellationToken); + // after + } +} + +builder.Services.AddInterlink(options => +{ + options.AddNotificationBehavior(typeof(NotificationLoggingBehavior<>)); +}); +``` + +## ⏱️ Request timeout (v1.6) + +```csharp +builder.Services.AddInterlink(options => +{ + options.DefaultRequestTimeout = TimeSpan.FromSeconds(30); +}, typeof(MyHandler).Assembly); +``` + +Registers `TimeoutBehavior<,>` automatically. Exceeding the timeout throws `TimeoutException`. + + +## 🛡️ Notification exception strategies (v1.7) + +When a notification handler throws, Interlink applies a configurable policy instead of leaving failure handling entirely to outbox workarounds. + +```csharp +builder.Services.AddInterlink(options => +{ + options.PublishStrategy = PublishStrategy.Parallel; + options.NotificationExceptionStrategy = NotificationExceptionStrategy.Aggregate; +}, typeof(MyHandler).Assembly); +``` -## 👨‍💻 Author +| Strategy | Behavior | +|----------|----------| +| **StopOnFirst** (default) | Stop and rethrow the first handler failure | +| **Aggregate** | Run all handlers; if any failed, throw `AggregateException` | +| **Continue** | Run all handlers; failures are dispatched to exception handlers and not rethrown | -**Manoj Babu**, -ManuHub +Failures are wrapped in `NotificationHandlerException` with `NotificationType` and `HandlerType` for diagnostics. -## 👥 Contributors +### Notification exception handlers (outbox-friendly) -Thanks to all contributors ❤️ +```csharp +public sealed class EmailFailedOutboxHandler + : INotificationExceptionHandler +{ + public Task Handle(UserCreated notification, Exception exception, CancellationToken ct) + { + // log, write dead-letter / outbox row, compensate... + return Task.CompletedTask; + } +} +``` + +Handlers are discovered by `AddInterlink` assembly scanning (same as notification handlers). - - - +They run **before** the chosen strategy rethrows or continues, so you can persist a failure even when using `StopOnFirst`. + +## 📊 Telemetry (v1.7) + +```bash +dotnet add package Interlink.Extensions.Telemetry +``` + +```csharp +builder.Services.AddInterlink(typeof(MyHandler).Assembly); +builder.Services.AddInterlinkTelemetry(); +``` +Subscribe to activity source **`Interlink`** in OpenTelemetry: + +```csharp +builder.Services.AddOpenTelemetry() + .WithTracing(t => t + .AddSource("Interlink") + .AddAspNetCoreInstrumentation() + .AddOtlpExporter()); +``` + +| Operation | Activity name | +|-----------|----------------| +| `Send` | `Interlink.Send {Request}` | +| `Publish` | `Interlink.Publish {Notification}` | +| `CreateStream` | `Interlink.CreateStream {Request}` | + +Failed operations set activity status to **Error** and add exception tags. + +## 📜 Changelog + +See [CHANGELOG.md](CHANGELOG.md) for the full history. Summary: + +### 1.7.0 +- Notification exception strategies + `INotificationExceptionHandler` + `NotificationHandlerException` +- `Interlink.Extensions.Telemetry` package + +### 1.6.0 +- Streaming requests, publish strategies, notification pipelines, timeout, ILINK002 + +### 1.5.x +- Unit/void commands, `IMediator`, Logging, Validation, AspNetCore, Analyzers (ILINK001) + + +## 📜 License + +MIT License © ManuHub diff --git a/src/Interlink.Analyzers/Interlink.Analyzers.csproj b/src/Interlink.Analyzers/Interlink.Analyzers.csproj index 7540cc5..3b71b65 100644 --- a/src/Interlink.Analyzers/Interlink.Analyzers.csproj +++ b/src/Interlink.Analyzers/Interlink.Analyzers.csproj @@ -9,7 +9,7 @@ Interlink.Analyzers Interlink.Analyzers Interlink.Analyzers - 1.6.0 + 1.7.0 Roslyn analyzer that detects requests without corresponding handlers for the Interlink mediator library. Copyright © 2025-2026 ManuHub Manojbabu diff --git a/src/Interlink.AspNetCore/Interlink.AspNetCore.csproj b/src/Interlink.AspNetCore/Interlink.AspNetCore.csproj index efdd603..26ae6c5 100644 --- a/src/Interlink.AspNetCore/Interlink.AspNetCore.csproj +++ b/src/Interlink.AspNetCore/Interlink.AspNetCore.csproj @@ -8,7 +8,7 @@ Interlink.AspNetCore Interlink.AspNetCore Interlink.AspNetCore - 1.6.0 + 1.7.0 ASP.NET Core integration for the Interlink mediator library (filters, exception handling, helpers). Copyright © 2025-2026 ManuHub Manojbabu diff --git a/src/Interlink.Extensions.Logging/Interlink.Extensions.Logging.csproj b/src/Interlink.Extensions.Logging/Interlink.Extensions.Logging.csproj index 8a573bb..06e4557 100644 --- a/src/Interlink.Extensions.Logging/Interlink.Extensions.Logging.csproj +++ b/src/Interlink.Extensions.Logging/Interlink.Extensions.Logging.csproj @@ -8,7 +8,7 @@ Interlink.Extensions.Logging Interlink.Extensions.Logging Interlink.Extensions.Logging - 1.6.0 + 1.7.0 Built-in logging pipeline behavior for the Interlink mediator library. Copyright © 2025-2026 ManuHub Manojbabu diff --git a/src/Interlink.Extensions.Telemetry/Interlink.Extensions.Telemetry.csproj b/src/Interlink.Extensions.Telemetry/Interlink.Extensions.Telemetry.csproj new file mode 100644 index 0000000..bbbc27a --- /dev/null +++ b/src/Interlink.Extensions.Telemetry/Interlink.Extensions.Telemetry.csproj @@ -0,0 +1,33 @@ + + + + netstandard2.0;net10.0 + enable + enable + latest + Interlink.Extensions.Telemetry + Interlink.Extensions.Telemetry + Interlink.Extensions.Telemetry + 1.7.0 + OpenTelemetry-style Activity instrumentation for Interlink mediator requests, streams, and notifications. + Manojbabu + interlink mediator telemetry opentelemetry activity diagnostics + true + README.md + true + + + + + + + + + + + + + + + + diff --git a/src/Interlink.Extensions.Telemetry/InterlinkActivitySource.cs b/src/Interlink.Extensions.Telemetry/InterlinkActivitySource.cs new file mode 100644 index 0000000..12bdd23 --- /dev/null +++ b/src/Interlink.Extensions.Telemetry/InterlinkActivitySource.cs @@ -0,0 +1,15 @@ +using System.Diagnostics; + +namespace Interlink.Extensions.Telemetry; + +/// +/// Shared for Interlink instrumentation. +/// +public static class InterlinkActivitySource +{ + /// Activity source name used in OpenTelemetry configuration. + public const string Name = "Interlink"; + + /// The activity source instance. + public static readonly ActivitySource Source = new(Name, "1.7.0"); +} diff --git a/src/Interlink.Extensions.Telemetry/NotificationTelemetryBehavior.cs b/src/Interlink.Extensions.Telemetry/NotificationTelemetryBehavior.cs new file mode 100644 index 0000000..101f148 --- /dev/null +++ b/src/Interlink.Extensions.Telemetry/NotificationTelemetryBehavior.cs @@ -0,0 +1,39 @@ +using System.Diagnostics; +using Interlink.Contracts; + +namespace Interlink.Extensions.Telemetry; + +/// +/// Notification pipeline behavior that creates an for each Publish. +/// +public sealed class NotificationTelemetryBehavior : INotificationPipelineBehavior + where TNotification : INotification +{ + /// + public async Task Handle( + TNotification notification, + NotificationHandlerDelegate next, + CancellationToken cancellationToken) + { + var name = typeof(TNotification).FullName ?? typeof(TNotification).Name; + using var activity = InterlinkActivitySource.Source.StartActivity( + $"Interlink.Publish {typeof(TNotification).Name}", + ActivityKind.Internal); + + activity?.SetTag("interlink.notification_type", name); + activity?.SetTag("interlink.operation", "publish"); + + try + { + await next(cancellationToken).ConfigureAwait(false); + activity?.SetStatus(ActivityStatusCode.Ok); + } + catch (Exception ex) + { + activity?.SetStatus(ActivityStatusCode.Error, ex.Message); + activity?.SetTag("exception.type", ex.GetType().FullName); + activity?.SetTag("exception.message", ex.Message); + throw; + } + } +} diff --git a/src/Interlink.Extensions.Telemetry/README.md b/src/Interlink.Extensions.Telemetry/README.md new file mode 100644 index 0000000..d4ebad1 --- /dev/null +++ b/src/Interlink.Extensions.Telemetry/README.md @@ -0,0 +1,44 @@ +![Static Badge](https://img.shields.io/badge/Interlink.Extensions.Telemetry-blue) +![NuGet Version](https://img.shields.io/nuget/v/Interlink.Extensions.Telemetry) +![NuGet Downloads](https://img.shields.io/nuget/dt/Interlink.Extensions.Telemetry) + +# Interlink.Extensions.Telemetry + +Activity-based instrumentation for [Interlink](https://www.nuget.org/packages/Interlink). + +## Install + +```bash +dotnet add package Interlink.Extensions.Telemetry +``` + +## Usage + +```csharp +builder.Services.AddInterlink(typeof(MyHandler).Assembly); +builder.Services.AddInterlinkTelemetry(); +``` + +Subscribe to the activity source name **`Interlink`** in OpenTelemetry: + +```csharp +builder.Services.AddOpenTelemetry() + .WithTracing(t => t + .AddSource(Interlink.Extensions.Telemetry.InterlinkActivitySource.Name) + .AddAspNetCoreInstrumentation() + .AddOtlpExporter()); +``` + +## Activities + +| Operation | Activity name pattern | Tags | +|-----------|----------------------|------| +| `Send` | `Interlink.Send {Request}` | `interlink.request_type`, `interlink.operation` | +| `Publish` | `Interlink.Publish {Notification}` | `interlink.notification_type`, `interlink.operation` | +| `CreateStream` | `Interlink.CreateStream {Request}` | `interlink.request_type`, `interlink.stream_items` | + +Failed operations set activity status to **Error** and add exception tags. + +## License + +MIT © ManuHub diff --git a/src/Interlink.Extensions.Telemetry/ServiceCollectionExtensions.cs b/src/Interlink.Extensions.Telemetry/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..897d2d6 --- /dev/null +++ b/src/Interlink.Extensions.Telemetry/ServiceCollectionExtensions.cs @@ -0,0 +1,26 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace Interlink.Extensions.Telemetry; + +/// +/// Extension methods for registering Interlink telemetry behaviors. +/// +public static class ServiceCollectionExtensions +{ + /// + /// Registers request, notification, and stream telemetry pipeline behaviors. + /// Configure OpenTelemetry (or another listener) to subscribe to activity source + /// Interlink (). + /// + public static IServiceCollection AddInterlinkTelemetry(this IServiceCollection services) + { + if (services is null) + throw new ArgumentNullException(nameof(services)); + + services.AddScoped(typeof(IPipelineBehavior<,>), typeof(TelemetryBehavior<,>)); + services.AddScoped(typeof(INotificationPipelineBehavior<>), typeof(NotificationTelemetryBehavior<>)); + services.AddScoped(typeof(IStreamPipelineBehavior<,>), typeof(StreamTelemetryBehavior<,>)); + + return services; + } +} diff --git a/src/Interlink.Extensions.Telemetry/StreamTelemetryBehavior.cs b/src/Interlink.Extensions.Telemetry/StreamTelemetryBehavior.cs new file mode 100644 index 0000000..7bd2d10 --- /dev/null +++ b/src/Interlink.Extensions.Telemetry/StreamTelemetryBehavior.cs @@ -0,0 +1,48 @@ +using System.Diagnostics; +using System.Runtime.CompilerServices; +using Interlink.Contracts; + +namespace Interlink.Extensions.Telemetry; + +/// +/// Stream pipeline behavior that creates an for each CreateStream. +/// +public sealed class StreamTelemetryBehavior : IStreamPipelineBehavior + where TRequest : IStreamRequest +{ + /// + public async IAsyncEnumerable Handle( + TRequest request, + StreamHandlerDelegate next, + [EnumeratorCancellation] CancellationToken cancellationToken) + { + var requestName = typeof(TRequest).FullName ?? typeof(TRequest).Name; + using var activity = InterlinkActivitySource.Source.StartActivity( + $"Interlink.CreateStream {typeof(TRequest).Name}", + ActivityKind.Internal); + + activity?.SetTag("interlink.request_type", requestName); + activity?.SetTag("interlink.operation", "create_stream"); + + var count = 0; + Exception? error = null; + try + { + await foreach (var item in next().WithCancellation(cancellationToken)) + { + count++; + yield return item; + } + + activity?.SetStatus(ActivityStatusCode.Ok); + } + finally + { + activity?.SetTag("interlink.stream_items", count); + if (error is not null) + { + activity?.SetStatus(ActivityStatusCode.Error, error.Message); + } + } + } +} diff --git a/src/Interlink.Extensions.Telemetry/TelemetryBehavior.cs b/src/Interlink.Extensions.Telemetry/TelemetryBehavior.cs new file mode 100644 index 0000000..2e3132c --- /dev/null +++ b/src/Interlink.Extensions.Telemetry/TelemetryBehavior.cs @@ -0,0 +1,39 @@ +using System.Diagnostics; + +namespace Interlink.Extensions.Telemetry; + +/// +/// Request pipeline behavior that creates an for each Send. +/// +public sealed class TelemetryBehavior : IPipelineBehavior + where TRequest : notnull +{ + /// + public async Task Handle( + TRequest request, + RequestHandlerDelegate next, + CancellationToken cancellationToken) + { + var requestName = typeof(TRequest).FullName ?? typeof(TRequest).Name; + using var activity = InterlinkActivitySource.Source.StartActivity( + $"Interlink.Send {typeof(TRequest).Name}", + ActivityKind.Internal); + + activity?.SetTag("interlink.request_type", requestName); + activity?.SetTag("interlink.operation", "send"); + + try + { + var response = await next(cancellationToken).ConfigureAwait(false); + activity?.SetStatus(ActivityStatusCode.Ok); + return response; + } + catch (Exception ex) + { + activity?.SetStatus(ActivityStatusCode.Error, ex.Message); + activity?.SetTag("exception.type", ex.GetType().FullName); + activity?.SetTag("exception.message", ex.Message); + throw; + } + } +} diff --git a/src/Interlink.Extensions.Validation/Interlink.Extensions.Validation.csproj b/src/Interlink.Extensions.Validation/Interlink.Extensions.Validation.csproj index da63fc4..f48f92e 100644 --- a/src/Interlink.Extensions.Validation/Interlink.Extensions.Validation.csproj +++ b/src/Interlink.Extensions.Validation/Interlink.Extensions.Validation.csproj @@ -8,7 +8,7 @@ Interlink.Extensions.Validation Interlink.Extensions.Validation Interlink.Extensions.Validation - 1.6.0 + 1.7.0 FluentValidation integration for the Interlink mediator library. Copyright © 2025-2026 ManuHub Manojbabu diff --git a/src/Interlink/Abstractions/INotificationExceptionHandler.cs b/src/Interlink/Abstractions/INotificationExceptionHandler.cs new file mode 100644 index 0000000..8411c65 --- /dev/null +++ b/src/Interlink/Abstractions/INotificationExceptionHandler.cs @@ -0,0 +1,22 @@ +using Interlink.Contracts; + +namespace Interlink; + +/// +/// Handles an exception thrown by a notification handler for . +/// Use this to log, write an outbox/failure record, or compensate without failing the whole publish. +/// +/// The notification type. +/// The exception type this handler deals with. +public interface INotificationExceptionHandler + where TNotification : INotification + where TException : Exception +{ + /// + /// Called when a notification handler throws . + /// + /// The notification being published. + /// The exception thrown by a handler. + /// Cancellation token. + Task Handle(TNotification notification, TException exception, CancellationToken cancellationToken); +} diff --git a/src/Interlink/Configurations/InterlinkOptions.cs b/src/Interlink/Configurations/InterlinkOptions.cs index 7ba391a..457c0d3 100644 --- a/src/Interlink/Configurations/InterlinkOptions.cs +++ b/src/Interlink/Configurations/InterlinkOptions.cs @@ -23,6 +23,13 @@ public class InterlinkOptions /// public PublishStrategy PublishStrategy { get; set; } = PublishStrategy.Sequential; + /// + /// Gets or sets how exceptions from notification handlers are handled. + /// Default is . + /// + public NotificationExceptionStrategy NotificationExceptionStrategy { get; set; } + = NotificationExceptionStrategy.StopOnFirst; + /// /// Gets or sets an optional default timeout applied to all requests via /// . @@ -117,3 +124,4 @@ public void AddStreamBehavior(int? order = null) AddStreamBehavior(typeof(TBehavior), order); } } + diff --git a/src/Interlink/Core/Publisher.cs b/src/Interlink/Core/Publisher.cs index aa3f779..0127e46 100644 --- a/src/Interlink/Core/Publisher.cs +++ b/src/Interlink/Core/Publisher.cs @@ -5,22 +5,22 @@ namespace Interlink; /// /// Default implementation of that resolves notification handlers, -/// runs notification pipeline behaviors, and invokes handlers using the configured -/// . +/// runs notification pipeline behaviors, invokes handlers using the configured +/// , and applies . /// internal sealed class Publisher : IPublisher { private readonly IServiceProvider _provider; private readonly Func _serviceFactory; private readonly PublishStrategy _publishStrategy; + private readonly NotificationExceptionStrategy _exceptionStrategy; /// /// Initializes a new instance of the class. /// - public Publisher( - IServiceProvider provider, - InterlinkOptions options, - Func? customFactory = null) + public Publisher(IServiceProvider provider, + InterlinkOptions options, + Func? customFactory = null) { _provider = provider ?? throw new ArgumentNullException(nameof(provider)); if (options is null) @@ -28,6 +28,7 @@ public Publisher( _serviceFactory = customFactory ?? (type => _provider.GetService(type)); _publishStrategy = options.PublishStrategy; + _exceptionStrategy = options.NotificationExceptionStrategy; } /// @@ -44,10 +45,9 @@ public async Task Publish(TNotification notification, Cancellatio var handlers = (_serviceFactory(enumerableType) as IEnumerable)?.ToList() ?? new List(); - // Innermost: invoke all handlers according to strategy - NotificationHandlerDelegate pipeline = token => InvokeHandlersAsync(handlers, notification, token); + NotificationHandlerDelegate pipeline = token => + InvokeHandlersAsync(handlers, notification, notificationType, token); - // Notification pipeline behaviors (ordered, outermost first) var behaviorType = typeof(INotificationPipelineBehavior<>).MakeGenericType(notificationType); var behaviors = ResolveEnumerable(behaviorType) .Select(b => (Instance: b, Order: GetOrder(b.GetType()))) @@ -65,33 +65,140 @@ public async Task Publish(TNotification notification, Cancellatio await pipeline(cancellationToken).ConfigureAwait(false); } - private async Task InvokeHandlersAsync( - List handlers, - object notification, - CancellationToken cancellationToken) + private async Task InvokeHandlersAsync(List handlers, + object notification, + Type notificationType, + CancellationToken cancellationToken) { if (handlers.Count == 0) return; if (_publishStrategy == PublishStrategy.Parallel) + await InvokeParallelAsync(handlers, notification, notificationType, cancellationToken).ConfigureAwait(false); + else + await InvokeSequentialAsync(handlers, notification, notificationType, cancellationToken).ConfigureAwait(false); + } + + private async Task InvokeSequentialAsync(List handlers, + object notification, + Type notificationType, + CancellationToken cancellationToken) + { + var failures = new List(); + + foreach (var handler in handlers) { - var tasks = new Task[handlers.Count]; - for (var i = 0; i < handlers.Count; i++) + try { - dynamic handler = handlers[i]; - tasks[i] = handler.Handle((dynamic)notification, cancellationToken); + await ((dynamic)handler).Handle((dynamic)notification, cancellationToken).ConfigureAwait(false); } + catch (Exception ex) when (ex is not OperationCanceledException || cancellationToken.IsCancellationRequested) + { + if (ex is OperationCanceledException && cancellationToken.IsCancellationRequested) + throw; + + var wrapped = Wrap(notificationType, handler.GetType(), ex); + await DispatchExceptionHandlersAsync(notification, wrapped, cancellationToken).ConfigureAwait(false); + + switch (_exceptionStrategy) + { + case NotificationExceptionStrategy.StopOnFirst: + throw wrapped; + case NotificationExceptionStrategy.Aggregate: + case NotificationExceptionStrategy.Continue: + failures.Add(wrapped); + break; + } + } + } - await Task.WhenAll(tasks).ConfigureAwait(false); + ThrowIfAggregated(failures); + } + + private async Task InvokeParallelAsync(List handlers, + object notification, + Type notificationType, + CancellationToken cancellationToken) + { + var tasks = handlers.Select(async handler => + { + try + { + await ((dynamic)handler).Handle((dynamic)notification, cancellationToken).ConfigureAwait(false); + return (Exception?)null; + } + catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + if (ex is OperationCanceledException && cancellationToken.IsCancellationRequested) + throw; + + var wrapped = Wrap(notificationType, handler.GetType(), ex); + await DispatchExceptionHandlersAsync(notification, wrapped, cancellationToken).ConfigureAwait(false); + return wrapped; + } + }).ToArray(); + + var results = await Task.WhenAll(tasks).ConfigureAwait(false); + var failures = results.Where(e => e is not null).Cast().ToList(); + + if (failures.Count == 0) return; - } - // Sequential (default) - foreach (var handler in handlers) + if (_exceptionStrategy == NotificationExceptionStrategy.StopOnFirst) + throw failures[0]; + + if (_exceptionStrategy == NotificationExceptionStrategy.Aggregate) + throw new AggregateException("One or more notification handlers failed.", failures); + + // Continue: already dispatched to exception handlers; do not rethrow + } + + private void ThrowIfAggregated(List failures) + { + if (failures.Count == 0) + return; + + if (_exceptionStrategy == NotificationExceptionStrategy.Aggregate) + throw new AggregateException("One or more notification handlers failed.", failures); + + // Continue: swallow after exception handlers ran + } + + private static NotificationHandlerException Wrap(Type notificationType, Type handlerType, Exception ex) + => ex is NotificationHandlerException nhe + ? nhe + : new NotificationHandlerException(notificationType, handlerType, ex); + + private async Task DispatchExceptionHandlersAsync(object notification, + NotificationHandlerException exception, + CancellationToken cancellationToken) + { + var notificationType = exception.NotificationType; + var inner = exception.InnerException ?? exception; + + // Resolve INotificationExceptionHandler for the concrete exception type + // and walk the exception inheritance chain so handlers for Exception also match. + var exceptionType = inner.GetType(); + while (true) { - await ((dynamic)handler).Handle((dynamic)notification, cancellationToken).ConfigureAwait(false); + var handlerInterface = typeof(INotificationExceptionHandler<,>) + .MakeGenericType(notificationType, exceptionType); + + var enumerableType = typeof(IEnumerable<>).MakeGenericType(handlerInterface); + var handlers = _serviceFactory(enumerableType) as IEnumerable ?? Array.Empty(); + + foreach (var handler in handlers) + { + await ((dynamic)handler).Handle((dynamic)notification, (dynamic)inner, cancellationToken) + .ConfigureAwait(false); + } + + if (exceptionType == typeof(Exception)) + break; + + exceptionType = exceptionType.BaseType ?? typeof(Exception); } - } + } private IEnumerable ResolveEnumerable(Type elementType) { diff --git a/src/Interlink/Exceptions/NotificationExceptionStrategy.cs b/src/Interlink/Exceptions/NotificationExceptionStrategy.cs new file mode 100644 index 0000000..dfa2780 --- /dev/null +++ b/src/Interlink/Exceptions/NotificationExceptionStrategy.cs @@ -0,0 +1,28 @@ +namespace Interlink; + +/// +/// Controls how exceptions thrown by notification handlers are treated during . +/// +public enum NotificationExceptionStrategy +{ + /// + /// Stop at the first handler failure and rethrow that exception. + /// Remaining handlers are not invoked (sequential) or may still be in-flight (parallel). + /// This is the default. + /// + StopOnFirst = 0, + + /// + /// Invoke every handler. If one or more fail, throw a single + /// after all handlers have completed. + /// + Aggregate = 1, + + /// + /// Invoke every handler. Failures are passed to any registered + /// instances. + /// If no exception handler handles the error, the exception is swallowed + /// (use with care — prefer Aggregate or explicit exception handlers). + /// + Continue = 2 +} diff --git a/src/Interlink/Exceptions/NotificationHandlerException.cs b/src/Interlink/Exceptions/NotificationHandlerException.cs new file mode 100644 index 0000000..75fadaa --- /dev/null +++ b/src/Interlink/Exceptions/NotificationHandlerException.cs @@ -0,0 +1,26 @@ +namespace Interlink; + +/// +/// Wraps an exception thrown by a single notification handler, including +/// the notification and handler types for diagnostics and outbox-style recovery. +/// +public sealed class NotificationHandlerException : Exception +{ + /// + /// Initializes a new instance of the class. + /// + public NotificationHandlerException(Type notificationType, Type handlerType, Exception innerException) + : base( + $"Notification handler '{handlerType.FullName}' failed while handling '{notificationType.FullName}'.", + innerException) + { + NotificationType = notificationType ?? throw new ArgumentNullException(nameof(notificationType)); + HandlerType = handlerType ?? throw new ArgumentNullException(nameof(handlerType)); + } + + /// The notification type that was being published. + public Type NotificationType { get; } + + /// The handler type that threw. + public Type HandlerType { get; } +} diff --git a/src/Interlink/Interlink.csproj b/src/Interlink/Interlink.csproj index f294659..e24a019 100644 --- a/src/Interlink/Interlink.csproj +++ b/src/Interlink/Interlink.csproj @@ -10,7 +10,7 @@ Interlink Interlink Interlink - 1.6.0 + 1.7.0 A lightweight and minimal mediator library for .NET. Interlink helps you decouple your application using request/response and notification patterns with simple, clean code. Copyright © 2025-2026 ManuHub Manojbabu diff --git a/src/Interlink/README.md b/src/Interlink/README.md index bbb73f1..529c5cf 100644 --- a/src/Interlink/README.md +++ b/src/Interlink/README.md @@ -25,9 +25,11 @@ * 🔍 Assembly scanning for automatic handler registration * 🧪 Custom service factory injection * 🔄 Pipeline ordering via attributes or configuration -* 🚨 Dedicated `HandlerNotFoundException` +* 🛡️ Notification exception strategies (`StopOnFirst` / `Aggregate` / `Continue`) +* 🧰 `INotificationExceptionHandler` for per-handler failure recovery (outbox-friendly) +* 🚨 Dedicated `HandlerNotFoundException` / `NotificationHandlerException` * ✅ Compatible with .NET Standard 2.0+ to .NET 10 -* 📦 Optional packages: Logging, FluentValidation, ASP.NET Core, Analyzer +* 📦 Optional packages: Logging, FluentValidation, ASP.NET Core, Analyzer, **Telemetry** --- @@ -42,6 +44,7 @@ Optional packages: ```bash dotnet add package Interlink.Extensions.Logging dotnet add package Interlink.Extensions.Validation +dotnet add package Interlink.Extensions.Telemetry dotnet add package Interlink.AspNetCore dotnet add package Interlink.Analyzers ``` @@ -82,7 +85,8 @@ With the extension packages: builder.Services.AddInterlink(typeof(MyHandler).Assembly); builder.Services.AddInterlinkLogging(); builder.Services.AddInterlinkValidation(typeof(MyValidator).Assembly); -builder.Services.AddInterlinkAspNetCore(); // registers exception filter +builder.Services.AddInterlinkTelemetry(); // Activity source "Interlink" +builder.Services.AddInterlinkAspNetCore(); // registers exception filter ``` --- @@ -330,92 +334,6 @@ They are discovered automatically by `AddInterlink()`. --- -## 📡 Streaming requests (v1.6) - -```csharp -public sealed record ExportPetsStream : IStreamRequest; - -public sealed class ExportPetsStreamHandler : IStreamRequestHandler -{ - public async IAsyncEnumerable Handle( - ExportPetsStream request, - [EnumeratorCancellation] CancellationToken cancellationToken) - { - await foreach (var pet in _repository.StreamAllAsync(cancellationToken)) - yield return pet; - } -} - -// Consumer -await foreach (var pet in sender.CreateStream(new ExportPetsStream(), ct)) -{ - // process each item -} - -// or via IMediator -await foreach (var pet in mediator.CreateStream(new ExportPetsStream(), ct)) -{ - // ... -} -``` - -Register stream pipeline behaviors: - -```csharp -builder.Services.AddInterlink(options => -{ - options.AddStreamBehavior(typeof(MyStreamBehavior<,>)); -}, typeof(MyHandler).Assembly); -``` - -## ⚡ Notification publish strategies (v1.6) - -```csharp -builder.Services.AddInterlink(options => -{ - options.PublishStrategy = PublishStrategy.Parallel; // or Sequential (default) -}, typeof(MyHandler).Assembly); -``` - -- **Sequential** — handlers run one after another (ordering preserved). -- **Parallel** — handlers run concurrently via `Task.WhenAll`. - -## 🔔 Notification pipeline behaviors (v1.6) - -```csharp -public sealed class NotificationLoggingBehavior : INotificationPipelineBehavior - where TNotification : INotification -{ - public async Task Handle( - TNotification notification, - NotificationHandlerDelegate next, - CancellationToken cancellationToken) - { - // before - await next(cancellationToken); - // after - } -} - -builder.Services.AddInterlink(options => -{ - options.AddNotificationBehavior(typeof(NotificationLoggingBehavior<>)); -}); -``` - -## ⏱️ Request timeout (v1.6) - -```csharp -builder.Services.AddInterlink(options => -{ - options.DefaultRequestTimeout = TimeSpan.FromSeconds(30); -}, typeof(MyHandler).Assembly); -``` - -Registers `TimeoutBehavior<,>` automatically. Exceeding the timeout throws `TimeoutException`. - ---- - ## 📋 Built-in Logging Behavior ```bash @@ -428,9 +346,9 @@ builder.Services.AddInterlinkLogging(); This registers `LoggingBehavior`, which logs: -- request start -- successful completion + elapsed milliseconds -- exceptions +- request start +- successful completion + elapsed milliseconds +- exceptions --- @@ -484,16 +402,65 @@ The filter maps: --- -## 🔍 Analyzer (missing handler detection) +## 🔍 Analyzer (ILINK001 / ILINK002) ```bash dotnet add package Interlink.Analyzers +dotnet add package Interlink +``` + +| Id | Severity | Description | +|----|----------|-------------| +| **ILINK001** | Warning | Request has no matching handler | +| **ILINK002** | Warning | More than one handler for the same request type | + +These are compilation-end diagnostics — they show after **Build / Rebuild** (`dotnet build` or Error List **Build Only**). + +### ILINK001 — Missing request handler + +```csharp +using Interlink.Contracts; + +// Warning ILINK001: No handler found for request type 'GetAllPetsQuery' +public sealed record GetAllPetsQuery : IRequest>; +``` + +Clear it by adding a handler: + +```csharp +using Interlink; + +public sealed class GetAllPetsHandler : IRequestHandler> +{ + public Task> Handle(GetAllPetsQuery request, CancellationToken cancellationToken) + => Task.FromResult(new List { "Dog", "Cat" }); +} +``` + +### ILINK002 — Duplicate request handler + +```csharp +using Interlink; +using Interlink.Contracts; + +public sealed record GetSomething : IRequest; + +public sealed class Handler1 : IRequestHandler +{ + public Task Handle(GetSomething request, CancellationToken cancellationToken) + => Unit.Task; +} + +// Warning ILINK002 on Handler1 and Handler2: +// Multiple handlers found for request type 'GetSomething' +public sealed class Handler2 : IRequestHandler +{ + public Task Handle(GetSomething request, CancellationToken cancellationToken) + => Unit.Task; +} ``` -| Id | Meaning | -|----|---------| -| **ILINK001** | Request has no handler | -| **ILINK002** | Multiple handlers for the same request (v1.6) | +Keep **exactly one** handler per request type. --- @@ -588,25 +555,6 @@ public interface IRequestPostProcessor where TRequest } ``` -### Streaming requests -```csharp -public interface IStreamRequest { } - -public interface IStreamRequestHandler - where TRequest : IStreamRequest -{ - IAsyncEnumerable Handle(TRequest request, CancellationToken cancellationToken); -} -``` - -Register stream pipeline behaviors: -```csharp -builder.Services.AddInterlink(opt => -{ - opt.AddStreamBehavior(typeof(StreamLoggingBehavior<,>)); -}, typeof(MyHandler).Assembly); -``` - ### Exception ```csharp @@ -627,18 +575,167 @@ public class HandlerNotFoundException : InvalidOperationException | 1.4 | ✅ Released | .NET Standard 2.0+ | | 1.5 | ✅ Released | Logging, Validation, ASP.NET Core, Analyzer, exceptions, ordering fixes | | 1.5.1 | ✅ Released | `Unit` support for fire-and-forget / void commands (`IRequest` / `IRequest`) | -| 1.5.2 | ✅ Released | Added unified `IMediator` interface (composes `ISender` + `IPublisher`) | -| **1.6** | 🔄 Current | Streaming requests, notification publish strategies, notification pipeline behaviors, request timeout behavior | - +| 1.5.2 | ✅ Released | Unified `IMediator` (`ISender` + `IPublisher`) | +| 1.6.0 | ✅ Released | Streaming, publish strategies, notification pipelines, timeout, ILINK002 | +| **1.7.0** | ✅ Current | Notification exception strategies, exception handlers, Telemetry package | ### Future ideas -* Request cancellation -* Metrics & tracing support +* Request exception handlers (`IRequestExceptionHandler`) +* Constrained / filtered behaviors (command vs query vs stream) +* Minimal API helpers +* Source-generated handler registration (AOT-friendly) * Dynamic / externalized pipeline configuration --- +## 📡 Streaming requests (v1.6) + +```csharp +public sealed record ExportPetsStream : IStreamRequest; + +public sealed class ExportPetsStreamHandler : IStreamRequestHandler +{ + public async IAsyncEnumerable Handle( + ExportPetsStream request, + [EnumeratorCancellation] CancellationToken cancellationToken) + { + await foreach (var pet in _repository.StreamAllAsync(cancellationToken)) + yield return pet; + } +} + +// Consumer +await foreach (var pet in sender.CreateStream(new ExportPetsStream(), ct)) +{ + // process each item +} +``` + +Register stream pipeline behaviors: + +```csharp +builder.Services.AddInterlink(options => +{ + options.AddStreamBehavior(typeof(MyStreamBehavior<,>)); +}, typeof(MyHandler).Assembly); +``` + +## ⚡ Notification publish strategies (v1.6) + +```csharp +builder.Services.AddInterlink(options => +{ + options.PublishStrategy = PublishStrategy.Parallel; // or Sequential (default) +}, typeof(MyHandler).Assembly); +``` + +- **Sequential** — handlers run one after another (ordering preserved). +- **Parallel** — handlers run concurrently via `Task.WhenAll`. + +## 🔔 Notification pipeline behaviors (v1.6) + +```csharp +public sealed class NotificationLoggingBehavior : INotificationPipelineBehavior + where TNotification : INotification +{ + public async Task Handle( + TNotification notification, + NotificationHandlerDelegate next, + CancellationToken cancellationToken) + { + // before + await next(cancellationToken); + // after + } +} + +builder.Services.AddInterlink(options => +{ + options.AddNotificationBehavior(typeof(NotificationLoggingBehavior<>)); +}); +``` + +## ⏱️ Request timeout (v1.6) + +```csharp +builder.Services.AddInterlink(options => +{ + options.DefaultRequestTimeout = TimeSpan.FromSeconds(30); +}, typeof(MyHandler).Assembly); +``` + +Registers `TimeoutBehavior<,>` automatically. Exceeding the timeout throws `TimeoutException`. + + +## 🛡️ Notification exception strategies (v1.7) + +When a notification handler throws, Interlink applies a configurable policy instead of leaving failure handling entirely to outbox workarounds. + +```csharp +builder.Services.AddInterlink(options => +{ + options.PublishStrategy = PublishStrategy.Parallel; + options.NotificationExceptionStrategy = NotificationExceptionStrategy.Aggregate; +}, typeof(MyHandler).Assembly); +``` + +| Strategy | Behavior | +|----------|----------| +| **StopOnFirst** (default) | Stop and rethrow the first handler failure | +| **Aggregate** | Run all handlers; if any failed, throw `AggregateException` | +| **Continue** | Run all handlers; failures are dispatched to exception handlers and not rethrown | + +Failures are wrapped in `NotificationHandlerException` with `NotificationType` and `HandlerType` for diagnostics. + +### Notification exception handlers (outbox-friendly) + +```csharp +public sealed class EmailFailedOutboxHandler + : INotificationExceptionHandler +{ + public Task Handle(UserCreated notification, Exception exception, CancellationToken ct) + { + // log, write dead-letter / outbox row, compensate... + return Task.CompletedTask; + } +} +``` + +Handlers are discovered by `AddInterlink` assembly scanning (same as notification handlers). + +They run **before** the chosen strategy rethrows or continues, so you can persist a failure even when using `StopOnFirst`. + +## 📊 Telemetry (v1.7) + +```bash +dotnet add package Interlink.Extensions.Telemetry +``` + +```csharp +builder.Services.AddInterlink(typeof(MyHandler).Assembly); +builder.Services.AddInterlinkTelemetry(); +``` + +Subscribe to activity source **`Interlink`** in OpenTelemetry: + +```csharp +builder.Services.AddOpenTelemetry() + .WithTracing(t => t + .AddSource("Interlink") + .AddAspNetCoreInstrumentation() + .AddOtlpExporter()); +``` + +| Operation | Activity name | +|-----------|----------------| +| `Send` | `Interlink.Send {Request}` | +| `Publish` | `Interlink.Publish {Notification}` | +| `CreateStream` | `Interlink.CreateStream {Request}` | + +Failed operations set activity status to **Error** and add exception tags. + + ## 📜 License MIT License © ManuHub \ No newline at end of file diff --git a/src/Interlink/ServiceCollectionExtensions.cs b/src/Interlink/ServiceCollectionExtensions.cs index e38112a..c53d53e 100644 --- a/src/Interlink/ServiceCollectionExtensions.cs +++ b/src/Interlink/ServiceCollectionExtensions.cs @@ -22,10 +22,9 @@ public static class ServiceCollectionExtensions /// When omitted, the calling assembly is scanned. /// /// The same instance so that calls can be chained. - public static IServiceCollection AddInterlink( - this IServiceCollection services, - Action? configure = null, - params Assembly[] assemblies) + public static IServiceCollection AddInterlink(this IServiceCollection services, + Action? configure = null, + params Assembly[] assemblies) { if (services is null) throw new ArgumentNullException(nameof(services)); @@ -68,6 +67,7 @@ public static IServiceCollection AddInterlink( { RegisterClosedGenericImplementations(services, assembly, typeof(IRequestHandler<,>)); RegisterClosedGenericImplementations(services, assembly, typeof(INotificationHandler<>)); + RegisterClosedGenericImplementations(services, assembly, typeof(INotificationExceptionHandler<,>)); RegisterClosedGenericImplementations(services, assembly, typeof(IRequestPreProcessor<>)); RegisterClosedGenericImplementations(services, assembly, typeof(IRequestPostProcessor<,>)); RegisterClosedGenericImplementations(services, assembly, typeof(INotificationPipelineBehavior<>)); @@ -93,10 +93,9 @@ public static IServiceCollection AddInterlink( return services; } - private static void RegisterClosedGenericImplementations( - IServiceCollection services, - Assembly assembly, - Type openGenericType) + private static void RegisterClosedGenericImplementations(IServiceCollection services, + Assembly assembly, + Type openGenericType) { foreach (var (serviceType, implementationType) in TypeScanner.Scan(assembly, openGenericType)) { diff --git a/test/Interlink.Test/NotificationExceptionStrategyTests.cs b/test/Interlink.Test/NotificationExceptionStrategyTests.cs new file mode 100644 index 0000000..3a8e617 --- /dev/null +++ b/test/Interlink.Test/NotificationExceptionStrategyTests.cs @@ -0,0 +1,328 @@ +namespace Interlink.Test; + +/// +/// Tests for and +/// . +/// Each scenario uses its own notification type so assembly scanning does not +/// cross-register handlers across tests. +/// +public class NotificationExceptionStrategyTests +{ + [Fact] + public async Task StopOnFirst_Throws_NotificationHandlerException() + { + var services = new ServiceCollection(); + services.AddSingleton(new StopOnFirstProbe()); + services.AddInterlink(options => + { + options.PublishStrategy = PublishStrategy.Sequential; + options.NotificationExceptionStrategy = NotificationExceptionStrategy.StopOnFirst; + }, typeof(NotificationExceptionStrategyTests).Assembly); + + await using var provider = services.BuildServiceProvider(); + var publisher = provider.GetRequiredService(); + + var ex = await Assert.ThrowsAsync( + () => publisher.Publish(new StopOnFirstNotification())); + + Assert.Equal(typeof(StopOnFirstNotification), ex.NotificationType); + Assert.Equal(typeof(StopOnFirst_ThrowingHandler), ex.HandlerType); + Assert.Contains("stop-boom", ex.InnerException!.Message); + Assert.IsNotType(ex); + } + + [Fact] + public async Task Aggregate_RunsAllHandlers_ThenThrowsAggregateException() + { + var services = new ServiceCollection(); + services.AddSingleton(new AggregateProbe()); + services.AddInterlink(options => + { + options.PublishStrategy = PublishStrategy.Sequential; + options.NotificationExceptionStrategy = NotificationExceptionStrategy.Aggregate; + }, typeof(NotificationExceptionStrategyTests).Assembly); + + await using var provider = services.BuildServiceProvider(); + var publisher = provider.GetRequiredService(); + var probe = provider.GetRequiredService(); + + var ex = await Assert.ThrowsAsync( + () => publisher.Publish(new AggregateNotification())); + + Assert.Equal(2, ex.InnerExceptions.Count); + Assert.All(ex.InnerExceptions, e => Assert.IsType(e)); + Assert.Equal(1, probe.SuccessCount); + Assert.Equal(2, probe.ThrowCount); + } + + [Fact] + public async Task Continue_RunsAllHandlers_DoesNotThrow() + { + var services = new ServiceCollection(); + services.AddSingleton(new ContinueProbe()); + services.AddInterlink(options => + { + options.PublishStrategy = PublishStrategy.Sequential; + options.NotificationExceptionStrategy = NotificationExceptionStrategy.Continue; + }, typeof(NotificationExceptionStrategyTests).Assembly); + + await using var provider = services.BuildServiceProvider(); + var publisher = provider.GetRequiredService(); + var probe = provider.GetRequiredService(); + + await publisher.Publish(new ContinueNotification()); + + Assert.Equal(1, probe.ThrowCount); + Assert.Equal(1, probe.SuccessCount); + } + + [Fact] + public async Task ExceptionHandler_IsInvoked_OnHandlerFailure() + { + var services = new ServiceCollection(); + services.AddSingleton(new ExceptionHandlerProbe()); + services.AddInterlink(options => + { + options.PublishStrategy = PublishStrategy.Sequential; + options.NotificationExceptionStrategy = NotificationExceptionStrategy.Continue; + }, typeof(NotificationExceptionStrategyTests).Assembly); + + await using var provider = services.BuildServiceProvider(); + var publisher = provider.GetRequiredService(); + var exceptionProbe = provider.GetRequiredService(); + + await publisher.Publish(new ExceptionHandlerNotification()); + + Assert.Equal(1, exceptionProbe.CallCount); + Assert.NotNull(exceptionProbe.LastException); + Assert.Contains("eh-boom", exceptionProbe.LastException!.Message); + } + + [Fact] + public async Task Aggregate_Parallel_CollectsFailuresFromAllHandlers() + { + var services = new ServiceCollection(); + services.AddInterlink(options => + { + options.PublishStrategy = PublishStrategy.Parallel; + options.NotificationExceptionStrategy = NotificationExceptionStrategy.Aggregate; + }, typeof(NotificationExceptionStrategyTests).Assembly); + + await using var provider = services.BuildServiceProvider(); + var publisher = provider.GetRequiredService(); + + var ex = await Assert.ThrowsAsync( + () => publisher.Publish(new ParallelAggregateNotification())); + + Assert.Equal(2, ex.InnerExceptions.Count); + Assert.All(ex.InnerExceptions, e => Assert.IsType(e)); + } + + [Fact] + public async Task ExceptionHandler_Runs_Before_StopOnFirst_Rethrows() + { + var services = new ServiceCollection(); + services.AddSingleton(new ExceptionHandlerProbe()); + services.AddInterlink(options => + { + options.PublishStrategy = PublishStrategy.Sequential; + options.NotificationExceptionStrategy = NotificationExceptionStrategy.StopOnFirst; + }, typeof(NotificationExceptionStrategyTests).Assembly); + + await using var provider = services.BuildServiceProvider(); + var publisher = provider.GetRequiredService(); + var exceptionProbe = provider.GetRequiredService(); + + await Assert.ThrowsAsync( + () => publisher.Publish(new ExceptionHandlerNotification())); + + Assert.Equal(1, exceptionProbe.CallCount); + } +} + +// ─── StopOnFirst ───────────────────────────────────────────── + +public sealed class StopOnFirstProbe +{ + private int _throwCount; + private int _secondRan; + + public int ThrowCount => _throwCount; + public int SecondRanCount => _secondRan; + + public void MarkThrow() => Interlocked.Increment(ref _throwCount); + public void MarkSecond() => Interlocked.Increment(ref _secondRan); +} + +public sealed class StopOnFirstNotification : INotification; + +public sealed class StopOnFirst_ThrowingHandler : INotificationHandler +{ + private readonly StopOnFirstProbe _probe; + public StopOnFirst_ThrowingHandler(StopOnFirstProbe probe) => _probe = probe; + + public Task Handle(StopOnFirstNotification notification, CancellationToken cancellationToken) + { + _probe.MarkThrow(); + throw new InvalidOperationException("stop-boom"); + } +} + +public sealed class StopOnFirst_SecondHandler : INotificationHandler +{ + private readonly StopOnFirstProbe _probe; + public StopOnFirst_SecondHandler(StopOnFirstProbe probe) => _probe = probe; + + public Task Handle(StopOnFirstNotification notification, CancellationToken cancellationToken) + { + _probe.MarkSecond(); + return Task.CompletedTask; + } +} + +// ─── Aggregate ─────────────────────────────────────────────── + +public sealed class AggregateProbe +{ + private int _throwCount; + private int _successCount; + + public int ThrowCount => _throwCount; + public int SuccessCount => _successCount; + + public void MarkThrow() => Interlocked.Increment(ref _throwCount); + public void MarkSuccess() => Interlocked.Increment(ref _successCount); +} + +public sealed class AggregateNotification : INotification; + +public sealed class Aggregate_FirstThrows : INotificationHandler +{ + private readonly AggregateProbe _probe; + public Aggregate_FirstThrows(AggregateProbe probe) => _probe = probe; + + public Task Handle(AggregateNotification notification, CancellationToken cancellationToken) + { + _probe.MarkThrow(); + throw new InvalidOperationException("agg-1"); + } +} + +public sealed class Aggregate_SecondSucceeds : INotificationHandler +{ + private readonly AggregateProbe _probe; + public Aggregate_SecondSucceeds(AggregateProbe probe) => _probe = probe; + + public Task Handle(AggregateNotification notification, CancellationToken cancellationToken) + { + _probe.MarkSuccess(); + return Task.CompletedTask; + } +} + +public sealed class Aggregate_ThirdThrows : INotificationHandler +{ + private readonly AggregateProbe _probe; + public Aggregate_ThirdThrows(AggregateProbe probe) => _probe = probe; + + public Task Handle(AggregateNotification notification, CancellationToken cancellationToken) + { + _probe.MarkThrow(); + throw new InvalidOperationException("agg-3"); + } +} + +// ─── Continue ──────────────────────────────────────────────── + +public sealed class ContinueProbe +{ + private int _throwCount; + private int _successCount; + + public int ThrowCount => _throwCount; + public int SuccessCount => _successCount; + + public void MarkThrow() => Interlocked.Increment(ref _throwCount); + public void MarkSuccess() => Interlocked.Increment(ref _successCount); +} + +public sealed class ContinueNotification : INotification; + +public sealed class Continue_ThrowingHandler : INotificationHandler +{ + private readonly ContinueProbe _probe; + public Continue_ThrowingHandler(ContinueProbe probe) => _probe = probe; + + public Task Handle(ContinueNotification notification, CancellationToken cancellationToken) + { + _probe.MarkThrow(); + throw new InvalidOperationException("continue-boom"); + } +} + +public sealed class Continue_SuccessHandler : INotificationHandler +{ + private readonly ContinueProbe _probe; + public Continue_SuccessHandler(ContinueProbe probe) => _probe = probe; + + public Task Handle(ContinueNotification notification, CancellationToken cancellationToken) + { + _probe.MarkSuccess(); + return Task.CompletedTask; + } +} + +// ─── Exception handler ─────────────────────────────────────── + +public sealed class ExceptionHandlerProbe +{ + private int _callCount; + + public int CallCount => _callCount; + public Exception? LastException { get; private set; } + + public void Record(Exception ex) + { + Interlocked.Increment(ref _callCount); + LastException = ex; + } +} + +public sealed class ExceptionHandlerNotification : INotification; + +public sealed class ExceptionHandler_ThrowingHandler : INotificationHandler +{ + public Task Handle(ExceptionHandlerNotification notification, CancellationToken cancellationToken) + => throw new InvalidOperationException("eh-boom"); +} + +public sealed class ExceptionHandler_Capture : INotificationExceptionHandler +{ + private readonly ExceptionHandlerProbe _probe; + public ExceptionHandler_Capture(ExceptionHandlerProbe probe) => _probe = probe; + + public Task Handle( + ExceptionHandlerNotification notification, + Exception exception, + CancellationToken cancellationToken) + { + _probe.Record(exception); + return Task.CompletedTask; + } +} + +// ─── Parallel Aggregate ────────────────────────────────────── + +public sealed class ParallelAggregateNotification : INotification; + +public sealed class Parallel_FirstThrows : INotificationHandler +{ + public Task Handle(ParallelAggregateNotification notification, CancellationToken cancellationToken) + => throw new InvalidOperationException("par-1"); +} + +public sealed class Parallel_SecondThrows : INotificationHandler +{ + public Task Handle(ParallelAggregateNotification notification, CancellationToken cancellationToken) + => throw new InvalidOperationException("par-2"); +}