MdpApiPullExecutor.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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 SqlSugar;
  6. using Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  7. namespace Admin.NET.Plugin.AiDOP.DataPlatform.Executors;
  8. /// <summary>
  9. /// 方式乙:按 mdp_source API 段 + mdp_entity.source_api_path 拉取 JSON → target_table_name(贴源)。
  10. /// </summary>
  11. public sealed class MdpApiPullExecutor : IMdpSourcePullExecutor, ITransient
  12. {
  13. public string SupportedType => "API_PULL";
  14. private readonly MdpApiPullEgress _egress;
  15. private readonly ISqlSugarClient _db;
  16. private readonly MdpStagingWriter _writer;
  17. public MdpApiPullExecutor(MdpApiPullEgress egress, ISqlSugarClient db, MdpStagingWriter writer)
  18. {
  19. _egress = egress;
  20. _db = db;
  21. _writer = writer;
  22. }
  23. public async Task<MdpPullResult> PullAsync(MdpSource source, MdpEntity entity, MdpPullContext ctx, CancellationToken cancellationToken = default)
  24. {
  25. if (string.IsNullOrWhiteSpace(source.ApiBaseUrl))
  26. throw new InvalidOperationException($"源 {source.SourceCode} 未配置 api_base_url");
  27. if (string.IsNullOrWhiteSpace(entity.SourceApiPath))
  28. throw new InvalidOperationException($"实体 {entity.EntityCode} 未配置 source_api_path");
  29. if (string.IsNullOrWhiteSpace(entity.TargetTableName))
  30. throw new InvalidOperationException($"实体 {entity.EntityCode} 未配置 target_table_name");
  31. var url = CombineUrl(source.ApiBaseUrl!, entity.SourceApiPath!);
  32. if (!string.IsNullOrWhiteSpace(entity.LastCursor) && !ctx.FullRefresh)
  33. url += (url.Contains('?') ? "&" : "?") + "cursor=" + Uri.EscapeDataString(entity.LastCursor);
  34. var endpoint = new Uri(url);
  35. var requiresTls = !string.IsNullOrWhiteSpace(source.ApiAuthType) && !source.ApiAuthType.Equals("NONE", StringComparison.OrdinalIgnoreCase);
  36. using var client = _egress.Open(source.TenantId, source.Id, endpoint, requireHttps: requiresTls);
  37. using var request = new HttpRequestMessage(HttpMethod.Get, endpoint);
  38. ApplyAuth(request, source);
  39. using var response = await client.SendAsync(request, cancellationToken);
  40. var body = await response.Content.ReadAsStringAsync(cancellationToken);
  41. if (!response.IsSuccessStatusCode)
  42. throw new InvalidOperationException($"API_PULL 失败 HTTP {(int)response.StatusCode}");
  43. using var doc = JsonDocument.Parse(string.IsNullOrWhiteSpace(body) ? "[]" : body);
  44. var items = ResolveArray(doc.RootElement, entity.ResponseDataPath);
  45. var written = 0;
  46. var now = DateTime.Now;
  47. string? newCursor = entity.LastCursor;
  48. var seen = new HashSet<string>(StringComparer.Ordinal);
  49. var pending = new List<(IDictionary<string, object?> Row, string RawJson, string SourceRowId)>();
  50. foreach (var item in items)
  51. {
  52. cancellationToken.ThrowIfCancellationRequested();
  53. var dedup = ResolvePath(item, entity.DedupKeyPath) ?? Guid.NewGuid().ToString("N");
  54. if (!seen.Add(dedup)) continue;
  55. var rawJson = item.GetRawText();
  56. var dict = JsonElementToDict(item);
  57. pending.Add((dict, rawJson, dedup));
  58. newCursor = dedup;
  59. }
  60. if (pending.Count > 0)
  61. {
  62. // 贴源 source_table 优先用逻辑源表名(与 DB 路线/std 过滤一致);未配置时回落 API path
  63. var stagingTable = !string.IsNullOrWhiteSpace(entity.SourceTableName)
  64. ? entity.SourceTableName!
  65. : entity.SourceApiPath!;
  66. var results = await _writer.UpsertBatchAsync(source, entity, stagingTable, pending, ctx);
  67. written += results.Sum();
  68. }
  69. if (!string.IsNullOrEmpty(newCursor) && newCursor != entity.LastCursor)
  70. {
  71. await _db.Updateable<MdpEntity>()
  72. .SetColumns(x => new MdpEntity
  73. {
  74. LastCursor = newCursor,
  75. LastSyncTo = now,
  76. UpdateTime = now
  77. })
  78. .Where(x => x.Id == entity.Id)
  79. .ExecuteCommandAsync(cancellationToken);
  80. }
  81. return new MdpPullResult
  82. {
  83. RowsPulled = items.Count,
  84. RowsWritten = written,
  85. NewCursor = newCursor,
  86. Message = "OK"
  87. };
  88. }
  89. private static void ApplyAuth(HttpRequestMessage request, MdpSource source)
  90. {
  91. var authType = (source.ApiAuthType ?? "NONE").Trim().ToUpperInvariant();
  92. if (authType is "NONE" or "") return;
  93. Dictionary<string, string>? cfg = null;
  94. if (!string.IsNullOrWhiteSpace(source.ApiAuthConfig))
  95. {
  96. try
  97. {
  98. cfg = JsonSerializer.Deserialize<Dictionary<string, string>>(source.ApiAuthConfig!);
  99. }
  100. catch { /* ignore */ }
  101. }
  102. cfg ??= new Dictionary<string, string>();
  103. switch (authType)
  104. {
  105. case "BEARER":
  106. case "TOKEN":
  107. if (cfg.TryGetValue("token", out var token) || cfg.TryGetValue("access_token", out token))
  108. request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
  109. break;
  110. case "BASIC":
  111. if (cfg.TryGetValue("username", out var user) && cfg.TryGetValue("password", out var pwd))
  112. {
  113. var bytes = Encoding.UTF8.GetBytes($"{user}:{pwd}");
  114. request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytes));
  115. }
  116. break;
  117. case "APIKEY":
  118. var header = cfg.GetValueOrDefault("header") ?? "X-API-Key";
  119. if (cfg.TryGetValue("apiKey", out var key) || cfg.TryGetValue("key", out key))
  120. request.Headers.TryAddWithoutValidation(header, key);
  121. break;
  122. case "OAUTH2":
  123. if (cfg.TryGetValue("access_token", out var oauth))
  124. request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", oauth);
  125. break;
  126. }
  127. }
  128. private static List<JsonElement> ResolveArray(JsonElement root, string? path)
  129. {
  130. var el = string.IsNullOrWhiteSpace(path) ? root : ResolveElement(root, path!) ?? root;
  131. if (el.ValueKind == JsonValueKind.Array)
  132. return el.EnumerateArray().Select(x => x.Clone()).ToList();
  133. if (el.ValueKind == JsonValueKind.Object)
  134. return new List<JsonElement> { el.Clone() };
  135. return new List<JsonElement>();
  136. }
  137. private static JsonElement? ResolveElement(JsonElement root, string path)
  138. {
  139. var cur = root;
  140. foreach (var part in path.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
  141. {
  142. if (cur.ValueKind != JsonValueKind.Object || !cur.TryGetProperty(part, out cur))
  143. return null;
  144. }
  145. return cur;
  146. }
  147. private static string? ResolvePath(JsonElement el, string? path)
  148. {
  149. if (string.IsNullOrWhiteSpace(path)) return null;
  150. var found = ResolveElement(el, path);
  151. if (found == null) return null;
  152. return found.Value.ValueKind switch
  153. {
  154. JsonValueKind.String => found.Value.GetString(),
  155. JsonValueKind.Number => found.Value.ToString(),
  156. JsonValueKind.True => "true",
  157. JsonValueKind.False => "false",
  158. _ => found.Value.ToString()
  159. };
  160. }
  161. private static string CombineUrl(string baseUrl, string path)
  162. {
  163. baseUrl = baseUrl.TrimEnd('/');
  164. path = path.StartsWith('/') ? path : "/" + path;
  165. return baseUrl + path;
  166. }
  167. private static Dictionary<string, object?> JsonElementToDict(JsonElement el)
  168. {
  169. var dict = new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase);
  170. if (el.ValueKind != JsonValueKind.Object) return dict;
  171. foreach (var prop in el.EnumerateObject())
  172. {
  173. dict[prop.Name] = prop.Value.ValueKind switch
  174. {
  175. JsonValueKind.Null => null,
  176. JsonValueKind.String => prop.Value.GetString(),
  177. JsonValueKind.Number => prop.Value.TryGetInt64(out var l) ? l
  178. : prop.Value.TryGetDecimal(out var d) ? d
  179. : prop.Value.GetDouble(),
  180. JsonValueKind.True => true,
  181. JsonValueKind.False => false,
  182. _ => prop.Value.GetRawText()
  183. };
  184. }
  185. return dict;
  186. }
  187. }