MdpIngestReceiveService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. if (submission.IdempotencyKey.StartsWith("relational-sync-", StringComparison.Ordinal))
  116. {
  117. var frozen = await db.Ado.GetIntAsync("""
  118. SELECT COUNT(*) FROM mdp_connector_relational_sync_page p
  119. JOIN mdp_connector_relational_sync_run r ON r.run_id=p.run_id
  120. WHERE p.idem_key=@IdemKey AND p.payload_sha256=@PayloadSha256
  121. AND r.tenant_id=@TenantId AND r.factory_id=@FactoryId AND r.source_id=@SourceId
  122. AND r.dataset_id=@DatasetId AND r.schema_version=@SchemaVersion AND r.phase='RECEIVING'
  123. """, new { IdemKey = submission.IdempotencyKey, batch.PayloadSha256, scope.TenantId, scope.FactoryId,
  124. scope.SourceId, DatasetId = datasetId.Value, SchemaVersion = batch.Versions.SourceSchema.Version });
  125. if (frozen != 1) throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "RELATIONAL_FROZEN_PAGE_REQUIRED");
  126. var generation = await db.Ado.SqlQuerySingleAsync<long?>("""
  127. SELECT changes.source_generation FROM mdp_connector_relational_change_run changes
  128. JOIN mdp_connector_relational_sync_page p ON p.run_id=changes.run_id
  129. WHERE p.idem_key=@IdemKey
  130. """, new { IdemKey = submission.IdempotencyKey });
  131. batch = batch with { SourceWindow = new(null, null, IngestSourceWindow.VerifiedRelationalSnapshot)
  132. {
  133. SourceGeneration = generation,
  134. } };
  135. }
  136. var receivedAt = new DateTimeOffset(batch.ReceivedAt.UtcTicks / 10 * 10, TimeSpan.Zero);
  137. var batchId = batch.BatchId.ToString("D");
  138. cancellationToken.ThrowIfCancellationRequested();
  139. await db.Ado.ExecuteCommandAsync(
  140. """
  141. INSERT INTO mdp_ingest_idempotency_reservation
  142. (tenant_id, factory_id, source_id, dataset_id, key_sha256, first_received_at)
  143. VALUES (@TenantId, @FactoryId, @SourceId, @DatasetId, @KeySha256, @ReceivedAt)
  144. """, new
  145. {
  146. reservation.TenantId, reservation.FactoryId, reservation.SourceId, reservation.DatasetId,
  147. reservation.KeySha256, ReceivedAt = receivedAt.UtcDateTime
  148. });
  149. await PersistRawAsync(db, batch, prepared.Events, submission.Payload, idempotencyKey, receivedAt, cancellationToken);
  150. // 发布与接收都锁定同一数据集行;同版本重新发布后也能追溯本批当时的发布记录。
  151. await db.Ado.ExecuteCommandAsync("""
  152. INSERT INTO mdp_ingest_release_batch (batch_id, release_id, tenant_id, dataset_id, source_id, factory_id)
  153. SELECT @BatchId, p.release_id, p.tenant_id, p.dataset_id, p.source_id, @ActualFactory
  154. FROM mdp_ingest_published_source p
  155. WHERE p.tenant_id=@TenantId AND p.factory_id=@ConfigurationFactory AND p.dataset_id=@DatasetId
  156. AND p.source_id=@SourceId AND p.schema_version=@Version
  157. """, new { BatchId = batchId, scope.TenantId, ConfigurationFactory = configurationFactory,
  158. DatasetId = datasetId.Value, scope.SourceId, Version = batch.Versions.SourceSchema.Version,
  159. ActualFactory = scope.FactoryId });
  160. cancellationToken.ThrowIfCancellationRequested();
  161. await db.Ado.ExecuteCommandAsync(
  162. """
  163. INSERT INTO mdp_ingest_receive_task (batch_id, tenant_id, factory_id, source_id, dataset_id, status, created_at)
  164. VALUES (@BatchId, @TenantId, @FactoryId, @SourceId, @DatasetId, 'PENDING', @CreatedAt)
  165. """, new
  166. {
  167. BatchId = batchId,
  168. batch.Identity.TenantId,
  169. batch.Identity.FactoryId,
  170. batch.Identity.SourceId,
  171. batch.Identity.DatasetId,
  172. CreatedAt = receivedAt.UtcDateTime
  173. });
  174. cancellationToken.ThrowIfCancellationRequested();
  175. return new MdpIngestReceipt(batch.BatchId, Accepted, batch.AcceptedRowCount, batch.Versions.SourceSchema.Version, receivedAt);
  176. }
  177. internal static async Task PersistRawAsync(ISqlSugarClient db, RawIngestBatch batch,
  178. IReadOnlyList<RawIngestEvent> events, byte[] payload, byte[] idempotencyKey, DateTimeOffset receivedAt, CancellationToken token)
  179. {
  180. token.ThrowIfCancellationRequested();
  181. var batchId = batch.BatchId.ToString("D");
  182. await db.Ado.ExecuteCommandAsync(
  183. """
  184. INSERT INTO mdp_ingest_raw_batch
  185. (batch_id, tenant_id, factory_id, source_id, dataset_id, source_code, dataset_key, idempotency_key,
  186. payload, payload_sha256, accepted_record_count, source_schema_version, version_snapshot, source_window, received_at)
  187. VALUES (@BatchId, @TenantId, @FactoryId, @SourceId, @DatasetId, @SourceCode, @DatasetKey, @IdempotencyKey,
  188. @Payload, @PayloadSha256, @AcceptedRecordCount, @SchemaVersion, @VersionSnapshot, @SourceWindow, @ReceivedAt)
  189. """, new
  190. {
  191. BatchId = batchId,
  192. batch.Identity.TenantId,
  193. batch.Identity.FactoryId,
  194. batch.Identity.SourceId,
  195. batch.Identity.DatasetId,
  196. batch.Identity.SourceCode,
  197. batch.Identity.DatasetKey,
  198. IdempotencyKey = idempotencyKey,
  199. Payload = payload,
  200. batch.PayloadSha256,
  201. AcceptedRecordCount = batch.AcceptedRowCount,
  202. SchemaVersion = batch.Versions.SourceSchema.Version,
  203. VersionSnapshot = JsonSerializer.Serialize(batch.Versions, SnapshotOptions),
  204. SourceWindow = batch.SourceWindow is null ? null : JsonSerializer.Serialize(batch.SourceWindow, SnapshotOptions),
  205. ReceivedAt = receivedAt.UtcDateTime
  206. });
  207. token.ThrowIfCancellationRequested();
  208. await InsertEventsAsync(db, batchId, events);
  209. }
  210. private static Task<int> InsertEventsAsync(ISqlSugarClient db, string batchId, IReadOnlyList<RawIngestEvent> events)
  211. {
  212. const int parametersPerEvent = 9;
  213. var parameters = new List<SugarParameter>(1 + events.Count * parametersPerEvent) { new("@BatchId", batchId) };
  214. var values = new List<string>(events.Count);
  215. for (var index = 0; index < events.Count; index++)
  216. {
  217. var item = events[index];
  218. values.Add($"(@BatchId, @EventId{index}, @Ordinal{index}, @Object{index}, @Position{index}, @Offset{index}, @Length{index}, @Hash{index}, @BusinessKey{index}, @UpdatedAt{index})");
  219. parameters.Add(new($"@EventId{index}", item.RawEventId.ToString("D")));
  220. parameters.Add(new($"@Ordinal{index}", item.RecordOrdinal));
  221. parameters.Add(new($"@Object{index}", item.ObjectCode));
  222. parameters.Add(new($"@Position{index}", item.SourcePosition));
  223. parameters.Add(new($"@Offset{index}", item.PayloadOffset));
  224. parameters.Add(new($"@Length{index}", item.PayloadLength));
  225. parameters.Add(new($"@Hash{index}", item.PayloadSha256));
  226. parameters.Add(new($"@BusinessKey{index}", item.SourceBusinessKey));
  227. parameters.Add(new($"@UpdatedAt{index}", item.SourceUpdatedAt));
  228. }
  229. const string insert = """
  230. INSERT INTO mdp_ingest_raw_event
  231. (batch_id, raw_event_id, record_ordinal, object_code, source_position, payload_offset, payload_length,
  232. payload_sha256, source_business_key, source_updated_at) VALUES
  233. """;
  234. return db.Ado.ExecuteCommandAsync(insert + " " + string.Join(", ", values), parameters.ToArray());
  235. }
  236. private static MdpIngestReceipt Replay(StoredReceipt previous, byte[] payload)
  237. {
  238. var receivedAt = new DateTimeOffset(DateTime.SpecifyKind(previous.ReceivedAt, DateTimeKind.Utc));
  239. if (DateTimeOffset.UtcNow - receivedAt >= ReplayDuration)
  240. throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "IDEMPOTENCY_EXPIRED");
  241. var hash = Convert.ToHexString(SHA256.HashData(payload));
  242. if (!string.Equals(hash, previous.PayloadSha256, StringComparison.OrdinalIgnoreCase))
  243. throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "IDEMPOTENCY_CONFLICT");
  244. return new MdpIngestReceipt(Guid.Parse(previous.BatchId), Accepted, previous.AcceptedRecordCount, previous.SchemaVersion, receivedAt);
  245. }
  246. private static MdpIngestHttpException IngestUnavailable() =>
  247. new(StatusCodes.Status503ServiceUnavailable, "INGEST_UNAVAILABLE");
  248. private sealed class StoredReceipt
  249. {
  250. public string BatchId { get; set; } = string.Empty;
  251. public string PayloadSha256 { get; set; } = string.Empty;
  252. public int AcceptedRecordCount { get; set; }
  253. public string SchemaVersion { get; set; } = string.Empty;
  254. public DateTime ReceivedAt { get; set; }
  255. }
  256. }