| | | 1 | | using System.Net; |
| | | 2 | | using System.Net.Http; |
| | | 3 | | using System.Text; |
| | | 4 | | using Microsoft.Extensions.Http; |
| | | 5 | | using Newtonsoft.Json; |
| | | 6 | | using Newtonsoft.Json.Linq; |
| | | 7 | | using Services.ApiServices; |
| | | 8 | | using SlqStudio.Application.Services.EmailService; |
| | | 9 | | |
| | | 10 | | namespace Services.ApiServices.OzonApi |
| | | 11 | | { |
| | | 12 | | public class OzonApiClient : BaseApiClient |
| | | 13 | | { |
| | | 14 | | private readonly string _clientId; |
| | | 15 | | private readonly string _apiKey; |
| | | 16 | | |
| | | 17 | | // Простая защита от слишком частых быстрых запросов: |
| | | 18 | | // задержка включается только если в окне времени уже было много запросов. |
| | 1 | 19 | | private static readonly object _fastLock = new object(); |
| | 1 | 20 | | private static readonly Queue<DateTime> _fastRequestTimes = new Queue<DateTime>(); |
| | 1 | 21 | | private static readonly TimeSpan _fastWindow = TimeSpan.FromSeconds(5); |
| | | 22 | | private const int _fastThreshold = 15; // максимум 15 быстрых запросов за 5 секунд |
| | | 23 | | |
| | | 24 | | // POST /v2/products/stocks: Ozon ограничивает до 80 запросов/минуту НА ОДИН аккаунт продавца |
| | | 25 | | // (Client-Id) — отдельно от общего _fastLock выше, который делит бюджет между всеми аккаунтами |
| | | 26 | | // и эндпоинтами и не гарантирует этот лимит для конкретного клиента. |
| | 1 | 27 | | private static readonly System.Collections.Concurrent.ConcurrentDictionary<string, object> _stocksLocks = new(); |
| | 1 | 28 | | private static readonly System.Collections.Concurrent.ConcurrentDictionary<string, Queue<DateTime>> _stocksReque |
| | 1 | 29 | | private static readonly TimeSpan _stocksWindow = TimeSpan.FromMinutes(1); |
| | | 30 | | private const int _stocksRateLimit = 80; |
| | 1 | 31 | | private static readonly TimeSpan BitrixPostTimeout = TimeSpan.FromSeconds(90); |
| | | 32 | | private const string BitrixHttpClientName = "OzonApiBitrix"; |
| | | 33 | | |
| | | 34 | | public OzonApiClient( |
| | | 35 | | IHttpClientFactory httpClientFactory, |
| | | 36 | | IEmailService? emailService, |
| | | 37 | | string clientId, |
| | | 38 | | string apiKey) |
| | 44 | 39 | | : base(httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory)), emailService, "OzonA |
| | | 40 | | { |
| | 44 | 41 | | _clientId = clientId; |
| | 44 | 42 | | _apiKey = apiKey; |
| | 44 | 43 | | } |
| | | 44 | | |
| | | 45 | | protected override void SetRequestHeaders(HttpWebRequest request) |
| | | 46 | | { |
| | 0 | 47 | | request.Headers.Add("Client-Id", _clientId); |
| | 0 | 48 | | request.Headers.Add("Api-Key", _apiKey); |
| | 0 | 49 | | } |
| | | 50 | | |
| | | 51 | | protected override void SetHttpClientHeaders(HttpClient client) |
| | | 52 | | { |
| | 0 | 53 | | client.DefaultRequestHeaders.Add("Client-Id", _clientId); |
| | 0 | 54 | | client.DefaultRequestHeaders.Add("Api-Key", _apiKey); |
| | 0 | 55 | | } |
| | | 56 | | |
| | | 57 | | /// <summary> |
| | | 58 | | /// Асинхронный POST с задержкой 2 сек (rate limit). Использует IHttpClientFactory. |
| | | 59 | | /// </summary> |
| | | 60 | | public new async Task<JObject> MakeRequestPostAsync<T>(T requestModel, string requestUri) where T : IRequestMode |
| | | 61 | | { |
| | 5 | 62 | | await Task.Delay(2000).ConfigureAwait(false); |
| | 5 | 63 | | var client = _httpClientFactory!.CreateClient(_clientName); |
| | 5 | 64 | | client.Timeout = _timeout; |
| | 5 | 65 | | var json = JsonConvert.SerializeObject(requestModel); |
| | 5 | 66 | | using var content = new StringContent(json, Encoding.UTF8, "application/json"); |
| | 5 | 67 | | var request = new HttpRequestMessage(HttpMethod.Post, requestUri) { Content = content }; |
| | 5 | 68 | | request.Headers.Add("Client-Id", _clientId); |
| | 5 | 69 | | request.Headers.Add("Api-Key", _apiKey); |
| | 5 | 70 | | using var response = await client.SendAsync(request).ConfigureAwait(false); |
| | 5 | 71 | | var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false); |
| | 5 | 72 | | if (!response.IsSuccessStatusCode) |
| | | 73 | | { |
| | 0 | 74 | | await HandleErrorAsync($"HTTP {response.StatusCode} при запросе к {_clientName}", |
| | 0 | 75 | | new HttpRequestException($"Status: {response.StatusCode}, Body: {responseBody}"), requestUri).Config |
| | 0 | 76 | | throw new HttpRequestException($"Ozon API вернул {(int)response.StatusCode} {response.StatusCode}. Ответ |
| | | 77 | | } |
| | 5 | 78 | | return string.IsNullOrWhiteSpace(responseBody) ? new JObject() : JObject.Parse(responseBody); |
| | 5 | 79 | | } |
| | | 80 | | |
| | | 81 | | /// <summary> |
| | | 82 | | /// Асинхронный POST для Bitrix-сценариев с повтором при 429. Использует IHttpClientFactory. |
| | | 83 | | /// </summary> |
| | | 84 | | public async Task<JObject> MakeRequestPostForBitrixAsync<T>(T requestModel, string requestUri) where T : IReques |
| | | 85 | | { |
| | | 86 | | const int maxRetries = 3; |
| | 27 | 87 | | int delayMs = 500; |
| | 54 | 88 | | for (int attempt = 1; attempt <= maxRetries; attempt++) |
| | | 89 | | { |
| | 27 | 90 | | await Task.Delay(attempt == 1 ? 100 : 0).ConfigureAwait(false); |
| | 27 | 91 | | var client = _httpClientFactory!.CreateClient(BitrixHttpClientName); |
| | 27 | 92 | | client.Timeout = BitrixPostTimeout; |
| | 27 | 93 | | var json = JsonConvert.SerializeObject(requestModel); |
| | 27 | 94 | | using var content = new StringContent(json, Encoding.UTF8, "application/json"); |
| | 27 | 95 | | var request = new HttpRequestMessage(HttpMethod.Post, requestUri) { Content = content }; |
| | 27 | 96 | | request.Headers.Add("Client-Id", _clientId); |
| | 27 | 97 | | request.Headers.Add("Api-Key", _apiKey); |
| | | 98 | | try |
| | | 99 | | { |
| | 27 | 100 | | using var response = await client.SendAsync(request).ConfigureAwait(false); |
| | 27 | 101 | | var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false); |
| | | 102 | | |
| | 27 | 103 | | if (response.StatusCode == (HttpStatusCode)429) |
| | | 104 | | { |
| | 0 | 105 | | if (attempt == maxRetries) |
| | | 106 | | { |
| | 0 | 107 | | throw new Exception($"Request failed after retries. Status: 429, Body: {responseBody}"); |
| | | 108 | | } |
| | | 109 | | |
| | 0 | 110 | | await Task.Delay(delayMs).ConfigureAwait(false); |
| | 0 | 111 | | delayMs *= 2; |
| | 0 | 112 | | continue; |
| | | 113 | | } |
| | | 114 | | |
| | 27 | 115 | | if (!response.IsSuccessStatusCode) |
| | | 116 | | { |
| | 4 | 117 | | throw new Exception($"Request failed. Status: {response.StatusCode}, Body: {responseBody}"); |
| | | 118 | | } |
| | | 119 | | |
| | 23 | 120 | | return string.IsNullOrWhiteSpace(responseBody) ? new JObject() : JObject.Parse(responseBody); |
| | | 121 | | } |
| | 4 | 122 | | catch (Exception ex) when (IsBitrixOzonTransientFailure(ex)) |
| | | 123 | | { |
| | 0 | 124 | | if (attempt == maxRetries) |
| | | 125 | | { |
| | 0 | 126 | | throw; |
| | | 127 | | } |
| | | 128 | | |
| | 0 | 129 | | await Task.Delay(delayMs).ConfigureAwait(false); |
| | 0 | 130 | | delayMs *= 2; |
| | | 131 | | } |
| | 0 | 132 | | } |
| | | 133 | | |
| | 0 | 134 | | throw new Exception("Unknown error in retry loop."); |
| | 23 | 135 | | } |
| | | 136 | | |
| | | 137 | | private static bool IsBitrixOzonTransientFailure(Exception ex) |
| | | 138 | | { |
| | 16 | 139 | | for (var current = ex; current != null; current = current.InnerException) |
| | | 140 | | { |
| | 4 | 141 | | if (current is TaskCanceledException or TimeoutException or HttpRequestException) |
| | | 142 | | { |
| | 0 | 143 | | return true; |
| | | 144 | | } |
| | | 145 | | |
| | 4 | 146 | | if (current.GetType().FullName == "Polly.CircuitBreaker.BrokenCircuitException") |
| | | 147 | | { |
| | 0 | 148 | | return true; |
| | | 149 | | } |
| | | 150 | | } |
| | | 151 | | |
| | 4 | 152 | | return false; |
| | | 153 | | } |
| | | 154 | | |
| | | 155 | | /// <summary> |
| | | 156 | | /// Троттлинг specifically для POST /v2/products/stocks: не более 80 запросов/минуту |
| | | 157 | | /// на один Client-Id (скользящее окно), как того требует документация Ozon. |
| | | 158 | | /// </summary> |
| | | 159 | | private async Task ThrottleStocksUpdateAsync() |
| | | 160 | | { |
| | | 161 | | TimeSpan delay; |
| | 0 | 162 | | var lockObj = _stocksLocks.GetOrAdd(_clientId, _ => new object()); |
| | 0 | 163 | | lock (lockObj) |
| | | 164 | | { |
| | 0 | 165 | | var queue = _stocksRequestTimes.GetOrAdd(_clientId, _ => new Queue<DateTime>()); |
| | 0 | 166 | | var now = DateTime.UtcNow; |
| | 0 | 167 | | while (queue.Count > 0 && now - queue.Peek() > _stocksWindow) |
| | 0 | 168 | | queue.Dequeue(); |
| | | 169 | | |
| | 0 | 170 | | delay = queue.Count >= _stocksRateLimit |
| | 0 | 171 | | ? queue.Peek() + _stocksWindow - now |
| | 0 | 172 | | : TimeSpan.Zero; |
| | 0 | 173 | | if (delay < TimeSpan.Zero) |
| | 0 | 174 | | delay = TimeSpan.Zero; |
| | | 175 | | |
| | 0 | 176 | | queue.Enqueue(now + delay); |
| | 0 | 177 | | } |
| | | 178 | | |
| | 0 | 179 | | if (delay > TimeSpan.Zero) |
| | 0 | 180 | | await Task.Delay(delay).ConfigureAwait(false); |
| | 0 | 181 | | } |
| | | 182 | | |
| | | 183 | | /// <summary> |
| | | 184 | | /// POST /v2/products/stocks с троттлингом до 80 запросов/минуту на аккаунт. |
| | | 185 | | /// </summary> |
| | | 186 | | public async Task<JObject> MakeStocksUpdateRequestAsync<T>(T requestModel, string requestUri) where T : IRequest |
| | | 187 | | { |
| | 0 | 188 | | await ThrottleStocksUpdateAsync().ConfigureAwait(false); |
| | 0 | 189 | | return await MakeFastRequestAsync(requestModel, requestUri).ConfigureAwait(false); |
| | 0 | 190 | | } |
| | | 191 | | |
| | | 192 | | /// <summary> |
| | | 193 | | /// Быстрый асинхронный POST (задержка 500 мс). Использует IHttpClientFactory. |
| | | 194 | | /// </summary> |
| | | 195 | | /// <param name="clientNameOverride">Опционально: имя HttpClient (например "OzonApiReturns" без Circuit Breaker) |
| | | 196 | | public async Task<JObject> MakeFastRequestAsync<T>(T requestModel, string requestUri, string? clientNameOverride |
| | | 197 | | { |
| | | 198 | | // Задержка только если в последние _fastWindow было уже много быстрых запросов |
| | 9 | 199 | | bool needDelay = false; |
| | 9 | 200 | | lock (_fastLock) |
| | | 201 | | { |
| | 9 | 202 | | var now = DateTime.UtcNow; |
| | | 203 | | |
| | 16 | 204 | | while (_fastRequestTimes.Count > 0 && |
| | 16 | 205 | | now - _fastRequestTimes.Peek() > _fastWindow) |
| | | 206 | | { |
| | 7 | 207 | | _fastRequestTimes.Dequeue(); |
| | | 208 | | } |
| | | 209 | | |
| | 9 | 210 | | if (_fastRequestTimes.Count >= _fastThreshold) |
| | | 211 | | { |
| | 0 | 212 | | needDelay = true; |
| | | 213 | | } |
| | | 214 | | |
| | 9 | 215 | | _fastRequestTimes.Enqueue(now); |
| | 9 | 216 | | } |
| | | 217 | | |
| | 9 | 218 | | if (needDelay) |
| | | 219 | | { |
| | 0 | 220 | | await Task.Delay(500).ConfigureAwait(false); |
| | | 221 | | } |
| | | 222 | | |
| | 9 | 223 | | var clientName = clientNameOverride ?? _clientName; |
| | 9 | 224 | | var client = _httpClientFactory!.CreateClient(clientName); |
| | 9 | 225 | | client.Timeout = _timeout; |
| | 9 | 226 | | var json = JsonConvert.SerializeObject(requestModel); |
| | 9 | 227 | | using var content = new StringContent(json, Encoding.UTF8, "application/json"); |
| | 9 | 228 | | var request = new HttpRequestMessage(HttpMethod.Post, requestUri) { Content = content }; |
| | 9 | 229 | | request.Headers.Add("Client-Id", _clientId); |
| | 9 | 230 | | request.Headers.Add("Api-Key", _apiKey); |
| | 9 | 231 | | using var response = await client.SendAsync(request).ConfigureAwait(false); |
| | 9 | 232 | | var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false); |
| | | 233 | | |
| | 9 | 234 | | if (!response.IsSuccessStatusCode) |
| | | 235 | | { |
| | | 236 | | try |
| | | 237 | | { |
| | 1 | 238 | | var doc = System.Text.Json.JsonDocument.Parse(responseBody); |
| | 0 | 239 | | if (doc.RootElement.TryGetProperty("message", out var message)) |
| | 0 | 240 | | throw new Exception(message.GetString() ?? responseBody); |
| | 0 | 241 | | } |
| | 2 | 242 | | catch (System.Text.Json.JsonException) { } |
| | 1 | 243 | | throw new Exception($"Request failed ({(int)response.StatusCode} {response.ReasonPhrase})\n{responseBody |
| | | 244 | | } |
| | | 245 | | |
| | 8 | 246 | | return string.IsNullOrWhiteSpace(responseBody) ? new JObject() : JObject.Parse(responseBody); |
| | 8 | 247 | | } |
| | | 248 | | |
| | | 249 | | /// <summary> |
| | | 250 | | /// Асинхронный POST с возвратом файла (stream). Использует IHttpClientFactory. |
| | | 251 | | /// </summary> |
| | | 252 | | public async Task<MemoryStream> MakeFileRequestAsync<T>(T requestModel, string requestUri) |
| | | 253 | | where T : IRequestModel |
| | | 254 | | { |
| | 0 | 255 | | var client = _httpClientFactory!.CreateClient(_clientName); |
| | 0 | 256 | | client.Timeout = _timeout; |
| | 0 | 257 | | var json = JsonConvert.SerializeObject(requestModel); |
| | 0 | 258 | | using var content = new StringContent(json, Encoding.UTF8, "application/json"); |
| | 0 | 259 | | var request = new HttpRequestMessage(HttpMethod.Post, requestUri) { Content = content }; |
| | 0 | 260 | | request.Headers.Add("Client-Id", _clientId); |
| | 0 | 261 | | request.Headers.Add("Api-Key", _apiKey); |
| | 0 | 262 | | using var response = await client.SendAsync(request).ConfigureAwait(false); |
| | | 263 | | |
| | 0 | 264 | | if (!response.IsSuccessStatusCode) |
| | | 265 | | { |
| | 0 | 266 | | var errorBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false); |
| | 0 | 267 | | throw new Exception($"Request failed. Status: {response.StatusCode}, Body: {errorBody}"); |
| | | 268 | | } |
| | | 269 | | |
| | 0 | 270 | | var memoryStream = new MemoryStream(); |
| | 0 | 271 | | await response.Content.CopyToAsync(memoryStream).ConfigureAwait(false); |
| | 0 | 272 | | memoryStream.Seek(0, SeekOrigin.Begin); |
| | 0 | 273 | | return memoryStream; |
| | 0 | 274 | | } |
| | | 275 | | |
| | | 276 | | public override async Task<bool> GetTestRequest(string clientId, string apiKey) |
| | | 277 | | { |
| | 0 | 278 | | var requestUri = "https://api-seller.ozon.ru/v1/warehouse/list"; |
| | 0 | 279 | | var client = _httpClientFactory!.CreateClient(_clientName); |
| | 0 | 280 | | client.Timeout = _timeout; |
| | 0 | 281 | | var request = new HttpRequestMessage(HttpMethod.Post, requestUri); |
| | 0 | 282 | | request.Headers.Add("Client-Id", clientId); |
| | 0 | 283 | | request.Headers.Add("Api-Key", apiKey); |
| | 0 | 284 | | request.Content = new StringContent("{}", Encoding.UTF8, "application/json"); |
| | | 285 | | try |
| | | 286 | | { |
| | 0 | 287 | | var response = await client.SendAsync(request).ConfigureAwait(false); |
| | 0 | 288 | | return response.IsSuccessStatusCode; |
| | | 289 | | } |
| | 0 | 290 | | catch |
| | | 291 | | { |
| | 0 | 292 | | return false; |
| | | 293 | | } |
| | 0 | 294 | | } |
| | | 295 | | } |
| | | 296 | | } |