#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));
}
}