Files
vigilcare-clinical/VigilCare.WardGateway/BackgroundService/GatewayHeartbeatService.cs
T
Trent 68a2ab3204
CI / changes (push) Successful in 17s
CI / frontend (push) Skipped
CI / backend (push) Successful in 15m10s
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.
2026-11-30 21:32:43 +08:00

67 lines
2.5 KiB
C#

using System.Net.Http.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
public sealed class GatewayHeartbeatService : BackgroundService
{
private readonly IServiceScopeFactory _scopes;
private readonly IHttpClientFactory _http;
private readonly CentralReachabilityService _reachability;
private readonly GatewayOptions _gateway;
private readonly IConfiguration _config;
private readonly ILogger<GatewayHeartbeatService> _logger;
public GatewayHeartbeatService(
IServiceScopeFactory scopes,
IHttpClientFactory http,
CentralReachabilityService reachability,
IOptions<GatewayOptions> gateway,
IConfiguration config,
ILogger<GatewayHeartbeatService> logger)
{
_scopes = scopes;
_http = http;
_reachability = reachability;
_gateway = gateway.Value;
_config = config;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken ct)
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(_gateway.HeartbeatIntervalSeconds));
while (await timer.WaitForNextTickAsync(ct))
await SendHeartbeatAsync(ct);
}
private async Task SendHeartbeatAsync(CancellationToken ct)
{
await using var scope = _scopes.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<GatewayDbContext>();
var bufferDepth = await db.BufferedSyncItems.CountAsync(b => !b.Synced, ct);
var status = _reachability.IsCentralReachable ? "ONLINE" : "DEGRADED";
var req = new GatewayHeartbeatRequest(status, bufferDepth, DateTimeOffset.UtcNow);
try
{
var client = _http.CreateClient("central");
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.SendAsync(message, ct);
if (!resp.IsSuccessStatusCode)
_logger.LogWarning("Heartbeat failed: {Status}", resp.StatusCode);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Heartbeat to central failed — gateway continues in DEGRADED mode");
}
}
}