MdpIngestReceiveService.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.Extensions.Logging;
  4. using Microsoft.Extensions.Configuration;
  5. using System.Data.Common;
  6. using System.Runtime.ExceptionServices;
  7. using System.Security.Cryptography;
  8. using System.Text;
  9. using System.Text.Json;
  10. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  11. public sealed class MdpIngestReceiveService(ISqlSugarClient db, ILogger<MdpIngestReceiveService> logger, IConfiguration? configuration = null) : ITransient
  12. {
  13. private const string Accepted = "accepted";
  14. private static readonly TimeSpan ReplayDuration = TimeSpan.FromDays(7);
  15. private static readonly JsonSerializerOptions SnapshotOptions = new(JsonSerializerDefaults.Web);
  16. public async Task<MdpIngestReceipt> ReceiveAsync(MdpIngestSubmission submission, CancellationToken cancellationToken)
  17. {
  18. cancellationToken.ThrowIfCancellationRequested();
  19. try
  20. {
  21. using var transactionDb = MdpIngestDatabase.Open(db);
  22. transactionDb.Ado.CancellationToken = cancellationToken;
  23. var transaction = await transactionDb.Ado.UseTranAsync(() =>
  24. ReceiveInTransactionAsync(transactionDb, submission, cancellationToken));
  25. if (transaction.IsSuccess)
  26. return transaction.Data;
  27. if (transaction.ErrorException is not null)
  28. ExceptionDispatchInfo.Throw(transaction.ErrorException);
  29. throw IngestUnavailable();
  30. }
  31. catch (Exception error) when (error is DbException or SqlSugarException)
  32. {
  33. cancellationToken.ThrowIfCancellationRequested();
  34. logger.LogWarning("通用接收事务未确认提交,数据库异常类型为 {ErrorType}", error.GetType().Name);
  35. throw IngestUnavailable();
  36. }
  37. }
  38. private async Task<MdpIngestReceipt> ReceiveInTransactionAsync(
  39. ISqlSugarClient db, MdpIngestSubmission submission, CancellationToken cancellationToken)
  40. {
  41. var datasetKey = submission.DatasetKey.Trim().ToLowerInvariant();
  42. var idempotencyKey = Encoding.ASCII.GetBytes(submission.IdempotencyKey);
  43. var scope = new { submission.TenantId, submission.FactoryId, submission.SourceId, DatasetKey = datasetKey };
  44. var configurationFactory = submission.ConfigurationFactoryId ?? submission.FactoryId;
  45. var factory = await db.Ado.SqlQuerySingleAsync<long?>("""
  46. SELECT factory_id FROM mdp_purchase_active_factory WHERE tenant_id=@TenantId AND factory_id=@FactoryId FOR SHARE
  47. """, new { scope.TenantId, scope.FactoryId });
  48. if (factory != submission.FactoryId)
  49. throw new MdpIngestHttpException(StatusCodes.Status403Forbidden, "FACTORY_UNAVAILABLE");
  50. // 管理端切换数据集版本或来源绑定时先更新同一行。
  51. var datasetId = await db.Ado.SqlQuerySingleAsync<long?>(
  52. """
  53. SELECT id FROM mdp_ingest_dataset
  54. WHERE tenant_id = @TenantId AND factory_id = @ConfigurationFactory AND dataset_key = @DatasetKey AND enabled = 1
  55. FOR UPDATE
  56. """, new { scope.TenantId, ConfigurationFactory = configurationFactory, scope.DatasetKey });
  57. if (datasetId is null or <= 0)
  58. throw new IngestContractException(IngestContractError.DatasetUnavailable);
  59. var grantId = await db.Ado.SqlQuerySingleAsync<long?>(
  60. """
  61. SELECT id FROM mdp_ingest_access_grant
  62. WHERE id = @GrantId AND tenant_id = @TenantId AND factory_id = @ConfigurationFactory AND use_batch_factory = @FromBatch
  63. AND source_id = @SourceId AND dataset_key = @DatasetKey
  64. AND access_key_hash = @AccessKeyHash AND enabled = 1
  65. FOR UPDATE
  66. """, new { submission.GrantId, submission.AccessKeyHash, scope.TenantId, ConfigurationFactory = configurationFactory, FromBatch = submission.ConfigurationFactoryId.HasValue, scope.SourceId, scope.DatasetKey });
  67. if (grantId is null or <= 0)
  68. throw new IngestContractException(IngestContractError.DatasetUnavailable);
  69. var sourceId = await db.Ado.SqlQuerySingleAsync<long?>(
  70. """
  71. SELECT id FROM mdp_source
  72. WHERE id = @SourceId AND tenant_id = @TenantId AND status = 1
  73. FOR UPDATE
  74. """, new { scope.SourceId, scope.TenantId });
  75. if (sourceId is null or <= 0)
  76. throw new IngestContractException(IngestContractError.DatasetUnavailable);
  77. cancellationToken.ThrowIfCancellationRequested();
  78. var previous = await db.Ado.SqlQuerySingleAsync<StoredReceipt>(
  79. """
  80. SELECT batch_id AS BatchId, payload_sha256 AS PayloadSha256, accepted_record_count AS AcceptedRecordCount,
  81. source_schema_version AS SchemaVersion, received_at AS ReceivedAt,
  82. (SELECT e.source_position FROM mdp_ingest_raw_event e
  83. WHERE e.batch_id = mdp_ingest_raw_batch.batch_id AND e.record_ordinal = 0) AS FirstPosition
  84. FROM mdp_ingest_raw_batch
  85. WHERE tenant_id = @TenantId AND factory_id = @FactoryId AND source_id = @SourceId
  86. AND dataset_id = @DatasetId AND idempotency_key = @IdempotencyKey AND accepted_record_count > 0
  87. """, new { scope.TenantId, scope.FactoryId, scope.SourceId, DatasetId = datasetId.Value, IdempotencyKey = idempotencyKey });
  88. var registry = new MdpIngestDatasetRegistry(db);
  89. if (previous is not null)
  90. {
  91. var currentBinding = await registry.ResolveActiveBindingAsync(scope.TenantId, configurationFactory, scope.SourceId, datasetKey);
  92. if (currentBinding is null)
  93. throw new IngestContractException(IngestContractError.DatasetUnavailable);
  94. cancellationToken.ThrowIfCancellationRequested();
  95. var previousIsNdjson = previous.FirstPosition?.StartsWith("/lines/", StringComparison.Ordinal) == true;
  96. if ((submission.Format == IngestPayloadFormat.Ndjson) != previousIsNdjson
  97. || submission.SchemaVersion is not null && submission.SchemaVersion != previous.SchemaVersion)
  98. throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "IDEMPOTENCY_CONFLICT");
  99. return Replay(previous, submission.Payload);
  100. }
  101. await MdpEdgeRoute.RequireDirectAsync(db, configuration, scope.TenantId, scope.FactoryId, datasetId.Value, scope.SourceId);
  102. var migration = await MdpPurchaseMigrationStore.LockNewAsync(
  103. db, scope.TenantId, scope.FactoryId, datasetId.Value, scope.SourceId);
  104. MdpPurchaseMigrationStore.RequireAdmission(migration, MdpPurchaseMigrationStore.Unified);
  105. var reservation = new
  106. {
  107. scope.TenantId, scope.FactoryId, scope.SourceId, DatasetId = datasetId.Value,
  108. KeySha256 = Convert.ToHexString(SHA256.HashData(idempotencyKey)).ToLowerInvariant()
  109. };
  110. // A key stays reserved even when its Raw body and receipt have reached their retention limit.
  111. var reserved = await db.Ado.GetIntAsync(
  112. """
  113. SELECT COUNT(*) FROM mdp_ingest_idempotency_reservation
  114. WHERE tenant_id = @TenantId AND factory_id = @FactoryId AND source_id = @SourceId
  115. AND dataset_id = @DatasetId AND key_sha256 = @KeySha256
  116. """, reservation);
  117. if (reserved != 0)
  118. throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "IDEMPOTENCY_EXPIRED");
  119. var binder = new MdpIngestContractBinder(registry);
  120. var prepared = await binder.PrepareAsync(scope.TenantId, scope.FactoryId, scope.SourceId, datasetKey,
  121. submission.Payload, MdpIngestProtocol.Limits, configurationFactory, submission.Format, submission.SchemaVersion);
  122. if (submission.Format == IngestPayloadFormat.Ndjson && !MdpBatchFactory.RowsMatch(prepared))
  123. throw new MdpIngestHttpException(StatusCodes.Status400BadRequest, "INVALID_BATCH_SCOPE");
  124. var batch = prepared.Batch;
  125. if (submission.IdempotencyKey.StartsWith("relational-sync-", StringComparison.Ordinal))
  126. {
  127. var frozen = await db.Ado.GetIntAsync("""
  128. SELECT COUNT(*) FROM mdp_connector_relational_sync_page p
  129. JOIN mdp_connector_relational_sync_run r ON r.run_id=p.run_id
  130. WHERE p.idem_key=@IdemKey AND p.payload_sha256=@PayloadSha256
  131. AND r.tenant_id=@TenantId AND r.factory_id=@FactoryId AND r.source_id=@SourceId
  132. AND r.dataset_id=@DatasetId AND r.schema_version=@SchemaVersion AND r.phase='RECEIVING'
  133. """, new { IdemKey = submission.IdempotencyKey, batch.PayloadSha256, scope.TenantId, scope.FactoryId,
  134. scope.SourceId, DatasetId = datasetId.Value, SchemaVersion = batch.Versions.SourceSchema.Version });
  135. if (frozen != 1) throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "RELATIONAL_FROZEN_PAGE_REQUIRED");
  136. var generation = await db.Ado.SqlQuerySingleAsync<long?>("""
  137. SELECT changes.source_generation FROM mdp_connector_relational_change_run changes
  138. JOIN mdp_connector_relational_sync_page p ON p.run_id=changes.run_id
  139. WHERE p.idem_key=@IdemKey
  140. """, new { IdemKey = submission.IdempotencyKey });
  141. batch = batch with { SourceWindow = new(null, null, IngestSourceWindow.VerifiedRelationalSnapshot)
  142. {
  143. SourceGeneration = generation,
  144. } };
  145. }
  146. else if (submission.TrackPurchaseApiTime && prepared.Events[0].ObjectCode == "PURCHASE_ORDER")
  147. {
  148. batch = batch with { SourceWindow = new(null, null, IngestSourceWindow.PurchaseApiTime) };
  149. }
  150. return await PersistAcceptedBatchAsync(db, prepared with { Batch = batch }, idempotencyKey, configurationFactory, cancellationToken);
  151. }
  152. internal static async Task<MdpIngestReceipt> PersistAcceptedBatchAsync(ISqlSugarClient db, PreparedIngestBatch prepared,
  153. byte[] idempotencyKey, long configurationFactory, CancellationToken cancellationToken, bool useCapturedRaw = false)
  154. {
  155. var batch = prepared.Batch;
  156. var scope = batch.Identity;
  157. var receivedAt = new DateTimeOffset(batch.ReceivedAt.UtcTicks / 10 * 10, TimeSpan.Zero);
  158. var batchId = batch.BatchId.ToString("D");
  159. cancellationToken.ThrowIfCancellationRequested();
  160. await db.Ado.ExecuteCommandAsync(
  161. """
  162. INSERT INTO mdp_ingest_idempotency_reservation
  163. (tenant_id, factory_id, source_id, dataset_id, key_sha256, first_received_at)
  164. VALUES (@TenantId, @FactoryId, @SourceId, @DatasetId, @KeySha256, @ReceivedAt)
  165. """, new
  166. {
  167. scope.TenantId, scope.FactoryId, scope.SourceId, scope.DatasetId,
  168. KeySha256 = Convert.ToHexString(SHA256.HashData(idempotencyKey)).ToLowerInvariant(), ReceivedAt = receivedAt.UtcDateTime
  169. });
  170. if (useCapturedRaw)
  171. {
  172. var updated = await db.Ado.ExecuteCommandAsync("""
  173. UPDATE mdp_ingest_raw_batch SET accepted_record_count=@AcceptedRowCount, idempotency_key=@idempotencyKey
  174. WHERE batch_id=@batchId AND tenant_id=@TenantId AND factory_id=@FactoryId AND source_id=@SourceId
  175. AND dataset_id=@DatasetId AND LEFT(idempotency_key,1)=X'00' AND accepted_record_count=0
  176. AND payload_sha256=@PayloadSha256 AND source_schema_version=@SchemaVersion
  177. AND version_snapshot=CAST(@VersionSnapshot AS JSON)
  178. """, new { batchId, scope.TenantId, scope.FactoryId, scope.SourceId, scope.DatasetId, idempotencyKey,
  179. batch.AcceptedRowCount, batch.PayloadSha256, SchemaVersion = batch.Versions.SourceSchema.Version,
  180. VersionSnapshot = JsonSerializer.Serialize(batch.Versions, SnapshotOptions) });
  181. if (updated != 1)
  182. throw new MdpApiPullException("PULL_CAPTURE_CHANGED");
  183. await InsertEventsAsync(db, batchId, prepared.Events);
  184. }
  185. else
  186. {
  187. await PersistRawWithJournalAsync(db, batch, prepared.Events, batch.Payload.ToArray(), idempotencyKey, receivedAt, cancellationToken);
  188. }
  189. // 发布与接收都锁定同一数据集行;同版本重新发布后也能追溯本批当时的发布记录。
  190. await db.Ado.ExecuteCommandAsync("""
  191. INSERT INTO mdp_ingest_release_batch (batch_id, release_id, tenant_id, dataset_id, source_id, factory_id)
  192. SELECT @BatchId, p.release_id, p.tenant_id, p.dataset_id, p.source_id, @ActualFactory
  193. FROM mdp_ingest_published_source p
  194. WHERE p.tenant_id=@TenantId AND p.factory_id=@ConfigurationFactory AND p.dataset_id=@DatasetId
  195. AND p.source_id=@SourceId AND p.schema_version=@Version
  196. """, new { BatchId = batchId, scope.TenantId, ConfigurationFactory = configurationFactory,
  197. scope.DatasetId, scope.SourceId, Version = batch.Versions.SourceSchema.Version,
  198. ActualFactory = scope.FactoryId });
  199. cancellationToken.ThrowIfCancellationRequested();
  200. await db.Ado.ExecuteCommandAsync(
  201. """
  202. INSERT INTO mdp_ingest_receive_task (batch_id, tenant_id, factory_id, source_id, dataset_id, status, created_at)
  203. VALUES (@BatchId, @TenantId, @FactoryId, @SourceId, @DatasetId, 'PENDING', @CreatedAt)
  204. """, new
  205. {
  206. BatchId = batchId,
  207. batch.Identity.TenantId,
  208. batch.Identity.FactoryId,
  209. batch.Identity.SourceId,
  210. batch.Identity.DatasetId,
  211. CreatedAt = receivedAt.UtcDateTime
  212. });
  213. cancellationToken.ThrowIfCancellationRequested();
  214. await MdpIngestBatchJournal.AppendAsync(db, batch.BatchId, batch.Identity, IngestBatchJournal.RawAccepted, batch.AcceptedRowCount);
  215. return new MdpIngestReceipt(batch.BatchId, Accepted, batch.AcceptedRowCount, batch.Versions.SourceSchema.Version, receivedAt);
  216. }
  217. internal static async Task PersistRawWithJournalAsync(ISqlSugarClient db, RawIngestBatch batch,
  218. IReadOnlyList<RawIngestEvent> events, byte[] payload, byte[] idempotencyKey, DateTimeOffset receivedAt, CancellationToken token)
  219. {
  220. await PersistRawAsync(db, batch, events, payload, idempotencyKey, receivedAt, token);
  221. await MdpIngestBatchJournal.AppendAsync(db, batch.BatchId, batch.Identity, IngestBatchJournal.RawStored);
  222. }
  223. internal static async Task PersistRawAsync(ISqlSugarClient db, RawIngestBatch batch,
  224. IReadOnlyList<RawIngestEvent> events, byte[] payload, byte[] idempotencyKey, DateTimeOffset receivedAt, CancellationToken token)
  225. {
  226. token.ThrowIfCancellationRequested();
  227. var batchId = batch.BatchId.ToString("D");
  228. await db.Ado.ExecuteCommandAsync(
  229. """
  230. INSERT INTO mdp_ingest_raw_batch
  231. (batch_id, tenant_id, factory_id, source_id, dataset_id, source_code, dataset_key, idempotency_key,
  232. payload, payload_sha256, accepted_record_count, source_schema_version, version_snapshot, source_window, received_at)
  233. VALUES (@BatchId, @TenantId, @FactoryId, @SourceId, @DatasetId, @SourceCode, @DatasetKey, @IdempotencyKey,
  234. @Payload, @PayloadSha256, @AcceptedRecordCount, @SchemaVersion, @VersionSnapshot, @SourceWindow, @ReceivedAt)
  235. """, new
  236. {
  237. BatchId = batchId,
  238. batch.Identity.TenantId,
  239. batch.Identity.FactoryId,
  240. batch.Identity.SourceId,
  241. batch.Identity.DatasetId,
  242. batch.Identity.SourceCode,
  243. batch.Identity.DatasetKey,
  244. IdempotencyKey = idempotencyKey,
  245. Payload = payload,
  246. batch.PayloadSha256,
  247. AcceptedRecordCount = batch.AcceptedRowCount,
  248. SchemaVersion = batch.Versions.SourceSchema.Version,
  249. VersionSnapshot = JsonSerializer.Serialize(batch.Versions, SnapshotOptions),
  250. SourceWindow = batch.SourceWindow is null ? null : JsonSerializer.Serialize(batch.SourceWindow, SnapshotOptions),
  251. ReceivedAt = receivedAt.UtcDateTime
  252. });
  253. token.ThrowIfCancellationRequested();
  254. if (events.Count > 0)
  255. await InsertEventsAsync(db, batchId, events);
  256. }
  257. private static Task<int> InsertEventsAsync(ISqlSugarClient db, string batchId, IReadOnlyList<RawIngestEvent> events)
  258. {
  259. const int parametersPerEvent = 9;
  260. var parameters = new List<SugarParameter>(1 + events.Count * parametersPerEvent) { new("@BatchId", batchId) };
  261. var values = new List<string>(events.Count);
  262. for (var index = 0; index < events.Count; index++)
  263. {
  264. var item = events[index];
  265. values.Add($"(@BatchId, @EventId{index}, @Ordinal{index}, @Object{index}, @Position{index}, @Offset{index}, @Length{index}, @Hash{index}, @BusinessKey{index}, @UpdatedAt{index})");
  266. parameters.Add(new($"@EventId{index}", item.RawEventId.ToString("D")));
  267. parameters.Add(new($"@Ordinal{index}", item.RecordOrdinal));
  268. parameters.Add(new($"@Object{index}", item.ObjectCode));
  269. parameters.Add(new($"@Position{index}", item.SourcePosition));
  270. parameters.Add(new($"@Offset{index}", item.PayloadOffset));
  271. parameters.Add(new($"@Length{index}", item.PayloadLength));
  272. parameters.Add(new($"@Hash{index}", item.PayloadSha256));
  273. parameters.Add(new($"@BusinessKey{index}", item.SourceBusinessKey));
  274. parameters.Add(new($"@UpdatedAt{index}", item.SourceUpdatedAt));
  275. }
  276. const string insert = """
  277. INSERT INTO mdp_ingest_raw_event
  278. (batch_id, raw_event_id, record_ordinal, object_code, source_position, payload_offset, payload_length,
  279. payload_sha256, source_business_key, source_updated_at) VALUES
  280. """;
  281. return db.Ado.ExecuteCommandAsync(insert + " " + string.Join(", ", values), parameters.ToArray());
  282. }
  283. private static MdpIngestReceipt Replay(StoredReceipt previous, byte[] payload)
  284. {
  285. var receivedAt = new DateTimeOffset(DateTime.SpecifyKind(previous.ReceivedAt, DateTimeKind.Utc));
  286. if (DateTimeOffset.UtcNow - receivedAt >= ReplayDuration)
  287. throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "IDEMPOTENCY_EXPIRED");
  288. var hash = Convert.ToHexString(SHA256.HashData(payload));
  289. if (!string.Equals(hash, previous.PayloadSha256, StringComparison.OrdinalIgnoreCase))
  290. throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "IDEMPOTENCY_CONFLICT");
  291. return new MdpIngestReceipt(Guid.Parse(previous.BatchId), Accepted, previous.AcceptedRecordCount, previous.SchemaVersion, receivedAt);
  292. }
  293. private static MdpIngestHttpException IngestUnavailable() =>
  294. new(StatusCodes.Status503ServiceUnavailable, "INGEST_UNAVAILABLE");
  295. private sealed class StoredReceipt
  296. {
  297. public string? FirstPosition { get; set; }
  298. public string BatchId { get; set; } = string.Empty;
  299. public string PayloadSha256 { get; set; } = string.Empty;
  300. public int AcceptedRecordCount { get; set; }
  301. public string SchemaVersion { get; set; } = string.Empty;
  302. public DateTime ReceivedAt { get; set; }
  303. }
  304. }