| | | 1 | | using System.Diagnostics; |
| | | 2 | | using Newtonsoft.Json.Linq; |
| | | 3 | | using Services.ApiServices.ApiSupplierRequestLog; |
| | | 4 | | |
| | | 5 | | namespace Services.ApiServices.MlAutoApi; |
| | | 6 | | |
| | | 7 | | public sealed record MlAutoApiResponse(Newtonsoft.Json.Linq.JToken Response, string? Message); |
| | | 8 | | |
| | | 9 | | /// <summary>Read-only клиент ML-Auto: API принимает только form-urlencoded POST.</summary> |
| | | 10 | | public class MlAutoHttpClient |
| | | 11 | | { |
| | | 12 | | private readonly IHttpClientFactory _factory; |
| | | 13 | | private readonly MlAutoConfig _config; |
| | | 14 | | private readonly ApiSupplierRequestLogStore? _logs; |
| | | 15 | | private readonly string _httpClientName; |
| | | 16 | | private readonly string _providerKey; |
| | | 17 | | private readonly MlAutoRateLimiter _limiter; |
| | | 18 | | |
| | 112 | 19 | | public MlAutoHttpClient(IHttpClientFactory factory, MlAutoConfig config, ApiSupplierRequestLogStore? logs = null, |
| | 112 | 20 | | string httpClientName = "MlAutoApi", string providerKey = "MlAuto") |
| | | 21 | | { |
| | 112 | 22 | | _factory = factory; |
| | 112 | 23 | | _config = config; |
| | 112 | 24 | | _logs = logs; |
| | 112 | 25 | | _httpClientName = httpClientName; |
| | 112 | 26 | | _providerKey = providerKey; |
| | 112 | 27 | | _limiter = new MlAutoRateLimiter(config.RequestsPerMinute); |
| | 112 | 28 | | } |
| | | 29 | | |
| | | 30 | | public async Task<JToken> PingAsync(CancellationToken cancellationToken = default) => |
| | 0 | 31 | | (await PostDetailedAsync("/Ping/", null, false, cancellationToken)).Response; |
| | | 32 | | |
| | | 33 | | public async Task<JToken> PostAsync(string path, IReadOnlyDictionary<string, string?>? parameters, CancellationToken |
| | 91 | 34 | | (await PostDetailedAsync(path, parameters, true, cancellationToken)).Response; |
| | | 35 | | |
| | | 36 | | public Task<MlAutoApiResponse> PostDetailedAsync(string path, IReadOnlyDictionary<string, string?>? parameters, Canc |
| | 20 | 37 | | PostDetailedAsync(path, parameters, true, cancellationToken); |
| | | 38 | | |
| | | 39 | | private async Task<MlAutoApiResponse> PostDetailedAsync(string path, IReadOnlyDictionary<string, string?>? parameter |
| | | 40 | | { |
| | 111 | 41 | | if (authorize && (string.IsNullOrWhiteSpace(_config.Login) || string.IsNullOrWhiteSpace(_config.Password))) |
| | 0 | 42 | | throw new MlAutoApiException("Не настроены MlAuto:Login и/или MlAuto:Password."); |
| | | 43 | | |
| | 111 | 44 | | var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); |
| | 111 | 45 | | if (authorize) |
| | | 46 | | { |
| | 111 | 47 | | values["LOGIN"] = _config.Login; |
| | 111 | 48 | | values["PASSWORD"] = _config.Password; |
| | | 49 | | } |
| | 111 | 50 | | if (parameters != null) |
| | 1477 | 51 | | foreach (var (key, value) in parameters.Where(x => !string.IsNullOrWhiteSpace(x.Value))) |
| | 422 | 52 | | values[key] = value!; |
| | | 53 | | |
| | 111 | 54 | | await _limiter.WaitAsync(cancellationToken); |
| | 110 | 55 | | var timer = Stopwatch.StartNew(); |
| | | 56 | | HttpResponseMessage response; |
| | | 57 | | string text; |
| | | 58 | | try |
| | | 59 | | { |
| | 110 | 60 | | response = await _factory.CreateClient(_httpClientName).PostAsync(BuildUri(path), new FormUrlEncodedContent( |
| | 106 | 61 | | text = await response.Content.ReadAsStringAsync(cancellationToken); |
| | 106 | 62 | | } |
| | 4 | 63 | | catch (Exception ex) |
| | | 64 | | { |
| | 4 | 65 | | _logs?.Add(_providerKey, "POST", path, null, timer, |
| | 10 | 66 | | string.Join("&", values.Select(x => $"{x.Key}={x.Value}")), ex.Message); |
| | 4 | 67 | | throw; |
| | | 68 | | } |
| | 106 | 69 | | using (response) |
| | | 70 | | { |
| | 106 | 71 | | _logs?.Add(_providerKey, "POST", path, (int)response.StatusCode, timer, |
| | 652 | 72 | | string.Join("&", values.Select(x => $"{x.Key}={x.Value}")), text); |
| | 106 | 73 | | if (!response.IsSuccessStatusCode) |
| | 1 | 74 | | throw new MlAutoApiException($"ML-Auto вернул HTTP {(int)response.StatusCode}.", (int)response.StatusCode, p |
| | 105 | 75 | | } |
| | | 76 | | |
| | | 77 | | JObject envelope; |
| | 209 | 78 | | try { envelope = JObject.Parse(text); } |
| | 1 | 79 | | catch (Exception ex) |
| | | 80 | | { |
| | 1 | 81 | | var snippet = FormatResponseSnippet(text); |
| | 1 | 82 | | var message = string.IsNullOrWhiteSpace(snippet) |
| | 1 | 83 | | ? "ML-Auto вернул невалидный JSON." |
| | 1 | 84 | | : $"ML-Auto вернул невалидный JSON (ответ: '{snippet}')."; |
| | 1 | 85 | | throw new MlAutoApiException(message, requestPath: path, innerException: ex); |
| | | 86 | | } |
| | | 87 | | |
| | 104 | 88 | | var providerMessage = GetProviderMessage(envelope["MESSAGES"]); |
| | 104 | 89 | | var status = envelope.Value<int?>("STATUS") ?? 200; |
| | 104 | 90 | | if (status != 200) |
| | | 91 | | { |
| | 5 | 92 | | var rateLimited = IsRateLimitMessage(providerMessage); |
| | 6 | 93 | | if (rateLimited) _limiter.Penalize(); |
| | 5 | 94 | | throw new MlAutoApiException(string.IsNullOrWhiteSpace(providerMessage) ? $"ML-Auto вернул статус {status}." |
| | 5 | 95 | | { |
| | 5 | 96 | | IsRateLimited = rateLimited |
| | 5 | 97 | | }; |
| | | 98 | | } |
| | 99 | 99 | | return new MlAutoApiResponse(envelope["RESPONSE"] ?? new JArray(), string.IsNullOrWhiteSpace(providerMessage) ? |
| | 99 | 100 | | } |
| | | 101 | | |
| | | 102 | | private static bool IsRateLimitMessage(string? message) => |
| | 5 | 103 | | message?.Contains("лимит запросов", StringComparison.OrdinalIgnoreCase) == true; |
| | | 104 | | |
| | 104 | 105 | | private static string GetProviderMessage(JToken? messages) => messages switch |
| | 104 | 106 | | { |
| | 14 | 107 | | JArray array => string.Join("; ", array.Select(ExtractMessage).Where(x => !string.IsNullOrWhiteSpace(x))), |
| | 6 | 108 | | JObject obj => string.Join("; ", obj.Properties().Select(x => ExtractMessage(x.Value)).Where(x => !string.IsNull |
| | 93 | 109 | | _ => string.Empty |
| | 104 | 110 | | }; |
| | | 111 | | |
| | | 112 | | private static string ExtractMessage(JToken message) => |
| | 7 | 113 | | message is JObject obj ? obj.Value<string>("MSG_TEXT") ?? obj.ToString() : message.ToString(); |
| | | 114 | | |
| | | 115 | | private static string FormatResponseSnippet(string? text) |
| | | 116 | | { |
| | 1 | 117 | | if (string.IsNullOrWhiteSpace(text)) return string.Empty; |
| | 1 | 118 | | var singleLine = string.Join(" ", text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)); |
| | 1 | 119 | | return singleLine.Length > 120 ? singleLine[..117] + "..." : singleLine; |
| | | 120 | | } |
| | | 121 | | |
| | 110 | 122 | | private Uri BuildUri(string path) => new(_config.BaseUrl.TrimEnd('/') + "/" + path.TrimStart('/')); |
| | | 123 | | } |