Dopo una prova dal vivo andata male, Alberto deve poter mandare un solo file che spieghi perché, senza che nessuno veda dati di altre persone. Attività ha ora il pulsante «Diagnostica», che scarica il rapporto delle sessioni degli ultimi 14 giorni: pagine aperte e forma degli indirizzi, risposte per tipo, stato e dimensione con ciò che i lettori ne hanno fatto, struttura stretta delle forme sconosciute, ricette, segnali, permessi negati, file in coda e scaricati, e il motivo di ogni arresto. Nel rapporto entrano solo valori da elenchi chiusi, numeri, orari e forme: mai nomi, indirizzi completi, codici, cursori, cookie o pezzi di risposte. Le forme degli indirizzi e la regola delle chiavi-dato passano dalla sonda a Core, e la sonda le richiama. Il registratore non lancia mai eccezioni verso la raccolta e tiene i file in Dati/diagnostica per 14 giorni. Prova che il rapporto non contiene valori, con controlli di mutazione; tre giri di revisione avversaria (25 difetti confermati, tutti corretti). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
210 lines
9.4 KiB
C#
210 lines
9.4 KiB
C#
using Febe.Core.Abstractions;
|
|
using Febe.Core.Collection;
|
|
using Febe.Core.Collection.Diagnostics;
|
|
using Febe.Core.Domain;
|
|
using Febe.Core.Engine;
|
|
using Febe.Tests.Engine.Support;
|
|
|
|
namespace Febe.Tests.Engine;
|
|
|
|
/// <summary>Why each session stopped, as the engine tells the diagnostic report (issue #39).</summary>
|
|
[TestClass]
|
|
public sealed class SessionStopCauseTests
|
|
{
|
|
private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0);
|
|
|
|
[TestMethod]
|
|
public async Task SessionsThatRunTheirCourseEndByTimeByWorkOrByBudgets()
|
|
{
|
|
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
|
var diagnostics = Record(bed);
|
|
await bed.AddAccountAsync("uno.demo", followed: false, Frequency.High);
|
|
await bed.AddAccountAsync("due.demo", followed: true);
|
|
bed.Start(new ScriptedRunner(bed.Governor, bed.Clock));
|
|
await bed.RunUntilAsync(Morning.AddDays(1));
|
|
|
|
var sessions = await bed.Db.Sessions.ListAsync(Morning, bed.Clock.Now);
|
|
var traces = diagnostics.Recent.Where(t => t.Session is not null).ToList();
|
|
Assert.IsTrue(traces.Count > 5, $"{traces.Count} traces");
|
|
CollectionAssert.AreEquivalent(
|
|
sessions.Where(s => s.EndedAt is not null).Select(s => (long?)s.Id).ToList(),
|
|
traces.Select(t => t.Session).ToList(),
|
|
"One trace for every finished session.");
|
|
foreach (var trace in traces)
|
|
{
|
|
Assert.AreEqual(SessionOutcome.Completed, trace.Outcome);
|
|
Assert.IsTrue(trace.StopCause is SessionStopCause.PlannedEnd or SessionStopCause.WorkDone or SessionStopCause.BudgetsExhausted, trace.StopCause.ToString());
|
|
Assert.IsNull(trace.StoppedBy);
|
|
Assert.IsFalse(trace.InProgress);
|
|
Assert.IsTrue(trace.End >= trace.Start);
|
|
Assert.IsTrue(trace.Recipes.Count == 0, "The scripted runner bypasses the recipe runner.");
|
|
}
|
|
|
|
Assert.AreEqual(0, diagnostics.Faults);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task AThrottleEndsTheSessionWithTheBreakerOpen()
|
|
{
|
|
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
|
var diagnostics = Record(bed);
|
|
await bed.AddAccountAsync("uno.demo", followed: false, Frequency.High);
|
|
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
|
|
var throttled = false;
|
|
runner.AfterGrant = r =>
|
|
{
|
|
if (!throttled && r.Kind == RecipeKind.ProfileCheck)
|
|
{
|
|
throttled = true;
|
|
bed.Breaker.Report(new Signal(SignalLevel.Throttle, "http-429", null, bed.Clock.Now));
|
|
}
|
|
};
|
|
bed.Start(runner);
|
|
await bed.RunUntilAsync(Morning.AddHours(12));
|
|
|
|
Assert.IsTrue(throttled);
|
|
var trace = diagnostics.Recent.Single(t => t.Outcome == SessionOutcome.Throttled);
|
|
Assert.AreEqual(SessionStopCause.BreakerOpen, trace.StopCause);
|
|
Assert.AreEqual("http-429", trace.Signals.Single().Code, "The signal that opened the breaker, reported straight to it.");
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task ALogoutDuringASessionSaysItsCodeInTheTrace()
|
|
{
|
|
// The connection finds the session cookie gone and tells the breaker directly: the detector never sees it.
|
|
var session = default(long?);
|
|
var trace = await StopHeldSessionTraceAsync(async (bed, _, _) =>
|
|
{
|
|
session = bed.Runtime.CurrentSession?.SessionId;
|
|
bed.Breaker.Report(new Signal(SignalLevel.Disconnect, SignalRules.SessionCookieMissingCode, null, bed.Clock.Now));
|
|
|
|
// The engine closes the session from a task of its own (the breaker's event may come from a capture thread).
|
|
var waited = System.Diagnostics.Stopwatch.StartNew();
|
|
while (bed.Runtime.CurrentSession is not null && waited.Elapsed < TimeSpan.FromSeconds(10))
|
|
{
|
|
await Task.Delay(10);
|
|
}
|
|
});
|
|
Assert.IsNotNull(session);
|
|
Assert.AreEqual(SessionStopCause.BreakerOpen, trace.StopCause);
|
|
var signal = trace.Signals.Single();
|
|
Assert.AreEqual(SignalLevel.Disconnect, signal.Level);
|
|
Assert.AreEqual(SignalRules.SessionCookieMissingCode, signal.Code, "A logout does not look like any other stop.");
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task AMissingTargetStopsTheSessionEarlyAndSaysWhichStatus()
|
|
{
|
|
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
|
var diagnostics = Record(bed);
|
|
await bed.AddAccountAsync("uno.demo", followed: false, Frequency.High);
|
|
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
|
|
var missed = false;
|
|
runner.Script = r =>
|
|
{
|
|
if (!missed && r.Kind == RecipeKind.ProfileCheck)
|
|
{
|
|
missed = true;
|
|
return new RecipeOutcome(RecipeStatus.TargetNotFound, 1, 0);
|
|
}
|
|
|
|
return null;
|
|
};
|
|
bed.Start(runner);
|
|
await bed.RunUntilAsync(Morning.AddHours(12));
|
|
|
|
Assert.IsTrue(missed);
|
|
var trace = diagnostics.Recent.Single(t => t.StoppedBy is not null);
|
|
Assert.AreEqual(SessionStopCause.StoppedEarly, trace.StopCause);
|
|
Assert.AreEqual(RecipeStatus.TargetNotFound, trace.StoppedBy);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task ThePauseAlbertoAtTheBrowserAndTheShutdownEndTheSessionInProgress()
|
|
{
|
|
Assert.AreEqual(SessionStopCause.Paused, await StopHeldSessionAsync((bed, host, _) => host.PauseAsync()));
|
|
Assert.AreEqual(SessionStopCause.UserDriving, await StopHeldSessionAsync((bed, host, drive) =>
|
|
{
|
|
drive();
|
|
host.NotifyUserDrivingChanged();
|
|
return Task.CompletedTask;
|
|
}));
|
|
Assert.AreEqual(SessionStopCause.Shutdown, await StopHeldSessionAsync((bed, _, _) => bed.StopAsync()));
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task AShutdownDuringARealRecipeIsAShutdownToo()
|
|
{
|
|
// The real recipe runner does not let the cancellation out: it answers «Cancelled», and the composer ends as
|
|
// if a recipe had stopped the session. The pause still says «Paused».
|
|
Assert.AreEqual(SessionStopCause.Shutdown, await StopHeldSessionAsync((bed, _, _) => bed.StopAsync(), answersCancelled: true));
|
|
Assert.AreEqual(SessionStopCause.Paused, await StopHeldSessionAsync((bed, host, _) => host.PauseAsync(), answersCancelled: true));
|
|
}
|
|
|
|
/// <summary>Starts a session whose first recipe waits an hour, stops it with <paramref name="stop"/>, returns its cause.</summary>
|
|
private static async Task<SessionStopCause?> StopHeldSessionAsync(Func<EngineTestBed, EngineHost, Action, Task> stop, bool answersCancelled = false) =>
|
|
(await StopHeldSessionTraceAsync(stop, answersCancelled)).StopCause;
|
|
|
|
/// <summary>The same as <see cref="StopHeldSessionAsync"/>, returning the whole trace.</summary>
|
|
private static async Task<SessionTrace> StopHeldSessionTraceAsync(Func<EngineTestBed, EngineHost, Action, Task> stop, bool answersCancelled = false)
|
|
{
|
|
var driving = false;
|
|
await using var bed = await EngineTestBed.CreateAsync(EngineTestBed.Noon, userIsDriving: () => driving);
|
|
var diagnostics = Record(bed);
|
|
await bed.AddAccountAsync("uno.demo", followed: true);
|
|
var runner = new HoldingRunner(new ScriptedRunner(bed.Governor, bed.Clock), bed.Clock, answersCancelled);
|
|
var host = bed.Start(runner);
|
|
await bed.RunForAsync(TimeSpan.FromMinutes(20));
|
|
Assert.IsTrue(runner.Holding, "A session is in progress.");
|
|
var session = bed.Runtime.CurrentSession?.SessionId;
|
|
Assert.IsNotNull(session);
|
|
|
|
await stop(bed, host, () => driving = true);
|
|
await bed.RunForAsync(TimeSpan.FromMinutes(1));
|
|
await bed.StopAsync();
|
|
|
|
var trace = diagnostics.Recent.Single(t => t.Session == session);
|
|
Assert.IsFalse(trace.InProgress);
|
|
Assert.IsTrue(trace.End - trace.Start < TimeSpan.FromMinutes(30), "It ended when it was stopped, not after the hour.");
|
|
return trace;
|
|
}
|
|
|
|
private static CollectionDiagnostics Record(EngineTestBed bed)
|
|
{
|
|
var diagnostics = new CollectionDiagnostics(bed.Clock, () => bed.Runtime.CurrentSession?.SessionId);
|
|
bed.Services.Diagnostics = diagnostics;
|
|
return diagnostics;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The first recipe waits an hour of virtual time (until cancelled); the others run as scripted. With
|
|
/// <paramref name="answersCancelled"/> a cancellation is answered «Cancelled», as <c>RecipeRunner</c> does.
|
|
/// </summary>
|
|
private sealed class HoldingRunner(ScriptedRunner inner, IClock clock, bool answersCancelled = false) : IRecipeRunner
|
|
{
|
|
private int _held;
|
|
|
|
public bool Holding { get; private set; }
|
|
|
|
public async Task<RecipeOutcome> RunAsync(RecipeRequest request, ISessionContext session, CancellationToken ct)
|
|
{
|
|
if (Interlocked.Exchange(ref _held, 1) == 0)
|
|
{
|
|
Holding = true;
|
|
try
|
|
{
|
|
await clock.Delay(TimeSpan.FromHours(1), ct);
|
|
}
|
|
catch (OperationCanceledException) when (answersCancelled)
|
|
{
|
|
return new RecipeOutcome(RecipeStatus.Cancelled, 0, 0, "Ricetta interrotta.");
|
|
}
|
|
}
|
|
|
|
return await inner.RunAsync(request, session, ct);
|
|
}
|
|
|
|
public Task RestAsync(CancellationToken ct) => inner.RestAsync(ct);
|
|
}
|
|
}
|