MdpPurchaseHandoffService.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.Extensions.Logging;
  4. using System.Data.Common;
  5. using System.Runtime.ExceptionServices;
  6. using Microsoft.Extensions.Configuration;
  7. using Microsoft.Extensions.Options;
  8. using Microsoft.AspNetCore.Mvc;
  9. using System.Text.Json;
  10. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  11. /// <summary>接收核心已确认的采购首包,在同一事务中登记两层结果和交接回执。</summary>
  12. public sealed class MdpPurchaseHandoffService(
  13. IConfiguration settings, IOptions<MvcNewtonsoftJsonOptions> legacyJson, ILogger<MdpPurchaseHandoffService> logger) : ITransient
  14. {
  15. private static readonly JsonSerializerOptions WireJson = new(JsonSerializerDefaults.Web);
  16. private static readonly PurchaseOrderSchemaRegistry Schemas = new();
  17. public async Task<PurchaseHandoffReceipt> ReceiveAsync(PurchaseHandoffPackage package, CancellationToken token)
  18. {
  19. token.ThrowIfCancellationRequested();
  20. if (package.BatchId == Guid.Empty || package.LeaseToken != string.Empty)
  21. throw Error(StatusCodes.Status409Conflict, "LEASE_LOST");
  22. try
  23. {
  24. using var db = OpenBusinessDatabase();
  25. db.Ado.CancellationToken = token;
  26. var contract = Schemas.Find(package.DatasetKey, package.SourceSchemaVersion);
  27. if (contract == null)
  28. {
  29. var mapping = await db.Ado.SqlQuerySingleAsync<string>("""
  30. SELECT mapping_json FROM mdp_purchase_contract_version
  31. WHERE tenant_id=@TenantId AND dataset_id=@DatasetId AND schema_version=@SourceSchemaVersion
  32. AND dataset_key=@DatasetKey
  33. """, new { package.TenantId, package.FactoryId, package.DatasetId, package.DatasetKey, package.SourceSchemaVersion });
  34. if (mapping != null)
  35. contract = new PurchaseVersionConfiguration(package.DatasetKey, package.SourceSchemaVersion, mapping)
  36. .Find(package.DatasetKey, package.SourceSchemaVersion);
  37. }
  38. if (contract == null || package.Items == null || package.Items.Count > MdpIngestProtocol.Limits.MaxRecords
  39. || package.Items.Any(line => line == null)
  40. || contract.HandoffSchema.Stamp.Version != $"{package.PackageCode}@{package.PackageVersion}"
  41. || contract.MappingVersion != package.MappingVersion)
  42. throw Error(StatusCodes.Status400BadRequest, "HANDOFF_INVALID_PACKAGE");
  43. var tx = await db.Ado.UseTranAsync(() => ReceiveLockedAsync(db, package, token));
  44. if (tx.IsSuccess)
  45. return tx.Data;
  46. // Another delivery can win the unique receipt or order-row lock. The failed transaction
  47. // has rolled back, so a fresh read can return the winning receipt.
  48. if (tx.ErrorException is DbException { SqlState: "23000" or "40001" } or MySqlConnector.MySqlException { Number: 1062 or 1213 })
  49. {
  50. var committed = await ReadReceiptAsync(db, package.BatchId.ToString("D"));
  51. if (committed is not null)
  52. return VerifiedReceipt(package, committed);
  53. }
  54. if (tx.ErrorException is not null)
  55. ExceptionDispatchInfo.Throw(tx.ErrorException);
  56. throw Unavailable();
  57. }
  58. catch (Exception ex) when (ex is DbException or SqlSugarException)
  59. {
  60. token.ThrowIfCancellationRequested();
  61. logger.LogWarning("采购交接事务未确认提交,数据库异常类型为 {ErrorType}", ex.GetType().Name);
  62. throw Unavailable();
  63. }
  64. }
  65. private async Task<PurchaseHandoffReceipt> ReceiveLockedAsync(
  66. ISqlSugarClient db, PurchaseHandoffPackage package, CancellationToken token)
  67. {
  68. var batchId = package.BatchId.ToString("D");
  69. var digest = package.ComputeDigest();
  70. var prior = await ReadReceiptAsync(db, batchId);
  71. if (prior is not null)
  72. return VerifiedReceipt(package, prior);
  73. // Reserve the unique key before taking any order-row locks. Concurrent first deliveries
  74. // wait here and see the completed receipt after commit. A rollback removes the reservation.
  75. await db.Ado.ExecuteCommandAsync(
  76. """
  77. INSERT INTO mdp_ingest_handoff_receipt
  78. (batch_id, tenant_id, factory_id, source_id, dataset_id, package_code, package_version,
  79. payload_sha256, receipt_json, line_results, created_at, digest_format)
  80. VALUES (@BatchId, @TenantId, @FactoryId, @SourceId, @DatasetId, @PackageCode, @PackageVersion,
  81. @Digest, JSON_OBJECT(), JSON_ARRAY(), UTC_TIMESTAMP(6), 2)
  82. """, new
  83. {
  84. BatchId = batchId, package.TenantId, package.FactoryId, package.SourceId, package.DatasetId,
  85. package.PackageCode, package.PackageVersion, Digest = digest
  86. });
  87. var migration = await ValidateWriterAsync(db, package);
  88. var results = new List<LineResult>(package.Items.Count);
  89. // 标准表的同一租户订单行跨来源唯一,统一加锁顺序减小并发死锁概率。
  90. foreach (var line in package.Items.OrderBy(line => line.PoNo, StringComparer.Ordinal).ThenBy(line => line.PoLine, StringComparer.Ordinal))
  91. {
  92. token.ThrowIfCancellationRequested();
  93. var result = migration is null
  94. ? await WriteLineAsync(db, package, batchId, line)
  95. : await MdpPurchaseMigrationWriter.WriteAsync(db, migration, MdpPurchaseMigrationStore.Unified, line, batchId,
  96. line.RawEventId.ToString("D"));
  97. results.Add(new(line.RawEventId, result.Status, result.StageId, result.StandardId));
  98. }
  99. var conflicts = results.Where(result => result.Status == "CONFLICT")
  100. .Select(result => new PurchaseQuarantine(result.RawEventId, "businessKey", "TARGET_ORDER_CONFLICT")).ToArray();
  101. var receipt = new PurchaseHandoffReceipt(package.BatchId, results.Count - conflicts.Length, conflicts);
  102. await db.Ado.ExecuteCommandAsync(
  103. """
  104. UPDATE mdp_ingest_handoff_receipt SET receipt_json=@ReceiptJson, line_results=@LineResults
  105. WHERE batch_id=@BatchId
  106. """, new {
  107. BatchId = batchId, ReceiptJson = JsonSerializer.Serialize(receipt, WireJson),
  108. LineResults = JsonSerializer.Serialize(results, WireJson)
  109. });
  110. token.ThrowIfCancellationRequested();
  111. return receipt;
  112. }
  113. private static Task<StoredReceipt> ReadReceiptAsync(ISqlSugarClient db, string batchId) =>
  114. db.Ado.SqlQuerySingleAsync<StoredReceipt>(
  115. "SELECT digest_format AS DigestFormat, payload_sha256 AS PayloadSha256, receipt_json AS ReceiptJson FROM mdp_ingest_handoff_receipt WHERE batch_id=@BatchId",
  116. new { BatchId = batchId });
  117. private PurchaseHandoffReceipt VerifiedReceipt(PurchaseHandoffPackage package, StoredReceipt prior)
  118. {
  119. if (prior.PayloadSha256 != package.ComputeDigest() && !(prior.DigestFormat == 1 && MatchesLegacyReceipt(package, prior.PayloadSha256)))
  120. throw Error(StatusCodes.Status409Conflict, "HANDOFF_CONTENT_CONFLICT");
  121. return JsonSerializer.Deserialize<PurchaseHandoffReceipt>(prior.ReceiptJson, WireJson) ?? throw Unavailable();
  122. }
  123. private SqlSugarClient OpenBusinessDatabase()
  124. {
  125. var connection = settings["MDP_PURCHASE_RECEIVER_MYSQL"];
  126. if (string.IsNullOrWhiteSpace(connection))
  127. throw Unavailable();
  128. return new SqlSugarClient(new ConnectionConfig
  129. {
  130. DbType = SqlSugar.DbType.MySql, ConnectionString = connection, IsAutoCloseConnection = true
  131. });
  132. }
  133. private bool MatchesLegacyReceipt(PurchaseHandoffPackage package, string recorded)
  134. {
  135. // Version 1 receipts hashed the model produced by the host's Newtonsoft input formatter.
  136. var json = JsonSerializer.Serialize(package, WireJson);
  137. var legacyPackage = Newtonsoft.Json.JsonConvert.DeserializeObject<PurchaseHandoffPackage>(json, legacyJson.Value.SerializerSettings);
  138. return legacyPackage?.ComputeDigest() == recorded;
  139. }
  140. public async Task<PurchaseHandoffReceipt?> FindReceiptAsync(Guid batch, string digest, CancellationToken token)
  141. {
  142. using var db = OpenBusinessDatabase();
  143. db.Ado.CancellationToken = token;
  144. var prior = await ReadReceiptAsync(db, batch.ToString("D"));
  145. if (prior is null) return null;
  146. if (prior.PayloadSha256 != digest && prior.DigestFormat == 1)
  147. throw Error(StatusCodes.Status412PreconditionFailed, "HANDOFF_LEGACY_COMPARE");
  148. if (prior.PayloadSha256 != digest)
  149. throw Error(StatusCodes.Status409Conflict, "HANDOFF_CONTENT_CONFLICT");
  150. return JsonSerializer.Deserialize<PurchaseHandoffReceipt>(prior.ReceiptJson, WireJson);
  151. }
  152. private static async Task<PurchaseMigrationScope?> ValidateWriterAsync(ISqlSugarClient db, PurchaseHandoffPackage package)
  153. {
  154. var sourceCode = package.SourceCode;
  155. var migration = await MdpPurchaseMigrationStore.LockNewAsync(
  156. db, package.TenantId, package.FactoryId, package.DatasetId, package.SourceId, confirmedDelivery: true);
  157. if (migration is null)
  158. {
  159. var authority = await new MdpTenantStdSourceResolver(db).GetSourceForShareAsync(package.TenantId, "PURCHASE");
  160. if (!string.Equals(authority?.SourceSystem, sourceCode, StringComparison.OrdinalIgnoreCase))
  161. throw Error(StatusCodes.Status403Forbidden, "HANDOFF_SOURCE_NOT_AUTHORIZED");
  162. }
  163. else if (migration.NewSourceCode != sourceCode)
  164. throw Error(StatusCodes.Status403Forbidden, "HANDOFF_SOURCE_NOT_AUTHORIZED");
  165. MdpPurchaseMigrationStore.RequireWriter(migration, MdpPurchaseMigrationStore.Unified);
  166. var factory = await db.Ado.SqlQuerySingleAsync<long?>(
  167. "SELECT factory_id FROM mdp_purchase_active_factory WHERE tenant_id=@TenantId AND factory_id=@FactoryId FOR SHARE",
  168. new { package.TenantId, package.FactoryId });
  169. if (factory is null)
  170. throw Error(StatusCodes.Status403Forbidden, "HANDOFF_SCOPE_MISMATCH");
  171. return migration;
  172. }
  173. internal static async Task<PurchaseMigrationLineResult> WriteLineAsync(
  174. ISqlSugarClient db, PurchaseHandoffPackage package, string batchId, PurchaseHandoffLine line,
  175. string? sourceBizKey = null, string? sourceRowId = null)
  176. {
  177. var scopedKey = sourceBizKey ?? FormattableString.Invariant($"{package.TenantId}#{package.FactoryId}#{line.BusinessKey}");
  178. var args = new
  179. {
  180. BatchId = batchId, package.TenantId, package.FactoryId, SourceSystem = package.SourceCode,
  181. SourceBizKey = scopedKey, RawEventId = sourceRowId ?? line.RawEventId.ToString("D"), line.PoNo, line.PoLine,
  182. line.ItemCode, line.SupplierCode, line.OrderQty, line.DueDate, line.OrderDate, line.Status
  183. };
  184. var standards = await db.Ado.SqlQueryAsync<StandardRow>(
  185. """
  186. SELECT id AS Id, factory_id AS FactoryId, source_system AS SourceSystem, source_biz_key AS SourceBizKey,
  187. po_no AS PoNo, po_line AS PoLine, item_code AS ItemCode, supplier_code AS SupplierCode,
  188. order_qty AS OrderQty, due_date AS DueDate, order_date AS OrderDate, status AS Status
  189. FROM mdp_std_purchase_order
  190. WHERE tenant_id = @TenantId AND (((factory_id = @FactoryId OR factory_id IS NULL OR factory_id = 0)
  191. AND po_no = @PoNo AND po_line = @PoLine)
  192. OR (source_system = @SourceSystem AND source_biz_key = @SourceBizKey))
  193. FOR UPDATE
  194. """, args);
  195. var standard = standards.Count == 1 ? standards[0] : null;
  196. if (standards.Count > 1 || (standard is not null && !standard.Matches(package, line, scopedKey)))
  197. return new("CONFLICT", null, null);
  198. var stage = await db.Ado.SqlQuerySingleAsync<StageRow>(
  199. """
  200. SELECT id AS Id, tenant_id AS TenantId, factory_id AS FactoryId, source_system AS SourceSystem,
  201. source_biz_key AS SourceBizKey, raw_data AS RawData
  202. FROM mdp_stg_purchase_order
  203. WHERE source_system = @SourceSystem AND source_table = 'S3_PURCHASE_ORDER' AND source_biz_key = @SourceBizKey
  204. FOR SHARE
  205. """, args);
  206. var stageFields = new StageFields(line.PoNo, line.PoLine, line.ItemCode, line.SupplierCode,
  207. line.OrderQty, line.DueDate, line.OrderDate, line.Status, line.SourceUpdatedAt);
  208. if (stage is not null && !stage.Matches(package, scopedKey, stageFields))
  209. return new("CONFLICT", null, null);
  210. var reused = stage is not null && standard is not null;
  211. var standardId = standard?.Id ?? await InsertStandardAsync(db, package.TenantId, package.FactoryId,
  212. package.SourceCode, scopedKey, batchId, line);
  213. if (standardId is null)
  214. return new("CONFLICT", null, null);
  215. var stageId = stage?.Id;
  216. if (stageId is null)
  217. {
  218. await db.Ado.ExecuteCommandAsync(
  219. """
  220. INSERT INTO mdp_stg_purchase_order
  221. (tenant_id, factory_id, source_system, source_table, source_row_id, source_biz_key,
  222. raw_data, sync_batch_id, sync_time, process_status)
  223. VALUES (@TenantId, @FactoryId, @SourceSystem, 'S3_PURCHASE_ORDER', @RawEventId, @SourceBizKey,
  224. @RawData, @BatchId, UTC_TIMESTAMP(), 'DONE')
  225. """, new
  226. {
  227. args.TenantId, args.FactoryId, args.SourceSystem, args.RawEventId, args.SourceBizKey, args.BatchId,
  228. RawData = JsonSerializer.Serialize(stageFields)
  229. });
  230. stageId = await db.Ado.GetLongAsync("SELECT LAST_INSERT_ID()");
  231. }
  232. return new(reused ? "REUSED" : "WRITTEN", stageId, standardId);
  233. }
  234. internal static async Task<long?> InsertStandardAsync(ISqlSugarClient db, long tenantId, long factoryId,
  235. string sourceSystem, string sourceBizKey, string batchId, PurchaseHandoffLine line)
  236. {
  237. try
  238. {
  239. await db.Ado.ExecuteCommandAsync(
  240. """
  241. INSERT INTO mdp_std_purchase_order
  242. (tenant_id, factory_id, source_system, po_no, po_line, item_code, supplier_code, order_qty,
  243. due_date, order_date, status, source_biz_key, sync_batch_id, sync_time)
  244. VALUES (@TenantId, @FactoryId, @SourceSystem, @PoNo, @PoLine, @ItemCode, @SupplierCode, @OrderQty,
  245. @DueDate, @OrderDate, @Status, @SourceBizKey, @BatchId, UTC_TIMESTAMP())
  246. """, new { TenantId = tenantId, FactoryId = factoryId, SourceSystem = sourceSystem, SourceBizKey = sourceBizKey,
  247. BatchId = batchId, line.PoNo, line.PoLine, line.ItemCode, line.SupplierCode, line.OrderQty,
  248. line.DueDate, line.OrderDate, line.Status });
  249. }
  250. catch (MySqlConnector.MySqlException error) when (error.Number == 1062
  251. && error.Message.Contains("uk_po_line", StringComparison.OrdinalIgnoreCase))
  252. {
  253. // 旧三列索引仍在线时,同号的其他工厂继续逐行隔离,不留下半条贴源记录。
  254. var foreignOrder = await db.Ado.GetIntAsync(
  255. """
  256. SELECT IF(COUNT(*)>0 AND SUM(factory_id <=> @FactoryId)=0,1,0) FROM mdp_std_purchase_order
  257. WHERE tenant_id=@TenantId AND po_no=@PoNo AND po_line=@PoLine FOR UPDATE
  258. """, new { TenantId = tenantId, FactoryId = factoryId, line.PoNo, line.PoLine });
  259. if (foreignOrder > 0)
  260. return null;
  261. throw;
  262. }
  263. return await db.Ado.GetLongAsync("SELECT LAST_INSERT_ID()");
  264. }
  265. private static MdpIngestHttpException Unavailable() =>
  266. Error(StatusCodes.Status503ServiceUnavailable, "HANDOFF_UNAVAILABLE");
  267. private static MdpIngestHttpException Error(int status, string code) => new(status, code);
  268. private sealed class StoredReceipt
  269. {
  270. public int DigestFormat { get; set; }
  271. public string PayloadSha256 { get; set; } = string.Empty;
  272. public string ReceiptJson { get; set; } = string.Empty;
  273. }
  274. private sealed record LineResult(Guid RawEventId, string Status, long? StageId, long? StandardId);
  275. private sealed record StageFields(
  276. string PoNo, string PoLine, string ItemCode, string? SupplierCode, decimal OrderQty,
  277. DateTime? DueDate, DateTime? OrderDate, string? Status,
  278. [property: System.Text.Json.Serialization.JsonPropertyName("sourceUpdatedAt")] string SourceUpdatedAt);
  279. private sealed class StageRow
  280. {
  281. public long Id { get; set; }
  282. public long? TenantId { get; set; }
  283. public long? FactoryId { get; set; }
  284. public string SourceSystem { get; set; } = string.Empty;
  285. public string SourceBizKey { get; set; } = string.Empty;
  286. public string? RawData { get; set; }
  287. public bool Matches(PurchaseHandoffPackage package, string key, StageFields fields)
  288. {
  289. if (TenantId != package.TenantId || FactoryId != package.FactoryId
  290. || SourceSystem != package.SourceCode || SourceBizKey != key || RawData is null)
  291. return false;
  292. try
  293. {
  294. return JsonSerializer.Deserialize<StageFields>(RawData, WireJson) == fields;
  295. }
  296. catch (JsonException)
  297. {
  298. return false;
  299. }
  300. }
  301. }
  302. private sealed class StandardRow
  303. {
  304. public long Id { get; set; }
  305. public long? FactoryId { get; set; }
  306. public string SourceSystem { get; set; } = string.Empty;
  307. public string SourceBizKey { get; set; } = string.Empty;
  308. public string PoNo { get; set; } = string.Empty;
  309. public string PoLine { get; set; } = string.Empty;
  310. public string ItemCode { get; set; } = string.Empty;
  311. public string? SupplierCode { get; set; }
  312. public decimal? OrderQty { get; set; }
  313. public DateTime? DueDate { get; set; }
  314. public DateTime? OrderDate { get; set; }
  315. public string? Status { get; set; }
  316. public bool Matches(PurchaseHandoffPackage package, PurchaseHandoffLine line, string key) =>
  317. FactoryId == package.FactoryId && SourceSystem == package.SourceCode && SourceBizKey == key
  318. && PoNo == line.PoNo && PoLine == line.PoLine && ItemCode == line.ItemCode && SupplierCode == line.SupplierCode
  319. && OrderQty == line.OrderQty && DueDate == line.DueDate && OrderDate == line.OrderDate && Status == line.Status;
  320. }
  321. }