MdpPurchaseHandoffService.Recovery.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. using System.Globalization;
  2. using System.Security.Cryptography;
  3. using System.Text.Json;
  4. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  5. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  6. public sealed partial class MdpPurchaseHandoffService
  7. {
  8. private const string RecoveryReceiptSql = """
  9. SELECT payload_sha256 AS PayloadSha256,digest_format AS DigestFormat,line_results AS LineResults,
  10. package_version AS PackageVersion,created_at AS CreatedAt
  11. FROM mdp_ingest_handoff_receipt
  12. WHERE batch_id=@BatchId AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId
  13. """;
  14. internal async Task<PurchaseTrace?> ReadTraceAsync(StoredIngestBatch batch, CancellationToken token)
  15. {
  16. if (string.IsNullOrWhiteSpace(settings["MDP_PURCHASE_RECEIVER_MYSQL"]))
  17. return null;
  18. using var db = OpenBusinessDatabase();
  19. db.Ado.CancellationToken = token;
  20. var receipt = await db.Ado.SqlQuerySingleAsync<RecoveryReceipt>(RecoveryReceiptSql, batch.SqlArguments);
  21. if (receipt is null) return null;
  22. var history = await db.Ado.SqlQueryAsync<RecoveryAudit>("""
  23. SELECT CAST(actor_id AS CHAR) AS Actor,reason AS Reason,line_results AS LineResults,created_at AS CreatedAt
  24. FROM mdp_ingest_purchase_recovery
  25. WHERE batch_id=@BatchId AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId
  26. ORDER BY id DESC LIMIT 100
  27. """, batch.SqlArguments);
  28. return new(receipt.PackageVersion, receipt.PayloadSha256, Utc(receipt.CreatedAt), ReceiptLines(receipt).Select(ToTrace).ToList(),
  29. history.Select(row => new PurchaseRecoveryTrace(row.Actor, row.Reason, Utc(row.CreatedAt),
  30. (JsonSerializer.Deserialize<List<LineResult>>(row.LineResults, WireJson) ?? []).Select(ToTrace).ToList())).ToList());
  31. }
  32. internal async Task<PurchaseRecoveryPreview?> PreviewRestoreAsync(StoredIngestBatch batch, PurchaseHandoffPackage package,
  33. CancellationToken token)
  34. {
  35. if (string.IsNullOrWhiteSpace(settings["MDP_PURCHASE_RECEIVER_MYSQL"]))
  36. return null;
  37. using var db = OpenBusinessDatabase();
  38. db.Ado.CancellationToken = token;
  39. var tx = await db.Ado.UseTranAsync(async () =>
  40. {
  41. var receipt = await db.Ado.SqlQuerySingleAsync<RecoveryReceipt>(RecoveryReceiptSql + " FOR SHARE", batch.SqlArguments);
  42. if (receipt is null) return null;
  43. VerifyRecoveryReceipt(package, receipt);
  44. var lines = await InspectRecoveryAsync(db, package, receipt, token);
  45. return Preview(package, lines, await RecoveryRevisionAsync(db, batch));
  46. });
  47. if (!tx.IsSuccess) throw tx.ErrorException ?? Unavailable();
  48. return tx.Data;
  49. }
  50. internal async Task<PurchaseRecoveryResult> RestoreAsync(StoredIngestBatch batch, PurchaseHandoffPackage package,
  51. string previewDigest, string reason, long actor, CancellationToken token)
  52. {
  53. using var db = OpenBusinessDatabase();
  54. db.Ado.CancellationToken = token;
  55. var tx = await db.Ado.UseTranAsync(async () =>
  56. {
  57. var receipt = await db.Ado.SqlQuerySingleAsync<RecoveryReceipt>(RecoveryReceiptSql + " FOR UPDATE", batch.SqlArguments)
  58. ?? throw Error(409, "RAW_REPLAY_RECEIPT_MISSING");
  59. VerifyRecoveryReceipt(package, receipt);
  60. var prior = await db.Ado.SqlQuerySingleAsync<string>("""
  61. SELECT line_results FROM mdp_ingest_purchase_recovery WHERE batch_id=@BatchId AND preview_digest=@PreviewDigest
  62. AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId
  63. """, new { batch.BatchId, batch.TenantId, batch.FactoryId, batch.DatasetId, batch.SourceId, previewDigest });
  64. if (prior is not null)
  65. return Result(prior);
  66. // Lock the original source authority before taking business row locks (same order as ordinary handoff).
  67. var migration = await ValidateWriterAsync(db, package);
  68. MdpPurchaseMigrationStore.RequireAdmission(migration, MdpPurchaseMigrationStore.Unified);
  69. var lines = await InspectRecoveryAsync(db, package, receipt, token);
  70. var preview = Preview(package, lines, await RecoveryRevisionAsync(db, batch));
  71. if (preview.Digest != previewDigest || !preview.CanRestore)
  72. throw Error(409, "RAW_REPLAY_PREVIEW_CHANGED");
  73. var restored = new List<LineResult>();
  74. foreach (var line in lines.Where(row => row.NeedsRestore))
  75. {
  76. token.ThrowIfCancellationRequested();
  77. var outcome = await WriteLineAsync(db, package, batch.BatchId, line.Item);
  78. if (outcome.Status != "WRITTEN" || outcome.StageId is null || outcome.StandardId is null)
  79. throw Error(409, "RAW_REPLAY_TARGET_CONFLICT");
  80. if (line.Item.SourceChange is { } change)
  81. {
  82. var updated = await db.Ado.ExecuteCommandAsync("""
  83. UPDATE mdp_std_purchase_order_version SET stage_id=@StageId,standard_id=@StandardId
  84. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND po_no=@PoNo AND po_line=@PoLine
  85. AND source_id=@SourceId AND dataset_id=@DatasetId AND source_generation=@Generation
  86. AND source_version=@Version AND is_deleted=0
  87. """, new { outcome.StageId, outcome.StandardId, package.TenantId, package.FactoryId,
  88. line.Item.PoNo, line.Item.PoLine, package.SourceId, package.DatasetId, change.Generation, change.Version });
  89. if (updated != 1)
  90. throw Error(409, "RAW_REPLAY_VERSION_CHANGED");
  91. }
  92. if (migration is not null)
  93. {
  94. var traceKey = "restore-" + Convert.ToHexString(SHA256.HashData(
  95. System.Text.Encoding.UTF8.GetBytes(previewDigest + line.Item.RawEventId.ToString("D")))).ToLowerInvariant();
  96. await MdpPurchaseMigrationWriter.RecordVersionedAsync(db, migration, line.Item, batch.BatchId, outcome, traceKey);
  97. }
  98. restored.Add(new(line.Item.RawEventId, "RESTORED", outcome.StageId, outcome.StandardId));
  99. }
  100. var json = JsonSerializer.Serialize(restored, WireJson);
  101. await db.Ado.ExecuteCommandAsync("""
  102. INSERT INTO mdp_ingest_purchase_recovery
  103. (batch_id,tenant_id,factory_id,dataset_id,source_id,actor_id,preview_digest,reason,line_results,created_at)
  104. VALUES (@BatchId,@TenantId,@FactoryId,@DatasetId,@SourceId,@Actor,@PreviewDigest,@Reason,@Json,UTC_TIMESTAMP(6))
  105. """, new { batch.BatchId, batch.TenantId, batch.FactoryId, batch.DatasetId, batch.SourceId, actor, previewDigest, reason, json });
  106. token.ThrowIfCancellationRequested();
  107. return Result(json);
  108. });
  109. if (!tx.IsSuccess) throw tx.ErrorException ?? Unavailable();
  110. return tx.Data;
  111. }
  112. private void VerifyRecoveryReceipt(PurchaseHandoffPackage package, RecoveryReceipt receipt)
  113. {
  114. if (receipt.PackageVersion != package.PackageVersion
  115. || (receipt.PayloadSha256 != package.ComputeDigest()
  116. && !(receipt.DigestFormat == 1 && MatchesLegacyReceipt(package, receipt.PayloadSha256))))
  117. throw Error(409, "RAW_REPLAY_RECEIPT_MISMATCH");
  118. }
  119. private static async Task<List<RecoveryLine>> InspectRecoveryAsync(ISqlSugarClient db, PurchaseHandoffPackage package,
  120. RecoveryReceipt receipt, CancellationToken token)
  121. {
  122. var originals = ReceiptLines(receipt).ToDictionary(row => row.RawEventId);
  123. if (!package.Items.All(item => originals.ContainsKey(item.RawEventId)) || originals.Count != package.Items.Count)
  124. throw Error(409, "RAW_REPLAY_RECEIPT_MISMATCH");
  125. var result = new List<RecoveryLine>(package.Items.Count);
  126. foreach (var item in package.Items.OrderBy(row => row.PoNo, StringComparer.Ordinal)
  127. .ThenBy(row => row.PoLine, StringComparer.Ordinal).ThenBy(row => row.SourceChange?.Version))
  128. {
  129. token.ThrowIfCancellationRequested();
  130. var original = originals[item.RawEventId];
  131. if (original.Status is not ("WRITTEN" or "REUSED") || item.SourceChange is { Deleted: true })
  132. {
  133. result.Add(new(item, "EXCLUDED", null, null));
  134. continue;
  135. }
  136. var scope = new { package.TenantId, package.FactoryId, package.SourceId, package.DatasetId,
  137. package.SourceCode, item.PoNo, item.PoLine,
  138. ScopedKey = FormattableString.Invariant($"{package.TenantId}#{package.FactoryId}#{item.BusinessKey}") };
  139. var fields = new StageFields(item.PoNo, item.PoLine, item.ItemCode, item.SupplierCode, item.OrderQty,
  140. item.DueDate, item.OrderDate, item.Status, item.SourceUpdatedAt);
  141. var version = await db.Ado.SqlQuerySingleAsync<PurchaseLineVersion>("""
  142. SELECT source_id AS SourceId,dataset_id AS DatasetId,source_system AS SourceSystem,
  143. source_generation AS Generation,source_version AS Version,is_deleted AS Deleted,
  144. content_sha256 AS Digest,standard_id AS StandardId,stage_id AS StageId
  145. FROM mdp_std_purchase_order_version
  146. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND po_no=@PoNo AND po_line=@PoLine FOR UPDATE
  147. """, scope);
  148. if (item.SourceChange is { } change)
  149. {
  150. var expected = VersionedDigest(fields, false, package.PackageVersion == PurchaseHandoffPackage.ApiChangeVersion);
  151. if (version is null || version.SourceId != package.SourceId || version.DatasetId != package.DatasetId
  152. || version.SourceSystem != package.SourceCode || version.Deleted || version.Generation != change.Generation
  153. || version.Version != change.Version || version.Digest != expected)
  154. {
  155. result.Add(new(item, "VERSION_CHANGED", null, null));
  156. continue;
  157. }
  158. }
  159. else if (version is not null)
  160. {
  161. result.Add(new(item, "VERSION_CHANGED", null, null));
  162. continue;
  163. }
  164. var standard = await db.Ado.SqlQueryAsync<StandardRow>("""
  165. SELECT id AS Id,factory_id AS FactoryId,source_system AS SourceSystem,source_biz_key AS SourceBizKey,
  166. po_no AS PoNo,po_line AS PoLine,item_code AS ItemCode,supplier_code AS SupplierCode,
  167. order_qty AS OrderQty,due_date AS DueDate,order_date AS OrderDate,status AS Status
  168. FROM mdp_std_purchase_order
  169. WHERE tenant_id=@TenantId AND (((factory_id=@FactoryId OR factory_id IS NULL OR factory_id=0)
  170. AND po_no=@PoNo AND po_line=@PoLine)
  171. OR (source_system=@SourceCode AND source_biz_key=@ScopedKey)) FOR UPDATE
  172. """, scope);
  173. var stage = await db.Ado.SqlQuerySingleAsync<StageRow>("""
  174. SELECT id AS Id,tenant_id AS TenantId,factory_id AS FactoryId,source_system AS SourceSystem,
  175. source_biz_key AS SourceBizKey,raw_data AS RawData
  176. FROM mdp_stg_purchase_order
  177. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND source_system=@SourceCode
  178. AND source_table='S3_PURCHASE_ORDER' AND source_biz_key=@ScopedKey FOR UPDATE
  179. """, scope);
  180. var currentStandard = standard.FirstOrDefault();
  181. var conflict = standard.Count > 1 || currentStandard is not null && !currentStandard.Matches(package, item, scope.ScopedKey)
  182. || stage is not null && !stage.Matches(package, scope.ScopedKey, fields)
  183. || version?.StandardId is long expectedStandard && currentStandard is not null && expectedStandard != currentStandard.Id
  184. || version?.StageId is long expectedStage && stage is not null && expectedStage != stage.Id;
  185. var status = conflict ? "CONFLICT" : stage is null && currentStandard is null ? "MISSING_BOTH"
  186. : stage is null ? "MISSING_STAGE" : currentStandard is null ? "MISSING_STANDARD" : "COMPLETE";
  187. result.Add(new(item, status, stage?.Id, currentStandard?.Id));
  188. }
  189. return result;
  190. }
  191. private static Task<long> RecoveryRevisionAsync(ISqlSugarClient db, StoredIngestBatch batch) =>
  192. db.Ado.GetLongAsync("""
  193. SELECT COALESCE(MAX(id),0) FROM mdp_ingest_purchase_recovery
  194. WHERE batch_id=@BatchId AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId
  195. """, batch.SqlArguments);
  196. private static PurchaseRecoveryPreview Preview(PurchaseHandoffPackage package, List<RecoveryLine> rows, long revision)
  197. {
  198. var lines = rows.Select(row => ToTrace(new(row.Item.RawEventId, row.Status, row.StageId, row.StandardId))).ToList();
  199. var digest = Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new
  200. {
  201. Package = package.ComputeDigest(), Revision = revision, Lines = lines
  202. }, WireJson))).ToLowerInvariant();
  203. return new(digest, rows.Any(row => row.NeedsRestore) && rows.All(row => row.Status is not ("CONFLICT" or "VERSION_CHANGED")), lines);
  204. }
  205. private static List<LineResult> ReceiptLines(RecoveryReceipt row) =>
  206. JsonSerializer.Deserialize<List<LineResult>>(row.LineResults, WireJson) ?? throw Unavailable();
  207. private static PurchaseRecoveryResult Result(string json) => new(
  208. (JsonSerializer.Deserialize<List<LineResult>>(json, WireJson) ?? throw Unavailable()).Select(ToTrace).ToList());
  209. private static PurchaseLineTrace ToTrace(LineResult row) => new(row.RawEventId, row.Status,
  210. row.StageId?.ToString(CultureInfo.InvariantCulture), row.StandardId?.ToString(CultureInfo.InvariantCulture));
  211. private static DateTime Utc(DateTime value) => DateTime.SpecifyKind(value, DateTimeKind.Utc);
  212. private sealed record RecoveryLine(PurchaseHandoffLine Item, string Status, long? StageId, long? StandardId)
  213. {
  214. public bool NeedsRestore => Status is "MISSING_BOTH" or "MISSING_STAGE" or "MISSING_STANDARD";
  215. }
  216. private sealed class RecoveryReceipt
  217. {
  218. public string PayloadSha256 { get; set; } = "";
  219. public int DigestFormat { get; set; }
  220. public string LineResults { get; set; } = "";
  221. public string PackageVersion { get; set; } = "";
  222. public DateTime CreatedAt { get; set; }
  223. }
  224. private sealed class RecoveryAudit
  225. {
  226. public string Actor { get; set; } = "";
  227. public string Reason { get; set; } = "";
  228. public string LineResults { get; set; } = "";
  229. public DateTime CreatedAt { get; set; }
  230. }
  231. }
  232. internal sealed record PurchaseLineTrace(Guid RawEventId, string Status, string? StageId, string? StandardId);
  233. internal sealed record PurchaseTrace(string PackageVersion, string Digest, DateTime CreatedAt, List<PurchaseLineTrace> Lines, List<PurchaseRecoveryTrace> Recoveries);
  234. internal sealed record PurchaseRecoveryTrace(string Actor, string Reason, DateTime CreatedAt, List<PurchaseLineTrace> Lines);
  235. internal sealed record PurchaseRecoveryPreview(string Digest, bool CanRestore, List<PurchaseLineTrace> Lines);
  236. internal sealed record PurchaseRecoveryResult(List<PurchaseLineTrace> Restored);