Files
Heimdall/tests/Heimdall.Agent.Tests/AgentRecordingServiceTests.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

111 lines
5.3 KiB
C#

using System.Collections.Concurrent;
using Heimdall.Agent.Services;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using NSubstitute;
namespace Heimdall.Agent.Tests;
public sealed class AgentRecordingServiceTests
{
[Fact]
public void CreateStartInfo_UsesSegmentedMp4AndTreatsRtspAsOneArgument()
{
const string rtsp = "rtsp://user:p@ss@camera/stream?profile=1&x=2";
var info = AgentRecordingService.CreateStartInfo("ffmpeg-test", rtsp, "/tmp/segments", 45);
info.FileName.ShouldBe("ffmpeg-test");
info.ArgumentList.ShouldContain(rtsp);
info.ArgumentList.ShouldContain("-map");
info.ArgumentList.ShouldContain("0:a:0?");
info.ArgumentList.ShouldContain("-c:a");
info.ArgumentList.ShouldContain("aac");
info.ArgumentList.ShouldContain("-b:a");
info.ArgumentList.ShouldContain("128k");
info.ArgumentList.ShouldContain("-segment_time");
info.ArgumentList.ShouldContain("45");
info.ArgumentList.ShouldContain("-segment_format");
info.ArgumentList.ShouldContain("mp4");
info.ArgumentList.ShouldContain("-segment_list_type");
info.ArgumentList.ShouldContain("csv");
info.ArgumentList.ShouldContain("/tmp/segments/segment-%06d.mp4");
info.UseShellExecute.ShouldBeFalse();
}
[Fact]
public async Task UploadFailureKeepsSegmentAndRetryUsesSameRecordingIdentity()
{
using var temp = new TempDir();
var cameraId = Guid.NewGuid();
var sessionId = Guid.NewGuid();
var sessionDirectory = Path.Combine(temp.Path, "recordings", cameraId.ToString("N"), sessionId.ToString("N"));
Directory.CreateDirectory(sessionDirectory);
var segmentPath = Path.Combine(sessionDirectory, "segment-000001.mp4");
await File.WriteAllBytesAsync(segmentPath, [0, 0, 0, 24, 102, 116, 121, 112]);
await File.WriteAllTextAsync(Path.Combine(sessionDirectory, "started-at.txt"), DateTime.UtcNow.ToString("O"));
await File.WriteAllTextAsync(Path.Combine(sessionDirectory, "segments.csv"), "segment-000001.mp4,0.000000,12.000000\n");
var requests = new ConcurrentQueue<(string Url, string? ApiKey, string? ContentType, bool SegmentExists)>();
var firstResponse = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var secondResponse = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var requestCount = 0;
using var client = new HttpClient(new MockHttpMessageHandler(request =>
{
requests.Enqueue((request.RequestUri!.ToString(), request.Headers.GetValues("X-API-Key").Single(),
request.Content?.Headers.ContentType?.MediaType, File.Exists(segmentPath)));
var status = Interlocked.Increment(ref requestCount) == 1
? System.Net.HttpStatusCode.ServiceUnavailable
: System.Net.HttpStatusCode.NoContent;
if (requestCount == 1) firstResponse.TrySetResult();
else secondResponse.TrySetResult();
return new HttpResponseMessage(status);
})) { BaseAddress = new Uri("http://central.test/") };
var clients = Substitute.For<IHttpClientFactory>();
clients.CreateClient("Central").Returns(client);
var streams = new CameraStreamService(NullLogger<CameraStreamService>.Instance);
var service = new AgentRecordingService(new CameraConfigStore(), streams,
new AgentState { ApiKey = "synthetic-agent-key" },
Options.Create(new AgentOptions
{
CentralUrl = "http://central.test",
SiteToken = "synthetic-site-token",
StateDirectory = temp.Path,
RecordingSpoolMaxBytes = 16 * 1024 * 1024
}), clients, NullLogger<AgentRecordingService>.Instance);
try
{
await service.StartAsync(CancellationToken.None);
await firstResponse.Task.WaitAsync(TimeSpan.FromSeconds(5));
await WaitUntilAsync(() => File.Exists(segmentPath), TimeSpan.FromSeconds(2));
await secondResponse.Task.WaitAsync(TimeSpan.FromSeconds(12));
await WaitUntilAsync(() => !File.Exists(segmentPath), TimeSpan.FromSeconds(2));
requestCount.ShouldBe(2);
var attempts = requests.ToArray();
attempts[0].Url.ShouldBe(attempts[1].Url);
attempts[0].Url.ShouldContain($"/api/cameras/{cameraId:D}/recordings/");
attempts[0].ApiKey.ShouldBe("synthetic-agent-key");
attempts[1].ApiKey.ShouldBe("synthetic-agent-key");
attempts[0].ContentType.ShouldBe("video/mp4");
attempts[1].ContentType.ShouldBe("video/mp4");
attempts[0].SegmentExists.ShouldBeTrue();
attempts[1].SegmentExists.ShouldBeTrue();
File.Exists(segmentPath).ShouldBeFalse();
}
finally
{
await service.StopAsync(CancellationToken.None);
streams.Dispose();
}
}
private static async Task WaitUntilAsync(Func<bool> condition, TimeSpan timeout)
{
var deadline = DateTime.UtcNow + timeout;
while (!condition() && DateTime.UtcNow < deadline)
await Task.Delay(25);
condition().ShouldBeTrue();
}
}