MdpTargetPushDispatcher.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. using Admin.NET.Plugin.AiDOP.DataPlatform.HotWatch;
  2. using Admin.NET.Plugin.AiDOP.DataPlatform.Wms;
  3. using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
  4. using Microsoft.Extensions.Logging;
  5. namespace Admin.NET.Plugin.AiDOP.DataPlatform.Executors;
  6. /// <summary>
  7. /// 出站分发:扫描 mdp_outbox,按 source_type 路由到 API / DB 执行器。
  8. /// WP10 S4b / D12:退避 1m/5m/15m/30m/60m/120m,MaxRetry=6;配置类失败不烧重试。
  9. /// P-029:MarkAsync 按 UpdateTime 乐观锁,避免与 TryEnqueueOrRefreshAsync 并发整列覆盖。
  10. /// </summary>
  11. public sealed class MdpTargetPushDispatcher : ITransient
  12. {
  13. public const int DefaultTake = 500;
  14. private const int MaxRetry = 6;
  15. /// <summary>D12:按 retry_count 下标取退避分钟数(clamp 到末项)。</summary>
  16. private static readonly int[] BackoffMinutes = [1, 5, 15, 30, 60, 120];
  17. private static readonly string[] PermanentErrorPrefixes =
  18. [
  19. "PAYLOAD_INVALID",
  20. "CONSTRAINT_VIOLATION",
  21. "SQL_CONSTRAINT",
  22. "UNSUPPORTED_OP",
  23. ];
  24. private readonly ISqlSugarClient _db;
  25. private readonly MdpApiPushExecutor _api;
  26. private readonly MdpDbPushExecutor _dbPush;
  27. private readonly MdpHotWatchService _hotWatch;
  28. private readonly PickBillNbrSyncService _pickNbrSync;
  29. private readonly ILogger _logger;
  30. public MdpTargetPushDispatcher(
  31. ISqlSugarClient db,
  32. MdpApiPushExecutor api,
  33. MdpDbPushExecutor dbPush,
  34. MdpHotWatchService hotWatch,
  35. PickBillNbrSyncService pickNbrSync,
  36. ILoggerFactory loggerFactory)
  37. {
  38. _db = db;
  39. _api = api;
  40. _dbPush = dbPush;
  41. _hotWatch = hotWatch;
  42. _pickNbrSync = pickNbrSync;
  43. _logger = loggerFactory.CreateLogger(nameof(MdpTargetPushDispatcher));
  44. }
  45. public async Task<(int success, int failed, int skipped)> PushPendingAsync(
  46. int take = DefaultTake, CancellationToken cancellationToken = default)
  47. {
  48. var now = DateTime.Now;
  49. var pending = await _db.Queryable<MdpOutbox>()
  50. .Where(x => x.Status == 0
  51. && x.RetryCount < MaxRetry
  52. && (x.NextRetryTime == null || x.NextRetryTime <= now))
  53. .OrderBy(x => x.Id)
  54. .Take(take > 0 ? take : DefaultTake)
  55. .ToListAsync(cancellationToken);
  56. var success = 0;
  57. var failed = 0;
  58. var skipped = 0;
  59. foreach (var item in pending)
  60. {
  61. cancellationToken.ThrowIfCancellationRequested();
  62. // 乐观锁基准:仅当 UpdateTime 未变时写入(期间被 refresh 则放弃)
  63. var loadedUpdateTime = item.UpdateTime;
  64. try
  65. {
  66. var sources = await _db.Queryable<MdpSource>()
  67. .Where(x => x.SourceCode == item.TargetSourceCode && x.Status == 1)
  68. .Take(1)
  69. .ToListAsync(cancellationToken);
  70. var source = sources.FirstOrDefault();
  71. if (source == null)
  72. {
  73. // 配置类失败:保持 pending,不烧 retry_count,便于配置修复后被 60s 兜底作业捡起
  74. await MarkConfigIssueAsync(
  75. item,
  76. "SOURCE_DISABLED",
  77. $"目标源 {item.TargetSourceCode} 未启用",
  78. cancellationToken);
  79. skipped++;
  80. continue;
  81. }
  82. if (!TryResolve(source, out var executor, out var routeError))
  83. {
  84. await MarkConfigIssueAsync(item, "SOURCE_ROUTE_UNRESOLVED", routeError!, cancellationToken);
  85. skipped++;
  86. continue;
  87. }
  88. _logger.LogInformation(
  89. "[MdpTargetPushDispatcher] outbox id={Id} source={Source} type={SourceType} via={Executor} action={Action}",
  90. item.Id, source.SourceCode, source.SourceType, executor!.SupportedType, item.ActionCode);
  91. var result = string.Equals(item.ActionCode, PickBillNbrSyncService.ActionCode, StringComparison.OrdinalIgnoreCase)
  92. ? await _pickNbrSync.ApplyFromOutboxAsync(item, cancellationToken)
  93. : await executor.PushAsync(source, item, cancellationToken);
  94. if (result.Success)
  95. {
  96. var marked = await MarkAsync(
  97. item, 1, result.ResponseJson, null, null, null, loadedUpdateTime, cancellationToken);
  98. if (!marked)
  99. {
  100. item.Status = 0;
  101. skipped++;
  102. continue;
  103. }
  104. try
  105. {
  106. await _hotWatch.TryEnrollFromOutboxSuccessAsync(item, cancellationToken);
  107. }
  108. catch (Exception enrollEx)
  109. {
  110. _logger.LogWarning(
  111. enrollEx,
  112. "[MdpTargetPushDispatcher] hot-watch enroll failed outbox id={Id} action={Action}",
  113. item.Id, item.ActionCode);
  114. }
  115. success++;
  116. }
  117. else
  118. {
  119. await ApplyFailureAsync(
  120. item, result.ResponseJson, result.ErrorMessage, loadedUpdateTime, cancellationToken);
  121. if (item.Status == 2) failed++; else skipped++;
  122. }
  123. }
  124. catch (Exception ex)
  125. {
  126. await ApplyFailureAsync(item, null, ex.Message, loadedUpdateTime, cancellationToken);
  127. if (item.Status == 2) failed++; else skipped++;
  128. _logger.LogWarning(ex, "[MdpTargetPushDispatcher] outbox id={Id} failed", item.Id);
  129. }
  130. }
  131. return (success, failed, skipped);
  132. }
  133. private async Task ApplyFailureAsync(
  134. MdpOutbox item,
  135. string? responseJson,
  136. string? errorMessage,
  137. DateTime loadedUpdateTime,
  138. CancellationToken ct)
  139. {
  140. var msg = Truncate(errorMessage, 900);
  141. var (errorCode, permanent) = ClassifyFailure(msg);
  142. if (permanent)
  143. {
  144. // 立即死信,不递增 retry_count
  145. item.NextRetryTime = null;
  146. item.LastErrorCode = errorCode;
  147. var marked = await MarkAsync(item, 2, responseJson, msg, null, errorCode, loadedUpdateTime, ct);
  148. if (!marked) item.Status = 0;
  149. return;
  150. }
  151. item.RetryCount++;
  152. item.LastErrorCode = errorCode;
  153. if (item.RetryCount >= MaxRetry)
  154. {
  155. item.NextRetryTime = null;
  156. var marked = await MarkAsync(item, 2, responseJson, msg, null, errorCode, loadedUpdateTime, ct);
  157. if (!marked) item.Status = 0;
  158. }
  159. else
  160. {
  161. item.NextRetryTime = DateTime.Now.AddMinutes(GetBackoffMinutes(item.RetryCount));
  162. var marked = await MarkAsync(
  163. item, 0, responseJson, msg, item.NextRetryTime, errorCode, loadedUpdateTime, ct);
  164. if (!marked) item.Status = 0;
  165. }
  166. }
  167. /// <summary>
  168. /// 可重试 vs 不可重试。配置类走 <see cref="MarkConfigIssueAsync"/>,不进本方法。
  169. /// </summary>
  170. private static (string? errorCode, bool permanent) ClassifyFailure(string? error)
  171. {
  172. if (string.IsNullOrWhiteSpace(error))
  173. return ("UNKNOWN", false);
  174. var trimmed = error.Trim();
  175. foreach (var prefix in PermanentErrorPrefixes)
  176. {
  177. if (trimmed.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
  178. return (prefix, true);
  179. }
  180. // payload 反序列化 / 解析失败 → 永久
  181. if (trimmed.Contains("payload 解析失败", StringComparison.OrdinalIgnoreCase)
  182. || trimmed.Contains("payload parse", StringComparison.OrdinalIgnoreCase)
  183. || trimmed.Contains("JsonException", StringComparison.OrdinalIgnoreCase)
  184. || trimmed.Contains("反序列化", StringComparison.OrdinalIgnoreCase))
  185. return ("PAYLOAD_INVALID", true);
  186. // SQL 约束 / 唯一冲突 → 永久
  187. if (ContainsAny(trimmed,
  188. "unique constraint", "unique key", "duplicate key", "duplicate entry",
  189. "primary key", "violation of unique", "violation of primary",
  190. "cannot insert duplicate", "约束", "唯一索引", "主键冲突"))
  191. return ("CONSTRAINT_VIOLATION", true);
  192. if (trimmed.Contains("不支持的 op", StringComparison.OrdinalIgnoreCase))
  193. return ("UNSUPPORTED_OP", true);
  194. // 连接 / 超时 → 可重试
  195. if (ContainsAny(trimmed,
  196. "timeout", "timed out", "connection", "network", "could not open",
  197. "unable to connect", "transport-level", "broken pipe", "socket",
  198. "连接", "超时", "无法连接"))
  199. return ("TRANSIENT", false);
  200. return ("RETRYABLE", false);
  201. }
  202. private static bool ContainsAny(string haystack, params string[] needles)
  203. {
  204. foreach (var n in needles)
  205. {
  206. if (haystack.Contains(n, StringComparison.OrdinalIgnoreCase))
  207. return true;
  208. }
  209. return false;
  210. }
  211. /// <summary>retry_count 从 1 起对应 Backoff[0];越界 clamp 到末项。</summary>
  212. private static int GetBackoffMinutes(int retryCount)
  213. {
  214. var idx = Math.Max(0, retryCount - 1);
  215. if (idx >= BackoffMinutes.Length)
  216. idx = BackoffMinutes.Length - 1;
  217. return BackoffMinutes[idx];
  218. }
  219. /// <summary>
  220. /// 按 source_type / 连接信息解析执行器;无法解析时返回可诊断错误(不再静默落到 API)。
  221. /// </summary>
  222. private bool TryResolve(MdpSource source, out IMdpTargetPushExecutor? executor, out string? errorMessage)
  223. {
  224. var t = (source.SourceType ?? "").Trim().ToUpperInvariant();
  225. if (t is "DB" or "SQLSERVER" or "MYSQL" or "DATABASE")
  226. {
  227. executor = _dbPush;
  228. errorMessage = null;
  229. return true;
  230. }
  231. if (t == "API" || t == "HTTP")
  232. {
  233. executor = _api;
  234. errorMessage = null;
  235. return true;
  236. }
  237. // 未标注类型时:有库连接信息则走 DB,否则不再猜 API
  238. if (!string.IsNullOrWhiteSpace(source.DbHost) && !string.IsNullOrWhiteSpace(source.DbName))
  239. {
  240. executor = _dbPush;
  241. errorMessage = null;
  242. return true;
  243. }
  244. _logger.LogWarning(
  245. "[MdpTargetPushDispatcher] 路由未解析 source={Code} source_type='{Type}' DbHost='{Host}' DbName='{Name}' ApiBaseUrl='{Api}'",
  246. source.SourceCode, source.SourceType, source.DbHost, source.DbName, source.ApiBaseUrl);
  247. executor = null;
  248. errorMessage =
  249. $"SOURCE_ROUTE_UNRESOLVED: 源 {source.SourceCode} 既未标注 source_type,也无 DbHost/DbName";
  250. return false;
  251. }
  252. /// <summary>配置类问题:仅写 ErrorMsg/LastErrorCode/UpdateTime,status 保持 0,retry_count 不变。</summary>
  253. private async Task MarkConfigIssueAsync(MdpOutbox item, string errorCode, string error, CancellationToken ct)
  254. {
  255. item.ErrorMsg = Truncate(error, 900);
  256. item.LastErrorCode = Truncate(errorCode, 64);
  257. item.UpdateTime = DateTime.Now;
  258. await _db.Updateable(item)
  259. .UpdateColumns(x => new { x.ErrorMsg, x.LastErrorCode, x.UpdateTime })
  260. .ExecuteCommandAsync(ct);
  261. }
  262. /// <summary>
  263. /// 条件更新:仅当 UpdateTime 与加载时一致才写入,避免与入队 refresh 丢失更新。
  264. /// </summary>
  265. private async Task<bool> MarkAsync(
  266. MdpOutbox item,
  267. int status,
  268. string? responseJson,
  269. string? error,
  270. DateTime? nextRetryTime,
  271. string? lastErrorCode,
  272. DateTime loadedUpdateTime,
  273. CancellationToken ct)
  274. {
  275. var now = DateTime.Now;
  276. var resp = Truncate(responseJson, 4000);
  277. var code = Truncate(lastErrorCode, 64);
  278. var affected = await _db.Updateable<MdpOutbox>()
  279. .SetColumns(x => x.Status == status)
  280. .SetColumns(x => x.RetryCount == item.RetryCount)
  281. .SetColumns(x => x.ResponseJson == resp)
  282. .SetColumns(x => x.ErrorMsg == error)
  283. .SetColumns(x => x.NextRetryTime == nextRetryTime)
  284. .SetColumns(x => x.LastErrorCode == code)
  285. .SetColumns(x => x.UpdateTime == now)
  286. .Where(x => x.Id == item.Id && x.UpdateTime == loadedUpdateTime)
  287. .ExecuteCommandAsync(ct);
  288. if (affected <= 0)
  289. {
  290. _logger.LogInformation(
  291. "[MdpTargetPushDispatcher] 标记被跳过(期间已被重新入队)outbox id={Id} idem={Idem} wantStatus={Status}",
  292. item.Id, item.IdemKey, status);
  293. return false;
  294. }
  295. item.Status = status;
  296. item.ResponseJson = resp;
  297. item.ErrorMsg = error;
  298. item.NextRetryTime = nextRetryTime;
  299. item.LastErrorCode = code;
  300. item.UpdateTime = now;
  301. return true;
  302. }
  303. private static string? Truncate(string? s, int max) =>
  304. string.IsNullOrEmpty(s) ? s : (s.Length <= max ? s : s[..max]);
  305. }