| | | 1 | | using Microsoft.Extensions.Caching.Memory; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using Services.SystemMonitoringServices; |
| | | 4 | | |
| | | 5 | | namespace Services.FeedPriceServices; |
| | | 6 | | |
| | | 7 | | public interface IFeedPriceService |
| | | 8 | | { |
| | | 9 | | Task<FeedPriceResult> GetAsync(IReadOnlyCollection<string> articleKeys, CancellationToken ct = default); |
| | | 10 | | |
| | | 11 | | /// <summary>Только текущие данные, без истории: облегчённый ответ для колонок грида.</summary> |
| | | 12 | | Task<FeedPriceResult> GetCurrentAsync(IReadOnlyCollection<string> articleKeys, CancellationToken ct = default); |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Текущие строки фида по любому числу ключей: недостающие в кеше запрашиваются пачками до |
| | | 16 | | /// <see cref="FeedPriceService.MaxKeysPerRequest"/> ключей, кеш ведётся по каждому ключу отдельно. |
| | | 17 | | /// </summary> |
| | | 18 | | Task<FeedRowsResult> GetCurrentRowsAsync(IReadOnlyCollection<string> articleKeys, CancellationToken ct = default); |
| | | 19 | | } |
| | | 20 | | |
| | | 21 | | /// <summary> |
| | | 22 | | /// Цена и остатки артикула в фиде для модалки заказа. Недоступность фид-сервиса не должна ронять страницу, |
| | | 23 | | /// поэтому ошибка возвращается в модели; ответ с ошибкой не кешируется. |
| | | 24 | | /// </summary> |
| | | 25 | | public sealed class FeedPriceService : IFeedPriceService |
| | | 26 | | { |
| | | 27 | | private const string CacheKeyPrefix = "feed_price_v1_"; |
| | | 28 | | private const string CurrentCacheKeyPrefix = "feed_price_current_v1_"; |
| | | 29 | | private const string RowsCacheKeyPrefix = "feed_price_rows_v1_"; |
| | | 30 | | |
| | | 31 | | /// <summary>Сколько ключей feed API принимает в одном запросе price-stock.</summary> |
| | | 32 | | public const int MaxKeysPerRequest = 100; |
| | 1 | 33 | | private static readonly TimeSpan CacheTtl = TimeSpan.FromSeconds(90); |
| | | 34 | | |
| | | 35 | | private readonly IFeedPriceReader _reader; |
| | | 36 | | private readonly FeedPriceOptions _options; |
| | | 37 | | private readonly IMemoryCache _cache; |
| | | 38 | | private readonly ILogger<FeedPriceService> _logger; |
| | | 39 | | private readonly ISystemMonitoringSignalWriter? _signals; |
| | | 40 | | |
| | 10 | 41 | | public FeedPriceService(IFeedPriceReader reader, FeedPriceOptions options, IMemoryCache cache, ILogger<FeedPriceServ |
| | 10 | 42 | | ISystemMonitoringSignalWriter? signals = null) |
| | | 43 | | { |
| | 10 | 44 | | _reader = reader; |
| | 10 | 45 | | _options = options; |
| | 10 | 46 | | _cache = cache; |
| | 10 | 47 | | _logger = logger; |
| | 10 | 48 | | _signals = signals; |
| | 10 | 49 | | } |
| | | 50 | | |
| | | 51 | | public Task<FeedPriceResult> GetAsync(IReadOnlyCollection<string> articleKeys, CancellationToken ct = default) => |
| | 6 | 52 | | LoadAsync(articleKeys, _options.HistoryRuns, includeHistory: true, CacheKeyPrefix, ct); |
| | | 53 | | |
| | | 54 | | public Task<FeedPriceResult> GetCurrentAsync(IReadOnlyCollection<string> articleKeys, CancellationToken ct = default |
| | 2 | 55 | | LoadAsync(articleKeys, historyRuns: 1, includeHistory: false, CurrentCacheKeyPrefix, ct); |
| | | 56 | | |
| | | 57 | | public async Task<FeedRowsResult> GetCurrentRowsAsync(IReadOnlyCollection<string> articleKeys, CancellationToken ct |
| | | 58 | | { |
| | 8 | 59 | | var keys = articleKeys |
| | 563 | 60 | | .Where(x => !string.IsNullOrWhiteSpace(x)) |
| | 561 | 61 | | .Select(x => x.Trim()) |
| | 8 | 62 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 8 | 63 | | .ToArray(); |
| | 8 | 64 | | var rows = new Dictionary<string, IReadOnlyList<FeedCurrentRow>>(StringComparer.OrdinalIgnoreCase); |
| | 8 | 65 | | var failed = new HashSet<string>(StringComparer.OrdinalIgnoreCase); |
| | 8 | 66 | | var missing = new List<string>(); |
| | 1138 | 67 | | foreach (var key in keys) |
| | | 68 | | { |
| | 561 | 69 | | if (_cache.TryGetValue<IReadOnlyList<FeedCurrentRow>>(RowsCacheKeyPrefix + key.ToUpperInvariant(), out var c |
| | 105 | 70 | | rows[key] = cached; |
| | | 71 | | else |
| | 456 | 72 | | missing.Add(key); |
| | | 73 | | } |
| | | 74 | | |
| | 34 | 75 | | foreach (var chunk in missing.Chunk(MaxKeysPerRequest)) |
| | | 76 | | { |
| | | 77 | | try |
| | | 78 | | { |
| | 9 | 79 | | var snapshot = await _reader.GetAsync(chunk, 1, ct); |
| | 13 | 80 | | var byArticle = snapshot.Current.ToLookup(row => row.Article, StringComparer.OrdinalIgnoreCase); |
| | 828 | 81 | | foreach (var key in chunk) |
| | | 82 | | { |
| | | 83 | | // Ключа нет в фиде: пустой список тоже кешируется, иначе каждая ячейка гнала бы запрос заново. |
| | 406 | 84 | | IReadOnlyList<FeedCurrentRow> found = byArticle[key].ToArray(); |
| | 406 | 85 | | rows[key] = found; |
| | 406 | 86 | | _cache.Set(RowsCacheKeyPrefix + key.ToUpperInvariant(), found, CacheTtl); |
| | | 87 | | } |
| | | 88 | | |
| | 8 | 89 | | await (_signals?.RecordAsync("feed-price-stock", "success", cancellationToken: ct) ?? Task.CompletedTask |
| | 8 | 90 | | } |
| | 0 | 91 | | catch (OperationCanceledException) when (ct.IsCancellationRequested) |
| | | 92 | | { |
| | 0 | 93 | | throw; |
| | | 94 | | } |
| | 1 | 95 | | catch (Exception ex) |
| | | 96 | | { |
| | 1 | 97 | | _logger.LogWarning(ex, "Фид: не удалось прочитать цену пачки из {Count} артикулов", chunk.Length); |
| | 1 | 98 | | await (_signals?.RecordAsync("feed-price-stock", "failure", message: "Не удалось получить цены и остатки |
| | 152 | 99 | | foreach (var key in chunk) failed.Add(key); |
| | | 100 | | } |
| | 9 | 101 | | } |
| | | 102 | | |
| | 8 | 103 | | return new FeedRowsResult(rows, failed); |
| | 8 | 104 | | } |
| | | 105 | | |
| | | 106 | | private async Task<FeedPriceResult> LoadAsync(IReadOnlyCollection<string> articleKeys, int historyRuns, bool include |
| | | 107 | | string cachePrefix, CancellationToken ct) |
| | | 108 | | { |
| | 8 | 109 | | var keys = articleKeys |
| | 9 | 110 | | .Where(x => !string.IsNullOrWhiteSpace(x)) |
| | 7 | 111 | | .Select(x => x.Trim()) |
| | 8 | 112 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 8 | 113 | | .ToArray(); |
| | 8 | 114 | | if (keys.Length == 0) |
| | 1 | 115 | | return new FeedPriceResult { Error = "Не удалось собрать ключ артикула: у заказа нет артикула или префикса п |
| | | 116 | | |
| | 21 | 117 | | var cacheKey = cachePrefix + string.Join('|', keys.Select(x => x.ToUpperInvariant()).OrderBy(x => x, StringCompa |
| | 7 | 118 | | if (_cache.TryGetValue<FeedPriceResult>(cacheKey, out var cached) && cached is not null) |
| | 1 | 119 | | return cached; |
| | | 120 | | |
| | | 121 | | try |
| | | 122 | | { |
| | 6 | 123 | | var snapshot = await _reader.GetAsync(keys, historyRuns, ct); |
| | | 124 | | |
| | 5 | 125 | | var result = new FeedPriceResult |
| | 5 | 126 | | { |
| | 5 | 127 | | ArticleKeys = keys, |
| | 5 | 128 | | Current = snapshot.Current, |
| | 5 | 129 | | History = includeHistory ? WithDeltas(snapshot.History) : Array.Empty<FeedHistoryRow>() |
| | 5 | 130 | | }; |
| | 5 | 131 | | _cache.Set(cacheKey, result, CacheTtl); |
| | 5 | 132 | | await (_signals?.RecordAsync("feed-price-stock", "success", cancellationToken: ct) ?? Task.CompletedTask); |
| | 5 | 133 | | return result; |
| | | 134 | | } |
| | 0 | 135 | | catch (OperationCanceledException) when (ct.IsCancellationRequested) |
| | | 136 | | { |
| | 0 | 137 | | throw; |
| | | 138 | | } |
| | | 139 | | catch (Exception ex) |
| | | 140 | | { |
| | 1 | 141 | | _logger.LogWarning(ex, "Фид: не удалось прочитать цену и остатки артикула {Articles}", string.Join(", ", key |
| | 1 | 142 | | await (_signals?.RecordAsync("feed-price-stock", "failure", message: "Не удалось получить цены и остатки из |
| | 1 | 143 | | return new FeedPriceResult { ArticleKeys = keys, Error = "Фид-сервис недоступен. Повторите позже." }; |
| | | 144 | | } |
| | 8 | 145 | | } |
| | | 146 | | |
| | | 147 | | /// <summary>Разница цены к предыдущему по времени прогону того же кабинета и артикула; строки — свежие сверху.</sum |
| | | 148 | | internal static IReadOnlyList<FeedHistoryRow> WithDeltas(IEnumerable<FeedHistoryRow> rows) |
| | | 149 | | { |
| | 19 | 150 | | var ordered = rows.OrderByDescending(x => x.AssembledAt).ThenByDescending(x => x.RunId).ToList(); |
| | 25 | 151 | | foreach (var group in ordered.GroupBy(x => (x.Cabinet, x.Article))) |
| | | 152 | | { |
| | 4 | 153 | | var chain = group.ToList(); |
| | 14 | 154 | | for (var i = 0; i < chain.Count - 1; i++) |
| | | 155 | | { |
| | 3 | 156 | | if (chain[i].Price is { } now && chain[i + 1].Price is { } before) |
| | 2 | 157 | | chain[i].PriceDelta = now - before; |
| | | 158 | | } |
| | | 159 | | } |
| | | 160 | | |
| | 5 | 161 | | return ordered; |
| | | 162 | | } |
| | | 163 | | } |