| | | 1 | | using System.Net; |
| | | 2 | | using System.Reflection; |
| | | 3 | | using ArturRios.Configuration.Enums; |
| | | 4 | | using ArturRios.Output; |
| | | 5 | | using Microsoft.AspNetCore.Mvc; |
| | | 6 | | using Microsoft.AspNetCore.Mvc.Controllers; |
| | | 7 | | using Microsoft.AspNetCore.Mvc.Filters; |
| | | 8 | | using Microsoft.Extensions.Configuration; |
| | | 9 | | using Microsoft.Extensions.DependencyInjection; |
| | | 10 | | |
| | | 11 | | namespace 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)] |
| | | 30 | | public 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; |
| | 31 | 41 | | private readonly string _key = string.Empty; |
| | 31 | 42 | | private readonly string _keyPrefix = string.Empty; |
| | 31 | 43 | | private readonly string _keySeparator = string.Empty; |
| | 31 | 44 | | 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 |
| | 19 | 52 | | public EndpointToggleAttribute( |
| | 19 | 53 | | bool isEnabled = true, |
| | 19 | 54 | | HttpStatusCode disabledStatusCode = HttpStatusCode.NotFound, |
| | 19 | 55 | | OutputType disabledOutputType = OutputType.Object, |
| | 19 | 56 | | string disabledMessage = DisabledMessage |
| | 19 | 57 | | ) |
| | | 58 | | { |
| | 19 | 59 | | _isEnabled = isEnabled; |
| | 19 | 60 | | _disabledStatusCode = disabledStatusCode; |
| | 19 | 61 | | _disabledMessage = disabledMessage; |
| | 19 | 62 | | _disabledOutputType = disabledOutputType; |
| | 19 | 63 | | _useConfigurationFile = false; |
| | 19 | 64 | | } |
| | | 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 |
| | 12 | 78 | | public EndpointToggleAttribute( |
| | 12 | 79 | | ConfigurationSourceType configurationSource, |
| | 12 | 80 | | string key = "", |
| | 12 | 81 | | string keyPrefix = "", |
| | 12 | 82 | | string keySuffix = "", |
| | 12 | 83 | | HttpStatusCode disabledStatusCode = HttpStatusCode.NotFound, |
| | 12 | 84 | | OutputType disabledOutputType = OutputType.Object, |
| | 12 | 85 | | string disabledMessage = DisabledMessage |
| | 12 | 86 | | ) |
| | | 87 | | { |
| | 12 | 88 | | _configurationSource = configurationSource; |
| | 12 | 89 | | _key = key; |
| | 12 | 90 | | _disabledStatusCode = disabledStatusCode; |
| | 12 | 91 | | _disabledMessage = disabledMessage; |
| | 12 | 92 | | _disabledOutputType = disabledOutputType; |
| | 12 | 93 | | _useConfigurationFile = true; |
| | 12 | 94 | | _keySuffix = keySuffix; |
| | 12 | 95 | | _keySeparator = configurationSource == ConfigurationSourceType.AppSettings ? ":" : "_"; |
| | | 96 | | |
| | 12 | 97 | | if (string.IsNullOrWhiteSpace(keyPrefix)) |
| | | 98 | | { |
| | 12 | 99 | | _keyPrefix = configurationSource == ConfigurationSourceType.AppSettings |
| | 12 | 100 | | ? DefaultAppSettingsKeyPrefix |
| | 12 | 101 | | : DefaultEnvFileKeyPrefix; |
| | | 102 | | } |
| | | 103 | | else |
| | | 104 | | { |
| | 0 | 105 | | _keyPrefix = keyPrefix; |
| | | 106 | | } |
| | 0 | 107 | | } |
| | | 108 | | |
| | | 109 | | /// <summary>The default message describing a disabled endpoint: <c>"This endpoint is currently disabled"</c>.</summ |
| | 1 | 110 | | 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 | | { |
| | 429 | 118 | | ArgumentNullException.ThrowIfNull(context); |
| | | 119 | | |
| | 428 | 120 | | var isEnabled = _useConfigurationFile ? GetToggleFromFile(context) : _isEnabled; |
| | | 121 | | |
| | 428 | 122 | | if (isEnabled) |
| | | 123 | | { |
| | 8 | 124 | | return; |
| | | 125 | | } |
| | | 126 | | |
| | 420 | 127 | | switch (_disabledOutputType) |
| | | 128 | | { |
| | | 129 | | case OutputType.Void: |
| | 1 | 130 | | context.Result = new StatusCodeResult((int)_disabledStatusCode); |
| | 1 | 131 | | break; |
| | | 132 | | case OutputType.Default: |
| | | 133 | | case OutputType.Primitive: |
| | 10 | 134 | | ReturnDefault(context); |
| | 10 | 135 | | break; |
| | | 136 | | case OutputType.Object: |
| | 406 | 137 | | ReturnObject(context); |
| | 406 | 138 | | break; |
| | | 139 | | case OutputType.Exception: |
| | 3 | 140 | | throw new EndpointDisabledException([_disabledMessage], (int)_disabledStatusCode); |
| | | 141 | | default: |
| | 0 | 142 | | ReturnObject(context); |
| | | 143 | | break; |
| | | 144 | | } |
| | 0 | 145 | | } |
| | | 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. |
| | 406 | 151 | | var output = ProcessOutput.New.WithError(_disabledMessage); |
| | | 152 | | |
| | 406 | 153 | | context.Result = new ObjectResult(output) { StatusCode = (int)_disabledStatusCode }; |
| | 406 | 154 | | } |
| | | 155 | | |
| | | 156 | | private void ReturnDefault(ActionExecutingContext context) |
| | | 157 | | { |
| | 10 | 158 | | var returnType = UnwrapReturnType(GetMethodInfo(context)?.ReturnType); |
| | | 159 | | |
| | 10 | 160 | | if (returnType is null) |
| | | 161 | | { |
| | 3 | 162 | | context.Result = new StatusCodeResult((int)_disabledStatusCode); |
| | | 163 | | |
| | 3 | 164 | | return; |
| | | 165 | | } |
| | | 166 | | |
| | 7 | 167 | | var defaultObj = returnType.IsValueType ? Activator.CreateInstance(returnType) : null; |
| | | 168 | | |
| | 7 | 169 | | context.Result = new ObjectResult(defaultObj) { StatusCode = (int)_disabledStatusCode }; |
| | 7 | 170 | | } |
| | | 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 | | { |
| | 15 | 177 | | if (returnType is null || returnType == typeof(void) || returnType == typeof(Task) || |
| | 15 | 178 | | returnType == typeof(ValueTask)) |
| | | 179 | | { |
| | 3 | 180 | | return null; |
| | | 181 | | } |
| | | 182 | | |
| | 12 | 183 | | if (returnType.IsGenericType) |
| | | 184 | | { |
| | 5 | 185 | | var definition = returnType.GetGenericTypeDefinition(); |
| | | 186 | | |
| | 5 | 187 | | if (definition == typeof(Task<>) || definition == typeof(ValueTask<>) || |
| | 5 | 188 | | definition == typeof(ActionResult<>)) |
| | | 189 | | { |
| | 5 | 190 | | return UnwrapReturnType(returnType.GetGenericArguments()[0]); |
| | | 191 | | } |
| | | 192 | | } |
| | | 193 | | |
| | 7 | 194 | | return returnType; |
| | | 195 | | } |
| | | 196 | | |
| | | 197 | | private bool GetToggleFromFile(ActionExecutingContext context) |
| | | 198 | | { |
| | 211 | 199 | | var toggleKey = string.IsNullOrWhiteSpace(_key) ? GetDefaultKey(context) : _key; |
| | | 200 | | |
| | 211 | 201 | | if (string.IsNullOrWhiteSpace(toggleKey)) |
| | | 202 | | { |
| | 0 | 203 | | return true; |
| | | 204 | | } |
| | | 205 | | |
| | 211 | 206 | | return _configurationSource switch |
| | 211 | 207 | | { |
| | 7 | 208 | | ConfigurationSourceType.AppSettings => GetToggleFromAppSettings(context, toggleKey) ?? true, |
| | 211 | 209 | | ConfigurationSourceType.EnvFile or ConfigurationSourceType.EnvironmentVariables => |
| | 204 | 210 | | GetToggleFromEnvironmentVariables(toggleKey) ?? true, |
| | 0 | 211 | | _ => GetToggleFromAppSettings(context, toggleKey) ?? |
| | 0 | 212 | | GetToggleFromEnvironmentVariables(toggleKey) ?? true |
| | 211 | 213 | | }; |
| | | 214 | | } |
| | | 215 | | |
| | | 216 | | private static bool? GetToggleFromAppSettings(ActionExecutingContext context, string key) |
| | | 217 | | { |
| | 7 | 218 | | var config = context.HttpContext.RequestServices?.GetService<IConfiguration>(); |
| | | 219 | | |
| | 7 | 220 | | return ParseToggle(config?[key]); |
| | | 221 | | } |
| | | 222 | | |
| | | 223 | | private static bool? GetToggleFromEnvironmentVariables(string key) => |
| | 204 | 224 | | ParseToggle(Environment.GetEnvironmentVariable(key)); |
| | | 225 | | |
| | 211 | 226 | | private static bool? ParseToggle(string? value) => bool.TryParse(value, out var parsed) ? parsed : null; |
| | | 227 | | |
| | | 228 | | private string? GetDefaultKey(ActionExecutingContext context) |
| | | 229 | | { |
| | 2 | 230 | | var methodInfo = GetMethodInfo(context); |
| | | 231 | | |
| | 2 | 232 | | if (methodInfo is null) |
| | | 233 | | { |
| | 0 | 234 | | return null; |
| | | 235 | | } |
| | | 236 | | |
| | 2 | 237 | | var controllerName = (context.ActionDescriptor as ControllerActionDescriptor)?.ControllerName; |
| | | 238 | | |
| | 2 | 239 | | var keyPrefix = controllerName is null |
| | 2 | 240 | | ? _keyPrefix.Replace($"{_keySeparator}{ControllerPlaceholder}", string.Empty) |
| | 2 | 241 | | : _keyPrefix.Replace(ControllerPlaceholder, controllerName); |
| | | 242 | | |
| | 2 | 243 | | var key = $"{keyPrefix}{_keySeparator}{methodInfo.Name}"; |
| | | 244 | | |
| | 2 | 245 | | return string.IsNullOrWhiteSpace(_keySuffix) ? key : $"{key}{_keySeparator}{_keySuffix}"; |
| | | 246 | | } |
| | | 247 | | |
| | | 248 | | private static MethodInfo? GetMethodInfo(ActionExecutingContext context) => |
| | 12 | 249 | | (context.ActionDescriptor as ControllerActionDescriptor)?.MethodInfo; |
| | | 250 | | } |