Files
Heimdall/src/Heimdall.Web/Controllers/AnalysisJobsController.cs
T

130 lines
6.6 KiB
C#
Raw Normal View History

2026-10-24 13:38:12 +02:00
using System.Text.Json;
using Heimdall.Api.Security;
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api")]
public sealed class AnalysisJobsController(
IApplicationDbContext db,
IAnalysisJobSchedulerService scheduler,
ResourceAccess access) : ControllerBase
{
private static readonly JsonSerializerOptions ResultJsonOptions = new(JsonSerializerDefaults.Web);
private const int MaxDetections = 500;
public sealed record CreateAnalysisJobRequest(string JobType = "ObjectDetection", string? ParametersJson = null);
public sealed record AnalysisDetection(string Label, float Confidence, float X, float Y,
float Width, float Height, int? ClassIndex = null);
public sealed record SubmitAnalysisResult(Guid AttemptId, bool Success, string? Error,
IReadOnlyList<AnalysisDetection>? Detections = null);
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
[HttpPost("cameras/{cameraId:guid}/analysis-jobs")]
public async Task<IActionResult> Create(Guid cameraId, [FromBody] CreateAnalysisJobRequest request,
CancellationToken ct)
{
var requester = await access.ResolveAsync(User, ct);
if (requester is null || requester.Kind != RequesterKind.Human ||
!await access.CameraAsync(requester, cameraId, ct)) return Forbid();
if (!Enum.TryParse<AnalysisJobType>(request.JobType, true, out var type) ||
type != AnalysisJobType.ObjectDetection)
return BadRequest(new { error = "Only ObjectDetection jobs are currently supported" });
if (request.ParametersJson is { Length: > 16_384 } || !IsJsonObjectOrNull(request.ParametersJson))
return BadRequest(new { error = "ParametersJson must be a JSON object of at most 16 KiB" });
var created = await scheduler.CreateJobAsync(cameraId, type, AnalysisJobPriority.SecurityHigh,
request.ParametersJson, ct);
return created.IsSuccess
? AcceptedAtAction(nameof(Get), new { cameraId, jobId = created.Data!.Id },
new { jobId = created.Data!.Id, status = created.Data.Status.ToString() })
: StatusCode(created.StatusCode ?? 400, new { error = created.Error });
}
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)]
[HttpGet("cameras/{cameraId:guid}/analysis-jobs/{jobId:guid}")]
public async Task<IActionResult> Get(Guid cameraId, Guid jobId, CancellationToken ct)
{
var requester = await access.ResolveAsync(User, ct);
if (requester is null || requester.Kind != RequesterKind.Human ||
!await access.CameraAsync(requester, cameraId, ct)) return Forbid();
var job = await db.AnalysisJobs.AsNoTracking()
.Where(j => j.Id == jobId && j.CameraId == cameraId)
.Select(j => new { j.Id, j.JobType, j.Status, j.RetryCount, j.ErrorMessage,
j.ResultJson, j.CreatedAt, j.DispatchedAt, j.CompletedAt })
.FirstOrDefaultAsync(ct);
return job is null ? NotFound() : Ok(job);
}
[Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)]
[HttpGet("agents/{agentId:guid}/analysis-jobs/next")]
public async Task<IActionResult> ClaimNext(Guid agentId, CancellationToken ct)
{
var requester = await access.ResolveAsync(User, ct);
if (requester is null || requester.Kind != RequesterKind.Agent ||
!await access.AgentAsync(requester, agentId, ct)) return Forbid();
var job = await scheduler.ClaimNextJobAsync(agentId, ct);
return job is null ? NoContent() : Ok(new
{
jobId = job.Id,
cameraId = job.CameraId,
attemptId = job.AttemptId,
jobType = job.JobType.ToString(),
parametersJson = job.ParametersJson
});
}
[Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)]
[HttpPut("agents/{agentId:guid}/analysis-jobs/{jobId:guid}/result")]
public async Task<IActionResult> SubmitResult(Guid agentId, Guid jobId,
[FromBody] SubmitAnalysisResult result, CancellationToken ct)
{
var requester = await access.ResolveAsync(User, ct);
if (requester is null || requester.Kind != RequesterKind.Agent ||
!await access.AgentAsync(requester, agentId, ct)) return Forbid();
if (result.AttemptId == Guid.Empty) return BadRequest(new { error = "AttemptId is required" });
if (result.Success && (result.Detections?.Count ?? 0) > MaxDetections)
return BadRequest(new { error = $"At most {MaxDetections} detections are accepted" });
if (result.Success && result.Detections?.Any(d => string.IsNullOrWhiteSpace(d.Label) ||
d.Label.Length > 120 || !float.IsFinite(d.Confidence) || d.Confidence is < 0 or > 1 ||
!float.IsFinite(d.X) || !float.IsFinite(d.Y) || !float.IsFinite(d.Width) ||
!float.IsFinite(d.Height) || d.X < 0 || d.Y < 0 || d.Width < 0 || d.Height < 0 ||
d.X + d.Width > 1.001f || d.Y + d.Height > 1.001f) == true)
return BadRequest(new { error = "Detection values are invalid" });
ServiceResult updated;
if (result.Success)
{
var payload = JsonSerializer.Serialize(new { detections = result.Detections ?? [] }, ResultJsonOptions);
updated = await scheduler.CompleteJobAsync(jobId, agentId, result.AttemptId, ct, payload);
}
else
{
var error = string.IsNullOrWhiteSpace(result.Error) ? "Agent reported analysis failure" : result.Error;
updated = await scheduler.FailJobAsync(jobId, agentId, result.AttemptId, error[..Math.Min(error.Length, 2000)], ct);
}
if (updated.IsSuccess) return NoContent();
if (updated.StatusCode == 404) return NotFound();
if (updated.StatusCode == 409) return Conflict(new { error = updated.Error });
return StatusCode(updated.StatusCode ?? 400, new { error = updated.Error });
}
private static bool IsJsonObjectOrNull(string? value)
{
if (value is null) return true;
try
{
using var document = JsonDocument.Parse(value);
return document.RootElement.ValueKind == JsonValueKind.Object;
}
catch (JsonException) { return false; }
}
}