using System.IO.Compression; using Febe.Core.Codecs.H264; using Febe.Core.Domain; using Febe.Core.Export; using Febe.Tests.Support; using Febe.Web.Export; namespace Febe.Tests.Web; /// /// The zip of «Scarica» of frames (tappa E3, D14): written while it is sent, through asynchronous writes only (a /// response body refuses synchronous ones), one entry per frame under the account folder, names made unique. /// [TestClass] public sealed class FrameServiceTests { public TestContext TestContext { get; set; } = null!; [TestMethod] public async Task TheZipIsWrittenThroughAsynchronousWritesOnly() { using var temp = new TempFolder("fotogrammi-zip"); var path = temp.Combine("video.mp4"); await File.WriteAllBytesAsync(path, H264PcmWriter.DemoVideo(), TestContext.CancellationToken); var clock = new ManualClock(Make.T0); var service = new FrameService(clock); var instants = new[] { TimeSpan.Zero, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1.5) }; var plan = new FrameDownloadPlan(FrameMode.Count, ExportFormat.Png, [ new FrameDownloadVideo("marta.demo", path, "post", instants, Make.T0.AddDays(-3)), new FrameDownloadVideo("marta.demo", path, "post", instants[..1], Make.T0.AddDays(-3)), ]); using var sent = new MemoryStream(); await service.WriteZipAsync(new AsyncOnlyStream(sent), plan, publicationTime: true, TestContext.CancellationToken); using var archive = new ZipArchive(new MemoryStream(sent.ToArray()), ZipArchiveMode.Read); CollectionAssert.AreEqual( new[] { "marta.demo/post_f001.png", "marta.demo/post_f002.png", "marta.demo/post_f003.png", "marta.demo/post_f001 (2).png" }, archive.Entries.Select(e => e.FullName).ToArray()); var published = TimeZoneInfo.ConvertTime(Make.T0.AddDays(-3), clock.LocalZone).DateTime; foreach (var entry in archive.Entries) { Assert.AreEqual(entry.Length, entry.CompressedLength, "frames are stored, not compressed"); // The zip keeps local date and time fields at 2 s steps: the time of publication where Febe runs (D18). Assert.IsLessThanOrEqualTo(2.0, Math.Abs((entry.LastWriteTime.DateTime - published).TotalSeconds), $"{entry.LastWriteTime} vs {published}"); } } [TestMethod] [Timeout(120_000, CooperativeCancellation = true)] public async Task ASlowReaderThatKeepsReadingGetsTheWholeZip() { var ct = TestContext.CancellationToken; using var temp = new TempFolder("fotogrammi-lento"); var path = temp.Combine("rumore.mp4"); await File.WriteAllBytesAsync(path, NoiseVideo(), ct); // The time of the stalls moves only as the link sends, never with the load of the machine. var time = new LinkTime(); var service = new FrameService(new ManualClock(Make.T0)) { WriteStall = TimeSpan.FromMilliseconds(400), StallTime = time }; var plan = new FrameDownloadPlan(FrameMode.At, ExportFormat.Png, [ new FrameDownloadVideo("marta.demo", path, "rumore", [TimeSpan.Zero], Make.T0), ]); // 64 KB every 150 ms: a frame of a few hundred KB takes longer than the 400 ms of a stall, but every piece goes. using var sent = new MemoryStream(); var link = new SlowStream(sent, TimeSpan.FromMilliseconds(150), time); await service.WriteZipAsync(link, plan, publicationTime: false, ct); using var archive = new ZipArchive(new MemoryStream(sent.ToArray()), ZipArchiveMode.Read); var entry = archive.Entries.Single(); Assert.IsGreaterThan(64L * 1024 * 3, entry.Length, "a frame that takes more than a stall to send"); Assert.IsGreaterThan(TimeSpan.FromMilliseconds(400), link.Busy, "the link was slower than a stall for the frame"); } [TestMethod] [Timeout(120_000, CooperativeCancellation = true)] public async Task AReaderThatStopsReadingAbortsTheZip() { var ct = TestContext.CancellationToken; using var temp = new TempFolder("fotogrammi-fermo"); var path = temp.Combine("video.mp4"); await File.WriteAllBytesAsync(path, H264PcmWriter.DemoVideo(), ct); var service = new FrameService(new ManualClock(Make.T0)) { WriteStall = TimeSpan.FromMilliseconds(300) }; var plan = new FrameDownloadPlan(FrameMode.At, ExportFormat.Png, [ new FrameDownloadVideo("marta.demo", path, "post", [TimeSpan.Zero], Make.T0), ]); await Assert.ThrowsAsync(() => service.WriteZipAsync(new SlowStream(Stream.Null, Timeout.InfiniteTimeSpan), plan, false, ct)); Assert.IsFalse(ct.IsCancellationRequested); } /// A video of one picture of noise (320 × 320): its PNG frame is several hundred KB. private static byte[] NoiseVideo() { var random = new Random(28); using var output = new MemoryStream(); H264PcmWriter.WriteMp4(output, 320, 320, 1, 8, _ => { var p = new H264PcmPicture(320, 320); for (var i = 0; i < p.Y.Length; i++) { p.Y[i] = (byte)random.Next(16, 236); } for (var i = 0; i < p.Cb.Length; i++) { p.Cb[i] = (byte)random.Next(16, 241); p.Cr[i] = (byte)random.Next(16, 241); } return p; }); return output.ToArray(); } /// /// A response body on a slow link: asynchronous writes only, each taking perPiece for every 64 KB it holds /// (a write completes once its bytes are sent); an infinite time is a reader that stopped. With a /// a write moves that time instead of waiting for the real one. /// private sealed class SlowStream(Stream inner, TimeSpan perPiece, LinkTime? time = null) : Stream { public TimeSpan Busy { get; private set; } public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public override void Flush() => throw new InvalidOperationException("synchronous flush"); public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask; public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); public override void SetLength(long value) => throw new NotSupportedException(); public override void Write(byte[] buffer, int offset, int count) => throw new InvalidOperationException("synchronous write"); public override void Write(ReadOnlySpan buffer) => throw new InvalidOperationException("synchronous write"); public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) { var wait = perPiece == Timeout.InfiniteTimeSpan ? Timeout.InfiniteTimeSpan : perPiece * ((buffer.Length + 65535) / 65536); if (time is not null && wait != Timeout.InfiniteTimeSpan) { time.Advance(wait); // the stall timers due before this write is sent fire now cancellationToken.ThrowIfCancellationRequested(); } else { await Task.Delay(wait, cancellationToken); } if (wait != Timeout.InfiniteTimeSpan) { Busy += wait; } await inner.WriteAsync(buffer, cancellationToken); } } /// /// A time that moves only when is called: its timers fire then, in order, on the caller's /// thread. Only one-shot timers (those of a ) are supported. /// private sealed class LinkTime : TimeProvider { private readonly Lock _gate = new(); private readonly List _timers = []; private DateTimeOffset _now = Make.T0; public override DateTimeOffset GetUtcNow() { lock (_gate) { return _now; } } public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) { Assert.AreEqual(Timeout.InfiniteTimeSpan, period, "one-shot timers only"); var timer = new LinkTimer(this, callback, state); timer.Change(dueTime, period); return timer; } public void Advance(TimeSpan by) { List due; lock (_gate) { _now += by; due = [.. _timers.Where(t => t.Due <= _now).OrderBy(t => t.Due)]; foreach (var t in due) { _timers.Remove(t); } } foreach (var t in due) { t.Fire(); } } private sealed class LinkTimer(LinkTime owner, TimerCallback callback, object? state) : ITimer { public DateTimeOffset Due { get; private set; } public bool Change(TimeSpan dueTime, TimeSpan period) { lock (owner._gate) { owner._timers.Remove(this); if (dueTime != Timeout.InfiniteTimeSpan) { Due = owner._now + dueTime; owner._timers.Add(this); } } return true; } public void Fire() => callback(state); public void Dispose() { lock (owner._gate) { owner._timers.Remove(this); } } public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; } } } /// A response body: asynchronous writes only. private sealed class AsyncOnlyStream(Stream inner) : Stream { public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public override void Flush() => throw new InvalidOperationException("synchronous flush"); public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask; public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); public override void SetLength(long value) => throw new NotSupportedException(); public override void Write(byte[] buffer, int offset, int count) => throw new InvalidOperationException("synchronous write"); public override void Write(ReadOnlySpan buffer) => throw new InvalidOperationException("synchronous write"); public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => inner.WriteAsync(buffer, offset, count, cancellationToken); public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) => inner.WriteAsync(buffer, cancellationToken); } }