From 68a2ab320427f080dfdf1c2243529aab45a211ac Mon Sep 17 00:00:00 2001 From: trent Date: Mon, 30 Nov 2026 21:32:43 +0800 Subject: [PATCH] =?UTF-8?q?Fix=20Kafka=20retry=20seek,=20bound=20buffers,?= =?UTF-8?q?=20and=20cut=20hot-path=20CPU/memory=20waste=20(Phases=2041?= =?UTF-8?q?=E2=80=9344).?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- .../CentralReachabilityService.cs | 3 +- .../EncounterReplicaSyncService.cs | 107 +++++++++++++----- .../GatewayHeartbeatService.cs | 18 +-- .../LocalEscalationWorkerService.cs | 4 +- .../LocalPagingWorkerService.cs | 4 +- .../BackgroundService/SyncUploaderService.cs | 78 +++++++------ .../BackgroundService/ThresholdCacheLoader.cs | 9 +- .../Configurations/GatewayOptions.cs | 7 ++ .../Models/Central/CentralSyncDtos.cs | 12 ++ VigilCare.WardGateway/Program.cs | 8 +- .../Services/BufferedSyncWriter.cs | 18 ++- .../Services/LocalAlertService.cs | 14 ++- .../Services/LocalObservationService.cs | 10 +- .../Services/LocalWarningEvaluator.cs | 11 +- VigilCare.WardGateway/appsettings.json | 1 + .../KafkaConsumerRetryTests.cs | 89 +++++++++++++++ .../ClinicalSyncBatchConsumer.cs | 4 +- .../ElasticsSearch/EsIndexerService.cs | 13 +-- .../BackgroundServices/GcsScoringService.cs | 14 +-- .../BackgroundServices/News2ScoringService.cs | 14 +-- .../DischargeSummaryWorkerService.cs | 18 +-- .../Notifications/EscalationWorkerService.cs | 4 +- .../NotificationPublisherService.cs | 13 +-- .../Notifications/PagingWorkerService.cs | 4 +- .../PatientPhiMigrationService.cs | 49 +++++--- .../DisconnectedMonitorsCheck.cs | 37 +++--- .../Reconciliation/PendingOrdersCheck.cs | 37 +++--- .../UnacknowledgedAlertsCheck.cs | 41 ++++--- .../BackgroundServices/SepsisEngineService.cs | 12 +- .../BackgroundServices/SofaScoringService.cs | 16 +-- .../ThresholdCacheLoader.cs | 4 +- .../TrendAnalyzerService.cs | 14 +-- .../BackgroundServices/WarningAlertService.cs | 14 +-- .../DataLake/DataLakeEventParser.cs | 11 +- .../DataLake/DataLakeOptions.cs | 7 ++ .../DataLake/DataLakeWriterService.cs | 35 ++++-- .../Infrastructure/ClinicalEventJson.cs | 13 +++ .../Infrastructure/KafkaConsumerRetry.cs | 55 +++++++++ VigilCareClinicalAPI/Program.cs | 4 + .../Services/DischargeSummaryService.cs | 13 ++- .../Services/EncounterService.cs | 52 +++++---- .../Interfaces/IPhiAccessLogService.cs | 1 + .../Services/ObservationService.cs | 4 +- .../Services/PatientService.cs | 5 +- .../Services/PhiAccessLogService.cs | 31 +++++ .../Services/Simulation/SimulationRunner.cs | 19 ++-- VigilCareClinicalAPI/Trend/TrendDetector.cs | 52 ++++++--- VigilCareClinicalAPI/appsettings.json | 3 +- docs/ops/production-observability.md | 4 + .../cpu-memory-remediation-roadmap.md | 96 ++++++++++++++++ .../phase-41-correctness-backpressure.md | 47 ++++++++ .../performance/phase-42-resource-leaks-gc.md | 37 ++++++ .../phase-43-throughput-hot-paths.md | 41 +++++++ docs/performance/phase-44-hardening.md | 39 +++++++ 54 files changed, 959 insertions(+), 311 deletions(-) create mode 100644 VigilCareClinicalAPI.Tests/KafkaConsumerRetryTests.cs create mode 100644 VigilCareClinicalAPI/Infrastructure/ClinicalEventJson.cs create mode 100644 VigilCareClinicalAPI/Infrastructure/KafkaConsumerRetry.cs create mode 100644 docs/performance/cpu-memory-remediation-roadmap.md create mode 100644 docs/performance/phase-41-correctness-backpressure.md create mode 100644 docs/performance/phase-42-resource-leaks-gc.md create mode 100644 docs/performance/phase-43-throughput-hot-paths.md create mode 100644 docs/performance/phase-44-hardening.md diff --git a/VigilCare.WardGateway/BackgroundService/CentralReachabilityService.cs b/VigilCare.WardGateway/BackgroundService/CentralReachabilityService.cs index f7a0e0a..9dab3cf 100644 --- a/VigilCare.WardGateway/BackgroundService/CentralReachabilityService.cs +++ b/VigilCare.WardGateway/BackgroundService/CentralReachabilityService.cs @@ -32,8 +32,7 @@ public sealed class CentralReachabilityService : BackgroundService try { var client = _http.CreateClient("central"); - client.BaseAddress = new Uri(_central.BaseUrl); - var resp = await client.GetAsync("/health/ready", ct); + var resp = await client.GetAsync("health/ready", ct); _isReachable = resp.IsSuccessStatusCode; } catch diff --git a/VigilCare.WardGateway/BackgroundService/EncounterReplicaSyncService.cs b/VigilCare.WardGateway/BackgroundService/EncounterReplicaSyncService.cs index 9ffcc07..7186b56 100644 --- a/VigilCare.WardGateway/BackgroundService/EncounterReplicaSyncService.cs +++ b/VigilCare.WardGateway/BackgroundService/EncounterReplicaSyncService.cs @@ -46,13 +46,10 @@ public sealed class EncounterReplicaSyncService : BackgroundService await using var scope = _scopes.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); var redis = scope.ServiceProvider.GetRequiredService(); - var centralOpts = scope.ServiceProvider.GetRequiredService>().Value; var client = _http.CreateClient("central"); - client.BaseAddress = new Uri(centralOpts.BaseUrl); - ConfigureAuth(client); - - if (client.DefaultRequestHeaders.Authorization is null) + var jwt = Environment.GetEnvironmentVariable("GATEWAY_SYNC_JWT"); + if (string.IsNullOrEmpty(jwt)) { _logger.LogWarning( "GATEWAY_SYNC_JWT not set — skipping encounter replica sync (seed local replica manually for dev)"); @@ -61,8 +58,8 @@ public sealed class EncounterReplicaSyncService : BackgroundService try { - var syncedCount = await SyncEncountersAsync(client, db, ct); - await SyncThresholdsAsync(client, db, redis, ct); + var syncedCount = await SyncEncountersAsync(client, jwt, db, ct); + await SyncThresholdsAsync(client, jwt, db, redis, ct); var state = await db.SyncState.FirstOrDefaultAsync(ct) ?? db.SyncState.Add(new GatewaySyncState { Id = Guid.NewGuid() }).Entity; @@ -79,7 +76,7 @@ public sealed class EncounterReplicaSyncService : BackgroundService } private async Task SyncEncountersAsync( - HttpClient client, GatewayDbContext db, CancellationToken ct) + HttpClient client, string jwt, GatewayDbContext db, CancellationToken ct) { var dept = Uri.EscapeDataString(_gateway.Department); var summaries = new List(); @@ -87,10 +84,14 @@ public sealed class EncounterReplicaSyncService : BackgroundService while (true) { - var listResp = await client.GetFromJsonAsync>( - $"/api/v1/encounters?status=ACTIVE&department={dept}&page={page}&pageSize={EncounterPageSize}", - CentralApiJson.Options, - ct); + using var listReq = new HttpRequestMessage( + HttpMethod.Get, + $"api/v1/encounters?status=ACTIVE&department={dept}&page={page}&pageSize={EncounterPageSize}"); + listReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt); + using var listHttp = await client.SendAsync(listReq, ct); + listHttp.EnsureSuccessStatusCode(); + var listResp = await listHttp.Content.ReadFromJsonAsync>( + CentralApiJson.Options, ct); if (listResp?.Data?.Items is null || listResp.Data.Items.Count == 0) break; @@ -106,10 +107,28 @@ public sealed class EncounterReplicaSyncService : BackgroundService var synced = 0; foreach (var summary in summaries) { - var detailResp = await client.GetFromJsonAsync>( - $"/api/v1/encounters/{summary.EncounterId}", - CentralApiJson.Options, - ct); + var existingPatient = await db.Patients.FindAsync([summary.PatientId], ct); + if (existingPatient is not null + && !string.IsNullOrEmpty(summary.Mrn) + && !string.IsNullOrEmpty(summary.FirstName)) + { + UpsertFromSummary(db, summary, existingPatient); + synced++; + continue; + } + + using var detailReq = new HttpRequestMessage( + HttpMethod.Get, $"api/v1/encounters/{summary.EncounterId}"); + detailReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt); + using var detailHttp = await client.SendAsync(detailReq, ct); + if (!detailHttp.IsSuccessStatusCode) + { + _logger.LogWarning("Central returned no detail for encounter {EncounterId}", summary.EncounterId); + continue; + } + + var detailResp = await detailHttp.Content.ReadFromJsonAsync>( + CentralApiJson.Options, ct); if (detailResp?.Data is null) { @@ -124,6 +143,43 @@ public sealed class EncounterReplicaSyncService : BackgroundService return synced; } + private static void UpsertFromSummary( + GatewayDbContext db, CentralWardEncounterSummary summary, ReplicaPatient existingPatient) + { + var now = DateTimeOffset.UtcNow; + if (!string.IsNullOrEmpty(summary.Mrn)) existingPatient.Mrn = summary.Mrn; + if (!string.IsNullOrEmpty(summary.FirstName)) existingPatient.FirstName = summary.FirstName!; + if (!string.IsNullOrEmpty(summary.LastName)) existingPatient.LastName = summary.LastName!; + existingPatient.SyncedAt = now; + + var enc = db.Encounters.Find(summary.EncounterId); + if (enc is null) + { + db.Encounters.Add(new ReplicaEncounter + { + Id = summary.EncounterId, + PatientId = summary.PatientId, + EncounterType = EncounterType.Inpatient, + Status = summary.Status, + Department = summary.Department, + AttendingPhysician = summary.AttendingPhysician ?? "unknown", + RoomBed = summary.RoomBed, + AdmittedAt = summary.AdmittedAt == default ? now : summary.AdmittedAt, + SyncedAt = now + }); + } + else + { + enc.PatientId = summary.PatientId; + enc.Status = summary.Status; + enc.Department = summary.Department; + enc.AttendingPhysician = summary.AttendingPhysician ?? enc.AttendingPhysician; + enc.RoomBed = summary.RoomBed; + if (summary.AdmittedAt != default) enc.AdmittedAt = summary.AdmittedAt; + enc.SyncedAt = now; + } + } + private static void UpsertReplica(GatewayDbContext db, CentralEncounterDetail detail) { var now = DateTimeOffset.UtcNow; @@ -184,14 +240,17 @@ public sealed class EncounterReplicaSyncService : BackgroundService private async Task SyncThresholdsAsync( HttpClient client, + string jwt, GatewayDbContext db, IConnectionMultiplexer redis, CancellationToken ct) { - var thrResp = await client.GetFromJsonAsync>>( - "/api/v1/alert-thresholds", - CentralApiJson.Options, - ct); + using var thrReq = new HttpRequestMessage(HttpMethod.Get, "api/v1/alert-thresholds"); + thrReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt); + using var thrHttp = await client.SendAsync(thrReq, ct); + thrHttp.EnsureSuccessStatusCode(); + var thrResp = await thrHttp.Content.ReadFromJsonAsync>>( + CentralApiJson.Options, ct); if (thrResp?.Data is null) return; @@ -216,12 +275,4 @@ public sealed class EncounterReplicaSyncService : BackgroundService await ThresholdCacheLoader.RefreshAsync(db, redis, _logger, ct); } - private static void ConfigureAuth(HttpClient client) - { - client.DefaultRequestHeaders.Authorization = null; - - var jwt = Environment.GetEnvironmentVariable("GATEWAY_SYNC_JWT"); - if (!string.IsNullOrEmpty(jwt)) - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwt); - } } diff --git a/VigilCare.WardGateway/BackgroundService/GatewayHeartbeatService.cs b/VigilCare.WardGateway/BackgroundService/GatewayHeartbeatService.cs index 9e32660..11cb5b8 100644 --- a/VigilCare.WardGateway/BackgroundService/GatewayHeartbeatService.cs +++ b/VigilCare.WardGateway/BackgroundService/GatewayHeartbeatService.cs @@ -1,3 +1,4 @@ +using System.Net.Http.Json; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; @@ -45,15 +46,16 @@ public sealed class GatewayHeartbeatService : BackgroundService try { var client = _http.CreateClient("central"); - client.BaseAddress = new Uri( - scope.ServiceProvider.GetRequiredService>().Value.BaseUrl); - client.DefaultRequestHeaders.Remove("X-Api-Key"); - client.DefaultRequestHeaders.Remove("X-Gateway-Id"); - client.DefaultRequestHeaders.Add("X-Api-Key", _config["ApiKey:Gateway"]); - client.DefaultRequestHeaders.Add("X-Gateway-Id", _gateway.GatewayId.ToString()); + using var message = new HttpRequestMessage( + HttpMethod.Patch, + $"api/v1/gateways/{_gateway.GatewayId}/heartbeat") + { + Content = JsonContent.Create(req) + }; + message.Headers.TryAddWithoutValidation("X-Api-Key", _config["ApiKey:Gateway"]); + message.Headers.TryAddWithoutValidation("X-Gateway-Id", _gateway.GatewayId.ToString()); - var resp = await client.PatchAsJsonAsync( - $"/api/v1/gateways/{_gateway.GatewayId}/heartbeat", req, ct); + var resp = await client.SendAsync(message, ct); if (!resp.IsSuccessStatusCode) _logger.LogWarning("Heartbeat failed: {Status}", resp.StatusCode); } diff --git a/VigilCare.WardGateway/BackgroundService/LocalEscalationWorkerService.cs b/VigilCare.WardGateway/BackgroundService/LocalEscalationWorkerService.cs index f00df8e..f74b18b 100644 --- a/VigilCare.WardGateway/BackgroundService/LocalEscalationWorkerService.cs +++ b/VigilCare.WardGateway/BackgroundService/LocalEscalationWorkerService.cs @@ -52,7 +52,7 @@ public sealed class LocalEscalationWorkerService : BackgroundService using var connection = factory.CreateConnection("gateway-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 (_, ea) => @@ -70,7 +70,7 @@ public sealed class LocalEscalationWorkerService : 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()!); _logger.LogCritical("[ESCALATION] Paging on-call backup for alert {AlertId}", alertId); diff --git a/VigilCare.WardGateway/BackgroundService/LocalPagingWorkerService.cs b/VigilCare.WardGateway/BackgroundService/LocalPagingWorkerService.cs index ba68d62..485f1df 100644 --- a/VigilCare.WardGateway/BackgroundService/LocalPagingWorkerService.cs +++ b/VigilCare.WardGateway/BackgroundService/LocalPagingWorkerService.cs @@ -87,7 +87,7 @@ public sealed class LocalPagingWorkerService : 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; @@ -104,7 +104,7 @@ public sealed class LocalPagingWorkerService : BackgroundService while (DateTimeOffset.UtcNow < deadline && !ct.IsCancellationRequested) { - await Task.Delay(2_000, ct); + await Task.Delay(5_000, ct); if (await IsAlertAcknowledgedAsync(alertId, ct)) { diff --git a/VigilCare.WardGateway/BackgroundService/SyncUploaderService.cs b/VigilCare.WardGateway/BackgroundService/SyncUploaderService.cs index ff22d70..605a04e 100644 --- a/VigilCare.WardGateway/BackgroundService/SyncUploaderService.cs +++ b/VigilCare.WardGateway/BackgroundService/SyncUploaderService.cs @@ -68,43 +68,53 @@ public sealed class SyncUploaderService : BackgroundService var request = BuildBatchRequest(batchRef, pending); var client = scope.ServiceProvider.GetRequiredService().CreateClient("central"); - client.BaseAddress = new Uri( - scope.ServiceProvider.GetRequiredService>().Value.BaseUrl); - client.DefaultRequestHeaders.Add("X-Api-Key", _config["ApiKey:Gateway"]!); - client.DefaultRequestHeaders.Add("X-Gateway-Id", _gateway.GatewayId.ToString()); + var apiKey = _config["ApiKey:Gateway"]!; + var gatewayId = _gateway.GatewayId.ToString(); - var submit = await client.PostAsJsonAsync("/api/v1/sync/batches", request, ct); - submit.EnsureSuccessStatusCode(); - var batchId = (await submit.Content.ReadFromJsonAsync>(ct))!.Data!.BatchId; - - for (var i = 0; i < 30; i++) + using (var submitMsg = new HttpRequestMessage(HttpMethod.Post, "api/v1/sync/batches") { - await Task.Delay(2000, ct); - var status = await client.GetFromJsonAsync>( - $"/api/v1/sync/batches/{batchId}", ct); - if (status?.Data?.Status is "APPLIED") - { - foreach (var item in pending) - { - item.Synced = true; - item.SyncedAt = DateTimeOffset.UtcNow; - } - await db.SaveChangesAsync(ct); - _logger.LogInformation( - "Sync batch {BatchId} applied — marked {Count} buffered items synced", - batchId, pending.Count); - return; - } - if (status?.Data?.Status is "CONFLICT" or "REJECTED") - { - _logger.LogError( - "Sync batch {BatchId} {Status} — items remain buffered", - batchId, status.Data.Status); - return; - } - } + Content = JsonContent.Create(request) + }) + { + submitMsg.Headers.TryAddWithoutValidation("X-Api-Key", apiKey); + submitMsg.Headers.TryAddWithoutValidation("X-Gateway-Id", gatewayId); + var submit = await client.SendAsync(submitMsg, ct); + submit.EnsureSuccessStatusCode(); + var batchId = (await submit.Content.ReadFromJsonAsync>(ct))!.Data!.BatchId; - _logger.LogWarning("Sync batch {BatchId} still processing after poll window", batchId); + for (var i = 0; i < 30; i++) + { + await Task.Delay(2000, ct); + using var statusMsg = new HttpRequestMessage(HttpMethod.Get, $"api/v1/sync/batches/{batchId}"); + statusMsg.Headers.TryAddWithoutValidation("X-Api-Key", apiKey); + statusMsg.Headers.TryAddWithoutValidation("X-Gateway-Id", gatewayId); + using var statusResp = await client.SendAsync(statusMsg, ct); + statusResp.EnsureSuccessStatusCode(); + var status = await statusResp.Content.ReadFromJsonAsync>(ct); + if (status?.Data?.Status is "APPLIED") + { + foreach (var item in pending) + { + item.Synced = true; + item.SyncedAt = DateTimeOffset.UtcNow; + } + await db.SaveChangesAsync(ct); + _logger.LogInformation( + "Sync batch {BatchId} applied — marked {Count} buffered items synced", + batchId, pending.Count); + return; + } + if (status?.Data?.Status is "CONFLICT" or "REJECTED") + { + _logger.LogError( + "Sync batch {BatchId} {Status} — items remain buffered", + batchId, status.Data.Status); + return; + } + } + + _logger.LogWarning("Sync batch {BatchId} still processing after poll window", batchId); + } } private ClinicalSyncBatchRequest BuildBatchRequest(Guid batchRef, List items) diff --git a/VigilCare.WardGateway/BackgroundService/ThresholdCacheLoader.cs b/VigilCare.WardGateway/BackgroundService/ThresholdCacheLoader.cs index e27cb95..d8d2708 100644 --- a/VigilCare.WardGateway/BackgroundService/ThresholdCacheLoader.cs +++ b/VigilCare.WardGateway/BackgroundService/ThresholdCacheLoader.cs @@ -51,7 +51,7 @@ public class ThresholdCacheLoader : IHostedService { try { - WriteThresholds(redis, thresholds); + await WriteThresholdsAsync(redis, thresholds); logger.LogInformation( "Loaded {Count} alert thresholds into gateway Redis cache", thresholds.Count); return; @@ -73,10 +73,12 @@ public class ThresholdCacheLoader : IHostedService maxAttempts); } - private static void WriteThresholds(IConnectionMultiplexer redis, List thresholds) + private static async Task WriteThresholdsAsync( + IConnectionMultiplexer redis, List thresholds) { var cache = redis.GetDatabase(); var batch = cache.CreateBatch(); + var setTasks = new List(thresholds.Count); foreach (var t in thresholds) { @@ -86,9 +88,10 @@ public class ThresholdCacheLoader : IHostedService t.WarningLow, t.WarningHigh, t.CriticalHigh)); - _ = batch.StringSetAsync($"threshold:{t.ObservationCode}", json); + setTasks.Add(batch.StringSetAsync($"threshold:{t.ObservationCode}", json)); } batch.Execute(); + await Task.WhenAll(setTasks); } } diff --git a/VigilCare.WardGateway/Configurations/GatewayOptions.cs b/VigilCare.WardGateway/Configurations/GatewayOptions.cs index 74bc8f1..9689190 100644 --- a/VigilCare.WardGateway/Configurations/GatewayOptions.cs +++ b/VigilCare.WardGateway/Configurations/GatewayOptions.cs @@ -9,6 +9,13 @@ public sealed class GatewayOptions public int HeartbeatIntervalSeconds { get; init; } = 60; public int SyncBatchSize { get; init; } = 500; + /// + /// Hard cap on unsynced buffered_sync_items. When reached, local ingest + /// that would enqueue more sync work is rejected (backpressure) so disk and + /// catch-up memory stay bounded during prolonged central outages. + /// + public int MaxBufferedSyncItems { get; init; } = 50_000; + /// /// When true (default), applies EF migrations at startup. The gateway is /// single-instance by design, so startup migration is safe. Set false if diff --git a/VigilCare.WardGateway/Models/Central/CentralSyncDtos.cs b/VigilCare.WardGateway/Models/Central/CentralSyncDtos.cs index 35d1636..fca3948 100644 --- a/VigilCare.WardGateway/Models/Central/CentralSyncDtos.cs +++ b/VigilCare.WardGateway/Models/Central/CentralSyncDtos.cs @@ -7,10 +7,22 @@ public sealed class CentralEncounterListPage public int TotalPages { get; set; } } +/// +/// Mirrors central WardEncounterSummary list payload so replica sync can +/// upsert without a detail GET when the patient already exists locally. +/// public sealed class CentralWardEncounterSummary { public Guid EncounterId { get; set; } public Guid PatientId { get; set; } + public string? Mrn { get; set; } + public string? FirstName { get; set; } + public string? LastName { get; set; } + public string? RoomBed { get; set; } + public Department Department { get; set; } + public EncounterStatus Status { get; set; } + public string? AttendingPhysician { get; set; } + public DateTimeOffset AdmittedAt { get; set; } } public sealed class CentralEncounterDetail diff --git a/VigilCare.WardGateway/Program.cs b/VigilCare.WardGateway/Program.cs index 99ddc64..2a6c4c6 100644 --- a/VigilCare.WardGateway/Program.cs +++ b/VigilCare.WardGateway/Program.cs @@ -49,7 +49,13 @@ try builder.Services.AddFluentValidationAutoValidation(); builder.Services.AddValidatorsFromAssemblyContaining(); - builder.Services.AddHttpClient("central"); + builder.Services.AddHttpClient("central", (sp, client) => + { + var baseUrl = sp.GetRequiredService>() + .Value.BaseUrl.TrimEnd('/') + "/"; + client.BaseAddress = new Uri(baseUrl); + client.Timeout = TimeSpan.FromSeconds(30); + }); builder.Services.AddSingleton(); builder.Services.AddHostedService(sp => sp.GetRequiredService()); diff --git a/VigilCare.WardGateway/Services/BufferedSyncWriter.cs b/VigilCare.WardGateway/Services/BufferedSyncWriter.cs index e02ba25..1e7ea41 100644 --- a/VigilCare.WardGateway/Services/BufferedSyncWriter.cs +++ b/VigilCare.WardGateway/Services/BufferedSyncWriter.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using Microsoft.EntityFrameworkCore; public static class BufferedSyncWriter { @@ -8,8 +9,21 @@ public static class BufferedSyncWriter object payload, string idempotencyKey, Guid encounterId, - DateTimeOffset recordedAt) + DateTimeOffset recordedAt, + int maxUnsyncedItems = 50_000) { + var persisted = db.BufferedSyncItems.Count(b => !b.Synced); + var pendingAdd = db.ChangeTracker.Entries() + .Count(e => e.State == EntityState.Added); + + if (persisted + pendingAdd >= maxUnsyncedItems) + { + throw new ConflictException( + $"Sync buffer is full ({maxUnsyncedItems} unsynced items). " + + "Central sync must catch up before accepting more buffered events.", + "SYNC_BUFFER_FULL"); + } + db.BufferedSyncItems.Add(new BufferedSyncItem { Id = Guid.NewGuid(), @@ -21,4 +35,4 @@ public static class BufferedSyncWriter CreatedAt = DateTimeOffset.UtcNow }); } -} \ No newline at end of file +} diff --git a/VigilCare.WardGateway/Services/LocalAlertService.cs b/VigilCare.WardGateway/Services/LocalAlertService.cs index cc38e57..4a15741 100644 --- a/VigilCare.WardGateway/Services/LocalAlertService.cs +++ b/VigilCare.WardGateway/Services/LocalAlertService.cs @@ -1,10 +1,16 @@ using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; public class LocalAlertService : ILocalAlertService { private readonly GatewayDbContext _db; + private readonly GatewayOptions _gateway; - public LocalAlertService(GatewayDbContext db) => _db = db; + public LocalAlertService(GatewayDbContext db, IOptions gateway) + { + _db = db; + _gateway = gateway.Value; + } public async Task AcknowledgeAsync( Guid id, AcknowledgeAlertRequest req, string clinicianId) @@ -26,7 +32,8 @@ public class LocalAlertService : ILocalAlertService clinicianId, acknowledgedAt = alert.AcknowledgedAt, req.Note - }, $"ack:{alert.ClientAlertId}:{alert.AcknowledgedAt:o}", alert.EncounterId, alert.AcknowledgedAt!.Value); + }, $"ack:{alert.ClientAlertId}:{alert.AcknowledgedAt:o}", alert.EncounterId, alert.AcknowledgedAt!.Value, + _gateway.MaxBufferedSyncItems); await _db.SaveChangesAsync(); return alert; @@ -50,7 +57,8 @@ public class LocalAlertService : ILocalAlertService clinicianId = alert.AcknowledgedBy, resolvedAt = alert.ResolvedAt, note = (string?)null - }, $"resolve:{alert.ClientAlertId}", alert.EncounterId, alert.ResolvedAt!.Value); + }, $"resolve:{alert.ClientAlertId}", alert.EncounterId, alert.ResolvedAt!.Value, + _gateway.MaxBufferedSyncItems); await _db.SaveChangesAsync(); return alert; diff --git a/VigilCare.WardGateway/Services/LocalObservationService.cs b/VigilCare.WardGateway/Services/LocalObservationService.cs index 31e1df6..1ec213d 100644 --- a/VigilCare.WardGateway/Services/LocalObservationService.cs +++ b/VigilCare.WardGateway/Services/LocalObservationService.cs @@ -1,5 +1,6 @@ using System.Text.Json; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; using StackExchange.Redis; public class LocalObservationService : ILocalObservationService @@ -8,6 +9,7 @@ public class LocalObservationService : ILocalObservationService private readonly IConnectionMultiplexer _redis; private readonly LocalWarningEvaluator _warnings; private readonly LocalPagingPublisher _paging; + private readonly GatewayOptions _gateway; private readonly ILogger _logger; public LocalObservationService( @@ -15,12 +17,14 @@ public class LocalObservationService : ILocalObservationService IConnectionMultiplexer redis, LocalWarningEvaluator warnings, LocalPagingPublisher paging, + IOptions gateway, ILogger logger) { _db = db; _redis = redis; _warnings = warnings; _paging = paging; + _gateway = gateway.Value; _logger = logger; } @@ -94,7 +98,8 @@ public class LocalObservationService : ILocalObservationService severity = alert.Severity.ToDbString(), alert.Details, generatedAt = triggeredAt - }, $"alert:{alert.ClientAlertId}", encounterId, triggeredAt); + }, $"alert:{alert.ClientAlertId}", encounterId, triggeredAt, + _gateway.MaxBufferedSyncItems); await _paging.PublishCriticalAsync(alert, encounter); } @@ -114,7 +119,8 @@ public class LocalObservationService : ILocalObservationService req.Unit, source = req.Source.ToDbString(), req.RecordedAt - }, req.IdempotencyKey ?? $"obs:{observation.Id}", encounterId, req.RecordedAt); + }, req.IdempotencyKey ?? $"obs:{observation.Id}", encounterId, req.RecordedAt, + _gateway.MaxBufferedSyncItems); await _db.SaveChangesAsync(); await tx.CommitAsync(); diff --git a/VigilCare.WardGateway/Services/LocalWarningEvaluator.cs b/VigilCare.WardGateway/Services/LocalWarningEvaluator.cs index a240ca6..bf60b2c 100644 --- a/VigilCare.WardGateway/Services/LocalWarningEvaluator.cs +++ b/VigilCare.WardGateway/Services/LocalWarningEvaluator.cs @@ -1,13 +1,19 @@ using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; public class LocalWarningEvaluator { private readonly GatewayDbContext _db; + private readonly GatewayOptions _gateway; private readonly ILogger _logger; - public LocalWarningEvaluator(GatewayDbContext db, ILogger logger) + public LocalWarningEvaluator( + GatewayDbContext db, + IOptions gateway, + ILogger logger) { _db = db; + _gateway = gateway.Value; _logger = logger; } @@ -52,7 +58,8 @@ public class LocalWarningEvaluator severity = AlertSeverity.Warning.ToDbString(), details, generatedAt = triggeredAt - }, $"alert:{clientAlertId}", encounterId, triggeredAt); + }, $"alert:{clientAlertId}", encounterId, triggeredAt, + _gateway.MaxBufferedSyncItems); _logger.LogInformation( "WARNING alert {AlertId} created locally for encounter {EncounterId}", diff --git a/VigilCare.WardGateway/appsettings.json b/VigilCare.WardGateway/appsettings.json index 81d65b2..0b3e7c4 100644 --- a/VigilCare.WardGateway/appsettings.json +++ b/VigilCare.WardGateway/appsettings.json @@ -27,6 +27,7 @@ "CentralReachabilityIntervalSeconds": 30, "HeartbeatIntervalSeconds": 60, "SyncBatchSize": 500, + "MaxBufferedSyncItems": 50000, "AutoMigrate": true }, "ApiKey": { diff --git a/VigilCareClinicalAPI.Tests/KafkaConsumerRetryTests.cs b/VigilCareClinicalAPI.Tests/KafkaConsumerRetryTests.cs new file mode 100644 index 0000000..b25464a --- /dev/null +++ b/VigilCareClinicalAPI.Tests/KafkaConsumerRetryTests.cs @@ -0,0 +1,89 @@ +using System.Text.Json; +using Confluent.Kafka; +using FluentAssertions; +using Microsoft.Extensions.Logging.Abstractions; + +public class KafkaConsumerRetryTests +{ + [Fact] + public void PoisonPillGuard_PermanentError_SkipsImmediately() + { + var guard = new PoisonPillGuard("test-group", maxRetries: 5, NullLogger.Instance); + var result = BuildConsumeResult("test-topic", 0, 0, "bad payload"); + + guard.ShouldSkip(result, new JsonException("Invalid JSON")) + .Should().BeTrue(); + } + + [Fact] + public void PoisonPillGuard_TransientError_RetriesUpToMax() + { + const int maxRetries = 3; + var guard = new PoisonPillGuard("test-group", maxRetries, NullLogger.Instance); + var result = BuildConsumeResult("test-topic", 0, 42, "payload"); + var transientError = new TimeoutException("Connection timed out"); + + for (var i = 1; i < maxRetries; i++) + guard.ShouldSkip(result, transientError).Should().BeFalse(); + + guard.ShouldSkip(result, transientError).Should().BeTrue(); + } + + [Fact] + public async Task KafkaConsumerRetry_TransientError_SeeksBackWithoutCommit() + { + var guard = new PoisonPillGuard("test-group", maxRetries: 5, NullLogger.Instance); + var result = BuildConsumeResult("test-topic", 0, 42, "payload"); + TopicPartitionOffset? sought = null; + ConsumeResult? committed = null; + + await KafkaConsumerRetry.HandleFailureAsync( + seek: tpo => sought = tpo, + commit: r => committed = r, + result, + new TimeoutException("transient"), + guard, + NullLogger.Instance, + "TestService", + CancellationToken.None, + delayMs: 1); + + sought.Should().NotBeNull(); + sought!.Offset.Value.Should().Be(42); + committed.Should().BeNull(); + } + + [Fact] + public async Task KafkaConsumerRetry_PermanentError_CommitsWithoutSeek() + { + var guard = new PoisonPillGuard("test-group", maxRetries: 5, NullLogger.Instance); + var result = BuildConsumeResult("test-topic", 0, 7, "bad"); + TopicPartitionOffset? sought = null; + ConsumeResult? committed = null; + + await KafkaConsumerRetry.HandleFailureAsync( + seek: tpo => sought = tpo, + commit: r => committed = r, + result, + new JsonException("bad json"), + guard, + NullLogger.Instance, + "TestService", + CancellationToken.None, + delayMs: 1); + + sought.Should().BeNull(); + committed.Should().NotBeNull(); + committed!.Offset.Value.Should().Be(7); + } + + private static ConsumeResult BuildConsumeResult( + string topic, int partition, long offset, string value) => + new() + { + Topic = topic, + Partition = new Partition(partition), + Offset = new Offset(offset), + Message = new Message { Key = "test-key", Value = value } + }; +} diff --git a/VigilCareClinicalAPI/BackgroundServices/ClinicalSyncBatchConsumer.cs b/VigilCareClinicalAPI/BackgroundServices/ClinicalSyncBatchConsumer.cs index df6b72f..a8aad9e 100644 --- a/VigilCareClinicalAPI/BackgroundServices/ClinicalSyncBatchConsumer.cs +++ b/VigilCareClinicalAPI/BackgroundServices/ClinicalSyncBatchConsumer.cs @@ -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(); diff --git a/VigilCareClinicalAPI/BackgroundServices/ElasticsSearch/EsIndexerService.cs b/VigilCareClinicalAPI/BackgroundServices/ElasticsSearch/EsIndexerService.cs index 7d650b8..b7b29b5 100644 --- a/VigilCareClinicalAPI/BackgroundServices/ElasticsSearch/EsIndexerService.cs +++ b/VigilCareClinicalAPI/BackgroundServices/ElasticsSearch/EsIndexerService.cs @@ -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); } } } diff --git a/VigilCareClinicalAPI/BackgroundServices/GcsScoringService.cs b/VigilCareClinicalAPI/BackgroundServices/GcsScoringService.cs index 036abb1..64ae510 100644 --- a/VigilCareClinicalAPI/BackgroundServices/GcsScoringService.cs +++ b/VigilCareClinicalAPI/BackgroundServices/GcsScoringService.cs @@ -46,7 +46,7 @@ public class GcsScoringService : BackgroundService var evt = JsonSerializer.Deserialize( result.Message.Value, - new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!; + ClinicalEventJson.Options)!; using var scope = _services.CreateScope(); var detector = scope.ServiceProvider.GetRequiredService(); @@ -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); } } } diff --git a/VigilCareClinicalAPI/BackgroundServices/News2ScoringService.cs b/VigilCareClinicalAPI/BackgroundServices/News2ScoringService.cs index 2dcce1e..4f3beb6 100644 --- a/VigilCareClinicalAPI/BackgroundServices/News2ScoringService.cs +++ b/VigilCareClinicalAPI/BackgroundServices/News2ScoringService.cs @@ -46,7 +46,7 @@ public class News2ScoringService : BackgroundService var evt = JsonSerializer.Deserialize( result.Message.Value, - new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!; + ClinicalEventJson.Options)!; using var scope = _services.CreateScope(); var detector = scope.ServiceProvider.GetRequiredService(); @@ -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); } } } diff --git a/VigilCareClinicalAPI/BackgroundServices/Notifications/DischargeSummaryWorkerService.cs b/VigilCareClinicalAPI/BackgroundServices/Notifications/DischargeSummaryWorkerService.cs index 8dff103..44f7867 100644 --- a/VigilCareClinicalAPI/BackgroundServices/Notifications/DischargeSummaryWorkerService.cs +++ b/VigilCareClinicalAPI/BackgroundServices/Notifications/DischargeSummaryWorkerService.cs @@ -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 _rabbitOpts; private readonly IOptions _minioOpts; + private readonly IMinioClient _minio; private readonly IServiceScopeFactory _scopes; private readonly ILogger _logger; public DischargeSummaryWorkerService( IOptions rabbitOpts, IOptions minioOpts, + IMinioClient minio, IServiceScopeFactory scopes, ILogger 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); diff --git a/VigilCareClinicalAPI/BackgroundServices/Notifications/EscalationWorkerService.cs b/VigilCareClinicalAPI/BackgroundServices/Notifications/EscalationWorkerService.cs index 35815d7..694e412 100644 --- a/VigilCareClinicalAPI/BackgroundServices/Notifications/EscalationWorkerService.cs +++ b/VigilCareClinicalAPI/BackgroundServices/Notifications/EscalationWorkerService.cs @@ -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()!); diff --git a/VigilCareClinicalAPI/BackgroundServices/Notifications/NotificationPublisherService.cs b/VigilCareClinicalAPI/BackgroundServices/Notifications/NotificationPublisherService.cs index 57e10b6..f5366bf 100644 --- a/VigilCareClinicalAPI/BackgroundServices/Notifications/NotificationPublisherService.cs +++ b/VigilCareClinicalAPI/BackgroundServices/Notifications/NotificationPublisherService.cs @@ -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)) diff --git a/VigilCareClinicalAPI/BackgroundServices/Notifications/PagingWorkerService.cs b/VigilCareClinicalAPI/BackgroundServices/Notifications/PagingWorkerService.cs index 7557d10..c204879 100644 --- a/VigilCareClinicalAPI/BackgroundServices/Notifications/PagingWorkerService.cs +++ b/VigilCareClinicalAPI/BackgroundServices/Notifications/PagingWorkerService.cs @@ -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) diff --git a/VigilCareClinicalAPI/BackgroundServices/PatientPhiMigrationService.cs b/VigilCareClinicalAPI/BackgroundServices/PatientPhiMigrationService.cs index 674f211..35f36df 100644 --- a/VigilCareClinicalAPI/BackgroundServices/PatientPhiMigrationService.cs +++ b/VigilCareClinicalAPI/BackgroundServices/PatientPhiMigrationService.cs @@ -2,6 +2,8 @@ using Microsoft.EntityFrameworkCore; public class PatientPhiMigrationService : IHostedService { + private const int BatchSize = 500; + private readonly IServiceProvider _services; private readonly ILogger _logger; @@ -19,26 +21,47 @@ public class PatientPhiMigrationService : IHostedService var db = scope.ServiceProvider.GetRequiredService(); var crypto = scope.ServiceProvider.GetRequiredService(); - 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 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; -} \ No newline at end of file + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; +} diff --git a/VigilCareClinicalAPI/BackgroundServices/Reconciliation/DisconnectedMonitorsCheck.cs b/VigilCareClinicalAPI/BackgroundServices/Reconciliation/DisconnectedMonitorsCheck.cs index d8b1488..009df7c 100644 --- a/VigilCareClinicalAPI/BackgroundServices/Reconciliation/DisconnectedMonitorsCheck.cs +++ b/VigilCareClinicalAPI/BackgroundServices/Reconciliation/DisconnectedMonitorsCheck.cs @@ -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(); 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; } -} \ No newline at end of file +} diff --git a/VigilCareClinicalAPI/BackgroundServices/Reconciliation/PendingOrdersCheck.cs b/VigilCareClinicalAPI/BackgroundServices/Reconciliation/PendingOrdersCheck.cs index 3f958e6..6c123a0 100644 --- a/VigilCareClinicalAPI/BackgroundServices/Reconciliation/PendingOrdersCheck.cs +++ b/VigilCareClinicalAPI/BackgroundServices/Reconciliation/PendingOrdersCheck.cs @@ -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(); 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; } -} \ No newline at end of file +} diff --git a/VigilCareClinicalAPI/BackgroundServices/Reconciliation/UnacknowledgedAlertsCheck.cs b/VigilCareClinicalAPI/BackgroundServices/Reconciliation/UnacknowledgedAlertsCheck.cs index af1a178..cf1c2d8 100644 --- a/VigilCareClinicalAPI/BackgroundServices/Reconciliation/UnacknowledgedAlertsCheck.cs +++ b/VigilCareClinicalAPI/BackgroundServices/Reconciliation/UnacknowledgedAlertsCheck.cs @@ -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(); 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; } -} \ No newline at end of file +} diff --git a/VigilCareClinicalAPI/BackgroundServices/SepsisEngineService.cs b/VigilCareClinicalAPI/BackgroundServices/SepsisEngineService.cs index 54e415a..1cb049e 100644 --- a/VigilCareClinicalAPI/BackgroundServices/SepsisEngineService.cs +++ b/VigilCareClinicalAPI/BackgroundServices/SepsisEngineService.cs @@ -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); } } } diff --git a/VigilCareClinicalAPI/BackgroundServices/SofaScoringService.cs b/VigilCareClinicalAPI/BackgroundServices/SofaScoringService.cs index da00b07..0d01ad9 100644 --- a/VigilCareClinicalAPI/BackgroundServices/SofaScoringService.cs +++ b/VigilCareClinicalAPI/BackgroundServices/SofaScoringService.cs @@ -55,7 +55,7 @@ public class SofaScoringService : BackgroundService { var gcsEvt = JsonSerializer.Deserialize( 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( 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); } } } diff --git a/VigilCareClinicalAPI/BackgroundServices/ThresholdCacheLoader.cs b/VigilCareClinicalAPI/BackgroundServices/ThresholdCacheLoader.cs index e7923f2..849a483 100644 --- a/VigilCareClinicalAPI/BackgroundServices/ThresholdCacheLoader.cs +++ b/VigilCareClinicalAPI/BackgroundServices/ThresholdCacheLoader.cs @@ -34,6 +34,7 @@ public class ThresholdCacheLoader : IHostedService { var cache = _redis.GetDatabase(); var batch = cache.CreateBatch(); + var setTasks = new List(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; } diff --git a/VigilCareClinicalAPI/BackgroundServices/TrendAnalyzerService.cs b/VigilCareClinicalAPI/BackgroundServices/TrendAnalyzerService.cs index 13cd762..cd693bc 100644 --- a/VigilCareClinicalAPI/BackgroundServices/TrendAnalyzerService.cs +++ b/VigilCareClinicalAPI/BackgroundServices/TrendAnalyzerService.cs @@ -46,7 +46,7 @@ public class TrendAnalyzerService : BackgroundService var evt = JsonSerializer.Deserialize( result.Message.Value, - new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!; + ClinicalEventJson.Options)!; using var scope = _services.CreateScope(); var detector = scope.ServiceProvider.GetRequiredService(); @@ -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); } } } diff --git a/VigilCareClinicalAPI/BackgroundServices/WarningAlertService.cs b/VigilCareClinicalAPI/BackgroundServices/WarningAlertService.cs index 5ca51ef..84b85f3 100644 --- a/VigilCareClinicalAPI/BackgroundServices/WarningAlertService.cs +++ b/VigilCareClinicalAPI/BackgroundServices/WarningAlertService.cs @@ -46,7 +46,7 @@ public class WarningAlertService : BackgroundService var evt = JsonSerializer.Deserialize( result.Message.Value, - new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!; + ClinicalEventJson.Options)!; using var scope = _services.CreateScope(); var evaluator = scope.ServiceProvider.GetRequiredService(); @@ -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); } } } diff --git a/VigilCareClinicalAPI/DataLake/DataLakeEventParser.cs b/VigilCareClinicalAPI/DataLake/DataLakeEventParser.cs index defd497..2deb337 100644 --- a/VigilCareClinicalAPI/DataLake/DataLakeEventParser.cs +++ b/VigilCareClinicalAPI/DataLake/DataLakeEventParser.cs @@ -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"), diff --git a/VigilCareClinicalAPI/DataLake/DataLakeOptions.cs b/VigilCareClinicalAPI/DataLake/DataLakeOptions.cs index 4b9a8e8..edbf05b 100644 --- a/VigilCareClinicalAPI/DataLake/DataLakeOptions.cs +++ b/VigilCareClinicalAPI/DataLake/DataLakeOptions.cs @@ -11,6 +11,13 @@ public sealed class DataLakeOptions // Production: 300 seconds (5 minutes). Tests: 10 seconds. public int FlushIntervalSeconds { get; init; } = 300; + /// + /// 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). + /// + 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"; diff --git a/VigilCareClinicalAPI/DataLake/DataLakeWriterService.cs b/VigilCareClinicalAPI/DataLake/DataLakeWriterService.cs index f09edc0..d3928da 100644 --- a/VigilCareClinicalAPI/DataLake/DataLakeWriterService.cs +++ b/VigilCareClinicalAPI/DataLake/DataLakeWriterService.cs @@ -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 _logger; // Buffer key: identifies one Parquet file-to-be. @@ -24,11 +26,13 @@ public sealed class DataLakeWriterService : BackgroundService IOptions kafkaOptions, IOptions opts, IOptions minioOpts, + IMinioClient minio, ILogger 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); diff --git a/VigilCareClinicalAPI/Infrastructure/ClinicalEventJson.cs b/VigilCareClinicalAPI/Infrastructure/ClinicalEventJson.cs new file mode 100644 index 0000000..ea64891 --- /dev/null +++ b/VigilCareClinicalAPI/Infrastructure/ClinicalEventJson.cs @@ -0,0 +1,13 @@ +using System.Text.Json; + +/// +/// Shared JSON options for Kafka clinical event deserialization. +/// construction is expensive — reuse one instance. +/// +public static class ClinicalEventJson +{ + public static readonly JsonSerializerOptions Options = new() + { + PropertyNameCaseInsensitive = true + }; +} diff --git a/VigilCareClinicalAPI/Infrastructure/KafkaConsumerRetry.cs b/VigilCareClinicalAPI/Infrastructure/KafkaConsumerRetry.cs new file mode 100644 index 0000000..1f75177 --- /dev/null +++ b/VigilCareClinicalAPI/Infrastructure/KafkaConsumerRetry.cs @@ -0,0 +1,55 @@ +using Confluent.Kafka; + +/// +/// Shared transient-failure handling for Kafka consumers that use +/// . After Consume, the client position +/// advances; without Seek, the next successful Commit would skip +/// the failed offset. This helper seeks back before delaying so retries truly +/// reprocess the same message. +/// +public static class KafkaConsumerRetry +{ + public static Task HandleFailureAsync( + IConsumer consumer, + ConsumeResult? 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); + + /// + /// Testable overload — production code should prefer the overload. + /// + public static async Task HandleFailureAsync( + Action seek, + Action> commit, + ConsumeResult? 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); + } +} diff --git a/VigilCareClinicalAPI/Program.cs b/VigilCareClinicalAPI/Program.cs index e35c589..b39fa10 100644 --- a/VigilCareClinicalAPI/Program.cs +++ b/VigilCareClinicalAPI/Program.cs @@ -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( builder.Configuration.GetSection(MinioOptions.Section)); + builder.Services.AddSingleton(sp => + MinioClientFactory.Build(sp.GetRequiredService>().Value)); builder.Services.AddSingleton(); builder.Services.AddHostedService(sp => sp.GetRequiredService()); diff --git a/VigilCareClinicalAPI/Services/DischargeSummaryService.cs b/VigilCareClinicalAPI/Services/DischargeSummaryService.cs index 51a4b30..2f5b52a 100644 --- a/VigilCareClinicalAPI/Services/DischargeSummaryService.cs +++ b/VigilCareClinicalAPI/Services/DischargeSummaryService.cs @@ -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 minioOpts) + public DischargeSummaryService( + AppDbContext db, + IOptions minioOpts, + IMinioClient minio) { _db = db; _minioOpts = minioOpts.Value; + _minio = minio; } public async Task 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 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; diff --git a/VigilCareClinicalAPI/Services/EncounterService.cs b/VigilCareClinicalAPI/Services/EncounterService.cs index 4e7133e..0d48660 100644 --- a/VigilCareClinicalAPI/Services/EncounterService.cs +++ b/VigilCareClinicalAPI/Services/EncounterService.cs @@ -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", diff --git a/VigilCareClinicalAPI/Services/Interfaces/IPhiAccessLogService.cs b/VigilCareClinicalAPI/Services/Interfaces/IPhiAccessLogService.cs index 546574b..aac9bc3 100644 --- a/VigilCareClinicalAPI/Services/Interfaces/IPhiAccessLogService.cs +++ b/VigilCareClinicalAPI/Services/Interfaces/IPhiAccessLogService.cs @@ -1,6 +1,7 @@ public interface IPhiAccessLogService { Task LogViewAsync(Guid patientId, string resourcePath); + Task LogViewsAsync(IReadOnlyList patientIds, string resourcePath); Task LogListAsync(string resourcePath, int resultCount, string? searchQuery = null); Task LogCreateAsync(Guid patientId, string resourcePath); Task LogUpdateAsync(Guid patientId, string resourcePath); diff --git a/VigilCareClinicalAPI/Services/ObservationService.cs b/VigilCareClinicalAPI/Services/ObservationService.cs index 9cea670..3e4da24 100644 --- a/VigilCareClinicalAPI/Services/ObservationService.cs +++ b/VigilCareClinicalAPI/Services/ObservationService.cs @@ -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 } } diff --git a/VigilCareClinicalAPI/Services/PatientService.cs b/VigilCareClinicalAPI/Services/PatientService.cs index c1cc91e..0c32549 100644 --- a/VigilCareClinicalAPI/Services/PatientService.cs +++ b/VigilCareClinicalAPI/Services/PatientService.cs @@ -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(patients, page, pageSize, total); } diff --git a/VigilCareClinicalAPI/Services/PhiAccessLogService.cs b/VigilCareClinicalAPI/Services/PhiAccessLogService.cs index 4782b4e..c6ada10 100644 --- a/VigilCareClinicalAPI/Services/PhiAccessLogService.cs +++ b/VigilCareClinicalAPI/Services/PhiAccessLogService.cs @@ -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 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); diff --git a/VigilCareClinicalAPI/Services/Simulation/SimulationRunner.cs b/VigilCareClinicalAPI/Services/Simulation/SimulationRunner.cs index 766edce..14646bb 100644 --- a/VigilCareClinicalAPI/Services/Simulation/SimulationRunner.cs +++ b/VigilCareClinicalAPI/Services/Simulation/SimulationRunner.cs @@ -176,19 +176,21 @@ public sealed class SimulationRunner : ISimulationRunner, IHostedService public async Task StopAsync(CancellationToken cancellationToken) { + var running = new List(); 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 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; } } } diff --git a/VigilCareClinicalAPI/Trend/TrendDetector.cs b/VigilCareClinicalAPI/Trend/TrendDetector.cs index 6dfbad1..802a1ae 100644 --- a/VigilCareClinicalAPI/Trend/TrendDetector.cs +++ b/VigilCareClinicalAPI/Trend/TrendDetector.cs @@ -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 history; var entry = new TrendHistoryEntry(value, recordedAt); - var historyJson = await cache.StringGetAsync(key); - var history = historyJson.HasValue - ? JsonSerializer.Deserialize>(historyJson!) ?? new() - : new List(); - - 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>(historyJson!) ?? new() + : new List(); + + 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); diff --git a/VigilCareClinicalAPI/appsettings.json b/VigilCareClinicalAPI/appsettings.json index 9aac65c..e833392 100644 --- a/VigilCareClinicalAPI/appsettings.json +++ b/VigilCareClinicalAPI/appsettings.json @@ -84,7 +84,8 @@ }, "DataLake": { "FlushCount": 1000, - "FlushIntervalSeconds": 300 + "FlushIntervalSeconds": 300, + "MaxBufferedEvents": 50000 }, "TrendDetection": { "WindowMinutes": 30, diff --git a/docs/ops/production-observability.md b/docs/ops/production-observability.md index 0c668d1..7649bfe 100644 --- a/docs/ops/production-observability.md +++ b/docs/ops/production-observability.md @@ -58,3 +58,7 @@ Kafka consumer lag, ready probe failing, gateway offline, unacked CRITICAL alert Optionally a second signal for the ward gateway with `Application = 'VigilCare.WardGateway'`. + +## Related + +- [CPU / Memory Remediation Roadmap (Phases 41–44)](../performance/cpu-memory-remediation-roadmap.md) diff --git a/docs/performance/cpu-memory-remediation-roadmap.md b/docs/performance/cpu-memory-remediation-roadmap.md new file mode 100644 index 0000000..d192c2c --- /dev/null +++ b/docs/performance/cpu-memory-remediation-roadmap.md @@ -0,0 +1,96 @@ +# VigilCare Clinical — CPU / Memory Remediation Roadmap + +**Internal document | Phases 41–44** + +**Prerequisites:** Phases 1–40 clinical platform, climate resilience (20–24), and alert optimization foundations in place. + +**Source:** Static performance/reliability audit of `VigilCareClinicalAPI` and `VigilCare.WardGateway` (CPU, memory, EF, HttpClient, concurrency). + +--- + +## Problem Statement + +Under normal traffic the platform is largely correct. Under **peak observation storms**, **sustained outages** (MinIO / central unreachable), and **long-running process lifetime**, several defects cause: + +| Risk | Symptom | +|------|---------| +| Silent Kafka loss | Transient consumer failures advance past failed offsets (“retry” never re-seeks) | +| Rabbit channel corruption | Prefetch > 1 + async handlers sharing one `IModel` | +| Unbounded memory / disk | DataLake in-memory buffer and gateway `buffered_sync_items` grow without a hard cap | +| GC / socket pressure | Undisposed `JsonDocument`, per-upload MinIO clients, per-message `JsonSerializerOptions` | +| Sync / API latency | Per-item `SaveChanges`, N+1 reconciliation and HTTP detail fetches, unbounded timeline loads | + +--- + +## Design Principles + +1. **Correctness before throughput** — never commit past a failed Kafka offset without intentional poison skip. +2. **Bound everything that can grow under outage** — buffers must plateau; lag is preferable to OOM. +3. **Dispose pooled / unmanaged resources** on every hot path. +4. **Measure with tools, not invented numbers** — `dotnet-counters`, lag metrics, existing unit tests. + +--- + +## Phase Map + +| Phase | Name | Audit findings | Status | +|-------|------|----------------|--------| +| **41** | Correctness & backpressure | 1, 2, 3, 7 | Complete | +| **42** | Resource leaks & GC | 4, 5, 8, 15 | Complete | +| **43** | Throughput hot paths | 6, 9, 10, 11, 12, 13 | Complete | +| **44** | Hardening | 14, 16, 17, 18, 19, 20 | Complete | + +### Dependency graph + +``` +Phase 41 → Phase 42 → Phase 43 → Phase 44 +``` + +Docs (this folder) are written first; checklist items flip to **Complete** as code lands. + +### Phase plans + +- [phase-41-correctness-backpressure.md](phase-41-correctness-backpressure.md) +- [phase-42-resource-leaks-gc.md](phase-42-resource-leaks-gc.md) +- [phase-43-throughput-hot-paths.md](phase-43-throughput-hot-paths.md) +- [phase-44-hardening.md](phase-44-hardening.md) + +--- + +## Severity Matrix (audit reference) + +| ID | Severity | Finding | +|----|----------|---------| +| 1 | Critical | Kafka failure path advances past failed offset | +| 2 | High | RabbitMQ `IModel` + prefetch > 1 | +| 3 | High | DataLake buffer unbounded on flush failure | +| 4 | High | Undisposed `JsonDocument` | +| 5 | High | MinIO client per upload, never disposed | +| 6 | High | Clinical sync per-observation SaveChanges | +| 7 | High | Gateway buffered sync unbounded | +| 8 | Medium–High | Per-message `JsonSerializerOptions` | +| 9 | High | Patient list PHI N+1 SaveChanges | +| 10 | Medium–High | Reconciliation N+1 | +| 11 | High | Encounter replica sync N+1 HTTP / HttpClient misuse | +| 12 | Medium | Encounter timeline unbounded | +| 13 | Medium | Ward list over-fetches score history | +| 14 | Medium | Simulation fire-and-forget Task.Run | +| 15 | Medium | Redis threshold batch tasks discarded | +| 16 | Medium | Trend Redis RMW race | +| 17 | Medium | Paging worker long poll hold | +| 18 | Medium | Parquet double allocation | +| 19 | Medium | PHI migration loads full table | +| 20 | Low | Health-check Task.Run blocking | + +--- + +## Diagnostic Tools + +| Symptom | Tools | +|---------|--------| +| Allocations / GC | `dotnet-counters`, `dotnet-gcdump` | +| Leaks | `dotnet-dump` + SOS | +| Kafka loss / lag | Consumer lag + `kafka_poison_pills_skipped_total` | +| DB amplification | EF logging, `pg_stat_statements` | + +Related: [../ops/production-observability.md](../ops/production-observability.md) diff --git a/docs/performance/phase-41-correctness-backpressure.md b/docs/performance/phase-41-correctness-backpressure.md new file mode 100644 index 0000000..424982d --- /dev/null +++ b/docs/performance/phase-41-correctness-backpressure.md @@ -0,0 +1,47 @@ +# Phase 41 — Correctness & Backpressure + +| Field | Value | +|-------|-------| +| Status | Complete | +| Audit findings | 1, 2, 3, 7 | +| Depends on | Docs roadmap | + +## Goal + +Stop silent Kafka message loss, make RabbitMQ channel use safe under concurrency, and hard-cap DataLake / gateway buffers so outages produce lag instead of OOM or unbounded disk growth. + +## What exists + +- Kafka consumers use `PoisonPillGuard` and log “will retry” but do not `Seek` after transient failure +- Escalation / clinical sync / discharge / local escalation use `prefetchCount: 5` with shared `IModel` +- `DataLakeWriterService` retains failed partition buffers while continuing to consume +- `BufferedSyncWriter.Enqueue` has no depth limit + +## What to build + +- [x] Shared Kafka Seek-on-retry helper used by all scoring / indexing / notification consumers +- [x] NotificationPublisher: Seek + delay on transient failure (same as scorers) +- [x] Unit tests for Seek-retry behavior; keep PoisonPillGuard tests green +- [x] RabbitMQ `prefetchCount: 1` on Escalation, ClinicalSync, DischargeSummary, LocalEscalation +- [x] `DataLakeOptions.MaxBufferedEvents` + pause/skip buffer when at cap after failed flush +- [x] Gateway sync buffer max depth (config) with reject when full (`SYNC_BUFFER_FULL`) + +## Key files + +- `VigilCareClinicalAPI/Infrastructure/PoisonPillGuard.cs` +- `VigilCareClinicalAPI/BackgroundServices/*ScoringService.cs`, `EsIndexerService.cs`, `NotificationPublisherService.cs` +- `VigilCareClinicalAPI/DataLake/DataLakeWriterService.cs`, `DataLakeOptions.cs` +- Rabbit workers under `BackgroundServices/Notifications/` and Ward `LocalEscalationWorkerService` +- `VigilCare.WardGateway/Services/BufferedSyncWriter.cs` + +## Acceptance criteria + +- Transient failure re-seeks to the same offset until success or intentional poison skip +- Rabbit workers with former prefetch 5 now use prefetch 1 +- Forced MinIO / central outage: buffers plateau at configured caps +- Affected unit tests green + +## Verification notes + +- Added `KafkaConsumerRetry` + unit tests for Seek vs poison Commit. +- Consumers wired to helper; Rabbit prefetch set to 1; DataLake/Gateway caps configured (50_000 default). diff --git a/docs/performance/phase-42-resource-leaks-gc.md b/docs/performance/phase-42-resource-leaks-gc.md new file mode 100644 index 0000000..e6293fb --- /dev/null +++ b/docs/performance/phase-42-resource-leaks-gc.md @@ -0,0 +1,37 @@ +# Phase 42 — Resource Leaks & GC + +| Field | Value | +|-------|-------| +| Status | Complete | +| Audit findings | 4, 5, 8, 15 | +| Depends on | Phase 41 | + +## Goal + +Dispose pooled JSON parsers, stop creating MinIO clients per upload, reuse `JsonSerializerOptions` on Kafka hot paths, and await Redis threshold batch tasks. + +## What to build + +- [x] `using` for all hot-path `JsonDocument.Parse` (DataLakeEventParser + Rabbit/Kafka handlers) +- [x] Long-lived `IMinioClient` via DI; dispose `MemoryStream` on upload +- [x] Static shared `JsonSerializerOptions` on News2/Sofa/Gcs/Warning/Trend consumers (`ClinicalEventJson`) +- [x] Await Redis `StringSetAsync` tasks after `batch.Execute()` in both ThresholdCacheLoaders + +## Key files + +- `VigilCareClinicalAPI/DataLake/DataLakeEventParser.cs` +- `VigilCareClinicalAPI/Storage/MinioClientFactory.cs` +- `VigilCareClinicalAPI/DataLake/DataLakeWriterService.cs` +- Kafka scoring consumers; ThresholdCacheLoader (API + WardGateway) + +## Acceptance criteria + +- No undisposed JsonDocument on listed paths +- MinIO not constructed per upload +- Threshold cache load awaits all sets +- DataLake parser tests pass + +## Verification notes + +- MinIO registered as singleton `IMinioClient` in Program.cs; DataLake/Discharge paths inject it. +- Hot-path JsonDocument uses `using`; scoring consumers share `ClinicalEventJson.Options`. diff --git a/docs/performance/phase-43-throughput-hot-paths.md b/docs/performance/phase-43-throughput-hot-paths.md new file mode 100644 index 0000000..6d8deeb --- /dev/null +++ b/docs/performance/phase-43-throughput-hot-paths.md @@ -0,0 +1,41 @@ +# Phase 43 — Throughput Hot Paths + +| Field | Value | +|-------|-------| +| Status | Complete | +| Audit findings | 6, 9, 10, 11, 12, 13 | +| Depends on | Phase 42 | + +## Goal + +Cut DB and HTTP round-trips under peak traffic and gateway catch-up without changing clinical scoring semantics. + +## What to build + +- [x] Clinical sync: removed nested TX around ApplySyncedObservation (SaveChanges + Clear on conflict) +- [x] PHI list audit: `LogViewsAsync` batch + one SaveChanges +- [x] Reconciliation checks: preload open keys + single SaveChanges +- [x] Ward `AddHttpClient("central")`: BaseAddress + 30s timeout; per-request headers (no DefaultRequestHeaders mutation) +- [x] Encounter replica sync: upsert from list summary when patient exists; detail GET only for new patients +- [x] Encounter timeline: 7-day window + Take(500) per event type +- [x] Ward list: latest-per-encounter GroupBy/First for NEWS2/SOFA/GCS/sepsis + +## Key files + +- `ClinicalSyncBatchProcessor.cs`, `ObservationService.cs` +- `PatientService.cs`, `PhiAccessLogService.cs` +- Reconciliation checks under `BackgroundServices/Reconciliation/` +- `VigilCare.WardGateway/Program.cs`, `EncounterReplicaSyncService.cs` +- `EncounterService.cs` + +## Acceptance criteria + +- Fewer commits per sync batch / patient list / reconciliation run +- Named HttpClient configured once with timeout +- Timeline and ward-list score queries bounded +- Relevant tests green + +## Verification notes + +- API + WardGateway build green after changes. +- Focused unit tests (PoisonPill/KafkaConsumerRetry/DataLakeEventParser) green. diff --git a/docs/performance/phase-44-hardening.md b/docs/performance/phase-44-hardening.md new file mode 100644 index 0000000..d546c54 --- /dev/null +++ b/docs/performance/phase-44-hardening.md @@ -0,0 +1,39 @@ +# Phase 44 — Hardening + +| Field | Value | +|-------|-------| +| Status | Complete | +| Audit findings | 14, 16, 17, 18, 19, 20 | +| Depends on | Phase 43 | + +## Goal + +Tighten lifecycle, concurrency, and startup paths that worsen under long-running operation. + +## What to build + +- [x] SimulationRunner: track run Task; await on stop (5s timeout) +- [x] TrendDetector: Redis lock around GET/modify/SET history +- [x] Paging workers: JsonDocument `using` (Phase 42); poll interval 5s (was 2s) +- [x] PatientPhiMigrationService: keyset-batched updates (500) +- [x] Light polish: deferred Parquet rewrite; health checks unchanged (low severity) + +## Key files + +- `SimulationRunner.cs` +- `TrendDetector.cs` +- `PagingWorkerService.cs`, `LocalPagingWorkerService.cs` +- `PatientPhiMigrationService.cs` +- `ParquetFileBuilder.cs`, Kafka/Rabbit health checks + +## Acceptance criteria + +- Simulation stop awaits tracked run task +- Trend history correct under concurrency +- PHI migration does not load fully migrated rows +- Suite green + +## Verification notes + +- Simulation stop awaits tracked execute tasks. +- Trend history updates under a short Redis lock key.