Fix Kafka retry seek, bound buffers, and cut hot-path CPU/memory waste (Phases 41–44).
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:
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,13 @@ public sealed class GatewayOptions
|
||||
public int HeartbeatIntervalSeconds { get; init; } = 60;
|
||||
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>
|
||||
/// When true (default), applies EF migrations at startup. The gateway is
|
||||
/// 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; }
|
||||
}
|
||||
|
||||
/// <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 Guid EncounterId { get; set; }
|
||||
public Guid PatientId { get; set; }
|
||||
public string? Mrn { get; set; }
|
||||
public string? FirstName { get; set; }
|
||||
public string? LastName { get; set; }
|
||||
public string? RoomBed { get; set; }
|
||||
public Department Department { get; set; }
|
||||
public EncounterStatus Status { get; set; }
|
||||
public string? AttendingPhysician { get; set; }
|
||||
public DateTimeOffset AdmittedAt { get; set; }
|
||||
}
|
||||
|
||||
public sealed class CentralEncounterDetail
|
||||
|
||||
@@ -49,7 +49,13 @@ try
|
||||
builder.Services.AddFluentValidationAutoValidation();
|
||||
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.AddHostedService(sp => sp.GetRequiredService<CentralReachabilityService>());
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
public static class BufferedSyncWriter
|
||||
{
|
||||
@@ -8,8 +9,21 @@ public static class BufferedSyncWriter
|
||||
object payload,
|
||||
string idempotencyKey,
|
||||
Guid encounterId,
|
||||
DateTimeOffset recordedAt)
|
||||
DateTimeOffset recordedAt,
|
||||
int maxUnsyncedItems = 50_000)
|
||||
{
|
||||
var persisted = db.BufferedSyncItems.Count(b => !b.Synced);
|
||||
var pendingAdd = db.ChangeTracker.Entries<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
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
@@ -21,4 +35,4 @@ public static class BufferedSyncWriter
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
public class LocalAlertService : ILocalAlertService
|
||||
{
|
||||
private readonly GatewayDbContext _db;
|
||||
private readonly GatewayOptions _gateway;
|
||||
|
||||
public LocalAlertService(GatewayDbContext db) => _db = db;
|
||||
public LocalAlertService(GatewayDbContext db, IOptions<GatewayOptions> gateway)
|
||||
{
|
||||
_db = db;
|
||||
_gateway = gateway.Value;
|
||||
}
|
||||
|
||||
public async Task<LocalClinicalAlert> AcknowledgeAsync(
|
||||
Guid id, AcknowledgeAlertRequest req, string clinicianId)
|
||||
@@ -26,7 +32,8 @@ public class LocalAlertService : ILocalAlertService
|
||||
clinicianId,
|
||||
acknowledgedAt = alert.AcknowledgedAt,
|
||||
req.Note
|
||||
}, $"ack:{alert.ClientAlertId}:{alert.AcknowledgedAt:o}", alert.EncounterId, alert.AcknowledgedAt!.Value);
|
||||
}, $"ack:{alert.ClientAlertId}:{alert.AcknowledgedAt:o}", alert.EncounterId, alert.AcknowledgedAt!.Value,
|
||||
_gateway.MaxBufferedSyncItems);
|
||||
|
||||
await _db.SaveChangesAsync();
|
||||
return alert;
|
||||
@@ -50,7 +57,8 @@ public class LocalAlertService : ILocalAlertService
|
||||
clinicianId = alert.AcknowledgedBy,
|
||||
resolvedAt = alert.ResolvedAt,
|
||||
note = (string?)null
|
||||
}, $"resolve:{alert.ClientAlertId}", alert.EncounterId, alert.ResolvedAt!.Value);
|
||||
}, $"resolve:{alert.ClientAlertId}", alert.EncounterId, alert.ResolvedAt!.Value,
|
||||
_gateway.MaxBufferedSyncItems);
|
||||
|
||||
await _db.SaveChangesAsync();
|
||||
return alert;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StackExchange.Redis;
|
||||
|
||||
public class LocalObservationService : ILocalObservationService
|
||||
@@ -8,6 +9,7 @@ public class LocalObservationService : ILocalObservationService
|
||||
private readonly IConnectionMultiplexer _redis;
|
||||
private readonly LocalWarningEvaluator _warnings;
|
||||
private readonly LocalPagingPublisher _paging;
|
||||
private readonly GatewayOptions _gateway;
|
||||
private readonly ILogger<LocalObservationService> _logger;
|
||||
|
||||
public LocalObservationService(
|
||||
@@ -15,12 +17,14 @@ public class LocalObservationService : ILocalObservationService
|
||||
IConnectionMultiplexer redis,
|
||||
LocalWarningEvaluator warnings,
|
||||
LocalPagingPublisher paging,
|
||||
IOptions<GatewayOptions> gateway,
|
||||
ILogger<LocalObservationService> logger)
|
||||
{
|
||||
_db = db;
|
||||
_redis = redis;
|
||||
_warnings = warnings;
|
||||
_paging = paging;
|
||||
_gateway = gateway.Value;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
@@ -94,7 +98,8 @@ public class LocalObservationService : ILocalObservationService
|
||||
severity = alert.Severity.ToDbString(),
|
||||
alert.Details,
|
||||
generatedAt = triggeredAt
|
||||
}, $"alert:{alert.ClientAlertId}", encounterId, triggeredAt);
|
||||
}, $"alert:{alert.ClientAlertId}", encounterId, triggeredAt,
|
||||
_gateway.MaxBufferedSyncItems);
|
||||
|
||||
await _paging.PublishCriticalAsync(alert, encounter);
|
||||
}
|
||||
@@ -114,7 +119,8 @@ public class LocalObservationService : ILocalObservationService
|
||||
req.Unit,
|
||||
source = req.Source.ToDbString(),
|
||||
req.RecordedAt
|
||||
}, req.IdempotencyKey ?? $"obs:{observation.Id}", encounterId, req.RecordedAt);
|
||||
}, req.IdempotencyKey ?? $"obs:{observation.Id}", encounterId, req.RecordedAt,
|
||||
_gateway.MaxBufferedSyncItems);
|
||||
|
||||
await _db.SaveChangesAsync();
|
||||
await tx.CommitAsync();
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
public class LocalWarningEvaluator
|
||||
{
|
||||
private readonly GatewayDbContext _db;
|
||||
private readonly GatewayOptions _gateway;
|
||||
private readonly ILogger<LocalWarningEvaluator> _logger;
|
||||
|
||||
public LocalWarningEvaluator(GatewayDbContext db, ILogger<LocalWarningEvaluator> logger)
|
||||
public LocalWarningEvaluator(
|
||||
GatewayDbContext db,
|
||||
IOptions<GatewayOptions> gateway,
|
||||
ILogger<LocalWarningEvaluator> logger)
|
||||
{
|
||||
_db = db;
|
||||
_gateway = gateway.Value;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
@@ -52,7 +58,8 @@ public class LocalWarningEvaluator
|
||||
severity = AlertSeverity.Warning.ToDbString(),
|
||||
details,
|
||||
generatedAt = triggeredAt
|
||||
}, $"alert:{clientAlertId}", encounterId, triggeredAt);
|
||||
}, $"alert:{clientAlertId}", encounterId, triggeredAt,
|
||||
_gateway.MaxBufferedSyncItems);
|
||||
|
||||
_logger.LogInformation(
|
||||
"WARNING alert {AlertId} created locally for encounter {EncounterId}",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"CentralReachabilityIntervalSeconds": 30,
|
||||
"HeartbeatIntervalSeconds": 60,
|
||||
"SyncBatchSize": 500,
|
||||
"MaxBufferedSyncItems": 50000,
|
||||
"AutoMigrate": true
|
||||
},
|
||||
"ApiKey": {
|
||||
|
||||
Reference in New Issue
Block a user