diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index 229555a5..b8f5bc7d 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Telemetry; using Lumina.Domain.Common.Events; using Microsoft.Extensions.DependencyInjection; using System; @@ -46,9 +47,18 @@ public static class ApplicationLayerServices continue; if (registration.Contract.GetGenericTypeDefinition() == typeof(Infrastructure.Validation.IValidator<>)) + { services.AddSingleton(registration.Contract, registration.Implementation); - else - services.AddScoped(registration.Contract, registration.Implementation); + continue; + } + + // wrap query, command, and domain event handlers in their telemetry decorator, so that every invocation emits traces, metrics, and structured logs + services.AddScoped(registration.Contract, serviceProvider => + { + object handler = ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, registration.Implementation); + Type decoratorType = TelemetryDecoratorFactory.GetDecoratorType(registration.Contract); + return ActivatorUtilities.CreateInstance(serviceProvider, decoratorType, handler); + }); } return services; diff --git a/src/Lumina.Application/Common/Telemetry/ApplicationHandlerTelemetry.cs b/src/Lumina.Application/Common/Telemetry/ApplicationHandlerTelemetry.cs new file mode 100644 index 00000000..369ec505 --- /dev/null +++ b/src/Lumina.Application/Common/Telemetry/ApplicationHandlerTelemetry.cs @@ -0,0 +1,108 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.Extensions.Logging; +using System; +using System.Diagnostics; +using System.Diagnostics.Metrics; +#endregion + +namespace Lumina.Application.Common.Telemetry; + +/// +/// Helper that emits the traces, metrics, and structured logs for the execution of application handlers. +/// +internal static class ApplicationHandlerTelemetry +{ + private const string HANDLER_DURATION_METRIC_NAME = "lumina.application.handler.duration"; + private const string HANDLER_INVOCATIONS_METRIC_NAME = "lumina.application.handler.invocations"; + + private static readonly Histogram s_handlerDuration = ApplicationTelemetry.Meter.CreateHistogram( + name: HANDLER_DURATION_METRIC_NAME, + description: "Duration in milliseconds of the execution of an application handler."); + + private static readonly Counter s_handlerInvocations = ApplicationTelemetry.Meter.CreateCounter( + name: HANDLER_INVOCATIONS_METRIC_NAME, + description: "Number of invocations of an application handler."); + + /// + /// Starts a new for the execution of the handler with the specified name. + /// + /// The name of the handler being executed. + /// The type of the handler being executed. + /// The started activity, or when no trace listener is registered. + public static Activity? StartActivity(string handlerName, string handlerType) + { + Activity? activity = ApplicationTelemetry.ActivitySource.StartActivity($"Handle {handlerName}", ActivityKind.Internal); + activity?.SetTag("lumina.handler.type", handlerType); + activity?.SetTag("lumina.handler.name", handlerName); + return activity; + } + + /// + /// Records the successful completion of a handler execution, including its trace status, metrics, and a structured log entry. + /// + /// The logger to write the structured log entry to. + /// The activity to mark as successful. + /// The name of the handled handler. + /// The type of the handled handler. + /// The duration of the handler execution. + public static void RecordSuccess(ILogger logger, Activity? activity, string handlerName, string handlerType, TimeSpan duration) + { + activity?.SetStatus(ActivityStatusCode.Ok); + RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: true); + logger.LogDebug("Completed handling {HandlerType} {HandlerName} in {DurationMs}ms", handlerType, handlerName, duration.TotalMilliseconds); + } + + /// + /// Records the failed completion of a handler execution, including its trace status, metrics, and a structured log entry. + /// + /// The logger to write the structured log entry to. + /// The activity to mark as failed. + /// The name of the handled handler. + /// The type of the handled handler. + /// The duration of the handler execution. + /// An optional description of the failure. + public static void RecordFailure(ILogger logger, Activity? activity, string handlerName, string handlerType, TimeSpan duration, string? error) + { + activity?.SetStatus(ActivityStatusCode.Error, error); + RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: false); + // business-rule failures are routine outcomes (e.g. failed logins), so log at Debug to avoid noise from high-frequency handlers + logger.LogDebug("Failed handling {HandlerType} {HandlerName} in {DurationMs}ms: {Error}", handlerType, handlerName, duration.TotalMilliseconds, error); + } + + /// + /// Records the exceptional completion of a handler execution, including its trace status, metrics, and a structured log entry. + /// + /// The logger to write the structured log entry to. + /// The activity to mark as failed. + /// The name of the handled handler. + /// The type of the handled handler. + /// The exception that was thrown during the handler execution. + /// The duration of the handler execution. + public static void RecordException(ILogger logger, Activity? activity, string handlerName, string handlerType, Exception exception, TimeSpan duration) + { + activity?.SetStatus(ActivityStatusCode.Error, exception.Message); + RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: false); + logger.LogError(exception, "Failed handling {HandlerType} {HandlerName} in {DurationMs}ms", handlerType, handlerName, duration.TotalMilliseconds); + } + + /// + /// Records the invocation count and duration of a handler execution into the corresponding metrics, and tags the activity with the outcome. + /// + /// The activity to tag with the outcome. + /// The name of the handled handler. + /// The type of the handled handler. + /// The duration of the handler execution. + /// Whether the handler execution completed successfully. + private static void RecordOutcome(Activity? activity, string handlerName, string handlerType, TimeSpan duration, bool isSuccess) + { + TagList tags = new() + { + { "lumina.handler.type", handlerType }, + { "lumina.handler.name", handlerName }, + { "lumina.outcome", isSuccess ? "success" : "failure" } + }; + s_handlerInvocations.Add(1, tags); + s_handlerDuration.Record(duration.TotalMilliseconds, tags); + activity?.SetTag("lumina.outcome", isSuccess ? "success" : "failure"); + } +} diff --git a/src/Lumina.Application/Common/Telemetry/ApplicationTelemetry.cs b/src/Lumina.Application/Common/Telemetry/ApplicationTelemetry.cs new file mode 100644 index 00000000..45128ef6 --- /dev/null +++ b/src/Lumina.Application/Common/Telemetry/ApplicationTelemetry.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.Diagnostics.Metrics; +#endregion + +namespace Lumina.Application.Common.Telemetry; + +/// +/// Central registry of the and used by the Application layer to emit traces and metrics. +/// +public static class ApplicationTelemetry +{ + /// + /// The source name shared by the and of the Application layer. + /// + public const string SOURCE_NAME = "Lumina.Application"; + + /// + /// The source of the traces emitted by the Application layer. + /// + public static ActivitySource ActivitySource { get; } = new(SOURCE_NAME); + + /// + /// The source of the metrics emitted by the Application layer. + /// + public static Meter Meter { get; } = new(SOURCE_NAME); +} diff --git a/src/Lumina.Application/Common/Telemetry/HandlerOutcomeDetector.cs b/src/Lumina.Application/Common/Telemetry/HandlerOutcomeDetector.cs new file mode 100644 index 00000000..ac2c7a1d --- /dev/null +++ b/src/Lumina.Application/Common/Telemetry/HandlerOutcomeDetector.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Concurrent; +using System.Reflection; +#endregion + +namespace Lumina.Application.Common.Telemetry; + +/// +/// Detects the outcome of an application handler result in a generic way, without coupling the telemetry decorators to any concrete result type. +/// +internal static class HandlerOutcomeDetector +{ + private static readonly ConcurrentDictionary s_isSuccessPropertyCache = new(); + private static readonly ConcurrentDictionary s_firstErrorPropertyCache = new(); + private static readonly ConcurrentDictionary s_errorDescriptionPropertyCache = new(); + + /// + /// Determines whether the specified result represents a successful outcome. + /// + /// The result returned by an application handler, or . + /// + /// when the result reports success, when it is , or when it exposes no success flag. + /// + /// + /// Handlers that return plain DTOs (no IsSuccess property) cannot express a failure and are reported as successful; + /// only handlers returning a result type such as report failures. + /// + public static bool IsSuccessful(object? result) + { + if (result is null) + return true; + PropertyInfo? isSuccessProperty = GetIsSuccessProperty(result.GetType()); + return isSuccessProperty is null || (bool)isSuccessProperty.GetValue(result)!; + } + + /// + /// Gets a human-readable description of the first error of a failed result, when the result exposes one. + /// + /// The failed result returned by an application handler, or . + /// The description of the first error, or when the result exposes no errors. + public static string? GetErrorDescription(object? result) + { + if (result is null) + return null; + PropertyInfo? firstErrorProperty = s_firstErrorPropertyCache.GetOrAdd(result.GetType(), type => type.GetProperty("FirstError", BindingFlags.Public | BindingFlags.Instance)); + object? firstError = firstErrorProperty?.GetValue(result); + if (firstError is null) + return null; + PropertyInfo? descriptionProperty = s_errorDescriptionPropertyCache.GetOrAdd(firstError.GetType(), type => type.GetProperty("Description", BindingFlags.Public | BindingFlags.Instance)); + return descriptionProperty?.GetValue(firstError)?.ToString(); + } + + /// + /// Gets the public instance IsSuccess property of the specified type, if it has one. + /// + /// The type to inspect. + /// The IsSuccess property, or when the type does not expose one. + private static PropertyInfo? GetIsSuccessProperty(Type type) + { + return s_isSuccessPropertyCache.GetOrAdd(type, candidateType => candidateType.GetProperty("IsSuccess", BindingFlags.Public | BindingFlags.Instance)); + } +} diff --git a/src/Lumina.Application/Common/Telemetry/TelemetryCommandHandlerDecorator.cs b/src/Lumina.Application/Common/Telemetry/TelemetryCommandHandlerDecorator.cs new file mode 100644 index 00000000..29123465 --- /dev/null +++ b/src/Lumina.Application/Common/Telemetry/TelemetryCommandHandlerDecorator.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Microsoft.Extensions.Logging; +using System; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.Telemetry; + +/// +/// Decorator that wraps an to emit traces, metrics, and structured logs for every command execution. +/// +/// The type of command to handle. +/// The type of result returned after handling the command. +public class TelemetryCommandHandlerDecorator : ICommandHandler where TCommand : ICommand +{ + private const string HANDLER_TYPE = "command"; + + private readonly ICommandHandler _innerHandler; + private readonly ILogger> _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The wrapped command handler. + /// Injected logger used for structured logging. + public TelemetryCommandHandlerDecorator(ICommandHandler innerHandler, ILogger> logger) + { + _innerHandler = innerHandler; + _logger = logger; + } + + /// + /// Handles the specified command, emitting telemetry around the execution of the wrapped handler. + /// + /// The command to handle. + /// Token to monitor for cancellation requests. + /// A task that represents the asynchronous operation, containing the result of the command execution. + public async Task HandleAsync(TCommand command, CancellationToken cancellationToken) + { + string handlerName = _innerHandler.GetType().Name; + using (Activity? activity = ApplicationHandlerTelemetry.StartActivity(handlerName, HANDLER_TYPE)) + { + Stopwatch stopwatch = Stopwatch.StartNew(); + try + { + TResult result = await _innerHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false); + stopwatch.Stop(); + if (HandlerOutcomeDetector.IsSuccessful(result)) + ApplicationHandlerTelemetry.RecordSuccess(_logger, activity, handlerName, HANDLER_TYPE, stopwatch.Elapsed); + else + ApplicationHandlerTelemetry.RecordFailure(_logger, activity, handlerName, HANDLER_TYPE, stopwatch.Elapsed, HandlerOutcomeDetector.GetErrorDescription(result)); + return result; + } + catch (Exception exception) + { + stopwatch.Stop(); + ApplicationHandlerTelemetry.RecordException(_logger, activity, handlerName, HANDLER_TYPE, exception, stopwatch.Elapsed); + throw; + } + } + } +} diff --git a/src/Lumina.Application/Common/Telemetry/TelemetryDecoratorFactory.cs b/src/Lumina.Application/Common/Telemetry/TelemetryDecoratorFactory.cs new file mode 100644 index 00000000..78506590 --- /dev/null +++ b/src/Lumina.Application/Common/Telemetry/TelemetryDecoratorFactory.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Domain.Common.Events; +using System; +#endregion + +namespace Lumina.Application.Common.Telemetry; + +/// +/// Resolves the telemetry decorator type that wraps a given application handler contract. +/// +internal static class TelemetryDecoratorFactory +{ + /// + /// Gets the closed telemetry decorator type for the specified handler contract. + /// + /// The handler contract to wrap. + /// The closed generic telemetry decorator type for the contract. + /// Thrown when the contract has no matching telemetry decorator. + public static Type GetDecoratorType(Type contract) + { + Type contractDefinition = contract.GetGenericTypeDefinition(); + Type[] typeArguments = contract.GetGenericArguments(); + + if (contractDefinition == typeof(IQueryHandler<,>)) + return typeof(TelemetryQueryHandlerDecorator<,>).MakeGenericType(typeArguments); + if (contractDefinition == typeof(ICommandHandler<,>)) + return typeof(TelemetryCommandHandlerDecorator<,>).MakeGenericType(typeArguments); + if (contractDefinition == typeof(IDomainEventHandler<>)) + return typeof(TelemetryDomainEventHandlerDecorator<>).MakeGenericType(typeArguments); + + throw new ArgumentException($"No telemetry decorator is defined for the contract type '{contract}'.", nameof(contract)); + } +} diff --git a/src/Lumina.Application/Common/Telemetry/TelemetryDomainEventHandlerDecorator.cs b/src/Lumina.Application/Common/Telemetry/TelemetryDomainEventHandlerDecorator.cs new file mode 100644 index 00000000..02e96c1f --- /dev/null +++ b/src/Lumina.Application/Common/Telemetry/TelemetryDomainEventHandlerDecorator.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Microsoft.Extensions.Logging; +using System; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.Telemetry; + +/// +/// Decorator that wraps an to emit traces, metrics, and structured logs for every domain event handling. +/// +/// The type of domain event to handle. +public class TelemetryDomainEventHandlerDecorator : IDomainEventHandler where TDomainEvent : IDomainEvent +{ + private const string HANDLER_TYPE = "domain-event"; + + private readonly IDomainEventHandler _innerHandler; + private readonly ILogger> _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The wrapped domain event handler. + /// Injected logger used for structured logging. + public TelemetryDomainEventHandlerDecorator(IDomainEventHandler innerHandler, ILogger> logger) + { + _innerHandler = innerHandler; + _logger = logger; + } + + /// + /// Handles the specified domain event, emitting telemetry around the execution of the wrapped handler. + /// + /// The domain event to handle. + /// Token to monitor for cancellation requests. + /// A task that represents the asynchronous operation. + public async ValueTask HandleAsync(TDomainEvent domainEvent, CancellationToken cancellationToken) + { + string handlerName = _innerHandler.GetType().Name; + using (Activity? activity = ApplicationHandlerTelemetry.StartActivity(handlerName, HANDLER_TYPE)) + { + Stopwatch stopwatch = Stopwatch.StartNew(); + try + { + await _innerHandler.HandleAsync(domainEvent, cancellationToken).ConfigureAwait(false); + stopwatch.Stop(); + ApplicationHandlerTelemetry.RecordSuccess(_logger, activity, handlerName, HANDLER_TYPE, stopwatch.Elapsed); + } + catch (Exception exception) + { + stopwatch.Stop(); + ApplicationHandlerTelemetry.RecordException(_logger, activity, handlerName, HANDLER_TYPE, exception, stopwatch.Elapsed); + throw; + } + } + } +} diff --git a/src/Lumina.Application/Common/Telemetry/TelemetryQueryHandlerDecorator.cs b/src/Lumina.Application/Common/Telemetry/TelemetryQueryHandlerDecorator.cs new file mode 100644 index 00000000..f5529bb6 --- /dev/null +++ b/src/Lumina.Application/Common/Telemetry/TelemetryQueryHandlerDecorator.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Microsoft.Extensions.Logging; +using System; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.Telemetry; + +/// +/// Decorator that wraps an to emit traces, metrics, and structured logs for every query execution. +/// +/// The type of query to handle. +/// The type of result returned after handling the query. +public class TelemetryQueryHandlerDecorator : IQueryHandler where TQuery : IQuery +{ + private const string HANDLER_TYPE = "query"; + + private readonly IQueryHandler _innerHandler; + private readonly ILogger> _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The wrapped query handler. + /// Injected logger used for structured logging. + public TelemetryQueryHandlerDecorator(IQueryHandler innerHandler, ILogger> logger) + { + _innerHandler = innerHandler; + _logger = logger; + } + + /// + /// Handles the specified query, emitting telemetry around the execution of the wrapped handler. + /// + /// The query to handle. + /// Token to monitor for cancellation requests. + /// A task that represents the asynchronous operation, containing the result of the query execution. + public async Task HandleAsync(TQuery query, CancellationToken cancellationToken) + { + string handlerName = _innerHandler.GetType().Name; + using (Activity? activity = ApplicationHandlerTelemetry.StartActivity(handlerName, HANDLER_TYPE)) + { + Stopwatch stopwatch = Stopwatch.StartNew(); + try + { + TResult result = await _innerHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); + stopwatch.Stop(); + if (HandlerOutcomeDetector.IsSuccessful(result)) + ApplicationHandlerTelemetry.RecordSuccess(_logger, activity, handlerName, HANDLER_TYPE, stopwatch.Elapsed); + else + ApplicationHandlerTelemetry.RecordFailure(_logger, activity, handlerName, HANDLER_TYPE, stopwatch.Elapsed, HandlerOutcomeDetector.GetErrorDescription(result)); + return result; + } + catch (Exception exception) + { + stopwatch.Stop(); + ApplicationHandlerTelemetry.RecordException(_logger, activity, handlerName, HANDLER_TYPE, exception, stopwatch.Elapsed); + throw; + } + } + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEventFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEventFixture.cs new file mode 100644 index 00000000..329de61e --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEventFixture.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibrarySavedDomainEventFixture +{ + private readonly LibraryFixture _libraryFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the domain event. + /// Optional. The library that was created or updated. + /// Optional. The date and time when the domain event occurred. + /// The created . + public LibrarySavedDomainEvent Create(Guid? id = null, Library? library = null, DateTime? occurredOnUtc = null) + { + return new LibrarySavedDomainEvent( + id ?? Guid.NewGuid(), + library ?? _libraryFixture.Create(), + occurredOnUtc ?? DateTime.UtcNow); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryCommandHandlerDecoratorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryCommandHandlerDecoratorTests.cs new file mode 100644 index 00000000..9b50bc16 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryCommandHandlerDecoratorTests.cs @@ -0,0 +1,118 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Telemetry; +using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; +using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.AddRole; +using Lumina.Contracts.Fixtures.Core.Responses.Authorization; +using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.Metrics; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Common.Telemetry; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TelemetryCommandHandlerDecoratorTests +{ + private readonly ICommandHandler> _mockInnerHandler; + private readonly TelemetryCommandHandlerDecorator> _sut; + private readonly AddRoleCommandFixture _addRoleCommandFixture = new(); + private readonly RolePermissionsResponseFixture _rolePermissionsResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public TelemetryCommandHandlerDecoratorTests() + { + _mockInnerHandler = Substitute.For>>(); + ILogger>> mockLogger = + Substitute.For>>>(); + _sut = new TelemetryCommandHandlerDecorator>( + _mockInnerHandler, + mockLogger); + } + + [Fact] + public async Task HandleAsync_WhenInnerHandlerSucceeds_ShouldDelegateAndEmitSuccessfulTraceAndMetric() + { + // Arrange + List capturedActivities = []; + using ActivityListener activityListener = TelemetryTestHelpers.CreateActivityListener(capturedActivities); + List<(string InstrumentName, double Value, string Outcome)> metricMeasurements = []; + using MeterListener meterListener = TelemetryTestHelpers.CreateMeterListener(metricMeasurements); + AddRoleCommand command = _addRoleCommandFixture.Create(); + Result expectedResult = Result.Success(_rolePermissionsResponseFixture.Create()); + _mockInnerHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedResult); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.Equal(expectedResult, result); + await _mockInnerHandler.Received(1).HandleAsync(command, CancellationToken.None); + Activity activity = Assert.Single(capturedActivities); + Assert.Equal($"Handle {_mockInnerHandler.GetType().Name}", activity.OperationName); + Assert.Equal("command", activity.GetTagItem("lumina.handler.type")); + Assert.Equal(ActivityStatusCode.Ok, activity.Status); + Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.duration" && measurement.Outcome == "success"); + Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.invocations" && measurement.Outcome == "success"); + } + + [Fact] + public async Task HandleAsync_WhenInnerHandlerReturnsFailedResult_ShouldReturnResultAndEmitFailureTraceAndMetric() + { + // Arrange + List capturedActivities = []; + using ActivityListener activityListener = TelemetryTestHelpers.CreateActivityListener(capturedActivities); + List<(string InstrumentName, double Value, string Outcome)> metricMeasurements = []; + using MeterListener meterListener = TelemetryTestHelpers.CreateMeterListener(metricMeasurements); + AddRoleCommand command = _addRoleCommandFixture.Create(); + Result failedResult = Error.Failure("Test.Failed", "Test failure description"); + _mockInnerHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(failedResult); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.Equal(failedResult, result); + Activity activity = Assert.Single(capturedActivities); + Assert.Equal(ActivityStatusCode.Error, activity.Status); + Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.duration" && measurement.Outcome == "failure"); + Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.invocations" && measurement.Outcome == "failure"); + } + + [Fact] + public async Task HandleAsync_WhenInnerHandlerThrows_ShouldRethrowAndEmitFailureTraceAndMetric() + { + // Arrange + List capturedActivities = []; + using ActivityListener activityListener = TelemetryTestHelpers.CreateActivityListener(capturedActivities); + List<(string InstrumentName, double Value, string Outcome)> metricMeasurements = []; + using MeterListener meterListener = TelemetryTestHelpers.CreateMeterListener(metricMeasurements); + AddRoleCommand command = _addRoleCommandFixture.Create(); + InvalidOperationException exception = new("boom"); + _mockInnerHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException>(exception)); + + // Act + await Assert.ThrowsAsync(() => _sut.HandleAsync(command, CancellationToken.None)); + + // Assert + Activity activity = Assert.Single(capturedActivities); + Assert.Equal(ActivityStatusCode.Error, activity.Status); + Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.duration" && measurement.Outcome == "failure"); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryDomainEventHandlerDecoratorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryDomainEventHandlerDecoratorTests.cs new file mode 100644 index 00000000..8ad48a11 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryDomainEventHandlerDecoratorTests.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Telemetry; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.Metrics; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Common.Telemetry; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TelemetryDomainEventHandlerDecoratorTests +{ + private readonly IDomainEventHandler _mockInnerHandler; + private readonly TelemetryDomainEventHandlerDecorator _sut; + private readonly LibrarySavedDomainEventFixture _librarySavedDomainEventFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public TelemetryDomainEventHandlerDecoratorTests() + { + _mockInnerHandler = Substitute.For>(); + ILogger> mockLogger = + Substitute.For>>(); + _sut = new TelemetryDomainEventHandlerDecorator( + _mockInnerHandler, + mockLogger); + } + + [Fact] + public async Task HandleAsync_WhenInnerHandlerSucceeds_ShouldDelegateAndEmitSuccessfulTraceAndMetric() + { + // Arrange + List capturedActivities = []; + using ActivityListener activityListener = TelemetryTestHelpers.CreateActivityListener(capturedActivities); + List<(string InstrumentName, double Value, string Outcome)> metricMeasurements = []; + using MeterListener meterListener = TelemetryTestHelpers.CreateMeterListener(metricMeasurements); + LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(); + _mockInnerHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.CompletedTask); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + await _mockInnerHandler.Received(1).HandleAsync(domainEvent, CancellationToken.None); + Activity activity = Assert.Single(capturedActivities); + Assert.Equal($"Handle {_mockInnerHandler.GetType().Name}", activity.OperationName); + Assert.Equal("domain-event", activity.GetTagItem("lumina.handler.type")); + Assert.Equal(ActivityStatusCode.Ok, activity.Status); + Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.duration" && measurement.Outcome == "success"); + Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.invocations" && measurement.Outcome == "success"); + } + + [Fact] + public async Task HandleAsync_WhenInnerHandlerThrows_ShouldRethrowAndEmitFailureTraceAndMetric() + { + // Arrange + List capturedActivities = []; + using ActivityListener activityListener = TelemetryTestHelpers.CreateActivityListener(capturedActivities); + List<(string InstrumentName, double Value, string Outcome)> metricMeasurements = []; + using MeterListener meterListener = TelemetryTestHelpers.CreateMeterListener(metricMeasurements); + LibrarySavedDomainEvent domainEvent = _librarySavedDomainEventFixture.Create(); + InvalidOperationException exception = new("boom"); + _mockInnerHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.FromException(exception)); + + // Act + await Assert.ThrowsAsync(() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Activity activity = Assert.Single(capturedActivities); + Assert.Equal(ActivityStatusCode.Error, activity.Status); + Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.duration" && measurement.Outcome == "failure"); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryQueryHandlerDecoratorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryQueryHandlerDecoratorTests.cs new file mode 100644 index 00000000..85271099 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryQueryHandlerDecoratorTests.cs @@ -0,0 +1,118 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Telemetry; +using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; +using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; +using Lumina.Contracts.Fixtures.Core.Responses.Authorization; +using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.Metrics; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Common.Telemetry; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TelemetryQueryHandlerDecoratorTests +{ + private readonly IQueryHandler> _mockInnerHandler; + private readonly TelemetryQueryHandlerDecorator> _sut; + private readonly GetRolePermissionsQueryFixture _getRolePermissionsQueryFixture = new(); + private readonly RolePermissionsResponseFixture _rolePermissionsResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public TelemetryQueryHandlerDecoratorTests() + { + _mockInnerHandler = Substitute.For>>(); + ILogger>> mockLogger = + Substitute.For>>>(); + _sut = new TelemetryQueryHandlerDecorator>( + _mockInnerHandler, + mockLogger); + } + + [Fact] + public async Task HandleAsync_WhenInnerHandlerSucceeds_ShouldDelegateAndEmitSuccessfulTraceAndMetric() + { + // Arrange + List capturedActivities = []; + using ActivityListener activityListener = TelemetryTestHelpers.CreateActivityListener(capturedActivities); + List<(string InstrumentName, double Value, string Outcome)> metricMeasurements = []; + using MeterListener meterListener = TelemetryTestHelpers.CreateMeterListener(metricMeasurements); + GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.Create(); + Result expectedResult = Result.Success(_rolePermissionsResponseFixture.Create()); + _mockInnerHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedResult); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.Equal(expectedResult, result); + await _mockInnerHandler.Received(1).HandleAsync(query, CancellationToken.None); + Activity activity = Assert.Single(capturedActivities); + Assert.Equal($"Handle {_mockInnerHandler.GetType().Name}", activity.OperationName); + Assert.Equal("query", activity.GetTagItem("lumina.handler.type")); + Assert.Equal(ActivityStatusCode.Ok, activity.Status); + Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.duration" && measurement.Outcome == "success"); + Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.invocations" && measurement.Outcome == "success"); + } + + [Fact] + public async Task HandleAsync_WhenInnerHandlerReturnsFailedResult_ShouldReturnResultAndEmitFailureTraceAndMetric() + { + // Arrange + List capturedActivities = []; + using ActivityListener activityListener = TelemetryTestHelpers.CreateActivityListener(capturedActivities); + List<(string InstrumentName, double Value, string Outcome)> metricMeasurements = []; + using MeterListener meterListener = TelemetryTestHelpers.CreateMeterListener(metricMeasurements); + GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.Create(); + Result failedResult = Error.Failure("Test.Failed", "Test failure description"); + _mockInnerHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(failedResult); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.Equal(failedResult, result); + Activity activity = Assert.Single(capturedActivities); + Assert.Equal(ActivityStatusCode.Error, activity.Status); + Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.duration" && measurement.Outcome == "failure"); + Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.invocations" && measurement.Outcome == "failure"); + } + + [Fact] + public async Task HandleAsync_WhenInnerHandlerThrows_ShouldRethrowAndEmitFailureTraceAndMetric() + { + // Arrange + List capturedActivities = []; + using ActivityListener activityListener = TelemetryTestHelpers.CreateActivityListener(capturedActivities); + List<(string InstrumentName, double Value, string Outcome)> metricMeasurements = []; + using MeterListener meterListener = TelemetryTestHelpers.CreateMeterListener(metricMeasurements); + GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.Create(); + InvalidOperationException exception = new("boom"); + _mockInnerHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException>(exception)); + + // Act + await Assert.ThrowsAsync(() => _sut.HandleAsync(query, CancellationToken.None)); + + // Assert + Activity activity = Assert.Single(capturedActivities); + Assert.Equal(ActivityStatusCode.Error, activity.Status); + Assert.Contains(metricMeasurements, measurement => measurement.InstrumentName == "lumina.application.handler.duration" && measurement.Outcome == "failure"); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryTestHelpers.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryTestHelpers.cs new file mode 100644 index 00000000..64c03f30 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Telemetry/TelemetryTestHelpers.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Telemetry; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.Metrics; +#endregion + +namespace Lumina.Application.UnitTests.Common.Telemetry; + +/// +/// Test utilities for capturing the traces and metrics emitted by the application telemetry. +/// +[ExcludeFromCodeCoverage] +internal static class TelemetryTestHelpers +{ + /// + /// Creates an that captures every activity emitted by the activity source. + /// + /// The collection that stopped activities are added to. + /// The started . + public static ActivityListener CreateActivityListener(ICollection capturedActivities) + { + ActivityListener listener = new() + { + ShouldListenTo = source => source.Name == ApplicationTelemetry.SOURCE_NAME, + Sample = (ref ActivityCreationOptions options) => ActivitySamplingResult.AllData, + ActivityStopped = activity => capturedActivities.Add(activity) + }; + ActivitySource.AddActivityListener(listener); + return listener; + } + + /// + /// Creates a that captures every measurement emitted by the meter. + /// + /// The collection that measurements are added to. + /// The started . + public static MeterListener CreateMeterListener(ICollection<(string InstrumentName, double Value, string Outcome)> measurements) + { + MeterListener listener = new() + { + InstrumentPublished = (instrument, meterListener) => + { + if (instrument.Meter.Name == ApplicationTelemetry.SOURCE_NAME) + meterListener.EnableMeasurementEvents(instrument); + } + }; + // InstrumentPublished fires for instruments created after Start(), and Start() also replays every instrument + // that already exists on the meter; therefore the lazily-initialized static handler instruments are captured by + // every listener, whether they were created before or during the test + listener.SetMeasurementEventCallback((instrument, value, tags, state) => measurements.Add((instrument.Name, value, GetOutcomeTag(tags)))); + listener.SetMeasurementEventCallback((instrument, value, tags, state) => measurements.Add((instrument.Name, value, GetOutcomeTag(tags)))); + listener.Start(); + return listener; + } + + /// + /// Reads the value of the lumina.outcome tag from the specified tag list. + /// + /// The tag list of a measurement. + /// The outcome tag value, or an empty string when the tag is not present. + private static string GetOutcomeTag(ReadOnlySpan> tags) + { + foreach (KeyValuePair tag in tags) + if (tag.Key == "lumina.outcome") + return tag.Value?.ToString() ?? string.Empty; + return string.Empty; + } +}