S0DimMaterializer.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. try
  65. {
  66. // [0] 前置校验:配置漂移与源侧数据质量,全部在动任何数据之前
  67. var batchSize = await AssertEntityContractAsync(def, ct);
  68. var sourceCount = await _db.Ado.GetIntAsync(S0DimSqlBuilder.BuildSourceCountSql(def), ps);
  69. await AssertNoSourceDuplicateAsync(def, tenantId, sourceCount, batchSize, ps);
  70. // [2] purge:三段谓词精确到本租户 + 本源系统 + 本源表
  71. result.StagingPurged = await _purge.PurgeAsync(def, tenantId, ct);
  72. // [3] FULL pull
  73. // 租户三重防护:① MdpDbPullExecutor 对含租户列的源表加 WHERE tenant_id=@scopeTenantId;
  74. // ② MdpStagingWriter 对 tenantValue != ctx.TenantId 的行直接跳过;
  75. // ③ RequireMatchingSourceTenant=true → 源行无租户时不拿 ctx 兜底,直接跳过(绝不落 0)
  76. var pullCtx = new MdpPullContext
  77. {
  78. TenantId = tenantId,
  79. BatchId = batchId,
  80. FullRefresh = true,
  81. RequireMatchingSourceTenant = true
  82. };
  83. // 同库时优先走集合式装载(一条 INSERT ... SELECT,DB 往返 O(1));
  84. // 判定不成立或计划生成失败一律回退下面的逐行路径,语义不变、只是慢。
  85. // 参见 S0DimSameDbStagingLoader:判定只依据源与库的客观属性,
  86. // 不看 entity 名 / source_code 字面量 / 主机硬编码。
  87. var samedb = await _sameDbLoader.TryPlanAsync(def, ct);
  88. if (samedb is not null)
  89. {
  90. var written = await _sameDbLoader.LoadAsync(def, samedb, tenantId, batchId, ct);
  91. // 集合式语句无「读了多少行」的独立计数,装载行数即贴源行数;
  92. // 真正的把关在下面 [4][5] 的 stg == source 闸门,不依赖这里的自报数。
  93. result.SourcePulled = written;
  94. result.StagingWritten = written;
  95. _logger.LogInformation("[S0Dim] {Key} 走同库快路径:{Reason},写入 {Rows} 行",
  96. def.Key, samedb.Reason, written);
  97. }
  98. else
  99. {
  100. var pull = await _pullDispatcher.PullAllByEntityCodeAsync(def.EntityCode, pullCtx, ct);
  101. result.SourcePulled = pull.RowsPulled;
  102. result.StagingWritten = pull.RowsWritten;
  103. }
  104. // [4][5] 闸门:本批 staging 必须与源侧行数完全一致,否则不碰 dim
  105. var stagingCount = await _db.Ado.GetIntAsync(S0DimSqlBuilder.BuildStagingCountSql(def), ps);
  106. if (stagingCount != sourceCount)
  107. throw new InvalidOperationException(
  108. $"[{def.Key}] 贴源闸门未通过:source_count={sourceCount} 本批 stg_count={stagingCount}(dim 未改动)");
  109. // [6] dim 单事务:DELETE 本租户 → INSERT → 事务内阻断级对账
  110. result.DimRows = await MdpStdFullReplace.ReplaceAsync(
  111. _db, def.DimTable, tenantId, extraWhere: null,
  112. insertScopedAsync: async () =>
  113. {
  114. var now = DateTime.Now;
  115. var insertPs = new List<SugarParameter>(ps) { new("@Now", now) };
  116. var rows = await _db.Ado.ExecuteCommandAsync(S0DimSqlBuilder.BuildInsertSql(def), insertPs);
  117. result.Reconcile = await _reconciler.AssertBlockingAsync(def, tenantId, batchId, ct);
  118. return rows;
  119. },
  120. ct);
  121. result.Status = "SUCCESS";
  122. _logger.LogInformation(
  123. "[S0Dim] {Key} tenant={Tenant} batch={Batch} purged={Purged} pulled={Pulled} stg={Stg} dim={Dim}",
  124. def.Key, tenantId, batchId, result.StagingPurged, result.SourcePulled, stagingCount, result.DimRows);
  125. }
  126. catch (OperationCanceledException)
  127. {
  128. // 取消不是本维度的「失败」:吞掉它会把客户端断开记成 FAILED,
  129. // 且外层 RefreshAsync 的 ct.ThrowIfCancellationRequested() 会在下一轮抛出,
  130. // 导致 CompleteRunLogAsync 永不执行、run log 永久停在 RUNNING。
  131. // 事务侧无需担心:异常已在 MdpStdFullReplace 的 catch 中回滚,dim 未改动。
  132. throw;
  133. }
  134. catch (Exception ex)
  135. {
  136. result.Status = "FAILED";
  137. result.Error = ex.Message;
  138. _logger.LogError(ex, "[S0Dim] {Key} tenant={Tenant} batch={Batch} 物化失败(dim 未改动)",
  139. def.Key, tenantId, batchId);
  140. }
  141. return result;
  142. }
  143. /// <summary>
  144. /// 断言 <c>mdp_entity</c> 的运行时配置与 definition 完全一致,返回 batch_size。
  145. /// 这一步把「配置漂移」变成显式失败 —— 否则 <c>PullAll</c> 可能悄悄拉到别的表 / 别的源。
  146. /// </summary>
  147. private async Task<int> AssertEntityContractAsync(S0DimDefinition def, CancellationToken ct)
  148. {
  149. var entity = await _db.Queryable<MdpEntity>()
  150. .Where(x => x.EntityCode == def.EntityCode)
  151. .FirstAsync(ct)
  152. ?? throw new InvalidOperationException($"[{def.Key}] mdp_entity 未登记:{def.EntityCode}(migration 未执行?)");
  153. if (entity.Status != 1)
  154. throw new InvalidOperationException($"[{def.Key}] mdp_entity.{def.EntityCode} 已停用(status={entity.Status})");
  155. var source = await _db.Queryable<MdpSource>().Where(x => x.Id == entity.SourceId).FirstAsync(ct)
  156. ?? throw new InvalidOperationException($"[{def.Key}] mdp_source id={entity.SourceId} 不存在");
  157. void Expect(string what, string? actual, string expected)
  158. {
  159. if (!string.Equals(actual, expected, StringComparison.Ordinal))
  160. throw new InvalidOperationException($"[{def.Key}] mdp_entity 配置漂移:{what} 实际='{actual}' 期望='{expected}'");
  161. }
  162. Expect("source_code", source.SourceCode, def.SourceSystem);
  163. Expect("source_table_name", entity.SourceTableName, def.SourceTable);
  164. Expect("target_table_name", entity.TargetTableName, def.StagingTable);
  165. Expect("biz_key_expr", entity.BizKeyExpr, string.Join(",", def.SourceBizKeyColumns));
  166. // ── 执行器选路的三个开关:不查会被静默改道 ──
  167. // MdpSourcePullDispatcher 按
  168. // !IsNullOrWhiteSpace(entity.SourceApiPath) || source.SourceType == "API" → _apiExecutor
  169. // source.SourceType == "FILE_EXCEL" → Excel 分支
  170. // 选择执行器。上面那几条 Expect 全部**照样通过**,但拉取已不再是「本库 SELECT」。
  171. // 比较口径与 dispatcher 一致(OrdinalIgnoreCase),否则大小写差异会造成假通过。
  172. if (!string.IsNullOrWhiteSpace(entity.SourceApiPath))
  173. throw new InvalidOperationException(
  174. $"[{def.Key}] mdp_entity.source_api_path 必须为空,实际='{entity.SourceApiPath}':" +
  175. "非空会让 MdpSourcePullDispatcher 改走 API 执行器,绕开本库 DB 拉取契约");
  176. if (!string.Equals(source.SourceType, "DB", StringComparison.OrdinalIgnoreCase))
  177. throw new InvalidOperationException(
  178. $"[{def.Key}] mdp_source.source_type 必须为 DB,实际='{source.SourceType}'");
  179. if (!string.Equals(source.DbType, "MySQL", StringComparison.OrdinalIgnoreCase))
  180. throw new InvalidOperationException(
  181. $"[{def.Key}] mdp_source.db_type 必须为 MySQL,实际='{source.DbType}'");
  182. // 本阶段只做 FULL:留了 incr_column 会让 BuildSelectSql 生成 "col > @cursor",
  183. // 使源侧水位为 NULL 的行(如 DepartmentMaster 的 UATDEMO/未分配)永久不可达
  184. if (!string.Equals(entity.SyncMode, "FULL", StringComparison.OrdinalIgnoreCase))
  185. throw new InvalidOperationException($"[{def.Key}] sync_mode 必须为 FULL,实际='{entity.SyncMode}'");
  186. if (!string.IsNullOrWhiteSpace(entity.IncrColumn))
  187. throw new InvalidOperationException($"[{def.Key}] incr_column 必须为空(FULL 语义),实际='{entity.IncrColumn}'");
  188. return entity.BatchSize > 0 ? entity.BatchSize : 1000;
  189. }
  190. /// <summary>
  191. /// 源侧业务键重复探针 + 单页容量检查。两者都在 purge 之前,失败时**任何数据都未被触碰**。
  192. /// </summary>
  193. private async Task AssertNoSourceDuplicateAsync(
  194. S0DimDefinition def, long tenantId, int sourceCount, int batchSize, List<SugarParameter> ps)
  195. {
  196. // 分页依赖 MdpDbPullExecutor 无 incr_column 时的 "ORDER BY 1"(按第 1 个物理列),
  197. // 而 LocationMaster 的第 1 列是 Capacity(非唯一)→ 一旦真的翻页,OFFSET 结果不稳定。
  198. // 因此要求单页装得下;超出时显式失败并提示调大 mdp_entity.batch_size。
  199. if (sourceCount >= batchSize)
  200. throw new InvalidOperationException(
  201. $"[{def.Key}] 源行数 {sourceCount} 已达单页容量 {batchSize}:" +
  202. "通用执行器在无 incr_column 时按 'ORDER BY 1' 分页,对本表非稳定序,请调大 mdp_entity.batch_size");
  203. var q = await _db.Ado.SqlQueryAsync<SourceBizKeyProbe>(
  204. S0DimSqlBuilder.BuildBizKeyQualitySql(S0DimSqlBuilder.SourceBizKeySetSql(def)), ps);
  205. var probe = q.FirstOrDefault();
  206. if (probe is null) return;
  207. if (probe.Blank_Cnt > 0)
  208. throw new InvalidOperationException(
  209. $"[{def.Key}] tenant={tenantId} 源侧有 {probe.Blank_Cnt} 行业务键为空,拒绝物化");
  210. if (probe.Total != probe.Distinct_Cnt)
  211. throw new InvalidOperationException(
  212. $"[{def.Key}] tenant={tenantId} 源侧业务键重复(total={probe.Total} distinct={probe.Distinct_Cnt}):" +
  213. "主数据唯一性已被破坏,transform 显式失败 —— 不做 first-wins / last-wins 静默取舍");
  214. }
  215. private sealed class SourceBizKeyProbe
  216. {
  217. public int Total { get; set; }
  218. public int Distinct_Cnt { get; set; }
  219. public int Blank_Cnt { get; set; }
  220. }
  221. }