S0DimMaterializer.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. using Admin.NET.Plugin.AiDOP.DataPlatform.Executors;
  2. using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
  3. using Microsoft.Extensions.Logging;
  4. using SqlSugar;
  5. namespace Admin.NET.Plugin.AiDOP.DataPlatform.S0Dim;
  6. /// <summary>
  7. /// 单个 S0 维度的物化:source → staging → dim,FULL REPLACE 语义。
  8. ///
  9. /// 时序与事务边界:
  10. /// <code>
  11. /// [0] 前置校验(只读):mdp_entity 配置与 definition 一致 + 源侧业务键无重复 + 数据量未超单页
  12. /// [1] source_count(只读,按租户)
  13. /// ── 阶段 I:staging(非事务,可重跑)
  14. /// [2] purge 本租户+本源系统+本源表 分区
  15. /// [3] FULL pull(源侧/写入侧双重租户过滤)
  16. /// [4] staging_count(本批四段谓词)
  17. /// ── 阶段 II:闸门
  18. /// [5] stg_count != source_count → 本维度 FAILED,**dim 不动**(保持上一轮完整快照)
  19. /// ── 阶段 III:dim(单事务)
  20. /// [6] DELETE tenant 行 + INSERT(无 ON DUPLICATE KEY)+ 事务内阻断级对账 → 任一失败整体回滚
  21. /// </code>
  22. ///
  23. /// 失败时 dim 永远停在**上一轮的完整快照**,不会半新半旧。
  24. /// </summary>
  25. public sealed class S0DimMaterializer : ITransient
  26. {
  27. private readonly ISqlSugarClient _db;
  28. private readonly MdpSourcePullDispatcher _pullDispatcher;
  29. private readonly S0DimStagingPurge _purge;
  30. private readonly S0DimSameDbStagingLoader _sameDbLoader;
  31. private readonly S0DimReconciler _reconciler;
  32. private readonly ILogger<S0DimMaterializer> _logger;
  33. /// <summary>构造。</summary>
  34. public S0DimMaterializer(
  35. ISqlSugarClient db,
  36. MdpSourcePullDispatcher pullDispatcher,
  37. S0DimStagingPurge purge,
  38. S0DimSameDbStagingLoader sameDbLoader,
  39. S0DimReconciler reconciler,
  40. ILogger<S0DimMaterializer> logger)
  41. {
  42. _db = db;
  43. _pullDispatcher = pullDispatcher;
  44. _purge = purge;
  45. _sameDbLoader = sameDbLoader;
  46. _reconciler = reconciler;
  47. _logger = logger;
  48. }
  49. /// <summary>物化一个维度。</summary>
  50. public async Task<S0DimMaterializeResult> RunAsync(
  51. S0DimDefinition def, long tenantId, string batchId, CancellationToken ct = default)
  52. {
  53. def.Validate();
  54. if (tenantId <= 0) throw new InvalidOperationException($"[{def.Key}] 拒绝无效租户:{tenantId}");
  55. if (string.IsNullOrWhiteSpace(batchId)) throw new InvalidOperationException($"[{def.Key}] batchId 不得为空");
  56. var result = new S0DimMaterializeResult { Key = def.Key, TenantId = tenantId, BatchId = batchId };
  57. var ps = new List<SugarParameter>
  58. {
  59. new("@TenantId", tenantId),
  60. new("@SourceSystem", def.SourceSystem),
  61. new("@SourceTable", def.SourceTable),
  62. new("@BatchId", batchId)
  63. };
  64. // 🔴 全局 CommandTimeOut = 30s(Admin.NET.Core/SqlSugar/SqlSugarSetup.cs:155),对本管线不够用。
  65. // 实测(mdp_transform_run_log,2026-09-08):ITEM 单维度平均 132.7s、最大 1169.8s;
  66. // ITEM_BOM 的同库 INSERT ... SELECT 单条就要 ~27s,**紧贴 30s 线**,已实际炸过三次:
  67. // 45747 ITEM "The Command Timeout expired before the operation completed."
  68. // 45941 ITEM_BOM "Connection must be Open; current state is Closed"
  69. // 45945 ITEM_BOM "The Command Timeout expired before the operation completed."
  70. // 手工逐个刷时人会重试,所以问题被掩盖;自动刷新上线后会变成每拍稳定失败。
  71. // 这里只在物化区间内临时放宽,Dispose 时还原(异常路径同样还原),
  72. // 不改全局常量、不影响其它模块 —— 范式取自
  73. // MaterialWarehouse/InventoryMdpSyncService.cs:627-644。
  74. using var commandTimeout = new LongCommandTimeoutScope(_db, MaterializeCommandTimeoutSeconds);
  75. try
  76. {
  77. // [0] 前置校验:配置漂移与源侧数据质量,全部在动任何数据之前
  78. var batchSize = await AssertEntityContractAsync(def, ct);
  79. var sourceCount = await _db.Ado.GetIntAsync(S0DimSqlBuilder.BuildSourceCountSql(def), ps);
  80. await AssertNoSourceDuplicateAsync(def, tenantId, sourceCount, batchSize, ps);
  81. // [2] purge:三段谓词精确到本租户 + 本源系统 + 本源表
  82. result.StagingPurged = await _purge.PurgeAsync(def, tenantId, ct);
  83. // [3] FULL pull
  84. // 租户三重防护:① MdpDbPullExecutor 对含租户列的源表加 WHERE tenant_id=@scopeTenantId;
  85. // ② MdpStagingWriter 对 tenantValue != ctx.TenantId 的行直接跳过;
  86. // ③ RequireMatchingSourceTenant=true → 源行无租户时不拿 ctx 兜底,直接跳过(绝不落 0)
  87. var pullCtx = new MdpPullContext
  88. {
  89. TenantId = tenantId,
  90. BatchId = batchId,
  91. FullRefresh = true,
  92. RequireMatchingSourceTenant = true
  93. };
  94. // 同库时优先走集合式装载(一条 INSERT ... SELECT,DB 往返 O(1));
  95. // 判定不成立或计划生成失败一律回退下面的逐行路径,语义不变、只是慢。
  96. // 参见 S0DimSameDbStagingLoader:判定只依据源与库的客观属性,
  97. // 不看 entity 名 / source_code 字面量 / 主机硬编码。
  98. var samedb = await _sameDbLoader.TryPlanAsync(def, ct);
  99. if (samedb is not null)
  100. {
  101. var written = await _sameDbLoader.LoadAsync(def, samedb, tenantId, batchId, ct);
  102. // 集合式语句无「读了多少行」的独立计数,装载行数即贴源行数;
  103. // 真正的把关在下面 [4][5] 的 stg == source 闸门,不依赖这里的自报数。
  104. result.SourcePulled = written;
  105. result.StagingWritten = written;
  106. _logger.LogInformation("[S0Dim] {Key} 走同库快路径:{Reason},写入 {Rows} 行",
  107. def.Key, samedb.Reason, written);
  108. }
  109. else
  110. {
  111. var pull = await _pullDispatcher.PullAllByEntityCodeAsync(def.EntityCode, pullCtx, ct);
  112. result.SourcePulled = pull.RowsPulled;
  113. result.StagingWritten = pull.RowsWritten;
  114. }
  115. // [4][5] 闸门:本批 staging 必须与源侧行数完全一致,否则不碰 dim
  116. var stagingCount = await _db.Ado.GetIntAsync(S0DimSqlBuilder.BuildStagingCountSql(def), ps);
  117. if (stagingCount != sourceCount)
  118. throw new InvalidOperationException(
  119. $"[{def.Key}] 贴源闸门未通过:source_count={sourceCount} 本批 stg_count={stagingCount}(dim 未改动)");
  120. // [6] dim 单事务:DELETE 本租户 → INSERT → 事务内阻断级对账
  121. result.DimRows = await MdpStdFullReplace.ReplaceAsync(
  122. _db, def.DimTable, tenantId, extraWhere: null,
  123. insertScopedAsync: async () =>
  124. {
  125. var now = DateTime.Now;
  126. var insertPs = new List<SugarParameter>(ps) { new("@Now", now) };
  127. var rows = await _db.Ado.ExecuteCommandAsync(S0DimSqlBuilder.BuildInsertSql(def), insertPs);
  128. result.Reconcile = await _reconciler.AssertBlockingAsync(def, tenantId, batchId, ct);
  129. return rows;
  130. },
  131. ct);
  132. result.Status = "SUCCESS";
  133. _logger.LogInformation(
  134. "[S0Dim] {Key} tenant={Tenant} batch={Batch} purged={Purged} pulled={Pulled} stg={Stg} dim={Dim}",
  135. def.Key, tenantId, batchId, result.StagingPurged, result.SourcePulled, stagingCount, result.DimRows);
  136. }
  137. catch (OperationCanceledException)
  138. {
  139. // 取消不是本维度的「失败」:吞掉它会把客户端断开记成 FAILED,
  140. // 且外层 RefreshAsync 的 ct.ThrowIfCancellationRequested() 会在下一轮抛出,
  141. // 导致 CompleteRunLogAsync 永不执行、run log 永久停在 RUNNING。
  142. // 事务侧无需担心:异常已在 MdpStdFullReplace 的 catch 中回滚,dim 未改动。
  143. throw;
  144. }
  145. catch (Exception ex)
  146. {
  147. result.Status = "FAILED";
  148. result.Error = ex.Message;
  149. _logger.LogError(ex, "[S0Dim] {Key} tenant={Tenant} batch={Batch} 物化失败(dim 未改动)",
  150. def.Key, tenantId, batchId);
  151. }
  152. return result;
  153. }
  154. /// <summary>
  155. /// 物化区间的命令超时(秒)。取 900 与 <c>InventoryMdpSyncService</c> 一致:
  156. /// 覆盖实测最慢的 ITEM(单维度最大 1169.8s 是整轮耗时,其中单条命令远小于此)并留足余量。
  157. /// </summary>
  158. private const int MaterializeCommandTimeoutSeconds = 900;
  159. /// <summary>物化区间内临时放宽命令超时,Dispose 时还原原值(异常路径同样还原)。</summary>
  160. private sealed class LongCommandTimeoutScope : IDisposable
  161. {
  162. private readonly ISqlSugarClient _db;
  163. private readonly int _original;
  164. public LongCommandTimeoutScope(ISqlSugarClient db, int seconds)
  165. {
  166. _db = db;
  167. _original = db.Ado.CommandTimeOut;
  168. db.Ado.CommandTimeOut = seconds;
  169. }
  170. public void Dispose() => _db.Ado.CommandTimeOut = _original;
  171. }
  172. /// <summary>
  173. /// 断言 <c>mdp_entity</c> 的运行时配置与 definition 完全一致,返回 batch_size。
  174. /// 这一步把「配置漂移」变成显式失败 —— 否则 <c>PullAll</c> 可能悄悄拉到别的表 / 别的源。
  175. /// </summary>
  176. private async Task<int> AssertEntityContractAsync(S0DimDefinition def, CancellationToken ct)
  177. {
  178. var entity = await _db.Queryable<MdpEntity>()
  179. .Where(x => x.EntityCode == def.EntityCode)
  180. .FirstAsync(ct)
  181. ?? throw new InvalidOperationException($"[{def.Key}] mdp_entity 未登记:{def.EntityCode}(migration 未执行?)");
  182. if (entity.Status != 1)
  183. throw new InvalidOperationException($"[{def.Key}] mdp_entity.{def.EntityCode} 已停用(status={entity.Status})");
  184. var source = await _db.Queryable<MdpSource>().Where(x => x.Id == entity.SourceId).FirstAsync(ct)
  185. ?? throw new InvalidOperationException($"[{def.Key}] mdp_source id={entity.SourceId} 不存在");
  186. void Expect(string what, string? actual, string expected)
  187. {
  188. if (!string.Equals(actual, expected, StringComparison.Ordinal))
  189. throw new InvalidOperationException($"[{def.Key}] mdp_entity 配置漂移:{what} 实际='{actual}' 期望='{expected}'");
  190. }
  191. Expect("source_code", source.SourceCode, def.SourceSystem);
  192. Expect("source_table_name", entity.SourceTableName, def.SourceTable);
  193. Expect("target_table_name", entity.TargetTableName, def.StagingTable);
  194. Expect("biz_key_expr", entity.BizKeyExpr, string.Join(",", def.SourceBizKeyColumns));
  195. // ── 执行器选路的三个开关:不查会被静默改道 ──
  196. // MdpSourcePullDispatcher 按
  197. // !IsNullOrWhiteSpace(entity.SourceApiPath) || source.SourceType == "API" → _apiExecutor
  198. // source.SourceType == "FILE_EXCEL" → Excel 分支
  199. // 选择执行器。上面那几条 Expect 全部**照样通过**,但拉取已不再是「本库 SELECT」。
  200. // 比较口径与 dispatcher 一致(OrdinalIgnoreCase),否则大小写差异会造成假通过。
  201. if (!string.IsNullOrWhiteSpace(entity.SourceApiPath))
  202. throw new InvalidOperationException(
  203. $"[{def.Key}] mdp_entity.source_api_path 必须为空,实际='{entity.SourceApiPath}':" +
  204. "非空会让 MdpSourcePullDispatcher 改走 API 执行器,绕开本库 DB 拉取契约");
  205. if (!string.Equals(source.SourceType, "DB", StringComparison.OrdinalIgnoreCase))
  206. throw new InvalidOperationException(
  207. $"[{def.Key}] mdp_source.source_type 必须为 DB,实际='{source.SourceType}'");
  208. if (!string.Equals(source.DbType, "MySQL", StringComparison.OrdinalIgnoreCase))
  209. throw new InvalidOperationException(
  210. $"[{def.Key}] mdp_source.db_type 必须为 MySQL,实际='{source.DbType}'");
  211. // 本阶段只做 FULL:留了 incr_column 会让 BuildSelectSql 生成 "col > @cursor",
  212. // 使源侧水位为 NULL 的行(如 DepartmentMaster 的 UATDEMO/未分配)永久不可达
  213. if (!string.Equals(entity.SyncMode, "FULL", StringComparison.OrdinalIgnoreCase))
  214. throw new InvalidOperationException($"[{def.Key}] sync_mode 必须为 FULL,实际='{entity.SyncMode}'");
  215. if (!string.IsNullOrWhiteSpace(entity.IncrColumn))
  216. throw new InvalidOperationException($"[{def.Key}] incr_column 必须为空(FULL 语义),实际='{entity.IncrColumn}'");
  217. return entity.BatchSize > 0 ? entity.BatchSize : 1000;
  218. }
  219. /// <summary>
  220. /// 源侧业务键重复探针 + 单页容量检查。两者都在 purge 之前,失败时**任何数据都未被触碰**。
  221. /// </summary>
  222. private async Task AssertNoSourceDuplicateAsync(
  223. S0DimDefinition def, long tenantId, int sourceCount, int batchSize, List<SugarParameter> ps)
  224. {
  225. // 分页依赖 MdpDbPullExecutor 无 incr_column 时的 "ORDER BY 1"(按第 1 个物理列),
  226. // 而 LocationMaster 的第 1 列是 Capacity(非唯一)→ 一旦真的翻页,OFFSET 结果不稳定。
  227. // 因此要求单页装得下;超出时显式失败并提示调大 mdp_entity.batch_size。
  228. if (sourceCount >= batchSize)
  229. throw new InvalidOperationException(
  230. $"[{def.Key}] 源行数 {sourceCount} 已达单页容量 {batchSize}:" +
  231. "通用执行器在无 incr_column 时按 'ORDER BY 1' 分页,对本表非稳定序,请调大 mdp_entity.batch_size");
  232. var q = await _db.Ado.SqlQueryAsync<SourceBizKeyProbe>(
  233. S0DimSqlBuilder.BuildBizKeyQualitySql(S0DimSqlBuilder.SourceBizKeySetSql(def)), ps);
  234. var probe = q.FirstOrDefault();
  235. if (probe is null) return;
  236. if (probe.Blank_Cnt > 0)
  237. throw new InvalidOperationException(
  238. $"[{def.Key}] tenant={tenantId} 源侧有 {probe.Blank_Cnt} 行业务键为空,拒绝物化");
  239. if (probe.Total != probe.Distinct_Cnt)
  240. throw new InvalidOperationException(
  241. $"[{def.Key}] tenant={tenantId} 源侧业务键重复(total={probe.Total} distinct={probe.Distinct_Cnt}):" +
  242. "主数据唯一性已被破坏,transform 显式失败 —— 不做 first-wins / last-wins 静默取舍");
  243. }
  244. private sealed class SourceBizKeyProbe
  245. {
  246. public int Total { get; set; }
  247. public int Distinct_Cnt { get; set; }
  248. public int Blank_Cnt { get; set; }
  249. }
  250. }