Fix Kafka retry seek, bound buffers, and cut hot-path CPU/memory waste (Phases 41–44).
CI / changes (push) Successful in 17s
CI / frontend (push) Skipped
CI / backend (push) Successful in 15m10s

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:
2026-11-30 21:32:43 +08:00
parent 1c1065938f
commit 68a2ab3204
54 changed files with 959 additions and 311 deletions
@@ -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);
}
}
}
@@ -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()!);
@@ -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;
}
@@ -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;
}
}
}
@@ -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);
}
}
}
@@ -9,7 +9,8 @@ public static class DataLakeEventParser
{
public static ObservationRow ParseObservationRow(string payload, long offset, int partition)
{
var d = JsonDocument.Parse(payload).RootElement;
using var doc = JsonDocument.Parse(payload);
var d = doc.RootElement;
var encounterId = GetString(d, "encounterId");
var observationId = GetString(d, "observationId");
if (string.IsNullOrEmpty(observationId))
@@ -31,7 +32,8 @@ public static class DataLakeEventParser
public static AlertRow ParseAlertRow(string payload, long offset, int partition)
{
var d = JsonDocument.Parse(payload).RootElement;
using var doc = JsonDocument.Parse(payload);
var d = doc.RootElement;
return new AlertRow(
AlertId : GetString(d, "alertId"),
EncounterId : GetString(d, "encounterId"),
@@ -47,7 +49,8 @@ public static class DataLakeEventParser
public static EncounterStatusRow ParseEncounterRow(string payload, long offset, int partition)
{
var d = JsonDocument.Parse(payload).RootElement;
using var doc = JsonDocument.Parse(payload);
var d = doc.RootElement;
return new EncounterStatusRow(
EncounterId : GetString(d, "encounterId"),
PatientId : GetString(d, "patientId"),
@@ -62,7 +65,7 @@ public static class DataLakeEventParser
{
try
{
var doc = JsonDocument.Parse(payload);
using var doc = JsonDocument.Parse(payload);
var ts = topic switch
{
var t when t == topics.ObservationRecorded => GetTimestamp(doc.RootElement, "recordedAt"),
@@ -11,6 +11,13 @@ public sealed class DataLakeOptions
// Production: 300 seconds (5 minutes). Tests: 10 seconds.
public int FlushIntervalSeconds { get; init; } = 300;
/// <summary>
/// Hard cap on in-memory buffered events across all partitions. When reached,
/// consume seeks back and pauses until a flush frees space (prevents OOM when
/// MinIO is down while Kafka keeps delivering).
/// </summary>
public int MaxBufferedEvents { get; init; } = 50_000;
// MinIO bucket. The discharge summary worker from Phase 6 uses the same bucket
// under a different prefix — all VigilCare data stays in one bucket.
public string BucketName { get; init; } = "vigilcare";
@@ -1,6 +1,7 @@
using System.Text.Json;
using Confluent.Kafka;
using Microsoft.Extensions.Options;
using Minio;
using Minio.DataModel.Args;
public sealed class DataLakeWriterService : BackgroundService
@@ -8,6 +9,7 @@ public sealed class DataLakeWriterService : BackgroundService
private readonly KafkaOptions _kafkaOptions;
private readonly DataLakeOptions _opts;
private readonly MinioOptions _minioOpts;
private readonly IMinioClient _minio;
private readonly ILogger<DataLakeWriterService> _logger;
// Buffer key: identifies one Parquet file-to-be.
@@ -24,11 +26,13 @@ public sealed class DataLakeWriterService : BackgroundService
IOptions<KafkaOptions> kafkaOptions,
IOptions<DataLakeOptions> opts,
IOptions<MinioOptions> minioOpts,
IMinioClient minio,
ILogger<DataLakeWriterService> logger)
{
_kafkaOptions = kafkaOptions.Value;
_opts = opts.Value;
_minioOpts = minioOpts.Value;
_minio = minio;
_logger = logger;
}
@@ -51,8 +55,8 @@ public sealed class DataLakeWriterService : BackgroundService
});
_logger.LogInformation(
"DataLakeWriterService started. FlushCount={FlushCount} FlushIntervalSeconds={FlushInterval}",
_opts.FlushCount, _opts.FlushIntervalSeconds);
"DataLakeWriterService started. FlushCount={FlushCount} FlushIntervalSeconds={FlushInterval} MaxBufferedEvents={MaxBuffered}",
_opts.FlushCount, _opts.FlushIntervalSeconds, _opts.MaxBufferedEvents);
var lastFlush = DateTimeOffset.UtcNow;
@@ -72,7 +76,24 @@ public sealed class DataLakeWriterService : BackgroundService
}
if (result is not null)
{
var totalBefore = _buffer.Values.Sum(v => v.Count);
if (totalBefore >= _opts.MaxBufferedEvents)
{
// Consume advanced the position — seek back so we do not drop the message.
consumer.Seek(result.TopicPartitionOffset);
_logger.LogCritical(
"[DATA-LAKE] Buffer at cap {Cap} — pausing consume until flush frees space",
_opts.MaxBufferedEvents);
await FlushAsync(consumer, ct);
lastFlush = DateTimeOffset.UtcNow;
if (_buffer.Values.Sum(v => v.Count) >= _opts.MaxBufferedEvents)
await Task.Delay(5_000, ct);
continue;
}
AddToBuffer(result);
}
var totalBuffered = _buffer.Values.Sum(v => v.Count);
var shouldFlushCount = totalBuffered >= _opts.FlushCount;
@@ -245,18 +266,18 @@ public sealed class DataLakeWriterService : BackgroundService
private async Task UploadToMinioAsync(string objectKey, byte[] bytes, CancellationToken ct)
{
var client = MinioClientFactory.Build(_minioOpts);
var bucket = _opts.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);
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("application/octet-stream"),
ct);
@@ -0,0 +1,13 @@
using System.Text.Json;
/// <summary>
/// Shared JSON options for Kafka clinical event deserialization.
/// <see cref="JsonSerializerOptions"/> construction is expensive — reuse one instance.
/// </summary>
public static class ClinicalEventJson
{
public static readonly JsonSerializerOptions Options = new()
{
PropertyNameCaseInsensitive = true
};
}
@@ -0,0 +1,55 @@
using Confluent.Kafka;
/// <summary>
/// Shared transient-failure handling for Kafka consumers that use
/// <see cref="PoisonPillGuard"/>. After <c>Consume</c>, the client position
/// advances; without <c>Seek</c>, the next successful <c>Commit</c> would skip
/// the failed offset. This helper seeks back before delaying so retries truly
/// reprocess the same message.
/// </summary>
public static class KafkaConsumerRetry
{
public static Task HandleFailureAsync(
IConsumer<string, string> consumer,
ConsumeResult<string, string>? result,
Exception ex,
PoisonPillGuard guard,
ILogger logger,
string serviceName,
CancellationToken ct,
int delayMs = 2000) =>
HandleFailureAsync(
seek: tpo => consumer.Seek(tpo),
commit: r => consumer.Commit(r),
result, ex, guard, logger, serviceName, ct, delayMs);
/// <summary>
/// Testable overload — production code should prefer the <see cref="IConsumer{TKey,TValue}"/> overload.
/// </summary>
public static async Task HandleFailureAsync(
Action<TopicPartitionOffset> seek,
Action<ConsumeResult<string, string>> commit,
ConsumeResult<string, string>? result,
Exception ex,
PoisonPillGuard guard,
ILogger logger,
string serviceName,
CancellationToken ct,
int delayMs = 2000)
{
if (result is not null && guard.ShouldSkip(result, ex))
{
commit(result);
return;
}
logger.LogError(ex,
"{Service} failed on topic={Topic} offset={Offset} — will retry",
serviceName, result?.Topic, result?.Offset.Value);
if (result is not null)
seek(result.TopicPartitionOffset);
await Task.Delay(delayMs, ct);
}
}
+4
View File
@@ -1,6 +1,7 @@
using Elastic.Clients.Elasticsearch;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Minio;
using Prometheus;
using Serilog;
using StackExchange.Redis;
@@ -16,6 +17,7 @@ using Microsoft.AspNetCore.Authorization;
using System.Text;
using Microsoft.OpenApi;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Options;
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
@@ -114,6 +116,8 @@ try
builder.Configuration.GetSection(RabbitMqOptions.Section));
builder.Services.Configure<MinioOptions>(
builder.Configuration.GetSection(MinioOptions.Section));
builder.Services.AddSingleton<IMinioClient>(sp =>
MinioClientFactory.Build(sp.GetRequiredService<IOptions<MinioOptions>>().Value));
builder.Services.AddSingleton<RabbitMqTopologyProvisioner>();
builder.Services.AddHostedService(sp => sp.GetRequiredService<RabbitMqTopologyProvisioner>());
@@ -8,11 +8,16 @@ public sealed class DischargeSummaryService : IDischargeSummaryService
{
private readonly AppDbContext _db;
private readonly MinioOptions _minioOpts;
private readonly IMinioClient _minio;
public DischargeSummaryService(AppDbContext db, IOptions<MinioOptions> minioOpts)
public DischargeSummaryService(
AppDbContext db,
IOptions<MinioOptions> minioOpts,
IMinioClient minio)
{
_db = db;
_minioOpts = minioOpts.Value;
_minio = minio;
}
public async Task<DischargeSummaryInfo> GetInfoAsync(Guid encounterId, CancellationToken ct = default)
@@ -68,12 +73,11 @@ public sealed class DischargeSummaryService : IDischargeSummaryService
"DISCHARGE_SUMMARY_PENDING");
}
var client = MinioClientFactory.Build(_minioOpts);
var bucket = _minioOpts.BucketName;
var objectKey = ObjectKey(encounterId);
var ms = new MemoryStream();
await client.GetObjectAsync(new GetObjectArgs()
await _minio.GetObjectAsync(new GetObjectArgs()
.WithBucket(bucket)
.WithObject(objectKey)
.WithCallbackStream(stream => stream.CopyTo(ms)), ct);
@@ -84,13 +88,12 @@ public sealed class DischargeSummaryService : IDischargeSummaryService
private async Task<bool> ObjectExistsAsync(Guid encounterId, CancellationToken ct)
{
var client = MinioClientFactory.Build(_minioOpts);
var bucket = _minioOpts.BucketName;
var objectKey = ObjectKey(encounterId);
try
{
await client.StatObjectAsync(new StatObjectArgs()
await _minio.StatObjectAsync(new StatObjectArgs()
.WithBucket(bucket)
.WithObject(objectKey), ct);
return true;
@@ -74,13 +74,12 @@ public class EncounterService : IEncounterService
var encounterIds = encounters.Select(e => e.Id).ToList();
var news2ByEncounter = (await _db.News2Scores
var news2ByEncounter = await _db.News2Scores
.AsNoTracking()
.Where(s => encounterIds.Contains(s.EncounterId))
.OrderByDescending(s => s.CalculatedAt)
.ToListAsync())
.GroupBy(s => s.EncounterId)
.ToDictionary(g => g.Key, g => g.First());
.Select(g => g.OrderByDescending(s => s.CalculatedAt).First())
.ToDictionaryAsync(s => s.EncounterId);
var openAlertCounts = await _db.ClinicalAlerts
.AsNoTracking()
@@ -89,29 +88,26 @@ public class EncounterService : IEncounterService
.Select(g => new { EncounterId = g.Key, Count = g.Count() })
.ToDictionaryAsync(x => x.EncounterId, x => x.Count);
var bundlesByEncounter = (await _db.SepsisBundles
var bundlesByEncounter = await _db.SepsisBundles
.AsNoTracking()
.Where(b => encounterIds.Contains(b.EncounterId))
.OrderByDescending(b => b.RecognizedAt)
.ToListAsync())
.GroupBy(b => b.EncounterId)
.ToDictionary(g => g.Key, g => g.First());
.Select(g => g.OrderByDescending(b => b.RecognizedAt).First())
.ToDictionaryAsync(b => b.EncounterId);
var sofaByEncounter = (await _db.SofaScores
var sofaByEncounter = await _db.SofaScores
.AsNoTracking()
.Where(s => encounterIds.Contains(s.EncounterId))
.OrderByDescending(s => s.CalculatedAt)
.ToListAsync())
.GroupBy(s => s.EncounterId)
.ToDictionary(g => g.Key, g => g.First());
.Select(g => g.OrderByDescending(s => s.CalculatedAt).First())
.ToDictionaryAsync(s => s.EncounterId);
var gcsByEncounter = (await _db.GcsScores
var gcsByEncounter = await _db.GcsScores
.AsNoTracking()
.Where(s => encounterIds.Contains(s.EncounterId))
.OrderByDescending(s => s.CalculatedAt)
.ToListAsync())
.GroupBy(s => s.EncounterId)
.ToDictionary(g => g.Key, g => g.First());
.Select(g => g.OrderByDescending(s => s.CalculatedAt).First())
.ToDictionaryAsync(s => s.EncounterId);
var lastObservationByEncounter = await _db.Observations
.AsNoTracking()
@@ -246,8 +242,15 @@ public class EncounterService : IEncounterService
});
}
// Bound timeline payloads for long-stay encounters (recent window + row caps).
const int maxEventsPerType = 500;
var timelineCutoff = DateTimeOffset.UtcNow.AddDays(-7);
var observations = await _db.Observations
.Where(o => o.EncounterId == encounterId)
.AsNoTracking()
.Where(o => o.EncounterId == encounterId && o.RecordedAt >= timelineCutoff)
.OrderByDescending(o => o.RecordedAt)
.Take(maxEventsPerType)
.Select(o => new
{
type = "observation",
@@ -260,7 +263,10 @@ public class EncounterService : IEncounterService
events.AddRange(observations);
var alerts = await _db.ClinicalAlerts
.Where(a => a.EncounterId == encounterId)
.AsNoTracking()
.Where(a => a.EncounterId == encounterId && a.TriggeredAt >= timelineCutoff)
.OrderByDescending(a => a.TriggeredAt)
.Take(maxEventsPerType)
.Select(a => new
{
type = "alert",
@@ -273,7 +279,10 @@ public class EncounterService : IEncounterService
events.AddRange(alerts);
var orders = await _db.Orders
.Where(o => o.EncounterId == encounterId)
.AsNoTracking()
.Where(o => o.EncounterId == encounterId && o.OrderedAt >= timelineCutoff)
.OrderByDescending(o => o.OrderedAt)
.Take(maxEventsPerType)
.Select(o => new
{
type = "order",
@@ -286,7 +295,10 @@ public class EncounterService : IEncounterService
events.AddRange(orders);
var medications = await _db.MedicationAdministrations
.Where(m => m.EncounterId == encounterId)
.AsNoTracking()
.Where(m => m.EncounterId == encounterId && m.AdministeredAt >= timelineCutoff)
.OrderByDescending(m => m.AdministeredAt)
.Take(maxEventsPerType)
.Select(m => new
{
type = "medication",
@@ -1,6 +1,7 @@
public interface IPhiAccessLogService
{
Task LogViewAsync(Guid patientId, string resourcePath);
Task LogViewsAsync(IReadOnlyList<Guid> patientIds, string resourcePath);
Task LogListAsync(string resourcePath, int resultCount, string? searchQuery = null);
Task LogCreateAsync(Guid patientId, string resourcePath);
Task LogUpdateAsync(Guid patientId, string resourcePath);
@@ -197,7 +197,6 @@ public class ObservationService : IObservationService
if (encounter.Status != EncounterStatus.Active)
throw new ValidationException("Encounter not active.", "ENCOUNTER_NOT_ACTIVE");
await using var tx = await _db.Database.BeginTransactionAsync(ct);
try
{
var observation = new Observation
@@ -267,11 +266,10 @@ public class ObservationService : IObservationService
}, obs.EncounterId.ToString()));
await _db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
}
catch (DbUpdateException ex) when (IsUniqueViolation(ex))
{
await tx.RollbackAsync(ct);
_db.ChangeTracker.Clear();
// silent skip — idempotency key already applied
}
}
@@ -113,8 +113,9 @@ public class PatientService : IPatientService
var path = _http.HttpContext?.Request.Path.Value ?? "/api/v1/patients";
await _phiAccess.LogListAsync(path, patients.Count, q);
foreach (var p in patients)
await _phiAccess.LogViewAsync(p.Id, $"{path}?page={page}");
await _phiAccess.LogViewsAsync(
patients.Select(p => p.Id).ToList(),
$"{path}?page={page}");
return new PagedResult<Patient>(patients, page, pageSize, total);
}
@@ -27,6 +27,37 @@ public class PhiAccessLogService : IPhiAccessLogService
public async Task LogViewAsync(Guid patientId, string resourcePath) =>
await WriteAsync(PhiAccessType.View, patientId, resourcePath);
public async Task LogViewsAsync(IReadOnlyList<Guid> patientIds, string resourcePath)
{
if (patientIds.Count == 0) return;
if (!_currentUser.IsAuthenticated || _currentUser.UserId is null) return;
var now = DateTimeOffset.UtcNow;
var userId = _currentUser.UserId.Value;
var display = _currentUser.DisplayName ?? _currentUser.Username ?? "Unknown";
var ip = _currentUser.IpAddress;
var correlationId = _http.HttpContext?.Items["CorrelationId"]?.ToString();
foreach (var patientId in patientIds)
{
_db.PhiAccessLogs.Add(new PhiAccessLog
{
Id = Guid.NewGuid(),
AccessType = PhiAccessType.View,
PatientId = patientId,
UserId = userId,
UserDisplayName = display,
ResourcePath = resourcePath,
IpAddress = ip,
CorrelationId = correlationId,
AccessedAt = now
});
}
await _db.SaveChangesAsync();
_metrics.PhiAccessLogsTotal.WithLabels(PhiAccessType.View.ToDbString()).Inc(patientIds.Count);
}
public async Task LogCreateAsync(Guid patientId, string resourcePath) =>
await WriteAsync(PhiAccessType.Create, patientId, resourcePath);
@@ -176,19 +176,21 @@ public sealed class SimulationRunner : ISimulationRunner, IHostedService
public async Task StopAsync(CancellationToken cancellationToken)
{
var running = new List<Task>();
foreach (var ctx in _runs.Values)
{
if (ctx.State.Status is SimulationRunStatus.Pending or SimulationRunStatus.Running)
ctx.Cts.Cancel();
if (ctx.ExecuteTask is not null)
running.Add(ctx.ExecuteTask);
}
var deadline = DateTimeOffset.UtcNow.AddSeconds(5);
while (DateTimeOffset.UtcNow < deadline
&& _runs.Values.Any(c =>
c.State.Status is SimulationRunStatus.Pending or SimulationRunStatus.Running))
{
await Task.Delay(50, cancellationToken);
}
if (running.Count == 0) return;
var all = Task.WhenAll(running);
var completed = await Task.WhenAny(all, Task.Delay(TimeSpan.FromSeconds(5), cancellationToken));
if (completed != all)
_logger.LogWarning("Simulation stop timed out waiting for {Count} run task(s)", running.Count);
}
private async Task<SimulationRunState> RegisterAndStartAsync(
@@ -224,7 +226,7 @@ public sealed class SimulationRunner : ISimulationRunner, IHostedService
if (!_runs.TryAdd(runId, ctx))
throw new ConflictException("Failed to register simulation run.", "SIMULATION_REGISTER_FAILED");
_ = Task.Run(() => ExecuteAsync(ctx, CancellationToken.None), CancellationToken.None);
ctx.ExecuteTask = Task.Run(() => ExecuteAsync(ctx, CancellationToken.None), CancellationToken.None);
return state.Snapshot();
}
@@ -365,5 +367,6 @@ public sealed class SimulationRunner : ISimulationRunner, IHostedService
public SimulationRunState State { get; } = state;
public CancellationTokenSource Cts { get; } = cts;
public ScenarioFile Scenario { get; } = scenario;
public Task? ExecuteTask { get; set; }
}
}
+35 -17
View File
@@ -41,27 +41,45 @@ public class TrendDetector
var cache = _redis.GetDatabase();
var key = TrendCalculator.HistoryKey(encounterId, observationCode);
var lockKey = key + ":lock";
// Append new entry to history list
List<TrendHistoryEntry> history;
var entry = new TrendHistoryEntry(value, recordedAt);
var historyJson = await cache.StringGetAsync(key);
var history = historyJson.HasValue
? JsonSerializer.Deserialize<List<TrendHistoryEntry>>(historyJson!) ?? new()
: new List<TrendHistoryEntry>();
history.Add(entry);
// Trim to max entries and evict entries outside window
var cutoff = recordedAt.AddMinutes(-_options.WindowMinutes);
history = history
.Where(e => e.RecordedAt >= cutoff)
.TakeLast(_options.MaxHistoryEntries)
.ToList();
await cache.StringSetAsync(
key,
JsonSerializer.Serialize(history),
TimeSpan.FromSeconds(_options.HistoryTtlSeconds));
// Short Redis lock so concurrent observations for the same key do not lose history.
var locked = false;
for (var attempt = 0; attempt < 8 && !locked; attempt++)
{
locked = await cache.StringSetAsync(
lockKey, "1", TimeSpan.FromSeconds(2), When.NotExists);
if (!locked)
await Task.Delay(15, ct);
}
try
{
var historyJson = await cache.StringGetAsync(key);
history = historyJson.HasValue
? JsonSerializer.Deserialize<List<TrendHistoryEntry>>(historyJson!) ?? new()
: new List<TrendHistoryEntry>();
history.Add(entry);
history = history
.Where(e => e.RecordedAt >= cutoff)
.TakeLast(_options.MaxHistoryEntries)
.ToList();
await cache.StringSetAsync(
key,
JsonSerializer.Serialize(history),
TimeSpan.FromSeconds(_options.HistoryTtlSeconds));
}
finally
{
if (locked)
await cache.KeyDeleteAsync(lockKey);
}
if (history.Count < 2)
return new TrendResult(TrendOutcome.InsufficientHistory, observationCode);
+2 -1
View File
@@ -84,7 +84,8 @@
},
"DataLake": {
"FlushCount": 1000,
"FlushIntervalSeconds": 300
"FlushIntervalSeconds": 300,
"MaxBufferedEvents": 50000
},
"TrendDetection": {
"WindowMinutes": 30,