| | | 1 | | using System.Net; |
| | | 2 | | using ArturRios.Configuration.Enums; |
| | | 3 | | using ArturRios.Output; |
| | | 4 | | using Microsoft.AspNetCore.Mvc; |
| | | 5 | | using Microsoft.AspNetCore.Mvc.Controllers; |
| | | 6 | | using Microsoft.AspNetCore.Mvc.Filters; |
| | | 7 | | using Microsoft.Extensions.Configuration; |
| | | 8 | | |
| | | 9 | | namespace ArturRios.Util.WebApi.EndpointToggle; |
| | | 10 | | |
| | | 11 | | /// <summary>Action filter attribute that enables or disables a single endpoint, either from a compile-time flag or from |
| | | 12 | | /// a runtime configuration value. When the endpoint is disabled the request is short-circuited before the action runs |
| | | 13 | | /// and the response is shaped according to <see cref="OutputType"/>: an empty status code, the action's default return |
| | | 14 | | /// value, a <see cref="ProcessOutput"/> envelope, or a thrown <see cref="EndpointDisabledException"/>.</summary> |
| | | 15 | | /// <remarks> |
| | | 16 | | /// Two forms are available. The static form (<see cref="EndpointToggleAttribute(bool, HttpStatusCode, OutputType, strin |
| | | 17 | | /// fixes the toggle at compile time. The configuration form |
| | | 18 | | /// (<see cref="EndpointToggleAttribute(ConfigurationSourceType, string, string, string, HttpStatusCode, OutputType, str |
| | | 19 | | /// resolves the toggle on each request from <c>appsettings.json</c> and/or environment variables, so an endpoint can be |
| | | 20 | | /// turned on or off without redeploying. |
| | | 21 | | /// </remarks> |
| | | 22 | | [AttributeUsage(AttributeTargets.Method)] |
| | | 23 | | public class EndpointToggleAttribute : ActionFilterAttribute |
| | | 24 | | { |
| | | 25 | | private const string DefaultAppSettingsKeyPrefix = "Endpoints:[Controller]"; |
| | | 26 | | private const string DefaultEnvFileKeyPrefix = "Endpoints_[Controller]"; |
| | | 27 | | private readonly ConfigurationSourceType _configurationSource; |
| | | 28 | | private readonly string _disabledMessage; |
| | | 29 | | private readonly OutputType _disabledOutputType; |
| | | 30 | | private readonly HttpStatusCode _disabledStatusCode; |
| | | 31 | | private readonly bool _isEnabled; |
| | 19 | 32 | | private readonly string _key = string.Empty; |
| | 19 | 33 | | private readonly string _keyPrefix = string.Empty; |
| | 19 | 34 | | private readonly string _keySeparator = string.Empty; |
| | 19 | 35 | | private readonly string _keySuffix = string.Empty; |
| | | 36 | | private readonly bool _useConfigurationFile; |
| | | 37 | | |
| | 19 | 38 | | private ActionExecutingContext _context = null!; |
| | | 39 | | |
| | | 40 | | /// <summary>Creates a toggle whose enabled state is fixed at compile time.</summary> |
| | | 41 | | /// <param name="isEnabled">Whether the endpoint is enabled. When <c>false</c> the action is short-circuited on ever |
| | | 42 | | /// <param name="disabledStatusCode">The HTTP status code returned when the endpoint is disabled. Defaults to 404 No |
| | | 43 | | /// <param name="disabledOutputType">How the disabled response is shaped. Defaults to <see cref="OutputType.Object"/ |
| | | 44 | | /// <param name="disabledMessage">The message included in the disabled response when <paramref name="disabledOutputT |
| | 8 | 45 | | public EndpointToggleAttribute( |
| | 8 | 46 | | bool isEnabled = true, |
| | 8 | 47 | | HttpStatusCode disabledStatusCode = HttpStatusCode.NotFound, |
| | 8 | 48 | | OutputType disabledOutputType = OutputType.Object, |
| | 8 | 49 | | string disabledMessage = "This endpoint is currently disabled" |
| | 8 | 50 | | ) |
| | 8 | 51 | | { |
| | 8 | 52 | | _isEnabled = isEnabled; |
| | 8 | 53 | | _disabledStatusCode = disabledStatusCode; |
| | 8 | 54 | | _disabledMessage = disabledMessage; |
| | 8 | 55 | | _disabledOutputType = disabledOutputType; |
| | 8 | 56 | | _useConfigurationFile = false; |
| | 8 | 57 | | } |
| | | 58 | | |
| | | 59 | | /// <summary>Creates a toggle whose enabled state is resolved on each request from configuration.</summary> |
| | | 60 | | /// <param name="configurationSource">Where the toggle value is read from: <c>AppSettings</c>, an env file / environ |
| | | 61 | | /// variables, or both. This also selects the key separator (<c>:</c> for app settings, <c>_</c> otherwise).</param> |
| | | 62 | | /// <param name="key">The full configuration key to read. When empty, a key is derived from the key prefix, the |
| | | 63 | | /// controller name, the action name and the optional suffix.</param> |
| | | 64 | | /// <param name="keyPrefix">The prefix for the derived key. When empty a default is used |
| | | 65 | | /// (<c>Endpoints:[Controller]</c> for app settings, <c>Endpoints_[Controller]</c> otherwise), with <c>[Controller]< |
| | | 66 | | /// replaced by the current controller name.</param> |
| | | 67 | | /// <param name="keySuffix">An optional suffix appended to the derived key.</param> |
| | | 68 | | /// <param name="disabledStatusCode">The HTTP status code returned when the endpoint is disabled. Defaults to 404 No |
| | | 69 | | /// <param name="disabledOutputType">How the disabled response is shaped. Defaults to <see cref="OutputType.Object"/ |
| | | 70 | | /// <param name="disabledMessage">The message included in the disabled response when <paramref name="disabledOutputT |
| | 11 | 71 | | public EndpointToggleAttribute( |
| | 11 | 72 | | ConfigurationSourceType configurationSource, |
| | 11 | 73 | | string key = "", |
| | 11 | 74 | | string keyPrefix = "", |
| | 11 | 75 | | string keySuffix = "", |
| | 11 | 76 | | HttpStatusCode disabledStatusCode = HttpStatusCode.NotFound, |
| | 11 | 77 | | OutputType disabledOutputType = OutputType.Object, |
| | 11 | 78 | | string disabledMessage = "This endpoint is currently disabled" |
| | 11 | 79 | | ) |
| | 11 | 80 | | { |
| | 11 | 81 | | _configurationSource = configurationSource; |
| | 11 | 82 | | _key = key; |
| | 11 | 83 | | _disabledStatusCode = disabledStatusCode; |
| | 11 | 84 | | _disabledMessage = disabledMessage; |
| | 11 | 85 | | _disabledOutputType = disabledOutputType; |
| | 11 | 86 | | _useConfigurationFile = true; |
| | 11 | 87 | | _keySuffix = keySuffix; |
| | 11 | 88 | | _keySeparator = configurationSource == ConfigurationSourceType.AppSettings ? ":" : "_"; |
| | | 89 | | |
| | 11 | 90 | | if (string.IsNullOrWhiteSpace(keyPrefix)) |
| | 11 | 91 | | { |
| | 11 | 92 | | _keyPrefix = configurationSource == ConfigurationSourceType.AppSettings |
| | 11 | 93 | | ? DefaultAppSettingsKeyPrefix |
| | 11 | 94 | | : DefaultEnvFileKeyPrefix; |
| | 11 | 95 | | } |
| | | 96 | | else |
| | 0 | 97 | | { |
| | 0 | 98 | | _keyPrefix = keyPrefix; |
| | 0 | 99 | | } |
| | 11 | 100 | | } |
| | | 101 | | |
| | | 102 | | /// <summary>The default message describing a disabled endpoint: <c>"This endpoint is currently disabled"</c>.</summ |
| | 2 | 103 | | public static string DefaultDisabledMessage => "This endpoint is currently disabled"; |
| | | 104 | | |
| | | 105 | | /// <summary>Evaluates the toggle before the action runs and, when the endpoint is disabled, short-circuits the |
| | | 106 | | /// pipeline with a response shaped according to the configured <see cref="OutputType"/>.</summary> |
| | | 107 | | /// <param name="context">The executing-action context for the current request.</param> |
| | | 108 | | /// <exception cref="EndpointDisabledException">Thrown when the endpoint is disabled and its disabled output type is |
| | | 109 | | public override void OnActionExecuting(ActionExecutingContext context) |
| | 19 | 110 | | { |
| | 19 | 111 | | _context = context; |
| | | 112 | | |
| | 19 | 113 | | var isEnabled = _useConfigurationFile ? GetToggleFromFile() : _isEnabled; |
| | | 114 | | |
| | 19 | 115 | | if (isEnabled) |
| | 8 | 116 | | { |
| | 8 | 117 | | return; |
| | | 118 | | } |
| | | 119 | | |
| | 11 | 120 | | switch (_disabledOutputType) |
| | | 121 | | { |
| | | 122 | | case OutputType.Void: |
| | 1 | 123 | | _context.Result = new StatusCodeResult((int)_disabledStatusCode); |
| | 1 | 124 | | break; |
| | | 125 | | case OutputType.Default: |
| | 4 | 126 | | ReturnDefault(); |
| | 4 | 127 | | break; |
| | | 128 | | case OutputType.Object: |
| | 5 | 129 | | ReturnObject(); |
| | 5 | 130 | | break; |
| | | 131 | | case OutputType.Exception: |
| | 1 | 132 | | throw new EndpointDisabledException([DefaultDisabledMessage]); |
| | | 133 | | case OutputType.Primitive: |
| | 0 | 134 | | ReturnDefault(); |
| | 0 | 135 | | break; |
| | | 136 | | default: |
| | 0 | 137 | | ReturnObject(); |
| | 0 | 138 | | break; |
| | | 139 | | } |
| | 18 | 140 | | } |
| | | 141 | | |
| | | 142 | | private void ReturnObject() |
| | 5 | 143 | | { |
| | 5 | 144 | | var output = ProcessOutput.New.WithMessage(_disabledMessage); |
| | | 145 | | |
| | 5 | 146 | | _context.Result = new ObjectResult(output) { StatusCode = (int)_disabledStatusCode }; |
| | 5 | 147 | | } |
| | | 148 | | |
| | | 149 | | private void ReturnDefault() |
| | 4 | 150 | | { |
| | 4 | 151 | | var methodInfo = (_context.ActionDescriptor as ControllerActionDescriptor)?.MethodInfo; |
| | 4 | 152 | | var returnType = methodInfo?.ReturnType; |
| | | 153 | | |
| | 4 | 154 | | if (returnType == null || returnType == typeof(void)) |
| | 1 | 155 | | { |
| | 1 | 156 | | _context.Result = new StatusCodeResult((int)_disabledStatusCode); |
| | | 157 | | |
| | 1 | 158 | | return; |
| | | 159 | | } |
| | | 160 | | |
| | 3 | 161 | | var defaultObj = returnType.IsValueType ? Activator.CreateInstance(returnType) : null; |
| | | 162 | | |
| | 3 | 163 | | _context.Result = new ObjectResult(defaultObj) { StatusCode = (int)_disabledStatusCode }; |
| | 4 | 164 | | } |
| | | 165 | | |
| | | 166 | | private bool GetToggleFromFile() |
| | 11 | 167 | | { |
| | 11 | 168 | | var toggleKey = string.IsNullOrWhiteSpace(_key) ? GetDefaultKey() : _key; |
| | | 169 | | |
| | 11 | 170 | | if (string.IsNullOrWhiteSpace(toggleKey)) |
| | 0 | 171 | | { |
| | 0 | 172 | | return true; |
| | | 173 | | } |
| | | 174 | | |
| | 11 | 175 | | return _configurationSource switch |
| | 11 | 176 | | { |
| | 7 | 177 | | ConfigurationSourceType.AppSettings => GetToggleFromAppSettings(toggleKey) ?? true, |
| | 11 | 178 | | ConfigurationSourceType.EnvFile or ConfigurationSourceType.EnvironmentVariables => |
| | 4 | 179 | | GetToggleFromEnvironmentVariables(toggleKey) ?? true, |
| | 0 | 180 | | _ => GetToggleFromAppSettings(toggleKey) ?? |
| | 0 | 181 | | GetToggleFromEnvironmentVariables(toggleKey) ?? true |
| | 11 | 182 | | }; |
| | 11 | 183 | | } |
| | | 184 | | |
| | | 185 | | private bool? GetToggleFromAppSettings(string key) |
| | 7 | 186 | | { |
| | 7 | 187 | | if (_context.HttpContext.RequestServices.GetService(typeof(IConfiguration)) is not IConfiguration config) |
| | 1 | 188 | | { |
| | 1 | 189 | | return null; |
| | | 190 | | } |
| | | 191 | | |
| | 6 | 192 | | var value = config[key]; |
| | | 193 | | |
| | 6 | 194 | | if (string.IsNullOrEmpty(value)) |
| | 1 | 195 | | { |
| | 1 | 196 | | return null; |
| | | 197 | | } |
| | | 198 | | |
| | 5 | 199 | | return bool.TryParse(value, out var parsed) ? parsed : null; |
| | 7 | 200 | | } |
| | | 201 | | |
| | | 202 | | private static bool? GetToggleFromEnvironmentVariables(string key) |
| | 4 | 203 | | { |
| | 4 | 204 | | var envValue = Environment.GetEnvironmentVariable(key); |
| | | 205 | | |
| | 4 | 206 | | if (string.IsNullOrEmpty(envValue)) |
| | 1 | 207 | | { |
| | 1 | 208 | | return null; |
| | | 209 | | } |
| | | 210 | | |
| | 3 | 211 | | if (bool.TryParse(envValue, out var parsed)) |
| | 2 | 212 | | { |
| | 2 | 213 | | return parsed; |
| | | 214 | | } |
| | | 215 | | |
| | 1 | 216 | | return null; |
| | 4 | 217 | | } |
| | | 218 | | |
| | | 219 | | private string? GetDefaultKey() |
| | 2 | 220 | | { |
| | 2 | 221 | | var methodInfo = (_context.ActionDescriptor as ControllerActionDescriptor)?.MethodInfo; |
| | 2 | 222 | | var methodName = methodInfo?.Name; |
| | | 223 | | |
| | 2 | 224 | | var keyPrefix = GetKeyPrefix(_key); |
| | | 225 | | |
| | 2 | 226 | | return methodInfo is not null ? AddKeySuffix($"{keyPrefix}{_keySeparator}{methodName}") : null; |
| | 2 | 227 | | } |
| | | 228 | | |
| | | 229 | | private string? GetControllerName() |
| | 4 | 230 | | { |
| | 4 | 231 | | var controllerActionDescriptor = _context.ActionDescriptor as ControllerActionDescriptor; |
| | 4 | 232 | | return controllerActionDescriptor?.ControllerName; |
| | 4 | 233 | | } |
| | | 234 | | |
| | | 235 | | private string GetKeyPrefix(string key) |
| | 2 | 236 | | { |
| | 2 | 237 | | if (string.IsNullOrWhiteSpace(_keyPrefix)) |
| | 0 | 238 | | { |
| | 0 | 239 | | return key; |
| | | 240 | | } |
| | | 241 | | |
| | 2 | 242 | | var controllerName = GetControllerName(); |
| | | 243 | | |
| | 2 | 244 | | return controllerName is null |
| | 2 | 245 | | ? _keyPrefix.Replace($"{_keySeparator}[Controller]", string.Empty) |
| | 2 | 246 | | : _keyPrefix.Replace("[Controller]", GetControllerName()); |
| | 2 | 247 | | } |
| | | 248 | | |
| | | 249 | | private string AddKeySuffix(string key) => |
| | 2 | 250 | | string.IsNullOrWhiteSpace(_keySuffix) ? key : $"{key}{_keySeparator}{_keySuffix}"; |
| | | 251 | | } |