Adds telemetry instrumentation to application handlers

This commit is contained in:
BinaryAlley committed 2026-08-22 06:27:31 -07:00
1 parent ffcb25c13f
commit a2c99b1b79
13 files changed
+862 -2

No files matched your search

@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Telemetry;
using Lumina.Domain.Common.Events;
using Microsoft.Extensions.DependencyInjection;
using System;
@@ -46,9 +47,18 @@ public static class ApplicationLayerServices
continue;
if (registration.Contract.GetGenericTypeDefinition() == typeof(Infrastructure.Validation.IValidator<>))
{
services.AddSingleton(registration.Contract, registration.Implementation);
else
services.AddScoped(registration.Contract, registration.Implementation);
continue;
}
// wrap query, command, and domain event handlers in their telemetry decorator, so that every invocation emits traces, metrics, and structured logs
services.AddScoped(registration.Contract, serviceProvider =>
{
object handler = ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, registration.Implementation);
Type decoratorType = TelemetryDecoratorFactory.GetDecoratorType(registration.Contract);
return ActivatorUtilities.CreateInstance(serviceProvider, decoratorType, handler);
});
}
return services;
@@ -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;
}
}
}
}
@@ -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,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;
}
}