Fix Kafka retry seek, bound buffers, and cut hot-path CPU/memory waste (Phases 41–44).
Stop consumers from committing past failed offsets, harden Rabbit/DataLake/gateway backpressure, dispose JsonDocument/MinIO correctly, and batch expensive DB/HTTP paths. Track progress in docs/performance.
This commit is contained in:
@@ -28,7 +28,7 @@ public sealed class ClinicalSyncBatchConsumer : BackgroundService
|
||||
|
||||
using var connection = factory.CreateConnection("clinical-sync-consumer");
|
||||
using var channel = connection.CreateModel();
|
||||
channel.BasicQos(0, prefetchCount: 5, global: false);
|
||||
channel.BasicQos(0, prefetchCount: 1, global: false);
|
||||
|
||||
var consumer = new AsyncEventingBasicConsumer(channel);
|
||||
consumer.Received += async (_, ea) =>
|
||||
@@ -58,7 +58,7 @@ public sealed class ClinicalSyncBatchConsumer : BackgroundService
|
||||
private async Task HandleMessageAsync(IModel channel, BasicDeliverEventArgs ea, CancellationToken ct)
|
||||
{
|
||||
var payload = Encoding.UTF8.GetString(ea.Body.Span);
|
||||
var doc = JsonDocument.Parse(payload);
|
||||
using var doc = JsonDocument.Parse(payload);
|
||||
var batchId = Guid.Parse(doc.RootElement.GetProperty("batchId").GetString()!);
|
||||
|
||||
await using var scope = _scopes.CreateAsyncScope();
|
||||
|
||||
@@ -74,16 +74,9 @@ public class EsIndexerService : BackgroundService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (result is not null && guard.ShouldSkip(result, ex))
|
||||
{
|
||||
consumer.Commit(result);
|
||||
continue;
|
||||
}
|
||||
|
||||
_logger.LogError(ex,
|
||||
"EsIndexer failed processing topic={Topic} offset={Offset} — will retry",
|
||||
result?.Topic, result?.Offset.Value);
|
||||
await Task.Delay(1000, stoppingToken);
|
||||
await KafkaConsumerRetry.HandleFailureAsync(
|
||||
consumer, result, ex, guard, _logger, nameof(EsIndexerService), stoppingToken,
|
||||
delayMs: 1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ public class GcsScoringService : BackgroundService
|
||||
|
||||
var evt = JsonSerializer.Deserialize<News2ObservationEvent>(
|
||||
result.Message.Value,
|
||||
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
|
||||
ClinicalEventJson.Options)!;
|
||||
|
||||
using var scope = _services.CreateScope();
|
||||
var detector = scope.ServiceProvider.GetRequiredService<GcsDetector>();
|
||||
@@ -76,16 +76,8 @@ public class GcsScoringService : BackgroundService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (result is not null && guard.ShouldSkip(result, ex))
|
||||
{
|
||||
consumer.Commit(result);
|
||||
continue;
|
||||
}
|
||||
|
||||
_logger.LogError(ex,
|
||||
"GcsScoringService failed on topic={Topic} offset={Offset} — will retry",
|
||||
result?.Topic, result?.Offset.Value);
|
||||
await Task.Delay(2000, stoppingToken);
|
||||
await KafkaConsumerRetry.HandleFailureAsync(
|
||||
consumer, result, ex, guard, _logger, nameof(GcsScoringService), stoppingToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ public class News2ScoringService : BackgroundService
|
||||
|
||||
var evt = JsonSerializer.Deserialize<News2ObservationEvent>(
|
||||
result.Message.Value,
|
||||
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
|
||||
ClinicalEventJson.Options)!;
|
||||
|
||||
using var scope = _services.CreateScope();
|
||||
var detector = scope.ServiceProvider.GetRequiredService<News2Detector>();
|
||||
@@ -76,16 +76,8 @@ public class News2ScoringService : BackgroundService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (result is not null && guard.ShouldSkip(result, ex))
|
||||
{
|
||||
consumer.Commit(result);
|
||||
continue;
|
||||
}
|
||||
|
||||
_logger.LogError(ex,
|
||||
"News2ScoringService failed on topic={Topic} offset={Offset} — will retry",
|
||||
result?.Topic, result?.Offset.Value);
|
||||
await Task.Delay(2000, stoppingToken);
|
||||
await KafkaConsumerRetry.HandleFailureAsync(
|
||||
consumer, result, ex, guard, _logger, nameof(News2ScoringService), stoppingToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+11
-7
@@ -2,6 +2,7 @@ using System.Text;
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Minio;
|
||||
using Minio.DataModel.Args;
|
||||
using RabbitMQ.Client;
|
||||
using RabbitMQ.Client.Events;
|
||||
@@ -10,17 +11,20 @@ public sealed class DischargeSummaryWorkerService : BackgroundService
|
||||
{
|
||||
private readonly IOptions<RabbitMqOptions> _rabbitOpts;
|
||||
private readonly IOptions<MinioOptions> _minioOpts;
|
||||
private readonly IMinioClient _minio;
|
||||
private readonly IServiceScopeFactory _scopes;
|
||||
private readonly ILogger<DischargeSummaryWorkerService> _logger;
|
||||
|
||||
public DischargeSummaryWorkerService(
|
||||
IOptions<RabbitMqOptions> rabbitOpts,
|
||||
IOptions<MinioOptions> minioOpts,
|
||||
IMinioClient minio,
|
||||
IServiceScopeFactory scopes,
|
||||
ILogger<DischargeSummaryWorkerService> logger)
|
||||
{
|
||||
_rabbitOpts = rabbitOpts;
|
||||
_minioOpts = minioOpts;
|
||||
_minio = minio;
|
||||
_scopes = scopes;
|
||||
_logger = logger;
|
||||
}
|
||||
@@ -35,7 +39,7 @@ public sealed class DischargeSummaryWorkerService : BackgroundService
|
||||
using var connection = factory.CreateConnection("discharge-summary-worker");
|
||||
using var channel = connection.CreateModel();
|
||||
|
||||
channel.BasicQos(0, prefetchCount: 3, global: false);
|
||||
channel.BasicQos(0, prefetchCount: 1, global: false);
|
||||
|
||||
var consumer = new AsyncEventingBasicConsumer(channel);
|
||||
consumer.Received += async (sender, ea) =>
|
||||
@@ -53,7 +57,7 @@ public sealed class DischargeSummaryWorkerService : BackgroundService
|
||||
private async Task HandleDischargeSummaryAsync(IModel channel, BasicDeliverEventArgs ea, CancellationToken ct)
|
||||
{
|
||||
var payload = Encoding.UTF8.GetString(ea.Body.Span);
|
||||
var doc = JsonDocument.Parse(payload);
|
||||
using var doc = JsonDocument.Parse(payload);
|
||||
var encounterId = Guid.Parse(doc.RootElement.GetProperty("encounterId").GetString()!);
|
||||
|
||||
try
|
||||
@@ -128,22 +132,22 @@ public sealed class DischargeSummaryWorkerService : BackgroundService
|
||||
private async Task UploadToMinioAsync(Guid encounterId, string content, CancellationToken ct)
|
||||
{
|
||||
var mo = _minioOpts.Value;
|
||||
var client = MinioClientFactory.Build(mo);
|
||||
var bucket = mo.BucketName;
|
||||
|
||||
var exists = await client.BucketExistsAsync(
|
||||
var exists = await _minio.BucketExistsAsync(
|
||||
new BucketExistsArgs().WithBucket(bucket), ct);
|
||||
|
||||
if (!exists)
|
||||
await client.MakeBucketAsync(new MakeBucketArgs().WithBucket(bucket), ct);
|
||||
await _minio.MakeBucketAsync(new MakeBucketArgs().WithBucket(bucket), ct);
|
||||
|
||||
var objectKey = $"discharge-summaries/{encounterId}/summary.pdf";
|
||||
var bytes = Encoding.UTF8.GetBytes(content);
|
||||
|
||||
await client.PutObjectAsync(new PutObjectArgs()
|
||||
await using var stream = new MemoryStream(bytes);
|
||||
await _minio.PutObjectAsync(new PutObjectArgs()
|
||||
.WithBucket(bucket)
|
||||
.WithObject(objectKey)
|
||||
.WithStreamData(new MemoryStream(bytes))
|
||||
.WithStreamData(stream)
|
||||
.WithObjectSize(bytes.Length)
|
||||
.WithContentType("text/plain"),
|
||||
ct);
|
||||
|
||||
@@ -34,7 +34,7 @@ public sealed class EscalationWorkerService : BackgroundService
|
||||
using var connection = factory.CreateConnection("escalation-worker");
|
||||
using var channel = connection.CreateModel();
|
||||
|
||||
channel.BasicQos(0, prefetchCount: 5, global: false);
|
||||
channel.BasicQos(0, prefetchCount: 1, global: false);
|
||||
|
||||
var consumer = new AsyncEventingBasicConsumer(channel);
|
||||
consumer.Received += async (sender, ea) =>
|
||||
@@ -52,7 +52,7 @@ public sealed class EscalationWorkerService : BackgroundService
|
||||
private async Task HandleEscalationAsync(IModel channel, BasicDeliverEventArgs ea, CancellationToken ct)
|
||||
{
|
||||
var payload = Encoding.UTF8.GetString(ea.Body.Span);
|
||||
var doc = JsonDocument.Parse(payload);
|
||||
using var doc = JsonDocument.Parse(payload);
|
||||
var alertId = Guid.Parse(doc.RootElement.GetProperty("alertId").GetString()!);
|
||||
var encounterId = Guid.Parse(doc.RootElement.GetProperty("encounterId").GetString()!);
|
||||
|
||||
|
||||
+4
-9
@@ -85,13 +85,8 @@ public sealed class NotificationPublisherService : BackgroundService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (guard.ShouldSkip(result, ex))
|
||||
{
|
||||
consumer.Commit(result);
|
||||
continue;
|
||||
}
|
||||
|
||||
_logger.LogError(ex, "NotificationPublisher failed to process message from {Topic} — will retry", result.Topic);
|
||||
await KafkaConsumerRetry.HandleFailureAsync(
|
||||
consumer, result, ex, guard, _logger, nameof(NotificationPublisherService), stoppingToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,7 +99,7 @@ public sealed class NotificationPublisherService : BackgroundService
|
||||
private Task HandleAlertGeneratedAsync(
|
||||
IModel chan, IBasicProperties props, string payload, CancellationToken ct)
|
||||
{
|
||||
var doc = JsonDocument.Parse(payload);
|
||||
using var doc = JsonDocument.Parse(payload);
|
||||
var severity = doc.RootElement.GetProperty("severity").GetString();
|
||||
|
||||
if (!string.Equals(severity, "Critical", StringComparison.OrdinalIgnoreCase))
|
||||
@@ -142,7 +137,7 @@ public sealed class NotificationPublisherService : BackgroundService
|
||||
private Task HandleEncounterStatusChangedAsync(
|
||||
IModel chan, IBasicProperties props, string payload, CancellationToken ct)
|
||||
{
|
||||
var doc = JsonDocument.Parse(payload);
|
||||
using var doc = JsonDocument.Parse(payload);
|
||||
var newStatus = doc.RootElement.GetProperty("newStatus").GetString();
|
||||
|
||||
if (!string.Equals(newStatus, "Discharged", StringComparison.OrdinalIgnoreCase))
|
||||
|
||||
@@ -69,7 +69,7 @@ public sealed class PagingWorkerService : BackgroundService
|
||||
{
|
||||
var o = _opts.Value;
|
||||
var payload = Encoding.UTF8.GetString(ea.Body.Span);
|
||||
var doc = JsonDocument.Parse(payload);
|
||||
using var doc = JsonDocument.Parse(payload);
|
||||
var alertId = Guid.Parse(doc.RootElement.GetProperty("alertId").GetString()!);
|
||||
var encounterId = doc.RootElement.GetProperty("encounterId").GetString();
|
||||
var details = doc.RootElement.TryGetProperty("details", out var d) ? d.GetString() : null;
|
||||
@@ -84,7 +84,7 @@ public sealed class PagingWorkerService : BackgroundService
|
||||
|
||||
while (DateTimeOffset.UtcNow < deadline && !ct.IsCancellationRequested)
|
||||
{
|
||||
await Task.Delay(2_000, ct);
|
||||
await Task.Delay(5_000, ct);
|
||||
|
||||
var acknowledged = await IsAlertAcknowledgedAsync(alertId, ct);
|
||||
if (acknowledged)
|
||||
|
||||
@@ -2,6 +2,8 @@ using Microsoft.EntityFrameworkCore;
|
||||
|
||||
public class PatientPhiMigrationService : IHostedService
|
||||
{
|
||||
private const int BatchSize = 500;
|
||||
|
||||
private readonly IServiceProvider _services;
|
||||
private readonly ILogger<PatientPhiMigrationService> _logger;
|
||||
|
||||
@@ -19,26 +21,47 @@ public class PatientPhiMigrationService : IHostedService
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
var crypto = scope.ServiceProvider.GetRequiredService<IPhiEncryptionService>();
|
||||
|
||||
var patients = await db.Patients.ToListAsync(ct);
|
||||
var migrated = 0;
|
||||
var totalMigrated = 0;
|
||||
Guid? afterId = null;
|
||||
|
||||
foreach (var patient in patients)
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
if (patient.NameSearchToken is not null && crypto.IsEncrypted(patient.FirstName))
|
||||
continue;
|
||||
IQueryable<Patient> query = db.Patients.OrderBy(p => p.Id);
|
||||
if (afterId is Guid cursor)
|
||||
query = query.Where(p => p.Id.CompareTo(cursor) > 0);
|
||||
|
||||
patient.NameSearchToken = crypto.ComputeNameSearchToken(
|
||||
patient.FirstName, patient.LastName);
|
||||
migrated++;
|
||||
var batch = await query.Take(BatchSize).ToListAsync(ct);
|
||||
if (batch.Count == 0)
|
||||
break;
|
||||
|
||||
afterId = batch[^1].Id;
|
||||
var migrated = 0;
|
||||
|
||||
foreach (var patient in batch)
|
||||
{
|
||||
if (patient.NameSearchToken is not null && crypto.IsEncrypted(patient.FirstName))
|
||||
continue;
|
||||
|
||||
patient.NameSearchToken = crypto.ComputeNameSearchToken(
|
||||
patient.FirstName, patient.LastName);
|
||||
migrated++;
|
||||
}
|
||||
|
||||
if (migrated > 0)
|
||||
{
|
||||
await db.SaveChangesAsync(ct);
|
||||
totalMigrated += migrated;
|
||||
}
|
||||
|
||||
db.ChangeTracker.Clear();
|
||||
}
|
||||
|
||||
if (migrated > 0)
|
||||
if (totalMigrated > 0)
|
||||
{
|
||||
await db.SaveChangesAsync(ct);
|
||||
_logger.LogInformation(
|
||||
"PHI migration: updated {Count} patient search tokens", migrated);
|
||||
"PHI migration: updated {Count} patient search tokens", totalMigrated);
|
||||
}
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
}
|
||||
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
}
|
||||
|
||||
+24
-13
@@ -55,14 +55,21 @@ public sealed class DisconnectedMonitorsCheck
|
||||
return 0;
|
||||
}
|
||||
|
||||
var inserted = 0;
|
||||
var encounterIds = stale.Select(e => e.EncounterId).ToList();
|
||||
var alreadyOpen = (await _db.ReconciliationAlerts
|
||||
.AsNoTracking()
|
||||
.Where(r => r.CheckType == CheckType
|
||||
&& r.ResolvedAt == null
|
||||
&& r.EncounterId != null
|
||||
&& encounterIds.Contains(r.EncounterId.Value))
|
||||
.Select(r => r.EncounterId!.Value)
|
||||
.ToListAsync(ct))
|
||||
.ToHashSet();
|
||||
|
||||
var created = new List<ReconciliationAlert>();
|
||||
foreach (var enc in stale)
|
||||
{
|
||||
var alreadyOpen = await _db.ReconciliationAlerts
|
||||
.AnyAsync(r => r.CheckType == CheckType
|
||||
&& r.EncounterId == enc.EncounterId
|
||||
&& r.ResolvedAt == null, ct);
|
||||
if (alreadyOpen) continue;
|
||||
if (alreadyOpen.Contains(enc.EncounterId)) continue;
|
||||
|
||||
var lastObs = enc.LastObservationAt.HasValue
|
||||
? $"last observation {enc.LastObservationAt:u}"
|
||||
@@ -73,7 +80,7 @@ public sealed class DisconnectedMonitorsCheck
|
||||
var rec = new ReconciliationAlert
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
CheckType = CheckType, // ReconciliationCheckType enum
|
||||
CheckType = CheckType,
|
||||
EncounterId = enc.EncounterId,
|
||||
PatientId = enc.PatientId,
|
||||
Details = details,
|
||||
@@ -81,16 +88,20 @@ public sealed class DisconnectedMonitorsCheck
|
||||
};
|
||||
|
||||
_db.ReconciliationAlerts.Add(rec);
|
||||
await _db.SaveChangesAsync(ct);
|
||||
await _publisher.PublishAsync(rec, ct);
|
||||
created.Add(rec);
|
||||
|
||||
_logger.LogWarning(
|
||||
"[RECONCILIATION] {CheckType} — encounter {EncounterId}: {LastObs}",
|
||||
CheckType, enc.EncounterId, lastObs);
|
||||
|
||||
inserted++;
|
||||
}
|
||||
|
||||
return inserted;
|
||||
if (created.Count > 0)
|
||||
{
|
||||
await _db.SaveChangesAsync(ct);
|
||||
foreach (var rec in created)
|
||||
await _publisher.PublishAsync(rec, ct);
|
||||
}
|
||||
|
||||
return created.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,14 +52,21 @@ public sealed class PendingOrdersCheck
|
||||
.GroupBy(o => new { o.EncounterId, o.PatientId })
|
||||
.ToList();
|
||||
|
||||
var inserted = 0;
|
||||
var encounterIds = byEncounter.Select(g => g.Key.EncounterId).ToList();
|
||||
var alreadyOpen = (await _db.ReconciliationAlerts
|
||||
.AsNoTracking()
|
||||
.Where(r => r.CheckType == CheckType
|
||||
&& r.ResolvedAt == null
|
||||
&& r.EncounterId != null
|
||||
&& encounterIds.Contains(r.EncounterId.Value))
|
||||
.Select(r => r.EncounterId!.Value)
|
||||
.ToListAsync(ct))
|
||||
.ToHashSet();
|
||||
|
||||
var created = new List<ReconciliationAlert>();
|
||||
foreach (var group in byEncounter)
|
||||
{
|
||||
var alreadyOpen = await _db.ReconciliationAlerts
|
||||
.AnyAsync(r => r.CheckType == CheckType
|
||||
&& r.EncounterId == group.Key.EncounterId
|
||||
&& r.ResolvedAt == null, ct);
|
||||
if (alreadyOpen) continue;
|
||||
if (alreadyOpen.Contains(group.Key.EncounterId)) continue;
|
||||
|
||||
var lines = group.Select(o =>
|
||||
$" [{o.OrderType.ToDbString()}] {o.Description} (ordered {o.OrderedAt:u}, "
|
||||
@@ -70,7 +77,7 @@ public sealed class PendingOrdersCheck
|
||||
var rec = new ReconciliationAlert
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
CheckType = CheckType, // ReconciliationCheckType enum
|
||||
CheckType = CheckType,
|
||||
EncounterId = group.Key.EncounterId,
|
||||
PatientId = group.Key.PatientId,
|
||||
Details = details,
|
||||
@@ -78,16 +85,20 @@ public sealed class PendingOrdersCheck
|
||||
};
|
||||
|
||||
_db.ReconciliationAlerts.Add(rec);
|
||||
await _db.SaveChangesAsync(ct);
|
||||
await _publisher.PublishAsync(rec, ct);
|
||||
created.Add(rec);
|
||||
|
||||
_logger.LogWarning(
|
||||
"[RECONCILIATION] {CheckType} — encounter {EncounterId}: {Count} stale order(s)",
|
||||
CheckType, group.Key.EncounterId, group.Count());
|
||||
|
||||
inserted++;
|
||||
}
|
||||
|
||||
return inserted;
|
||||
if (created.Count > 0)
|
||||
{
|
||||
await _db.SaveChangesAsync(ct);
|
||||
foreach (var rec in created)
|
||||
await _publisher.PublishAsync(rec, ct);
|
||||
}
|
||||
|
||||
return created.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+24
-17
@@ -27,7 +27,6 @@ public sealed class UnacknowledgedAlertsCheck
|
||||
var cutoff = DateTimeOffset.UtcNow
|
||||
.AddMinutes(-_opts.UnacknowledgedAlertThresholdMinutes);
|
||||
|
||||
// Load all stale critical alerts, grouped by encounter.
|
||||
var staleAlerts = await _db.ClinicalAlerts
|
||||
.Where(a => a.Severity == AlertSeverity.Critical
|
||||
&& a.Status == AlertStatus.Open
|
||||
@@ -41,21 +40,25 @@ public sealed class UnacknowledgedAlertsCheck
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Group by encounter so one reconciliation_alert covers all alerts in that encounter.
|
||||
var byEncounter = staleAlerts
|
||||
.GroupBy(a => new { a.EncounterId, a.PatientId })
|
||||
.ToList();
|
||||
|
||||
var inserted = 0;
|
||||
var encounterIds = byEncounter.Select(g => g.Key.EncounterId).ToList();
|
||||
var alreadyOpen = (await _db.ReconciliationAlerts
|
||||
.AsNoTracking()
|
||||
.Where(r => r.CheckType == CheckType
|
||||
&& r.ResolvedAt == null
|
||||
&& r.EncounterId != null
|
||||
&& encounterIds.Contains(r.EncounterId.Value))
|
||||
.Select(r => r.EncounterId!.Value)
|
||||
.ToListAsync(ct))
|
||||
.ToHashSet();
|
||||
|
||||
var created = new List<ReconciliationAlert>();
|
||||
foreach (var group in byEncounter)
|
||||
{
|
||||
// Deduplication: skip if an open reconciliation_alert already exists
|
||||
// for this check type and encounter (partial index makes this fast).
|
||||
var alreadyOpen = await _db.ReconciliationAlerts
|
||||
.AnyAsync(r => r.CheckType == CheckType
|
||||
&& r.EncounterId == group.Key.EncounterId
|
||||
&& r.ResolvedAt == null, ct);
|
||||
if (alreadyOpen) continue;
|
||||
if (alreadyOpen.Contains(group.Key.EncounterId)) continue;
|
||||
|
||||
var alertIds = group.Select(a => a.Id).ToList();
|
||||
var oldest = group.Min(a => a.TriggeredAt);
|
||||
@@ -66,7 +69,7 @@ public sealed class UnacknowledgedAlertsCheck
|
||||
var rec = new ReconciliationAlert
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
CheckType = CheckType, // ReconciliationCheckType enum
|
||||
CheckType = CheckType,
|
||||
EncounterId = group.Key.EncounterId,
|
||||
PatientId = group.Key.PatientId,
|
||||
Details = details,
|
||||
@@ -74,16 +77,20 @@ public sealed class UnacknowledgedAlertsCheck
|
||||
};
|
||||
|
||||
_db.ReconciliationAlerts.Add(rec);
|
||||
await _db.SaveChangesAsync(ct);
|
||||
await _publisher.PublishAsync(rec, ct);
|
||||
created.Add(rec);
|
||||
|
||||
_logger.LogWarning(
|
||||
"[RECONCILIATION] {CheckType} — encounter {EncounterId}: {Details}",
|
||||
CheckType, group.Key.EncounterId, details);
|
||||
|
||||
inserted++;
|
||||
}
|
||||
|
||||
return inserted;
|
||||
if (created.Count > 0)
|
||||
{
|
||||
await _db.SaveChangesAsync(ct);
|
||||
foreach (var rec in created)
|
||||
await _publisher.PublishAsync(rec, ct);
|
||||
}
|
||||
|
||||
return created.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,16 +78,8 @@ public class SepsisEngineService : BackgroundService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (result is not null && guard.ShouldSkip(result, ex))
|
||||
{
|
||||
consumer.Commit(result);
|
||||
continue;
|
||||
}
|
||||
|
||||
_logger.LogError(ex,
|
||||
"SepsisEngine failed on topic={Topic} offset={Offset} — will retry",
|
||||
result?.Topic, result?.Offset.Value);
|
||||
await Task.Delay(2000, stoppingToken);
|
||||
await KafkaConsumerRetry.HandleFailureAsync(
|
||||
consumer, result, ex, guard, _logger, nameof(SepsisEngineService), stoppingToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ public class SofaScoringService : BackgroundService
|
||||
{
|
||||
var gcsEvt = JsonSerializer.Deserialize<GcsScoredEvent>(
|
||||
result.Message.Value,
|
||||
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
|
||||
ClinicalEventJson.Options)!;
|
||||
|
||||
var outcome = await detector.ProcessGcsScoredAsync(
|
||||
gcsEvt.EncounterId, gcsEvt.PatientId, stoppingToken);
|
||||
@@ -73,7 +73,7 @@ public class SofaScoringService : BackgroundService
|
||||
{
|
||||
var evt = JsonSerializer.Deserialize<News2ObservationEvent>(
|
||||
result.Message.Value,
|
||||
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
|
||||
ClinicalEventJson.Options)!;
|
||||
|
||||
var outcome = await detector.ProcessObservationAsync(
|
||||
evt.EncounterId,
|
||||
@@ -102,16 +102,8 @@ public class SofaScoringService : BackgroundService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (result is not null && guard.ShouldSkip(result, ex))
|
||||
{
|
||||
consumer.Commit(result);
|
||||
continue;
|
||||
}
|
||||
|
||||
_logger.LogError(ex,
|
||||
"SofaScoringService failed on topic={Topic} offset={Offset} — will retry",
|
||||
result?.Topic, result?.Offset.Value);
|
||||
await Task.Delay(2000, stoppingToken);
|
||||
await KafkaConsumerRetry.HandleFailureAsync(
|
||||
consumer, result, ex, guard, _logger, nameof(SofaScoringService), stoppingToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ public class ThresholdCacheLoader : IHostedService
|
||||
{
|
||||
var cache = _redis.GetDatabase();
|
||||
var batch = cache.CreateBatch();
|
||||
var setTasks = new List<Task>(thresholds.Count);
|
||||
|
||||
foreach (var t in thresholds)
|
||||
{
|
||||
@@ -45,10 +46,11 @@ public class ThresholdCacheLoader : IHostedService
|
||||
t.WarningHigh,
|
||||
t.CriticalHigh
|
||||
});
|
||||
_ = batch.StringSetAsync($"threshold:{t.ObservationCode}", json);
|
||||
setTasks.Add(batch.StringSetAsync($"threshold:{t.ObservationCode}", json));
|
||||
}
|
||||
|
||||
batch.Execute();
|
||||
await Task.WhenAll(setTasks);
|
||||
_logger.LogInformation("Loaded {Count} alert thresholds into Redis cache", thresholds.Count);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ public class TrendAnalyzerService : BackgroundService
|
||||
|
||||
var evt = JsonSerializer.Deserialize<TrendObservationEvent>(
|
||||
result.Message.Value,
|
||||
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
|
||||
ClinicalEventJson.Options)!;
|
||||
|
||||
using var scope = _services.CreateScope();
|
||||
var detector = scope.ServiceProvider.GetRequiredService<TrendDetector>();
|
||||
@@ -77,16 +77,8 @@ public class TrendAnalyzerService : BackgroundService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (result is not null && guard.ShouldSkip(result, ex))
|
||||
{
|
||||
consumer.Commit(result);
|
||||
continue;
|
||||
}
|
||||
|
||||
_logger.LogError(ex,
|
||||
"TrendAnalyzerService failed on topic={Topic} offset={Offset} — will retry",
|
||||
result?.Topic, result?.Offset.Value);
|
||||
await Task.Delay(2000, stoppingToken);
|
||||
await KafkaConsumerRetry.HandleFailureAsync(
|
||||
consumer, result, ex, guard, _logger, nameof(TrendAnalyzerService), stoppingToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ public class WarningAlertService : BackgroundService
|
||||
|
||||
var evt = JsonSerializer.Deserialize<WarningObservationEvent>(
|
||||
result.Message.Value,
|
||||
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
|
||||
ClinicalEventJson.Options)!;
|
||||
|
||||
using var scope = _services.CreateScope();
|
||||
var evaluator = scope.ServiceProvider.GetRequiredService<WarningEvaluator>();
|
||||
@@ -68,16 +68,8 @@ public class WarningAlertService : BackgroundService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (result is not null && guard.ShouldSkip(result, ex))
|
||||
{
|
||||
consumer.Commit(result);
|
||||
continue;
|
||||
}
|
||||
|
||||
_logger.LogError(ex,
|
||||
"WarningAlertService failed on topic={Topic} offset={Offset} — will retry",
|
||||
result?.Topic, result?.Offset.Value);
|
||||
await Task.Delay(2000, stoppingToken);
|
||||
await KafkaConsumerRetry.HandleFailureAsync(
|
||||
consumer, result, ex, guard, _logger, nameof(WarningAlertService), stoppingToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user