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
{
var client = _http.CreateClient("central");
client.BaseAddress = new Uri(_central.BaseUrl);
var resp = await client.GetAsync("/health/ready", ct);
var resp = await client.GetAsync("health/ready", ct);
_isReachable = resp.IsSuccessStatusCode;
}
catch
@@ -46,13 +46,10 @@ public sealed class EncounterReplicaSyncService : BackgroundService
await using var scope = _scopes.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<GatewayDbContext>();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
var centralOpts = scope.ServiceProvider.GetRequiredService<IOptions<CentralApiOptions>>().Value;
var client = _http.CreateClient("central");
client.BaseAddress = new Uri(centralOpts.BaseUrl);
ConfigureAuth(client);
if (client.DefaultRequestHeaders.Authorization is null)
var jwt = Environment.GetEnvironmentVariable("GATEWAY_SYNC_JWT");
if (string.IsNullOrEmpty(jwt))
{
_logger.LogWarning(
"GATEWAY_SYNC_JWT not set — skipping encounter replica sync (seed local replica manually for dev)");
@@ -61,8 +58,8 @@ public sealed class EncounterReplicaSyncService : BackgroundService
try
{
var syncedCount = await SyncEncountersAsync(client, db, ct);
await SyncThresholdsAsync(client, db, redis, ct);
var syncedCount = await SyncEncountersAsync(client, jwt, db, ct);
await SyncThresholdsAsync(client, jwt, db, redis, ct);
var state = await db.SyncState.FirstOrDefaultAsync(ct)
?? db.SyncState.Add(new GatewaySyncState { Id = Guid.NewGuid() }).Entity;
@@ -79,7 +76,7 @@ public sealed class EncounterReplicaSyncService : BackgroundService
}
private async Task<int> SyncEncountersAsync(
HttpClient client, GatewayDbContext db, CancellationToken ct)
HttpClient client, string jwt, GatewayDbContext db, CancellationToken ct)
{
var dept = Uri.EscapeDataString(_gateway.Department);
var summaries = new List<CentralWardEncounterSummary>();
@@ -87,10 +84,14 @@ public sealed class EncounterReplicaSyncService : BackgroundService
while (true)
{
var listResp = await client.GetFromJsonAsync<ApiResponse<CentralEncounterListPage>>(
$"/api/v1/encounters?status=ACTIVE&department={dept}&page={page}&pageSize={EncounterPageSize}",
CentralApiJson.Options,
ct);
using var listReq = new HttpRequestMessage(
HttpMethod.Get,
$"api/v1/encounters?status=ACTIVE&department={dept}&page={page}&pageSize={EncounterPageSize}");
listReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
using var listHttp = await client.SendAsync(listReq, ct);
listHttp.EnsureSuccessStatusCode();
var listResp = await listHttp.Content.ReadFromJsonAsync<ApiResponse<CentralEncounterListPage>>(
CentralApiJson.Options, ct);
if (listResp?.Data?.Items is null || listResp.Data.Items.Count == 0)
break;
@@ -106,10 +107,28 @@ public sealed class EncounterReplicaSyncService : BackgroundService
var synced = 0;
foreach (var summary in summaries)
{
var detailResp = await client.GetFromJsonAsync<ApiResponse<CentralEncounterDetail>>(
$"/api/v1/encounters/{summary.EncounterId}",
CentralApiJson.Options,
ct);
var existingPatient = await db.Patients.FindAsync([summary.PatientId], ct);
if (existingPatient is not null
&& !string.IsNullOrEmpty(summary.Mrn)
&& !string.IsNullOrEmpty(summary.FirstName))
{
UpsertFromSummary(db, summary, existingPatient);
synced++;
continue;
}
using var detailReq = new HttpRequestMessage(
HttpMethod.Get, $"api/v1/encounters/{summary.EncounterId}");
detailReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
using var detailHttp = await client.SendAsync(detailReq, ct);
if (!detailHttp.IsSuccessStatusCode)
{
_logger.LogWarning("Central returned no detail for encounter {EncounterId}", summary.EncounterId);
continue;
}
var detailResp = await detailHttp.Content.ReadFromJsonAsync<ApiResponse<CentralEncounterDetail>>(
CentralApiJson.Options, ct);
if (detailResp?.Data is null)
{
@@ -124,6 +143,43 @@ public sealed class EncounterReplicaSyncService : BackgroundService
return synced;
}
private static void UpsertFromSummary(
GatewayDbContext db, CentralWardEncounterSummary summary, ReplicaPatient existingPatient)
{
var now = DateTimeOffset.UtcNow;
if (!string.IsNullOrEmpty(summary.Mrn)) existingPatient.Mrn = summary.Mrn;
if (!string.IsNullOrEmpty(summary.FirstName)) existingPatient.FirstName = summary.FirstName!;
if (!string.IsNullOrEmpty(summary.LastName)) existingPatient.LastName = summary.LastName!;
existingPatient.SyncedAt = now;
var enc = db.Encounters.Find(summary.EncounterId);
if (enc is null)
{
db.Encounters.Add(new ReplicaEncounter
{
Id = summary.EncounterId,
PatientId = summary.PatientId,
EncounterType = EncounterType.Inpatient,
Status = summary.Status,
Department = summary.Department,
AttendingPhysician = summary.AttendingPhysician ?? "unknown",
RoomBed = summary.RoomBed,
AdmittedAt = summary.AdmittedAt == default ? now : summary.AdmittedAt,
SyncedAt = now
});
}
else
{
enc.PatientId = summary.PatientId;
enc.Status = summary.Status;
enc.Department = summary.Department;
enc.AttendingPhysician = summary.AttendingPhysician ?? enc.AttendingPhysician;
enc.RoomBed = summary.RoomBed;
if (summary.AdmittedAt != default) enc.AdmittedAt = summary.AdmittedAt;
enc.SyncedAt = now;
}
}
private static void UpsertReplica(GatewayDbContext db, CentralEncounterDetail detail)
{
var now = DateTimeOffset.UtcNow;
@@ -184,14 +240,17 @@ public sealed class EncounterReplicaSyncService : BackgroundService
private async Task SyncThresholdsAsync(
HttpClient client,
string jwt,
GatewayDbContext db,
IConnectionMultiplexer redis,
CancellationToken ct)
{
var thrResp = await client.GetFromJsonAsync<ApiResponse<List<CentralAlertThreshold>>>(
"/api/v1/alert-thresholds",
CentralApiJson.Options,
ct);
using var thrReq = new HttpRequestMessage(HttpMethod.Get, "api/v1/alert-thresholds");
thrReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
using var thrHttp = await client.SendAsync(thrReq, ct);
thrHttp.EnsureSuccessStatusCode();
var thrResp = await thrHttp.Content.ReadFromJsonAsync<ApiResponse<List<CentralAlertThreshold>>>(
CentralApiJson.Options, ct);
if (thrResp?.Data is null)
return;
@@ -216,12 +275,4 @@ public sealed class EncounterReplicaSyncService : BackgroundService
await ThresholdCacheLoader.RefreshAsync(db, redis, _logger, ct);
}
private static void ConfigureAuth(HttpClient client)
{
client.DefaultRequestHeaders.Authorization = null;
var jwt = Environment.GetEnvironmentVariable("GATEWAY_SYNC_JWT");
if (!string.IsNullOrEmpty(jwt))
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwt);
}
}
@@ -1,3 +1,4 @@
using System.Net.Http.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
@@ -45,15 +46,16 @@ public sealed class GatewayHeartbeatService : BackgroundService
try
{
var client = _http.CreateClient("central");
client.BaseAddress = new Uri(
scope.ServiceProvider.GetRequiredService<IOptions<CentralApiOptions>>().Value.BaseUrl);
client.DefaultRequestHeaders.Remove("X-Api-Key");
client.DefaultRequestHeaders.Remove("X-Gateway-Id");
client.DefaultRequestHeaders.Add("X-Api-Key", _config["ApiKey:Gateway"]);
client.DefaultRequestHeaders.Add("X-Gateway-Id", _gateway.GatewayId.ToString());
using var message = new HttpRequestMessage(
HttpMethod.Patch,
$"api/v1/gateways/{_gateway.GatewayId}/heartbeat")
{
Content = JsonContent.Create(req)
};
message.Headers.TryAddWithoutValidation("X-Api-Key", _config["ApiKey:Gateway"]);
message.Headers.TryAddWithoutValidation("X-Gateway-Id", _gateway.GatewayId.ToString());
var resp = await client.PatchAsJsonAsync(
$"/api/v1/gateways/{_gateway.GatewayId}/heartbeat", req, ct);
var resp = await client.SendAsync(message, ct);
if (!resp.IsSuccessStatusCode)
_logger.LogWarning("Heartbeat failed: {Status}", resp.StatusCode);
}
@@ -52,7 +52,7 @@ public sealed class LocalEscalationWorkerService : BackgroundService
using var connection = factory.CreateConnection("gateway-escalation-worker");
using var channel = connection.CreateModel();
channel.BasicQos(0, prefetchCount: 5, global: false);
channel.BasicQos(0, prefetchCount: 1, global: false);
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.Received += async (_, ea) =>
@@ -70,7 +70,7 @@ public sealed class LocalEscalationWorkerService : BackgroundService
private async Task HandleEscalationAsync(IModel channel, BasicDeliverEventArgs ea, CancellationToken ct)
{
var payload = Encoding.UTF8.GetString(ea.Body.Span);
var doc = JsonDocument.Parse(payload);
using var doc = JsonDocument.Parse(payload);
var alertId = Guid.Parse(doc.RootElement.GetProperty("alertId").GetString()!);
_logger.LogCritical("[ESCALATION] Paging on-call backup for alert {AlertId}", alertId);
@@ -87,7 +87,7 @@ public sealed class LocalPagingWorkerService : BackgroundService
{
var o = _opts.Value;
var payload = Encoding.UTF8.GetString(ea.Body.Span);
var doc = JsonDocument.Parse(payload);
using var doc = JsonDocument.Parse(payload);
var alertId = Guid.Parse(doc.RootElement.GetProperty("alertId").GetString()!);
var encounterId = doc.RootElement.GetProperty("encounterId").GetString();
var details = doc.RootElement.TryGetProperty("details", out var d) ? d.GetString() : null;
@@ -104,7 +104,7 @@ public sealed class LocalPagingWorkerService : BackgroundService
while (DateTimeOffset.UtcNow < deadline && !ct.IsCancellationRequested)
{
await Task.Delay(2_000, ct);
await Task.Delay(5_000, ct);
if (await IsAlertAcknowledgedAsync(alertId, ct))
{
@@ -68,43 +68,53 @@ public sealed class SyncUploaderService : BackgroundService
var request = BuildBatchRequest(batchRef, pending);
var client = scope.ServiceProvider.GetRequiredService<IHttpClientFactory>().CreateClient("central");
client.BaseAddress = new Uri(
scope.ServiceProvider.GetRequiredService<IOptions<CentralApiOptions>>().Value.BaseUrl);
client.DefaultRequestHeaders.Add("X-Api-Key", _config["ApiKey:Gateway"]!);
client.DefaultRequestHeaders.Add("X-Gateway-Id", _gateway.GatewayId.ToString());
var apiKey = _config["ApiKey:Gateway"]!;
var gatewayId = _gateway.GatewayId.ToString();
var submit = await client.PostAsJsonAsync("/api/v1/sync/batches", request, ct);
submit.EnsureSuccessStatusCode();
var batchId = (await submit.Content.ReadFromJsonAsync<ApiResponse<SyncBatchStatus>>(ct))!.Data!.BatchId;
for (var i = 0; i < 30; i++)
using (var submitMsg = new HttpRequestMessage(HttpMethod.Post, "api/v1/sync/batches")
{
await Task.Delay(2000, ct);
var status = await client.GetFromJsonAsync<ApiResponse<SyncBatchStatus>>(
$"/api/v1/sync/batches/{batchId}", ct);
if (status?.Data?.Status is "APPLIED")
{
foreach (var item in pending)
{
item.Synced = true;
item.SyncedAt = DateTimeOffset.UtcNow;
}
await db.SaveChangesAsync(ct);
_logger.LogInformation(
"Sync batch {BatchId} applied — marked {Count} buffered items synced",
batchId, pending.Count);
return;
}
if (status?.Data?.Status is "CONFLICT" or "REJECTED")
{
_logger.LogError(
"Sync batch {BatchId} {Status} — items remain buffered",
batchId, status.Data.Status);
return;
}
}
Content = JsonContent.Create(request)
})
{
submitMsg.Headers.TryAddWithoutValidation("X-Api-Key", apiKey);
submitMsg.Headers.TryAddWithoutValidation("X-Gateway-Id", gatewayId);
var submit = await client.SendAsync(submitMsg, ct);
submit.EnsureSuccessStatusCode();
var batchId = (await submit.Content.ReadFromJsonAsync<ApiResponse<SyncBatchStatus>>(ct))!.Data!.BatchId;
_logger.LogWarning("Sync batch {BatchId} still processing after poll window", batchId);
for (var i = 0; i < 30; i++)
{
await Task.Delay(2000, ct);
using var statusMsg = new HttpRequestMessage(HttpMethod.Get, $"api/v1/sync/batches/{batchId}");
statusMsg.Headers.TryAddWithoutValidation("X-Api-Key", apiKey);
statusMsg.Headers.TryAddWithoutValidation("X-Gateway-Id", gatewayId);
using var statusResp = await client.SendAsync(statusMsg, ct);
statusResp.EnsureSuccessStatusCode();
var status = await statusResp.Content.ReadFromJsonAsync<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)
@@ -51,7 +51,7 @@ public class ThresholdCacheLoader : IHostedService
{
try
{
WriteThresholds(redis, thresholds);
await WriteThresholdsAsync(redis, thresholds);
logger.LogInformation(
"Loaded {Count} alert thresholds into gateway Redis cache", thresholds.Count);
return;
@@ -73,10 +73,12 @@ public class ThresholdCacheLoader : IHostedService
maxAttempts);
}
private static void WriteThresholds(IConnectionMultiplexer redis, List<ReplicaAlertThreshold> thresholds)
private static async Task WriteThresholdsAsync(
IConnectionMultiplexer redis, List<ReplicaAlertThreshold> thresholds)
{
var cache = redis.GetDatabase();
var batch = cache.CreateBatch();
var setTasks = new List<Task>(thresholds.Count);
foreach (var t in thresholds)
{
@@ -86,9 +88,10 @@ public class ThresholdCacheLoader : IHostedService
t.WarningLow,
t.WarningHigh,
t.CriticalHigh));
_ = batch.StringSetAsync($"threshold:{t.ObservationCode}", json);
setTasks.Add(batch.StringSetAsync($"threshold:{t.ObservationCode}", json));
}
batch.Execute();
await Task.WhenAll(setTasks);
}
}