diff --git a/src/Heimdall.Agent/Services/AgentRegistrationService.cs b/src/Heimdall.Agent/Services/AgentRegistrationService.cs index 5709018..f2a292c 100644 --- a/src/Heimdall.Agent/Services/AgentRegistrationService.cs +++ b/src/Heimdall.Agent/Services/AgentRegistrationService.cs @@ -12,6 +12,7 @@ public class AgentRegistrationService : BackgroundService private readonly IHttpClientFactory _httpClientFactory; private readonly ILogger _logger; private readonly AgentState _state; + private HttpClient? _client; public AgentRegistrationService( IHttpClientFactory httpClientFactory, @@ -23,6 +24,30 @@ public class AgentRegistrationService : BackgroundService _logger = logger; } + /// + /// Sends a final heartbeat on graceful shutdown so Central knows the agent went offline intentionally. + /// + 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);