| | | 1 | | using System.Collections; |
| | | 2 | | using System.Reflection; |
| | | 3 | | using Microsoft.AspNetCore.Mvc; |
| | | 4 | | using Microsoft.AspNetCore.Mvc.Filters; |
| | | 5 | | using Microsoft.Extensions.Options; |
| | | 6 | | |
| | | 7 | | namespace OzonOrdersWeb.Observability; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Фиксирует legacy-операции, которые сообщают об ошибке JSON/TempData, но возвращают HTTP 200. |
| | | 11 | | /// Такие ответы не видны middleware по HTTP status и иначе не попадают в общий реестр проблем. |
| | | 12 | | /// </summary> |
| | 7 | 13 | | public sealed class BusinessFailureLoggingFilter( |
| | 7 | 14 | | ILogger<BusinessFailureLoggingFilter> logger, |
| | 7 | 15 | | SensitiveDataRedactor redactor, |
| | 7 | 16 | | IOptions<ObservabilityOptions> options) : IAsyncResultFilter |
| | | 17 | | { |
| | | 18 | | public const string LoggedItemKey = "__studio2_business_failure_logged"; |
| | 7 | 19 | | private readonly ObservabilityOptions _options = options.Value; |
| | | 20 | | |
| | 1 | 21 | | private static readonly HashSet<string> ExcludedPaths = new(StringComparer.OrdinalIgnoreCase) |
| | 1 | 22 | | { |
| | 1 | 23 | | "/Studio2/OzonChat/GetTotalUnreadCount" |
| | 1 | 24 | | }; |
| | | 25 | | |
| | | 26 | | /// <summary> |
| | | 27 | | /// Операции, где отказ — штатный ответ пользователю, а не сбой (#1418, #1813, #2134, #2383): |
| | | 28 | | /// Ozon не выдаёт этикетки для отменённых/отгруженных отправлений, количество расходится с Ozon, |
| | | 29 | | /// данные экземпляров маркировки не подтверждены к сборке Ozon (SetOzonExemplars); |
| | | 30 | | /// проведение транзакции TransactionsGrid само логирует остановку шага (TransactionCommitService). |
| | | 31 | | /// Для них запись остаётся в Seq уровнем Information и не заводит инцидент. |
| | | 32 | | /// </summary> |
| | 1 | 33 | | private static readonly HashSet<string> ExpectedFailurePaths = new(StringComparer.OrdinalIgnoreCase) |
| | 1 | 34 | | { |
| | 1 | 35 | | "/Studio2/Orders/UpdateOrdersStatus", |
| | 1 | 36 | | "/Studio2/Orders/GenerateLabels", |
| | 1 | 37 | | "/Studio2/Orders/SetOzonExemplars" |
| | 1 | 38 | | }; |
| | | 39 | | |
| | | 40 | | internal static bool IsExpectedFailurePath(string? path) |
| | | 41 | | { |
| | 25 | 42 | | if (string.IsNullOrEmpty(path)) |
| | 0 | 43 | | return false; |
| | 25 | 44 | | if (ExpectedFailurePaths.Contains(path)) |
| | 14 | 45 | | return true; |
| | | 46 | | |
| | | 47 | | // /Studio2/TransactionsGrid/{slug}/Commit |
| | 11 | 48 | | var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries); |
| | 11 | 49 | | return segments.Length == 4 |
| | 11 | 50 | | && segments[0].Equals("Studio2", StringComparison.OrdinalIgnoreCase) |
| | 11 | 51 | | && segments[1].Equals("TransactionsGrid", StringComparison.OrdinalIgnoreCase) |
| | 11 | 52 | | && segments[3].Equals("Commit", StringComparison.OrdinalIgnoreCase); |
| | | 53 | | } |
| | | 54 | | |
| | | 55 | | public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) |
| | | 56 | | { |
| | 7 | 57 | | var path = context.HttpContext.Request.Path.Value; |
| | 7 | 58 | | if (path != null && ExcludedPaths.Contains(path)) |
| | | 59 | | { |
| | 0 | 60 | | context.HttpContext.Items[LoggedItemKey] = true; |
| | | 61 | | } |
| | | 62 | | |
| | 7 | 63 | | if (!context.HttpContext.Items.ContainsKey(LoggedItemKey) |
| | 7 | 64 | | && TryFindFailure(context, out var message)) |
| | | 65 | | { |
| | 7 | 66 | | context.HttpContext.Items[LoggedItemKey] = true; |
| | 7 | 67 | | var routeData = context.RouteData; |
| | 7 | 68 | | using var scope = logger.BeginScope(new Dictionary<string, object?> |
| | 7 | 69 | | { |
| | 7 | 70 | | ["EventKind"] = "BusinessOperationFailed", |
| | 7 | 71 | | ["EventCategory"] = "backend", |
| | 7 | 72 | | ["RequestPath"] = context.HttpContext.Request.Path.Value, |
| | 7 | 73 | | ["HttpMethod"] = context.HttpContext.Request.Method, |
| | 7 | 74 | | ["StatusCode"] = GetStatusCode(context.Result), |
| | 7 | 75 | | ["Controller"] = routeData.Values["controller"]?.ToString(), |
| | 7 | 76 | | ["Action"] = routeData.Values["action"]?.ToString(), |
| | 7 | 77 | | ["TraceId"] = context.HttpContext.TraceIdentifier, |
| | 7 | 78 | | ["BusinessError"] = redactor.Redact(message, _options.MaxPayloadCharacters) |
| | 7 | 79 | | }); |
| | 7 | 80 | | logger.Log(IsExpectedFailurePath(path) ? LogLevel.Information : LogLevel.Warning, |
| | 7 | 81 | | "Операция {Method} {Path} сообщила о бизнес-ошибке при успешном HTTP-ответе", |
| | 7 | 82 | | context.HttpContext.Request.Method, context.HttpContext.Request.Path); |
| | | 83 | | } |
| | | 84 | | |
| | 7 | 85 | | await next(); |
| | 7 | 86 | | } |
| | | 87 | | |
| | 7 | 88 | | private static int GetStatusCode(IActionResult result) => result switch |
| | 7 | 89 | | { |
| | 0 | 90 | | ObjectResult objectResult => objectResult.StatusCode ?? StatusCodes.Status200OK, |
| | 0 | 91 | | StatusCodeResult statusCodeResult => statusCodeResult.StatusCode, |
| | 7 | 92 | | _ => StatusCodes.Status200OK |
| | 7 | 93 | | }; |
| | | 94 | | |
| | | 95 | | private static bool TryFindFailure(ResultExecutingContext context, out string message) |
| | | 96 | | { |
| | 7 | 97 | | if (context.Result is JsonResult jsonResult && TryReadFailure(jsonResult.Value, out message)) |
| | | 98 | | { |
| | 7 | 99 | | return true; |
| | | 100 | | } |
| | | 101 | | |
| | 0 | 102 | | if (context.Result is ObjectResult objectResult && TryReadFailure(objectResult.Value, out message)) |
| | | 103 | | { |
| | 0 | 104 | | return true; |
| | | 105 | | } |
| | | 106 | | |
| | 0 | 107 | | if (context.Controller is Controller controller) |
| | | 108 | | { |
| | 0 | 109 | | foreach (var key in new[] { "Error", "ErrorMessage", "ErrorSummary" }) |
| | | 110 | | { |
| | 0 | 111 | | if (controller.TempData.TryGetValue(key, out var value) |
| | 0 | 112 | | && value is not null |
| | 0 | 113 | | && !string.IsNullOrWhiteSpace(value.ToString())) |
| | | 114 | | { |
| | 0 | 115 | | message = value.ToString()!; |
| | 0 | 116 | | return true; |
| | | 117 | | } |
| | | 118 | | } |
| | | 119 | | } |
| | | 120 | | |
| | 0 | 121 | | message = string.Empty; |
| | 0 | 122 | | return false; |
| | | 123 | | } |
| | | 124 | | |
| | | 125 | | private static bool TryReadFailure(object? value, out string message) |
| | | 126 | | { |
| | 7 | 127 | | if (value is null) |
| | | 128 | | { |
| | 0 | 129 | | message = string.Empty; |
| | 0 | 130 | | return false; |
| | | 131 | | } |
| | | 132 | | |
| | 7 | 133 | | if (value is IDictionary dictionary) |
| | | 134 | | { |
| | 0 | 135 | | return TryReadDictionaryFailure(dictionary, out message); |
| | | 136 | | } |
| | | 137 | | |
| | 7 | 138 | | var type = value.GetType(); |
| | 7 | 139 | | var success = type.GetProperty("Success", BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase) |
| | 7 | 140 | | if (success?.PropertyType != typeof(bool) || success.GetValue(value) is not false) |
| | | 141 | | { |
| | 0 | 142 | | message = string.Empty; |
| | 0 | 143 | | return false; |
| | | 144 | | } |
| | | 145 | | |
| | 7 | 146 | | var baseMessage = ReadProperty(value, type, "Error") |
| | 7 | 147 | | ?? ReadProperty(value, type, "Message"); |
| | 7 | 148 | | var details = ReadProperty(value, type, "Errors") |
| | 7 | 149 | | ?? ReadProperty(value, type, "Reasons"); |
| | | 150 | | |
| | 7 | 151 | | message = (baseMessage, details) switch |
| | 7 | 152 | | { |
| | 2 | 153 | | ({ Length: > 0 } m, { Length: > 0 } d) when !m.Contains(d, StringComparison.OrdinalIgnoreCase) => $"{m}: {d} |
| | 1 | 154 | | ({ Length: > 0 } m, _) => m, |
| | 5 | 155 | | (_, { Length: > 0 } d) => d, |
| | 0 | 156 | | _ => "Операция вернула Success=false" |
| | 7 | 157 | | }; |
| | 7 | 158 | | return true; |
| | | 159 | | } |
| | | 160 | | |
| | | 161 | | private static bool TryReadDictionaryFailure(IDictionary dictionary, out string message) |
| | | 162 | | { |
| | 0 | 163 | | object? success = dictionary.Keys.Cast<object?>() |
| | 0 | 164 | | .FirstOrDefault(key => string.Equals(key?.ToString(), "success", StringComparison.OrdinalIgnoreCase)); |
| | 0 | 165 | | if (success is null || dictionary[success] is not false) |
| | | 166 | | { |
| | 0 | 167 | | message = string.Empty; |
| | 0 | 168 | | return false; |
| | | 169 | | } |
| | | 170 | | |
| | 0 | 171 | | string? baseMsg = ReadDictKey(dictionary, "error") ?? ReadDictKey(dictionary, "message"); |
| | 0 | 172 | | string? details = ReadDictKey(dictionary, "errors") ?? ReadDictKey(dictionary, "reasons"); |
| | | 173 | | |
| | 0 | 174 | | message = (baseMsg, details) switch |
| | 0 | 175 | | { |
| | 0 | 176 | | ({ Length: > 0 } m, { Length: > 0 } d) when !m.Contains(d, StringComparison.OrdinalIgnoreCase) => $"{m}: {d} |
| | 0 | 177 | | ({ Length: > 0 } m, _) => m, |
| | 0 | 178 | | (_, { Length: > 0 } d) => d, |
| | 0 | 179 | | _ => "Операция вернула success=false" |
| | 0 | 180 | | }; |
| | 0 | 181 | | return true; |
| | | 182 | | } |
| | | 183 | | |
| | | 184 | | private static string? ReadDictKey(IDictionary dict, string name) |
| | | 185 | | { |
| | 0 | 186 | | var key = dict.Keys.Cast<object?>() |
| | 0 | 187 | | .FirstOrDefault(k => string.Equals(k?.ToString(), name, StringComparison.OrdinalIgnoreCase)); |
| | 0 | 188 | | if (key is null || dict[key] is not { } val) |
| | 0 | 189 | | return null; |
| | | 190 | | |
| | 0 | 191 | | return val switch |
| | 0 | 192 | | { |
| | 0 | 193 | | string s => s, |
| | 0 | 194 | | IEnumerable items => string.Join("; ", items.Cast<object?>().Select(i => i?.ToString()) |
| | 0 | 195 | | .Where(i => !string.IsNullOrWhiteSpace(i))) is { Length: > 0 } joined ? joined : null, |
| | 0 | 196 | | var other => other.ToString() |
| | 0 | 197 | | }; |
| | | 198 | | } |
| | | 199 | | |
| | | 200 | | // Коллекции (Errors = List<string>) склеиваются: ToString() давал «System.Collections.Generic.List`1[...]». |
| | | 201 | | private static string? ReadProperty(object value, Type type, string name) => |
| | 23 | 202 | | type.GetProperty(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase) |
| | 23 | 203 | | ?.GetValue(value) switch |
| | 23 | 204 | | { |
| | 15 | 205 | | null => null, |
| | 2 | 206 | | string text => text, |
| | 18 | 207 | | IEnumerable items => string.Join("; ", items.Cast<object?>().Select(item => item?.ToString()) |
| | 18 | 208 | | .Where(item => !string.IsNullOrWhiteSpace(item))) is { Length: > 0 } joined ? joined : null, |
| | 0 | 209 | | var other => other.ToString() |
| | 23 | 210 | | }; |
| | | 211 | | } |