refactor(agent): use Options pattern with validation instead of raw env vars
Introduce AgentOptions class with DataAnnotations validation bound from configuration (env vars with Agent__ prefix). Replace all Environment.GetEnvironmentVariable() calls with typed IOptions<T> injection. Config errors are caught at startup via ValidateOnStart().
This commit is contained in:
1 parent
58f46fe3dd
commit
1c08e0394d
7 files changed
+115
-51
No files matched your search
@@ -1,12 +1,22 @@
|
||||
using Heimdall.Agent;
|
||||
using Heimdall.Agent.Services;
|
||||
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
var builder = WebApplication.CreateSlimBuilder(args);
|
||||
|
||||
// Strongly-typed configuration with validation
|
||||
builder.Services.AddOptions<AgentOptions>()
|
||||
.BindConfiguration(AgentOptions.SectionName)
|
||||
.ValidateDataAnnotations()
|
||||
.ValidateOnStart();
|
||||
|
||||
// HTTP clients
|
||||
builder.Services.AddHttpClient("Central", client =>
|
||||
builder.Services.AddHttpClient("Central", (sp, client) =>
|
||||
{
|
||||
var options = sp.GetRequiredService<IOptions<AgentOptions>>().Value;
|
||||
client.BaseAddress = new Uri(options.CentralUrl.TrimEnd('/') + "/");
|
||||
client.Timeout = TimeSpan.FromSeconds(10);
|
||||
});
|
||||
|
||||
@@ -16,7 +26,19 @@ builder.Services.AddHttpClient("IpResolver", client =>
|
||||
});
|
||||
|
||||
// Agent services
|
||||
builder.Services.AddSingleton<AgentState>();
|
||||
builder.Services.AddSingleton<AgentState>(sp =>
|
||||
{
|
||||
var state = new AgentState();
|
||||
var options = sp.GetRequiredService<IOptions<AgentOptions>>().Value;
|
||||
|
||||
var stateDir = options.StateDirectory
|
||||
?? (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory());
|
||||
state.ConfigureStateDirectory(stateDir);
|
||||
|
||||
return state;
|
||||
});
|
||||
|
||||
builder.Services.AddSingleton<SystemMetricsProvider>();
|
||||
builder.Services.AddHostedService<AgentRegistrationService>();
|
||||
|
||||
// Health checks — used by Docker HEALTHCHECK
|
||||
@@ -25,7 +47,7 @@ builder.Services.AddHealthChecks()
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Health endpoint (port 5001 is mapped in Dockerfile)
|
||||
// Health endpoint
|
||||
app.MapHealthChecks("/healthz", new HealthCheckOptions
|
||||
{
|
||||
Predicate = _ => true,
|
||||
|
||||
Reference in new issue
Block a user