MdpPurchaseHandoffService.cs 19 KB

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