Track manual snapshots and apply versioned camera config
Heimdall Gitea / Build and tests (pull_request) Failing after 1m34s
Heimdall Gitea / Publish versioned release (pull_request) Skipped

This commit is contained in:
Arnaud Dartois committed 2026-10-23 07:30:58 +02:00
1 parent f4a8f4a668
commit 8f00f69a5f
30 files changed
+645 -63

No files matched your search

@@ -7,6 +7,7 @@ using Heimdall.Application.Cameras.Queries.GetCamera;
using Heimdall.Application.Cameras.Queries.GetCamerasBySite;
using Heimdall.Application.DTOs;
using Heimdall.Application.Common;
using Heimdall.Domain.Entities;
using Heimdall.Application.Services;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Security;
@@ -46,11 +47,67 @@ public class CamerasController : ControllerBase
if (camera.Status != CameraStatus.Online) return Conflict(new { error = "The camera is not online" });
if (camera.AgentId is null) return Conflict(new { error = "No agent is assigned to this camera" });
var requestId = Guid.NewGuid();
var snapshotRequest = new ManualSnapshotRequest(requestId, id, camera.AgentId.Value, DateTime.UtcNow);
_db.ManualSnapshotRequests.Add(snapshotRequest);
await _db.SaveChangesWithRetryAsync(ct: ct);
if (!await _broadcast.RequestManualSnapshot(camera.AgentId.Value, id, requestId, ct))
{
snapshotRequest.Fail("L'agent affecté est indisponible.", DateTime.UtcNow);
await _db.SaveChangesWithRetryAsync(ct: ct);
return Conflict(new { error = "The assigned agent is offline" });
}
return Accepted(new { requestId });
}
/// <summary>Read the durable outcome of a manual capture request.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)]
[HttpGet("{id:guid}/snapshot/{requestId:guid}")]
public async Task<IActionResult> GetSnapshotRequest(Guid id, Guid requestId, CancellationToken ct)
{
var request = await _db.ManualSnapshotRequests.AsNoTracking()
.FirstOrDefaultAsync(r => r.Id == requestId && r.CameraId == id, ct);
if (request is null) return NotFound();
if (request.Status == ManualSnapshotStatus.Pending && request.ExpiresAt <= DateTime.UtcNow)
{
await _db.ManualSnapshotRequests
.Where(r => r.Id == requestId && r.Status == ManualSnapshotStatus.Pending && r.ExpiresAt <= DateTime.UtcNow)
.ExecuteUpdateAsync(setters => setters
.SetProperty(r => r.Status, ManualSnapshotStatus.TimedOut)
.SetProperty(r => r.FailureReason, "La capture n'a pas été livrée dans le délai attendu.")
.SetProperty(r => r.UpdatedAt, DateTime.UtcNow), ct);
request = await _db.ManualSnapshotRequests.AsNoTracking()
.FirstAsync(r => r.Id == requestId, ct);
}
return Ok(new { requestId = request.Id, status = request.Status.ToString(),
reason = request.FailureReason, updatedAt = request.UpdatedAt });
}
/// <summary>Record a capture failure reported by the agent assigned when the command was issued.</summary>
[Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)]
[HttpPut("{id:guid}/snapshot/{requestId:guid}/failure")]
public async Task<IActionResult> FailSnapshotRequest(Guid id, Guid requestId,
[FromBody] ManualSnapshotFailure failure, CancellationToken ct)
{
var exists = await _db.ManualSnapshotRequests.AnyAsync(r => r.Id == requestId && r.CameraId == id, ct);
if (!exists) return NotFound();
var reason = failure.Code switch
{
"camera_unavailable" => "La caméra n'est plus affectée ou est désactivée sur l'agent.",
"no_frame" => "Aucune image n'a été reçue du flux de la caméra.",
"queue_failed" => "L'agent n'a pas pu enregistrer la capture pour livraison.",
_ => "La capture a échoué sur l'agent."
};
await _db.ManualSnapshotRequests
.Where(r => r.Id == requestId && r.CameraId == id && r.Status != ManualSnapshotStatus.Completed)
.ExecuteUpdateAsync(setters => setters
.SetProperty(r => r.Status, ManualSnapshotStatus.Failed)
.SetProperty(r => r.FailureReason, reason)
.SetProperty(r => r.UpdatedAt, DateTime.UtcNow), ct);
return NoContent();
}
public sealed record ManualSnapshotFailure(string Code);
/// <summary>Create a new camera.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
[HttpPost]
@@ -133,7 +133,11 @@ public class EventsController : ControllerBase
var ev = await _db.CameraEvents.FirstOrDefaultAsync(e => e.Id == id, ct);
if (ev is null) return NotFound();
if (ev.SnapshotObjectKey is not null) return Ok(new { url = ev.SnapshotUrl });
if (ev.SnapshotObjectKey is not null)
{
await CompleteManualSnapshotRequestAsync(ev, ct);
return Ok(new { url = ev.SnapshotUrl });
}
var mediaType = Request.ContentType?.Split(';')[0].Trim();
if (!string.Equals(mediaType, "image/jpeg", StringComparison.OrdinalIgnoreCase))
@@ -164,6 +168,10 @@ public class EventsController : ControllerBase
try
{
ev.SetStoredSnapshot(key, location);
var manualRequest = ev.Type == EventType.ManualSnapshot
? await _db.ManualSnapshotRequests.FirstOrDefaultAsync(r => r.Id == ev.Id && r.CameraId == ev.CameraId, ct)
: null;
manualRequest?.Complete(DateTime.UtcNow);
await _db.SaveChangesWithRetryAsync(ct: ct);
}
catch
@@ -175,6 +183,16 @@ public class EventsController : ControllerBase
return Ok(new { url = ev.SnapshotUrl });
}
private async Task CompleteManualSnapshotRequestAsync(Heimdall.Domain.Entities.CameraEvent ev, CancellationToken ct)
{
if (ev.Type != EventType.ManualSnapshot) return;
var request = await _db.ManualSnapshotRequests
.FirstOrDefaultAsync(r => r.Id == ev.Id && r.CameraId == ev.CameraId, ct);
if (request is null || request.Status == ManualSnapshotStatus.Completed) return;
request.Complete(DateTime.UtcNow);
await _db.SaveChangesWithRetryAsync(ct: ct);
}
/// <summary>Stream a stored JPEG only to a user allowed to read its camera.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)]
[HttpGet("{id:guid}/snapshot/content")]
@@ -1,4 +1,5 @@
using Heimdall.Application.Agents.Queries.GetAgent;
using Heimdall.Application.Agents.Commands.AcknowledgeCameraConfig;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
@@ -138,7 +139,7 @@ public class SettingsController : ControllerBase
/// <summary>
/// Get the effective configuration for an agent: global defaults merged with
/// per-agent overrides, plus the site's camera credential pool inside an
/// encrypted envelope. Accessible by the agent itself (API key, same site)
/// encrypted envelope. Accessible by the agent itself (API key)
/// or by an admin (JWT/Cookie).
/// </summary>
[Authorize(AuthenticationSchemes = "ApiKey,JwtBearer,Cookies")]
@@ -147,10 +148,13 @@ public class SettingsController : ControllerBase
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetEffectiveConfig(Guid agentId, CancellationToken ct)
{
// API key callers: the agent may only read its own site's config.
// The API key is bound to exactly one agent. Same-site agents must not
// be able to read each other's RTSP URLs or credential envelopes.
var isApiKey = User.HasClaim(c => c.Type == "auth_method" && c.Value == "api_key");
if (isApiKey)
{
if (User.FindFirst("agent_id")?.Value != agentId.ToString())
return Forbid();
var siteClaim = User.FindFirst("site_id")?.Value;
if (!Guid.TryParse(siteClaim, out var apiKeySiteId))
return Forbid();
@@ -167,9 +171,38 @@ public class SettingsController : ControllerBase
}
var result = await _mediator.Send(new GetEffectiveAgentConfigQuery(agentId), ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
if (!result.IsSuccess || result.Data is null)
return NotFound(new { error = result.Error });
Response.Headers["X-Camera-Config-Version"] = CameraConfigVersion.Compute(result.Data);
return Ok(result.Data);
}
public sealed record CameraConfigAckRequest(string Version);
/// <summary>Acknowledge the exact camera snapshot applied by this agent.</summary>
[Authorize(AuthenticationSchemes = "ApiKey")]
[HttpPost("agent/{agentId:guid}/camera-config-ack")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public async Task<IActionResult> AcknowledgeCameraConfig(Guid agentId,
[FromBody] CameraConfigAckRequest request, CancellationToken ct)
{
if (User.FindFirst("agent_id")?.Value != agentId.ToString())
return Forbid();
if (request.Version?.Length != 64 || !request.Version.All(Uri.IsHexDigit))
return BadRequest(new { error = "Invalid camera configuration version" });
var result = await _mediator.Send(new GetEffectiveAgentConfigQuery(agentId), ct);
if (!result.IsSuccess || result.Data is null)
return NotFound(new { error = result.Error });
if (!string.Equals(CameraConfigVersion.Compute(result.Data), request.Version,
StringComparison.OrdinalIgnoreCase))
return Conflict(new { error = "Camera configuration changed before acknowledgement" });
if (!await _mediator.Send(new AcknowledgeCameraConfigCommand(agentId, request.Version), ct))
return NotFound();
_logger.LogInformation("Agent {AgentId} applied camera configuration {Version}", agentId, request.Version);
return NoContent();
}
/// <summary>List all setting overrides for a specific agent (Admin only).</summary>