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
@@ -23,7 +23,7 @@ public abstract class PostgresTestBase : IAsyncLifetime
|
||||
protected PostgresTestBase(PostgreSqlContainerFixture postgres)
|
||||
{
|
||||
_postgres = postgres;
|
||||
_connectionString = postgres.ConnectionString;
|
||||
_connectionString = postgres.IsAvailable ? postgres.ConnectionString : string.Empty;
|
||||
_factoryLazy = new Lazy<HeimdallWebApplicationFactory>(
|
||||
() => new HeimdallWebApplicationFactory(postgres.ConnectionString));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
using Heimdall.IntegrationTests.Factories;
|
||||
using Heimdall.TestCommon;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.IntegrationTests.Controllers;
|
||||
|
||||
public sealed class RecordingQuotaTests : PostgresTestBase
|
||||
{
|
||||
private readonly PostgreSqlContainerFixture _postgres;
|
||||
|
||||
public RecordingQuotaTests(PostgreSqlContainerFixture postgres) : base(postgres)
|
||||
{
|
||||
_postgres = postgres;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConcurrentAgentUploads_DoNotExceedConfiguredCentralQuota()
|
||||
{
|
||||
if (!_postgres.IsAvailable) return;
|
||||
|
||||
var storage = new BarrierRecordingStorage(expectedConcurrentUploads: 2);
|
||||
await using var quotaFactory = new HeimdallWebApplicationFactory(_postgres.ConnectionString,
|
||||
recordingQuotaMaxBytes: 32,
|
||||
configureTestServices: services =>
|
||||
{
|
||||
services.RemoveAll<IRecordingStorage>();
|
||||
services.AddSingleton<IRecordingStorage>(storage);
|
||||
services.RemoveAll<IStorageObjectDeletion>();
|
||||
services.AddSingleton<IStorageObjectDeletion>(storage);
|
||||
});
|
||||
|
||||
var admin = await quotaFactory.CreateAdminClientAsync();
|
||||
var siteResponse = await admin.PostAsJsonAsync("api/sites", new
|
||||
{
|
||||
name = "Recording quota site",
|
||||
timezone = "UTC"
|
||||
});
|
||||
siteResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
using var site = JsonDocument.Parse(await siteResponse.Content.ReadAsStringAsync());
|
||||
var siteId = site.RootElement.GetProperty("id").GetGuid();
|
||||
var registrationToken = site.RootElement.GetProperty("registrationToken").GetString();
|
||||
registrationToken.ShouldNotBeNullOrWhiteSpace();
|
||||
|
||||
var registerResponse = await admin.PostAsJsonAsync("api/agents/register", new
|
||||
{
|
||||
token = registrationToken,
|
||||
hostname = "recording-quota-agent",
|
||||
version = "quota-test",
|
||||
publicIp = (string?)null
|
||||
});
|
||||
registerResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
using var agent = JsonDocument.Parse(await registerResponse.Content.ReadAsStringAsync());
|
||||
var agentId = agent.RootElement.GetProperty("agentId").GetGuid();
|
||||
var apiKey = agent.RootElement.GetProperty("apiKey").GetString();
|
||||
apiKey.ShouldNotBeNullOrWhiteSpace();
|
||||
|
||||
var cameraResponse = await admin.PostAsJsonAsync("api/cameras", new
|
||||
{
|
||||
siteId,
|
||||
name = "Quota camera",
|
||||
rtspUrl = "rtsp://quota-camera.invalid/stream",
|
||||
manufacturer = "test",
|
||||
model = "test"
|
||||
});
|
||||
cameraResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
using var cameraJson = JsonDocument.Parse(await cameraResponse.Content.ReadAsStringAsync());
|
||||
var cameraId = cameraJson.RootElement.GetProperty("id").GetGuid();
|
||||
|
||||
var assignmentResponse = await admin.PostAsJsonAsync("api/assignments", new
|
||||
{
|
||||
cameraId,
|
||||
agentId,
|
||||
reason = "quota-test"
|
||||
});
|
||||
assignmentResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
var enableResponse = await admin.PutAsJsonAsync($"api/cameras/{cameraId}", new
|
||||
{
|
||||
name = "Quota camera",
|
||||
rtspUrl = "rtsp://quota-camera.invalid/stream",
|
||||
status = "Online",
|
||||
recordingEnabled = true
|
||||
});
|
||||
enableResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
|
||||
using var agentClient = quotaFactory.CreateClient();
|
||||
agentClient.DefaultRequestHeaders.Add("X-API-Key", apiKey);
|
||||
var timestamp = Uri.EscapeDataString(DateTime.UtcNow.ToString("O"));
|
||||
// Force two first attempts with the same id to finish object upload before either
|
||||
// can persist metadata. The loser must not overwrite the winner's object key.
|
||||
var racedId = Guid.NewGuid();
|
||||
var racedUploads = await Task.WhenAll(
|
||||
UploadAsync(agentClient, cameraId, racedId, timestamp, "....ftyp....AAAA"u8.ToArray()),
|
||||
UploadAsync(agentClient, cameraId, racedId, timestamp, "....ftyp....BBBB"u8.ToArray()));
|
||||
racedUploads.Select(response => response.StatusCode).Distinct().ShouldBe([HttpStatusCode.OK]);
|
||||
string racedStoragePath;
|
||||
await using (var scope = quotaFactory.Services.CreateAsyncScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
|
||||
(await db.Recordings.CountAsync(recording => recording.Id == racedId)).ShouldBe(1);
|
||||
racedStoragePath = await db.Recordings.Where(recording => recording.Id == racedId)
|
||||
.Select(recording => recording.StoragePath).SingleAsync();
|
||||
}
|
||||
var racedKeyParts = racedStoragePath.Split('/');
|
||||
racedKeyParts.Length.ShouldBe(4);
|
||||
racedKeyParts[0].ShouldBe("recordings");
|
||||
racedKeyParts[1].ShouldBe(cameraId.ToString("D"));
|
||||
racedKeyParts[2].ShouldBe(racedId.ToString("D"));
|
||||
Guid.TryParseExact(Path.GetFileNameWithoutExtension(racedKeyParts[3]), "N", out _).ShouldBeTrue();
|
||||
storage.ObjectCount.ShouldBe(1);
|
||||
|
||||
var firstId = Guid.NewGuid();
|
||||
var secondId = Guid.NewGuid();
|
||||
var responses = await Task.WhenAll(
|
||||
UploadAsync(agentClient, cameraId, firstId, timestamp),
|
||||
UploadAsync(agentClient, cameraId, secondId, timestamp));
|
||||
responses.Select(response => response.StatusCode)
|
||||
.OrderBy(status => (int)status)
|
||||
.ShouldBe(new[] { HttpStatusCode.OK, (HttpStatusCode)507 });
|
||||
var denied = responses.Single(response => (int)response.StatusCode == 507);
|
||||
(await denied.Content.ReadAsStringAsync()).Contains("quota exceeded", StringComparison.OrdinalIgnoreCase)
|
||||
.ShouldBeTrue();
|
||||
storage.ObjectCount.ShouldBe(2);
|
||||
|
||||
var accepted = responses.Single(response => response.StatusCode == HttpStatusCode.OK);
|
||||
using var acceptedJson = JsonDocument.Parse(await accepted.Content.ReadAsStringAsync());
|
||||
var acceptedId = acceptedJson.RootElement.GetProperty("id").GetGuid();
|
||||
await using (var scope = quotaFactory.Services.CreateAsyncScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
|
||||
(await db.Recordings.CountAsync()).ShouldBe(2);
|
||||
(await db.Recordings.SumAsync(recording => recording.SizeBytes)).ShouldBe(32);
|
||||
}
|
||||
|
||||
var retry = await UploadAsync(agentClient, cameraId, acceptedId, timestamp);
|
||||
retry.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
storage.ObjectCount.ShouldBe(2);
|
||||
}
|
||||
|
||||
private static Task<HttpResponseMessage> UploadAsync(HttpClient client, Guid cameraId, Guid recordingId,
|
||||
string timestamp, byte[]? bytes = null)
|
||||
{
|
||||
var content = new ByteArrayContent(bytes ?? "....ftyp....1234"u8.ToArray());
|
||||
content.Headers.ContentType = new MediaTypeHeaderValue("video/mp4");
|
||||
return client.PutAsync(
|
||||
$"api/cameras/{cameraId}/recordings/{recordingId}/content?timestamp={timestamp}&durationSeconds=1",
|
||||
content);
|
||||
}
|
||||
|
||||
private sealed class BarrierRecordingStorage(int expectedConcurrentUploads) : IRecordingStorage, IStorageObjectDeletion
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, byte[]> _objects = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<int, TaskCompletionSource> _uploadBarriers = new();
|
||||
private int _uploads;
|
||||
|
||||
public int ObjectCount => _objects.Count;
|
||||
|
||||
public StorageLocation CaptureCurrentLocation() =>
|
||||
new(StorageProvider.Local, LocalRoot: "/quota-test-recordings");
|
||||
|
||||
public async Task UploadAsync(string key, Stream content, string contentType, StorageLocation location,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
using var buffer = new MemoryStream();
|
||||
await content.CopyToAsync(buffer, ct);
|
||||
_objects[key] = buffer.ToArray();
|
||||
var uploadNumber = Interlocked.Increment(ref _uploads);
|
||||
var batch = (uploadNumber - 1) / expectedConcurrentUploads;
|
||||
var barrier = _uploadBarriers.GetOrAdd(batch,
|
||||
_ => new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously));
|
||||
if (uploadNumber % expectedConcurrentUploads == 0)
|
||||
barrier.TrySetResult();
|
||||
await barrier.Task.WaitAsync(ct);
|
||||
}
|
||||
|
||||
public Task<Stream?> DownloadAsync(string key, StorageLocation location, CancellationToken ct = default)
|
||||
=> Task.FromResult<Stream?>(_objects.TryGetValue(key, out var bytes) ? new MemoryStream(bytes, writable: false) : null);
|
||||
|
||||
public Task<Stream?> DownloadRangeAsync(string key, StorageLocation location, long start, long endInclusive,
|
||||
CancellationToken ct = default)
|
||||
=> Task.FromResult<Stream?>(null);
|
||||
|
||||
public Task DeleteBatchAsync(IReadOnlyCollection<string> keys, StorageLocation location,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
foreach (var key in keys) _objects.TryRemove(key, out _);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user