feat: complete local camera and operations acceptance
Heimdall Gitea / Detect CI scope (pull_request) Successful in 1m27s
Heimdall Gitea / Build and tests (pull_request) Failing after 12m27s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 4s
Heimdall Gitea / Detect CI scope (pull_request) Successful in 1m27s
Heimdall Gitea / Build and tests (pull_request) Failing after 12m27s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 4s
This commit is contained in:
1 parent
ae3203222b
commit
3208bc93fe
52 files changed
+1193
-106
No files matched your search
@@ -0,0 +1,14 @@
|
||||
namespace Heimdall.Application.Common;
|
||||
|
||||
/// <summary>Serializes recording usage checks across cameras and exposes the validated Central quota.</summary>
|
||||
public interface IRecordingQuotaGuard
|
||||
{
|
||||
long MaxStorageBytes { get; }
|
||||
Task<IRecordingQuotaLease> AcquireAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>A short-lived database transaction holding the global recording quota lock.</summary>
|
||||
public interface IRecordingQuotaLease : IAsyncDisposable
|
||||
{
|
||||
Task CommitAsync(CancellationToken ct = default);
|
||||
}
|
||||
+98
-17
@@ -4,6 +4,7 @@ using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Application.Recordings.Commands.UploadRecording;
|
||||
|
||||
@@ -18,7 +19,10 @@ public sealed record UploadRecordingCommand(
|
||||
|
||||
public sealed class UploadRecordingHandler(
|
||||
IApplicationDbContext db,
|
||||
IRecordingStorage storage) : IRequestHandler<UploadRecordingCommand, ServiceResult<RecordingDto>>
|
||||
IRecordingStorage storage,
|
||||
IRecordingQuotaGuard quota,
|
||||
IStorageObjectDeletion objectDeletion,
|
||||
ILogger<UploadRecordingHandler> logger) : IRequestHandler<UploadRecordingCommand, ServiceResult<RecordingDto>>
|
||||
{
|
||||
public async Task<ServiceResult<RecordingDto>> Handle(UploadRecordingCommand request, CancellationToken ct)
|
||||
{
|
||||
@@ -29,9 +33,9 @@ public sealed class UploadRecordingHandler(
|
||||
|
||||
var camera = await db.Cameras.AsNoTracking()
|
||||
.Where(c => c.Id == request.CameraId && !c.IsDeleted)
|
||||
.Select(c => new { c.Id, c.AgentId, c.StoragePolicyId })
|
||||
.Select(c => new { c.Id, c.AgentId, c.StoragePolicyId, c.RecordingEnabled })
|
||||
.SingleOrDefaultAsync(ct).ConfigureAwait(false);
|
||||
if (camera?.AgentId != request.AgentId)
|
||||
if (camera?.AgentId != request.AgentId || !camera.RecordingEnabled)
|
||||
return ServiceResult<RecordingDto>.NotFound("Camera not found");
|
||||
|
||||
var existing = await db.Recordings.AsNoTracking()
|
||||
@@ -45,23 +49,100 @@ public sealed class UploadRecordingHandler(
|
||||
|
||||
var timestamp = CameraEvent.NormalizeOccurredAt(request.Timestamp);
|
||||
var location = storage.CaptureCurrentLocation();
|
||||
var key = $"recordings/{request.CameraId:D}/{request.RecordingId:D}.mp4";
|
||||
if (request.Content.CanSeek) request.Content.Position = 0;
|
||||
await storage.UploadAsync(key, request.Content, "video/mp4", location, ct).ConfigureAwait(false);
|
||||
// Each attempt gets its own key so a racing retry cannot overwrite the winner's object
|
||||
// before the transaction discovers its already-persisted metadata row.
|
||||
var key = $"recordings/{request.CameraId:D}/{request.RecordingId:D}/{Guid.NewGuid():N}.mp4";
|
||||
|
||||
var recording = new Recording(request.CameraId, timestamp, request.DurationSeconds,
|
||||
key, request.SizeBytes, location.Provider, location, camera.StoragePolicyId, request.RecordingId);
|
||||
db.Recordings.Add(recording);
|
||||
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
||||
var shouldDeleteObject = false;
|
||||
var commitAttempted = false;
|
||||
try
|
||||
{
|
||||
if (request.Content.CanSeek) request.Content.Position = 0;
|
||||
await storage.UploadAsync(key, request.Content, "video/mp4", location, ct).ConfigureAwait(false);
|
||||
|
||||
var end = timestamp.AddSeconds(request.DurationSeconds);
|
||||
await db.CameraEvents
|
||||
.Where(e => e.CameraId == request.CameraId && e.RecordingId == null && e.OccurredAt >= timestamp && e.OccurredAt < end)
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(e => e.RecordingId, recording.Id), ct)
|
||||
.ConfigureAwait(false);
|
||||
ServiceResult<RecordingDto> result;
|
||||
await using (var quotaLease = await quota.AcquireAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
// Recheck under the quota lock to keep duplicate retries safe when uploads race.
|
||||
existing = await db.Recordings.AsNoTracking()
|
||||
.Where(r => r.Id == request.RecordingId)
|
||||
.Select(r => new { r.Id, r.CameraId, r.Timestamp, r.DurationSeconds, r.SizeBytes })
|
||||
.SingleOrDefaultAsync(ct).ConfigureAwait(false);
|
||||
if (existing is not null)
|
||||
{
|
||||
// The uploaded key is unique to this attempt, so it cannot be the
|
||||
// already-persisted object's key and is safe to remove in either case.
|
||||
shouldDeleteObject = true;
|
||||
result = existing.CameraId == request.CameraId
|
||||
? ServiceResult<RecordingDto>.Success(Map(existing.Id, existing.CameraId,
|
||||
existing.Timestamp, existing.DurationSeconds, existing.SizeBytes))
|
||||
: ServiceResult<RecordingDto>.Conflict("Recording identifier already belongs to another camera");
|
||||
commitAttempted = true;
|
||||
await quotaLease.CommitAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
var usedBytes = await db.Recordings.AsNoTracking()
|
||||
.SumAsync(r => (long?)r.SizeBytes, ct).ConfigureAwait(false) ?? 0;
|
||||
var overQuota = request.SizeBytes > quota.MaxStorageBytes ||
|
||||
usedBytes > quota.MaxStorageBytes - request.SizeBytes;
|
||||
if (overQuota)
|
||||
{
|
||||
shouldDeleteObject = true;
|
||||
result = ServiceResult<RecordingDto>.Failure(
|
||||
"Central recording storage quota exceeded; segment was not retained", 507);
|
||||
commitAttempted = true;
|
||||
await quotaLease.CommitAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
var recording = new Recording(request.CameraId, timestamp, request.DurationSeconds,
|
||||
key, request.SizeBytes, location.Provider, location, camera.StoragePolicyId, request.RecordingId);
|
||||
db.Recordings.Add(recording);
|
||||
await db.SaveChangesAsync(ct).ConfigureAwait(false);
|
||||
|
||||
return ServiceResult<RecordingDto>.Success(Map(recording.Id, recording.CameraId,
|
||||
recording.Timestamp, recording.DurationSeconds, recording.SizeBytes));
|
||||
var end = timestamp.AddSeconds(request.DurationSeconds);
|
||||
await db.CameraEvents
|
||||
.Where(e => e.CameraId == request.CameraId && e.RecordingId == null &&
|
||||
e.OccurredAt >= timestamp && e.OccurredAt < end)
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(e => e.RecordingId, recording.Id), ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
commitAttempted = true;
|
||||
await quotaLease.CommitAsync(ct).ConfigureAwait(false);
|
||||
result = ServiceResult<RecordingDto>.Success(Map(recording.Id, recording.CameraId,
|
||||
recording.Timestamp, recording.DurationSeconds, recording.SizeBytes));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldDeleteObject)
|
||||
await TryDeleteUploadedObjectAsync(key, location, request.RecordingId, ct).ConfigureAwait(false);
|
||||
return result;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Once commit starts its outcome can be ambiguous; leave this attempt's unique object
|
||||
// for the retry/orphan sweep instead of risking deletion after a successful DB commit.
|
||||
if (!commitAttempted)
|
||||
await TryDeleteUploadedObjectAsync(key, location, request.RecordingId, CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task TryDeleteUploadedObjectAsync(string key, StorageLocation location, Guid recordingId,
|
||||
CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await objectDeletion.DeleteBatchAsync([key], location, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
logger.LogWarning("Could not clean up an unretained recording object {RecordingId} (error type {ErrorType})",
|
||||
recordingId, ex.GetType().Name);
|
||||
}
|
||||
}
|
||||
|
||||
private static RecordingDto Map(Guid id, Guid cameraId, DateTime timestamp, double duration, long size) =>
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
public sealed record PlateOcrResult(string Text, double Confidence);
|
||||
|
||||
/// <summary>Runs self-hosted OCR over a user-supplied plate crop.</summary>
|
||||
public interface ILicensePlateOcr
|
||||
{
|
||||
Task<PlateOcrResult?> RecognizeAsync(ReadOnlyMemory<byte> image, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed record LicensePlateRecognitionResponse(Guid PlateId, Guid EventId, string PlateText,
|
||||
double Confidence, Guid? SuggestedVehicleId, Guid? SuggestedPersonId);
|
||||
|
||||
public interface ILicensePlateRecognitionService
|
||||
{
|
||||
Task<Common.ServiceResult<LicensePlateRecognitionResponse>> RecognizeAsync(
|
||||
Guid cameraId, ReadOnlyMemory<byte> image, CancellationToken ct);
|
||||
}
|
||||
Reference in new issue
Block a user