Files
Heimdall/tests/Heimdall.IntegrationTests/Scenarios/AgentFailoverScenarios.cs
T
arnaud.dartois 636154572b
Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Successful in 19m19s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 6m13s
Heimdall Gitea / Build and scan agent image (push) Successful in 14m44s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m48s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 19m9s
Heimdall Gitea / CI policy (push) Successful in 10s
Complete remaining Heimdall features and acceptance
Merge pull request #138

Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-06 11:14:49 +01:00

105 lines
4.9 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Heimdall.Application.Services;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Jobs;
using Heimdall.IntegrationTests.Controllers;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
namespace Heimdall.IntegrationTests.Scenarios;
[Collection("Postgres")]
public sealed class AgentFailoverScenarios(PostgreSqlContainerFixture postgres) : PostgresTestBase(postgres)
{
[Fact]
public async Task StaleAgent_IsMarkedOfflineAndCameraMovesToOnlinePeer()
{
var admin = await Factory.CreateAdminClientAsync();
var siteResponse = await admin.PostAsJsonAsync("api/sites", new
{
name = $"Failover {Guid.NewGuid():N}",
timezone = "UTC"
});
siteResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var siteId = (await siteResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("id").GetGuid();
var failedAgent = await RegisterAgentAsync(admin, siteId, "failover-source");
var replacementAgent = await RegisterAgentAsync(admin, siteId, "failover-replacement");
var cameraResponse = await admin.PostAsJsonAsync("api/cameras", new
{
siteId,
name = "Failover camera",
rtspUrl = "rtsp://127.0.0.1/synthetic"
});
cameraResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var cameraId = (await cameraResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("id").GetGuid();
(await admin.PostAsJsonAsync("api/assignments", new { cameraId, agentId = failedAgent.Id }))
.StatusCode.ShouldBe(HttpStatusCode.OK);
await using (var scope = Factory.Services.CreateAsyncScope())
{
var dbFactory = scope.ServiceProvider.GetRequiredService<IDbContextFactory<AppDbContext>>();
await using var db = await dbFactory.CreateDbContextAsync();
await db.Agents.Where(agent => agent.Id == failedAgent.Id)
.ExecuteUpdateAsync(setters => setters.SetProperty(agent => agent.LastHeartbeat,
DateTime.UtcNow.AddSeconds(-900)));
}
await using (var scope = Factory.Services.CreateAsyncScope())
{
var services = scope.ServiceProvider;
var job = new AgentFailoverJob(
services.GetRequiredService<IDbContextFactory<AppDbContext>>(),
services.GetRequiredService<ICameraAssignmentService>(),
services.GetRequiredService<Microsoft.Extensions.Logging.ILogger<AgentFailoverJob>>());
await job.ExecuteAsync();
}
await using (var scope = Factory.Services.CreateAsyncScope())
{
var dbFactory = scope.ServiceProvider.GetRequiredService<IDbContextFactory<AppDbContext>>();
await using var db = await dbFactory.CreateDbContextAsync();
(await db.Agents.Where(agent => agent.Id == failedAgent.Id).Select(agent => agent.Status).SingleAsync())
.ShouldBe(AgentStatus.Offline);
(await db.Cameras.Where(camera => camera.Id == cameraId).Select(camera => camera.AgentId).SingleAsync())
.ShouldBe(replacementAgent.Id);
var assignments = await db.CameraAssignments.Where(assignment => assignment.CameraId == cameraId)
.OrderBy(assignment => assignment.AssignedAt).ToListAsync();
assignments.Count.ShouldBe(2);
assignments[0].ReleasedAt.ShouldNotBeNull();
assignments[0].AgentId.ShouldBe(failedAgent.Id);
assignments[1].ReleasedAt.ShouldBeNull();
assignments[1].AgentId.ShouldBe(replacementAgent.Id);
}
}
private async Task<(Guid Id, string ApiKey)> RegisterAgentAsync(HttpClient admin, Guid siteId, string hostname)
{
var tokenResponse = await admin.PostAsync($"api/sites/{siteId}/tokens", null);
tokenResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var siteToken = (await tokenResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("token").GetString()!;
var registration = await admin.PostAsJsonAsync("api/agents/register", new
{
token = siteToken,
hostname,
version = "1.0.0-test"
});
registration.StatusCode.ShouldBe(HttpStatusCode.OK);
var registered = await registration.Content.ReadFromJsonAsync<JsonElement>();
var id = registered.GetProperty("agentId").GetGuid();
var apiKey = registered.GetProperty("apiKey").GetString()!;
var heartbeat = Factory.CreateClient();
heartbeat.DefaultRequestHeaders.Add("X-API-Key", apiKey);
(await heartbeat.PostAsJsonAsync($"api/agents/{id}/heartbeat", new
{
publicIp = "127.0.0.1",
cpuCores = 4,
memoryMb = 4096
})).StatusCode.ShouldBe(HttpStatusCode.OK);
return (id, apiKey);
}
}