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

Stop consumers from committing past failed offsets, harden Rabbit/DataLake/gateway backpressure, dispose JsonDocument/MinIO correctly, and batch expensive DB/HTTP paths. Track progress in docs/performance.
This commit is contained in:
2026-11-30 21:32:43 +08:00
parent 1c1065938f
commit 68a2ab3204
54 changed files with 959 additions and 311 deletions
@@ -32,8 +32,7 @@ public sealed class CentralReachabilityService : BackgroundService
try try
{ {
var client = _http.CreateClient("central"); 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; _isReachable = resp.IsSuccessStatusCode;
} }
catch catch
@@ -46,13 +46,10 @@ public sealed class EncounterReplicaSyncService : BackgroundService
await using var scope = _scopes.CreateAsyncScope(); await using var scope = _scopes.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<GatewayDbContext>(); var db = scope.ServiceProvider.GetRequiredService<GatewayDbContext>();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>(); var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
var centralOpts = scope.ServiceProvider.GetRequiredService<IOptions<CentralApiOptions>>().Value;
var client = _http.CreateClient("central"); var client = _http.CreateClient("central");
client.BaseAddress = new Uri(centralOpts.BaseUrl); var jwt = Environment.GetEnvironmentVariable("GATEWAY_SYNC_JWT");
ConfigureAuth(client); if (string.IsNullOrEmpty(jwt))
if (client.DefaultRequestHeaders.Authorization is null)
{ {
_logger.LogWarning( _logger.LogWarning(
"GATEWAY_SYNC_JWT not set — skipping encounter replica sync (seed local replica manually for dev)"); "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 try
{ {
var syncedCount = await SyncEncountersAsync(client, db, ct); var syncedCount = await SyncEncountersAsync(client, jwt, db, ct);
await SyncThresholdsAsync(client, db, redis, ct); await SyncThresholdsAsync(client, jwt, db, redis, ct);
var state = await db.SyncState.FirstOrDefaultAsync(ct) var state = await db.SyncState.FirstOrDefaultAsync(ct)
?? db.SyncState.Add(new GatewaySyncState { Id = Guid.NewGuid() }).Entity; ?? db.SyncState.Add(new GatewaySyncState { Id = Guid.NewGuid() }).Entity;
@@ -79,7 +76,7 @@ public sealed class EncounterReplicaSyncService : BackgroundService
} }
private async Task<int> SyncEncountersAsync( private async Task<int> SyncEncountersAsync(
HttpClient client, GatewayDbContext db, CancellationToken ct) HttpClient client, string jwt, GatewayDbContext db, CancellationToken ct)
{ {
var dept = Uri.EscapeDataString(_gateway.Department); var dept = Uri.EscapeDataString(_gateway.Department);
var summaries = new List<CentralWardEncounterSummary>(); var summaries = new List<CentralWardEncounterSummary>();
@@ -87,10 +84,14 @@ public sealed class EncounterReplicaSyncService : BackgroundService
while (true) while (true)
{ {
var listResp = await client.GetFromJsonAsync<ApiResponse<CentralEncounterListPage>>( using var listReq = new HttpRequestMessage(
$"/api/v1/encounters?status=ACTIVE&department={dept}&page={page}&pageSize={EncounterPageSize}", HttpMethod.Get,
CentralApiJson.Options, $"api/v1/encounters?status=ACTIVE&department={dept}&page={page}&pageSize={EncounterPageSize}");
ct); listReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
using var listHttp = await client.SendAsync(listReq, ct);
listHttp.EnsureSuccessStatusCode();
var listResp = await listHttp.Content.ReadFromJsonAsync<ApiResponse<CentralEncounterListPage>>(
CentralApiJson.Options, ct);
if (listResp?.Data?.Items is null || listResp.Data.Items.Count == 0) if (listResp?.Data?.Items is null || listResp.Data.Items.Count == 0)
break; break;
@@ -106,10 +107,28 @@ public sealed class EncounterReplicaSyncService : BackgroundService
var synced = 0; var synced = 0;
foreach (var summary in summaries) foreach (var summary in summaries)
{ {
var detailResp = await client.GetFromJsonAsync<ApiResponse<CentralEncounterDetail>>( var existingPatient = await db.Patients.FindAsync([summary.PatientId], ct);
$"/api/v1/encounters/{summary.EncounterId}", if (existingPatient is not null
CentralApiJson.Options, && !string.IsNullOrEmpty(summary.Mrn)
ct); && !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<ApiResponse<CentralEncounterDetail>>(
CentralApiJson.Options, ct);
if (detailResp?.Data is null) if (detailResp?.Data is null)
{ {
@@ -124,6 +143,43 @@ public sealed class EncounterReplicaSyncService : BackgroundService
return synced; 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) private static void UpsertReplica(GatewayDbContext db, CentralEncounterDetail detail)
{ {
var now = DateTimeOffset.UtcNow; var now = DateTimeOffset.UtcNow;
@@ -184,14 +240,17 @@ public sealed class EncounterReplicaSyncService : BackgroundService
private async Task SyncThresholdsAsync( private async Task SyncThresholdsAsync(
HttpClient client, HttpClient client,
string jwt,
GatewayDbContext db, GatewayDbContext db,
IConnectionMultiplexer redis, IConnectionMultiplexer redis,
CancellationToken ct) CancellationToken ct)
{ {
var thrResp = await client.GetFromJsonAsync<ApiResponse<List<CentralAlertThreshold>>>( using var thrReq = new HttpRequestMessage(HttpMethod.Get, "api/v1/alert-thresholds");
"/api/v1/alert-thresholds", thrReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
CentralApiJson.Options, using var thrHttp = await client.SendAsync(thrReq, ct);
ct); thrHttp.EnsureSuccessStatusCode();
var thrResp = await thrHttp.Content.ReadFromJsonAsync<ApiResponse<List<CentralAlertThreshold>>>(
CentralApiJson.Options, ct);
if (thrResp?.Data is null) if (thrResp?.Data is null)
return; return;
@@ -216,12 +275,4 @@ public sealed class EncounterReplicaSyncService : BackgroundService
await ThresholdCacheLoader.RefreshAsync(db, redis, _logger, ct); 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);
}
} }
@@ -1,3 +1,4 @@
using System.Net.Http.Json;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
@@ -45,15 +46,16 @@ public sealed class GatewayHeartbeatService : BackgroundService
try try
{ {
var client = _http.CreateClient("central"); var client = _http.CreateClient("central");
client.BaseAddress = new Uri( using var message = new HttpRequestMessage(
scope.ServiceProvider.GetRequiredService<IOptions<CentralApiOptions>>().Value.BaseUrl); HttpMethod.Patch,
client.DefaultRequestHeaders.Remove("X-Api-Key"); $"api/v1/gateways/{_gateway.GatewayId}/heartbeat")
client.DefaultRequestHeaders.Remove("X-Gateway-Id"); {
client.DefaultRequestHeaders.Add("X-Api-Key", _config["ApiKey:Gateway"]); Content = JsonContent.Create(req)
client.DefaultRequestHeaders.Add("X-Gateway-Id", _gateway.GatewayId.ToString()); };
message.Headers.TryAddWithoutValidation("X-Api-Key", _config["ApiKey:Gateway"]);
message.Headers.TryAddWithoutValidation("X-Gateway-Id", _gateway.GatewayId.ToString());
var resp = await client.PatchAsJsonAsync( var resp = await client.SendAsync(message, ct);
$"/api/v1/gateways/{_gateway.GatewayId}/heartbeat", req, ct);
if (!resp.IsSuccessStatusCode) if (!resp.IsSuccessStatusCode)
_logger.LogWarning("Heartbeat failed: {Status}", resp.StatusCode); _logger.LogWarning("Heartbeat failed: {Status}", resp.StatusCode);
} }
@@ -52,7 +52,7 @@ public sealed class LocalEscalationWorkerService : BackgroundService
using var connection = factory.CreateConnection("gateway-escalation-worker"); using var connection = factory.CreateConnection("gateway-escalation-worker");
using var channel = connection.CreateModel(); using var channel = connection.CreateModel();
channel.BasicQos(0, prefetchCount: 5, global: false); channel.BasicQos(0, prefetchCount: 1, global: false);
var consumer = new AsyncEventingBasicConsumer(channel); var consumer = new AsyncEventingBasicConsumer(channel);
consumer.Received += async (_, ea) => consumer.Received += async (_, ea) =>
@@ -70,7 +70,7 @@ public sealed class LocalEscalationWorkerService : BackgroundService
private async Task HandleEscalationAsync(IModel channel, BasicDeliverEventArgs ea, CancellationToken ct) private async Task HandleEscalationAsync(IModel channel, BasicDeliverEventArgs ea, CancellationToken ct)
{ {
var payload = Encoding.UTF8.GetString(ea.Body.Span); 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 alertId = Guid.Parse(doc.RootElement.GetProperty("alertId").GetString()!);
_logger.LogCritical("[ESCALATION] Paging on-call backup for alert {AlertId}", alertId); _logger.LogCritical("[ESCALATION] Paging on-call backup for alert {AlertId}", alertId);
@@ -87,7 +87,7 @@ public sealed class LocalPagingWorkerService : BackgroundService
{ {
var o = _opts.Value; var o = _opts.Value;
var payload = Encoding.UTF8.GetString(ea.Body.Span); 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 alertId = Guid.Parse(doc.RootElement.GetProperty("alertId").GetString()!);
var encounterId = doc.RootElement.GetProperty("encounterId").GetString(); var encounterId = doc.RootElement.GetProperty("encounterId").GetString();
var details = doc.RootElement.TryGetProperty("details", out var d) ? d.GetString() : null; 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) while (DateTimeOffset.UtcNow < deadline && !ct.IsCancellationRequested)
{ {
await Task.Delay(2_000, ct); await Task.Delay(5_000, ct);
if (await IsAlertAcknowledgedAsync(alertId, ct)) if (await IsAlertAcknowledgedAsync(alertId, ct))
{ {
@@ -68,43 +68,53 @@ public sealed class SyncUploaderService : BackgroundService
var request = BuildBatchRequest(batchRef, pending); var request = BuildBatchRequest(batchRef, pending);
var client = scope.ServiceProvider.GetRequiredService<IHttpClientFactory>().CreateClient("central"); var client = scope.ServiceProvider.GetRequiredService<IHttpClientFactory>().CreateClient("central");
client.BaseAddress = new Uri( var apiKey = _config["ApiKey:Gateway"]!;
scope.ServiceProvider.GetRequiredService<IOptions<CentralApiOptions>>().Value.BaseUrl); var gatewayId = _gateway.GatewayId.ToString();
client.DefaultRequestHeaders.Add("X-Api-Key", _config["ApiKey:Gateway"]!);
client.DefaultRequestHeaders.Add("X-Gateway-Id", _gateway.GatewayId.ToString());
var submit = await client.PostAsJsonAsync("/api/v1/sync/batches", request, ct); using (var submitMsg = new HttpRequestMessage(HttpMethod.Post, "api/v1/sync/batches")
submit.EnsureSuccessStatusCode();
var batchId = (await submit.Content.ReadFromJsonAsync<ApiResponse<SyncBatchStatus>>(ct))!.Data!.BatchId;
for (var i = 0; i < 30; i++)
{ {
await Task.Delay(2000, ct); Content = JsonContent.Create(request)
var status = await client.GetFromJsonAsync<ApiResponse<SyncBatchStatus>>( })
$"/api/v1/sync/batches/{batchId}", ct); {
if (status?.Data?.Status is "APPLIED") submitMsg.Headers.TryAddWithoutValidation("X-Api-Key", apiKey);
{ submitMsg.Headers.TryAddWithoutValidation("X-Gateway-Id", gatewayId);
foreach (var item in pending) var submit = await client.SendAsync(submitMsg, ct);
{ submit.EnsureSuccessStatusCode();
item.Synced = true; var batchId = (await submit.Content.ReadFromJsonAsync<ApiResponse<SyncBatchStatus>>(ct))!.Data!.BatchId;
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); 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<ApiResponse<SyncBatchStatus>>(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<BufferedSyncItem> items) private ClinicalSyncBatchRequest BuildBatchRequest(Guid batchRef, List<BufferedSyncItem> items)
@@ -51,7 +51,7 @@ public class ThresholdCacheLoader : IHostedService
{ {
try try
{ {
WriteThresholds(redis, thresholds); await WriteThresholdsAsync(redis, thresholds);
logger.LogInformation( logger.LogInformation(
"Loaded {Count} alert thresholds into gateway Redis cache", thresholds.Count); "Loaded {Count} alert thresholds into gateway Redis cache", thresholds.Count);
return; return;
@@ -73,10 +73,12 @@ public class ThresholdCacheLoader : IHostedService
maxAttempts); maxAttempts);
} }
private static void WriteThresholds(IConnectionMultiplexer redis, List<ReplicaAlertThreshold> thresholds) private static async Task WriteThresholdsAsync(
IConnectionMultiplexer redis, List<ReplicaAlertThreshold> thresholds)
{ {
var cache = redis.GetDatabase(); var cache = redis.GetDatabase();
var batch = cache.CreateBatch(); var batch = cache.CreateBatch();
var setTasks = new List<Task>(thresholds.Count);
foreach (var t in thresholds) foreach (var t in thresholds)
{ {
@@ -86,9 +88,10 @@ public class ThresholdCacheLoader : IHostedService
t.WarningLow, t.WarningLow,
t.WarningHigh, t.WarningHigh,
t.CriticalHigh)); t.CriticalHigh));
_ = batch.StringSetAsync($"threshold:{t.ObservationCode}", json); setTasks.Add(batch.StringSetAsync($"threshold:{t.ObservationCode}", json));
} }
batch.Execute(); batch.Execute();
await Task.WhenAll(setTasks);
} }
} }
@@ -9,6 +9,13 @@ public sealed class GatewayOptions
public int HeartbeatIntervalSeconds { get; init; } = 60; public int HeartbeatIntervalSeconds { get; init; } = 60;
public int SyncBatchSize { get; init; } = 500; public int SyncBatchSize { get; init; } = 500;
/// <summary>
/// Hard cap on unsynced <c>buffered_sync_items</c>. 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.
/// </summary>
public int MaxBufferedSyncItems { get; init; } = 50_000;
/// <summary> /// <summary>
/// When true (default), applies EF migrations at startup. The gateway is /// When true (default), applies EF migrations at startup. The gateway is
/// single-instance by design, so startup migration is safe. Set false if /// single-instance by design, so startup migration is safe. Set false if
@@ -7,10 +7,22 @@ public sealed class CentralEncounterListPage
public int TotalPages { get; set; } public int TotalPages { get; set; }
} }
/// <summary>
/// Mirrors central <c>WardEncounterSummary</c> list payload so replica sync can
/// upsert without a detail GET when the patient already exists locally.
/// </summary>
public sealed class CentralWardEncounterSummary public sealed class CentralWardEncounterSummary
{ {
public Guid EncounterId { get; set; } public Guid EncounterId { get; set; }
public Guid PatientId { 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 public sealed class CentralEncounterDetail
+7 -1
View File
@@ -49,7 +49,13 @@ try
builder.Services.AddFluentValidationAutoValidation(); builder.Services.AddFluentValidationAutoValidation();
builder.Services.AddValidatorsFromAssemblyContaining<Program>(); builder.Services.AddValidatorsFromAssemblyContaining<Program>();
builder.Services.AddHttpClient("central"); builder.Services.AddHttpClient("central", (sp, client) =>
{
var baseUrl = sp.GetRequiredService<Microsoft.Extensions.Options.IOptions<CentralApiOptions>>()
.Value.BaseUrl.TrimEnd('/') + "/";
client.BaseAddress = new Uri(baseUrl);
client.Timeout = TimeSpan.FromSeconds(30);
});
builder.Services.AddSingleton<CentralReachabilityService>(); builder.Services.AddSingleton<CentralReachabilityService>();
builder.Services.AddHostedService(sp => sp.GetRequiredService<CentralReachabilityService>()); builder.Services.AddHostedService(sp => sp.GetRequiredService<CentralReachabilityService>());
@@ -1,4 +1,5 @@
using System.Text.Json; using System.Text.Json;
using Microsoft.EntityFrameworkCore;
public static class BufferedSyncWriter public static class BufferedSyncWriter
{ {
@@ -8,8 +9,21 @@ public static class BufferedSyncWriter
object payload, object payload,
string idempotencyKey, string idempotencyKey,
Guid encounterId, Guid encounterId,
DateTimeOffset recordedAt) DateTimeOffset recordedAt,
int maxUnsyncedItems = 50_000)
{ {
var persisted = db.BufferedSyncItems.Count(b => !b.Synced);
var pendingAdd = db.ChangeTracker.Entries<BufferedSyncItem>()
.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 db.BufferedSyncItems.Add(new BufferedSyncItem
{ {
Id = Guid.NewGuid(), Id = Guid.NewGuid(),
@@ -1,10 +1,16 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
public class LocalAlertService : ILocalAlertService public class LocalAlertService : ILocalAlertService
{ {
private readonly GatewayDbContext _db; private readonly GatewayDbContext _db;
private readonly GatewayOptions _gateway;
public LocalAlertService(GatewayDbContext db) => _db = db; public LocalAlertService(GatewayDbContext db, IOptions<GatewayOptions> gateway)
{
_db = db;
_gateway = gateway.Value;
}
public async Task<LocalClinicalAlert> AcknowledgeAsync( public async Task<LocalClinicalAlert> AcknowledgeAsync(
Guid id, AcknowledgeAlertRequest req, string clinicianId) Guid id, AcknowledgeAlertRequest req, string clinicianId)
@@ -26,7 +32,8 @@ public class LocalAlertService : ILocalAlertService
clinicianId, clinicianId,
acknowledgedAt = alert.AcknowledgedAt, acknowledgedAt = alert.AcknowledgedAt,
req.Note 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(); await _db.SaveChangesAsync();
return alert; return alert;
@@ -50,7 +57,8 @@ public class LocalAlertService : ILocalAlertService
clinicianId = alert.AcknowledgedBy, clinicianId = alert.AcknowledgedBy,
resolvedAt = alert.ResolvedAt, resolvedAt = alert.ResolvedAt,
note = (string?)null note = (string?)null
}, $"resolve:{alert.ClientAlertId}", alert.EncounterId, alert.ResolvedAt!.Value); }, $"resolve:{alert.ClientAlertId}", alert.EncounterId, alert.ResolvedAt!.Value,
_gateway.MaxBufferedSyncItems);
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
return alert; return alert;
@@ -1,5 +1,6 @@
using System.Text.Json; using System.Text.Json;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using StackExchange.Redis; using StackExchange.Redis;
public class LocalObservationService : ILocalObservationService public class LocalObservationService : ILocalObservationService
@@ -8,6 +9,7 @@ public class LocalObservationService : ILocalObservationService
private readonly IConnectionMultiplexer _redis; private readonly IConnectionMultiplexer _redis;
private readonly LocalWarningEvaluator _warnings; private readonly LocalWarningEvaluator _warnings;
private readonly LocalPagingPublisher _paging; private readonly LocalPagingPublisher _paging;
private readonly GatewayOptions _gateway;
private readonly ILogger<LocalObservationService> _logger; private readonly ILogger<LocalObservationService> _logger;
public LocalObservationService( public LocalObservationService(
@@ -15,12 +17,14 @@ public class LocalObservationService : ILocalObservationService
IConnectionMultiplexer redis, IConnectionMultiplexer redis,
LocalWarningEvaluator warnings, LocalWarningEvaluator warnings,
LocalPagingPublisher paging, LocalPagingPublisher paging,
IOptions<GatewayOptions> gateway,
ILogger<LocalObservationService> logger) ILogger<LocalObservationService> logger)
{ {
_db = db; _db = db;
_redis = redis; _redis = redis;
_warnings = warnings; _warnings = warnings;
_paging = paging; _paging = paging;
_gateway = gateway.Value;
_logger = logger; _logger = logger;
} }
@@ -94,7 +98,8 @@ public class LocalObservationService : ILocalObservationService
severity = alert.Severity.ToDbString(), severity = alert.Severity.ToDbString(),
alert.Details, alert.Details,
generatedAt = triggeredAt generatedAt = triggeredAt
}, $"alert:{alert.ClientAlertId}", encounterId, triggeredAt); }, $"alert:{alert.ClientAlertId}", encounterId, triggeredAt,
_gateway.MaxBufferedSyncItems);
await _paging.PublishCriticalAsync(alert, encounter); await _paging.PublishCriticalAsync(alert, encounter);
} }
@@ -114,7 +119,8 @@ public class LocalObservationService : ILocalObservationService
req.Unit, req.Unit,
source = req.Source.ToDbString(), source = req.Source.ToDbString(),
req.RecordedAt req.RecordedAt
}, req.IdempotencyKey ?? $"obs:{observation.Id}", encounterId, req.RecordedAt); }, req.IdempotencyKey ?? $"obs:{observation.Id}", encounterId, req.RecordedAt,
_gateway.MaxBufferedSyncItems);
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
await tx.CommitAsync(); await tx.CommitAsync();
@@ -1,13 +1,19 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
public class LocalWarningEvaluator public class LocalWarningEvaluator
{ {
private readonly GatewayDbContext _db; private readonly GatewayDbContext _db;
private readonly GatewayOptions _gateway;
private readonly ILogger<LocalWarningEvaluator> _logger; private readonly ILogger<LocalWarningEvaluator> _logger;
public LocalWarningEvaluator(GatewayDbContext db, ILogger<LocalWarningEvaluator> logger) public LocalWarningEvaluator(
GatewayDbContext db,
IOptions<GatewayOptions> gateway,
ILogger<LocalWarningEvaluator> logger)
{ {
_db = db; _db = db;
_gateway = gateway.Value;
_logger = logger; _logger = logger;
} }
@@ -52,7 +58,8 @@ public class LocalWarningEvaluator
severity = AlertSeverity.Warning.ToDbString(), severity = AlertSeverity.Warning.ToDbString(),
details, details,
generatedAt = triggeredAt generatedAt = triggeredAt
}, $"alert:{clientAlertId}", encounterId, triggeredAt); }, $"alert:{clientAlertId}", encounterId, triggeredAt,
_gateway.MaxBufferedSyncItems);
_logger.LogInformation( _logger.LogInformation(
"WARNING alert {AlertId} created locally for encounter {EncounterId}", "WARNING alert {AlertId} created locally for encounter {EncounterId}",
+1
View File
@@ -27,6 +27,7 @@
"CentralReachabilityIntervalSeconds": 30, "CentralReachabilityIntervalSeconds": 30,
"HeartbeatIntervalSeconds": 60, "HeartbeatIntervalSeconds": 60,
"SyncBatchSize": 500, "SyncBatchSize": 500,
"MaxBufferedSyncItems": 50000,
"AutoMigrate": true "AutoMigrate": true
}, },
"ApiKey": { "ApiKey": {
@@ -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<string, string>? 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<string, string>? 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<string, string> BuildConsumeResult(
string topic, int partition, long offset, string value) =>
new()
{
Topic = topic,
Partition = new Partition(partition),
Offset = new Offset(offset),
Message = new Message<string, string> { Key = "test-key", Value = value }
};
}
@@ -28,7 +28,7 @@ public sealed class ClinicalSyncBatchConsumer : BackgroundService
using var connection = factory.CreateConnection("clinical-sync-consumer"); using var connection = factory.CreateConnection("clinical-sync-consumer");
using var channel = connection.CreateModel(); using var channel = connection.CreateModel();
channel.BasicQos(0, prefetchCount: 5, global: false); channel.BasicQos(0, prefetchCount: 1, global: false);
var consumer = new AsyncEventingBasicConsumer(channel); var consumer = new AsyncEventingBasicConsumer(channel);
consumer.Received += async (_, ea) => consumer.Received += async (_, ea) =>
@@ -58,7 +58,7 @@ public sealed class ClinicalSyncBatchConsumer : BackgroundService
private async Task HandleMessageAsync(IModel channel, BasicDeliverEventArgs ea, CancellationToken ct) private async Task HandleMessageAsync(IModel channel, BasicDeliverEventArgs ea, CancellationToken ct)
{ {
var payload = Encoding.UTF8.GetString(ea.Body.Span); 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()!); var batchId = Guid.Parse(doc.RootElement.GetProperty("batchId").GetString()!);
await using var scope = _scopes.CreateAsyncScope(); await using var scope = _scopes.CreateAsyncScope();
@@ -74,16 +74,9 @@ public class EsIndexerService : BackgroundService
} }
catch (Exception ex) catch (Exception ex)
{ {
if (result is not null && guard.ShouldSkip(result, ex)) await KafkaConsumerRetry.HandleFailureAsync(
{ consumer, result, ex, guard, _logger, nameof(EsIndexerService), stoppingToken,
consumer.Commit(result); delayMs: 1000);
continue;
}
_logger.LogError(ex,
"EsIndexer failed processing topic={Topic} offset={Offset} — will retry",
result?.Topic, result?.Offset.Value);
await Task.Delay(1000, stoppingToken);
} }
} }
} }
@@ -46,7 +46,7 @@ public class GcsScoringService : BackgroundService
var evt = JsonSerializer.Deserialize<News2ObservationEvent>( var evt = JsonSerializer.Deserialize<News2ObservationEvent>(
result.Message.Value, result.Message.Value,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!; ClinicalEventJson.Options)!;
using var scope = _services.CreateScope(); using var scope = _services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<GcsDetector>(); var detector = scope.ServiceProvider.GetRequiredService<GcsDetector>();
@@ -76,16 +76,8 @@ public class GcsScoringService : BackgroundService
} }
catch (Exception ex) catch (Exception ex)
{ {
if (result is not null && guard.ShouldSkip(result, ex)) await KafkaConsumerRetry.HandleFailureAsync(
{ consumer, result, ex, guard, _logger, nameof(GcsScoringService), stoppingToken);
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);
} }
} }
} }
@@ -46,7 +46,7 @@ public class News2ScoringService : BackgroundService
var evt = JsonSerializer.Deserialize<News2ObservationEvent>( var evt = JsonSerializer.Deserialize<News2ObservationEvent>(
result.Message.Value, result.Message.Value,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!; ClinicalEventJson.Options)!;
using var scope = _services.CreateScope(); using var scope = _services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<News2Detector>(); var detector = scope.ServiceProvider.GetRequiredService<News2Detector>();
@@ -76,16 +76,8 @@ public class News2ScoringService : BackgroundService
} }
catch (Exception ex) catch (Exception ex)
{ {
if (result is not null && guard.ShouldSkip(result, ex)) await KafkaConsumerRetry.HandleFailureAsync(
{ consumer, result, ex, guard, _logger, nameof(News2ScoringService), stoppingToken);
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);
} }
} }
} }
@@ -2,6 +2,7 @@ using System.Text;
using System.Text.Json; using System.Text.Json;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Minio;
using Minio.DataModel.Args; using Minio.DataModel.Args;
using RabbitMQ.Client; using RabbitMQ.Client;
using RabbitMQ.Client.Events; using RabbitMQ.Client.Events;
@@ -10,17 +11,20 @@ public sealed class DischargeSummaryWorkerService : BackgroundService
{ {
private readonly IOptions<RabbitMqOptions> _rabbitOpts; private readonly IOptions<RabbitMqOptions> _rabbitOpts;
private readonly IOptions<MinioOptions> _minioOpts; private readonly IOptions<MinioOptions> _minioOpts;
private readonly IMinioClient _minio;
private readonly IServiceScopeFactory _scopes; private readonly IServiceScopeFactory _scopes;
private readonly ILogger<DischargeSummaryWorkerService> _logger; private readonly ILogger<DischargeSummaryWorkerService> _logger;
public DischargeSummaryWorkerService( public DischargeSummaryWorkerService(
IOptions<RabbitMqOptions> rabbitOpts, IOptions<RabbitMqOptions> rabbitOpts,
IOptions<MinioOptions> minioOpts, IOptions<MinioOptions> minioOpts,
IMinioClient minio,
IServiceScopeFactory scopes, IServiceScopeFactory scopes,
ILogger<DischargeSummaryWorkerService> logger) ILogger<DischargeSummaryWorkerService> logger)
{ {
_rabbitOpts = rabbitOpts; _rabbitOpts = rabbitOpts;
_minioOpts = minioOpts; _minioOpts = minioOpts;
_minio = minio;
_scopes = scopes; _scopes = scopes;
_logger = logger; _logger = logger;
} }
@@ -35,7 +39,7 @@ public sealed class DischargeSummaryWorkerService : BackgroundService
using var connection = factory.CreateConnection("discharge-summary-worker"); using var connection = factory.CreateConnection("discharge-summary-worker");
using var channel = connection.CreateModel(); using var channel = connection.CreateModel();
channel.BasicQos(0, prefetchCount: 3, global: false); channel.BasicQos(0, prefetchCount: 1, global: false);
var consumer = new AsyncEventingBasicConsumer(channel); var consumer = new AsyncEventingBasicConsumer(channel);
consumer.Received += async (sender, ea) => consumer.Received += async (sender, ea) =>
@@ -53,7 +57,7 @@ public sealed class DischargeSummaryWorkerService : BackgroundService
private async Task HandleDischargeSummaryAsync(IModel channel, BasicDeliverEventArgs ea, CancellationToken ct) private async Task HandleDischargeSummaryAsync(IModel channel, BasicDeliverEventArgs ea, CancellationToken ct)
{ {
var payload = Encoding.UTF8.GetString(ea.Body.Span); 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()!); var encounterId = Guid.Parse(doc.RootElement.GetProperty("encounterId").GetString()!);
try try
@@ -128,22 +132,22 @@ public sealed class DischargeSummaryWorkerService : BackgroundService
private async Task UploadToMinioAsync(Guid encounterId, string content, CancellationToken ct) private async Task UploadToMinioAsync(Guid encounterId, string content, CancellationToken ct)
{ {
var mo = _minioOpts.Value; var mo = _minioOpts.Value;
var client = MinioClientFactory.Build(mo);
var bucket = mo.BucketName; var bucket = mo.BucketName;
var exists = await client.BucketExistsAsync( var exists = await _minio.BucketExistsAsync(
new BucketExistsArgs().WithBucket(bucket), ct); new BucketExistsArgs().WithBucket(bucket), ct);
if (!exists) 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 objectKey = $"discharge-summaries/{encounterId}/summary.pdf";
var bytes = Encoding.UTF8.GetBytes(content); 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) .WithBucket(bucket)
.WithObject(objectKey) .WithObject(objectKey)
.WithStreamData(new MemoryStream(bytes)) .WithStreamData(stream)
.WithObjectSize(bytes.Length) .WithObjectSize(bytes.Length)
.WithContentType("text/plain"), .WithContentType("text/plain"),
ct); ct);
@@ -34,7 +34,7 @@ public sealed class EscalationWorkerService : BackgroundService
using var connection = factory.CreateConnection("escalation-worker"); using var connection = factory.CreateConnection("escalation-worker");
using var channel = connection.CreateModel(); using var channel = connection.CreateModel();
channel.BasicQos(0, prefetchCount: 5, global: false); channel.BasicQos(0, prefetchCount: 1, global: false);
var consumer = new AsyncEventingBasicConsumer(channel); var consumer = new AsyncEventingBasicConsumer(channel);
consumer.Received += async (sender, ea) => consumer.Received += async (sender, ea) =>
@@ -52,7 +52,7 @@ public sealed class EscalationWorkerService : BackgroundService
private async Task HandleEscalationAsync(IModel channel, BasicDeliverEventArgs ea, CancellationToken ct) private async Task HandleEscalationAsync(IModel channel, BasicDeliverEventArgs ea, CancellationToken ct)
{ {
var payload = Encoding.UTF8.GetString(ea.Body.Span); 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 alertId = Guid.Parse(doc.RootElement.GetProperty("alertId").GetString()!);
var encounterId = Guid.Parse(doc.RootElement.GetProperty("encounterId").GetString()!); var encounterId = Guid.Parse(doc.RootElement.GetProperty("encounterId").GetString()!);
@@ -85,13 +85,8 @@ public sealed class NotificationPublisherService : BackgroundService
} }
catch (Exception ex) catch (Exception ex)
{ {
if (guard.ShouldSkip(result, ex)) await KafkaConsumerRetry.HandleFailureAsync(
{ consumer, result, ex, guard, _logger, nameof(NotificationPublisherService), stoppingToken);
consumer.Commit(result);
continue;
}
_logger.LogError(ex, "NotificationPublisher failed to process message from {Topic} — will retry", result.Topic);
} }
} }
} }
@@ -104,7 +99,7 @@ public sealed class NotificationPublisherService : BackgroundService
private Task HandleAlertGeneratedAsync( private Task HandleAlertGeneratedAsync(
IModel chan, IBasicProperties props, string payload, CancellationToken ct) 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(); var severity = doc.RootElement.GetProperty("severity").GetString();
if (!string.Equals(severity, "Critical", StringComparison.OrdinalIgnoreCase)) if (!string.Equals(severity, "Critical", StringComparison.OrdinalIgnoreCase))
@@ -142,7 +137,7 @@ public sealed class NotificationPublisherService : BackgroundService
private Task HandleEncounterStatusChangedAsync( private Task HandleEncounterStatusChangedAsync(
IModel chan, IBasicProperties props, string payload, CancellationToken ct) 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(); var newStatus = doc.RootElement.GetProperty("newStatus").GetString();
if (!string.Equals(newStatus, "Discharged", StringComparison.OrdinalIgnoreCase)) if (!string.Equals(newStatus, "Discharged", StringComparison.OrdinalIgnoreCase))
@@ -69,7 +69,7 @@ public sealed class PagingWorkerService : BackgroundService
{ {
var o = _opts.Value; var o = _opts.Value;
var payload = Encoding.UTF8.GetString(ea.Body.Span); 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 alertId = Guid.Parse(doc.RootElement.GetProperty("alertId").GetString()!);
var encounterId = doc.RootElement.GetProperty("encounterId").GetString(); var encounterId = doc.RootElement.GetProperty("encounterId").GetString();
var details = doc.RootElement.TryGetProperty("details", out var d) ? d.GetString() : null; 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) while (DateTimeOffset.UtcNow < deadline && !ct.IsCancellationRequested)
{ {
await Task.Delay(2_000, ct); await Task.Delay(5_000, ct);
var acknowledged = await IsAlertAcknowledgedAsync(alertId, ct); var acknowledged = await IsAlertAcknowledgedAsync(alertId, ct);
if (acknowledged) if (acknowledged)
@@ -2,6 +2,8 @@ using Microsoft.EntityFrameworkCore;
public class PatientPhiMigrationService : IHostedService public class PatientPhiMigrationService : IHostedService
{ {
private const int BatchSize = 500;
private readonly IServiceProvider _services; private readonly IServiceProvider _services;
private readonly ILogger<PatientPhiMigrationService> _logger; private readonly ILogger<PatientPhiMigrationService> _logger;
@@ -19,26 +21,47 @@ public class PatientPhiMigrationService : IHostedService
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>(); var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var crypto = scope.ServiceProvider.GetRequiredService<IPhiEncryptionService>(); var crypto = scope.ServiceProvider.GetRequiredService<IPhiEncryptionService>();
var patients = await db.Patients.ToListAsync(ct); var totalMigrated = 0;
var migrated = 0; Guid? afterId = null;
foreach (var patient in patients) while (!ct.IsCancellationRequested)
{ {
if (patient.NameSearchToken is not null && crypto.IsEncrypted(patient.FirstName)) IQueryable<Patient> query = db.Patients.OrderBy(p => p.Id);
continue; if (afterId is Guid cursor)
query = query.Where(p => p.Id.CompareTo(cursor) > 0);
patient.NameSearchToken = crypto.ComputeNameSearchToken( var batch = await query.Take(BatchSize).ToListAsync(ct);
patient.FirstName, patient.LastName); if (batch.Count == 0)
migrated++; 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( _logger.LogInformation(
"PHI migration: updated {Count} patient search tokens", migrated); "PHI migration: updated {Count} patient search tokens", totalMigrated);
} }
} }
public Task StopAsync(CancellationToken ct) => Task.CompletedTask; public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
} }
@@ -55,14 +55,21 @@ public sealed class DisconnectedMonitorsCheck
return 0; return 0;
} }
var inserted = 0; var encounterIds = stale.Select(e => e.EncounterId).ToList();
var alreadyOpen = (await _db.ReconciliationAlerts
.AsNoTracking()
.Where(r => r.CheckType == CheckType
&& r.ResolvedAt == null
&& r.EncounterId != null
&& encounterIds.Contains(r.EncounterId.Value))
.Select(r => r.EncounterId!.Value)
.ToListAsync(ct))
.ToHashSet();
var created = new List<ReconciliationAlert>();
foreach (var enc in stale) foreach (var enc in stale)
{ {
var alreadyOpen = await _db.ReconciliationAlerts if (alreadyOpen.Contains(enc.EncounterId)) continue;
.AnyAsync(r => r.CheckType == CheckType
&& r.EncounterId == enc.EncounterId
&& r.ResolvedAt == null, ct);
if (alreadyOpen) continue;
var lastObs = enc.LastObservationAt.HasValue var lastObs = enc.LastObservationAt.HasValue
? $"last observation {enc.LastObservationAt:u}" ? $"last observation {enc.LastObservationAt:u}"
@@ -73,7 +80,7 @@ public sealed class DisconnectedMonitorsCheck
var rec = new ReconciliationAlert var rec = new ReconciliationAlert
{ {
Id = Guid.NewGuid(), Id = Guid.NewGuid(),
CheckType = CheckType, // ReconciliationCheckType enum CheckType = CheckType,
EncounterId = enc.EncounterId, EncounterId = enc.EncounterId,
PatientId = enc.PatientId, PatientId = enc.PatientId,
Details = details, Details = details,
@@ -81,16 +88,20 @@ public sealed class DisconnectedMonitorsCheck
}; };
_db.ReconciliationAlerts.Add(rec); _db.ReconciliationAlerts.Add(rec);
await _db.SaveChangesAsync(ct); created.Add(rec);
await _publisher.PublishAsync(rec, ct);
_logger.LogWarning( _logger.LogWarning(
"[RECONCILIATION] {CheckType} — encounter {EncounterId}: {LastObs}", "[RECONCILIATION] {CheckType} — encounter {EncounterId}: {LastObs}",
CheckType, enc.EncounterId, lastObs); CheckType, enc.EncounterId, lastObs);
inserted++;
} }
return inserted; if (created.Count > 0)
{
await _db.SaveChangesAsync(ct);
foreach (var rec in created)
await _publisher.PublishAsync(rec, ct);
}
return created.Count;
} }
} }
@@ -52,14 +52,21 @@ public sealed class PendingOrdersCheck
.GroupBy(o => new { o.EncounterId, o.PatientId }) .GroupBy(o => new { o.EncounterId, o.PatientId })
.ToList(); .ToList();
var inserted = 0; var encounterIds = byEncounter.Select(g => g.Key.EncounterId).ToList();
var alreadyOpen = (await _db.ReconciliationAlerts
.AsNoTracking()
.Where(r => r.CheckType == CheckType
&& r.ResolvedAt == null
&& r.EncounterId != null
&& encounterIds.Contains(r.EncounterId.Value))
.Select(r => r.EncounterId!.Value)
.ToListAsync(ct))
.ToHashSet();
var created = new List<ReconciliationAlert>();
foreach (var group in byEncounter) foreach (var group in byEncounter)
{ {
var alreadyOpen = await _db.ReconciliationAlerts if (alreadyOpen.Contains(group.Key.EncounterId)) continue;
.AnyAsync(r => r.CheckType == CheckType
&& r.EncounterId == group.Key.EncounterId
&& r.ResolvedAt == null, ct);
if (alreadyOpen) continue;
var lines = group.Select(o => var lines = group.Select(o =>
$" [{o.OrderType.ToDbString()}] {o.Description} (ordered {o.OrderedAt:u}, " $" [{o.OrderType.ToDbString()}] {o.Description} (ordered {o.OrderedAt:u}, "
@@ -70,7 +77,7 @@ public sealed class PendingOrdersCheck
var rec = new ReconciliationAlert var rec = new ReconciliationAlert
{ {
Id = Guid.NewGuid(), Id = Guid.NewGuid(),
CheckType = CheckType, // ReconciliationCheckType enum CheckType = CheckType,
EncounterId = group.Key.EncounterId, EncounterId = group.Key.EncounterId,
PatientId = group.Key.PatientId, PatientId = group.Key.PatientId,
Details = details, Details = details,
@@ -78,16 +85,20 @@ public sealed class PendingOrdersCheck
}; };
_db.ReconciliationAlerts.Add(rec); _db.ReconciliationAlerts.Add(rec);
await _db.SaveChangesAsync(ct); created.Add(rec);
await _publisher.PublishAsync(rec, ct);
_logger.LogWarning( _logger.LogWarning(
"[RECONCILIATION] {CheckType} — encounter {EncounterId}: {Count} stale order(s)", "[RECONCILIATION] {CheckType} — encounter {EncounterId}: {Count} stale order(s)",
CheckType, group.Key.EncounterId, group.Count()); CheckType, group.Key.EncounterId, group.Count());
inserted++;
} }
return inserted; if (created.Count > 0)
{
await _db.SaveChangesAsync(ct);
foreach (var rec in created)
await _publisher.PublishAsync(rec, ct);
}
return created.Count;
} }
} }
@@ -27,7 +27,6 @@ public sealed class UnacknowledgedAlertsCheck
var cutoff = DateTimeOffset.UtcNow var cutoff = DateTimeOffset.UtcNow
.AddMinutes(-_opts.UnacknowledgedAlertThresholdMinutes); .AddMinutes(-_opts.UnacknowledgedAlertThresholdMinutes);
// Load all stale critical alerts, grouped by encounter.
var staleAlerts = await _db.ClinicalAlerts var staleAlerts = await _db.ClinicalAlerts
.Where(a => a.Severity == AlertSeverity.Critical .Where(a => a.Severity == AlertSeverity.Critical
&& a.Status == AlertStatus.Open && a.Status == AlertStatus.Open
@@ -41,21 +40,25 @@ public sealed class UnacknowledgedAlertsCheck
return 0; return 0;
} }
// Group by encounter so one reconciliation_alert covers all alerts in that encounter.
var byEncounter = staleAlerts var byEncounter = staleAlerts
.GroupBy(a => new { a.EncounterId, a.PatientId }) .GroupBy(a => new { a.EncounterId, a.PatientId })
.ToList(); .ToList();
var inserted = 0; var encounterIds = byEncounter.Select(g => g.Key.EncounterId).ToList();
var alreadyOpen = (await _db.ReconciliationAlerts
.AsNoTracking()
.Where(r => r.CheckType == CheckType
&& r.ResolvedAt == null
&& r.EncounterId != null
&& encounterIds.Contains(r.EncounterId.Value))
.Select(r => r.EncounterId!.Value)
.ToListAsync(ct))
.ToHashSet();
var created = new List<ReconciliationAlert>();
foreach (var group in byEncounter) foreach (var group in byEncounter)
{ {
// Deduplication: skip if an open reconciliation_alert already exists if (alreadyOpen.Contains(group.Key.EncounterId)) continue;
// 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;
var alertIds = group.Select(a => a.Id).ToList(); var alertIds = group.Select(a => a.Id).ToList();
var oldest = group.Min(a => a.TriggeredAt); var oldest = group.Min(a => a.TriggeredAt);
@@ -66,7 +69,7 @@ public sealed class UnacknowledgedAlertsCheck
var rec = new ReconciliationAlert var rec = new ReconciliationAlert
{ {
Id = Guid.NewGuid(), Id = Guid.NewGuid(),
CheckType = CheckType, // ReconciliationCheckType enum CheckType = CheckType,
EncounterId = group.Key.EncounterId, EncounterId = group.Key.EncounterId,
PatientId = group.Key.PatientId, PatientId = group.Key.PatientId,
Details = details, Details = details,
@@ -74,16 +77,20 @@ public sealed class UnacknowledgedAlertsCheck
}; };
_db.ReconciliationAlerts.Add(rec); _db.ReconciliationAlerts.Add(rec);
await _db.SaveChangesAsync(ct); created.Add(rec);
await _publisher.PublishAsync(rec, ct);
_logger.LogWarning( _logger.LogWarning(
"[RECONCILIATION] {CheckType} — encounter {EncounterId}: {Details}", "[RECONCILIATION] {CheckType} — encounter {EncounterId}: {Details}",
CheckType, group.Key.EncounterId, details); CheckType, group.Key.EncounterId, details);
inserted++;
} }
return inserted; if (created.Count > 0)
{
await _db.SaveChangesAsync(ct);
foreach (var rec in created)
await _publisher.PublishAsync(rec, ct);
}
return created.Count;
} }
} }
@@ -78,16 +78,8 @@ public class SepsisEngineService : BackgroundService
} }
catch (Exception ex) catch (Exception ex)
{ {
if (result is not null && guard.ShouldSkip(result, ex)) await KafkaConsumerRetry.HandleFailureAsync(
{ consumer, result, ex, guard, _logger, nameof(SepsisEngineService), stoppingToken);
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);
} }
} }
} }
@@ -55,7 +55,7 @@ public class SofaScoringService : BackgroundService
{ {
var gcsEvt = JsonSerializer.Deserialize<GcsScoredEvent>( var gcsEvt = JsonSerializer.Deserialize<GcsScoredEvent>(
result.Message.Value, result.Message.Value,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!; ClinicalEventJson.Options)!;
var outcome = await detector.ProcessGcsScoredAsync( var outcome = await detector.ProcessGcsScoredAsync(
gcsEvt.EncounterId, gcsEvt.PatientId, stoppingToken); gcsEvt.EncounterId, gcsEvt.PatientId, stoppingToken);
@@ -73,7 +73,7 @@ public class SofaScoringService : BackgroundService
{ {
var evt = JsonSerializer.Deserialize<News2ObservationEvent>( var evt = JsonSerializer.Deserialize<News2ObservationEvent>(
result.Message.Value, result.Message.Value,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!; ClinicalEventJson.Options)!;
var outcome = await detector.ProcessObservationAsync( var outcome = await detector.ProcessObservationAsync(
evt.EncounterId, evt.EncounterId,
@@ -102,16 +102,8 @@ public class SofaScoringService : BackgroundService
} }
catch (Exception ex) catch (Exception ex)
{ {
if (result is not null && guard.ShouldSkip(result, ex)) await KafkaConsumerRetry.HandleFailureAsync(
{ consumer, result, ex, guard, _logger, nameof(SofaScoringService), stoppingToken);
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);
} }
} }
} }
@@ -34,6 +34,7 @@ public class ThresholdCacheLoader : IHostedService
{ {
var cache = _redis.GetDatabase(); var cache = _redis.GetDatabase();
var batch = cache.CreateBatch(); var batch = cache.CreateBatch();
var setTasks = new List<Task>(thresholds.Count);
foreach (var t in thresholds) foreach (var t in thresholds)
{ {
@@ -45,10 +46,11 @@ public class ThresholdCacheLoader : IHostedService
t.WarningHigh, t.WarningHigh,
t.CriticalHigh t.CriticalHigh
}); });
_ = batch.StringSetAsync($"threshold:{t.ObservationCode}", json); setTasks.Add(batch.StringSetAsync($"threshold:{t.ObservationCode}", json));
} }
batch.Execute(); batch.Execute();
await Task.WhenAll(setTasks);
_logger.LogInformation("Loaded {Count} alert thresholds into Redis cache", thresholds.Count); _logger.LogInformation("Loaded {Count} alert thresholds into Redis cache", thresholds.Count);
return; return;
} }
@@ -46,7 +46,7 @@ public class TrendAnalyzerService : BackgroundService
var evt = JsonSerializer.Deserialize<TrendObservationEvent>( var evt = JsonSerializer.Deserialize<TrendObservationEvent>(
result.Message.Value, result.Message.Value,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!; ClinicalEventJson.Options)!;
using var scope = _services.CreateScope(); using var scope = _services.CreateScope();
var detector = scope.ServiceProvider.GetRequiredService<TrendDetector>(); var detector = scope.ServiceProvider.GetRequiredService<TrendDetector>();
@@ -77,16 +77,8 @@ public class TrendAnalyzerService : BackgroundService
} }
catch (Exception ex) catch (Exception ex)
{ {
if (result is not null && guard.ShouldSkip(result, ex)) await KafkaConsumerRetry.HandleFailureAsync(
{ consumer, result, ex, guard, _logger, nameof(TrendAnalyzerService), stoppingToken);
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);
} }
} }
} }
@@ -46,7 +46,7 @@ public class WarningAlertService : BackgroundService
var evt = JsonSerializer.Deserialize<WarningObservationEvent>( var evt = JsonSerializer.Deserialize<WarningObservationEvent>(
result.Message.Value, result.Message.Value,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!; ClinicalEventJson.Options)!;
using var scope = _services.CreateScope(); using var scope = _services.CreateScope();
var evaluator = scope.ServiceProvider.GetRequiredService<WarningEvaluator>(); var evaluator = scope.ServiceProvider.GetRequiredService<WarningEvaluator>();
@@ -68,16 +68,8 @@ public class WarningAlertService : BackgroundService
} }
catch (Exception ex) catch (Exception ex)
{ {
if (result is not null && guard.ShouldSkip(result, ex)) await KafkaConsumerRetry.HandleFailureAsync(
{ consumer, result, ex, guard, _logger, nameof(WarningAlertService), stoppingToken);
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);
} }
} }
} }
@@ -9,7 +9,8 @@ public static class DataLakeEventParser
{ {
public static ObservationRow ParseObservationRow(string payload, long offset, int partition) 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 encounterId = GetString(d, "encounterId");
var observationId = GetString(d, "observationId"); var observationId = GetString(d, "observationId");
if (string.IsNullOrEmpty(observationId)) if (string.IsNullOrEmpty(observationId))
@@ -31,7 +32,8 @@ public static class DataLakeEventParser
public static AlertRow ParseAlertRow(string payload, long offset, int partition) 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( return new AlertRow(
AlertId : GetString(d, "alertId"), AlertId : GetString(d, "alertId"),
EncounterId : GetString(d, "encounterId"), EncounterId : GetString(d, "encounterId"),
@@ -47,7 +49,8 @@ public static class DataLakeEventParser
public static EncounterStatusRow ParseEncounterRow(string payload, long offset, int partition) 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( return new EncounterStatusRow(
EncounterId : GetString(d, "encounterId"), EncounterId : GetString(d, "encounterId"),
PatientId : GetString(d, "patientId"), PatientId : GetString(d, "patientId"),
@@ -62,7 +65,7 @@ public static class DataLakeEventParser
{ {
try try
{ {
var doc = JsonDocument.Parse(payload); using var doc = JsonDocument.Parse(payload);
var ts = topic switch var ts = topic switch
{ {
var t when t == topics.ObservationRecorded => GetTimestamp(doc.RootElement, "recordedAt"), var t when t == topics.ObservationRecorded => GetTimestamp(doc.RootElement, "recordedAt"),
@@ -11,6 +11,13 @@ public sealed class DataLakeOptions
// Production: 300 seconds (5 minutes). Tests: 10 seconds. // Production: 300 seconds (5 minutes). Tests: 10 seconds.
public int FlushIntervalSeconds { get; init; } = 300; public int FlushIntervalSeconds { get; init; } = 300;
/// <summary>
/// Hard cap on in-memory buffered events across all partitions. When reached,
/// consume seeks back and pauses until a flush frees space (prevents OOM when
/// MinIO is down while Kafka keeps delivering).
/// </summary>
public int MaxBufferedEvents { get; init; } = 50_000;
// MinIO bucket. The discharge summary worker from Phase 6 uses the same bucket // MinIO bucket. The discharge summary worker from Phase 6 uses the same bucket
// under a different prefix — all VigilCare data stays in one bucket. // under a different prefix — all VigilCare data stays in one bucket.
public string BucketName { get; init; } = "vigilcare"; public string BucketName { get; init; } = "vigilcare";
@@ -1,6 +1,7 @@
using System.Text.Json; using System.Text.Json;
using Confluent.Kafka; using Confluent.Kafka;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Minio;
using Minio.DataModel.Args; using Minio.DataModel.Args;
public sealed class DataLakeWriterService : BackgroundService public sealed class DataLakeWriterService : BackgroundService
@@ -8,6 +9,7 @@ public sealed class DataLakeWriterService : BackgroundService
private readonly KafkaOptions _kafkaOptions; private readonly KafkaOptions _kafkaOptions;
private readonly DataLakeOptions _opts; private readonly DataLakeOptions _opts;
private readonly MinioOptions _minioOpts; private readonly MinioOptions _minioOpts;
private readonly IMinioClient _minio;
private readonly ILogger<DataLakeWriterService> _logger; private readonly ILogger<DataLakeWriterService> _logger;
// Buffer key: identifies one Parquet file-to-be. // Buffer key: identifies one Parquet file-to-be.
@@ -24,11 +26,13 @@ public sealed class DataLakeWriterService : BackgroundService
IOptions<KafkaOptions> kafkaOptions, IOptions<KafkaOptions> kafkaOptions,
IOptions<DataLakeOptions> opts, IOptions<DataLakeOptions> opts,
IOptions<MinioOptions> minioOpts, IOptions<MinioOptions> minioOpts,
IMinioClient minio,
ILogger<DataLakeWriterService> logger) ILogger<DataLakeWriterService> logger)
{ {
_kafkaOptions = kafkaOptions.Value; _kafkaOptions = kafkaOptions.Value;
_opts = opts.Value; _opts = opts.Value;
_minioOpts = minioOpts.Value; _minioOpts = minioOpts.Value;
_minio = minio;
_logger = logger; _logger = logger;
} }
@@ -51,8 +55,8 @@ public sealed class DataLakeWriterService : BackgroundService
}); });
_logger.LogInformation( _logger.LogInformation(
"DataLakeWriterService started. FlushCount={FlushCount} FlushIntervalSeconds={FlushInterval}", "DataLakeWriterService started. FlushCount={FlushCount} FlushIntervalSeconds={FlushInterval} MaxBufferedEvents={MaxBuffered}",
_opts.FlushCount, _opts.FlushIntervalSeconds); _opts.FlushCount, _opts.FlushIntervalSeconds, _opts.MaxBufferedEvents);
var lastFlush = DateTimeOffset.UtcNow; var lastFlush = DateTimeOffset.UtcNow;
@@ -72,7 +76,24 @@ public sealed class DataLakeWriterService : BackgroundService
} }
if (result is not null) 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); AddToBuffer(result);
}
var totalBuffered = _buffer.Values.Sum(v => v.Count); var totalBuffered = _buffer.Values.Sum(v => v.Count);
var shouldFlushCount = totalBuffered >= _opts.FlushCount; var shouldFlushCount = totalBuffered >= _opts.FlushCount;
@@ -245,18 +266,18 @@ public sealed class DataLakeWriterService : BackgroundService
private async Task UploadToMinioAsync(string objectKey, byte[] bytes, CancellationToken ct) private async Task UploadToMinioAsync(string objectKey, byte[] bytes, CancellationToken ct)
{ {
var client = MinioClientFactory.Build(_minioOpts);
var bucket = _opts.BucketName; var bucket = _opts.BucketName;
var exists = await client.BucketExistsAsync( var exists = await _minio.BucketExistsAsync(
new BucketExistsArgs().WithBucket(bucket), ct); new BucketExistsArgs().WithBucket(bucket), ct);
if (!exists) 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) .WithBucket(bucket)
.WithObject(objectKey) .WithObject(objectKey)
.WithStreamData(new MemoryStream(bytes)) .WithStreamData(stream)
.WithObjectSize(bytes.Length) .WithObjectSize(bytes.Length)
.WithContentType("application/octet-stream"), .WithContentType("application/octet-stream"),
ct); ct);
@@ -0,0 +1,13 @@
using System.Text.Json;
/// <summary>
/// Shared JSON options for Kafka clinical event deserialization.
/// <see cref="JsonSerializerOptions"/> construction is expensive — reuse one instance.
/// </summary>
public static class ClinicalEventJson
{
public static readonly JsonSerializerOptions Options = new()
{
PropertyNameCaseInsensitive = true
};
}
@@ -0,0 +1,55 @@
using Confluent.Kafka;
/// <summary>
/// Shared transient-failure handling for Kafka consumers that use
/// <see cref="PoisonPillGuard"/>. After <c>Consume</c>, the client position
/// advances; without <c>Seek</c>, the next successful <c>Commit</c> would skip
/// the failed offset. This helper seeks back before delaying so retries truly
/// reprocess the same message.
/// </summary>
public static class KafkaConsumerRetry
{
public static Task HandleFailureAsync(
IConsumer<string, string> consumer,
ConsumeResult<string, string>? result,
Exception ex,
PoisonPillGuard guard,
ILogger logger,
string serviceName,
CancellationToken ct,
int delayMs = 2000) =>
HandleFailureAsync(
seek: tpo => consumer.Seek(tpo),
commit: r => consumer.Commit(r),
result, ex, guard, logger, serviceName, ct, delayMs);
/// <summary>
/// Testable overload — production code should prefer the <see cref="IConsumer{TKey,TValue}"/> overload.
/// </summary>
public static async Task HandleFailureAsync(
Action<TopicPartitionOffset> seek,
Action<ConsumeResult<string, string>> commit,
ConsumeResult<string, string>? result,
Exception ex,
PoisonPillGuard guard,
ILogger logger,
string serviceName,
CancellationToken ct,
int delayMs = 2000)
{
if (result is not null && guard.ShouldSkip(result, ex))
{
commit(result);
return;
}
logger.LogError(ex,
"{Service} failed on topic={Topic} offset={Offset} — will retry",
serviceName, result?.Topic, result?.Offset.Value);
if (result is not null)
seek(result.TopicPartitionOffset);
await Task.Delay(delayMs, ct);
}
}
+4
View File
@@ -1,6 +1,7 @@
using Elastic.Clients.Elasticsearch; using Elastic.Clients.Elasticsearch;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Diagnostics.HealthChecks;
using Minio;
using Prometheus; using Prometheus;
using Serilog; using Serilog;
using StackExchange.Redis; using StackExchange.Redis;
@@ -16,6 +17,7 @@ using Microsoft.AspNetCore.Authorization;
using System.Text; using System.Text;
using Microsoft.OpenApi; using Microsoft.OpenApi;
using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Options;
Log.Logger = new LoggerConfiguration() Log.Logger = new LoggerConfiguration()
.WriteTo.Console() .WriteTo.Console()
@@ -114,6 +116,8 @@ try
builder.Configuration.GetSection(RabbitMqOptions.Section)); builder.Configuration.GetSection(RabbitMqOptions.Section));
builder.Services.Configure<MinioOptions>( builder.Services.Configure<MinioOptions>(
builder.Configuration.GetSection(MinioOptions.Section)); builder.Configuration.GetSection(MinioOptions.Section));
builder.Services.AddSingleton<IMinioClient>(sp =>
MinioClientFactory.Build(sp.GetRequiredService<IOptions<MinioOptions>>().Value));
builder.Services.AddSingleton<RabbitMqTopologyProvisioner>(); builder.Services.AddSingleton<RabbitMqTopologyProvisioner>();
builder.Services.AddHostedService(sp => sp.GetRequiredService<RabbitMqTopologyProvisioner>()); builder.Services.AddHostedService(sp => sp.GetRequiredService<RabbitMqTopologyProvisioner>());
@@ -8,11 +8,16 @@ public sealed class DischargeSummaryService : IDischargeSummaryService
{ {
private readonly AppDbContext _db; private readonly AppDbContext _db;
private readonly MinioOptions _minioOpts; private readonly MinioOptions _minioOpts;
private readonly IMinioClient _minio;
public DischargeSummaryService(AppDbContext db, IOptions<MinioOptions> minioOpts) public DischargeSummaryService(
AppDbContext db,
IOptions<MinioOptions> minioOpts,
IMinioClient minio)
{ {
_db = db; _db = db;
_minioOpts = minioOpts.Value; _minioOpts = minioOpts.Value;
_minio = minio;
} }
public async Task<DischargeSummaryInfo> GetInfoAsync(Guid encounterId, CancellationToken ct = default) public async Task<DischargeSummaryInfo> GetInfoAsync(Guid encounterId, CancellationToken ct = default)
@@ -68,12 +73,11 @@ public sealed class DischargeSummaryService : IDischargeSummaryService
"DISCHARGE_SUMMARY_PENDING"); "DISCHARGE_SUMMARY_PENDING");
} }
var client = MinioClientFactory.Build(_minioOpts);
var bucket = _minioOpts.BucketName; var bucket = _minioOpts.BucketName;
var objectKey = ObjectKey(encounterId); var objectKey = ObjectKey(encounterId);
var ms = new MemoryStream(); var ms = new MemoryStream();
await client.GetObjectAsync(new GetObjectArgs() await _minio.GetObjectAsync(new GetObjectArgs()
.WithBucket(bucket) .WithBucket(bucket)
.WithObject(objectKey) .WithObject(objectKey)
.WithCallbackStream(stream => stream.CopyTo(ms)), ct); .WithCallbackStream(stream => stream.CopyTo(ms)), ct);
@@ -84,13 +88,12 @@ public sealed class DischargeSummaryService : IDischargeSummaryService
private async Task<bool> ObjectExistsAsync(Guid encounterId, CancellationToken ct) private async Task<bool> ObjectExistsAsync(Guid encounterId, CancellationToken ct)
{ {
var client = MinioClientFactory.Build(_minioOpts);
var bucket = _minioOpts.BucketName; var bucket = _minioOpts.BucketName;
var objectKey = ObjectKey(encounterId); var objectKey = ObjectKey(encounterId);
try try
{ {
await client.StatObjectAsync(new StatObjectArgs() await _minio.StatObjectAsync(new StatObjectArgs()
.WithBucket(bucket) .WithBucket(bucket)
.WithObject(objectKey), ct); .WithObject(objectKey), ct);
return true; return true;
@@ -74,13 +74,12 @@ public class EncounterService : IEncounterService
var encounterIds = encounters.Select(e => e.Id).ToList(); var encounterIds = encounters.Select(e => e.Id).ToList();
var news2ByEncounter = (await _db.News2Scores var news2ByEncounter = await _db.News2Scores
.AsNoTracking() .AsNoTracking()
.Where(s => encounterIds.Contains(s.EncounterId)) .Where(s => encounterIds.Contains(s.EncounterId))
.OrderByDescending(s => s.CalculatedAt)
.ToListAsync())
.GroupBy(s => s.EncounterId) .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 var openAlertCounts = await _db.ClinicalAlerts
.AsNoTracking() .AsNoTracking()
@@ -89,29 +88,26 @@ public class EncounterService : IEncounterService
.Select(g => new { EncounterId = g.Key, Count = g.Count() }) .Select(g => new { EncounterId = g.Key, Count = g.Count() })
.ToDictionaryAsync(x => x.EncounterId, x => x.Count); .ToDictionaryAsync(x => x.EncounterId, x => x.Count);
var bundlesByEncounter = (await _db.SepsisBundles var bundlesByEncounter = await _db.SepsisBundles
.AsNoTracking() .AsNoTracking()
.Where(b => encounterIds.Contains(b.EncounterId)) .Where(b => encounterIds.Contains(b.EncounterId))
.OrderByDescending(b => b.RecognizedAt)
.ToListAsync())
.GroupBy(b => b.EncounterId) .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() .AsNoTracking()
.Where(s => encounterIds.Contains(s.EncounterId)) .Where(s => encounterIds.Contains(s.EncounterId))
.OrderByDescending(s => s.CalculatedAt)
.ToListAsync())
.GroupBy(s => s.EncounterId) .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() .AsNoTracking()
.Where(s => encounterIds.Contains(s.EncounterId)) .Where(s => encounterIds.Contains(s.EncounterId))
.OrderByDescending(s => s.CalculatedAt)
.ToListAsync())
.GroupBy(s => s.EncounterId) .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 var lastObservationByEncounter = await _db.Observations
.AsNoTracking() .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 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 .Select(o => new
{ {
type = "observation", type = "observation",
@@ -260,7 +263,10 @@ public class EncounterService : IEncounterService
events.AddRange(observations); events.AddRange(observations);
var alerts = await _db.ClinicalAlerts 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 .Select(a => new
{ {
type = "alert", type = "alert",
@@ -273,7 +279,10 @@ public class EncounterService : IEncounterService
events.AddRange(alerts); events.AddRange(alerts);
var orders = await _db.Orders 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 .Select(o => new
{ {
type = "order", type = "order",
@@ -286,7 +295,10 @@ public class EncounterService : IEncounterService
events.AddRange(orders); events.AddRange(orders);
var medications = await _db.MedicationAdministrations 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 .Select(m => new
{ {
type = "medication", type = "medication",
@@ -1,6 +1,7 @@
public interface IPhiAccessLogService public interface IPhiAccessLogService
{ {
Task LogViewAsync(Guid patientId, string resourcePath); Task LogViewAsync(Guid patientId, string resourcePath);
Task LogViewsAsync(IReadOnlyList<Guid> patientIds, string resourcePath);
Task LogListAsync(string resourcePath, int resultCount, string? searchQuery = null); Task LogListAsync(string resourcePath, int resultCount, string? searchQuery = null);
Task LogCreateAsync(Guid patientId, string resourcePath); Task LogCreateAsync(Guid patientId, string resourcePath);
Task LogUpdateAsync(Guid patientId, string resourcePath); Task LogUpdateAsync(Guid patientId, string resourcePath);
@@ -197,7 +197,6 @@ public class ObservationService : IObservationService
if (encounter.Status != EncounterStatus.Active) if (encounter.Status != EncounterStatus.Active)
throw new ValidationException("Encounter not active.", "ENCOUNTER_NOT_ACTIVE"); throw new ValidationException("Encounter not active.", "ENCOUNTER_NOT_ACTIVE");
await using var tx = await _db.Database.BeginTransactionAsync(ct);
try try
{ {
var observation = new Observation var observation = new Observation
@@ -267,11 +266,10 @@ public class ObservationService : IObservationService
}, obs.EncounterId.ToString())); }, obs.EncounterId.ToString()));
await _db.SaveChangesAsync(ct); await _db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
} }
catch (DbUpdateException ex) when (IsUniqueViolation(ex)) catch (DbUpdateException ex) when (IsUniqueViolation(ex))
{ {
await tx.RollbackAsync(ct); _db.ChangeTracker.Clear();
// silent skip — idempotency key already applied // silent skip — idempotency key already applied
} }
} }
@@ -113,8 +113,9 @@ public class PatientService : IPatientService
var path = _http.HttpContext?.Request.Path.Value ?? "/api/v1/patients"; var path = _http.HttpContext?.Request.Path.Value ?? "/api/v1/patients";
await _phiAccess.LogListAsync(path, patients.Count, q); await _phiAccess.LogListAsync(path, patients.Count, q);
foreach (var p in patients) await _phiAccess.LogViewsAsync(
await _phiAccess.LogViewAsync(p.Id, $"{path}?page={page}"); patients.Select(p => p.Id).ToList(),
$"{path}?page={page}");
return new PagedResult<Patient>(patients, page, pageSize, total); return new PagedResult<Patient>(patients, page, pageSize, total);
} }
@@ -27,6 +27,37 @@ public class PhiAccessLogService : IPhiAccessLogService
public async Task LogViewAsync(Guid patientId, string resourcePath) => public async Task LogViewAsync(Guid patientId, string resourcePath) =>
await WriteAsync(PhiAccessType.View, patientId, resourcePath); await WriteAsync(PhiAccessType.View, patientId, resourcePath);
public async Task LogViewsAsync(IReadOnlyList<Guid> patientIds, string resourcePath)
{
if (patientIds.Count == 0) return;
if (!_currentUser.IsAuthenticated || _currentUser.UserId is null) return;
var now = DateTimeOffset.UtcNow;
var userId = _currentUser.UserId.Value;
var display = _currentUser.DisplayName ?? _currentUser.Username ?? "Unknown";
var ip = _currentUser.IpAddress;
var correlationId = _http.HttpContext?.Items["CorrelationId"]?.ToString();
foreach (var patientId in patientIds)
{
_db.PhiAccessLogs.Add(new PhiAccessLog
{
Id = Guid.NewGuid(),
AccessType = PhiAccessType.View,
PatientId = patientId,
UserId = userId,
UserDisplayName = display,
ResourcePath = resourcePath,
IpAddress = ip,
CorrelationId = correlationId,
AccessedAt = now
});
}
await _db.SaveChangesAsync();
_metrics.PhiAccessLogsTotal.WithLabels(PhiAccessType.View.ToDbString()).Inc(patientIds.Count);
}
public async Task LogCreateAsync(Guid patientId, string resourcePath) => public async Task LogCreateAsync(Guid patientId, string resourcePath) =>
await WriteAsync(PhiAccessType.Create, patientId, resourcePath); await WriteAsync(PhiAccessType.Create, patientId, resourcePath);
@@ -176,19 +176,21 @@ public sealed class SimulationRunner : ISimulationRunner, IHostedService
public async Task StopAsync(CancellationToken cancellationToken) public async Task StopAsync(CancellationToken cancellationToken)
{ {
var running = new List<Task>();
foreach (var ctx in _runs.Values) foreach (var ctx in _runs.Values)
{ {
if (ctx.State.Status is SimulationRunStatus.Pending or SimulationRunStatus.Running) if (ctx.State.Status is SimulationRunStatus.Pending or SimulationRunStatus.Running)
ctx.Cts.Cancel(); ctx.Cts.Cancel();
if (ctx.ExecuteTask is not null)
running.Add(ctx.ExecuteTask);
} }
var deadline = DateTimeOffset.UtcNow.AddSeconds(5); if (running.Count == 0) return;
while (DateTimeOffset.UtcNow < deadline
&& _runs.Values.Any(c => var all = Task.WhenAll(running);
c.State.Status is SimulationRunStatus.Pending or SimulationRunStatus.Running)) var completed = await Task.WhenAny(all, Task.Delay(TimeSpan.FromSeconds(5), cancellationToken));
{ if (completed != all)
await Task.Delay(50, cancellationToken); _logger.LogWarning("Simulation stop timed out waiting for {Count} run task(s)", running.Count);
}
} }
private async Task<SimulationRunState> RegisterAndStartAsync( private async Task<SimulationRunState> RegisterAndStartAsync(
@@ -224,7 +226,7 @@ public sealed class SimulationRunner : ISimulationRunner, IHostedService
if (!_runs.TryAdd(runId, ctx)) if (!_runs.TryAdd(runId, ctx))
throw new ConflictException("Failed to register simulation run.", "SIMULATION_REGISTER_FAILED"); 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(); return state.Snapshot();
} }
@@ -365,5 +367,6 @@ public sealed class SimulationRunner : ISimulationRunner, IHostedService
public SimulationRunState State { get; } = state; public SimulationRunState State { get; } = state;
public CancellationTokenSource Cts { get; } = cts; public CancellationTokenSource Cts { get; } = cts;
public ScenarioFile Scenario { get; } = scenario; public ScenarioFile Scenario { get; } = scenario;
public Task? ExecuteTask { get; set; }
} }
} }
+35 -17
View File
@@ -41,27 +41,45 @@ public class TrendDetector
var cache = _redis.GetDatabase(); var cache = _redis.GetDatabase();
var key = TrendCalculator.HistoryKey(encounterId, observationCode); var key = TrendCalculator.HistoryKey(encounterId, observationCode);
var lockKey = key + ":lock";
// Append new entry to history list List<TrendHistoryEntry> history;
var entry = new TrendHistoryEntry(value, recordedAt); var entry = new TrendHistoryEntry(value, recordedAt);
var historyJson = await cache.StringGetAsync(key);
var history = historyJson.HasValue
? JsonSerializer.Deserialize<List<TrendHistoryEntry>>(historyJson!) ?? new()
: new List<TrendHistoryEntry>();
history.Add(entry);
// Trim to max entries and evict entries outside window
var cutoff = recordedAt.AddMinutes(-_options.WindowMinutes); var cutoff = recordedAt.AddMinutes(-_options.WindowMinutes);
history = history
.Where(e => e.RecordedAt >= cutoff)
.TakeLast(_options.MaxHistoryEntries)
.ToList();
await cache.StringSetAsync( // Short Redis lock so concurrent observations for the same key do not lose history.
key, var locked = false;
JsonSerializer.Serialize(history), for (var attempt = 0; attempt < 8 && !locked; attempt++)
TimeSpan.FromSeconds(_options.HistoryTtlSeconds)); {
locked = await cache.StringSetAsync(
lockKey, "1", TimeSpan.FromSeconds(2), When.NotExists);
if (!locked)
await Task.Delay(15, ct);
}
try
{
var historyJson = await cache.StringGetAsync(key);
history = historyJson.HasValue
? JsonSerializer.Deserialize<List<TrendHistoryEntry>>(historyJson!) ?? new()
: new List<TrendHistoryEntry>();
history.Add(entry);
history = history
.Where(e => e.RecordedAt >= cutoff)
.TakeLast(_options.MaxHistoryEntries)
.ToList();
await cache.StringSetAsync(
key,
JsonSerializer.Serialize(history),
TimeSpan.FromSeconds(_options.HistoryTtlSeconds));
}
finally
{
if (locked)
await cache.KeyDeleteAsync(lockKey);
}
if (history.Count < 2) if (history.Count < 2)
return new TrendResult(TrendOutcome.InsufficientHistory, observationCode); return new TrendResult(TrendOutcome.InsufficientHistory, observationCode);
+2 -1
View File
@@ -84,7 +84,8 @@
}, },
"DataLake": { "DataLake": {
"FlushCount": 1000, "FlushCount": 1000,
"FlushIntervalSeconds": 300 "FlushIntervalSeconds": 300,
"MaxBufferedEvents": 50000
}, },
"TrendDetection": { "TrendDetection": {
"WindowMinutes": 30, "WindowMinutes": 30,
+4
View File
@@ -58,3 +58,7 @@ Kafka consumer lag, ready probe failing, gateway offline, unacked CRITICAL alert
Optionally a second signal for the ward gateway with Optionally a second signal for the ward gateway with
`Application = 'VigilCare.WardGateway'`. `Application = 'VigilCare.WardGateway'`.
## Related
- [CPU / Memory Remediation Roadmap (Phases 41–44)](../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)
@@ -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).
@@ -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`.
@@ -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.
+39
View File
@@ -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.