MdpApiPushExecutor.cs 4.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System.Net.Http.Headers;
  2. using System.Text;
  3. using System.Text.Json;
  4. using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
  5. using Microsoft.Extensions.Logging;
  6. namespace Admin.NET.Plugin.AiDOP.DataPlatform.Executors;
  7. /// <summary>
  8. /// 出站回写(HTTP):按 payload 调第三方写接口。批量扫描由 <see cref="MdpTargetPushDispatcher"/> 负责。
  9. /// </summary>
  10. public sealed class MdpApiPushExecutor : IMdpTargetPushExecutor, ITransient
  11. {
  12. private readonly IHttpClientFactory _httpClientFactory;
  13. private readonly ILogger _logger;
  14. public MdpApiPushExecutor(IHttpClientFactory httpClientFactory, ILoggerFactory loggerFactory)
  15. {
  16. _httpClientFactory = httpClientFactory;
  17. _logger = loggerFactory.CreateLogger(nameof(MdpApiPushExecutor));
  18. }
  19. public string SupportedType => "API";
  20. public async Task<MdpPushResult> PushAsync(MdpSource source, MdpOutbox item, CancellationToken ct = default)
  21. {
  22. if (source == null || string.IsNullOrWhiteSpace(source.ApiBaseUrl))
  23. {
  24. _logger.LogWarning(
  25. "[MdpApiPushExecutor] 未配置 API outbox id={Id} idem={Idem} action={Action} source={Source} type={Type}",
  26. item.Id, item.IdemKey, item.ActionCode,
  27. source?.SourceCode ?? item.TargetSourceCode, source?.SourceType);
  28. return MdpPushResult.Fail($"目标源 {item.TargetSourceCode} 未配置 API");
  29. }
  30. using var payloadDoc = JsonDocument.Parse(string.IsNullOrWhiteSpace(item.PayloadJson) ? "{}" : item.PayloadJson!);
  31. var root = payloadDoc.RootElement;
  32. var path = root.TryGetProperty("path", out var p) ? p.GetString() : $"/outbox/{item.ActionCode}";
  33. var method = root.TryGetProperty("method", out var m) ? (m.GetString() ?? "POST") : "POST";
  34. var bodyEl = root.TryGetProperty("body", out var b) ? b : root;
  35. var client = _httpClientFactory.CreateClient("MdpApiPush");
  36. client.Timeout = TimeSpan.FromSeconds(60);
  37. var url = source.ApiBaseUrl!.TrimEnd('/') + (path!.StartsWith('/') ? path : "/" + path);
  38. using var request = new HttpRequestMessage(new HttpMethod(method), url);
  39. ApplyAuth(request, source);
  40. request.Content = new StringContent(bodyEl.GetRawText(), Encoding.UTF8, "application/json");
  41. using var response = await client.SendAsync(request, ct);
  42. var respBody = await response.Content.ReadAsStringAsync(ct);
  43. if (response.IsSuccessStatusCode)
  44. return MdpPushResult.Ok(1, Truncate(respBody, 4000));
  45. return MdpPushResult.Fail($"HTTP {(int)response.StatusCode}", Truncate(respBody, 4000));
  46. }
  47. private static void ApplyAuth(HttpRequestMessage request, MdpSource source)
  48. {
  49. var authType = (source.ApiAuthType ?? "NONE").Trim().ToUpperInvariant();
  50. if (authType is "NONE" or "") return;
  51. Dictionary<string, string>? cfg = null;
  52. if (!string.IsNullOrWhiteSpace(source.ApiAuthConfig))
  53. {
  54. try { cfg = JsonSerializer.Deserialize<Dictionary<string, string>>(source.ApiAuthConfig!); }
  55. catch { /* ignore */ }
  56. }
  57. cfg ??= new Dictionary<string, string>();
  58. if ((authType is "BEARER" or "TOKEN") && (cfg.TryGetValue("token", out var token) || cfg.TryGetValue("access_token", out token)))
  59. request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
  60. else if (authType == "BASIC" && cfg.TryGetValue("username", out var user) && cfg.TryGetValue("password", out var pwd))
  61. request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{user}:{pwd}")));
  62. else if (authType == "APIKEY")
  63. {
  64. var header = cfg.GetValueOrDefault("header") ?? "X-API-Key";
  65. if (cfg.TryGetValue("apiKey", out var key) || cfg.TryGetValue("key", out key))
  66. request.Headers.TryAddWithoutValidation(header, key);
  67. }
  68. }
  69. private static string? Truncate(string? s, int max) =>
  70. string.IsNullOrEmpty(s) ? s : (s.Length <= max ? s : s[..max]);
  71. }