| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using Microsoft.Extensions.Caching.Memory; |
| | | 3 | | |
| | | 4 | | namespace Services.BitrixStockServices; |
| | | 5 | | |
| | | 6 | | /// <summary>Кэш отчётов синхронизации (singleton — доступен и HTTP, и Hangfire в том же процессе).</summary> |
| | | 7 | | public sealed class BitrixStockSyncReportStore |
| | | 8 | | { |
| | 0 | 9 | | private readonly ConcurrentDictionary<string, (BitrixStockSyncReportDto Report, DateTime ExpiresUtc)> _reports = new |
| | | 10 | | private readonly IMemoryCache _memoryCache; |
| | | 11 | | |
| | 0 | 12 | | public BitrixStockSyncReportStore(IMemoryCache memoryCache) |
| | | 13 | | { |
| | 0 | 14 | | _memoryCache = memoryCache; |
| | 0 | 15 | | } |
| | | 16 | | |
| | | 17 | | public void Set(string reportId, BitrixStockSyncReportDto report, TimeSpan ttl) |
| | | 18 | | { |
| | 0 | 19 | | if (string.IsNullOrWhiteSpace(reportId) || report == null) |
| | | 20 | | { |
| | 0 | 21 | | return; |
| | | 22 | | } |
| | | 23 | | |
| | 0 | 24 | | var id = reportId.Trim(); |
| | 0 | 25 | | var expires = DateTime.UtcNow.Add(ttl); |
| | 0 | 26 | | _reports[id] = (report, expires); |
| | 0 | 27 | | _memoryCache.Set(CacheKey(id), report, ttl); |
| | 0 | 28 | | } |
| | | 29 | | |
| | | 30 | | public BitrixStockSyncReportDto? Get(string reportId) |
| | | 31 | | { |
| | 0 | 32 | | if (string.IsNullOrWhiteSpace(reportId)) |
| | | 33 | | { |
| | 0 | 34 | | return null; |
| | | 35 | | } |
| | | 36 | | |
| | 0 | 37 | | var id = reportId.Trim(); |
| | 0 | 38 | | if (_memoryCache.TryGetValue(CacheKey(id), out BitrixStockSyncReportDto? cached)) |
| | | 39 | | { |
| | 0 | 40 | | return cached; |
| | | 41 | | } |
| | | 42 | | |
| | 0 | 43 | | if (_reports.TryGetValue(id, out var entry)) |
| | | 44 | | { |
| | 0 | 45 | | if (entry.ExpiresUtc > DateTime.UtcNow) |
| | | 46 | | { |
| | 0 | 47 | | return entry.Report; |
| | | 48 | | } |
| | | 49 | | |
| | 0 | 50 | | _reports.TryRemove(id, out _); |
| | | 51 | | } |
| | | 52 | | |
| | 0 | 53 | | return null; |
| | | 54 | | } |
| | | 55 | | |
| | 0 | 56 | | private static string CacheKey(string reportId) => $"bitrix-sync-report:{reportId}"; |
| | | 57 | | } |