Merge pull request #162 from BinaryAlley/feature/application-telemetry-and-observability

Feature/application telemetry and observability
This commit is contained in:
BinaryAlley authored and GitHub committed 2026-08-22 06:35:36 -07:00
commit c9c517cf1e
46 files changed
+2020 -25

No files matched your search

+43
View File
@@ -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) 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. - 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 ## 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! 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) - [`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) - [`stop.svg`](https://www.svgrepo.com/svg/521862/stop) (CC Attribution License)
**I greatly appreciate the creators and contributors for providing these assets.**
## License ## License
This project is licensed under the GPLv3.0. See the [LICENSE](./LICENSE.md) file for details. This project is licensed under the GPLv3.0. See the [LICENSE](./LICENSE.md) file for details.
@@ -1,4 +1,5 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Telemetry;
using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Events;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using System; using System;
@@ -46,9 +47,18 @@ public static class ApplicationLayerServices
continue; continue;
if (registration.Contract.GetGenericTypeDefinition() == typeof(Infrastructure.Validation.IValidator<>)) if (registration.Contract.GetGenericTypeDefinition() == typeof(Infrastructure.Validation.IValidator<>))
{
services.AddSingleton(registration.Contract, registration.Implementation); services.AddSingleton(registration.Contract, registration.Implementation);
else continue;
services.AddScoped(registration.Contract, registration.Implementation); }
// 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; return services;
@@ -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;
/// <summary>
/// Helper that emits the traces, metrics, and structured logs for the execution of application handlers.
/// </summary>
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<double> s_handlerDuration = ApplicationTelemetry.Meter.CreateHistogram<double>(
name: HANDLER_DURATION_METRIC_NAME,
description: "Duration in milliseconds of the execution of an application handler.");
private static readonly Counter<long> s_handlerInvocations = ApplicationTelemetry.Meter.CreateCounter<long>(
name: HANDLER_INVOCATIONS_METRIC_NAME,
description: "Number of invocations of an application handler.");
/// <summary>
/// Starts a new <see cref="Activity"/> for the execution of the handler with the specified name.
/// </summary>
/// <param name="handlerName">The name of the handler being executed.</param>
/// <param name="handlerType">The type of the handler being executed.</param>
/// <returns>The started activity, or <see langword="null"/> when no trace listener is registered.</returns>
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;
}
/// <summary>
/// Records the successful completion of a handler execution, including its trace status, metrics, and a structured log entry.
/// </summary>
/// <param name="logger">The logger to write the structured log entry to.</param>
/// <param name="activity">The activity to mark as successful.</param>
/// <param name="handlerName">The name of the handled handler.</param>
/// <param name="handlerType">The type of the handled handler.</param>
/// <param name="duration">The duration of the handler execution.</param>
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);
}
/// <summary>
/// Records the failed completion of a handler execution, including its trace status, metrics, and a structured log entry.
/// </summary>
/// <param name="logger">The logger to write the structured log entry to.</param>
/// <param name="activity">The activity to mark as failed.</param>
/// <param name="handlerName">The name of the handled handler.</param>
/// <param name="handlerType">The type of the handled handler.</param>
/// <param name="duration">The duration of the handler execution.</param>
/// <param name="error">An optional description of the failure.</param>
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);
}
/// <summary>
/// Records the exceptional completion of a handler execution, including its trace status, metrics, and a structured log entry.
/// </summary>
/// <param name="logger">The logger to write the structured log entry to.</param>
/// <param name="activity">The activity to mark as failed.</param>
/// <param name="handlerName">The name of the handled handler.</param>
/// <param name="handlerType">The type of the handled handler.</param>
/// <param name="exception">The exception that was thrown during the handler execution.</param>
/// <param name="duration">The duration of the handler execution.</param>
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);
}
/// <summary>
/// Records the invocation count and duration of a handler execution into the corresponding metrics, and tags the activity with the outcome.
/// </summary>
/// <param name="activity">The activity to tag with the outcome.</param>
/// <param name="handlerName">The name of the handled handler.</param>
/// <param name="handlerType">The type of the handled handler.</param>
/// <param name="duration">The duration of the handler execution.</param>
/// <param name="isSuccess">Whether the handler execution completed successfully.</param>
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");
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
using System.Diagnostics.Metrics;
#endregion
namespace Lumina.Application.Common.Telemetry;
/// <summary>
/// Central registry of the <see cref="ActivitySource"/> and <see cref="Meter"/> used by the Application layer to emit traces and metrics.
/// </summary>
public static class ApplicationTelemetry
{
/// <summary>
/// The source name shared by the <see cref="ActivitySource"/> and <see cref="Meter"/> of the Application layer.
/// </summary>
public const string SOURCE_NAME = "Lumina.Application";
/// <summary>
/// The source of the traces emitted by the Application layer.
/// </summary>
public static ActivitySource ActivitySource { get; } = new(SOURCE_NAME);
/// <summary>
/// The source of the metrics emitted by the Application layer.
/// </summary>
public static Meter Meter { get; } = new(SOURCE_NAME);
}
@@ -0,0 +1,63 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Concurrent;
using System.Reflection;
#endregion
namespace Lumina.Application.Common.Telemetry;
/// <summary>
/// Detects the outcome of an application handler result in a generic way, without coupling the telemetry decorators to any concrete result type.
/// </summary>
internal static class HandlerOutcomeDetector
{
private static readonly ConcurrentDictionary<Type, PropertyInfo?> s_isSuccessPropertyCache = new();
private static readonly ConcurrentDictionary<Type, PropertyInfo?> s_firstErrorPropertyCache = new();
private static readonly ConcurrentDictionary<Type, PropertyInfo?> s_errorDescriptionPropertyCache = new();
/// <summary>
/// Determines whether the specified result represents a successful outcome.
/// </summary>
/// <param name="result">The result returned by an application handler, or <see langword="null"/>.</param>
/// <returns>
/// <see langword="true"/> when the result reports success, when it is <see langword="null"/>, or when it exposes no success flag.
/// </returns>
/// <remarks>
/// Handlers that return plain DTOs (no <c>IsSuccess</c> property) cannot express a failure and are reported as successful;
/// only handlers returning a result type such as <see cref="Domain.Common.Primitives.Result{TValue}"/> report failures.
/// </remarks>
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)!;
}
/// <summary>
/// Gets a human-readable description of the first error of a failed result, when the result exposes one.
/// </summary>
/// <param name="result">The failed result returned by an application handler, or <see langword="null"/>.</param>
/// <returns>The description of the first error, or <see langword="null"/> when the result exposes no errors.</returns>
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();
}
/// <summary>
/// Gets the public instance <c>IsSuccess</c> property of the specified type, if it has one.
/// </summary>
/// <param name="type">The type to inspect.</param>
/// <returns>The <c>IsSuccess</c> property, or <see langword="null"/> when the type does not expose one.</returns>
private static PropertyInfo? GetIsSuccessProperty(Type type)
{
return s_isSuccessPropertyCache.GetOrAdd(type, candidateType => candidateType.GetProperty("IsSuccess", BindingFlags.Public | BindingFlags.Instance));
}
}
@@ -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;
/// <summary>
/// Decorator that wraps an <see cref="ICommandHandler{TCommand,TResult}"/> to emit traces, metrics, and structured logs for every command execution.
/// </summary>
/// <typeparam name="TCommand">The type of command to handle.</typeparam>
/// <typeparam name="TResult">The type of result returned after handling the command.</typeparam>
public class TelemetryCommandHandlerDecorator<TCommand, TResult> : ICommandHandler<TCommand, TResult> where TCommand : ICommand
{
private const string HANDLER_TYPE = "command";
private readonly ICommandHandler<TCommand, TResult> _innerHandler;
private readonly ILogger<TelemetryCommandHandlerDecorator<TCommand, TResult>> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="TelemetryCommandHandlerDecorator{TCommand,TResult}"/> class.
/// </summary>
/// <param name="innerHandler">The wrapped command handler.</param>
/// <param name="logger">Injected logger used for structured logging.</param>
public TelemetryCommandHandlerDecorator(ICommandHandler<TCommand, TResult> innerHandler, ILogger<TelemetryCommandHandlerDecorator<TCommand, TResult>> logger)
{
_innerHandler = innerHandler;
_logger = logger;
}
/// <summary>
/// Handles the specified command, emitting telemetry around the execution of the wrapped handler.
/// </summary>
/// <param name="command">The command to handle.</param>
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous operation, containing the result of the command execution.</returns>
public async Task<TResult> 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;
}
}
}
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Domain.Common.Events;
using System;
#endregion
namespace Lumina.Application.Common.Telemetry;
/// <summary>
/// Resolves the telemetry decorator type that wraps a given application handler contract.
/// </summary>
internal static class TelemetryDecoratorFactory
{
/// <summary>
/// Gets the closed telemetry decorator type for the specified handler contract.
/// </summary>
/// <param name="contract">The handler contract to wrap.</param>
/// <returns>The closed generic telemetry decorator type for the contract.</returns>
/// <exception cref="ArgumentException">Thrown when the contract has no matching telemetry decorator.</exception>
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));
}
}
@@ -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;
/// <summary>
/// Decorator that wraps an <see cref="IDomainEventHandler{TDomainEvent}"/> to emit traces, metrics, and structured logs for every domain event handling.
/// </summary>
/// <typeparam name="TDomainEvent">The type of domain event to handle.</typeparam>
public class TelemetryDomainEventHandlerDecorator<TDomainEvent> : IDomainEventHandler<TDomainEvent> where TDomainEvent : IDomainEvent
{
private const string HANDLER_TYPE = "domain-event";
private readonly IDomainEventHandler<TDomainEvent> _innerHandler;
private readonly ILogger<TelemetryDomainEventHandlerDecorator<TDomainEvent>> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="TelemetryDomainEventHandlerDecorator{TDomainEvent}"/> class.
/// </summary>
/// <param name="innerHandler">The wrapped domain event handler.</param>
/// <param name="logger">Injected logger used for structured logging.</param>
public TelemetryDomainEventHandlerDecorator(IDomainEventHandler<TDomainEvent> innerHandler, ILogger<TelemetryDomainEventHandlerDecorator<TDomainEvent>> logger)
{
_innerHandler = innerHandler;
_logger = logger;
}
/// <summary>
/// Handles the specified domain event, emitting telemetry around the execution of the wrapped handler.
/// </summary>
/// <param name="domainEvent">The domain event to handle.</param>
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
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;
}
}
}
}
@@ -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;
/// <summary>
/// Decorator that wraps an <see cref="IQueryHandler{TQuery,TResult}"/> to emit traces, metrics, and structured logs for every query execution.
/// </summary>
/// <typeparam name="TQuery">The type of query to handle.</typeparam>
/// <typeparam name="TResult">The type of result returned after handling the query.</typeparam>
public class TelemetryQueryHandlerDecorator<TQuery, TResult> : IQueryHandler<TQuery, TResult> where TQuery : IQuery
{
private const string HANDLER_TYPE = "query";
private readonly IQueryHandler<TQuery, TResult> _innerHandler;
private readonly ILogger<TelemetryQueryHandlerDecorator<TQuery, TResult>> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="TelemetryQueryHandlerDecorator{TQuery,TResult}"/> class.
/// </summary>
/// <param name="innerHandler">The wrapped query handler.</param>
/// <param name="logger">Injected logger used for structured logging.</param>
public TelemetryQueryHandlerDecorator(IQueryHandler<TQuery, TResult> innerHandler, ILogger<TelemetryQueryHandlerDecorator<TQuery, TResult>> logger)
{
_innerHandler = innerHandler;
_logger = logger;
}
/// <summary>
/// Handles the specified query, emitting telemetry around the execution of the wrapped handler.
/// </summary>
/// <param name="query">The query to handle.</param>
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous operation, containing the result of the query execution.</returns>
public async Task<TResult> 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;
}
}
}
}
@@ -29,6 +29,7 @@ internal static class PresentationApiLayerConfiguration
configuration.SetBasePath(basePath); configuration.SetBasePath(basePath);
configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
configuration.AddJsonFile("appsettings.development.json", optional: true, reloadOnChange: true); configuration.AddJsonFile("appsettings.development.json", optional: true, reloadOnChange: true);
configuration.AddEnvironmentVariables(); // environment variables should override the configuration files
return services; return services;
} }
@@ -3,6 +3,7 @@ using FastEndpoints;
using FastEndpoints.Swagger; using FastEndpoints.Swagger;
using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Presentation.Api.Common.Authentication; using Lumina.Presentation.Api.Common.Authentication;
using Lumina.Presentation.Api.Common.HealthChecks;
using MessagePack; using MessagePack;
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
@@ -10,6 +11,7 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Json; using Microsoft.AspNetCore.Http.Json;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using System; using System;
@@ -39,6 +41,10 @@ public static class PresentationApiLayerServices
services.AddMemoryCache(); // used for the tracking involved in authentication rate limiting services.AddMemoryCache(); // used for the tracking involved in authentication rate limiting
services.AddProblemDetails(); 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<DatabaseHealthCheck>("database", HealthStatus.Unhealthy, ["ready"]);
services.Configure<JsonOptions>(jsonOptions => services.Configure<JsonOptions>(jsonOptions =>
{ {
jsonOptions.SerializerOptions.Converters.Add(new JsonStringEnumConverter()); jsonOptions.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
@@ -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;
/// <summary>
/// Contains the OpenTelemetry services of the Presentation API layer.
/// </summary>
[ExcludeFromCodeCoverage]
public static class PresentationApiTelemetryServices
{
private const string SERVICE_NAME = "Lumina.Api";
private const string ENTITY_FRAMEWORK_CORE_METER_NAME = "Microsoft.EntityFrameworkCore";
/// <summary>
/// Registers the OpenTelemetry tracing and metrics pipelines into the dependency injection container.
/// </summary>
/// <param name="services">The service collection to add the services to.</param>
/// <param name="configuration">Application configuration properties.</param>
/// <param name="environment">The hosting environment of the application.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddPresentationApiTelemetryServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment)
{
bool isTelemetryEnabled = configuration.GetValue<bool?>("Telemetry:Enabled") ?? true;
if (!isTelemetryEnabled)
return services;
bool isConsoleExporterEnabled = configuration.GetValue<bool?>("Telemetry:ConsoleExporterEnabled") ?? environment.IsDevelopment();
string? otlpEndpoint = GetOtlpEndpoint(configuration);
double traceSampleRatio = configuration.GetValue<double?>("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<string, object>
{
["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;
}
/// <summary>
/// Gets the OTLP exporter endpoint from configuration, falling back to the standard <c>OTEL_EXPORTER_OTLP_ENDPOINT</c> environment variable.
/// </summary>
/// <param name="configuration">Application configuration properties.</param>
/// <returns>The OTLP endpoint, or <see langword="null"/> when no endpoint is configured.</returns>
private static string? GetOtlpEndpoint(IConfiguration configuration)
{
string? endpoint = configuration.GetValue<string?>("Telemetry:Otlp:Endpoint");
if (string.IsNullOrWhiteSpace(endpoint))
endpoint = Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_ENDPOINT");
return string.IsNullOrWhiteSpace(endpoint) ? null : endpoint;
}
/// <summary>
/// Creates the trace sampler used by the API, sampling every trace by default and honoring the configured ratio for production traffic.
/// </summary>
/// <param name="traceSampleRatio">The ratio of traces to sample, in the range of zero to one.</param>
/// <returns>The configured trace sampler.</returns>
private static Sampler CreateSampler(double traceSampleRatio)
{
return traceSampleRatio < 1.0
? new ParentBasedSampler(new TraceIdRatioBasedSampler(traceSampleRatio))
: new AlwaysOnSampler();
}
}
@@ -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;
/// <summary>
/// Health check that verifies the database can be reached.
/// </summary>
public class DatabaseHealthCheck : IHealthCheck
{
private readonly LuminaDbContext _dbContext;
/// <summary>
/// Initializes a new instance of the <see cref="DatabaseHealthCheck"/> class.
/// </summary>
/// <param name="dbContext">Injected database context.</param>
public DatabaseHealthCheck(LuminaDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Checks whether the database can be reached.
/// </summary>
/// <param name="context">The health check context.</param>
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous operation, containing the health check result.</returns>
public virtual async Task<HealthCheckResult> 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);
}
}
}
+9 -1
View File
@@ -1,6 +1,10 @@
# This stage is used when running from VS in fast mode (Default for Debug configuration) # 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 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 USER app
WORKDIR /app WORKDIR /app
EXPOSE 5214 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.Application/Lumina.Application.csproj", "Lumina.Application/"]
COPY ["Lumina.Contracts/Lumina.Contracts.csproj", "Lumina.Contracts/"] COPY ["Lumina.Contracts/Lumina.Contracts.csproj", "Lumina.Contracts/"]
COPY ["Lumina.Domain/Lumina.Domain.csproj", "Lumina.Domain/"] 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.Infrastructure/Lumina.Infrastructure.csproj", "Lumina.Infrastructure/"]
COPY ["Lumina.DataAccess/Lumina.DataAccess.csproj", "Lumina.DataAccess/"] 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/ RUN dotnet restore "./Lumina.Presentation.Api/Lumina.Presentation.Api.csproj" /p:BaseOutputPath=/app/publish/
@@ -49,6 +55,8 @@ FROM base AS final
WORKDIR /app WORKDIR /app
COPY --from=publish /app/publish . 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 ENV ASPNETCORE_HTTP_PORTS=5214
EXPOSE 5214 EXPOSE 5214
ENTRYPOINT ["dotnet", "Lumina.Presentation.Api.dll"] ENTRYPOINT ["dotnet", "Lumina.Presentation.Api.dll"]
@@ -31,10 +31,17 @@
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="OpenTelemetry" Version="1.18.0" />
<PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.18.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.18.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.18.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.18.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.18.0" />
<PackageReference Include="Scalar.AspNetCore" Version="2.16.20" /> <PackageReference Include="Scalar.AspNetCore" Version="2.16.20" />
<PackageReference Include="Serilog" Version="4.4.0" /> <PackageReference Include="Serilog" Version="4.4.0" />
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" /> <PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
<PackageReference Include="Serilog.Enrichers.AspnetcoreHttpcontext" Version="1.1.0" /> <PackageReference Include="Serilog.Enrichers.AspnetcoreHttpcontext" Version="1.1.0" />
<PackageReference Include="Serilog.Enrichers.Span" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="10.0.1" /> <PackageReference Include="Serilog.Settings.Configuration" Version="10.0.1" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" /> <PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" /> <PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
+40 -2
View File
@@ -12,11 +12,14 @@ using Lumina.Presentation.Api.Common.DependencyInjection;
using Lumina.Presentation.Api.Common.Middlewares; using Lumina.Presentation.Api.Common.Middlewares;
using Lumina.Presentation.Api.Common.Utilities; using Lumina.Presentation.Api.Common.Utilities;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Scalar.AspNetCore; using Scalar.AspNetCore;
@@ -24,6 +27,7 @@ using Serilog;
using System; using System;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.IO; using System.IO;
using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
#endregion #endregion
@@ -47,6 +51,7 @@ public class Program
builder.Services.BindPresentationApiLayerConfiguration(builder.Configuration); builder.Services.BindPresentationApiLayerConfiguration(builder.Configuration);
builder.Services.AddPresentationApiLayerServices(builder.Configuration); builder.Services.AddPresentationApiLayerServices(builder.Configuration);
builder.Services.AddPresentationApiTelemetryServices(builder.Configuration, builder.Environment);
builder.Services.AddApplicationLayerServices(); builder.Services.AddApplicationLayerServices();
builder.Services.AddInfrastructureLayerServices(builder.Configuration); builder.Services.AddInfrastructureLayerServices(builder.Configuration);
builder.Services.AddDataAccessLayerServices(); builder.Services.AddDataAccessLayerServices();
@@ -137,8 +142,9 @@ public class Program
.WithDotNetFlag(true); .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 // 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<EventualConsistencyMiddleware>()); // 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<EventualConsistencyMiddleware>());
// 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 // 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<string>("MediaSettings:RootDirectory") ?? string.Empty; string mediaRootDirectoryPathSetting = app.Configuration.GetValue<string>("MediaSettings:RootDirectory") ?? string.Empty;
@@ -165,6 +171,38 @@ public class Program
app.MapHub<MediaLibraryScanProgressHub>("/scanProgressHub"); app.MapHub<MediaLibraryScanProgressHub>("/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); await app.RunAsync().ConfigureAwait(false);
} }
/// <summary>
/// Writes the health report as a JSON response.
/// </summary>
/// <param name="httpContext">The current HTTP context.</param>
/// <param name="healthReport">The health report to write.</param>
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
})
});
}
} }
+11 -9
View File
@@ -24,7 +24,7 @@
"Name": "Console", "Name": "Console",
"Args": { "Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console", "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": { "Args": {
"path": "%LOG_PATH%lumina_api_.log", "path": "%LOG_PATH%lumina_api_.log",
"rollingInterval": "Day", "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, "retainedFileCountLimit": 7,
"fileSizeLimitBytes": 10485760, "fileSizeLimitBytes": 10485760,
"rollOnFileSizeLimit": true, "rollOnFileSizeLimit": true,
@@ -45,7 +45,8 @@
"FromLogContext", "FromLogContext",
"WithMachineName", "WithMachineName",
"WithThreadId", "WithThreadId",
"WithEnvironmentName" "WithEnvironmentName",
"WithSpan"
], ],
"Properties": { "Properties": {
"Application": "LuminaApi" "Application": "LuminaApi"
@@ -57,11 +58,12 @@
"http://localhost:5012" "http://localhost:5012"
] ]
}, },
"Kestrel": { "Telemetry": {
"Endpoints": { "Enabled": true,
"Http": { "ConsoleExporterEnabled": false,
"Url": "http://localhost:5214" "Otlp": {
} "Endpoint": ""
} },
"TraceSampleRatio": 0.25 // production default; override to 1.0 in the development configuration for full trace capture
} }
} }
@@ -25,7 +25,8 @@ internal static class PresentationWebLayerConfiguration
// add the configuration sources to the configuration builder // add the configuration sources to the configuration builder
configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
configuration.AddJsonFile("appsettings.development.json", optional: true, reloadOnChange: true); configuration.AddJsonFile("appsettings.development.json", optional: true, reloadOnChange: true);
configuration.AddEnvironmentVariables(); // environment variables should override the configuration files
serviceCollection.AddOptions<ServerConfigurationDto>() serviceCollection.AddOptions<ServerConfigurationDto>()
.Bind(configuration.GetRequiredSection(ServerConfigurationDto.SECTION_NAME)) .Bind(configuration.GetRequiredSection(ServerConfigurationDto.SECTION_NAME))
.ValidateFluently() .ValidateFluently()
@@ -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;
/// <summary>
/// Contains the OpenTelemetry services of the Presentation Web layer.
/// </summary>
[ExcludeFromCodeCoverage]
public static class PresentationWebTelemetryServices
{
private const string SERVICE_NAME = "Lumina.Web";
/// <summary>
/// Registers the OpenTelemetry tracing and metrics pipelines into the dependency injection container.
/// </summary>
/// <param name="services">The service collection to add the services to.</param>
/// <param name="configuration">Application configuration properties.</param>
/// <param name="environment">The hosting environment of the application.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddPresentationWebTelemetryServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment)
{
bool isTelemetryEnabled = configuration.GetValue<bool?>("Telemetry:Enabled") ?? true;
if (!isTelemetryEnabled)
return services;
bool isConsoleExporterEnabled = configuration.GetValue<bool?>("Telemetry:ConsoleExporterEnabled") ?? environment.IsDevelopment();
string? otlpEndpoint = GetOtlpEndpoint(configuration);
double traceSampleRatio = configuration.GetValue<double?>("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<string, object>
{
["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;
}
/// <summary>
/// Gets the OTLP exporter endpoint from configuration, falling back to the standard <c>OTEL_EXPORTER_OTLP_ENDPOINT</c> environment variable.
/// </summary>
/// <param name="configuration">Application configuration properties.</param>
/// <returns>The OTLP endpoint, or <see langword="null"/> when no endpoint is configured.</returns>
private static string? GetOtlpEndpoint(IConfiguration configuration)
{
string? endpoint = configuration.GetValue<string?>("Telemetry:Otlp:Endpoint");
if (string.IsNullOrWhiteSpace(endpoint))
endpoint = Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_ENDPOINT");
return string.IsNullOrWhiteSpace(endpoint) ? null : endpoint;
}
/// <summary>
/// Creates the trace sampler used by the Web application, sampling every trace by default and honoring the configured ratio for production traffic.
/// </summary>
/// <param name="traceSampleRatio">The ratio of traces to sample, in the range of zero to one.</param>
/// <returns>The configured trace sampler.</returns>
private static Sampler CreateSampler(double traceSampleRatio)
{
return traceSampleRatio < 1.0
? new ParentBasedSampler(new TraceIdRatioBasedSampler(traceSampleRatio))
: new AlwaysOnSampler();
}
}
@@ -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;
/// <summary>
/// Health check that verifies the remote API is reachable.
/// </summary>
public class ApiReachabilityHealthCheck : IHealthCheck
{
private readonly HttpClient _httpClient;
private readonly ServerConfigurationDto _serverConfiguration;
/// <summary>
/// Initializes a new instance of the <see cref="ApiReachabilityHealthCheck"/> class.
/// </summary>
/// <param name="httpClientFactory">Injected factory for creating HTTP clients.</param>
/// <param name="serverConfigurationOptions">Injected server configuration application settings.</param>
public ApiReachabilityHealthCheck(IHttpClientFactory httpClientFactory, IOptionsSnapshot<ServerConfigurationDto> serverConfigurationOptions)
{
_httpClient = httpClientFactory.CreateClient();
_serverConfiguration = serverConfigurationOptions.Value;
}
/// <summary>
/// Checks whether the remote API is reachable by probing its readiness endpoint.
/// </summary>
/// <param name="context">The health check context.</param>
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous operation, containing the health check result.</returns>
public virtual async Task<HealthCheckResult> 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);
}
}
}
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Telemetry;
/// <summary>
/// Central registry of the <see cref="ActivitySource"/> used by the Presentation Web layer to emit traces.
/// </summary>
public static class WebTelemetry
{
/// <summary>
/// The source name shared by the <see cref="ActivitySource"/> of the Presentation Web layer.
/// </summary>
public const string SOURCE_NAME = "Lumina.Web";
/// <summary>
/// The source of the traces emitted by the Presentation Web layer.
/// </summary>
public static ActivitySource ActivitySource { get; } = new(SOURCE_NAME);
}
+7 -1
View File
@@ -1,6 +1,10 @@
# This stage is used when running from VS in fast mode (Default for Debug configuration) # 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 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 USER app
WORKDIR /app WORKDIR /app
EXPOSE 5012 EXPOSE 5012
@@ -40,6 +44,8 @@ FROM base AS final
WORKDIR /app WORKDIR /app
COPY --from=publish /app/publish . 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 ENV ASPNETCORE_HTTP_PORTS=5012
EXPOSE 5012 EXPOSE 5012
ENTRYPOINT ["dotnet", "Lumina.Presentation.Web.dll"] ENTRYPOINT ["dotnet", "Lumina.Presentation.Web.dll"]
@@ -25,10 +25,17 @@
<PackageReference Include="Microsoft.Extensions.Caching.Hybrid" Version="10.9.0" /> <PackageReference Include="Microsoft.Extensions.Caching.Hybrid" Version="10.9.0" />
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="10.0.11" /> <PackageReference Include="Microsoft.Extensions.Http.Polly" Version="10.0.11" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" /> <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
<PackageReference Include="OpenTelemetry" Version="1.18.0" />
<PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.18.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.18.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.18.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.18.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.18.0" />
<PackageReference Include="Polly" Version="8.7.0" /> <PackageReference Include="Polly" Version="8.7.0" />
<PackageReference Include="Scalar.AspNetCore" Version="2.16.20" /> <PackageReference Include="Scalar.AspNetCore" Version="2.16.20" />
<PackageReference Include="Serilog" Version="4.4.0" /> <PackageReference Include="Serilog" Version="4.4.0" />
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" /> <PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
<PackageReference Include="Serilog.Enrichers.Span" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="10.0.1" /> <PackageReference Include="Serilog.Settings.Configuration" Version="10.0.1" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" /> <PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" /> <PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
+11
View File
@@ -1,11 +1,14 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using FastEndpoints; using FastEndpoints;
using Lumina.Presentation.Web.Common.DependencyInjection; using Lumina.Presentation.Web.Common.DependencyInjection;
using Lumina.Presentation.Web.Common.HealthChecks;
using Lumina.Presentation.Web.Common.Utilities; using Lumina.Presentation.Web.Common.Utilities;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Primitives; using Microsoft.Extensions.Primitives;
using Scalar.AspNetCore; using Scalar.AspNetCore;
@@ -35,6 +38,9 @@ public class Program
builder.Services.BindConfiguration(builder.Configuration); builder.Services.BindConfiguration(builder.Configuration);
builder.Services.AddPresentationWebLayerServices(); builder.Services.AddPresentationWebLayerServices();
builder.Services.AddPresentationWebTelemetryServices(builder.Configuration, builder.Environment);
builder.Services.AddHealthChecks()
.AddCheck<ApiReachabilityHealthCheck>("api", HealthStatus.Unhealthy, ["ready"]);
// determine log path based on environment // determine log path based on environment
string logPath; string logPath;
@@ -122,6 +128,11 @@ public class Program
.WithDotNetFlag(true); .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(); await app.RunAsync();
} }
} }
+11 -9
View File
@@ -20,7 +20,7 @@
"Name": "Console", "Name": "Console",
"Args": { "Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console", "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": { "Args": {
"path": "%LOG_PATH%lumina_web_.log", "path": "%LOG_PATH%lumina_web_.log",
"rollingInterval": "Day", "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, "retainedFileCountLimit": 7,
"fileSizeLimitBytes": 10485760, "fileSizeLimitBytes": 10485760,
"rollOnFileSizeLimit": true, "rollOnFileSizeLimit": true,
@@ -42,7 +42,8 @@
"WithMachineName", "WithMachineName",
"WithThreadId", "WithThreadId",
"WithEnvironmentName", "WithEnvironmentName",
"WithRequestId" "WithRequestId",
"WithSpan"
], ],
"Properties": { "Properties": {
"Application": "LuminaWeb" "Application": "LuminaWeb"
@@ -54,11 +55,12 @@
"BaseAddress": "http://localhost", "BaseAddress": "http://localhost",
"Port": 5214 "Port": 5214
}, },
"Kestrel": { "Telemetry": {
"Endpoints": { "Enabled": true,
"Http": { "ConsoleExporterEnabled": false,
"Url": "http://localhost:5012" "Otlp": {
} "Endpoint": ""
} },
"TraceSampleRatio": 0.25 // production default; override to 1.0 in the development configuration for full trace capture
} }
} }
+75
View File
@@ -7,6 +7,20 @@ services:
dockerfile: Lumina.Presentation.Api/Dockerfile dockerfile: Lumina.Presentation.Api/Dockerfile
environment: environment:
- LOG_PATH=/logs - 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=<secret>
# - EncryptionSettings__SecretKey=<base64 secret>
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: lumina-web:
container_name: lumina-web container_name: lumina-web
@@ -16,3 +30,64 @@ services:
dockerfile: Lumina.Presentation.Web/Dockerfile dockerfile: Lumina.Presentation.Web/Dockerfile
environment: environment:
- LOG_PATH=/logs - 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
+138
View File
@@ -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
}
@@ -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
@@ -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
@@ -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
+9
View File
@@ -0,0 +1,9 @@
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: otel-collector
static_configs:
- targets:
- otel-collector:8889
@@ -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;
/// <summary>
/// Fixture class for the <see cref="LibrarySavedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibrarySavedDomainEventFixture
{
private readonly LibraryFixture _libraryFixture = new();
/// <summary>
/// Creates a random valid <see cref="LibrarySavedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="library">Optional. The library that was created or updated.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <returns>The created <see cref="LibrarySavedDomainEvent"/>.</returns>
public LibrarySavedDomainEvent Create(Guid? id = null, Library? library = null, DateTime? occurredOnUtc = null)
{
return new LibrarySavedDomainEvent(
id ?? Guid.NewGuid(),
library ?? _libraryFixture.Create(),
occurredOnUtc ?? DateTime.UtcNow);
}
}
@@ -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;
/// <summary>
/// Factory whose database health check always reports an unhealthy state.
/// </summary>
[ExcludeFromCodeCoverage]
public class FailingDatabaseApiFactory : LuminaApiFactory
{
/// <summary>
/// Configures the web host, replacing the database health check with one that always fails.
/// </summary>
/// <param name="builder">The web host builder to configure.</param>
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<DatabaseHealthCheck>();
services.AddScoped<DatabaseHealthCheck, FailingDatabaseHealthCheck>();
});
}
}
@@ -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;
/// <summary>
/// Database health check that always reports an unhealthy state.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class FailingDatabaseHealthCheck : DatabaseHealthCheck
{
/// <summary>
/// Initializes a new instance of the <see cref="FailingDatabaseHealthCheck"/> class.
/// </summary>
/// <param name="dbContext">Injected database context.</param>
public FailingDatabaseHealthCheck(LuminaDbContext dbContext) : base(dbContext)
{
}
/// <summary>
/// Reports an unhealthy state without probing the database.
/// </summary>
public override Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken)
{
return Task.FromResult(HealthCheckResult.Unhealthy("database unavailable"));
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <c>/health/ready</c> probe route when the database is unreachable.
/// </summary>
[ExcludeFromCodeCoverage]
public class HealthEndpointFailureTests : IClassFixture<FailingDatabaseApiFactory>
{
private readonly HttpClient _client;
/// <summary>
/// Initializes a new instance of the <see cref="HealthEndpointFailureTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory with a failing database health check.</param>
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);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <c>/health/live</c> and <c>/health/ready</c> probe routes.
/// </summary>
[ExcludeFromCodeCoverage]
public class HealthEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="HealthEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<HealthReportDto>(content, _jsonOptions)!;
Assert.Equal("Healthy", report.Status);
HealthCheckReportDto databaseCheck = Assert.Single(report.Checks, check => check.Name == "database");
Assert.Equal("Healthy", databaseCheck.Status);
}
/// <summary>
/// Deserialized shape of the health report JSON written by the API.
/// </summary>
private sealed record HealthReportDto(string Status, List<HealthCheckReportDto> Checks);
/// <summary>
/// Deserialized shape of a single health check entry within the health report.
/// </summary>
private sealed record HealthCheckReportDto(string Name, string Status, string? Description);
}
@@ -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;
/// <summary>
/// API reachability health check that always reports a healthy state.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class HealthyApiReachabilityHealthCheck : ApiReachabilityHealthCheck
{
/// <summary>
/// Initializes a new instance of the <see cref="HealthyApiReachabilityHealthCheck"/> class.
/// </summary>
/// <param name="httpClientFactory">Injected factory for creating HTTP clients.</param>
/// <param name="serverConfigurationOptions">Injected server configuration application settings.</param>
public HealthyApiReachabilityHealthCheck(IHttpClientFactory httpClientFactory, IOptionsSnapshot<ServerConfigurationDto> serverConfigurationOptions)
: base(httpClientFactory, serverConfigurationOptions)
{
}
/// <summary>
/// Reports a healthy state without probing the API.
/// </summary>
public override Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken)
{
return Task.FromResult(HealthCheckResult.Healthy());
}
}
@@ -1,11 +1,13 @@
#region ========================================================================= USING ===================================================================================== #region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web; using Lumina.Presentation.Web;
using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.HealthChecks;
using Lumina.Presentation.Web.Fixtures.Common.Api; using Lumina.Presentation.Web.Fixtures.Common.Api;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
@@ -58,6 +60,11 @@ public class LuminaWebFactory : WebApplicationFactory<Program>, IDisposable
foreach (ServiceDescriptor descriptor in apiClientDescriptors) foreach (ServiceDescriptor descriptor in apiClientDescriptors)
services.Remove(descriptor); services.Remove(descriptor);
services.AddSingleton<IApiHttpClient>(ApiClientStub); services.AddSingleton<IApiHttpClient>(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<ApiReachabilityHealthCheck>();
services.AddScoped<ApiReachabilityHealthCheck, HealthyApiReachabilityHealthCheck>();
}); });
} }
} }
@@ -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;
/// <summary>
/// Factory whose API reachability health check always reports an unhealthy state.
/// </summary>
[ExcludeFromCodeCoverage]
public class FailingApiHealthFactory : LuminaWebFactory
{
/// <summary>
/// Configures the web host, replacing the API reachability health check with one that always fails.
/// </summary>
/// <param name="builder">The web host builder to configure.</param>
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
builder.ConfigureServices(services =>
{
services.RemoveAll<ApiReachabilityHealthCheck>();
services.AddScoped<ApiReachabilityHealthCheck, UnhealthyApiReachabilityHealthCheck>();
});
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <c>/health/ready</c> probe route when the API is unreachable.
/// </summary>
[ExcludeFromCodeCoverage]
public class HealthEndpointFailureTests : IClassFixture<FailingApiHealthFactory>
{
private readonly FailingApiHealthFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="HealthEndpointFailureTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory with a failing API reachability check.</param>
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);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <c>/health/live</c> and <c>/health/ready</c> probe routes.
/// </summary>
[ExcludeFromCodeCoverage]
public class HealthEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="HealthEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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);
}
}
@@ -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;
/// <summary>
/// API reachability health check that always reports an unhealthy state.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class UnhealthyApiReachabilityHealthCheck : ApiReachabilityHealthCheck
{
/// <summary>
/// Initializes a new instance of the <see cref="UnhealthyApiReachabilityHealthCheck"/> class.
/// </summary>
/// <param name="httpClientFactory">Injected factory for creating HTTP clients.</param>
/// <param name="serverConfigurationOptions">Injected server configuration application settings.</param>
public UnhealthyApiReachabilityHealthCheck(IHttpClientFactory httpClientFactory, IOptionsSnapshot<ServerConfigurationDto> serverConfigurationOptions)
: base(httpClientFactory, serverConfigurationOptions)
{
}
/// <summary>
/// Reports an unhealthy state without probing the API.
/// </summary>
public override Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken)
{
return Task.FromResult(HealthCheckResult.Unhealthy("api unreachable"));
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="TelemetryCommandHandlerDecorator{TCommand,TResult}"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TelemetryCommandHandlerDecoratorTests
{
private readonly ICommandHandler<AddRoleCommand, Result<RolePermissionsResponse>> _mockInnerHandler;
private readonly TelemetryCommandHandlerDecorator<AddRoleCommand, Result<RolePermissionsResponse>> _sut;
private readonly AddRoleCommandFixture _addRoleCommandFixture = new();
private readonly RolePermissionsResponseFixture _rolePermissionsResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="TelemetryCommandHandlerDecoratorTests"/> class.
/// </summary>
public TelemetryCommandHandlerDecoratorTests()
{
_mockInnerHandler = Substitute.For<ICommandHandler<AddRoleCommand, Result<RolePermissionsResponse>>>();
ILogger<TelemetryCommandHandlerDecorator<AddRoleCommand, Result<RolePermissionsResponse>>> mockLogger =
Substitute.For<ILogger<TelemetryCommandHandlerDecorator<AddRoleCommand, Result<RolePermissionsResponse>>>>();
_sut = new TelemetryCommandHandlerDecorator<AddRoleCommand, Result<RolePermissionsResponse>>(
_mockInnerHandler,
mockLogger);
}
[Fact]
public async Task HandleAsync_WhenInnerHandlerSucceeds_ShouldDelegateAndEmitSuccessfulTraceAndMetric()
{
// Arrange
List<Activity> 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<RolePermissionsResponse> expectedResult = Result<RolePermissionsResponse>.Success(_rolePermissionsResponseFixture.Create());
_mockInnerHandler.HandleAsync(Arg.Any<AddRoleCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedResult);
// Act
Result<RolePermissionsResponse> 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<Activity> 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<RolePermissionsResponse> failedResult = Error.Failure("Test.Failed", "Test failure description");
_mockInnerHandler.HandleAsync(Arg.Any<AddRoleCommand>(), Arg.Any<CancellationToken>())
.Returns(failedResult);
// Act
Result<RolePermissionsResponse> 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<Activity> 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<AddRoleCommand>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<RolePermissionsResponse>>(exception));
// Act
await Assert.ThrowsAsync<InvalidOperationException>(() => _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");
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="TelemetryDomainEventHandlerDecorator{TDomainEvent}"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TelemetryDomainEventHandlerDecoratorTests
{
private readonly IDomainEventHandler<LibrarySavedDomainEvent> _mockInnerHandler;
private readonly TelemetryDomainEventHandlerDecorator<LibrarySavedDomainEvent> _sut;
private readonly LibrarySavedDomainEventFixture _librarySavedDomainEventFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="TelemetryDomainEventHandlerDecoratorTests"/> class.
/// </summary>
public TelemetryDomainEventHandlerDecoratorTests()
{
_mockInnerHandler = Substitute.For<IDomainEventHandler<LibrarySavedDomainEvent>>();
ILogger<TelemetryDomainEventHandlerDecorator<LibrarySavedDomainEvent>> mockLogger =
Substitute.For<ILogger<TelemetryDomainEventHandlerDecorator<LibrarySavedDomainEvent>>>();
_sut = new TelemetryDomainEventHandlerDecorator<LibrarySavedDomainEvent>(
_mockInnerHandler,
mockLogger);
}
[Fact]
public async Task HandleAsync_WhenInnerHandlerSucceeds_ShouldDelegateAndEmitSuccessfulTraceAndMetric()
{
// Arrange
List<Activity> 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<LibrarySavedDomainEvent>(), Arg.Any<CancellationToken>())
.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<Activity> 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<LibrarySavedDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(ValueTask.FromException(exception));
// Act
await Assert.ThrowsAsync<InvalidOperationException>(() => _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");
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="TelemetryQueryHandlerDecorator{TQuery,TResult}"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TelemetryQueryHandlerDecoratorTests
{
private readonly IQueryHandler<GetRolePermissionsQuery, Result<RolePermissionsResponse>> _mockInnerHandler;
private readonly TelemetryQueryHandlerDecorator<GetRolePermissionsQuery, Result<RolePermissionsResponse>> _sut;
private readonly GetRolePermissionsQueryFixture _getRolePermissionsQueryFixture = new();
private readonly RolePermissionsResponseFixture _rolePermissionsResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="TelemetryQueryHandlerDecoratorTests"/> class.
/// </summary>
public TelemetryQueryHandlerDecoratorTests()
{
_mockInnerHandler = Substitute.For<IQueryHandler<GetRolePermissionsQuery, Result<RolePermissionsResponse>>>();
ILogger<TelemetryQueryHandlerDecorator<GetRolePermissionsQuery, Result<RolePermissionsResponse>>> mockLogger =
Substitute.For<ILogger<TelemetryQueryHandlerDecorator<GetRolePermissionsQuery, Result<RolePermissionsResponse>>>>();
_sut = new TelemetryQueryHandlerDecorator<GetRolePermissionsQuery, Result<RolePermissionsResponse>>(
_mockInnerHandler,
mockLogger);
}
[Fact]
public async Task HandleAsync_WhenInnerHandlerSucceeds_ShouldDelegateAndEmitSuccessfulTraceAndMetric()
{
// Arrange
List<Activity> 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<RolePermissionsResponse> expectedResult = Result<RolePermissionsResponse>.Success(_rolePermissionsResponseFixture.Create());
_mockInnerHandler.HandleAsync(Arg.Any<GetRolePermissionsQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedResult);
// Act
Result<RolePermissionsResponse> 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<Activity> 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<RolePermissionsResponse> failedResult = Error.Failure("Test.Failed", "Test failure description");
_mockInnerHandler.HandleAsync(Arg.Any<GetRolePermissionsQuery>(), Arg.Any<CancellationToken>())
.Returns(failedResult);
// Act
Result<RolePermissionsResponse> 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<Activity> 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<GetRolePermissionsQuery>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<RolePermissionsResponse>>(exception));
// Act
await Assert.ThrowsAsync<InvalidOperationException>(() => _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");
}
}
@@ -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;
/// <summary>
/// Test utilities for capturing the traces and metrics emitted by the application telemetry.
/// </summary>
[ExcludeFromCodeCoverage]
internal static class TelemetryTestHelpers
{
/// <summary>
/// Creates an <see cref="ActivityListener"/> that captures every activity emitted by the <see cref="ApplicationTelemetry"/> activity source.
/// </summary>
/// <param name="capturedActivities">The collection that stopped activities are added to.</param>
/// <returns>The started <see cref="ActivityListener"/>.</returns>
public static ActivityListener CreateActivityListener(ICollection<Activity> capturedActivities)
{
ActivityListener listener = new()
{
ShouldListenTo = source => source.Name == ApplicationTelemetry.SOURCE_NAME,
Sample = (ref ActivityCreationOptions<ActivityContext> options) => ActivitySamplingResult.AllData,
ActivityStopped = activity => capturedActivities.Add(activity)
};
ActivitySource.AddActivityListener(listener);
return listener;
}
/// <summary>
/// Creates a <see cref="MeterListener"/> that captures every measurement emitted by the <see cref="ApplicationTelemetry"/> meter.
/// </summary>
/// <param name="measurements">The collection that measurements are added to.</param>
/// <returns>The started <see cref="MeterListener"/>.</returns>
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<double>((instrument, value, tags, state) => measurements.Add((instrument.Name, value, GetOutcomeTag(tags))));
listener.SetMeasurementEventCallback<long>((instrument, value, tags, state) => measurements.Add((instrument.Name, value, GetOutcomeTag(tags))));
listener.Start();
return listener;
}
/// <summary>
/// Reads the value of the <c>lumina.outcome</c> tag from the specified tag list.
/// </summary>
/// <param name="tags">The tag list of a measurement.</param>
/// <returns>The outcome tag value, or an empty string when the tag is not present.</returns>
private static string GetOutcomeTag(ReadOnlySpan<KeyValuePair<string, object?>> tags)
{
foreach (KeyValuePair<string, object?> tag in tags)
if (tag.Key == "lumina.outcome")
return tag.Value?.ToString() ?? string.Empty;
return string.Empty;
}
}