using System.Net.Http.Json; using System.Text.Json.Serialization; using Heimdall.Agent.Logging; using Heimdall.Agent.Services; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Heimdall.Agent.Services; /// /// Periodically flushes the agent's to the /// Central via POST /api/agents/{id}/logs (API Key auth). /// Non-blocking by design: if the Central is unreachable the entries are /// re-queued and retried on the next tick; a 400 (validation) drops the /// batch to avoid an infinite retry loop. /// public class LogUploadService : BackgroundService { internal static string ToCentralLevel(LogLevel level) => level switch { LogLevel.Trace => "Trace", LogLevel.Debug => "Debug", LogLevel.Information => "Information", LogLevel.Warning => "Warning", LogLevel.Error => "Error", LogLevel.Critical => "Critical", _ => "Info" }; private readonly IHttpClientFactory _httpClientFactory; private readonly LogBufferService _buffer; private readonly AgentState _state; private readonly ILogger _logger; public LogUploadService( IHttpClientFactory httpClientFactory, LogBufferService buffer, AgentState state, ILogger logger) { _httpClientFactory = httpClientFactory; _buffer = buffer; _state = state; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { using var timer = new PeriodicTimer(TimeSpan.FromSeconds(30)); while (await timer.WaitForNextTickAsync(stoppingToken).ConfigureAwait(false)) { try { await UploadOnceAsync(stoppingToken).ConfigureAwait(false); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } catch (Exception ex) { _logger.LogWarning(ex, "Log upload tick failed (non-fatal)"); } } } internal async Task UploadOnceAsync(CancellationToken ct) { // No registered identity yet → nothing to attach logs to. if (_state.AgentId == Guid.Empty || string.IsNullOrEmpty(_state.ApiKey)) return; var entries = _buffer.TakeAll(); if (entries.Count == 0) return; var client = _httpClientFactory.CreateClient("Central"); client.DefaultRequestHeaders.Remove("X-API-Key"); client.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey); var payload = new { entries = entries.Select(e => new { timestampUtc = e.TimestampUtc, level = ToCentralLevel(e.Level), message = e.Message, exception = e.Exception, source = e.Source }).ToList() }; try { using var response = await client.PostAsJsonAsync( $"api/agents/{_state.AgentId}/logs", payload, ct).ConfigureAwait(false); if (response.IsSuccessStatusCode) { if (_buffer.DroppedCount > 0) _logger.LogWarning( "Log upload OK; {Count} entries uploaded, {Dropped} dropped (buffer full)", entries.Count, _buffer.DroppedCount); return; } if ((int)response.StatusCode == 400) { // Validation error — re-sending the same batch will never succeed. _logger.LogWarning( "Central rejected log batch ({Status}): dropping {Count} entries", (int)response.StatusCode, entries.Count); return; } _logger.LogWarning( "Log upload failed ({Status}); {Count} entries re-queued", (int)response.StatusCode, entries.Count); _buffer.Requeue(entries); } catch (Exception ex) { _logger.LogDebug(ex, "Log upload failed (network): {Count} entries re-queued", entries.Count); _buffer.Requeue(entries); } } }