using System.Globalization; namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress; public sealed class MdpIngestBatchStatusService(ISqlSugarClient db) : ITransient { public Task FindAsync(MdpIngestSubmission caller, Guid batchId, CancellationToken cancellationToken) => FindAsync(new BatchReadScope(batchId.ToString("D"), caller.TenantId, caller.FactoryId, caller.ConfigurationFactoryId ?? caller.FactoryId, caller.SourceId, caller.DatasetKey, caller.GrantId, caller.AccessKeyHash, caller.ConfigurationFactoryId.HasValue, null, null), cancellationToken); internal Task FindForOperatorAsync(long tenantId, long configurationFactory, long datasetId, IReadOnlyCollection authorizedFactories, Guid batchId, CancellationToken cancellationToken) => FindAsync(new BatchReadScope(batchId.ToString("D"), tenantId, null, configurationFactory, null, null, null, null, false, datasetId, string.Join(',', authorizedFactories.Select(factory => factory.ToString(CultureInfo.InvariantCulture)))), cancellationToken); private async Task FindAsync(BatchReadScope scope, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using var connection = MdpIngestDatabase.Open(db); var row = await connection.Ado.SqlQuerySingleAsync(""" SELECT b.accepted_record_count AS AcceptedCount, b.source_schema_version AS SchemaVersion, b.received_at AS ReceivedAt, t.status AS WorkerStatus, COALESCE(t.last_error_code,CASE WHEN c.state='REJECTED' THEN c.diagnostic END) AS ErrorCode, c.state AS CaptureState, GREATEST(COALESCE(t.updated_at_utc, b.received_at), COALESCE(e.acknowledged_at, b.received_at), COALESCE(c.changed_at, b.received_at)) AS UpdatedAt, dispatch.status AS DispatchStatus, (SELECT COUNT(DISTINCT q.raw_event_id) FROM mdp_ingest_worker_quarantine q WHERE q.batch_id=b.batch_id AND q.tenant_id=b.tenant_id AND q.factory_id=b.factory_id AND q.source_id=b.source_id AND q.dataset_id=b.dataset_id) AS IsolatedCount, e.accepted_count AS ReceiverAcceptedCount FROM mdp_ingest_raw_batch b JOIN mdp_ingest_dataset d ON d.id=b.dataset_id AND d.tenant_id=b.tenant_id AND d.factory_id=@ConfigurationFactory JOIN mdp_purchase_active_factory f ON f.tenant_id=b.tenant_id AND f.factory_id=b.factory_id LEFT JOIN mdp_connector_api_pull_capture c ON c.batch_id=b.batch_id LEFT JOIN mdp_ingest_receive_task t ON t.batch_id=b.batch_id AND t.tenant_id=b.tenant_id AND t.factory_id=b.factory_id AND t.source_id=b.source_id AND t.dataset_id=b.dataset_id LEFT JOIN mdp_ingest_release_batch e ON e.batch_id=b.batch_id AND e.tenant_id=b.tenant_id AND e.factory_id=b.factory_id AND e.source_id=b.source_id AND e.dataset_id=b.dataset_id LEFT JOIN mdp_ingest_purchase_dispatch dispatch ON dispatch.batch_id=b.batch_id AND dispatch.tenant_id=b.tenant_id AND dispatch.factory_id=b.factory_id AND dispatch.source_id=b.source_id AND dispatch.dataset_id=b.dataset_id WHERE b.batch_id=@BatchId AND b.tenant_id=@TenantId AND ((b.dataset_id=@OperatorDatasetId AND FIND_IN_SET(CAST(b.factory_id AS CHAR), @AuthorizedFactories) > 0) OR (@OperatorDatasetId IS NULL AND b.accepted_record_count>0 AND b.factory_id=@FactoryId AND b.source_id=@SourceId AND d.dataset_key=@DatasetKey AND EXISTS (SELECT 1 FROM mdp_ingest_access_grant g WHERE g.id=@GrantId AND g.tenant_id=b.tenant_id AND g.factory_id=d.factory_id AND g.source_id=b.source_id AND g.dataset_key=d.dataset_key AND g.enabled=1 AND g.use_batch_factory=@FromBatch AND g.access_key_hash=@AccessKeyHash))) """, new { scope.BatchId, scope.TenantId, scope.FactoryId, scope.ConfigurationFactory, scope.SourceId, scope.DatasetKey, scope.GrantId, scope.AccessKeyHash, scope.FromBatch, scope.OperatorDatasetId, scope.AuthorizedFactories }); cancellationToken.ThrowIfCancellationRequested(); if (row is null) return null; if (row.CaptureState is { } state && state != "ACCEPTED") return new MdpIngestBatchStatus(Guid.Parse(scope.BatchId), state.ToLowerInvariant(), row.SchemaVersion, 0, null, 0, null, "not_started", Utc(row.ReceivedAt), Utc(row.UpdatedAt), row.ErrorCode); var receiverAccepted = row.ReceiverAcceptedCount; if (receiverAccepted is null && row.DispatchStatus == "DONE") receiverAccepted = row.AcceptedCount - row.IsolatedCount; return new MdpIngestBatchStatus(Guid.Parse(scope.BatchId), "accepted", row.SchemaVersion, row.AcceptedCount, row.WorkerStatus, row.IsolatedCount, receiverAccepted, receiverAccepted.HasValue ? "confirmed" : row.DispatchStatus switch { "FAILED" => "failed", "READY" => "awaiting_delivery", _ => "pending" }, Utc(row.ReceivedAt), Utc(row.UpdatedAt), row.ErrorCode); } private static DateTimeOffset Utc(DateTime value) => new(DateTime.SpecifyKind(value, DateTimeKind.Utc)); private sealed record BatchReadScope(string BatchId, long TenantId, long? FactoryId, long ConfigurationFactory, long? SourceId, string? DatasetKey, long? GrantId, string? AccessKeyHash, bool FromBatch, long? OperatorDatasetId, string? AuthorizedFactories); private sealed class BatchStatusRow { public int AcceptedCount { get; set; } public string? CaptureState { get; set; } public string SchemaVersion { get; set; } = ""; public DateTime ReceivedAt { get; set; } public string? WorkerStatus { get; set; } public string? ErrorCode { get; set; } public DateTime UpdatedAt { get; set; } public string? DispatchStatus { get; set; } public int? ReceiverAcceptedCount { get; set; } public int IsolatedCount { get; set; } } } public sealed record MdpIngestBatchStatus(Guid BatchId, string ReceiveStatus, string SchemaVersion, int AcceptedRecordCount, string? WorkerStatus, int IsolatedRecordCount, int? ReceiverAcceptedRecordCount, string HandoffStatus, DateTimeOffset ReceivedAt, DateTimeOffset UpdatedAt, string? ErrorCode);