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(); services.AddSingleton(storage); services.RemoveAll(); services.AddSingleton(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(); (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(); (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 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 _objects = new(StringComparer.Ordinal); private readonly ConcurrentDictionary _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 DownloadAsync(string key, StorageLocation location, CancellationToken ct = default) => Task.FromResult(_objects.TryGetValue(key, out var bytes) ? new MemoryStream(bytes, writable: false) : null); public Task DownloadRangeAsync(string key, StorageLocation location, long start, long endInclusive, CancellationToken ct = default) => Task.FromResult(null); public Task DeleteBatchAsync(IReadOnlyCollection keys, StorageLocation location, CancellationToken ct = default) { foreach (var key in keys) _objects.TryRemove(key, out _); return Task.CompletedTask; } } }