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
Merge pull request #138 Co-authored-by: Arnaud Dartois <admin@tordais.cc>
292 lines
14 KiB
C#
292 lines
14 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json;
|
|
using Heimdall.Application.Services;
|
|
using Heimdall.IntegrationTests.Controllers;
|
|
using Heimdall.Infrastructure.Data;
|
|
using Heimdall.Infrastructure.Jobs;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Shouldly;
|
|
|
|
namespace Heimdall.IntegrationTests.Scenarios;
|
|
|
|
[Collection("Postgres")]
|
|
public sealed class AnalysisJobScenarios(PostgreSqlContainerFixture postgres) : PostgresTestBase(postgres)
|
|
{
|
|
[Theory]
|
|
[InlineData("PersonDetection")]
|
|
[InlineData("VehicleClassification")]
|
|
[InlineData("MotionDetection")]
|
|
public async Task AnalysisJob_SupportedFilteredDetectionType_IsScheduledAndClaimed(string jobType)
|
|
{
|
|
var admin = await Factory.CreateAdminClientAsync();
|
|
var siteResponse = await admin.PostAsJsonAsync("api/sites", new
|
|
{
|
|
name = $"Analysis {Guid.NewGuid():N}",
|
|
timezone = "UTC"
|
|
});
|
|
siteResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var siteId = (await siteResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("id").GetGuid();
|
|
var agent = await RegisterAgentAsync(admin, siteId, $"analysis-{jobType}");
|
|
var cameraResponse = await admin.PostAsJsonAsync("api/cameras", new
|
|
{
|
|
siteId,
|
|
name = $"{jobType} camera",
|
|
rtspUrl = "rtsp://127.0.0.1/test"
|
|
});
|
|
cameraResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var cameraId = (await cameraResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("id").GetGuid();
|
|
(await admin.PostAsJsonAsync("api/assignments", new { cameraId, agentId = agent.Id }))
|
|
.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
|
|
var unsupported = await admin.PostAsJsonAsync($"api/cameras/{cameraId}/analysis-jobs",
|
|
new { jobType = "FaceRecognition" });
|
|
unsupported.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
|
|
|
|
var created = await admin.PostAsJsonAsync($"api/cameras/{cameraId}/analysis-jobs", new { jobType });
|
|
created.StatusCode.ShouldBe(HttpStatusCode.Accepted);
|
|
var jobId = (await created.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("jobId").GetGuid();
|
|
await DispatchPendingJobsAsync();
|
|
|
|
var claim = await ClaimNextAsync(agent);
|
|
claim.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var lease = await claim.Content.ReadFromJsonAsync<JsonElement>();
|
|
lease.GetProperty("jobType").GetString().ShouldBe(jobType);
|
|
|
|
var completed = await AgentClient(agent.ApiKey).PutAsJsonAsync(
|
|
$"api/agents/{agent.Id}/analysis-jobs/{jobId}/result",
|
|
new
|
|
{
|
|
attemptId = lease.GetProperty("attemptId").GetGuid(),
|
|
success = true,
|
|
detections = new[] { new { label = jobType switch
|
|
{
|
|
"PersonDetection" => "person",
|
|
"MotionDetection" => "motion",
|
|
_ => "car"
|
|
},
|
|
confidence = 0.93, x = 0.1, y = 0.1, width = 0.2, height = 0.2 } }
|
|
});
|
|
completed.StatusCode.ShouldBe(HttpStatusCode.NoContent);
|
|
var persisted = await admin.GetAsync($"api/cameras/{cameraId}/analysis-jobs/{jobId}");
|
|
persisted.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var persistedJob = await persisted.Content.ReadFromJsonAsync<JsonElement>();
|
|
persistedJob.GetProperty("status").ToString().ShouldBe("Completed");
|
|
persistedJob.GetProperty("resultJson").GetString()!.ShouldContain(
|
|
jobType switch
|
|
{
|
|
"PersonDetection" => "person",
|
|
"MotionDetection" => "motion",
|
|
_ => "car"
|
|
});
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AnalysisJob_RetriesOnReassignedAgent_AndRejectsLatePreviousAttempt()
|
|
{
|
|
var admin = await Factory.CreateAdminClientAsync();
|
|
var siteResponse = await admin.PostAsJsonAsync("api/sites", new
|
|
{
|
|
name = $"Analysis {Guid.NewGuid():N}",
|
|
timezone = "UTC"
|
|
});
|
|
siteResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var siteId = (await siteResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("id").GetGuid();
|
|
|
|
var firstAgent = await RegisterAgentAsync(admin, siteId, "analysis-agent-one");
|
|
var secondAgent = await RegisterAgentAsync(admin, siteId, "analysis-agent-two");
|
|
|
|
var cameraResponse = await admin.PostAsJsonAsync("api/cameras", new
|
|
{
|
|
siteId,
|
|
name = "Analysis camera",
|
|
rtspUrl = "rtsp://127.0.0.1/test"
|
|
});
|
|
cameraResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var cameraId = (await cameraResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("id").GetGuid();
|
|
|
|
(await admin.PostAsJsonAsync("api/assignments", new { cameraId, agentId = firstAgent.Id }))
|
|
.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
|
|
var createResponse = await admin.PostAsJsonAsync($"api/cameras/{cameraId}/analysis-jobs", new
|
|
{
|
|
jobType = "ObjectDetection",
|
|
parametersJson = "{\"minConfidence\":0.5}"
|
|
});
|
|
createResponse.StatusCode.ShouldBe(HttpStatusCode.Accepted);
|
|
var jobId = (await createResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("jobId").GetGuid();
|
|
|
|
await DispatchPendingJobsAsync();
|
|
var firstClaim = await ClaimNextAsync(firstAgent);
|
|
firstClaim.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var firstAttemptId = (await firstClaim.Content.ReadFromJsonAsync<JsonElement>())
|
|
.GetProperty("attemptId").GetGuid();
|
|
|
|
var secondAgentClient = AgentClient(secondAgent.ApiKey);
|
|
var secondAgentBeforeAssignment = await secondAgentClient.GetAsync(
|
|
$"api/agents/{secondAgent.Id}/analysis-jobs/next");
|
|
secondAgentBeforeAssignment.StatusCode.ShouldBe(HttpStatusCode.NoContent);
|
|
|
|
var failedAttempt = await AgentClient(firstAgent.ApiKey).PutAsJsonAsync(
|
|
$"api/agents/{firstAgent.Id}/analysis-jobs/{jobId}/result",
|
|
new { attemptId = firstAttemptId, success = false, error = "temporary inference failure" });
|
|
failedAttempt.StatusCode.ShouldBe(HttpStatusCode.NoContent);
|
|
|
|
(await admin.PostAsJsonAsync("api/assignments", new { cameraId, agentId = secondAgent.Id }))
|
|
.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
await DispatchPendingJobsAsync();
|
|
|
|
var secondClaim = await secondAgentClient.GetAsync($"api/agents/{secondAgent.Id}/analysis-jobs/next");
|
|
secondClaim.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var secondAttemptId = (await secondClaim.Content.ReadFromJsonAsync<JsonElement>())
|
|
.GetProperty("attemptId").GetGuid();
|
|
secondAttemptId.ShouldNotBe(firstAttemptId);
|
|
|
|
var staleResult = await AgentClient(firstAgent.ApiKey).PutAsJsonAsync(
|
|
$"api/agents/{firstAgent.Id}/analysis-jobs/{jobId}/result",
|
|
new
|
|
{
|
|
attemptId = firstAttemptId,
|
|
success = true,
|
|
detections = new[] { new { label = "stale", confidence = 0.9, x = 0.1, y = 0.1, width = 0.2, height = 0.2 } }
|
|
});
|
|
staleResult.StatusCode.ShouldBe(HttpStatusCode.Conflict);
|
|
|
|
var currentResult = await secondAgentClient.PutAsJsonAsync(
|
|
$"api/agents/{secondAgent.Id}/analysis-jobs/{jobId}/result",
|
|
new
|
|
{
|
|
attemptId = secondAttemptId,
|
|
success = true,
|
|
detections = new[] { new { label = "person", confidence = 0.95, x = 0.1, y = 0.1, width = 0.2, height = 0.2 } }
|
|
});
|
|
currentResult.StatusCode.ShouldBe(HttpStatusCode.NoContent);
|
|
|
|
var finalResponse = await admin.GetAsync($"api/cameras/{cameraId}/analysis-jobs/{jobId}");
|
|
finalResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var finalJob = await finalResponse.Content.ReadFromJsonAsync<JsonElement>();
|
|
finalJob.GetProperty("retryCount").GetInt32().ShouldBe(1);
|
|
var resultJson = finalJob.GetProperty("resultJson").GetString()
|
|
?? throw new InvalidOperationException("Completed analysis job must persist its result JSON");
|
|
resultJson.ShouldContain("person");
|
|
resultJson.ShouldNotContain("stale");
|
|
|
|
// Exercise the scheduled timeout sweep as well as the explicit failure retry above.
|
|
var timedJobResponse = await admin.PostAsJsonAsync($"api/cameras/{cameraId}/analysis-jobs", new
|
|
{
|
|
jobType = "ObjectDetection"
|
|
});
|
|
timedJobResponse.StatusCode.ShouldBe(HttpStatusCode.Accepted);
|
|
var timedJobId = (await timedJobResponse.Content.ReadFromJsonAsync<JsonElement>())
|
|
.GetProperty("jobId").GetGuid();
|
|
|
|
await DispatchPendingJobsAsync();
|
|
var timedClaim = await secondAgentClient.GetAsync($"api/agents/{secondAgent.Id}/analysis-jobs/next");
|
|
timedClaim.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var timedAttemptId = (await timedClaim.Content.ReadFromJsonAsync<JsonElement>())
|
|
.GetProperty("attemptId").GetGuid();
|
|
|
|
await using (var scope = Factory.Services.CreateAsyncScope())
|
|
{
|
|
var dbFactory = scope.ServiceProvider.GetRequiredService<IDbContextFactory<AppDbContext>>();
|
|
await using var db = await dbFactory.CreateDbContextAsync();
|
|
await db.AnalysisJobs
|
|
.Where(job => job.Id == timedJobId)
|
|
.ExecuteUpdateAsync(setters => setters
|
|
.SetProperty(job => job.DispatchedAt, DateTime.UtcNow.AddHours(-1)));
|
|
}
|
|
|
|
await using (var scope = Factory.Services.CreateAsyncScope())
|
|
{
|
|
var services = scope.ServiceProvider;
|
|
var dispatcher = new AnalysisJobDispatcherJob(
|
|
services.GetRequiredService<IDbContextFactory<AppDbContext>>(),
|
|
services.GetRequiredService<IAnalysisJobSchedulerService>(),
|
|
services.GetRequiredService<Microsoft.Extensions.Logging.ILogger<AnalysisJobDispatcherJob>>());
|
|
await dispatcher.ExecuteTimeoutSweepAsync();
|
|
}
|
|
|
|
(await secondAgentClient.GetAsync($"api/agents/{secondAgent.Id}/analysis-jobs/next"))
|
|
.StatusCode.ShouldBe(HttpStatusCode.NoContent);
|
|
await DispatchPendingJobsAsync();
|
|
var retriedClaim = await secondAgentClient.GetAsync($"api/agents/{secondAgent.Id}/analysis-jobs/next");
|
|
retriedClaim.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var retryAttemptId = (await retriedClaim.Content.ReadFromJsonAsync<JsonElement>())
|
|
.GetProperty("attemptId").GetGuid();
|
|
retryAttemptId.ShouldNotBe(timedAttemptId);
|
|
|
|
var lateTimedResult = await secondAgentClient.PutAsJsonAsync(
|
|
$"api/agents/{secondAgent.Id}/analysis-jobs/{timedJobId}/result",
|
|
new
|
|
{
|
|
attemptId = timedAttemptId,
|
|
success = true,
|
|
detections = new[] { new { label = "timed-out", confidence = 0.9, x = 0.1, y = 0.1, width = 0.2, height = 0.2 } }
|
|
});
|
|
lateTimedResult.StatusCode.ShouldBe(HttpStatusCode.Conflict);
|
|
|
|
var retryResult = await secondAgentClient.PutAsJsonAsync(
|
|
$"api/agents/{secondAgent.Id}/analysis-jobs/{timedJobId}/result",
|
|
new
|
|
{
|
|
attemptId = retryAttemptId,
|
|
success = true,
|
|
detections = new[] { new { label = "retry", confidence = 0.95, x = 0.1, y = 0.1, width = 0.2, height = 0.2 } }
|
|
});
|
|
retryResult.StatusCode.ShouldBe(HttpStatusCode.NoContent);
|
|
|
|
var timedFinalResponse = await admin.GetAsync($"api/cameras/{cameraId}/analysis-jobs/{timedJobId}");
|
|
timedFinalResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var timedFinalJob = await timedFinalResponse.Content.ReadFromJsonAsync<JsonElement>();
|
|
timedFinalJob.GetProperty("retryCount").GetInt32().ShouldBe(1);
|
|
var timedResultJson = timedFinalJob.GetProperty("resultJson").GetString()
|
|
?? throw new InvalidOperationException("Retried analysis job must persist its result JSON");
|
|
timedResultJson.ShouldContain("retry");
|
|
}
|
|
|
|
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 token = (await tokenResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("token").GetString()!;
|
|
|
|
var registration = await admin.PostAsJsonAsync("api/agents/register", new
|
|
{
|
|
token,
|
|
hostname,
|
|
version = "1.0.0-test"
|
|
});
|
|
registration.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
var agent = await registration.Content.ReadFromJsonAsync<JsonElement>();
|
|
var id = agent.GetProperty("agentId").GetGuid();
|
|
var apiKey = agent.GetProperty("apiKey").GetString()!;
|
|
|
|
var heartbeat = await AgentClient(apiKey).PostAsJsonAsync($"api/agents/{id}/heartbeat", new
|
|
{
|
|
publicIp = "127.0.0.1",
|
|
cpuCores = 4,
|
|
memoryMb = 4096
|
|
});
|
|
heartbeat.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
return (id, apiKey);
|
|
}
|
|
|
|
private HttpClient AgentClient(string apiKey)
|
|
{
|
|
var client = Factory.CreateClient();
|
|
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
|
|
return client;
|
|
}
|
|
|
|
private async Task<HttpResponseMessage> ClaimNextAsync((Guid Id, string ApiKey) agent) =>
|
|
await AgentClient(agent.ApiKey).GetAsync($"api/agents/{agent.Id}/analysis-jobs/next");
|
|
|
|
private async Task DispatchPendingJobsAsync()
|
|
{
|
|
await using var scope = Factory.Services.CreateAsyncScope();
|
|
var scheduler = scope.ServiceProvider.GetRequiredService<IAnalysisJobSchedulerService>();
|
|
(await scheduler.ProcessPendingJobsAsync(16, CancellationToken.None)).ShouldBe(1);
|
|
}
|
|
}
|