MdpIngestBatchStatusService.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System.Globalization;
  2. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  3. public sealed class MdpIngestBatchStatusService(ISqlSugarClient db) : ITransient
  4. {
  5. public Task<MdpIngestBatchStatus?> FindAsync(MdpIngestSubmission caller, Guid batchId, CancellationToken cancellationToken) =>
  6. FindAsync(new BatchReadScope(batchId.ToString("D"), caller.TenantId, caller.FactoryId,
  7. caller.ConfigurationFactoryId ?? caller.FactoryId, caller.SourceId, caller.DatasetKey,
  8. caller.GrantId, caller.AccessKeyHash, caller.ConfigurationFactoryId.HasValue, null, null), cancellationToken);
  9. internal Task<MdpIngestBatchStatus?> FindForOperatorAsync(long tenantId, long configurationFactory, long datasetId,
  10. IReadOnlyCollection<long> authorizedFactories, Guid batchId, CancellationToken cancellationToken) =>
  11. FindAsync(new BatchReadScope(batchId.ToString("D"), tenantId, null, configurationFactory, null, null, null, null, false,
  12. datasetId, string.Join(',', authorizedFactories.Select(factory => factory.ToString(CultureInfo.InvariantCulture)))),
  13. cancellationToken);
  14. private async Task<MdpIngestBatchStatus?> FindAsync(BatchReadScope scope, CancellationToken cancellationToken)
  15. {
  16. cancellationToken.ThrowIfCancellationRequested();
  17. using var connection = MdpIngestDatabase.Open(db);
  18. var row = await connection.Ado.SqlQuerySingleAsync<BatchStatusRow>("""
  19. SELECT b.accepted_record_count AS AcceptedCount, b.source_schema_version AS SchemaVersion,
  20. b.received_at AS ReceivedAt, t.status AS WorkerStatus,
  21. COALESCE(t.last_error_code,CASE WHEN c.state='REJECTED' THEN c.diagnostic END) AS ErrorCode,
  22. c.state AS CaptureState,
  23. 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,
  24. dispatch.status AS DispatchStatus,
  25. (SELECT COUNT(DISTINCT q.raw_event_id) FROM mdp_ingest_worker_quarantine q
  26. WHERE q.batch_id=b.batch_id AND q.tenant_id=b.tenant_id AND q.factory_id=b.factory_id
  27. AND q.source_id=b.source_id AND q.dataset_id=b.dataset_id) AS IsolatedCount,
  28. e.accepted_count AS ReceiverAcceptedCount
  29. FROM mdp_ingest_raw_batch b
  30. JOIN mdp_ingest_dataset d ON d.id=b.dataset_id AND d.tenant_id=b.tenant_id AND d.factory_id=@ConfigurationFactory
  31. JOIN mdp_purchase_active_factory f ON f.tenant_id=b.tenant_id AND f.factory_id=b.factory_id
  32. LEFT JOIN mdp_connector_api_pull_capture c ON c.batch_id=b.batch_id
  33. LEFT JOIN mdp_ingest_receive_task t ON t.batch_id=b.batch_id AND t.tenant_id=b.tenant_id
  34. AND t.factory_id=b.factory_id AND t.source_id=b.source_id AND t.dataset_id=b.dataset_id
  35. LEFT JOIN mdp_ingest_release_batch e ON e.batch_id=b.batch_id AND e.tenant_id=b.tenant_id
  36. AND e.factory_id=b.factory_id AND e.source_id=b.source_id AND e.dataset_id=b.dataset_id
  37. LEFT JOIN mdp_ingest_purchase_dispatch dispatch ON dispatch.batch_id=b.batch_id AND dispatch.tenant_id=b.tenant_id
  38. AND dispatch.factory_id=b.factory_id AND dispatch.source_id=b.source_id AND dispatch.dataset_id=b.dataset_id
  39. WHERE b.batch_id=@BatchId AND b.tenant_id=@TenantId
  40. AND ((b.dataset_id=@OperatorDatasetId AND FIND_IN_SET(CAST(b.factory_id AS CHAR), @AuthorizedFactories) > 0)
  41. 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
  42. AND EXISTS (SELECT 1 FROM mdp_ingest_access_grant g
  43. WHERE g.id=@GrantId AND g.tenant_id=b.tenant_id AND g.factory_id=d.factory_id
  44. AND g.source_id=b.source_id AND g.dataset_key=d.dataset_key AND g.enabled=1
  45. AND g.use_batch_factory=@FromBatch AND g.access_key_hash=@AccessKeyHash)))
  46. """, new
  47. {
  48. scope.BatchId, scope.TenantId, scope.FactoryId, scope.ConfigurationFactory, scope.SourceId,
  49. scope.DatasetKey, scope.GrantId, scope.AccessKeyHash, scope.FromBatch, scope.OperatorDatasetId, scope.AuthorizedFactories
  50. });
  51. cancellationToken.ThrowIfCancellationRequested();
  52. if (row is null)
  53. return null;
  54. if (row.CaptureState is { } state && state != "ACCEPTED")
  55. return new MdpIngestBatchStatus(Guid.Parse(scope.BatchId), state.ToLowerInvariant(), row.SchemaVersion, 0,
  56. null, 0, null, "not_started", Utc(row.ReceivedAt), Utc(row.UpdatedAt), row.ErrorCode);
  57. var receiverAccepted = row.ReceiverAcceptedCount;
  58. if (receiverAccepted is null && row.DispatchStatus == "DONE")
  59. receiverAccepted = row.AcceptedCount - row.IsolatedCount;
  60. return new MdpIngestBatchStatus(Guid.Parse(scope.BatchId), "accepted", row.SchemaVersion, row.AcceptedCount,
  61. row.WorkerStatus, row.IsolatedCount, receiverAccepted,
  62. receiverAccepted.HasValue ? "confirmed" : row.DispatchStatus switch
  63. {
  64. "FAILED" => "failed",
  65. "READY" => "awaiting_delivery",
  66. _ => "pending"
  67. },
  68. Utc(row.ReceivedAt), Utc(row.UpdatedAt), row.ErrorCode);
  69. }
  70. private static DateTimeOffset Utc(DateTime value) => new(DateTime.SpecifyKind(value, DateTimeKind.Utc));
  71. private sealed record BatchReadScope(string BatchId, long TenantId, long? FactoryId, long ConfigurationFactory,
  72. long? SourceId, string? DatasetKey, long? GrantId, string? AccessKeyHash, bool FromBatch, long? OperatorDatasetId, string? AuthorizedFactories);
  73. private sealed class BatchStatusRow
  74. {
  75. public int AcceptedCount { get; set; }
  76. public string? CaptureState { get; set; }
  77. public string SchemaVersion { get; set; } = "";
  78. public DateTime ReceivedAt { get; set; }
  79. public string? WorkerStatus { get; set; }
  80. public string? ErrorCode { get; set; }
  81. public DateTime UpdatedAt { get; set; }
  82. public string? DispatchStatus { get; set; }
  83. public int? ReceiverAcceptedCount { get; set; }
  84. public int IsolatedCount { get; set; }
  85. }
  86. }
  87. public sealed record MdpIngestBatchStatus(Guid BatchId, string ReceiveStatus, string SchemaVersion, int AcceptedRecordCount,
  88. string? WorkerStatus, int IsolatedRecordCount, int? ReceiverAcceptedRecordCount, string HandoffStatus,
  89. DateTimeOffset ReceivedAt, DateTimeOffset UpdatedAt, string? ErrorCode);