| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using Microsoft.Extensions.Caching.Memory; |
| | | 3 | | |
| | | 4 | | namespace Services.ApiServices.PartsnavigatorApi; |
| | | 5 | | |
| | | 6 | | public interface IPartsnavigatorService |
| | | 7 | | { |
| | | 8 | | /// <summary> |
| | | 9 | | /// Карточка запчасти: пробует бренды-кандидаты по порядку и возвращает первую найденную. Если не найдена нигде, |
| | | 10 | | /// но был сбой сервиса — возвращает сбой (чтобы пользователь мог повторить), иначе «не найдено». |
| | | 11 | | /// </summary> |
| | | 12 | | /// <param name="withAnalogs">false — быстрая карточка, true — со страницей аналогов (у сайта она медленная, поэтому |
| | | 13 | | Task<PartsnavigatorResult> GetAsync(IEnumerable<string?> brandCandidates, string number, bool withAnalogs, Cancellat |
| | | 14 | | } |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Кеш и защита парсера: бэкенд обрабатывает не более 5 запросов одновременно, поэтому одинаковые запросы |
| | | 18 | | /// схлопываются в один (single-flight), общий параллелизм ограничен, а результат кешируется на разные сроки |
| | | 19 | | /// (успех — часы, «не найдено» — минуты, сбой — секунды, чтобы не долбить упавший сервис). |
| | | 20 | | /// </summary> |
| | | 21 | | public sealed class PartsnavigatorService : IPartsnavigatorService |
| | | 22 | | { |
| | | 23 | | private const string CacheKeyPrefix = "partsnavigator:v2:"; |
| | | 24 | | |
| | | 25 | | private readonly IPartsnavigatorApiClient _client; |
| | | 26 | | private readonly IMemoryCache _cache; |
| | | 27 | | private readonly PartsnavigatorConfig _config; |
| | | 28 | | private readonly SemaphoreSlim _gate; |
| | 9 | 29 | | private readonly ConcurrentDictionary<string, Lazy<Task<PartsnavigatorResult>>> _inflight = new(); |
| | | 30 | | |
| | 9 | 31 | | public PartsnavigatorService(IPartsnavigatorApiClient client, IMemoryCache cache, PartsnavigatorConfig config) |
| | | 32 | | { |
| | 9 | 33 | | _client = client; |
| | 9 | 34 | | _cache = cache; |
| | 9 | 35 | | _config = config; |
| | 9 | 36 | | _gate = new SemaphoreSlim(Math.Max(1, config.MaxConcurrency)); |
| | 9 | 37 | | } |
| | | 38 | | |
| | | 39 | | public async Task<PartsnavigatorResult> GetAsync(IEnumerable<string?> brandCandidates, string number, bool withAnalo |
| | | 40 | | { |
| | 32 | 41 | | number = number?.Trim() ?? string.Empty; |
| | 32 | 42 | | var brands = brandCandidates |
| | 38 | 43 | | .Where(b => !string.IsNullOrWhiteSpace(b)) |
| | 34 | 44 | | .Select(b => b!.Trim()) |
| | 32 | 45 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 32 | 46 | | .ToList(); |
| | 32 | 47 | | if (brands.Count == 0 || number.Length == 0) |
| | 2 | 48 | | return PartsnavigatorResult.NotFound("Не указан бренд или артикул."); |
| | | 49 | | |
| | 30 | 50 | | PartsnavigatorResult? firstFailure = null; |
| | 30 | 51 | | PartsnavigatorResult? notFound = null; |
| | 101 | 52 | | foreach (var brand in brands) |
| | | 53 | | { |
| | 33 | 54 | | var result = await LookupCachedAsync(brand, number, withAnalogs, ct); |
| | 58 | 55 | | if (result.Status == PartsnavigatorStatus.Found) return result with { MatchedBrand = brand }; |
| | 11 | 56 | | if (result.Status == PartsnavigatorStatus.Error) firstFailure ??= result; |
| | 5 | 57 | | else notFound ??= result; |
| | 8 | 58 | | } |
| | | 59 | | |
| | 5 | 60 | | return firstFailure ?? notFound!; |
| | 32 | 61 | | } |
| | | 62 | | |
| | | 63 | | private async Task<PartsnavigatorResult> LookupCachedAsync(string brand, string number, bool withAnalogs, Cancellati |
| | | 64 | | { |
| | 33 | 65 | | var key = CacheKeyPrefix + (withAnalogs ? "analogs:" : "card:") + brand.ToUpperInvariant() + "|" + number.ToUppe |
| | 33 | 66 | | if (_cache.TryGetValue<PartsnavigatorResult>(key, out var cached) && cached is not null) |
| | 5 | 67 | | return cached; |
| | | 68 | | |
| | 66 | 69 | | var lazy = _inflight.GetOrAdd(key, _ => new Lazy<Task<PartsnavigatorResult>>(() => FetchAsync(key, brand, number |
| | | 70 | | // Запрос живёт независимо от отмены первого вызывающего: результат нужен и остальным ожидающим. |
| | 28 | 71 | | return await lazy.Value.WaitAsync(ct); |
| | 33 | 72 | | } |
| | | 73 | | |
| | | 74 | | private async Task<PartsnavigatorResult> FetchAsync(string key, string brand, string number, bool withAnalogs) |
| | | 75 | | { |
| | | 76 | | try |
| | | 77 | | { |
| | 19 | 78 | | await _gate.WaitAsync(); |
| | | 79 | | try |
| | | 80 | | { |
| | 19 | 81 | | var result = await _client.LookupAsync(brand, number, withAnalogs); |
| | 19 | 82 | | _cache.Set(key, result, ResolveTtl(result)); |
| | 19 | 83 | | return result; |
| | | 84 | | } |
| | | 85 | | finally |
| | | 86 | | { |
| | 19 | 87 | | _gate.Release(); |
| | | 88 | | } |
| | | 89 | | } |
| | | 90 | | finally |
| | | 91 | | { |
| | 19 | 92 | | _inflight.TryRemove(key, out _); |
| | | 93 | | } |
| | 19 | 94 | | } |
| | | 95 | | |
| | 19 | 96 | | private TimeSpan ResolveTtl(PartsnavigatorResult result) => result.Status switch |
| | 19 | 97 | | { |
| | 13 | 98 | | PartsnavigatorStatus.Found => TimeSpan.FromHours(Math.Max(1, _config.FoundCacheHours)), |
| | 4 | 99 | | PartsnavigatorStatus.NotFound => TimeSpan.FromMinutes(Math.Max(1, _config.NotFoundCacheMinutes)), |
| | 2 | 100 | | _ => TimeSpan.FromSeconds(Math.Max(5, _config.ErrorCacheSeconds)) |
| | 19 | 101 | | }; |
| | | 102 | | } |