MdpIngestReceiveService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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 System.Security.Cryptography;
  7. using System.Text;
  8. using System.Text.Json;
  9. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  10. public sealed class MdpIngestReceiveService(ISqlSugarClient db, ILogger<MdpIngestReceiveService> logger) : ITransient
  11. {
  12. private const string Accepted = "accepted";
  13. private static readonly TimeSpan ReplayDuration = TimeSpan.FromDays(7);
  14. private static readonly JsonSerializerOptions SnapshotOptions = new(JsonSerializerDefaults.Web);
  15. public async Task<MdpIngestReceipt> ReceiveAsync(MdpIngestSubmission submission, CancellationToken cancellationToken)
  16. {
  17. cancellationToken.ThrowIfCancellationRequested();
  18. try
  19. {
  20. using var transactionDb = MdpIngestDatabase.Open(db);
  21. transactionDb.Ado.CancellationToken = cancellationToken;
  22. var transaction = await transactionDb.Ado.UseTranAsync(() =>
  23. ReceiveInTransactionAsync(transactionDb, submission, cancellationToken));
  24. if (transaction.IsSuccess)
  25. return transaction.Data;
  26. if (transaction.ErrorException is not null)
  27. ExceptionDispatchInfo.Throw(transaction.ErrorException);
  28. throw IngestUnavailable();
  29. }
  30. catch (Exception error) when (error is DbException or SqlSugarException)
  31. {
  32. cancellationToken.ThrowIfCancellationRequested();
  33. logger.LogWarning("通用接收事务未确认提交,数据库异常类型为 {ErrorType}", error.GetType().Name);
  34. throw IngestUnavailable();
  35. }
  36. }
  37. private static async Task<MdpIngestReceipt> ReceiveInTransactionAsync(
  38. ISqlSugarClient db, MdpIngestSubmission submission, CancellationToken cancellationToken)
  39. {
  40. var datasetKey = submission.DatasetKey.Trim().ToLowerInvariant();
  41. var idempotencyKey = Encoding.ASCII.GetBytes(submission.IdempotencyKey);
  42. var scope = new { submission.TenantId, submission.FactoryId, submission.SourceId, DatasetKey = datasetKey };
  43. var configurationFactory = submission.ConfigurationFactoryId ?? submission.FactoryId;
  44. var factory = await db.Ado.SqlQuerySingleAsync<long?>("""
  45. SELECT factory_id FROM mdp_purchase_active_factory WHERE tenant_id=@TenantId AND factory_id=@FactoryId FOR SHARE
  46. """, new { scope.TenantId, scope.FactoryId });
  47. if (factory != submission.FactoryId)
  48. throw new MdpIngestHttpException(StatusCodes.Status403Forbidden, "FACTORY_UNAVAILABLE");
  49. // 管理端切换数据集版本或来源绑定时先更新同一行。
  50. var datasetId = await db.Ado.SqlQuerySingleAsync<long?>(
  51. """
  52. SELECT id FROM mdp_ingest_dataset
  53. WHERE tenant_id = @TenantId AND factory_id = @ConfigurationFactory AND dataset_key = @DatasetKey AND enabled = 1
  54. FOR UPDATE
  55. """, new { scope.TenantId, ConfigurationFactory = configurationFactory, scope.DatasetKey });
  56. if (datasetId is null or <= 0)
  57. throw new IngestContractException(IngestContractError.DatasetUnavailable);
  58. var grantId = await db.Ado.SqlQuerySingleAsync<long?>(
  59. """
  60. SELECT id FROM mdp_ingest_access_grant
  61. WHERE id = @GrantId AND tenant_id = @TenantId AND factory_id = @ConfigurationFactory AND use_batch_factory = @FromBatch
  62. AND source_id = @SourceId AND dataset_key = @DatasetKey
  63. AND access_key_hash = @AccessKeyHash AND enabled = 1
  64. FOR UPDATE
  65. """, new { submission.GrantId, submission.AccessKeyHash, scope.TenantId, ConfigurationFactory = configurationFactory, FromBatch = submission.ConfigurationFactoryId.HasValue, scope.SourceId, scope.DatasetKey });
  66. if (grantId is null or <= 0)
  67. throw new IngestContractException(IngestContractError.DatasetUnavailable);
  68. var sourceId = await db.Ado.SqlQuerySingleAsync<long?>(
  69. """
  70. SELECT id FROM mdp_source
  71. WHERE id = @SourceId AND tenant_id = @TenantId AND status = 1
  72. FOR UPDATE
  73. """, new { scope.SourceId, scope.TenantId });
  74. if (sourceId is null or <= 0)
  75. throw new IngestContractException(IngestContractError.DatasetUnavailable);
  76. cancellationToken.ThrowIfCancellationRequested();
  77. var previous = await db.Ado.SqlQuerySingleAsync<StoredReceipt>(
  78. """
  79. SELECT batch_id AS BatchId, payload_sha256 AS PayloadSha256, accepted_record_count AS AcceptedRecordCount,
  80. source_schema_version AS SchemaVersion, received_at AS ReceivedAt
  81. FROM mdp_ingest_raw_batch
  82. WHERE tenant_id = @TenantId AND factory_id = @FactoryId AND source_id = @SourceId
  83. AND dataset_id = @DatasetId AND idempotency_key = @IdempotencyKey
  84. """, new { scope.TenantId, scope.FactoryId, scope.SourceId, DatasetId = datasetId.Value, IdempotencyKey = idempotencyKey });
  85. var registry = new MdpIngestDatasetRegistry(db);
  86. if (previous is not null)
  87. {
  88. var currentBinding = await registry.ResolveActiveBindingAsync(scope.TenantId, configurationFactory, scope.SourceId, datasetKey);
  89. if (currentBinding is null)
  90. throw new IngestContractException(IngestContractError.DatasetUnavailable);
  91. cancellationToken.ThrowIfCancellationRequested();
  92. return Replay(previous, submission.Payload);
  93. }
  94. var migration = await MdpPurchaseMigrationStore.LockNewAsync(
  95. db, scope.TenantId, scope.FactoryId, datasetId.Value, scope.SourceId);
  96. MdpPurchaseMigrationStore.RequireAdmission(migration, MdpPurchaseMigrationStore.Unified);
  97. var reservation = new
  98. {
  99. scope.TenantId, scope.FactoryId, scope.SourceId, DatasetId = datasetId.Value,
  100. KeySha256 = Convert.ToHexString(SHA256.HashData(idempotencyKey)).ToLowerInvariant()
  101. };
  102. // A key stays reserved even when its Raw body and receipt have reached their retention limit.
  103. var reserved = await db.Ado.GetIntAsync(
  104. """
  105. SELECT COUNT(*) FROM mdp_ingest_idempotency_reservation
  106. WHERE tenant_id = @TenantId AND factory_id = @FactoryId AND source_id = @SourceId
  107. AND dataset_id = @DatasetId AND key_sha256 = @KeySha256
  108. """, reservation);
  109. if (reserved != 0)
  110. throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "IDEMPOTENCY_EXPIRED");
  111. var binder = new MdpIngestContractBinder(registry);
  112. var prepared = await binder.PrepareAsync(scope.TenantId, scope.FactoryId, scope.SourceId, datasetKey,
  113. submission.Payload, MdpIngestProtocol.Limits, configurationFactory);
  114. var batch = prepared.Batch;
  115. var receivedAt = new DateTimeOffset(batch.ReceivedAt.UtcTicks / 10 * 10, TimeSpan.Zero);
  116. var batchId = batch.BatchId.ToString("D");
  117. cancellationToken.ThrowIfCancellationRequested();
  118. await db.Ado.ExecuteCommandAsync(
  119. """
  120. INSERT INTO mdp_ingest_idempotency_reservation
  121. (tenant_id, factory_id, source_id, dataset_id, key_sha256, first_received_at)
  122. VALUES (@TenantId, @FactoryId, @SourceId, @DatasetId, @KeySha256, @ReceivedAt)
  123. """, new
  124. {
  125. reservation.TenantId, reservation.FactoryId, reservation.SourceId, reservation.DatasetId,
  126. reservation.KeySha256, ReceivedAt = receivedAt.UtcDateTime
  127. });
  128. await PersistRawAsync(db, batch, prepared.Events, submission.Payload, idempotencyKey, receivedAt, cancellationToken);
  129. // 发布与接收都锁定同一数据集行;同版本重新发布后也能追溯本批当时的发布记录。
  130. await db.Ado.ExecuteCommandAsync("""
  131. INSERT INTO mdp_ingest_release_batch (batch_id, release_id, tenant_id, dataset_id, source_id, factory_id)
  132. SELECT @BatchId, p.release_id, p.tenant_id, p.dataset_id, p.source_id, @ActualFactory
  133. FROM mdp_ingest_published_source p
  134. WHERE p.tenant_id=@TenantId AND p.factory_id=@ConfigurationFactory AND p.dataset_id=@DatasetId
  135. AND p.source_id=@SourceId AND p.schema_version=@Version
  136. """, new { BatchId = batchId, scope.TenantId, ConfigurationFactory = configurationFactory,
  137. DatasetId = datasetId.Value, scope.SourceId, Version = batch.Versions.SourceSchema.Version,
  138. ActualFactory = scope.FactoryId });
  139. cancellationToken.ThrowIfCancellationRequested();
  140. await db.Ado.ExecuteCommandAsync(
  141. """
  142. INSERT INTO mdp_ingest_receive_task (batch_id, tenant_id, factory_id, source_id, dataset_id, status, created_at)
  143. VALUES (@BatchId, @TenantId, @FactoryId, @SourceId, @DatasetId, 'PENDING', @CreatedAt)
  144. """, new
  145. {
  146. BatchId = batchId,
  147. batch.Identity.TenantId,
  148. batch.Identity.FactoryId,
  149. batch.Identity.SourceId,
  150. batch.Identity.DatasetId,
  151. CreatedAt = receivedAt.UtcDateTime
  152. });
  153. cancellationToken.ThrowIfCancellationRequested();
  154. return new MdpIngestReceipt(batch.BatchId, Accepted, batch.AcceptedRowCount, batch.Versions.SourceSchema.Version, receivedAt);
  155. }
  156. internal static async Task PersistRawAsync(ISqlSugarClient db, RawIngestBatch batch,
  157. IReadOnlyList<RawIngestEvent> events, byte[] payload, byte[] idempotencyKey, DateTimeOffset receivedAt, CancellationToken token)
  158. {
  159. token.ThrowIfCancellationRequested();
  160. var batchId = batch.BatchId.ToString("D");
  161. await db.Ado.ExecuteCommandAsync(
  162. """
  163. INSERT INTO mdp_ingest_raw_batch
  164. (batch_id, tenant_id, factory_id, source_id, dataset_id, source_code, dataset_key, idempotency_key,
  165. payload, payload_sha256, accepted_record_count, source_schema_version, version_snapshot, source_window, received_at)
  166. VALUES (@BatchId, @TenantId, @FactoryId, @SourceId, @DatasetId, @SourceCode, @DatasetKey, @IdempotencyKey,
  167. @Payload, @PayloadSha256, @AcceptedRecordCount, @SchemaVersion, @VersionSnapshot, @SourceWindow, @ReceivedAt)
  168. """, new
  169. {
  170. BatchId = batchId,
  171. batch.Identity.TenantId,
  172. batch.Identity.FactoryId,
  173. batch.Identity.SourceId,
  174. batch.Identity.DatasetId,
  175. batch.Identity.SourceCode,
  176. batch.Identity.DatasetKey,
  177. IdempotencyKey = idempotencyKey,
  178. Payload = payload,
  179. batch.PayloadSha256,
  180. AcceptedRecordCount = batch.AcceptedRowCount,
  181. SchemaVersion = batch.Versions.SourceSchema.Version,
  182. VersionSnapshot = JsonSerializer.Serialize(batch.Versions, SnapshotOptions),
  183. SourceWindow = batch.SourceWindow is null ? null : JsonSerializer.Serialize(batch.SourceWindow, SnapshotOptions),
  184. ReceivedAt = receivedAt.UtcDateTime
  185. });
  186. token.ThrowIfCancellationRequested();
  187. await InsertEventsAsync(db, batchId, events);
  188. }
  189. private static Task<int> InsertEventsAsync(ISqlSugarClient db, string batchId, IReadOnlyList<RawIngestEvent> events)
  190. {
  191. const int parametersPerEvent = 9;
  192. var parameters = new List<SugarParameter>(1 + events.Count * parametersPerEvent) { new("@BatchId", batchId) };
  193. var values = new List<string>(events.Count);
  194. for (var index = 0; index < events.Count; index++)
  195. {
  196. var item = events[index];
  197. values.Add($"(@BatchId, @EventId{index}, @Ordinal{index}, @Object{index}, @Position{index}, @Offset{index}, @Length{index}, @Hash{index}, @BusinessKey{index}, @UpdatedAt{index})");
  198. parameters.Add(new($"@EventId{index}", item.RawEventId.ToString("D")));
  199. parameters.Add(new($"@Ordinal{index}", item.RecordOrdinal));
  200. parameters.Add(new($"@Object{index}", item.ObjectCode));
  201. parameters.Add(new($"@Position{index}", item.SourcePosition));
  202. parameters.Add(new($"@Offset{index}", item.PayloadOffset));
  203. parameters.Add(new($"@Length{index}", item.PayloadLength));
  204. parameters.Add(new($"@Hash{index}", item.PayloadSha256));
  205. parameters.Add(new($"@BusinessKey{index}", item.SourceBusinessKey));
  206. parameters.Add(new($"@UpdatedAt{index}", item.SourceUpdatedAt));
  207. }
  208. const string insert = """
  209. INSERT INTO mdp_ingest_raw_event
  210. (batch_id, raw_event_id, record_ordinal, object_code, source_position, payload_offset, payload_length,
  211. payload_sha256, source_business_key, source_updated_at) VALUES
  212. """;
  213. return db.Ado.ExecuteCommandAsync(insert + " " + string.Join(", ", values), parameters.ToArray());
  214. }
  215. private static MdpIngestReceipt Replay(StoredReceipt previous, byte[] payload)
  216. {
  217. var receivedAt = new DateTimeOffset(DateTime.SpecifyKind(previous.ReceivedAt, DateTimeKind.Utc));
  218. if (DateTimeOffset.UtcNow - receivedAt >= ReplayDuration)
  219. throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "IDEMPOTENCY_EXPIRED");
  220. var hash = Convert.ToHexString(SHA256.HashData(payload));
  221. if (!string.Equals(hash, previous.PayloadSha256, StringComparison.OrdinalIgnoreCase))
  222. throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "IDEMPOTENCY_CONFLICT");
  223. return new MdpIngestReceipt(Guid.Parse(previous.BatchId), Accepted, previous.AcceptedRecordCount, previous.SchemaVersion, receivedAt);
  224. }
  225. private static MdpIngestHttpException IngestUnavailable() =>
  226. new(StatusCodes.Status503ServiceUnavailable, "INGEST_UNAVAILABLE");
  227. private sealed class StoredReceipt
  228. {
  229. public string BatchId { get; set; } = string.Empty;
  230. public string PayloadSha256 { get; set; } = string.Empty;
  231. public int AcceptedRecordCount { get; set; }
  232. public string SchemaVersion { get; set; } = string.Empty;
  233. public DateTime ReceivedAt { get; set; }
  234. }
  235. }