| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using Microsoft.AspNetCore.Http; |
| | | 3 | | |
| | | 4 | | namespace Services.ApiServices.InterpartsPriceApi; |
| | | 5 | | |
| | | 6 | | public sealed record InterpartsPriceDiagnosticsEntry( |
| | | 7 | | Guid Id, |
| | | 8 | | string? UserName, |
| | | 9 | | DateTimeOffset CreatedAt, |
| | | 10 | | string RequestUrl, |
| | | 11 | | int? StatusCode, |
| | | 12 | | string ErrorMessage, |
| | | 13 | | string ResponseBody); |
| | | 14 | | |
| | | 15 | | /// <summary>Короткоживущие безопасные детали ответов Interparts Price для открытия из UI.</summary> |
| | | 16 | | public sealed class InterpartsPriceDiagnosticsStore |
| | | 17 | | { |
| | 0 | 18 | | private static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(15); |
| | 5 | 19 | | private readonly ConcurrentDictionary<Guid, InterpartsPriceDiagnosticsEntry> _entries = new(); |
| | | 20 | | private readonly IHttpContextAccessor _httpContextAccessor; |
| | | 21 | | |
| | 10 | 22 | | public InterpartsPriceDiagnosticsStore(IHttpContextAccessor httpContextAccessor) => _httpContextAccessor = httpConte |
| | | 23 | | |
| | | 24 | | public Guid Add(string requestUrl, int? statusCode, string errorMessage, string? responseBody) |
| | | 25 | | { |
| | 0 | 26 | | RemoveExpired(); |
| | 0 | 27 | | var id = Guid.NewGuid(); |
| | 0 | 28 | | var userName = _httpContextAccessor.HttpContext?.User.Identity?.Name; |
| | 0 | 29 | | _entries[id] = new InterpartsPriceDiagnosticsEntry(id, userName, DateTimeOffset.Now, requestUrl, |
| | 0 | 30 | | statusCode, errorMessage, Trim(responseBody)); |
| | 0 | 31 | | return id; |
| | | 32 | | } |
| | | 33 | | |
| | | 34 | | public InterpartsPriceDiagnosticsEntry? Get(Guid id) |
| | | 35 | | { |
| | 0 | 36 | | RemoveExpired(); |
| | 0 | 37 | | if (!_entries.TryGetValue(id, out var entry)) return null; |
| | 0 | 38 | | var userName = _httpContextAccessor.HttpContext?.User.Identity?.Name; |
| | 0 | 39 | | return string.Equals(entry.UserName, userName, StringComparison.OrdinalIgnoreCase) ? entry : null; |
| | | 40 | | } |
| | | 41 | | |
| | | 42 | | private void RemoveExpired() |
| | | 43 | | { |
| | 0 | 44 | | var threshold = DateTimeOffset.Now - Lifetime; |
| | 0 | 45 | | foreach (var entry in _entries.Where(x => x.Value.CreatedAt < threshold)) |
| | 0 | 46 | | _entries.TryRemove(entry.Key, out _); |
| | 0 | 47 | | } |
| | | 48 | | |
| | | 49 | | private static string Trim(string? value) |
| | | 50 | | { |
| | 0 | 51 | | if (string.IsNullOrWhiteSpace(value)) return "—"; |
| | 0 | 52 | | return value.Length <= 12000 ? value : value[..12000] + "\n… ответ сокращён"; |
| | | 53 | | } |
| | | 54 | | } |