Collegamento e motore: correzioni regole-1, regole-2, regole-6, websec-1, websec-5, websec-6, engine-1, engine-2, sched-1

Pagine aperte da Alberto non sono segnali (regole-1); cookie perso fuori sessione = disconnessione (regole-2); pagina a riposo quando Alberto lascia il browser (regole-6); la lease di «Accedi»/«Usa il browser» finisce da sola dopo 2 minuti senza vista remota né finestra (websec-1); ping con scadenza sulla vista remota (websec-5); aperture della vista remota serializzate (websec-6); orologio virtuale senza fine anticipata (engine-1); la sincronizzazione della coda non duplica il compito in corso (engine-2); raccolte in evidenza programmate (sched-1).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-14 00:21:13 +00:00
1 parent 78c92eb2a4
commit aff81dfac9
19 files changed
+1122 -92

No files matched your search

@@ -0,0 +1,40 @@
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Tests.Browser.TestSupport;
namespace Febe.Tests.Collection;
/// <summary>
/// Rule 7 of §2 against §7.6: the pages Alberto opens while he drives and no session runs — the login of «Accedi a
/// Instagram», a verification he completes — are not the page «going back to the login»; Instagram's own answers
/// (status, text) still are signals.
/// </summary>
[TestClass]
public sealed class SignalOwnershipTests
{
[TestMethod]
public void PathRulesAreNotSignalsWhileThePageIsAlbertos()
{
var clock = new VirtualClock();
var breaker = new RecordingBreaker();
var albertos = true;
var detector = new SignalDetector(SignalRules.LoadDefault(), breaker, clock, TimeSpan.Zero) { UserOwnsPage = () => albertos };
NavigationDescriptor Nav(string path) => new(HostKind.Site, "https://www.instagram.com" + path, "www.instagram.com", path, clock.Now);
ResponseDescriptor Document(string path, int status) =>
new("1", HostKind.Site, "https://www.instagram.com" + path, "www.instagram.com", path, status, "text/html", "Document", true, clock.Now);
Assert.IsNull(detector.ObserveNavigation(Nav("/accounts/login/")));
Assert.IsNull(detector.ObserveNavigation(Nav("/challenge/AbC123/")));
Assert.IsNull(detector.ObserveResponse(Document("/accounts/login/", 200)));
Assert.IsEmpty(breaker.Signals);
// Instagram's own answers keep counting: a 429 is a 429 whoever loaded the page.
Assert.AreEqual(SignalLevel.Throttle, detector.ObserveResponse(Document("/accounts/login/", 429))?.Level);
Assert.IsFalse(detector.ObserveSessionCookie(false) is null, "the recipes' cookie check is not a path rule");
// The engine's page (Alberto not at the browser, or a session running): the same addresses are signals.
albertos = false;
Assert.AreEqual(SignalLevel.Disconnect, detector.ObserveNavigation(Nav("/accounts/login/"))?.Level);
Assert.AreEqual(SignalLevel.Challenge, detector.ObserveResponse(Document("/challenge/AbC123/", 200))?.Level);
}
}
@@ -0,0 +1,188 @@
using System.Net;
using Febe.App;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Desktop;
/// <summary>
/// The link to Instagram in the shared composition (spec §4.1, §7.6, rule 7 of §2), with the real Instagram rules of
/// <c>segnali.json</c> and a fake browser that only answers by itself: the pages Alberto opens are not stop signals, a
/// session lost outside a session is a disconnection, and the «driving» lease of the connection page does not outlive
/// the browser window. Never Instagram.
/// </summary>
[TestClass]
public sealed class ConnectionLifecycleTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheLoginPageAlbertoOpensIsNotADisconnectionButTheEnginesPageGoingBackToItIs()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
var breaker = bed.App.Engine!.Services.Breaker;
// «Accedi a Instagram»: the real login page, which segnali.json calls «login-url» (a disconnection).
using (var begin = await bed.SendAsync(HttpMethod.Post, "/api/connection/begin", """{"openLogin":true}"""))
{
Assert.AreEqual(HttpStatusCode.NoContent, begin.StatusCode);
}
Assert.AreEqual("https://www.instagram.com/accounts/login/", browser.FakeCdp.Url);
// Instagram asks the new device to confirm during his login: his to complete, not the engine's (rule 7).
browser.FakeCdp.Navigated("https://www.instagram.com/challenge/AbC123/");
await breaker.FlushAsync();
Assert.AreEqual(BreakerStatus.Closed, breaker.State.Status, "the pages Alberto opens are not stop signals");
Assert.IsEmpty(await bed.App.Database.Incidents.ListOpenAsync(ct));
browser.FakeCdp.LoggedIn = true;
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsTrue(finish.GetProperty("connected").GetBoolean());
Assert.DoesNotContain("Riprendi", finish.GetProperty("message").GetString()!, "nothing to resume after a plain login");
// Without Alberto at the browser, the same address is the page going back to the login (§7.6).
browser.FakeCdp.Navigated("https://www.instagram.com/accounts/login/");
await breaker.FlushAsync();
Assert.AreEqual(BreakerStatus.Disconnected, breaker.State.Status);
Assert.AreEqual("login-url", (await bed.App.Database.Incidents.ListOpenAsync(ct)).Single().Signal);
}
[TestMethod]
[Timeout(90_000, CooperativeCancellation = true)]
public async Task ASessionLostOutsideASessionStopsTheEngineUntilResumeButScollegaDoesNot()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder("collegamento");
var locations = new MemoryLocationStore();
await using (var bed = await DesktopTestBed.StartAsync(temp: temp, locations: locations))
{
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var engine = bed.App.Engine!;
var breaker = engine.Services.Breaker;
await breaker.FlushAsync();
Assert.AreEqual(BreakerStatus.Closed, breaker.State.Status, "never connected: no session is no news");
await LoginAsync(bed);
// The page at rest, Alberto away: the session cookie goes (expired, dropped by Instagram). The background
// check notices: a disconnection, with its incident and its line in Attività (the alert follows it).
bed.Browser!.FakeCdp.LoggedIn = false;
await bed.App.Connection!.RefreshAsync(ct);
await breaker.FlushAsync();
Assert.AreEqual(BreakerStatus.Disconnected, breaker.State.Status);
Assert.AreEqual(SignalRules.SessionCookieMissingCode, (await bed.App.Database.Incidents.ListOpenAsync(ct)).Single().Signal);
var events = await bed.App.Database.Events.ListAsync(new EventQuery(), ct);
Assert.IsTrue(events.Any(e => e.Code == EngineEventCodes.DisconnectStop), "the «disconnessione» line that the alerts follow");
Assert.AreEqual("verificationRequired", (await bed.JsonAsync(HttpMethod.Get, "/api/connection")).GetProperty("state").GetString());
// A new login is not enough: «Riprendi», with the gradual start, restarts the engine.
var again = await LoginAsync(bed);
StringAssert.Contains(again, "premi «Riprendi»");
Assert.IsTrue((await engine.ResumeAsync(ct)).Resumed);
Assert.AreEqual(BreakerStatus.Closed, breaker.State.Status);
await bed.StopAsync();
}
// Next start: the profile lost the session meanwhile (a crash, S3). It had been connected: a disconnection.
await using (var bed = await DesktopTestBed.StartAsync(temp: temp, locations: locations))
{
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var engine = bed.App.Engine!;
await engine.Services.Breaker.FlushAsync();
Assert.AreEqual(BreakerStatus.Disconnected, engine.Services.Breaker.State.Status, "missing at start-up after a connection");
Assert.IsTrue((await engine.ResumeAsync(ct)).Resumed);
// «Scollega»: the session goes because Alberto wants so. Not a disconnection, now or at the next start.
await LoginAsync(bed);
using (var disconnect = await bed.SendAsync(HttpMethod.Post, "/api/connection/disconnect"))
{
Assert.AreEqual(HttpStatusCode.NoContent, disconnect.StatusCode);
}
await bed.App.Connection!.RefreshAsync(ct);
await engine.Services.Breaker.FlushAsync();
Assert.AreEqual(BreakerStatus.Closed, engine.Services.Breaker.State.Status);
Assert.AreEqual("notConnected", (await bed.JsonAsync(HttpMethod.Get, "/api/connection")).GetProperty("state").GetString());
await bed.StopAsync();
}
await using (var bed = await DesktopTestBed.StartAsync(temp: temp, locations: locations))
{
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
await bed.App.Engine!.Services.Breaker.FlushAsync();
Assert.AreEqual(BreakerStatus.Closed, bed.App.Engine.Services.Breaker.State.Status, "after «Scollega» a missing session is expected");
Assert.IsEmpty(await bed.App.Database.Incidents.ListOpenAsync(ct));
await bed.StopAsync();
}
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheConnectionLeaseEndsSoonAfterTheBrowserWindowWithoutHoFinito()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.DrivingGrace = TimeSpan.FromMilliseconds(500);
await LoginAsync(bed);
// «Usa il browser»: the window comes to the front, Alberto is driving.
using (var begin = await bed.SendAsync(HttpMethod.Post, "/api/connection/begin", """{"openLogin":false}"""))
{
Assert.AreEqual(HttpStatusCode.NoContent, begin.StatusCode);
}
Assert.IsTrue(browser.UserIsDriving);
Assert.IsTrue(bed.App.Engine!.Services.Runtime.UserIsDriving);
// While the window is in front the lease holds, however long he takes.
await Task.Delay(TimeSpan.FromSeconds(1.5), ct);
Assert.IsTrue(browser.UserIsDriving, "the window is in front: Alberto is still driving");
// He closes the window with its X (WebView2Host.Done: the window's own lease ends), no «Ho finito».
int Navigations() => browser.FakeCdp.Methods.Count(m => m == "Page.navigate");
var navigations = Navigations();
await browser.HideFromUserAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo la chiusura della finestra");
Assert.IsFalse(bed.App.Engine.Services.Runtime.UserIsDriving, "the engine may work again");
// The engine puts back to rest whatever he left open (§6.1).
await DesktopTestBed.WaitUntilAsync(() => Navigations() > navigations, TimeSpan.FromSeconds(10), "la pagina di riposo");
Assert.AreEqual("about:blank", browser.FakeCdp.Url);
// A late «Annulla» from a page left open does nothing to the page, which is the engine's again.
navigations = Navigations();
using (var cancel = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel"))
{
Assert.AreEqual(HttpStatusCode.NoContent, cancel.StatusCode);
}
Assert.AreEqual(navigations, Navigations());
Assert.IsFalse(browser.UserIsDriving);
}
/// <summary>«Accedi a Instagram», Alberto logs in, «Ho finito». Returns the message of «Ho finito».</summary>
private static async Task<string> LoginAsync(DesktopTestBed bed)
{
using (var begin = await bed.SendAsync(HttpMethod.Post, "/api/connection/begin", """{"openLogin":true}"""))
{
Assert.AreEqual(HttpStatusCode.NoContent, begin.StatusCode);
}
bed.Browser!.FakeCdp.LoggedIn = true;
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsTrue(finish.GetProperty("connected").GetBoolean(), finish.GetProperty("message").GetString());
return finish.GetProperty("message").GetString()!;
}
}
@@ -202,15 +202,28 @@ internal sealed class FakeBrowser : IFebeBrowser
}
}
/// <summary>A CDP session answering like a page: frame tree, navigation, the session cookie (name only).</summary>
/// <summary>
/// A CDP session answering like a page: frame tree, navigation (with its <c>Page.frameNavigated</c> event, as the
/// collection pipeline hears it), the session cookie (name only).
/// </summary>
internal sealed class FakeCdp : ICdpSession
{
private readonly Lock _gate = new();
private readonly Dictionary<string, List<Action<JsonElement>>> _handlers = new(StringComparer.Ordinal);
public bool LoggedIn { get; set; }
public string Url { get; private set; } = "about:blank";
public ConcurrentQueue<string> Methods { get; } = new();
/// <summary>The main frame moved to <paramref name="url"/> by itself (a redirect of the site), not by a command.</summary>
public void Navigated(string url)
{
Url = url;
Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = url } });
}
public Task<JsonElement> SendAsync(string method, object? parameters = null, CancellationToken ct = default)
{
CdpCommandPolicy.EnsureAllowed(method);
@@ -225,18 +238,57 @@ internal sealed class FakeCdp : ICdpSession
return Task.FromResult(JsonDocument.Parse(result.ToJsonString()).RootElement.Clone());
}
public IDisposable On(string eventName, Action<JsonElement> handler) => new Nothing();
public IDisposable On(string eventName, Action<JsonElement> handler)
{
lock (_gate)
{
if (!_handlers.TryGetValue(eventName, out var list))
{
_handlers[eventName] = list = [];
}
list.Add(handler);
}
return new Removal(() =>
{
lock (_gate)
{
_handlers[eventName].Remove(handler);
}
});
}
private JsonObject Navigate(object? parameters)
{
Url = (parameters as JsonObject)?["url"]?.GetValue<string>() ?? Url;
var url = (parameters as JsonObject)?["url"]?.GetValue<string>();
if (url is not null)
{
Navigated(url);
}
return new JsonObject { ["frameId"] = "F1" };
}
private sealed class Nothing : IDisposable
private void Raise(string eventName, JsonObject parameters)
{
public void Dispose()
Action<JsonElement>[] handlers;
lock (_gate)
{
handlers = _handlers.TryGetValue(eventName, out var list) ? [.. list] : [];
}
var element = JsonDocument.Parse(parameters.ToJsonString()).RootElement.Clone();
foreach (var handler in handlers)
{
handler(element);
}
}
private sealed class Removal(Action remove) : IDisposable
{
private Action? _remove = remove;
public void Dispose() => Interlocked.Exchange(ref _remove, null)?.Invoke();
}
}
+137
View File
@@ -470,4 +470,141 @@ public sealed class EngineHostTests
Assert.AreEqual(CheckNowStatus.Refused, result.Status);
StringAssert.Contains(result.Message, "tetto giornaliero");
}
[TestMethod]
public async Task WhenAlbertoLetsGoOfTheBrowserThePageGoesBackToRestUnlessAVerificationKeepsIt()
{
var driving = false;
await using var bed = await EngineTestBed.CreateAsync(Morning, userIsDriving: () => driving);
await bed.AddAccountAsync("uno.demo", followed: true);
await bed.AddAccountAsync("due.demo", followed: false, Frequency.High);
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
EngineHost? host = null;
int? restsWhenTaken = null;
// He takes the browser in the middle of a recipe (a story viewer may be open): the session ends and leaves the
// page to him.
runner.Before = r =>
{
if (restsWhenTaken is null && r.Kind != RecipeKind.FollowingSweep)
{
restsWhenTaken = runner.Rests;
driving = true;
host!.NotifyUserDrivingChanged();
}
return Task.CompletedTask;
};
host = bed.Start(runner);
await bed.RunUntilAsync(EngineTestBed.Local(2026, 10, 14, 12, 0));
Assert.IsNotNull(restsWhenTaken, "Alberto took the browser during a session.");
Assert.AreEqual(restsWhenTaken, runner.Rests, "While he drives the page is his.");
// He lets go during a pause: nothing starts, but nothing of what was open stays on the site either (§6.1, §6.3).
await host.PauseAsync();
driving = false;
host.NotifyUserDrivingChanged();
await bed.RunForAsync(TimeSpan.FromSeconds(1));
Assert.AreEqual(restsWhenTaken + 1, runner.Rests, "Back to rest as soon as he lets go.");
// After a verification the page stays as it is until «Riprendi» (§7.6), also when he lets go.
bed.Breaker.Report(new Signal(SignalLevel.Challenge, "challenge-url", "https://sito.prova/challenge", bed.Clock.Now));
await bed.Breaker.FlushAsync();
driving = true;
host.NotifyUserDrivingChanged();
await bed.RunForAsync(TimeSpan.FromMinutes(5));
driving = false;
host.NotifyUserDrivingChanged();
await bed.RunForAsync(TimeSpan.FromMinutes(5));
Assert.AreEqual(restsWhenTaken + 1, runner.Rests, "The verification page is left as it is.");
}
[TestMethod]
public async Task ChangingTheAccountsDuringARecipeDoesNotBringItsNextCheckForward()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
var watched = await bed.AddAccountAsync("uno.demo", followed: false, Frequency.Low, types: ContentTypes.PostPhotos | ContentTypes.PostVideos);
await bed.AddAccountAsync("due.demo", followed: false, Frequency.Low, types: ContentTypes.PostPhotos | ContentTypes.PostVideos);
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
EngineHost? host = null;
DateTimeOffset? checkedAt = null;
// While the profile check of uno.demo runs (its task is «Running»), Alberto saves the settings of an account.
runner.Before = async r =>
{
if (checkedAt is null && r.Kind == RecipeKind.ProfileCheck && r.AccountId == watched.Id)
{
checkedAt = bed.Clock.Now;
await host!.NotifyAccountsChangedAsync();
}
};
host = bed.Start(runner);
await bed.RunUntilAsync(Morning.AddDays(1));
Assert.IsNotNull(checkedAt);
var visits = runner.Runs
.Where(r => r.Request.Kind == RecipeKind.ProfileCheck && r.Request.AccountId == watched.Id && r.Status == RecipeStatus.Completed)
.Select(r => r.At)
.ToList();
// «Bassa», not followed: about every 12 hours, never sooner than 0.6 × 12 h.
for (var i = 1; i < visits.Count; i++)
{
Assert.IsTrue(visits[i] - visits[i - 1] >= TimeSpan.FromHours(7), $"Visit after {visits[i] - visits[i - 1]}: the interval of the frequency holds.");
}
var pending = (await bed.Db.Tasks.ListPendingAsync(1000))
.Where(t => t.Kind == EngineTaskKind.ProfileCheck && t.AccountId == watched.Id)
.ToList();
Assert.HasCount(1, pending, "One planned check, not a second one from the queue sync.");
Assert.IsTrue(pending[0].DueAt >= visits[^1] + TimeSpan.FromHours(7), $"Next check at {pending[0].DueAt:O}, after {visits[^1]:O}.");
}
[TestMethod]
public async Task HighlightCollectionsAreLookedAtOncePerIntervalAndNoLongerOnceGone()
{
await using var bed = await EngineTestBed.CreateAsync(Morning);
var account = await bed.AddAccountAsync("uno.demo", followed: true, Frequency.High);
await bed.Db.Highlights.UpsertAsync(new Highlight { AccountId = account.Id, InstagramId = "17900000001", Title = "Viaggi", DiscoveredAt = Morning });
var food = await bed.Db.Highlights.UpsertAsync(new Highlight { AccountId = account.Id, InstagramId = "17900000002", Title = "Cucina", Position = 1, DiscoveredAt = Morning });
var noStories = await bed.AddAccountAsync("due.demo", followed: true, Frequency.High, types: ContentTypes.PostPhotos);
await bed.Db.Highlights.UpsertAsync(new Highlight { AccountId = noStories.Id, InstagramId = "17900000003", Title = "Altro", DiscoveredAt = Morning });
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
// Like the real recipe: the collection is marked as looked at.
runner.Before = async r =>
{
if (r.Kind == RecipeKind.Highlight && await bed.Db.Highlights.FindAsync(account.Id, r.HighlightId!) is { } highlight)
{
await bed.Db.Highlights.UpsertAsync(highlight with { LastCheckedAt = bed.Clock.Now });
}
};
bed.Start(runner);
await bed.RunUntilAsync(Morning.AddDays(3));
List<RunRecord> Looks(string id) => [.. runner.Runs.Where(r => r.Request.Kind == RecipeKind.Highlight && r.Request.HighlightId == id)];
foreach (var id in new[] { "17900000001", "17900000002" })
{
var looks = Looks(id);
Assert.IsNotEmpty(looks, $"Collection {id} of an account that wants «Storie in evidenza» is looked at.");
Assert.IsTrue(looks.All(l => l.Request.AccountId == account.Id));
for (var i = 1; i < looks.Count; i++)
{
// «Alta»: every 24 hours or so, never sooner than 0.6 × 24 h.
Assert.IsTrue(looks[i].At - looks[i - 1].At >= TimeSpan.FromHours(14), $"Look after {looks[i].At - looks[i - 1].At}.");
}
}
Assert.IsEmpty(Looks("17900000003"), "«Storie in evidenza» off: not looked at.");
var all = runner.Runs.Where(r => r.Request.Kind == RecipeKind.Highlight).ToList();
Assert.AreEqual(all.Count, all.Select(r => r.SessionId).Distinct().Count(), "One collection per account and session.");
// A collection that left the profile is no longer looked at; the other one still is.
await bed.Db.Highlights.MarkRemovedAsync(food.Id, bed.Clock.Now);
var foodLooks = Looks("17900000002").Count;
var travelLooks = Looks("17900000001").Count;
await bed.RunUntilAsync(Morning.AddDays(6));
Assert.HasCount(foodLooks, Looks("17900000002"));
Assert.IsTrue(Looks("17900000001").Count > travelLooks);
}
}
@@ -22,6 +22,12 @@ internal sealed class ScriptedRunner(IGovernor governor, IClock clock) : IRecipe
/// <summary>Called after the counted action was granted (e.g. to report a signal).</summary>
public Action<RecipeRequest>? AfterGrant { get; set; }
/// <summary>
/// Awaited when a recipe starts, while its task is running (e.g. what the real recipe writes, or a command of
/// Alberto arriving meanwhile).
/// </summary>
public Func<RecipeRequest, Task>? Before { get; set; }
/// <summary>Accounts the stories bar flags in every sweep.</summary>
public IReadOnlyList<long> FlaggedStories { get; set; } = [];
@@ -43,6 +49,11 @@ internal sealed class ScriptedRunner(IGovernor governor, IClock clock) : IRecipe
RecipeOutcome outcome;
try
{
if (Before is { } before)
{
await before(request);
}
outcome = Script?.Invoke(request) ?? await DefaultAsync(request, ct);
}
catch (OperationCanceledException)
@@ -81,6 +81,71 @@ public sealed class VirtualClockTests
await Assert.ThrowsAsync<InvalidOperationException>(() => clock.RunUntilAsync(Start.AddHours(1), CancellationToken.None, actor));
}
[TestMethod]
public async Task ATimerCancelledFromThePoolNeverEndsTheRunEarly()
{
// As EngineHost.OnBreakerChanged does: a pool thread cancels the actor's pending timer (here as soon as it is
// registered, so that it often lands between the driver's look at the actors and its decision).
for (var i = 0; i < 20_000; i++)
{
var clock = new VirtualClock(Start);
using var session = new CancellationTokenSource();
using var end = new CancellationTokenSource();
var oneMinuteLater = false;
var stop = 0;
Task? canceller = null;
async Task Actor()
{
canceller = Task.Run(() =>
{
while (clock.PendingTimers == 0 && Volatile.Read(ref stop) == 0)
{
Thread.SpinWait(20);
}
session.Cancel();
});
try
{
await clock.Delay(TimeSpan.FromSeconds(5), session.Token);
}
catch (OperationCanceledException)
{
}
await clock.Delay(TimeSpan.FromMinutes(1), CancellationToken.None);
oneMinuteLater = true;
await clock.Delay(TimeSpan.FromDays(10), end.Token);
}
var actor = Actor();
bool reached;
DateTimeOffset at;
try
{
await clock.RunUntilAsync(Start.AddHours(1), CancellationToken.None, actor);
reached = Volatile.Read(ref oneMinuteLater);
at = clock.Now;
}
finally
{
// Lets the actor end in every case (also when the driver left it behind), so nothing keeps running.
Volatile.Write(ref stop, 1);
await canceller!;
await end.CancelAsync();
for (var spin = 0; !actor.IsCompleted && spin < 1000; spin++)
{
clock.AdvanceTo(clock.Now.AddDays(1));
await Task.WhenAny(actor, Task.Delay(1));
}
}
Assert.IsTrue(reached, $"Run {i}: the driver returned while the actor was running, and skipped its timer.");
Assert.AreEqual(Start.AddHours(1), at);
Assert.IsTrue(actor.IsCanceled, $"Run {i}: the actor ends on its last timer, cancelled here.");
}
}
[TestMethod]
public async Task AutoAdvanceMovesTimeAtOnceAndRoundsToMilliseconds()
{
@@ -129,6 +129,39 @@ public sealed class RemoteViewSocketTests
Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
}
[TestMethod]
public void TheServerPingsThePageAndGivesUpOnOneThatStopsAnswering()
{
// With an interval alone ASP.NET Core sends unsolicited pongs and never notices a page that vanished.
var accept = RemoteViewSocket.AcceptContext();
Assert.AreEqual(RemoteViewSocket.KeepAliveInterval, accept.KeepAliveInterval);
Assert.IsNotNull(accept.KeepAliveTimeout, "a ping must have a deadline");
Assert.IsTrue(accept.KeepAliveTimeout > TimeSpan.Zero && accept.KeepAliveTimeout <= TimeSpan.FromMinutes(1), $"{accept.KeepAliveTimeout}");
Assert.IsFalse(accept.DangerousEnableCompression);
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task AViewWhosePageVanishedEndsWhenItsPingGoesUnanswered()
{
// The same keep-alive as the server, with short times: the page's machine went to sleep (it never answers).
using var listener = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0);
listener.Start();
using var page = new System.Net.Sockets.TcpClient();
await page.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port, TestContext.CancellationToken);
using var accepted = await listener.AcceptTcpClientAsync(TestContext.CancellationToken);
using var socket = WebSocket.CreateFromStream(accepted.GetStream(), new WebSocketCreationOptions
{
IsServer = true,
KeepAliveInterval = TimeSpan.FromMilliseconds(200),
KeepAliveTimeout = TimeSpan.FromMilliseconds(300),
});
var view = new FakeRemoteViewConnection();
var run = RemoteViewSocket.RunAsync(socket, view, CancellationToken.None);
Assert.AreSame(run, await Task.WhenAny(run, Task.Delay(TimeSpan.FromSeconds(10), TestContext.CancellationToken)), "the view ends by itself");
await run;
}
[TestMethod]
public void KeysGetTheVirtualCodesChromiumNeeds()
{
@@ -240,6 +240,62 @@ public sealed partial class ServerEndToEndTests
Assert.IsTrue(Febe.Browser.Hosting.LoopbackPortCheck.IsLoopbackOnly(bed.Options.DebugPort, out _));
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TwoViewsOpenedAtTheSameMomentLeaveOneViewWithItsFramesAndOneLease()
{
var ct = TestContext.CancellationToken;
await using var bed = await ServerTestBed.StartAsync();
var server = bed.Server;
await server.Running.WaitAsync(TimeSpan.FromSeconds(60), ct);
var host = server.RemoteView!;
var gate = server.Browser!.UserDriving;
for (var round = 0; round < 5; round++)
{
// From the rest page: where the browser starts, and where the engine puts it once nobody is at the browser.
await ServerTestBed.WaitUntilAsync(
async () => await Febe.Browser.Cdp.CdpPageExtensions.GetMainFrameUrlAsync(server.Browser.Cdp, ct) == "about:blank",
TimeSpan.FromSeconds(20),
"la pagina di riposo");
// Two tabs restored together, or the phone and the PC at once: the newest wins, the other is ended.
var views = await Task.WhenAll(Task.Run(() => host.OpenAsync(ct), ct), Task.Run(() => host.OpenAsync(ct), ct));
var open = views.Where(v => v.Ended is null).ToList();
Assert.HasCount(1, open, $"Round {round}: one view stays open.");
Assert.AreEqual(RemoteViewEnd.Replaced, views.Single(v => v.Ended is not null).Ended);
Assert.AreEqual(1, gate.Leases, $"Round {round}: only the open view holds the browser.");
// The page of the replaced view closes its socket: the open view still gets its frames.
await views.Single(v => v.Ended is not null).DisposeAsync();
await Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(server.Browser.Cdp, $"{bed.Site.SiteUrl}/?giro={round}", ct);
Assert.IsTrue(await FrameArrivesAsync(open[0], ct), $"Round {round}: frames go on after the other view closed.");
await open[0].DisposeAsync();
Assert.AreEqual(0, gate.Leases, $"Round {round}: no view, no lease.");
}
}
private static async Task<bool> FrameArrivesAsync(IRemoteViewConnection view, CancellationToken ct)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(15));
try
{
await foreach (var output in view.ReadAsync(timeout.Token))
{
if (output is RemoteViewFrame)
{
return true;
}
}
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
}
return false;
}
private static async Task<bool> WaitRunningAsync(Febe.Server.FebeServer server)
{
for (var i = 0; i < 40 && !server.Engine!.Services.Runtime.IsRunning; i++)