< Summary

Information
Class: ArturRios.Util.WebApi.EndpointToggle.EndpointToggleAttribute
Assembly: ArturRios.Util.WebApi
File(s): /home/runner/work/dotnet-webapi-util/dotnet-webapi-util/src/EndpointToggle/EndpointToggleAttribute.cs
Line coverage
91%
Covered lines: 90
Uncovered lines: 8
Coverable lines: 98
Total lines: 250
Line coverage: 91.8%
Branch coverage
79%
Covered branches: 51
Total branches: 64
Branch coverage: 79.6%
Method coverage
100%
Covered methods: 13
Fully covered methods: 9
Total methods: 13
Method coverage: 100%
Full method coverage: 69.2%

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
.ctor(...)83.33%6691.3%
get_DefaultDisabledMessage()100%11100%
OnActionExecuting(...)90%101085.71%
ReturnObject(...)100%11100%
ReturnDefault(...)83.33%66100%
UnwrapReturnType(...)93.75%1616100%
GetToggleFromFile(...)60%121072.72%
GetToggleFromAppSettings(...)75%44100%
GetToggleFromEnvironmentVariables(...)100%11100%
ParseToggle(...)100%22100%
GetDefaultKey(...)62.5%8888.88%
GetMethodInfo(...)50%22100%

File(s)

/home/runner/work/dotnet-webapi-util/dotnet-webapi-util/src/EndpointToggle/EndpointToggleAttribute.cs

#LineLine coverage
 1using System.Net;
 2using System.Reflection;
 3using ArturRios.Configuration.Enums;
 4using ArturRios.Output;
 5using Microsoft.AspNetCore.Mvc;
 6using Microsoft.AspNetCore.Mvc.Controllers;
 7using Microsoft.AspNetCore.Mvc.Filters;
 8using Microsoft.Extensions.Configuration;
 9using Microsoft.Extensions.DependencyInjection;
 10
 11namespace ArturRios.Util.WebApi.EndpointToggle;
 12
 13/// <summary>Action filter attribute that enables or disables a single endpoint, either from a compile-time flag or from
 14/// a runtime configuration value. When the endpoint is disabled the request is short-circuited before the action runs
 15/// and the response is shaped according to <see cref="OutputType"/>: an empty status code, the action's default return
 16/// value, a <see cref="ProcessOutput"/> envelope, or a thrown <see cref="EndpointDisabledException"/>.</summary>
 17/// <remarks>
 18/// Two forms are available. The static form (<see cref="EndpointToggleAttribute(bool, HttpStatusCode, OutputType, strin
 19/// fixes the toggle at compile time. The configuration form
 20/// (<see cref="EndpointToggleAttribute(ConfigurationSourceType, string, string, string, HttpStatusCode, OutputType, str
 21/// resolves the toggle on each request from <c>appsettings.json</c> and/or environment variables, so an endpoint can be
 22/// turned on or off without redeploying.
 23/// </remarks>
 24/// <remarks>
 25/// ASP.NET Core reuses a single filter-attribute instance for every request to the action it decorates, so
 26/// nothing per-request is kept on the instance: the executing context is threaded through the helpers
 27/// instead. Keeping it in a field let two concurrent requests overwrite each other's.
 28/// </remarks>
 29[AttributeUsage(AttributeTargets.Method)]
 30public class EndpointToggleAttribute : ActionFilterAttribute
 31{
 32    private const string ControllerPlaceholder = "[Controller]";
 33    private const string DefaultAppSettingsKeyPrefix = "Endpoints:" + ControllerPlaceholder;
 34    private const string DefaultEnvFileKeyPrefix = "Endpoints_" + ControllerPlaceholder;
 35    private const string DisabledMessage = "This endpoint is currently disabled";
 36    private readonly ConfigurationSourceType _configurationSource;
 37    private readonly string _disabledMessage;
 38    private readonly OutputType _disabledOutputType;
 39    private readonly HttpStatusCode _disabledStatusCode;
 40    private readonly bool _isEnabled;
 3141    private readonly string _key = string.Empty;
 3142    private readonly string _keyPrefix = string.Empty;
 3143    private readonly string _keySeparator = string.Empty;
 3144    private readonly string _keySuffix = string.Empty;
 45    private readonly bool _useConfigurationFile;
 46
 47    /// <summary>Creates a toggle whose enabled state is fixed at compile time.</summary>
 48    /// <param name="isEnabled">Whether the endpoint is enabled. When <c>false</c> the action is short-circuited on ever
 49    /// <param name="disabledStatusCode">The HTTP status code returned when the endpoint is disabled. Defaults to 404 No
 50    /// <param name="disabledOutputType">How the disabled response is shaped. Defaults to <see cref="OutputType.Object"/
 51    /// <param name="disabledMessage">The message included in the disabled response when <paramref name="disabledOutputT
 1952    public EndpointToggleAttribute(
 1953        bool isEnabled = true,
 1954        HttpStatusCode disabledStatusCode = HttpStatusCode.NotFound,
 1955        OutputType disabledOutputType = OutputType.Object,
 1956        string disabledMessage = DisabledMessage
 1957    )
 58    {
 1959        _isEnabled = isEnabled;
 1960        _disabledStatusCode = disabledStatusCode;
 1961        _disabledMessage = disabledMessage;
 1962        _disabledOutputType = disabledOutputType;
 1963        _useConfigurationFile = false;
 1964    }
 65
 66    /// <summary>Creates a toggle whose enabled state is resolved on each request from configuration.</summary>
 67    /// <param name="configurationSource">Where the toggle value is read from: <c>AppSettings</c>, an env file / environ
 68    /// variables, or both. This also selects the key separator (<c>:</c> for app settings, <c>_</c> otherwise).</param>
 69    /// <param name="key">The full configuration key to read. When empty, a key is derived from the key prefix, the
 70    /// controller name, the action name and the optional suffix.</param>
 71    /// <param name="keyPrefix">The prefix for the derived key. When empty a default is used
 72    /// (<c>Endpoints:[Controller]</c> for app settings, <c>Endpoints_[Controller]</c> otherwise), with <c>[Controller]<
 73    /// replaced by the current controller name.</param>
 74    /// <param name="keySuffix">An optional suffix appended to the derived key.</param>
 75    /// <param name="disabledStatusCode">The HTTP status code returned when the endpoint is disabled. Defaults to 404 No
 76    /// <param name="disabledOutputType">How the disabled response is shaped. Defaults to <see cref="OutputType.Object"/
 77    /// <param name="disabledMessage">The message included in the disabled response when <paramref name="disabledOutputT
 1278    public EndpointToggleAttribute(
 1279        ConfigurationSourceType configurationSource,
 1280        string key = "",
 1281        string keyPrefix = "",
 1282        string keySuffix = "",
 1283        HttpStatusCode disabledStatusCode = HttpStatusCode.NotFound,
 1284        OutputType disabledOutputType = OutputType.Object,
 1285        string disabledMessage = DisabledMessage
 1286    )
 87    {
 1288        _configurationSource = configurationSource;
 1289        _key = key;
 1290        _disabledStatusCode = disabledStatusCode;
 1291        _disabledMessage = disabledMessage;
 1292        _disabledOutputType = disabledOutputType;
 1293        _useConfigurationFile = true;
 1294        _keySuffix = keySuffix;
 1295        _keySeparator = configurationSource == ConfigurationSourceType.AppSettings ? ":" : "_";
 96
 1297        if (string.IsNullOrWhiteSpace(keyPrefix))
 98        {
 1299            _keyPrefix = configurationSource == ConfigurationSourceType.AppSettings
 12100                ? DefaultAppSettingsKeyPrefix
 12101                : DefaultEnvFileKeyPrefix;
 102        }
 103        else
 104        {
 0105            _keyPrefix = keyPrefix;
 106        }
 0107    }
 108
 109    /// <summary>The default message describing a disabled endpoint: <c>"This endpoint is currently disabled"</c>.</summ
 1110    public static string DefaultDisabledMessage => DisabledMessage;
 111
 112    /// <summary>Evaluates the toggle before the action runs and, when the endpoint is disabled, short-circuits the
 113    /// pipeline with a response shaped according to the configured <see cref="OutputType"/>.</summary>
 114    /// <param name="context">The executing-action context for the current request.</param>
 115    /// <exception cref="EndpointDisabledException">Thrown when the endpoint is disabled and its disabled output type is
 116    public override void OnActionExecuting(ActionExecutingContext context)
 117    {
 429118        ArgumentNullException.ThrowIfNull(context);
 119
 428120        var isEnabled = _useConfigurationFile ? GetToggleFromFile(context) : _isEnabled;
 121
 428122        if (isEnabled)
 123        {
 8124            return;
 125        }
 126
 420127        switch (_disabledOutputType)
 128        {
 129            case OutputType.Void:
 1130                context.Result = new StatusCodeResult((int)_disabledStatusCode);
 1131                break;
 132            case OutputType.Default:
 133            case OutputType.Primitive:
 10134                ReturnDefault(context);
 10135                break;
 136            case OutputType.Object:
 406137                ReturnObject(context);
 406138                break;
 139            case OutputType.Exception:
 3140                throw new EndpointDisabledException([_disabledMessage], (int)_disabledStatusCode);
 141            default:
 0142                ReturnObject(context);
 143                break;
 144        }
 0145    }
 146
 147    private void ReturnObject(ActionExecutingContext context)
 148    {
 149        // An error, not a message: Success is computed from Errors, so the disabled text under Messages
 150        // came back as a 404 whose envelope said "success": true.
 406151        var output = ProcessOutput.New.WithError(_disabledMessage);
 152
 406153        context.Result = new ObjectResult(output) { StatusCode = (int)_disabledStatusCode };
 406154    }
 155
 156    private void ReturnDefault(ActionExecutingContext context)
 157    {
 10158        var returnType = UnwrapReturnType(GetMethodInfo(context)?.ReturnType);
 159
 10160        if (returnType is null)
 161        {
 3162            context.Result = new StatusCodeResult((int)_disabledStatusCode);
 163
 3164            return;
 165        }
 166
 7167        var defaultObj = returnType.IsValueType ? Activator.CreateInstance(returnType) : null;
 168
 7169        context.Result = new ObjectResult(defaultObj) { StatusCode = (int)_disabledStatusCode };
 7170    }
 171
 172    /// <summary>The type whose default the action would have produced: the <c>T</c> of <see cref="Task{TResult}"/>,
 173    /// <see cref="ValueTask{TResult}"/> or <see cref="ActionResult{TValue}"/>, or <see langword="null"/> when the
 174    /// action produces no value (<c>void</c>, <see cref="Task"/>, <see cref="ValueTask"/>).</summary>
 175    private static Type? UnwrapReturnType(Type? returnType)
 176    {
 15177        if (returnType is null || returnType == typeof(void) || returnType == typeof(Task) ||
 15178            returnType == typeof(ValueTask))
 179        {
 3180            return null;
 181        }
 182
 12183        if (returnType.IsGenericType)
 184        {
 5185            var definition = returnType.GetGenericTypeDefinition();
 186
 5187            if (definition == typeof(Task<>) || definition == typeof(ValueTask<>) ||
 5188                definition == typeof(ActionResult<>))
 189            {
 5190                return UnwrapReturnType(returnType.GetGenericArguments()[0]);
 191            }
 192        }
 193
 7194        return returnType;
 195    }
 196
 197    private bool GetToggleFromFile(ActionExecutingContext context)
 198    {
 211199        var toggleKey = string.IsNullOrWhiteSpace(_key) ? GetDefaultKey(context) : _key;
 200
 211201        if (string.IsNullOrWhiteSpace(toggleKey))
 202        {
 0203            return true;
 204        }
 205
 211206        return _configurationSource switch
 211207        {
 7208            ConfigurationSourceType.AppSettings => GetToggleFromAppSettings(context, toggleKey) ?? true,
 211209            ConfigurationSourceType.EnvFile or ConfigurationSourceType.EnvironmentVariables =>
 204210                GetToggleFromEnvironmentVariables(toggleKey) ?? true,
 0211            _ => GetToggleFromAppSettings(context, toggleKey) ??
 0212                 GetToggleFromEnvironmentVariables(toggleKey) ?? true
 211213        };
 214    }
 215
 216    private static bool? GetToggleFromAppSettings(ActionExecutingContext context, string key)
 217    {
 7218        var config = context.HttpContext.RequestServices?.GetService<IConfiguration>();
 219
 7220        return ParseToggle(config?[key]);
 221    }
 222
 223    private static bool? GetToggleFromEnvironmentVariables(string key) =>
 204224        ParseToggle(Environment.GetEnvironmentVariable(key));
 225
 211226    private static bool? ParseToggle(string? value) => bool.TryParse(value, out var parsed) ? parsed : null;
 227
 228    private string? GetDefaultKey(ActionExecutingContext context)
 229    {
 2230        var methodInfo = GetMethodInfo(context);
 231
 2232        if (methodInfo is null)
 233        {
 0234            return null;
 235        }
 236
 2237        var controllerName = (context.ActionDescriptor as ControllerActionDescriptor)?.ControllerName;
 238
 2239        var keyPrefix = controllerName is null
 2240            ? _keyPrefix.Replace($"{_keySeparator}{ControllerPlaceholder}", string.Empty)
 2241            : _keyPrefix.Replace(ControllerPlaceholder, controllerName);
 242
 2243        var key = $"{keyPrefix}{_keySeparator}{methodInfo.Name}";
 244
 2245        return string.IsNullOrWhiteSpace(_keySuffix) ? key : $"{key}{_keySeparator}{_keySuffix}";
 246    }
 247
 248    private static MethodInfo? GetMethodInfo(ActionExecutingContext context) =>
 12249        (context.ActionDescriptor as ControllerActionDescriptor)?.MethodInfo;
 250}