S0DimMaterializer.cs 12 KB

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