MdpIngestReceiveService.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. (SELECT e.source_position FROM mdp_ingest_raw_event e
  82. WHERE e.batch_id = mdp_ingest_raw_batch.batch_id AND e.record_ordinal = 0) AS FirstPosition
  83. FROM mdp_ingest_raw_batch
  84. WHERE tenant_id = @TenantId AND factory_id = @FactoryId AND source_id = @SourceId
  85. AND dataset_id = @DatasetId AND idempotency_key = @IdempotencyKey
  86. """, new { scope.TenantId, scope.FactoryId, scope.SourceId, DatasetId = datasetId.Value, IdempotencyKey = idempotencyKey });
  87. var registry = new MdpIngestDatasetRegistry(db);
  88. if (previous is not null)
  89. {
  90. var currentBinding = await registry.ResolveActiveBindingAsync(scope.TenantId, configurationFactory, scope.SourceId, datasetKey);
  91. if (currentBinding is null)
  92. throw new IngestContractException(IngestContractError.DatasetUnavailable);
  93. cancellationToken.ThrowIfCancellationRequested();
  94. var previousIsNdjson = previous.FirstPosition?.StartsWith("/lines/", StringComparison.Ordinal) == true;
  95. if ((submission.Format == IngestPayloadFormat.Ndjson) != previousIsNdjson
  96. || submission.SchemaVersion is not null && submission.SchemaVersion != previous.SchemaVersion)
  97. throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "IDEMPOTENCY_CONFLICT");
  98. return Replay(previous, submission.Payload);
  99. }
  100. var migration = await MdpPurchaseMigrationStore.LockNewAsync(
  101. db, scope.TenantId, scope.FactoryId, datasetId.Value, scope.SourceId);
  102. MdpPurchaseMigrationStore.RequireAdmission(migration, MdpPurchaseMigrationStore.Unified);
  103. var reservation = new
  104. {
  105. scope.TenantId, scope.FactoryId, scope.SourceId, DatasetId = datasetId.Value,
  106. KeySha256 = Convert.ToHexString(SHA256.HashData(idempotencyKey)).ToLowerInvariant()
  107. };
  108. // A key stays reserved even when its Raw body and receipt have reached their retention limit.
  109. var reserved = await db.Ado.GetIntAsync(
  110. """
  111. SELECT COUNT(*) FROM mdp_ingest_idempotency_reservation
  112. WHERE tenant_id = @TenantId AND factory_id = @FactoryId AND source_id = @SourceId
  113. AND dataset_id = @DatasetId AND key_sha256 = @KeySha256
  114. """, reservation);
  115. if (reserved != 0)
  116. throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "IDEMPOTENCY_EXPIRED");
  117. var binder = new MdpIngestContractBinder(registry);
  118. var prepared = await binder.PrepareAsync(scope.TenantId, scope.FactoryId, scope.SourceId, datasetKey,
  119. submission.Payload, MdpIngestProtocol.Limits, configurationFactory, submission.Format, submission.SchemaVersion);
  120. if (submission.Format == IngestPayloadFormat.Ndjson && !MdpBatchFactory.RowsMatch(prepared))
  121. throw new MdpIngestHttpException(StatusCodes.Status400BadRequest, "INVALID_BATCH_SCOPE");
  122. var batch = prepared.Batch;
  123. if (submission.IdempotencyKey.StartsWith("relational-sync-", StringComparison.Ordinal))
  124. {
  125. var frozen = await db.Ado.GetIntAsync("""
  126. SELECT COUNT(*) FROM mdp_connector_relational_sync_page p
  127. JOIN mdp_connector_relational_sync_run r ON r.run_id=p.run_id
  128. WHERE p.idem_key=@IdemKey AND p.payload_sha256=@PayloadSha256
  129. AND r.tenant_id=@TenantId AND r.factory_id=@FactoryId AND r.source_id=@SourceId
  130. AND r.dataset_id=@DatasetId AND r.schema_version=@SchemaVersion AND r.phase='RECEIVING'
  131. """, new { IdemKey = submission.IdempotencyKey, batch.PayloadSha256, scope.TenantId, scope.FactoryId,
  132. scope.SourceId, DatasetId = datasetId.Value, SchemaVersion = batch.Versions.SourceSchema.Version });
  133. if (frozen != 1) throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "RELATIONAL_FROZEN_PAGE_REQUIRED");
  134. var generation = await db.Ado.SqlQuerySingleAsync<long?>("""
  135. SELECT changes.source_generation FROM mdp_connector_relational_change_run changes
  136. JOIN mdp_connector_relational_sync_page p ON p.run_id=changes.run_id
  137. WHERE p.idem_key=@IdemKey
  138. """, new { IdemKey = submission.IdempotencyKey });
  139. batch = batch with { SourceWindow = new(null, null, IngestSourceWindow.VerifiedRelationalSnapshot)
  140. {
  141. SourceGeneration = generation,
  142. } };
  143. }
  144. else if (submission.TrackPurchaseApiTime && prepared.Events[0].ObjectCode == "PURCHASE_ORDER")
  145. {
  146. batch = batch with { SourceWindow = new(null, null, IngestSourceWindow.PurchaseApiTime) };
  147. }
  148. return await PersistAcceptedBatchAsync(db, prepared with { Batch = batch }, idempotencyKey, configurationFactory, cancellationToken);
  149. }
  150. internal static async Task<MdpIngestReceipt> PersistAcceptedBatchAsync(ISqlSugarClient db, PreparedIngestBatch prepared,
  151. byte[] idempotencyKey, long configurationFactory, CancellationToken cancellationToken)
  152. {
  153. var batch = prepared.Batch;
  154. var scope = batch.Identity;
  155. var receivedAt = new DateTimeOffset(batch.ReceivedAt.UtcTicks / 10 * 10, TimeSpan.Zero);
  156. var batchId = batch.BatchId.ToString("D");
  157. cancellationToken.ThrowIfCancellationRequested();
  158. await db.Ado.ExecuteCommandAsync(
  159. """
  160. INSERT INTO mdp_ingest_idempotency_reservation
  161. (tenant_id, factory_id, source_id, dataset_id, key_sha256, first_received_at)
  162. VALUES (@TenantId, @FactoryId, @SourceId, @DatasetId, @KeySha256, @ReceivedAt)
  163. """, new
  164. {
  165. scope.TenantId, scope.FactoryId, scope.SourceId, scope.DatasetId,
  166. KeySha256 = Convert.ToHexString(SHA256.HashData(idempotencyKey)).ToLowerInvariant(), ReceivedAt = receivedAt.UtcDateTime
  167. });
  168. await PersistRawAsync(db, batch, prepared.Events, batch.Payload.ToArray(), idempotencyKey, receivedAt, cancellationToken);
  169. // 发布与接收都锁定同一数据集行;同版本重新发布后也能追溯本批当时的发布记录。
  170. await db.Ado.ExecuteCommandAsync("""
  171. INSERT INTO mdp_ingest_release_batch (batch_id, release_id, tenant_id, dataset_id, source_id, factory_id)
  172. SELECT @BatchId, p.release_id, p.tenant_id, p.dataset_id, p.source_id, @ActualFactory
  173. FROM mdp_ingest_published_source p
  174. WHERE p.tenant_id=@TenantId AND p.factory_id=@ConfigurationFactory AND p.dataset_id=@DatasetId
  175. AND p.source_id=@SourceId AND p.schema_version=@Version
  176. """, new { BatchId = batchId, scope.TenantId, ConfigurationFactory = configurationFactory,
  177. scope.DatasetId, scope.SourceId, Version = batch.Versions.SourceSchema.Version,
  178. ActualFactory = scope.FactoryId });
  179. cancellationToken.ThrowIfCancellationRequested();
  180. await db.Ado.ExecuteCommandAsync(
  181. """
  182. INSERT INTO mdp_ingest_receive_task (batch_id, tenant_id, factory_id, source_id, dataset_id, status, created_at)
  183. VALUES (@BatchId, @TenantId, @FactoryId, @SourceId, @DatasetId, 'PENDING', @CreatedAt)
  184. """, new
  185. {
  186. BatchId = batchId,
  187. batch.Identity.TenantId,
  188. batch.Identity.FactoryId,
  189. batch.Identity.SourceId,
  190. batch.Identity.DatasetId,
  191. CreatedAt = receivedAt.UtcDateTime
  192. });
  193. cancellationToken.ThrowIfCancellationRequested();
  194. return new MdpIngestReceipt(batch.BatchId, Accepted, batch.AcceptedRowCount, batch.Versions.SourceSchema.Version, receivedAt);
  195. }
  196. internal static async Task PersistRawAsync(ISqlSugarClient db, RawIngestBatch batch,
  197. IReadOnlyList<RawIngestEvent> events, byte[] payload, byte[] idempotencyKey, DateTimeOffset receivedAt, CancellationToken token)
  198. {
  199. token.ThrowIfCancellationRequested();
  200. var batchId = batch.BatchId.ToString("D");
  201. await db.Ado.ExecuteCommandAsync(
  202. """
  203. INSERT INTO mdp_ingest_raw_batch
  204. (batch_id, tenant_id, factory_id, source_id, dataset_id, source_code, dataset_key, idempotency_key,
  205. payload, payload_sha256, accepted_record_count, source_schema_version, version_snapshot, source_window, received_at)
  206. VALUES (@BatchId, @TenantId, @FactoryId, @SourceId, @DatasetId, @SourceCode, @DatasetKey, @IdempotencyKey,
  207. @Payload, @PayloadSha256, @AcceptedRecordCount, @SchemaVersion, @VersionSnapshot, @SourceWindow, @ReceivedAt)
  208. """, new
  209. {
  210. BatchId = batchId,
  211. batch.Identity.TenantId,
  212. batch.Identity.FactoryId,
  213. batch.Identity.SourceId,
  214. batch.Identity.DatasetId,
  215. batch.Identity.SourceCode,
  216. batch.Identity.DatasetKey,
  217. IdempotencyKey = idempotencyKey,
  218. Payload = payload,
  219. batch.PayloadSha256,
  220. AcceptedRecordCount = batch.AcceptedRowCount,
  221. SchemaVersion = batch.Versions.SourceSchema.Version,
  222. VersionSnapshot = JsonSerializer.Serialize(batch.Versions, SnapshotOptions),
  223. SourceWindow = batch.SourceWindow is null ? null : JsonSerializer.Serialize(batch.SourceWindow, SnapshotOptions),
  224. ReceivedAt = receivedAt.UtcDateTime
  225. });
  226. token.ThrowIfCancellationRequested();
  227. await InsertEventsAsync(db, batchId, events);
  228. }
  229. private static Task<int> InsertEventsAsync(ISqlSugarClient db, string batchId, IReadOnlyList<RawIngestEvent> events)
  230. {
  231. const int parametersPerEvent = 9;
  232. var parameters = new List<SugarParameter>(1 + events.Count * parametersPerEvent) { new("@BatchId", batchId) };
  233. var values = new List<string>(events.Count);
  234. for (var index = 0; index < events.Count; index++)
  235. {
  236. var item = events[index];
  237. values.Add($"(@BatchId, @EventId{index}, @Ordinal{index}, @Object{index}, @Position{index}, @Offset{index}, @Length{index}, @Hash{index}, @BusinessKey{index}, @UpdatedAt{index})");
  238. parameters.Add(new($"@EventId{index}", item.RawEventId.ToString("D")));
  239. parameters.Add(new($"@Ordinal{index}", item.RecordOrdinal));
  240. parameters.Add(new($"@Object{index}", item.ObjectCode));
  241. parameters.Add(new($"@Position{index}", item.SourcePosition));
  242. parameters.Add(new($"@Offset{index}", item.PayloadOffset));
  243. parameters.Add(new($"@Length{index}", item.PayloadLength));
  244. parameters.Add(new($"@Hash{index}", item.PayloadSha256));
  245. parameters.Add(new($"@BusinessKey{index}", item.SourceBusinessKey));
  246. parameters.Add(new($"@UpdatedAt{index}", item.SourceUpdatedAt));
  247. }
  248. const string insert = """
  249. INSERT INTO mdp_ingest_raw_event
  250. (batch_id, raw_event_id, record_ordinal, object_code, source_position, payload_offset, payload_length,
  251. payload_sha256, source_business_key, source_updated_at) VALUES
  252. """;
  253. return db.Ado.ExecuteCommandAsync(insert + " " + string.Join(", ", values), parameters.ToArray());
  254. }
  255. private static MdpIngestReceipt Replay(StoredReceipt previous, byte[] payload)
  256. {
  257. var receivedAt = new DateTimeOffset(DateTime.SpecifyKind(previous.ReceivedAt, DateTimeKind.Utc));
  258. if (DateTimeOffset.UtcNow - receivedAt >= ReplayDuration)
  259. throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "IDEMPOTENCY_EXPIRED");
  260. var hash = Convert.ToHexString(SHA256.HashData(payload));
  261. if (!string.Equals(hash, previous.PayloadSha256, StringComparison.OrdinalIgnoreCase))
  262. throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "IDEMPOTENCY_CONFLICT");
  263. return new MdpIngestReceipt(Guid.Parse(previous.BatchId), Accepted, previous.AcceptedRecordCount, previous.SchemaVersion, receivedAt);
  264. }
  265. private static MdpIngestHttpException IngestUnavailable() =>
  266. new(StatusCodes.Status503ServiceUnavailable, "INGEST_UNAVAILABLE");
  267. private sealed class StoredReceipt
  268. {
  269. public string? FirstPosition { get; set; }
  270. public string BatchId { get; set; } = string.Empty;
  271. public string PayloadSha256 { get; set; } = string.Empty;
  272. public int AcceptedRecordCount { get; set; }
  273. public string SchemaVersion { get; set; } = string.Empty;
  274. public DateTime ReceivedAt { get; set; }
  275. }
  276. }