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
@@ -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);
}
}