using System.Collections.Concurrent; using System.Text.Json.Nodes; using Febe.Browser.Cdp; using Febe.Browser.Diagnostics; using Febe.Browser.RemoteView; using Febe.Core.Abstractions; using Febe.Tests.Browser.TestSupport; namespace Febe.Tests.Browser; /// /// The frames' watchdog of the remote view (Gitea issue #52), without a browser: a lost acknowledgement, a page that /// does not repaint and a new document loaded without frames must never leave the view white and silent. The clock /// moves only when the test says so, one look of the watchdog at a time. /// [TestClass] public sealed class ScreencastWatchdogTests { private static readonly ScreencastWatchdog Watchdog = new(TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(250), TimeSpan.FromSeconds(30)); public TestContext TestContext { get; set; } = null!; [TestMethod] [Timeout(30_000, CooperativeCancellation = true)] public async Task ALostAcknowledgementIsFollowedByARestartAndTheFramesComeBack() { var ct = TestContext.CancellationToken; await using var bed = new Bed(lostAcks: true); await bed.StartAsync(ct); bed.Frame(); Assert.AreEqual(1, bed.Starts); // The ack was lost: Chromium sends nothing more. Two seconds later the frames are started again. await bed.StepAsync(TimeSpan.FromSeconds(2.25), ct); Assert.AreEqual(1, bed.Session.Restarts); Assert.AreEqual(2, bed.Starts, "a new screencast session"); var methods = bed.Cdp.Sent.Select(c => c.Method).Where(m => m is "Page.stopScreencast" or "Page.startScreencast").ToList(); CollectionAssert.AreEqual(new[] { "Page.startScreencast", "Page.stopScreencast", "Page.startScreencast" }, methods); Assert.IsTrue(bed.Info.Contains("Vista remota: nessun fotogramma da 2 s, riavvio dei fotogrammi."), bed.AllLines); // Frames flow again: said once, at Info. for (var i = 0; i < ScreencastWatchdog.FlowingFrames; i++) { bed.Frame(); } Assert.IsTrue(bed.Info.Any(l => l.StartsWith("Vista remota: fotogrammi di nuovo in arrivo, dopo ", StringComparison.Ordinal)), bed.AllLines); Assert.AreEqual(1 + ScreencastWatchdog.FlowingFrames, bed.Session.FramesReceived); // The stop is the last word: no start after it. await bed.Session.StopAsync(ct); Assert.AreEqual("Page.stopScreencast", bed.Cdp.Sent.Last(c => c.Method.Contains("Screencast", StringComparison.Ordinal) && c.Method != "Page.screencastFrameAck").Method); } [TestMethod] [Timeout(30_000, CooperativeCancellation = true)] public async Task APageThatNeverSendsAFrameGetsAStillPictureOfItself() { var ct = TestContext.CancellationToken; await using var bed = new Bed(screenshot: Jpeg(800, 600)); await bed.StartAsync(ct); // The restart after two seconds, then its wait for a first frame. await bed.StepAsync(TimeSpan.FromSeconds(2.25) + ScreencastWatchdog.FirstFrameWait, ct); var still = bed.Session.LastFrame; Assert.IsNotNull(still, "something to show"); Assert.IsTrue(still.Still); Assert.AreEqual(800, still.DeviceWidth, "the size written in the picture"); Assert.AreEqual(600, still.DeviceHeight); Assert.AreEqual(0, bed.Session.FramesReceived, "a still picture is not a frame of the screencast"); Assert.AreEqual(1, bed.Cdp.Sent.Count(c => c.Method == "Page.captureScreenshot")); using var read = CancellationTokenSource.CreateLinkedTokenSource(ct); read.CancelAfter(TimeSpan.FromSeconds(5)); await foreach (var frame in bed.Session.ReadFramesAsync(read.Token)) { Assert.IsTrue(frame.Still, "the reader gets it like any frame"); break; } } [TestMethod] [Timeout(30_000, CooperativeCancellation = true)] public async Task AFrameSoonAfterARestartNeedsNoStillPicture() { var ct = TestContext.CancellationToken; await using var bed = new Bed(screenshot: Jpeg(800, 600)); await bed.StartAsync(ct); // Restarted after two seconds: Chromium answers the start first and sends its frame a moment later. await bed.StepAsync(TimeSpan.FromSeconds(2.25), ct); Assert.AreEqual(1, bed.Session.Restarts); bed.Frame(); await bed.StepAsync(TimeSpan.FromSeconds(1), ct); Assert.IsFalse(bed.Cdp.Sent.Any(c => c.Method == "Page.captureScreenshot"), "the frame came: no picture taken. " + string.Join(", ", bed.Cdp.Sent.Where(c => c.Method != "Page.screencastFrameAck").Select(c => $"{c.Method}@{c.At:ss.fff}")) + " | " + bed.AllLines); Assert.IsNotNull(bed.Session.LastFrame); Assert.IsFalse(bed.Session.LastFrame.Still); } [TestMethod] [Timeout(30_000, CooperativeCancellation = true)] public async Task ANewDocumentLoadedWithoutFramesStartsThemAgainAtTheNextLook() { var ct = TestContext.CancellationToken; await using var bed = new Bed(); await bed.StartAsync(ct); bed.Frame(); // A frame of a page inside the page changes nothing; the main frame does. bed.Cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F2", ["parentId"] = "F1", ["url"] = "http://127.0.0.1/pubblicita" } }); bed.Cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "http://127.0.0.1/animata" } }); bed.Cdp.Raise("Page.loadEventFired", new JsonObject { ["timestamp"] = 1.0 }); await bed.StepAsync(Watchdog.Tick, ct); Assert.AreEqual(1, bed.Session.Restarts, "no two seconds of white after a new page"); Assert.IsTrue(bed.Info.Contains("Vista remota: pagina nuova caricata senza fotogrammi, riavvio dei fotogrammi."), bed.AllLines); } [TestMethod] [Timeout(30_000, CooperativeCancellation = true)] public async Task ANewDocumentWhoseFramesArriveIsLeftAlone() { var ct = TestContext.CancellationToken; await using var bed = new Bed(); await bed.StartAsync(ct); bed.Cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "http://127.0.0.1/animata" } }); bed.Frame(); bed.Cdp.Raise("Page.loadEventFired", new JsonObject { ["timestamp"] = 1.0 }); for (var i = 0; i < 6; i++) { await bed.StepAsync(Watchdog.Tick, ct); bed.Frame(); } Assert.AreEqual(0, bed.Session.Restarts); Assert.AreEqual(1, bed.Starts); } [TestMethod] [Timeout(60_000, CooperativeCancellation = true)] public async Task AStillPageCostsFewerAndFewerRestartsAndOneLineInTheRegistro() { var ct = TestContext.CancellationToken; await using var bed = new Bed(screenshot: Jpeg(1280, 900)); await bed.StartAsync(ct); // Thirty seconds of a page that does not move: restarts after 2, 4, 8 and 16 more seconds, not fifteen. await bed.StepAsync(TimeSpan.FromSeconds(30.25), ct); Assert.AreEqual(4, bed.Session.Restarts, bed.AllLines); Assert.AreEqual(1, bed.Info.Count(l => l.Contains("riavvio dei fotogrammi", StringComparison.Ordinal)), "one line for the whole silence, the others at Debug"); Assert.IsFalse(bed.AllLines.Contains("http", StringComparison.Ordinal), "no addresses in the registro"); } [TestMethod] [Timeout(30_000, CooperativeCancellation = true)] public async Task WithoutAWatchdogNothingIsStartedAgain() { var ct = TestContext.CancellationToken; await using var bed = new Bed(noWatchdog: true); await bed.StartAsync(ct); Assert.AreEqual(0, bed.Clock.Waiting, "nobody watches"); bed.Clock.Advance(TimeSpan.FromMinutes(1)); Assert.AreEqual(1, bed.Starts); Assert.IsFalse(bed.Cdp.Sent.Any(c => c.Method == "Page.captureScreenshot")); } [TestMethod] public void TheSizeOfAJpegIsReadFromItsFrameHeader() { Assert.AreEqual((800, 600), ScreencastSession.JpegSize(Jpeg(800, 600))); Assert.AreEqual((1280, 900), ScreencastSession.JpegSize(Jpeg(1280, 900, progressive: true))); Assert.IsNull(ScreencastSession.JpegSize([0xFF, 0xD8, 0xFF, 0xD9]), "no frame header"); Assert.IsNull(ScreencastSession.JpegSize([0x89, 0x50, 0x4E, 0x47]), "not a JPEG"); Assert.IsNull(ScreencastSession.JpegSize([])); Assert.IsNull(ScreencastSession.JpegSize([0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x11, 0x08]), "cut short"); } /// A minimal JPEG header: SOI, an APP0 segment, then a SOF0 (or SOF2) with the size. private static byte[] Jpeg(int width, int height, bool progressive = false) => [ 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0xFF, progressive ? (byte)0xC2 : (byte)0xC0, 0x00, 0x11, 0x08, (byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width, 0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xFF, 0xD9, ]; /// A screencast over a fake page and a clock that moves only when stepped. private sealed class Bed : IAsyncDisposable { private readonly ConcurrentQueue<(BrowserLogLevel Level, string Message)> _lines = new(); private readonly ScreencastWatchdog? _watchdog; private int _starts; private int _frameSession; public Bed(bool lostAcks = false, byte[]? screenshot = null, bool noWatchdog = false) { _watchdog = noWatchdog ? null : Watchdog; Clock = new SteppingClock(); Cdp = new FakeCdpSession(Clock) { Responder = (method, _) => { switch (method) { case "Page.startScreencast": Interlocked.Increment(ref _starts); return null; case "Page.screencastFrameAck" when lostAcks: throw new CdpCommandException(method, CdpCommandException.ServerErrorCode, "Session is not attached"); case "Page.captureScreenshot": return screenshot is null ? null : new JsonObject { ["data"] = Convert.ToBase64String(screenshot) }; default: return null; } }, }; Session = new ScreencastSession(Cdp, new DelegateBrowserLog((level, message, _) => _lines.Enqueue((level, message))), Clock); } public SteppingClock Clock { get; } public FakeCdpSession Cdp { get; } public ScreencastSession Session { get; } public int Starts => Volatile.Read(ref _starts); public List Info => [.. _lines.Where(l => l.Level == BrowserLogLevel.Information).Select(l => l.Message)]; public string AllLines => string.Join('\n', _lines.Select(l => $"{l.Level} {l.Message}")); public async Task StartAsync(CancellationToken ct) { await Session.StartAsync(new ScreencastOptions(Quality: 60, MaxWidth: 1280, MaxHeight: 900, Watchdog: _watchdog), ct); if (_watchdog is not null) { await Clock.WaitForSleeperAsync(ct); } } /// A frame of the screencast, as Chromium sends it. public void Frame() => Cdp.Raise("Page.screencastFrame", new JsonObject { ["sessionId"] = Interlocked.Increment(ref _frameSession), ["data"] = Convert.ToBase64String(Jpeg(1280, 900)), ["metadata"] = new JsonObject { ["deviceWidth"] = 1280, ["deviceHeight"] = 900, ["pageScaleFactor"] = 1 }, }); /// Moves the clock by , one look of the watchdog at a time. public async Task StepAsync(TimeSpan time, CancellationToken ct) { var tick = (_watchdog ?? Watchdog).Tick; for (var moved = TimeSpan.Zero; moved < time; moved += tick) { Clock.Advance(tick); await Clock.WaitForSleeperAsync(ct); } } public async ValueTask DisposeAsync() => await Session.DisposeAsync(); } /// A clock whose delays end only when the test moves it past them. private sealed class SteppingClock : IClock { private readonly Lock _gate = new(); private readonly List<(DateTimeOffset Due, TaskCompletionSource Done)> _sleepers = []; private DateTimeOffset _now = new(2026, 11, 16, 9, 0, 0, TimeSpan.Zero); public DateTimeOffset Now { get { lock (_gate) { return _now; } } } public TimeZoneInfo LocalZone => TimeZoneInfo.Utc; public int Waiting { get { lock (_gate) { return _sleepers.Count; } } } public Task Delay(TimeSpan time, CancellationToken ct) { ct.ThrowIfCancellationRequested(); if (time <= TimeSpan.Zero) { return Task.CompletedTask; } var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); lock (_gate) { _sleepers.Add((_now + time, done)); } ct.Register(() => { lock (_gate) { _sleepers.RemoveAll(s => s.Done == done); } done.TrySetCanceled(ct); }); return done.Task; } public void Advance(TimeSpan time) { List due; lock (_gate) { _now += time; due = [.. _sleepers.Where(s => s.Due <= _now).Select(s => s.Done)]; _sleepers.RemoveAll(s => s.Due <= _now); } foreach (var done in due) { done.TrySetResult(); } } /// Waits (in real time) until someone sleeps on the clock again: the watchdog finished its look. public async Task WaitForSleeperAsync(CancellationToken ct) { using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); timeout.CancelAfter(TimeSpan.FromSeconds(10)); while (Waiting == 0) { await Task.Delay(1, timeout.Token); } } } }