feat(agent): add graceful shutdown with final offline heartbeat
Override StopAsync to send a final heartbeat with IsOffline=true before the agent stops. This allows Central to distinguish between intentional shutdown and unexpected disconnection.
This commit is contained in:
1 parent
7d30d93939
commit
df74a61744
1 file changed
+29
-1
@@ -12,6 +12,7 @@ public class AgentRegistrationService : BackgroundService
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly ILogger<AgentRegistrationService> _logger;
|
||||
private readonly AgentState _state;
|
||||
private HttpClient? _client;
|
||||
|
||||
public AgentRegistrationService(
|
||||
IHttpClientFactory httpClientFactory,
|
||||
@@ -23,6 +24,30 @@ public class AgentRegistrationService : BackgroundService
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a final heartbeat on graceful shutdown so Central knows the agent went offline intentionally.
|
||||
/// </summary>
|
||||
public override async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_client is not null && _state.AgentId != Guid.Empty)
|
||||
{
|
||||
_logger.LogInformation("Agent stopping, sending final heartbeat...");
|
||||
try
|
||||
{
|
||||
var request = new HeartbeatRequest(_state.PublicIp, IsOffline: true);
|
||||
await _client.PostAsJsonAsync(
|
||||
$"api/agents/{_state.AgentId}/heartbeat",
|
||||
request, CancellationToken.None);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Final heartbeat failed (non-fatal)");
|
||||
}
|
||||
}
|
||||
|
||||
await base.StopAsync(cancellationToken);
|
||||
}
|
||||
|
||||
private HttpClient CreateApiClient()
|
||||
{
|
||||
var client = _httpClientFactory.CreateClient("Central");
|
||||
@@ -86,6 +111,7 @@ public class AgentRegistrationService : BackgroundService
|
||||
// Set API Key header for subsequent requests
|
||||
client.DefaultRequestHeaders.Remove("Authorization");
|
||||
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {registration.ApiKey}");
|
||||
_client = client;
|
||||
|
||||
_logger.LogInformation(
|
||||
"Agent registered successfully. ID: {AgentId}, Key prefix: {Prefix}",
|
||||
@@ -148,4 +174,6 @@ internal sealed record RegisterResponse(
|
||||
[property: JsonPropertyName("apiKey")] string ApiKey,
|
||||
[property: JsonPropertyName("apiKeyPrefix")] string ApiKeyPrefix);
|
||||
|
||||
internal sealed record HeartbeatRequest(string? PublicIp);
|
||||
internal sealed record HeartbeatRequest(
|
||||
string? PublicIp,
|
||||
[property: JsonPropertyName("isOffline")] bool IsOffline = false);
|
||||
Reference in new issue
Block a user