Files

44 lines
1.3 KiB
C#

using Microsoft.Extensions.Options;
public sealed class CentralReachabilityService : BackgroundService
{
private readonly IHttpClientFactory _http;
private readonly CentralApiOptions _central;
private readonly GatewayOptions _gateway;
private volatile bool _isReachable;
public bool IsCentralReachable => _isReachable;
public CentralReachabilityService(
IHttpClientFactory http,
IOptions<CentralApiOptions> central,
IOptions<GatewayOptions> gateway)
{
_http = http;
_central = central.Value;
_gateway = gateway.Value;
}
protected override async Task ExecuteAsync(CancellationToken ct)
{
using var timer = new PeriodicTimer(
TimeSpan.FromSeconds(_gateway.CentralReachabilityIntervalSeconds));
while (await timer.WaitForNextTickAsync(ct))
await ProbeAsync(ct);
}
private async Task ProbeAsync(CancellationToken ct)
{
try
{
var client = _http.CreateClient("central");
client.BaseAddress = new Uri(_central.BaseUrl);
var resp = await client.GetAsync("/health/ready", ct);
_isReachable = resp.IsSuccessStatusCode;
}
catch
{
_isReachable = false;
}
}
}