diff --git a/README.md b/README.md
index be5bec3a..34f826e7 100644
--- a/README.md
+++ b/README.md
@@ -30,6 +30,47 @@ For those with technical curiosities, here are some goodies to browse through:
5. [4.1 Code media library scanning diagram](./docs/technical/architecture/4.1%20code-media-library-scanning-diagram.svg)
- Also for Software Architects, you might want to take a look at the Architecture Decision Log, where you may find important stories from the past of Lumina's development, like [this one](./docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md), and others like it.
+## Telemetry and Observability
+
+Lumina instruments its applications with OpenTelemetry (traces and metrics) and structured logging (Serilog), correlated through trace and span identifiers.
+
+- Every query, command, and domain event handler in the application layer emits a trace span, latency and invocation metrics, and a structured log entry, through a telemetry decorator registered in the dependency injection container.
+- Serilog enriches every log line with `TraceId` and `SpanId`, so logs can be joined to the traces that produced them.
+- The API and Web applications export traces and metrics over OTLP, to an endpoint configured through `Telemetry:Otlp:Endpoint` or the standard `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable.
+- The Web application injects the W3C trace context into its calls to the API, so a single trace spans both applications.
+
+### Local observability stack
+
+The `docker-compose.yml` file ships an observability stack for local development, in addition to the API and Web applications:
+
+- OpenTelemetry Collector, receiving OTLP at `localhost:4317` (gRPC) and `localhost:4318` (HTTP), and fanning traces and metrics out to the backends below.
+- Jaeger for trace search: http://localhost:16686
+- Prometheus for metrics: http://localhost:9090
+- Grafana for dashboards: http://localhost:3000, pre-provisioned with a "Lumina" dashboard (handler latency and invocation rates) and Prometheus and Jaeger data sources. The local development stack signs in with `admin` / `lumina-admin`, overridable through the `GRAFANA_ADMIN_PASSWORD` environment variable.
+
+Start everything with `docker compose up` (or `docker compose up --build` after code changes), then open the dashboards. The Web application runs at http://localhost:5012 and the API at http://localhost:5214.
+
+### Configuration
+
+Telemetry behavior is controlled by the `Telemetry` section of `appsettings.json`:
+
+- `Enabled`: master switch for the OpenTelemetry pipelines (default `true`).
+- `Otlp:Endpoint`: OTLP exporter endpoint, falling back to the `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable when empty.
+- `TraceSampleRatio`: the ratio of traces to sample, `1.0` in development and `0.25` by default in production.
+- `ConsoleExporterEnabled`: writes telemetry to the console for local inspection (default off outside the Development environment).
+
+Note that telemetry being enabled by default does not mean anything is collected and sent anywhere on its own: with `Enabled` at `true`, the applications register the OpenTelemetry pipelines and keep emitting traces, metrics, and logs, but nothing leaves the process unless an OTLP endpoint is configured (via `Otlp:Endpoint` or `OTEL_EXPORTER_OTLP_ENDPOINT`) or the console exporter is turned on. Out of the box the default configuration sends nothing anywhere.
+
+For a production deployment, point the OTLP endpoint at a real collector instead of relying on the local stack.
+
+## Production notes
+
+The development setup ships convenience defaults that must never be used in a real deployment:
+
+- **API secrets.** The API requires a JWT signing key and an encryption key, both validated with `ValidateOnStart()`. Production deployments must supply their own values through the `JwtSettings__SecretKey` and `EncryptionSettings__SecretKey` environment variables, otherwise the API fails to start.
+- **Grafana.** The local observability stack signs in with the well-known `admin` / `lumina-admin` credentials and binds Grafana to `127.0.0.1`. Do not leave the default password: set `GRAFANA_ADMIN_PASSWORD` (or `GF_SECURITY_ADMIN_PASSWORD`) before exposing Grafana beyond your own machine.
+- **Scope.** The observability stack (collector, Jaeger, Prometheus, Grafana) in `docker-compose.yml` is intended for local development only.
+
## Contributing
Lumina welcomes community contributions. All forms of input, be it code, bug reports, or feature suggestions, are appreciated. Be sure to read the [guidelines](./docs/CONTRIBUTING.md) for contributing first!
@@ -62,6 +103,8 @@ Several icons used in this project were adapted from icons sourced from [svgrepo
- [`trigger.svg`](https://www.svgrepo.com/svg/489497/lightning-1) (Public Domain License)
- [`stop.svg`](https://www.svgrepo.com/svg/521862/stop) (CC Attribution License)
+**I greatly appreciate the creators and contributors for providing these assets.**
+
## License
This project is licensed under the GPLv3.0. See the [LICENSE](./LICENSE.md) file for details.
diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs
index 229555a5..b8f5bc7d 100644
--- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs
+++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Telemetry;
using Lumina.Domain.Common.Events;
using Microsoft.Extensions.DependencyInjection;
using System;
@@ -46,9 +47,18 @@ public static class ApplicationLayerServices
continue;
if (registration.Contract.GetGenericTypeDefinition() == typeof(Infrastructure.Validation.IValidator<>))
+ {
services.AddSingleton(registration.Contract, registration.Implementation);
- else
- services.AddScoped(registration.Contract, registration.Implementation);
+ continue;
+ }
+
+ // wrap query, command, and domain event handlers in their telemetry decorator, so that every invocation emits traces, metrics, and structured logs
+ services.AddScoped(registration.Contract, serviceProvider =>
+ {
+ object handler = ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, registration.Implementation);
+ Type decoratorType = TelemetryDecoratorFactory.GetDecoratorType(registration.Contract);
+ return ActivatorUtilities.CreateInstance(serviceProvider, decoratorType, handler);
+ });
}
return services;
diff --git a/src/Lumina.Application/Common/Telemetry/ApplicationHandlerTelemetry.cs b/src/Lumina.Application/Common/Telemetry/ApplicationHandlerTelemetry.cs
new file mode 100644
index 00000000..369ec505
--- /dev/null
+++ b/src/Lumina.Application/Common/Telemetry/ApplicationHandlerTelemetry.cs
@@ -0,0 +1,108 @@
+#region ========================================================================= USING =====================================================================================
+using Microsoft.Extensions.Logging;
+using System;
+using System.Diagnostics;
+using System.Diagnostics.Metrics;
+#endregion
+
+namespace Lumina.Application.Common.Telemetry;
+
+///
+/// Helper that emits the traces, metrics, and structured logs for the execution of application handlers.
+///
+internal static class ApplicationHandlerTelemetry
+{
+ private const string HANDLER_DURATION_METRIC_NAME = "lumina.application.handler.duration";
+ private const string HANDLER_INVOCATIONS_METRIC_NAME = "lumina.application.handler.invocations";
+
+ private static readonly Histogram s_handlerDuration = ApplicationTelemetry.Meter.CreateHistogram(
+ name: HANDLER_DURATION_METRIC_NAME,
+ description: "Duration in milliseconds of the execution of an application handler.");
+
+ private static readonly Counter s_handlerInvocations = ApplicationTelemetry.Meter.CreateCounter(
+ name: HANDLER_INVOCATIONS_METRIC_NAME,
+ description: "Number of invocations of an application handler.");
+
+ ///
+ /// Starts a new for the execution of the handler with the specified name.
+ ///
+ /// The name of the handler being executed.
+ /// The type of the handler being executed.
+ /// The started activity, or when no trace listener is registered.
+ public static Activity? StartActivity(string handlerName, string handlerType)
+ {
+ Activity? activity = ApplicationTelemetry.ActivitySource.StartActivity($"Handle {handlerName}", ActivityKind.Internal);
+ activity?.SetTag("lumina.handler.type", handlerType);
+ activity?.SetTag("lumina.handler.name", handlerName);
+ return activity;
+ }
+
+ ///
+ /// Records the successful completion of a handler execution, including its trace status, metrics, and a structured log entry.
+ ///
+ /// The logger to write the structured log entry to.
+ /// The activity to mark as successful.
+ /// The name of the handled handler.
+ /// The type of the handled handler.
+ /// The duration of the handler execution.
+ public static void RecordSuccess(ILogger logger, Activity? activity, string handlerName, string handlerType, TimeSpan duration)
+ {
+ activity?.SetStatus(ActivityStatusCode.Ok);
+ RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: true);
+ logger.LogDebug("Completed handling {HandlerType} {HandlerName} in {DurationMs}ms", handlerType, handlerName, duration.TotalMilliseconds);
+ }
+
+ ///
+ /// Records the failed completion of a handler execution, including its trace status, metrics, and a structured log entry.
+ ///
+ /// The logger to write the structured log entry to.
+ /// The activity to mark as failed.
+ /// The name of the handled handler.
+ /// The type of the handled handler.
+ /// The duration of the handler execution.
+ /// An optional description of the failure.
+ public static void RecordFailure(ILogger logger, Activity? activity, string handlerName, string handlerType, TimeSpan duration, string? error)
+ {
+ activity?.SetStatus(ActivityStatusCode.Error, error);
+ RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: false);
+ // business-rule failures are routine outcomes (e.g. failed logins), so log at Debug to avoid noise from high-frequency handlers
+ logger.LogDebug("Failed handling {HandlerType} {HandlerName} in {DurationMs}ms: {Error}", handlerType, handlerName, duration.TotalMilliseconds, error);
+ }
+
+ ///
+ /// Records the exceptional completion of a handler execution, including its trace status, metrics, and a structured log entry.
+ ///
+ /// The logger to write the structured log entry to.
+ /// The activity to mark as failed.
+ /// The name of the handled handler.
+ /// The type of the handled handler.
+ /// The exception that was thrown during the handler execution.
+ /// The duration of the handler execution.
+ public static void RecordException(ILogger logger, Activity? activity, string handlerName, string handlerType, Exception exception, TimeSpan duration)
+ {
+ activity?.SetStatus(ActivityStatusCode.Error, exception.Message);
+ RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: false);
+ logger.LogError(exception, "Failed handling {HandlerType} {HandlerName} in {DurationMs}ms", handlerType, handlerName, duration.TotalMilliseconds);
+ }
+
+ ///
+ /// Records the invocation count and duration of a handler execution into the corresponding metrics, and tags the activity with the outcome.
+ ///
+ /// The activity to tag with the outcome.
+ /// The name of the handled handler.
+ /// The type of the handled handler.
+ /// The duration of the handler execution.
+ /// Whether the handler execution completed successfully.
+ private static void RecordOutcome(Activity? activity, string handlerName, string handlerType, TimeSpan duration, bool isSuccess)
+ {
+ TagList tags = new()
+ {
+ { "lumina.handler.type", handlerType },
+ { "lumina.handler.name", handlerName },
+ { "lumina.outcome", isSuccess ? "success" : "failure" }
+ };
+ s_handlerInvocations.Add(1, tags);
+ s_handlerDuration.Record(duration.TotalMilliseconds, tags);
+ activity?.SetTag("lumina.outcome", isSuccess ? "success" : "failure");
+ }
+}
diff --git a/src/Lumina.Application/Common/Telemetry/ApplicationTelemetry.cs b/src/Lumina.Application/Common/Telemetry/ApplicationTelemetry.cs
new file mode 100644
index 00000000..45128ef6
--- /dev/null
+++ b/src/Lumina.Application/Common/Telemetry/ApplicationTelemetry.cs
@@ -0,0 +1,27 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+using System.Diagnostics.Metrics;
+#endregion
+
+namespace Lumina.Application.Common.Telemetry;
+
+///
+/// Central registry of the and used by the Application layer to emit traces and metrics.
+///
+public static class ApplicationTelemetry
+{
+ ///
+ /// The source name shared by the and of the Application layer.
+ ///
+ public const string SOURCE_NAME = "Lumina.Application";
+
+ ///
+ /// The source of the traces emitted by the Application layer.
+ ///
+ public static ActivitySource ActivitySource { get; } = new(SOURCE_NAME);
+
+ ///
+ /// The source of the metrics emitted by the Application layer.
+ ///
+ public static Meter Meter { get; } = new(SOURCE_NAME);
+}
diff --git a/src/Lumina.Application/Common/Telemetry/HandlerOutcomeDetector.cs b/src/Lumina.Application/Common/Telemetry/HandlerOutcomeDetector.cs
new file mode 100644
index 00000000..ac2c7a1d
--- /dev/null
+++ b/src/Lumina.Application/Common/Telemetry/HandlerOutcomeDetector.cs
@@ -0,0 +1,63 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Collections.Concurrent;
+using System.Reflection;
+#endregion
+
+namespace Lumina.Application.Common.Telemetry;
+
+///
+/// Detects the outcome of an application handler result in a generic way, without coupling the telemetry decorators to any concrete result type.
+///
+internal static class HandlerOutcomeDetector
+{
+ private static readonly ConcurrentDictionary s_isSuccessPropertyCache = new();
+ private static readonly ConcurrentDictionary s_firstErrorPropertyCache = new();
+ private static readonly ConcurrentDictionary s_errorDescriptionPropertyCache = new();
+
+ ///
+ /// Determines whether the specified result represents a successful outcome.
+ ///
+ /// The result returned by an application handler, or .
+ ///
+ /// when the result reports success, when it is , or when it exposes no success flag.
+ ///
+ ///
+ /// Handlers that return plain DTOs (no IsSuccess property) cannot express a failure and are reported as successful;
+ /// only handlers returning a result type such as report failures.
+ ///
+ public static bool IsSuccessful(object? result)
+ {
+ if (result is null)
+ return true;
+ PropertyInfo? isSuccessProperty = GetIsSuccessProperty(result.GetType());
+ return isSuccessProperty is null || (bool)isSuccessProperty.GetValue(result)!;
+ }
+
+ ///
+ /// Gets a human-readable description of the first error of a failed result, when the result exposes one.
+ ///
+ /// The failed result returned by an application handler, or .
+ /// The description of the first error, or when the result exposes no errors.
+ public static string? GetErrorDescription(object? result)
+ {
+ if (result is null)
+ return null;
+ PropertyInfo? firstErrorProperty = s_firstErrorPropertyCache.GetOrAdd(result.GetType(), type => type.GetProperty("FirstError", BindingFlags.Public | BindingFlags.Instance));
+ object? firstError = firstErrorProperty?.GetValue(result);
+ if (firstError is null)
+ return null;
+ PropertyInfo? descriptionProperty = s_errorDescriptionPropertyCache.GetOrAdd(firstError.GetType(), type => type.GetProperty("Description", BindingFlags.Public | BindingFlags.Instance));
+ return descriptionProperty?.GetValue(firstError)?.ToString();
+ }
+
+ ///
+ /// Gets the public instance IsSuccess property of the specified type, if it has one.
+ ///
+ /// The type to inspect.
+ /// The IsSuccess property, or when the type does not expose one.
+ private static PropertyInfo? GetIsSuccessProperty(Type type)
+ {
+ return s_isSuccessPropertyCache.GetOrAdd(type, candidateType => candidateType.GetProperty("IsSuccess", BindingFlags.Public | BindingFlags.Instance));
+ }
+}
diff --git a/src/Lumina.Application/Common/Telemetry/TelemetryCommandHandlerDecorator.cs b/src/Lumina.Application/Common/Telemetry/TelemetryCommandHandlerDecorator.cs
new file mode 100644
index 00000000..29123465
--- /dev/null
+++ b/src/Lumina.Application/Common/Telemetry/TelemetryCommandHandlerDecorator.cs
@@ -0,0 +1,65 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Microsoft.Extensions.Logging;
+using System;
+using System.Diagnostics;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Common.Telemetry;
+
+///
+/// Decorator that wraps an to emit traces, metrics, and structured logs for every command execution.
+///
+/// The type of command to handle.
+/// The type of result returned after handling the command.
+public class TelemetryCommandHandlerDecorator : ICommandHandler where TCommand : ICommand
+{
+ private const string HANDLER_TYPE = "command";
+
+ private readonly ICommandHandler _innerHandler;
+ private readonly ILogger> _logger;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The wrapped command handler.
+ /// Injected logger used for structured logging.
+ public TelemetryCommandHandlerDecorator(ICommandHandler innerHandler, ILogger> logger)
+ {
+ _innerHandler = innerHandler;
+ _logger = logger;
+ }
+
+ ///
+ /// Handles the specified command, emitting telemetry around the execution of the wrapped handler.
+ ///
+ /// The command to handle.
+ /// Token to monitor for cancellation requests.
+ /// A task that represents the asynchronous operation, containing the result of the command execution.
+ public async Task HandleAsync(TCommand command, CancellationToken cancellationToken)
+ {
+ string handlerName = _innerHandler.GetType().Name;
+ using (Activity? activity = ApplicationHandlerTelemetry.StartActivity(handlerName, HANDLER_TYPE))
+ {
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ try
+ {
+ TResult result = await _innerHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false);
+ stopwatch.Stop();
+ if (HandlerOutcomeDetector.IsSuccessful(result))
+ ApplicationHandlerTelemetry.RecordSuccess(_logger, activity, handlerName, HANDLER_TYPE, stopwatch.Elapsed);
+ else
+ ApplicationHandlerTelemetry.RecordFailure(_logger, activity, handlerName, HANDLER_TYPE, stopwatch.Elapsed, HandlerOutcomeDetector.GetErrorDescription(result));
+ return result;
+ }
+ catch (Exception exception)
+ {
+ stopwatch.Stop();
+ ApplicationHandlerTelemetry.RecordException(_logger, activity, handlerName, HANDLER_TYPE, exception, stopwatch.Elapsed);
+ throw;
+ }
+ }
+ }
+}
diff --git a/src/Lumina.Application/Common/Telemetry/TelemetryDecoratorFactory.cs b/src/Lumina.Application/Common/Telemetry/TelemetryDecoratorFactory.cs
new file mode 100644
index 00000000..78506590
--- /dev/null
+++ b/src/Lumina.Application/Common/Telemetry/TelemetryDecoratorFactory.cs
@@ -0,0 +1,34 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Domain.Common.Events;
+using System;
+#endregion
+
+namespace Lumina.Application.Common.Telemetry;
+
+///
+/// Resolves the telemetry decorator type that wraps a given application handler contract.
+///
+internal static class TelemetryDecoratorFactory
+{
+ ///
+ /// Gets the closed telemetry decorator type for the specified handler contract.
+ ///
+ /// The handler contract to wrap.
+ /// The closed generic telemetry decorator type for the contract.
+ /// Thrown when the contract has no matching telemetry decorator.
+ public static Type GetDecoratorType(Type contract)
+ {
+ Type contractDefinition = contract.GetGenericTypeDefinition();
+ Type[] typeArguments = contract.GetGenericArguments();
+
+ if (contractDefinition == typeof(IQueryHandler<,>))
+ return typeof(TelemetryQueryHandlerDecorator<,>).MakeGenericType(typeArguments);
+ if (contractDefinition == typeof(ICommandHandler<,>))
+ return typeof(TelemetryCommandHandlerDecorator<,>).MakeGenericType(typeArguments);
+ if (contractDefinition == typeof(IDomainEventHandler<>))
+ return typeof(TelemetryDomainEventHandlerDecorator<>).MakeGenericType(typeArguments);
+
+ throw new ArgumentException($"No telemetry decorator is defined for the contract type '{contract}'.", nameof(contract));
+ }
+}
diff --git a/src/Lumina.Application/Common/Telemetry/TelemetryDomainEventHandlerDecorator.cs b/src/Lumina.Application/Common/Telemetry/TelemetryDomainEventHandlerDecorator.cs
new file mode 100644
index 00000000..02e96c1f
--- /dev/null
+++ b/src/Lumina.Application/Common/Telemetry/TelemetryDomainEventHandlerDecorator.cs
@@ -0,0 +1,60 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.Common.Events;
+using Microsoft.Extensions.Logging;
+using System;
+using System.Diagnostics;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Common.Telemetry;
+
+///
+/// Decorator that wraps an to emit traces, metrics, and structured logs for every domain event handling.
+///
+/// The type of domain event to handle.
+public class TelemetryDomainEventHandlerDecorator : IDomainEventHandler where TDomainEvent : IDomainEvent
+{
+ private const string HANDLER_TYPE = "domain-event";
+
+ private readonly IDomainEventHandler _innerHandler;
+ private readonly ILogger> _logger;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The wrapped domain event handler.
+ /// Injected logger used for structured logging.
+ public TelemetryDomainEventHandlerDecorator(IDomainEventHandler innerHandler, ILogger> logger)
+ {
+ _innerHandler = innerHandler;
+ _logger = logger;
+ }
+
+ ///
+ /// Handles the specified domain event, emitting telemetry around the execution of the wrapped handler.
+ ///
+ /// The domain event to handle.
+ /// Token to monitor for cancellation requests.
+ /// A task that represents the asynchronous operation.
+ public async ValueTask HandleAsync(TDomainEvent domainEvent, CancellationToken cancellationToken)
+ {
+ string handlerName = _innerHandler.GetType().Name;
+ using (Activity? activity = ApplicationHandlerTelemetry.StartActivity(handlerName, HANDLER_TYPE))
+ {
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ try
+ {
+ await _innerHandler.HandleAsync(domainEvent, cancellationToken).ConfigureAwait(false);
+ stopwatch.Stop();
+ ApplicationHandlerTelemetry.RecordSuccess(_logger, activity, handlerName, HANDLER_TYPE, stopwatch.Elapsed);
+ }
+ catch (Exception exception)
+ {
+ stopwatch.Stop();
+ ApplicationHandlerTelemetry.RecordException(_logger, activity, handlerName, HANDLER_TYPE, exception, stopwatch.Elapsed);
+ throw;
+ }
+ }
+ }
+}
diff --git a/src/Lumina.Application/Common/Telemetry/TelemetryQueryHandlerDecorator.cs b/src/Lumina.Application/Common/Telemetry/TelemetryQueryHandlerDecorator.cs
new file mode 100644
index 00000000..f5529bb6
--- /dev/null
+++ b/src/Lumina.Application/Common/Telemetry/TelemetryQueryHandlerDecorator.cs
@@ -0,0 +1,65 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Microsoft.Extensions.Logging;
+using System;
+using System.Diagnostics;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Common.Telemetry;
+
+///
+/// Decorator that wraps an to emit traces, metrics, and structured logs for every query execution.
+///
+/// The type of query to handle.
+/// The type of result returned after handling the query.
+public class TelemetryQueryHandlerDecorator : IQueryHandler where TQuery : IQuery
+{
+ private const string HANDLER_TYPE = "query";
+
+ private readonly IQueryHandler _innerHandler;
+ private readonly ILogger> _logger;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The wrapped query handler.
+ /// Injected logger used for structured logging.
+ public TelemetryQueryHandlerDecorator(IQueryHandler innerHandler, ILogger> logger)
+ {
+ _innerHandler = innerHandler;
+ _logger = logger;
+ }
+
+ ///
+ /// Handles the specified query, emitting telemetry around the execution of the wrapped handler.
+ ///
+ /// The query to handle.
+ /// Token to monitor for cancellation requests.
+ /// A task that represents the asynchronous operation, containing the result of the query execution.
+ public async Task HandleAsync(TQuery query, CancellationToken cancellationToken)
+ {
+ string handlerName = _innerHandler.GetType().Name;
+ using (Activity? activity = ApplicationHandlerTelemetry.StartActivity(handlerName, HANDLER_TYPE))
+ {
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ try
+ {
+ TResult result = await _innerHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false);
+ stopwatch.Stop();
+ if (HandlerOutcomeDetector.IsSuccessful(result))
+ ApplicationHandlerTelemetry.RecordSuccess(_logger, activity, handlerName, HANDLER_TYPE, stopwatch.Elapsed);
+ else
+ ApplicationHandlerTelemetry.RecordFailure(_logger, activity, handlerName, HANDLER_TYPE, stopwatch.Elapsed, HandlerOutcomeDetector.GetErrorDescription(result));
+ return result;
+ }
+ catch (Exception exception)
+ {
+ stopwatch.Stop();
+ ApplicationHandlerTelemetry.RecordException(_logger, activity, handlerName, HANDLER_TYPE, exception, stopwatch.Elapsed);
+ throw;
+ }
+ }
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerConfiguration.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerConfiguration.cs
index 72f3cbb4..ce6736d7 100644
--- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerConfiguration.cs
+++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerConfiguration.cs
@@ -29,6 +29,7 @@ internal static class PresentationApiLayerConfiguration
configuration.SetBasePath(basePath);
configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
configuration.AddJsonFile("appsettings.development.json", optional: true, reloadOnChange: true);
+ configuration.AddEnvironmentVariables(); // environment variables should override the configuration files
return services;
}
diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs
index aa914527..920f999a 100644
--- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs
+++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs
@@ -3,6 +3,7 @@ using FastEndpoints;
using FastEndpoints.Swagger;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Presentation.Api.Common.Authentication;
+using Lumina.Presentation.Api.Common.HealthChecks;
using MessagePack;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
@@ -10,6 +11,7 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
@@ -39,6 +41,10 @@ public static class PresentationApiLayerServices
services.AddMemoryCache(); // used for the tracking involved in authentication rate limiting
services.AddProblemDetails();
+ // the readiness health check verifies that the database can be reached, and is probed by container orchestrators and load balancers
+ services.AddHealthChecks()
+ .AddCheck("database", HealthStatus.Unhealthy, ["ready"]);
+
services.Configure(jsonOptions =>
{
jsonOptions.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiTelemetryServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiTelemetryServices.cs
new file mode 100644
index 00000000..b7ef7ec7
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiTelemetryServices.cs
@@ -0,0 +1,102 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Telemetry;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using OpenTelemetry;
+using OpenTelemetry.Metrics;
+using OpenTelemetry.Resources;
+using OpenTelemetry.Trace;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Common.DependencyInjection;
+
+///
+/// Contains the OpenTelemetry services of the Presentation API layer.
+///
+[ExcludeFromCodeCoverage]
+public static class PresentationApiTelemetryServices
+{
+ private const string SERVICE_NAME = "Lumina.Api";
+ private const string ENTITY_FRAMEWORK_CORE_METER_NAME = "Microsoft.EntityFrameworkCore";
+
+ ///
+ /// Registers the OpenTelemetry tracing and metrics pipelines into the dependency injection container.
+ ///
+ /// The service collection to add the services to.
+ /// Application configuration properties.
+ /// The hosting environment of the application.
+ /// The updated .
+ public static IServiceCollection AddPresentationApiTelemetryServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment)
+ {
+ bool isTelemetryEnabled = configuration.GetValue("Telemetry:Enabled") ?? true;
+ if (!isTelemetryEnabled)
+ return services;
+
+ bool isConsoleExporterEnabled = configuration.GetValue("Telemetry:ConsoleExporterEnabled") ?? environment.IsDevelopment();
+ string? otlpEndpoint = GetOtlpEndpoint(configuration);
+ double traceSampleRatio = configuration.GetValue("Telemetry:TraceSampleRatio") ?? 1.0;
+ string serviceVersion = typeof(Program).Assembly.GetName().Version?.ToString() ?? "unknown";
+
+ services.AddOpenTelemetry()
+ .ConfigureResource(resourceBuilder => resourceBuilder
+ .AddService(serviceName: SERVICE_NAME, serviceVersion: serviceVersion)
+ .AddEnvironmentVariableDetector()
+ .AddAttributes(new Dictionary
+ {
+ ["deployment.environment"] = environment.EnvironmentName
+ }))
+ .WithTracing(tracingBuilder =>
+ {
+ tracingBuilder.SetSampler(CreateSampler(traceSampleRatio));
+ tracingBuilder.AddSource(ApplicationTelemetry.SOURCE_NAME);
+ tracingBuilder.AddAspNetCoreInstrumentation();
+ if (isConsoleExporterEnabled)
+ tracingBuilder.AddConsoleExporter();
+ if (otlpEndpoint is not null)
+ tracingBuilder.AddOtlpExporter(otlpExporterOptions => otlpExporterOptions.Endpoint = new Uri(otlpEndpoint));
+ })
+ .WithMetrics(metricsBuilder =>
+ {
+ metricsBuilder.AddMeter(ApplicationTelemetry.SOURCE_NAME);
+ metricsBuilder.AddMeter(ENTITY_FRAMEWORK_CORE_METER_NAME);
+ metricsBuilder.AddAspNetCoreInstrumentation();
+ metricsBuilder.AddRuntimeInstrumentation();
+ if (isConsoleExporterEnabled)
+ metricsBuilder.AddConsoleExporter();
+ if (otlpEndpoint is not null)
+ metricsBuilder.AddOtlpExporter(otlpExporterOptions => otlpExporterOptions.Endpoint = new Uri(otlpEndpoint));
+ });
+
+ return services;
+ }
+
+ ///
+ /// Gets the OTLP exporter endpoint from configuration, falling back to the standard OTEL_EXPORTER_OTLP_ENDPOINT environment variable.
+ ///
+ /// Application configuration properties.
+ /// The OTLP endpoint, or when no endpoint is configured.
+ private static string? GetOtlpEndpoint(IConfiguration configuration)
+ {
+ string? endpoint = configuration.GetValue("Telemetry:Otlp:Endpoint");
+ if (string.IsNullOrWhiteSpace(endpoint))
+ endpoint = Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_ENDPOINT");
+ return string.IsNullOrWhiteSpace(endpoint) ? null : endpoint;
+ }
+
+ ///
+ /// Creates the trace sampler used by the API, sampling every trace by default and honoring the configured ratio for production traffic.
+ ///
+ /// The ratio of traces to sample, in the range of zero to one.
+ /// The configured trace sampler.
+ private static Sampler CreateSampler(double traceSampleRatio)
+ {
+ return traceSampleRatio < 1.0
+ ? new ParentBasedSampler(new TraceIdRatioBasedSampler(traceSampleRatio))
+ : new AlwaysOnSampler();
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Common/HealthChecks/DatabaseHealthCheck.cs b/src/Lumina.Presentation.Api/Common/HealthChecks/DatabaseHealthCheck.cs
new file mode 100644
index 00000000..9ff53c7d
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Common/HealthChecks/DatabaseHealthCheck.cs
@@ -0,0 +1,48 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.DataAccess.Core.UoW;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Diagnostics.HealthChecks;
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.Common.HealthChecks;
+
+///
+/// Health check that verifies the database can be reached.
+///
+public class DatabaseHealthCheck : IHealthCheck
+{
+ private readonly LuminaDbContext _dbContext;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected database context.
+ public DatabaseHealthCheck(LuminaDbContext dbContext)
+ {
+ _dbContext = dbContext;
+ }
+
+ ///
+ /// Checks whether the database can be reached.
+ ///
+ /// The health check context.
+ /// Token to monitor for cancellation requests.
+ /// A task that represents the asynchronous operation, containing the health check result.
+ public virtual async Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken)
+ {
+ try
+ {
+ bool canConnect = await _dbContext.Database.CanConnectAsync(cancellationToken).ConfigureAwait(false);
+ return canConnect
+ ? HealthCheckResult.Healthy()
+ : HealthCheckResult.Unhealthy("The database is not reachable.");
+ }
+ catch (Exception exception)
+ {
+ return HealthCheckResult.Unhealthy("The database is not reachable.", exception);
+ }
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Dockerfile b/src/Lumina.Presentation.Api/Dockerfile
index 34e09240..297fdfe6 100644
--- a/src/Lumina.Presentation.Api/Dockerfile
+++ b/src/Lumina.Presentation.Api/Dockerfile
@@ -1,6 +1,10 @@
# This stage is used when running from VS in fast mode (Default for Debug configuration)
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base
-RUN mkdir /logs && chown -R app:app /logs
+# curl is used by the container healthcheck to probe the /health endpoints
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends curl \
+ && rm -rf /var/lib/apt/lists/* \
+ && mkdir /logs && chown -R app:app /logs
USER app
WORKDIR /app
EXPOSE 5214
@@ -18,8 +22,10 @@ COPY ["Lumina.Presentation.Api/Lumina.Presentation.Api.csproj", "Lumina.Presenta
COPY ["Lumina.Application/Lumina.Application.csproj", "Lumina.Application/"]
COPY ["Lumina.Contracts/Lumina.Contracts.csproj", "Lumina.Contracts/"]
COPY ["Lumina.Domain/Lumina.Domain.csproj", "Lumina.Domain/"]
+COPY ["Lumina.Domain.SharedKernel/Lumina.Domain.SharedKernel.csproj", "Lumina.Domain.SharedKernel/"]
COPY ["Lumina.Infrastructure/Lumina.Infrastructure.csproj", "Lumina.Infrastructure/"]
COPY ["Lumina.DataAccess/Lumina.DataAccess.csproj", "Lumina.DataAccess/"]
+COPY ["Lumina.Plugins.Contracts/Lumina.Plugins.Contracts.csproj", "Lumina.Plugins.Contracts/"]
RUN dotnet restore "./Lumina.Presentation.Api/Lumina.Presentation.Api.csproj" /p:BaseOutputPath=/app/publish/
@@ -49,6 +55,8 @@ FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
+# The HTTP port is controlled per run mode: launchSettings.json for local development, ASPNETCORE_HTTP_PORTS here for
+# Docker, and for a published DLL run directly on a host, ASPNETCORE_URLS (or ASPNETCORE_HTTP_PORTS) must be set
ENV ASPNETCORE_HTTP_PORTS=5214
EXPOSE 5214
ENTRYPOINT ["dotnet", "Lumina.Presentation.Api.dll"]
diff --git a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj
index da5dda00..76e93fc8 100644
--- a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj
+++ b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj
@@ -31,10 +31,17 @@
all
runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
+
+
+
+
diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs
index abe2bbd1..41052581 100644
--- a/src/Lumina.Presentation.Api/Program.cs
+++ b/src/Lumina.Presentation.Api/Program.cs
@@ -12,11 +12,14 @@ using Lumina.Presentation.Api.Common.DependencyInjection;
using Lumina.Presentation.Api.Common.Middlewares;
using Lumina.Presentation.Api.Common.Utilities;
using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Http;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Scalar.AspNetCore;
@@ -24,6 +27,7 @@ using Serilog;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
+using System.Linq;
using System.Threading.Tasks;
#endregion
@@ -47,6 +51,7 @@ public class Program
builder.Services.BindPresentationApiLayerConfiguration(builder.Configuration);
builder.Services.AddPresentationApiLayerServices(builder.Configuration);
+ builder.Services.AddPresentationApiTelemetryServices(builder.Configuration, builder.Environment);
builder.Services.AddApplicationLayerServices();
builder.Services.AddInfrastructureLayerServices(builder.Configuration);
builder.Services.AddDataAccessLayerServices();
@@ -137,8 +142,9 @@ public class Program
.WithDotNetFlag(true);
});
- // add the middleware that fires domain events and ensures eventual transactional consistency, but NOT for long-polling/WebSockets stuff like SignalR, which would keep the db locked
- app.UseWhen(ctx => !ctx.Request.Path.StartsWithSegments("/scanProgressHub"), app => app.UseMiddleware());
+ // add the middleware that fires domain events and ensures eventual transactional consistency, but NOT for long-polling/WebSockets stuff like SignalR, which would keep the db locked,
+ // and NOT for the health probes, which would otherwise begin a database transaction on every probe
+ app.UseWhen(ctx => !ctx.Request.Path.StartsWithSegments("/scanProgressHub") && !ctx.Request.Path.StartsWithSegments("/health"), app => app.UseMiddleware());
// create a directory relative to the application's startup directory, and use it to store static files that are served at the /media route on the API
string mediaRootDirectoryPathSetting = app.Configuration.GetValue("MediaSettings:RootDirectory") ?? string.Empty;
@@ -165,6 +171,38 @@ public class Program
app.MapHub("/scanProgressHub");
+ // the liveness probe reports whether the process is running, while the readiness probe also verifies that the database is reachable
+ app.MapHealthChecks("/health/live", new HealthCheckOptions
+ {
+ Predicate = _ => false,
+ ResponseWriter = WriteHealthCheckResponseAsync
+ });
+ app.MapHealthChecks("/health/ready", new HealthCheckOptions
+ {
+ Predicate = healthCheck => healthCheck.Tags.Contains("ready"),
+ ResponseWriter = WriteHealthCheckResponseAsync
+ });
+
await app.RunAsync().ConfigureAwait(false);
}
+
+ ///
+ /// Writes the health report as a JSON response.
+ ///
+ /// The current HTTP context.
+ /// The health report to write.
+ private static async Task WriteHealthCheckResponseAsync(HttpContext httpContext, HealthReport healthReport)
+ {
+ httpContext.Response.ContentType = "application/json";
+ await httpContext.Response.WriteAsJsonAsync(new
+ {
+ status = healthReport.Status.ToString(),
+ checks = healthReport.Entries.Select(entry => new
+ {
+ name = entry.Key,
+ status = entry.Value.Status.ToString(),
+ description = entry.Value.Description
+ })
+ });
+ }
}
diff --git a/src/Lumina.Presentation.Api/appsettings.json b/src/Lumina.Presentation.Api/appsettings.json
index 85513e30..21276bf3 100644
--- a/src/Lumina.Presentation.Api/appsettings.json
+++ b/src/Lumina.Presentation.Api/appsettings.json
@@ -24,7 +24,7 @@
"Name": "Console",
"Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console",
- "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
+ "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {TraceId} {SpanId} {Message:lj}{NewLine}{Exception}"
}
},
{
@@ -32,7 +32,7 @@
"Args": {
"path": "%LOG_PATH%lumina_api_.log",
"rollingInterval": "Day",
- "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
+ "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {TraceId} {SpanId} {Message:lj}{NewLine}{Exception}",
"retainedFileCountLimit": 7,
"fileSizeLimitBytes": 10485760,
"rollOnFileSizeLimit": true,
@@ -45,7 +45,8 @@
"FromLogContext",
"WithMachineName",
"WithThreadId",
- "WithEnvironmentName"
+ "WithEnvironmentName",
+ "WithSpan"
],
"Properties": {
"Application": "LuminaApi"
@@ -57,11 +58,12 @@
"http://localhost:5012"
]
},
- "Kestrel": {
- "Endpoints": {
- "Http": {
- "Url": "http://localhost:5214"
- }
- }
+ "Telemetry": {
+ "Enabled": true,
+ "ConsoleExporterEnabled": false,
+ "Otlp": {
+ "Endpoint": ""
+ },
+ "TraceSampleRatio": 0.25 // production default; override to 1.0 in the development configuration for full trace capture
}
}
diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs
index 8bea5b86..b99a8a74 100644
--- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs
+++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs
@@ -25,7 +25,8 @@ internal static class PresentationWebLayerConfiguration
// add the configuration sources to the configuration builder
configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
configuration.AddJsonFile("appsettings.development.json", optional: true, reloadOnChange: true);
-
+ configuration.AddEnvironmentVariables(); // environment variables should override the configuration files
+
serviceCollection.AddOptions()
.Bind(configuration.GetRequiredSection(ServerConfigurationDto.SECTION_NAME))
.ValidateFluently()
diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebTelemetryServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebTelemetryServices.cs
new file mode 100644
index 00000000..f6925745
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebTelemetryServices.cs
@@ -0,0 +1,102 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Telemetry;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using OpenTelemetry;
+using OpenTelemetry.Metrics;
+using OpenTelemetry.Resources;
+using OpenTelemetry.Trace;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.DependencyInjection;
+
+///
+/// Contains the OpenTelemetry services of the Presentation Web layer.
+///
+[ExcludeFromCodeCoverage]
+public static class PresentationWebTelemetryServices
+{
+ private const string SERVICE_NAME = "Lumina.Web";
+
+ ///
+ /// Registers the OpenTelemetry tracing and metrics pipelines into the dependency injection container.
+ ///
+ /// The service collection to add the services to.
+ /// Application configuration properties.
+ /// The hosting environment of the application.
+ /// The updated .
+ public static IServiceCollection AddPresentationWebTelemetryServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment)
+ {
+ bool isTelemetryEnabled = configuration.GetValue("Telemetry:Enabled") ?? true;
+ if (!isTelemetryEnabled)
+ return services;
+
+ bool isConsoleExporterEnabled = configuration.GetValue("Telemetry:ConsoleExporterEnabled") ?? environment.IsDevelopment();
+ string? otlpEndpoint = GetOtlpEndpoint(configuration);
+ double traceSampleRatio = configuration.GetValue("Telemetry:TraceSampleRatio") ?? 1.0;
+ string serviceVersion = typeof(Program).Assembly.GetName().Version?.ToString() ?? "unknown";
+
+ services.AddOpenTelemetry()
+ .ConfigureResource(resourceBuilder => resourceBuilder
+ .AddService(serviceName: SERVICE_NAME, serviceVersion: serviceVersion)
+ .AddEnvironmentVariableDetector()
+ .AddAttributes(new Dictionary
+ {
+ ["deployment.environment"] = environment.EnvironmentName
+ }))
+ .WithTracing(tracingBuilder =>
+ {
+ tracingBuilder.SetSampler(CreateSampler(traceSampleRatio));
+ tracingBuilder.AddSource(WebTelemetry.SOURCE_NAME);
+ tracingBuilder.AddAspNetCoreInstrumentation();
+ // the HTTP client instrumentation emits spans and metrics for the calls to the API, and injects the W3C trace context
+ // into their headers, so that the API continues the same trace across the two separately deployed applications
+ tracingBuilder.AddHttpClientInstrumentation();
+ if (isConsoleExporterEnabled)
+ tracingBuilder.AddConsoleExporter();
+ if (otlpEndpoint is not null)
+ tracingBuilder.AddOtlpExporter(otlpExporterOptions => otlpExporterOptions.Endpoint = new Uri(otlpEndpoint));
+ })
+ .WithMetrics(metricsBuilder =>
+ {
+ metricsBuilder.AddAspNetCoreInstrumentation();
+ metricsBuilder.AddHttpClientInstrumentation();
+ if (isConsoleExporterEnabled)
+ metricsBuilder.AddConsoleExporter();
+ if (otlpEndpoint is not null)
+ metricsBuilder.AddOtlpExporter(otlpExporterOptions => otlpExporterOptions.Endpoint = new Uri(otlpEndpoint));
+ });
+
+ return services;
+ }
+
+ ///
+ /// Gets the OTLP exporter endpoint from configuration, falling back to the standard OTEL_EXPORTER_OTLP_ENDPOINT environment variable.
+ ///
+ /// Application configuration properties.
+ /// The OTLP endpoint, or when no endpoint is configured.
+ private static string? GetOtlpEndpoint(IConfiguration configuration)
+ {
+ string? endpoint = configuration.GetValue("Telemetry:Otlp:Endpoint");
+ if (string.IsNullOrWhiteSpace(endpoint))
+ endpoint = Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_ENDPOINT");
+ return string.IsNullOrWhiteSpace(endpoint) ? null : endpoint;
+ }
+
+ ///
+ /// Creates the trace sampler used by the Web application, sampling every trace by default and honoring the configured ratio for production traffic.
+ ///
+ /// The ratio of traces to sample, in the range of zero to one.
+ /// The configured trace sampler.
+ private static Sampler CreateSampler(double traceSampleRatio)
+ {
+ return traceSampleRatio < 1.0
+ ? new ParentBasedSampler(new TraceIdRatioBasedSampler(traceSampleRatio))
+ : new AlwaysOnSampler();
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Common/HealthChecks/ApiReachabilityHealthCheck.cs b/src/Lumina.Presentation.Web/Common/HealthChecks/ApiReachabilityHealthCheck.cs
new file mode 100644
index 00000000..496e1493
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/HealthChecks/ApiReachabilityHealthCheck.cs
@@ -0,0 +1,55 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.Configuration;
+using Microsoft.Extensions.Diagnostics.HealthChecks;
+using Microsoft.Extensions.Options;
+using System;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.HealthChecks;
+
+///
+/// Health check that verifies the remote API is reachable.
+///
+public class ApiReachabilityHealthCheck : IHealthCheck
+{
+ private readonly HttpClient _httpClient;
+ private readonly ServerConfigurationDto _serverConfiguration;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected factory for creating HTTP clients.
+ /// Injected server configuration application settings.
+ public ApiReachabilityHealthCheck(IHttpClientFactory httpClientFactory, IOptionsSnapshot serverConfigurationOptions)
+ {
+ _httpClient = httpClientFactory.CreateClient();
+ _serverConfiguration = serverConfigurationOptions.Value;
+ }
+
+ ///
+ /// Checks whether the remote API is reachable by probing its readiness endpoint.
+ ///
+ /// The health check context.
+ /// Token to monitor for cancellation requests.
+ /// A task that represents the asynchronous operation, containing the health check result.
+ public virtual async Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken)
+ {
+ string healthUrl = $"{_serverConfiguration.BaseAddress}:{_serverConfiguration.Port}/health/ready";
+ using CancellationTokenSource timeoutCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ timeoutCancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(5));
+ try
+ {
+ using HttpResponseMessage response = await _httpClient.GetAsync(healthUrl, timeoutCancellationTokenSource.Token).ConfigureAwait(false);
+ return response.IsSuccessStatusCode
+ ? HealthCheckResult.Healthy()
+ : HealthCheckResult.Unhealthy($"The API returned status {(int)response.StatusCode}.");
+ }
+ catch (Exception exception)
+ {
+ return HealthCheckResult.Unhealthy("The API is not reachable.", exception);
+ }
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Common/Telemetry/WebTelemetry.cs b/src/Lumina.Presentation.Web/Common/Telemetry/WebTelemetry.cs
new file mode 100644
index 00000000..0fc6329e
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/Telemetry/WebTelemetry.cs
@@ -0,0 +1,21 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.Telemetry;
+
+///
+/// Central registry of the used by the Presentation Web layer to emit traces.
+///
+public static class WebTelemetry
+{
+ ///
+ /// The source name shared by the of the Presentation Web layer.
+ ///
+ public const string SOURCE_NAME = "Lumina.Web";
+
+ ///
+ /// The source of the traces emitted by the Presentation Web layer.
+ ///
+ public static ActivitySource ActivitySource { get; } = new(SOURCE_NAME);
+}
diff --git a/src/Lumina.Presentation.Web/Dockerfile b/src/Lumina.Presentation.Web/Dockerfile
index b02a6f9f..a8fa08da 100644
--- a/src/Lumina.Presentation.Web/Dockerfile
+++ b/src/Lumina.Presentation.Web/Dockerfile
@@ -1,6 +1,10 @@
# This stage is used when running from VS in fast mode (Default for Debug configuration)
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base
-RUN mkdir /logs && chown -R app:app /logs
+# curl is used by the container healthcheck to probe the /health endpoints
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends curl \
+ && rm -rf /var/lib/apt/lists/* \
+ && mkdir /logs && chown -R app:app /logs
USER app
WORKDIR /app
EXPOSE 5012
@@ -40,6 +44,8 @@ FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
+# The HTTP port is controlled per run mode: launchSettings.json for local development, ASPNETCORE_HTTP_PORTS here for
+# Docker, and for a published DLL run directly on a host, ASPNETCORE_URLS (or ASPNETCORE_HTTP_PORTS) must be set
ENV ASPNETCORE_HTTP_PORTS=5012
EXPOSE 5012
ENTRYPOINT ["dotnet", "Lumina.Presentation.Web.dll"]
diff --git a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj
index 6b86fafb..ccdd2176 100644
--- a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj
+++ b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj
@@ -25,10 +25,17 @@
+
+
+
+
+
+
+
diff --git a/src/Lumina.Presentation.Web/Program.cs b/src/Lumina.Presentation.Web/Program.cs
index c1e4d5bf..c6d9dc6d 100644
--- a/src/Lumina.Presentation.Web/Program.cs
+++ b/src/Lumina.Presentation.Web/Program.cs
@@ -1,11 +1,14 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DependencyInjection;
+using Lumina.Presentation.Web.Common.HealthChecks;
using Lumina.Presentation.Web.Common.Utilities;
using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Primitives;
using Scalar.AspNetCore;
@@ -35,6 +38,9 @@ public class Program
builder.Services.BindConfiguration(builder.Configuration);
builder.Services.AddPresentationWebLayerServices();
+ builder.Services.AddPresentationWebTelemetryServices(builder.Configuration, builder.Environment);
+ builder.Services.AddHealthChecks()
+ .AddCheck("api", HealthStatus.Unhealthy, ["ready"]);
// determine log path based on environment
string logPath;
@@ -122,6 +128,11 @@ public class Program
.WithDotNetFlag(true);
});
+ // liveness and readiness probes, probed by container orchestrators and load balancers; the readiness probe also
+ // verifies that the API is reachable, so the web application is only reported ready when it can actually serve requests
+ app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false });
+ app.MapHealthChecks("/health/ready", new HealthCheckOptions { Predicate = healthCheck => healthCheck.Tags.Contains("ready") });
+
await app.RunAsync();
}
}
diff --git a/src/Lumina.Presentation.Web/appsettings.json b/src/Lumina.Presentation.Web/appsettings.json
index 73c0a7f4..e7297334 100644
--- a/src/Lumina.Presentation.Web/appsettings.json
+++ b/src/Lumina.Presentation.Web/appsettings.json
@@ -20,7 +20,7 @@
"Name": "Console",
"Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console",
- "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
+ "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {TraceId} {SpanId} {Message:lj}{NewLine}{Exception}"
}
},
{
@@ -28,7 +28,7 @@
"Args": {
"path": "%LOG_PATH%lumina_web_.log",
"rollingInterval": "Day",
- "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
+ "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {TraceId} {SpanId} {Message:lj}{NewLine}{Exception}",
"retainedFileCountLimit": 7,
"fileSizeLimitBytes": 10485760,
"rollOnFileSizeLimit": true,
@@ -42,7 +42,8 @@
"WithMachineName",
"WithThreadId",
"WithEnvironmentName",
- "WithRequestId"
+ "WithRequestId",
+ "WithSpan"
],
"Properties": {
"Application": "LuminaWeb"
@@ -54,11 +55,12 @@
"BaseAddress": "http://localhost",
"Port": 5214
},
- "Kestrel": {
- "Endpoints": {
- "Http": {
- "Url": "http://localhost:5012"
- }
- }
+ "Telemetry": {
+ "Enabled": true,
+ "ConsoleExporterEnabled": false,
+ "Otlp": {
+ "Endpoint": ""
+ },
+ "TraceSampleRatio": 0.25 // production default; override to 1.0 in the development configuration for full trace capture
}
}
diff --git a/src/docker-compose.yml b/src/docker-compose.yml
index 10d6ab87..38565799 100644
--- a/src/docker-compose.yml
+++ b/src/docker-compose.yml
@@ -7,6 +7,20 @@ services:
dockerfile: Lumina.Presentation.Api/Dockerfile
environment:
- LOG_PATH=/logs
+ - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
+ # The API validates JwtSettings:SecretKey and EncryptionSettings:SecretKey with ValidateOnStart(). In the
+ # Development environment they come from appsettings.development.json; for any non-development run they must be
+ # supplied here, otherwise the API crashes on startup:
+ # - JwtSettings__SecretKey=
+ # - EncryptionSettings__SecretKey=
+ depends_on:
+ - otel-collector
+ healthcheck:
+ test: ["CMD-SHELL", "curl -sf http://localhost:5214/health/ready || exit 1"]
+ interval: 30s
+ timeout: 5s
+ retries: 3
+ start_period: 60s
lumina-web:
container_name: lumina-web
@@ -16,3 +30,64 @@ services:
dockerfile: Lumina.Presentation.Web/Dockerfile
environment:
- LOG_PATH=/logs
+ - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
+ - ServerConfiguration__BaseAddress=http://lumina-api
+ depends_on:
+ - otel-collector
+ - lumina-api
+ healthcheck:
+ test: ["CMD-SHELL", "curl -sf http://localhost:5012/health/ready || exit 1"]
+ interval: 30s
+ timeout: 5s
+ retries: 3
+ start_period: 60s
+
+ otel-collector:
+ container_name: otel-collector
+ image: otel/opentelemetry-collector-contrib:0.159.0
+ command:
+ - "--config=/etc/otelcol/config.yml"
+ volumes:
+ - ./otel-collector/otel-collector-config.yml:/etc/otelcol/config.yml:ro
+ ports:
+ - "4317:4317"
+ - "4318:4318"
+ - "8889:8889"
+ depends_on:
+ - jaeger
+ restart: unless-stopped
+
+ jaeger:
+ container_name: jaeger
+ image: jaegertracing/all-in-one:1.76.0
+ environment:
+ - COLLECTOR_OTLP_ENABLED=true
+ ports:
+ - "16686:16686"
+ restart: unless-stopped
+
+ prometheus:
+ container_name: prometheus
+ image: prom/prometheus:v3
+ volumes:
+ - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
+ ports:
+ - "9090:9090"
+ depends_on:
+ - otel-collector
+ restart: unless-stopped
+
+ grafana:
+ container_name: grafana
+ image: grafana/grafana:13.0.7-ubuntu-slim
+ environment:
+ # dev-only stack: set a non-default admin password (override GRAFANA_ADMIN_PASSWORD in real deployments)
+ - GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_ADMIN_PASSWORD:-lumina-admin}
+ volumes:
+ - ./grafana/provisioning:/etc/grafana/provisioning:ro
+ - ./grafana/dashboards:/var/lib/grafana/dashboards:ro
+ ports:
+ - "127.0.0.1:3000:3000"
+ depends_on:
+ - prometheus
+ restart: unless-stopped
diff --git a/src/grafana/dashboards/lumina.json b/src/grafana/dashboards/lumina.json
new file mode 100644
index 00000000..27bdcc5c
--- /dev/null
+++ b/src/grafana/dashboards/lumina.json
@@ -0,0 +1,138 @@
+{
+ "annotations": {
+ "list": [
+ {
+ "builtIn": 1,
+ "datasource": {
+ "type": "grafana",
+ "uid": "-- Grafana --"
+ },
+ "enable": true,
+ "hide": true,
+ "iconColor": "rgba(0, 211, 255, 1)",
+ "name": "Annotations & Alerts",
+ "type": "dashboard"
+ }
+ ]
+ },
+ "editable": true,
+ "fiscalYearStartMonth": 0,
+ "graphTooltip": 1,
+ "id": null,
+ "links": [],
+ "panels": [
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "prometheus"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "ms"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 12,
+ "x": 0,
+ "y": 0
+ },
+ "id": 1,
+ "options": {
+ "legend": {
+ "displayMode": "list",
+ "placement": "bottom",
+ "showLegend": true
+ },
+ "tooltip": {
+ "mode": "multi",
+ "sort": "desc"
+ }
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "prometheus"
+ },
+ "expr": "histogram_quantile(0.95, sum(rate(lumina_application_handler_duration_bucket[5m])) by (le, lumina_handler_type))",
+ "legendFormat": "p95 {{lumina_handler_type}}",
+ "refId": "A"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "prometheus"
+ },
+ "expr": "histogram_quantile(0.50, sum(rate(lumina_application_handler_duration_bucket[5m])) by (le, lumina_handler_type))",
+ "legendFormat": "p50 {{lumina_handler_type}}",
+ "refId": "B"
+ }
+ ],
+ "title": "Application handler duration",
+ "type": "timeseries"
+ },
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "prometheus"
+ },
+ "fieldConfig": {
+ "defaults": {
+ "unit": "ops"
+ },
+ "overrides": []
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 12,
+ "x": 12,
+ "y": 0
+ },
+ "id": 2,
+ "options": {
+ "legend": {
+ "displayMode": "list",
+ "placement": "bottom",
+ "showLegend": true
+ },
+ "tooltip": {
+ "mode": "multi",
+ "sort": "desc"
+ }
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "prometheus",
+ "uid": "prometheus"
+ },
+ "expr": "sum(rate(lumina_application_handler_invocations_total[5m])) by (lumina_handler_type, lumina_outcome)",
+ "legendFormat": "{{lumina_handler_type}} {{lumina_outcome}}",
+ "refId": "A"
+ }
+ ],
+ "title": "Application handler invocations",
+ "type": "timeseries"
+ }
+ ],
+ "refresh": "10s",
+ "schemaVersion": 40,
+ "tags": [
+ "lumina",
+ "telemetry"
+ ],
+ "templating": {
+ "list": []
+ },
+ "time": {
+ "from": "now-15m",
+ "to": "now"
+ },
+ "timepicker": {},
+ "timezone": "",
+ "title": "Lumina",
+ "uid": "lumina-overview",
+ "version": 1
+}
diff --git a/src/grafana/provisioning/dashboards/dashboards.yml b/src/grafana/provisioning/dashboards/dashboards.yml
new file mode 100644
index 00000000..4a016440
--- /dev/null
+++ b/src/grafana/provisioning/dashboards/dashboards.yml
@@ -0,0 +1,12 @@
+apiVersion: 1
+
+providers:
+ - name: Lumina
+ orgId: 1
+ folder: Lumina
+ type: file
+ disableDeletion: false
+ updateIntervalSeconds: 30
+ allowUiUpdates: true
+ options:
+ path: /var/lib/grafana/dashboards
diff --git a/src/grafana/provisioning/datasources/datasources.yml b/src/grafana/provisioning/datasources/datasources.yml
new file mode 100644
index 00000000..27f1a57a
--- /dev/null
+++ b/src/grafana/provisioning/datasources/datasources.yml
@@ -0,0 +1,16 @@
+apiVersion: 1
+
+datasources:
+ - name: Prometheus
+ uid: prometheus
+ type: prometheus
+ access: proxy
+ url: http://prometheus:9090
+ isDefault: true
+ editable: true
+ - name: Jaeger
+ uid: jaeger
+ type: jaeger
+ access: proxy
+ url: http://jaeger:16686
+ editable: true
diff --git a/src/otel-collector/otel-collector-config.yml b/src/otel-collector/otel-collector-config.yml
new file mode 100644
index 00000000..74cb5735
--- /dev/null
+++ b/src/otel-collector/otel-collector-config.yml
@@ -0,0 +1,46 @@
+receivers:
+ otlp:
+ protocols:
+ grpc:
+ endpoint: 0.0.0.0:4317
+ http:
+ endpoint: 0.0.0.0:4318
+
+processors:
+ memory_limiter:
+ check_interval: 5s
+ limit_mib: 512
+ spike_limit_mib: 128
+ batch:
+
+exporters:
+ otlp/jaeger:
+ endpoint: jaeger:4317
+ tls:
+ insecure: true
+ prometheus:
+ endpoint: 0.0.0.0:8889
+
+extensions:
+ health_check:
+
+service:
+ extensions:
+ - health_check
+ pipelines:
+ traces:
+ receivers:
+ - otlp
+ processors:
+ - memory_limiter
+ - batch
+ exporters:
+ - otlp/jaeger
+ metrics:
+ receivers:
+ - otlp
+ processors:
+ - memory_limiter
+ - batch
+ exporters:
+ - prometheus
diff --git a/src/prometheus/prometheus.yml b/src/prometheus/prometheus.yml
new file mode 100644
index 00000000..0d185162
--- /dev/null
+++ b/src/prometheus/prometheus.yml
@@ -0,0 +1,9 @@
+global:
+ scrape_interval: 15s
+ evaluation_interval: 15s
+
+scrape_configs:
+ - job_name: otel-collector
+ static_configs:
+ - targets:
+ - otel-collector:8889
diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEventFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEventFixture.cs
new file mode 100644
index 00000000..329de61e
--- /dev/null
+++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEventFixture.cs
@@ -0,0 +1,33 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
+using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
+using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
+using System;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class LibrarySavedDomainEventFixture
+{
+ private readonly LibraryFixture _libraryFixture = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the domain event.
+ /// Optional. The library that was created or updated.
+ /// Optional. The date and time when the domain event occurred.
+ /// The created .
+ public LibrarySavedDomainEvent Create(Guid? id = null, Library? library = null, DateTime? occurredOnUtc = null)
+ {
+ return new LibrarySavedDomainEvent(
+ id ?? Guid.NewGuid(),
+ library ?? _libraryFixture.Create(),
+ occurredOnUtc ?? DateTime.UtcNow);
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/FailingDatabaseApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/FailingDatabaseApiFactory.cs
new file mode 100644
index 00000000..6b3bc6f8
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/FailingDatabaseApiFactory.cs
@@ -0,0 +1,32 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Api.Common.HealthChecks;
+using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.DependencyInjection.Extensions;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.IntegrationTests.Core.Health;
+
+///
+/// Factory whose database health check always reports an unhealthy state.
+///
+[ExcludeFromCodeCoverage]
+public class FailingDatabaseApiFactory : LuminaApiFactory
+{
+ ///
+ /// Configures the web host, replacing the database health check with one that always fails.
+ ///
+ /// The web host builder to configure.
+ protected override void ConfigureWebHost(IWebHostBuilder builder)
+ {
+ base.ConfigureWebHost(builder);
+ builder.ConfigureServices(services =>
+ {
+ // the health check resolves DatabaseHealthCheck from DI when it runs, so replacing its registration with a failing subclass makes /health/ready report Unhealthy
+ services.RemoveAll();
+ services.AddScoped();
+ });
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/FailingDatabaseHealthCheck.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/FailingDatabaseHealthCheck.cs
new file mode 100644
index 00000000..2d6a625c
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/FailingDatabaseHealthCheck.cs
@@ -0,0 +1,33 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Presentation.Api.Common.HealthChecks;
+using Microsoft.Extensions.Diagnostics.HealthChecks;
+using System.Diagnostics.CodeAnalysis;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.IntegrationTests.Core.Health;
+
+///
+/// Database health check that always reports an unhealthy state.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class FailingDatabaseHealthCheck : DatabaseHealthCheck
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected database context.
+ public FailingDatabaseHealthCheck(LuminaDbContext dbContext) : base(dbContext)
+ {
+ }
+
+ ///
+ /// Reports an unhealthy state without probing the database.
+ ///
+ public override Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken)
+ {
+ return Task.FromResult(HealthCheckResult.Unhealthy("database unavailable"));
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/HealthEndpointFailureTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/HealthEndpointFailureTests.cs
new file mode 100644
index 00000000..e99d50b3
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/HealthEndpointFailureTests.cs
@@ -0,0 +1,37 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.IntegrationTests.Core.Health;
+
+///
+/// Contains integration tests for the /health/ready probe route when the database is unreachable.
+///
+[ExcludeFromCodeCoverage]
+public class HealthEndpointFailureTests : IClassFixture
+{
+ private readonly HttpClient _client;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory with a failing database health check.
+ public HealthEndpointFailureTests(FailingDatabaseApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ }
+
+ [Fact]
+ public async Task HealthReady_WhenDatabaseIsUnreachable_ShouldReturnServiceUnavailable()
+ {
+ // Act
+ HttpResponseMessage response = await _client.GetAsync("/health/ready");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/HealthEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/HealthEndpointTests.cs
new file mode 100644
index 00000000..9fe5c4dd
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Health/HealthEndpointTests.cs
@@ -0,0 +1,68 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.IntegrationTests.Core.Health;
+
+///
+/// Contains integration tests for the /health/live and /health/ready probe routes.
+///
+[ExcludeFromCodeCoverage]
+public class HealthEndpointTests : IClassFixture
+{
+ private readonly HttpClient _client;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public HealthEndpointTests(LuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ }
+
+ [Fact]
+ public async Task HealthLive_WhenCalled_ShouldReturnOk()
+ {
+ // Act
+ HttpResponseMessage response = await _client.GetAsync("/health/live");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ }
+
+ [Fact]
+ public async Task HealthReady_WhenDatabaseIsReachable_ShouldReturnHealthyReport()
+ {
+ // Act
+ HttpResponseMessage response = await _client.GetAsync("/health/ready");
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ HealthReportDto report = JsonSerializer.Deserialize(content, _jsonOptions)!;
+ Assert.Equal("Healthy", report.Status);
+ HealthCheckReportDto databaseCheck = Assert.Single(report.Checks, check => check.Name == "database");
+ Assert.Equal("Healthy", databaseCheck.Status);
+ }
+
+ ///
+ /// Deserialized shape of the health report JSON written by the API.
+ ///
+ private sealed record HealthReportDto(string Status, List Checks);
+
+ ///
+ /// Deserialized shape of a single health check entry within the health report.
+ ///
+ private sealed record HealthCheckReportDto(string Name, string Status, string? Description);
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/HealthyApiReachabilityHealthCheck.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/HealthyApiReachabilityHealthCheck.cs
new file mode 100644
index 00000000..f0ee4f3c
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/HealthyApiReachabilityHealthCheck.cs
@@ -0,0 +1,37 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.Configuration;
+using Lumina.Presentation.Web.Common.HealthChecks;
+using Microsoft.Extensions.Diagnostics.HealthChecks;
+using Microsoft.Extensions.Options;
+using System.Diagnostics.CodeAnalysis;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Common.Setup;
+
+///
+/// API reachability health check that always reports a healthy state.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class HealthyApiReachabilityHealthCheck : ApiReachabilityHealthCheck
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected factory for creating HTTP clients.
+ /// Injected server configuration application settings.
+ public HealthyApiReachabilityHealthCheck(IHttpClientFactory httpClientFactory, IOptionsSnapshot serverConfigurationOptions)
+ : base(httpClientFactory, serverConfigurationOptions)
+ {
+ }
+
+ ///
+ /// Reports a healthy state without probing the API.
+ ///
+ public override Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken)
+ {
+ return Task.FromResult(HealthCheckResult.Healthy());
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs
index 0ade61d2..e36b6f1e 100644
--- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Common/Setup/LuminaWebFactory.cs
@@ -1,11 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web;
using Lumina.Presentation.Web.Common.Api;
+using Lumina.Presentation.Web.Common.HealthChecks;
using Lumina.Presentation.Web.Fixtures.Common.Api;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -58,6 +60,11 @@ public class LuminaWebFactory : WebApplicationFactory, IDisposable
foreach (ServiceDescriptor descriptor in apiClientDescriptors)
services.Remove(descriptor);
services.AddSingleton(ApiClientStub);
+
+ // the API reachability health check resolves ApiReachabilityHealthCheck from DI when it runs; replace its
+ // registration with a healthy subclass, since no real API exists during these tests
+ services.RemoveAll();
+ services.AddScoped();
});
}
}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/FailingApiHealthFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/FailingApiHealthFactory.cs
new file mode 100644
index 00000000..67403fea
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/FailingApiHealthFactory.cs
@@ -0,0 +1,31 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.HealthChecks;
+using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.DependencyInjection.Extensions;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Health;
+
+///
+/// Factory whose API reachability health check always reports an unhealthy state.
+///
+[ExcludeFromCodeCoverage]
+public class FailingApiHealthFactory : LuminaWebFactory
+{
+ ///
+ /// Configures the web host, replacing the API reachability health check with one that always fails.
+ ///
+ /// The web host builder to configure.
+ protected override void ConfigureWebHost(IWebHostBuilder builder)
+ {
+ base.ConfigureWebHost(builder);
+ builder.ConfigureServices(services =>
+ {
+ services.RemoveAll();
+ services.AddScoped();
+ });
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/HealthEndpointFailureTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/HealthEndpointFailureTests.cs
new file mode 100644
index 00000000..f474e79b
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/HealthEndpointFailureTests.cs
@@ -0,0 +1,41 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
+using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Health;
+
+///
+/// Contains integration tests for the /health/ready probe route when the API is unreachable.
+///
+[ExcludeFromCodeCoverage]
+public class HealthEndpointFailureTests : IClassFixture
+{
+ private readonly FailingApiHealthFactory _apiFactory;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory with a failing API reachability check.
+ public HealthEndpointFailureTests(FailingApiHealthFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task HealthReady_WhenApiIsUnreachable_ShouldReturnServiceUnavailable()
+ {
+ // Arrange
+ HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await client.GetAsync("/health/ready");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/HealthEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/HealthEndpointTests.cs
new file mode 100644
index 00000000..33c27851
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/HealthEndpointTests.cs
@@ -0,0 +1,56 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
+using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Health;
+
+///
+/// Contains integration tests for the /health/live and /health/ready probe routes.
+///
+[ExcludeFromCodeCoverage]
+public class HealthEndpointTests : IClassFixture
+{
+ private readonly LuminaWebFactory _apiFactory;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public HealthEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task HealthLive_WhenCalled_ShouldReturnOk()
+ {
+ // Arrange
+ HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await client.GetAsync("/health/live");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ }
+
+ [Fact]
+ public async Task HealthReady_WhenApiIsReachable_ShouldReturnHealthy()
+ {
+ // Arrange
+ HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await client.GetAsync("/health/ready");
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Contains("Healthy", content, System.StringComparison.OrdinalIgnoreCase);
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/UnhealthyApiReachabilityHealthCheck.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/UnhealthyApiReachabilityHealthCheck.cs
new file mode 100644
index 00000000..e66af15d
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Health/UnhealthyApiReachabilityHealthCheck.cs
@@ -0,0 +1,37 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.Configuration;
+using Lumina.Presentation.Web.Common.HealthChecks;
+using Microsoft.Extensions.Diagnostics.HealthChecks;
+using Microsoft.Extensions.Options;
+using System.Diagnostics.CodeAnalysis;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Health;
+
+///
+/// API reachability health check that always reports an unhealthy state.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class UnhealthyApiReachabilityHealthCheck : ApiReachabilityHealthCheck
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected factory for creating HTTP clients.
+ /// Injected server configuration application settings.
+ public UnhealthyApiReachabilityHealthCheck(IHttpClientFactory httpClientFactory, IOptionsSnapshot serverConfigurationOptions)
+ : base(httpClientFactory, serverConfigurationOptions)
+ {
+ }
+
+ ///
+ /// Reports an unhealthy state without probing the API.
+ ///
+ public override Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken)
+ {
+ return Task.FromResult(HealthCheckResult.Unhealthy("api unreachable"));
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryCommandHandlerDecoratorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryCommandHandlerDecoratorTests.cs
new file mode 100644
index 00000000..9b50bc16
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryCommandHandlerDecoratorTests.cs
@@ -0,0 +1,118 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.Telemetry;
+using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole;
+using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.AddRole;
+using Lumina.Contracts.Fixtures.Core.Responses.Authorization;
+using Lumina.Contracts.Responses.Authorization;
+using Lumina.Domain.Common.Primitives;
+using Microsoft.Extensions.Logging;
+using NSubstitute;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.Diagnostics.Metrics;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.UnitTests.Common.Telemetry;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class TelemetryCommandHandlerDecoratorTests
+{
+ private readonly ICommandHandler> _mockInnerHandler;
+ private readonly TelemetryCommandHandlerDecorator> _sut;
+ private readonly AddRoleCommandFixture _addRoleCommandFixture = new();
+ private readonly RolePermissionsResponseFixture _rolePermissionsResponseFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public TelemetryCommandHandlerDecoratorTests()
+ {
+ _mockInnerHandler = Substitute.For>>();
+ ILogger>> mockLogger =
+ Substitute.For>>>();
+ _sut = new TelemetryCommandHandlerDecorator>(
+ _mockInnerHandler,
+ mockLogger);
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenInnerHandlerSucceeds_ShouldDelegateAndEmitSuccessfulTraceAndMetric()
+ {
+ // Arrange
+ List capturedActivities = [];
+ using ActivityListener activityListener = TelemetryTestHelpers.CreateActivityListener(capturedActivities);
+ List<(string InstrumentName, double Value, string Outcome)> metricMeasurements = [];
+ using MeterListener meterListener = TelemetryTestHelpers.CreateMeterListener(metricMeasurements);
+ AddRoleCommand command = _addRoleCommandFixture.Create();
+ Result expectedResult = Result.Success(_rolePermissionsResponseFixture.Create());
+ _mockInnerHandler.HandleAsync(Arg.Any(), Arg.Any())
+ .Returns(expectedResult);
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.Equal(expectedResult, result);
+ await _mockInnerHandler.Received(1).HandleAsync(command, CancellationToken.None);
+ Activity activity = Assert.Single(capturedActivities);
+ Assert.Equal($"Handle {_mockInnerHandler.GetType().Name}", activity.OperationName);
+ Assert.Equal("command", activity.GetTagItem("lumina.handler.type"));
+ Assert.Equal(ActivityStatusCode.Ok, activity.Status);
+ Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.duration" && measurement.Outcome == "success");
+ Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.invocations" && measurement.Outcome == "success");
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenInnerHandlerReturnsFailedResult_ShouldReturnResultAndEmitFailureTraceAndMetric()
+ {
+ // Arrange
+ List capturedActivities = [];
+ using ActivityListener activityListener = TelemetryTestHelpers.CreateActivityListener(capturedActivities);
+ List<(string InstrumentName, double Value, string Outcome)> metricMeasurements = [];
+ using MeterListener meterListener = TelemetryTestHelpers.CreateMeterListener(metricMeasurements);
+ AddRoleCommand command = _addRoleCommandFixture.Create();
+ Result failedResult = Error.Failure("Test.Failed", "Test failure description");
+ _mockInnerHandler.HandleAsync(Arg.Any(), Arg.Any())
+ .Returns(failedResult);
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.Equal(failedResult, result);
+ Activity activity = Assert.Single(capturedActivities);
+ Assert.Equal(ActivityStatusCode.Error, activity.Status);
+ Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.duration" && measurement.Outcome == "failure");
+ Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.invocations" && measurement.Outcome == "failure");
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenInnerHandlerThrows_ShouldRethrowAndEmitFailureTraceAndMetric()
+ {
+ // Arrange
+ List capturedActivities = [];
+ using ActivityListener activityListener = TelemetryTestHelpers.CreateActivityListener(capturedActivities);
+ List<(string InstrumentName, double Value, string Outcome)> metricMeasurements = [];
+ using MeterListener meterListener = TelemetryTestHelpers.CreateMeterListener(metricMeasurements);
+ AddRoleCommand command = _addRoleCommandFixture.Create();
+ InvalidOperationException exception = new("boom");
+ _mockInnerHandler.HandleAsync(Arg.Any(), Arg.Any())
+ .Returns(Task.FromException>(exception));
+
+ // Act
+ await Assert.ThrowsAsync(() => _sut.HandleAsync(command, CancellationToken.None));
+
+ // Assert
+ Activity activity = Assert.Single(capturedActivities);
+ Assert.Equal(ActivityStatusCode.Error, activity.Status);
+ Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.duration" && measurement.Outcome == "failure");
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryDomainEventHandlerDecoratorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryDomainEventHandlerDecoratorTests.cs
new file mode 100644
index 00000000..8ad48a11
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryDomainEventHandlerDecoratorTests.cs
@@ -0,0 +1,88 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Telemetry;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
+using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
+using Microsoft.Extensions.Logging;
+using NSubstitute;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.Diagnostics.Metrics;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.UnitTests.Common.Telemetry;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class TelemetryDomainEventHandlerDecoratorTests
+{
+ private readonly IDomainEventHandler _mockInnerHandler;
+ private readonly TelemetryDomainEventHandlerDecorator _sut;
+ private readonly LibrarySavedDomainEventFixture _librarySavedDomainEventFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public TelemetryDomainEventHandlerDecoratorTests()
+ {
+ _mockInnerHandler = Substitute.For>();
+ ILogger> mockLogger =
+ Substitute.For>>();
+ _sut = new TelemetryDomainEventHandlerDecorator(
+ _mockInnerHandler,
+ mockLogger);
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenInnerHandlerSucceeds_ShouldDelegateAndEmitSuccessfulTraceAndMetric()
+ {
+ // Arrange
+ List capturedActivities = [];
+ using ActivityListener activityListener = TelemetryTestHelpers.CreateActivityListener(capturedActivities);
+ List<(string InstrumentName, double Value, string Outcome)> metricMeasurements = [];
+ using MeterListener meterListener = TelemetryTestHelpers.CreateMeterListener(metricMeasurements);
+ LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create();
+ _mockInnerHandler.HandleAsync(Arg.Any(), Arg.Any())
+ .Returns(ValueTask.CompletedTask);
+
+ // Act
+ await _sut.HandleAsync(domainEvent, CancellationToken.None);
+
+ // Assert
+ await _mockInnerHandler.Received(1).HandleAsync(domainEvent, CancellationToken.None);
+ Activity activity = Assert.Single(capturedActivities);
+ Assert.Equal($"Handle {_mockInnerHandler.GetType().Name}", activity.OperationName);
+ Assert.Equal("domain-event", activity.GetTagItem("lumina.handler.type"));
+ Assert.Equal(ActivityStatusCode.Ok, activity.Status);
+ Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.duration" && measurement.Outcome == "success");
+ Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.invocations" && measurement.Outcome == "success");
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenInnerHandlerThrows_ShouldRethrowAndEmitFailureTraceAndMetric()
+ {
+ // Arrange
+ List capturedActivities = [];
+ using ActivityListener activityListener = TelemetryTestHelpers.CreateActivityListener(capturedActivities);
+ List<(string InstrumentName, double Value, string Outcome)> metricMeasurements = [];
+ using MeterListener meterListener = TelemetryTestHelpers.CreateMeterListener(metricMeasurements);
+ LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create();
+ InvalidOperationException exception = new("boom");
+ _mockInnerHandler.HandleAsync(Arg.Any(), Arg.Any())
+ .Returns(ValueTask.FromException(exception));
+
+ // Act
+ await Assert.ThrowsAsync(() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
+
+ // Assert
+ Activity activity = Assert.Single(capturedActivities);
+ Assert.Equal(ActivityStatusCode.Error, activity.Status);
+ Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.duration" && measurement.Outcome == "failure");
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryQueryHandlerDecoratorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryQueryHandlerDecoratorTests.cs
new file mode 100644
index 00000000..85271099
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryQueryHandlerDecoratorTests.cs
@@ -0,0 +1,118 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.Telemetry;
+using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions;
+using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Queries.GetRolePermissions;
+using Lumina.Contracts.Fixtures.Core.Responses.Authorization;
+using Lumina.Contracts.Responses.Authorization;
+using Lumina.Domain.Common.Primitives;
+using Microsoft.Extensions.Logging;
+using NSubstitute;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.Diagnostics.Metrics;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.UnitTests.Common.Telemetry;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class TelemetryQueryHandlerDecoratorTests
+{
+ private readonly IQueryHandler> _mockInnerHandler;
+ private readonly TelemetryQueryHandlerDecorator> _sut;
+ private readonly GetRolePermissionsQueryFixture _getRolePermissionsQueryFixture = new();
+ private readonly RolePermissionsResponseFixture _rolePermissionsResponseFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public TelemetryQueryHandlerDecoratorTests()
+ {
+ _mockInnerHandler = Substitute.For>>();
+ ILogger>> mockLogger =
+ Substitute.For>>>();
+ _sut = new TelemetryQueryHandlerDecorator>(
+ _mockInnerHandler,
+ mockLogger);
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenInnerHandlerSucceeds_ShouldDelegateAndEmitSuccessfulTraceAndMetric()
+ {
+ // Arrange
+ List capturedActivities = [];
+ using ActivityListener activityListener = TelemetryTestHelpers.CreateActivityListener(capturedActivities);
+ List<(string InstrumentName, double Value, string Outcome)> metricMeasurements = [];
+ using MeterListener meterListener = TelemetryTestHelpers.CreateMeterListener(metricMeasurements);
+ GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.Create();
+ Result expectedResult = Result.Success(_rolePermissionsResponseFixture.Create());
+ _mockInnerHandler.HandleAsync(Arg.Any(), Arg.Any())
+ .Returns(expectedResult);
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.Equal(expectedResult, result);
+ await _mockInnerHandler.Received(1).HandleAsync(query, CancellationToken.None);
+ Activity activity = Assert.Single(capturedActivities);
+ Assert.Equal($"Handle {_mockInnerHandler.GetType().Name}", activity.OperationName);
+ Assert.Equal("query", activity.GetTagItem("lumina.handler.type"));
+ Assert.Equal(ActivityStatusCode.Ok, activity.Status);
+ Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.duration" && measurement.Outcome == "success");
+ Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.invocations" && measurement.Outcome == "success");
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenInnerHandlerReturnsFailedResult_ShouldReturnResultAndEmitFailureTraceAndMetric()
+ {
+ // Arrange
+ List capturedActivities = [];
+ using ActivityListener activityListener = TelemetryTestHelpers.CreateActivityListener(capturedActivities);
+ List<(string InstrumentName, double Value, string Outcome)> metricMeasurements = [];
+ using MeterListener meterListener = TelemetryTestHelpers.CreateMeterListener(metricMeasurements);
+ GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.Create();
+ Result failedResult = Error.Failure("Test.Failed", "Test failure description");
+ _mockInnerHandler.HandleAsync(Arg.Any(), Arg.Any())
+ .Returns(failedResult);
+
+ // Act
+ Result result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.Equal(failedResult, result);
+ Activity activity = Assert.Single(capturedActivities);
+ Assert.Equal(ActivityStatusCode.Error, activity.Status);
+ Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.duration" && measurement.Outcome == "failure");
+ Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.invocations" && measurement.Outcome == "failure");
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenInnerHandlerThrows_ShouldRethrowAndEmitFailureTraceAndMetric()
+ {
+ // Arrange
+ List capturedActivities = [];
+ using ActivityListener activityListener = TelemetryTestHelpers.CreateActivityListener(capturedActivities);
+ List<(string InstrumentName, double Value, string Outcome)> metricMeasurements = [];
+ using MeterListener meterListener = TelemetryTestHelpers.CreateMeterListener(metricMeasurements);
+ GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.Create();
+ InvalidOperationException exception = new("boom");
+ _mockInnerHandler.HandleAsync(Arg.Any(), Arg.Any())
+ .Returns(Task.FromException>(exception));
+
+ // Act
+ await Assert.ThrowsAsync(() => _sut.HandleAsync(query, CancellationToken.None));
+
+ // Assert
+ Activity activity = Assert.Single(capturedActivities);
+ Assert.Equal(ActivityStatusCode.Error, activity.Status);
+ Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.duration" && measurement.Outcome == "failure");
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryTestHelpers.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryTestHelpers.cs
new file mode 100644
index 00000000..64c03f30
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryTestHelpers.cs
@@ -0,0 +1,71 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Telemetry;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.Diagnostics.Metrics;
+#endregion
+
+namespace Lumina.Application.UnitTests.Common.Telemetry;
+
+///
+/// Test utilities for capturing the traces and metrics emitted by the application telemetry.
+///
+[ExcludeFromCodeCoverage]
+internal static class TelemetryTestHelpers
+{
+ ///
+ /// Creates an that captures every activity emitted by the activity source.
+ ///
+ /// The collection that stopped activities are added to.
+ /// The started .
+ public static ActivityListener CreateActivityListener(ICollection capturedActivities)
+ {
+ ActivityListener listener = new()
+ {
+ ShouldListenTo = source => source.Name == ApplicationTelemetry.SOURCE_NAME,
+ Sample = (ref ActivityCreationOptions options) => ActivitySamplingResult.AllData,
+ ActivityStopped = activity => capturedActivities.Add(activity)
+ };
+ ActivitySource.AddActivityListener(listener);
+ return listener;
+ }
+
+ ///
+ /// Creates a that captures every measurement emitted by the meter.
+ ///
+ /// The collection that measurements are added to.
+ /// The started .
+ public static MeterListener CreateMeterListener(ICollection<(string InstrumentName, double Value, string Outcome)> measurements)
+ {
+ MeterListener listener = new()
+ {
+ InstrumentPublished = (instrument, meterListener) =>
+ {
+ if (instrument.Meter.Name == ApplicationTelemetry.SOURCE_NAME)
+ meterListener.EnableMeasurementEvents(instrument);
+ }
+ };
+ // InstrumentPublished fires for instruments created after Start(), and Start() also replays every instrument
+ // that already exists on the meter; therefore the lazily-initialized static handler instruments are captured by
+ // every listener, whether they were created before or during the test
+ listener.SetMeasurementEventCallback((instrument, value, tags, state) => measurements.Add((instrument.Name, value, GetOutcomeTag(tags))));
+ listener.SetMeasurementEventCallback((instrument, value, tags, state) => measurements.Add((instrument.Name, value, GetOutcomeTag(tags))));
+ listener.Start();
+ return listener;
+ }
+
+ ///
+ /// Reads the value of the lumina.outcome tag from the specified tag list.
+ ///
+ /// The tag list of a measurement.
+ /// The outcome tag value, or an empty string when the tag is not present.
+ private static string GetOutcomeTag(ReadOnlySpan> tags)
+ {
+ foreach (KeyValuePair tag in tags)
+ if (tag.Key == "lumina.outcome")
+ return tag.Value?.ToString() ?? string.Empty;
+ return string.Empty;
+ }
+}