using Admin.NET.Plugin.AiDOP.DataPlatform.Core; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using System.Data.Common; using System.Runtime.ExceptionServices; using System.Security.Cryptography; using System.Text; using System.Text.Json; namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress; public sealed class MdpIngestReceiveService(ISqlSugarClient db, ILogger logger) : ITransient { private const string Accepted = "accepted"; private static readonly TimeSpan ReplayDuration = TimeSpan.FromDays(7); private static readonly JsonSerializerOptions SnapshotOptions = new(JsonSerializerDefaults.Web); public async Task ReceiveAsync(MdpIngestSubmission submission, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { using var transactionDb = MdpIngestDatabase.Open(db); transactionDb.Ado.CancellationToken = cancellationToken; var transaction = await transactionDb.Ado.UseTranAsync(() => ReceiveInTransactionAsync(transactionDb, submission, cancellationToken)); if (transaction.IsSuccess) return transaction.Data; if (transaction.ErrorException is not null) ExceptionDispatchInfo.Throw(transaction.ErrorException); throw IngestUnavailable(); } catch (Exception error) when (error is DbException or SqlSugarException) { cancellationToken.ThrowIfCancellationRequested(); logger.LogWarning("通用接收事务未确认提交,数据库异常类型为 {ErrorType}", error.GetType().Name); throw IngestUnavailable(); } } private static async Task ReceiveInTransactionAsync( ISqlSugarClient db, MdpIngestSubmission submission, CancellationToken cancellationToken) { var datasetKey = submission.DatasetKey.Trim().ToLowerInvariant(); var idempotencyKey = Encoding.ASCII.GetBytes(submission.IdempotencyKey); var scope = new { submission.TenantId, submission.FactoryId, submission.SourceId, DatasetKey = datasetKey }; var configurationFactory = submission.ConfigurationFactoryId ?? submission.FactoryId; var factory = await db.Ado.SqlQuerySingleAsync(""" SELECT factory_id FROM mdp_purchase_active_factory WHERE tenant_id=@TenantId AND factory_id=@FactoryId FOR SHARE """, new { scope.TenantId, scope.FactoryId }); if (factory != submission.FactoryId) throw new MdpIngestHttpException(StatusCodes.Status403Forbidden, "FACTORY_UNAVAILABLE"); // 管理端切换数据集版本或来源绑定时先更新同一行。 var datasetId = await db.Ado.SqlQuerySingleAsync( """ SELECT id FROM mdp_ingest_dataset WHERE tenant_id = @TenantId AND factory_id = @ConfigurationFactory AND dataset_key = @DatasetKey AND enabled = 1 FOR UPDATE """, new { scope.TenantId, ConfigurationFactory = configurationFactory, scope.DatasetKey }); if (datasetId is null or <= 0) throw new IngestContractException(IngestContractError.DatasetUnavailable); var grantId = await db.Ado.SqlQuerySingleAsync( """ SELECT id FROM mdp_ingest_access_grant WHERE id = @GrantId AND tenant_id = @TenantId AND factory_id = @ConfigurationFactory AND use_batch_factory = @FromBatch AND source_id = @SourceId AND dataset_key = @DatasetKey AND access_key_hash = @AccessKeyHash AND enabled = 1 FOR UPDATE """, new { submission.GrantId, submission.AccessKeyHash, scope.TenantId, ConfigurationFactory = configurationFactory, FromBatch = submission.ConfigurationFactoryId.HasValue, scope.SourceId, scope.DatasetKey }); if (grantId is null or <= 0) throw new IngestContractException(IngestContractError.DatasetUnavailable); var sourceId = await db.Ado.SqlQuerySingleAsync( """ SELECT id FROM mdp_source WHERE id = @SourceId AND tenant_id = @TenantId AND status = 1 FOR UPDATE """, new { scope.SourceId, scope.TenantId }); if (sourceId is null or <= 0) throw new IngestContractException(IngestContractError.DatasetUnavailable); cancellationToken.ThrowIfCancellationRequested(); var previous = await db.Ado.SqlQuerySingleAsync( """ SELECT batch_id AS BatchId, payload_sha256 AS PayloadSha256, accepted_record_count AS AcceptedRecordCount, source_schema_version AS SchemaVersion, received_at AS ReceivedAt FROM mdp_ingest_raw_batch WHERE tenant_id = @TenantId AND factory_id = @FactoryId AND source_id = @SourceId AND dataset_id = @DatasetId AND idempotency_key = @IdempotencyKey """, new { scope.TenantId, scope.FactoryId, scope.SourceId, DatasetId = datasetId.Value, IdempotencyKey = idempotencyKey }); var registry = new MdpIngestDatasetRegistry(db); if (previous is not null) { var currentBinding = await registry.ResolveActiveBindingAsync(scope.TenantId, configurationFactory, scope.SourceId, datasetKey); if (currentBinding is null) throw new IngestContractException(IngestContractError.DatasetUnavailable); cancellationToken.ThrowIfCancellationRequested(); return Replay(previous, submission.Payload); } var migration = await MdpPurchaseMigrationStore.LockNewAsync( db, scope.TenantId, scope.FactoryId, datasetId.Value, scope.SourceId); MdpPurchaseMigrationStore.RequireAdmission(migration, MdpPurchaseMigrationStore.Unified); var reservation = new { scope.TenantId, scope.FactoryId, scope.SourceId, DatasetId = datasetId.Value, KeySha256 = Convert.ToHexString(SHA256.HashData(idempotencyKey)).ToLowerInvariant() }; // A key stays reserved even when its Raw body and receipt have reached their retention limit. var reserved = await db.Ado.GetIntAsync( """ SELECT COUNT(*) FROM mdp_ingest_idempotency_reservation WHERE tenant_id = @TenantId AND factory_id = @FactoryId AND source_id = @SourceId AND dataset_id = @DatasetId AND key_sha256 = @KeySha256 """, reservation); if (reserved != 0) throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "IDEMPOTENCY_EXPIRED"); var binder = new MdpIngestContractBinder(registry); var prepared = await binder.PrepareAsync(scope.TenantId, scope.FactoryId, scope.SourceId, datasetKey, submission.Payload, MdpIngestProtocol.Limits, configurationFactory); var batch = prepared.Batch; var receivedAt = new DateTimeOffset(batch.ReceivedAt.UtcTicks / 10 * 10, TimeSpan.Zero); var batchId = batch.BatchId.ToString("D"); cancellationToken.ThrowIfCancellationRequested(); await db.Ado.ExecuteCommandAsync( """ INSERT INTO mdp_ingest_idempotency_reservation (tenant_id, factory_id, source_id, dataset_id, key_sha256, first_received_at) VALUES (@TenantId, @FactoryId, @SourceId, @DatasetId, @KeySha256, @ReceivedAt) """, new { reservation.TenantId, reservation.FactoryId, reservation.SourceId, reservation.DatasetId, reservation.KeySha256, ReceivedAt = receivedAt.UtcDateTime }); await PersistRawAsync(db, batch, prepared.Events, submission.Payload, idempotencyKey, receivedAt, cancellationToken); // 发布与接收都锁定同一数据集行;同版本重新发布后也能追溯本批当时的发布记录。 await db.Ado.ExecuteCommandAsync(""" INSERT INTO mdp_ingest_release_batch (batch_id, release_id, tenant_id, dataset_id, source_id, factory_id) SELECT @BatchId, p.release_id, p.tenant_id, p.dataset_id, p.source_id, @ActualFactory FROM mdp_ingest_published_source p WHERE p.tenant_id=@TenantId AND p.factory_id=@ConfigurationFactory AND p.dataset_id=@DatasetId AND p.source_id=@SourceId AND p.schema_version=@Version """, new { BatchId = batchId, scope.TenantId, ConfigurationFactory = configurationFactory, DatasetId = datasetId.Value, scope.SourceId, Version = batch.Versions.SourceSchema.Version, ActualFactory = scope.FactoryId }); cancellationToken.ThrowIfCancellationRequested(); await db.Ado.ExecuteCommandAsync( """ INSERT INTO mdp_ingest_receive_task (batch_id, tenant_id, factory_id, source_id, dataset_id, status, created_at) VALUES (@BatchId, @TenantId, @FactoryId, @SourceId, @DatasetId, 'PENDING', @CreatedAt) """, new { BatchId = batchId, batch.Identity.TenantId, batch.Identity.FactoryId, batch.Identity.SourceId, batch.Identity.DatasetId, CreatedAt = receivedAt.UtcDateTime }); cancellationToken.ThrowIfCancellationRequested(); return new MdpIngestReceipt(batch.BatchId, Accepted, batch.AcceptedRowCount, batch.Versions.SourceSchema.Version, receivedAt); } internal static async Task PersistRawAsync(ISqlSugarClient db, RawIngestBatch batch, IReadOnlyList events, byte[] payload, byte[] idempotencyKey, DateTimeOffset receivedAt, CancellationToken token) { token.ThrowIfCancellationRequested(); var batchId = batch.BatchId.ToString("D"); await db.Ado.ExecuteCommandAsync( """ INSERT INTO mdp_ingest_raw_batch (batch_id, tenant_id, factory_id, source_id, dataset_id, source_code, dataset_key, idempotency_key, payload, payload_sha256, accepted_record_count, source_schema_version, version_snapshot, source_window, received_at) VALUES (@BatchId, @TenantId, @FactoryId, @SourceId, @DatasetId, @SourceCode, @DatasetKey, @IdempotencyKey, @Payload, @PayloadSha256, @AcceptedRecordCount, @SchemaVersion, @VersionSnapshot, @SourceWindow, @ReceivedAt) """, new { BatchId = batchId, batch.Identity.TenantId, batch.Identity.FactoryId, batch.Identity.SourceId, batch.Identity.DatasetId, batch.Identity.SourceCode, batch.Identity.DatasetKey, IdempotencyKey = idempotencyKey, Payload = payload, batch.PayloadSha256, AcceptedRecordCount = batch.AcceptedRowCount, SchemaVersion = batch.Versions.SourceSchema.Version, VersionSnapshot = JsonSerializer.Serialize(batch.Versions, SnapshotOptions), SourceWindow = batch.SourceWindow is null ? null : JsonSerializer.Serialize(batch.SourceWindow, SnapshotOptions), ReceivedAt = receivedAt.UtcDateTime }); token.ThrowIfCancellationRequested(); await InsertEventsAsync(db, batchId, events); } private static Task InsertEventsAsync(ISqlSugarClient db, string batchId, IReadOnlyList events) { const int parametersPerEvent = 9; var parameters = new List(1 + events.Count * parametersPerEvent) { new("@BatchId", batchId) }; var values = new List(events.Count); for (var index = 0; index < events.Count; index++) { var item = events[index]; values.Add($"(@BatchId, @EventId{index}, @Ordinal{index}, @Object{index}, @Position{index}, @Offset{index}, @Length{index}, @Hash{index}, @BusinessKey{index}, @UpdatedAt{index})"); parameters.Add(new($"@EventId{index}", item.RawEventId.ToString("D"))); parameters.Add(new($"@Ordinal{index}", item.RecordOrdinal)); parameters.Add(new($"@Object{index}", item.ObjectCode)); parameters.Add(new($"@Position{index}", item.SourcePosition)); parameters.Add(new($"@Offset{index}", item.PayloadOffset)); parameters.Add(new($"@Length{index}", item.PayloadLength)); parameters.Add(new($"@Hash{index}", item.PayloadSha256)); parameters.Add(new($"@BusinessKey{index}", item.SourceBusinessKey)); parameters.Add(new($"@UpdatedAt{index}", item.SourceUpdatedAt)); } const string insert = """ INSERT INTO mdp_ingest_raw_event (batch_id, raw_event_id, record_ordinal, object_code, source_position, payload_offset, payload_length, payload_sha256, source_business_key, source_updated_at) VALUES """; return db.Ado.ExecuteCommandAsync(insert + " " + string.Join(", ", values), parameters.ToArray()); } private static MdpIngestReceipt Replay(StoredReceipt previous, byte[] payload) { var receivedAt = new DateTimeOffset(DateTime.SpecifyKind(previous.ReceivedAt, DateTimeKind.Utc)); if (DateTimeOffset.UtcNow - receivedAt >= ReplayDuration) throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "IDEMPOTENCY_EXPIRED"); var hash = Convert.ToHexString(SHA256.HashData(payload)); if (!string.Equals(hash, previous.PayloadSha256, StringComparison.OrdinalIgnoreCase)) throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "IDEMPOTENCY_CONFLICT"); return new MdpIngestReceipt(Guid.Parse(previous.BatchId), Accepted, previous.AcceptedRecordCount, previous.SchemaVersion, receivedAt); } private static MdpIngestHttpException IngestUnavailable() => new(StatusCodes.Status503ServiceUnavailable, "INGEST_UNAVAILABLE"); private sealed class StoredReceipt { public string BatchId { get; set; } = string.Empty; public string PayloadSha256 { get; set; } = string.Empty; public int AcceptedRecordCount { get; set; } public string SchemaVersion { get; set; } = string.Empty; public DateTime ReceivedAt { get; set; } } }