Rapporto di diagnostica della raccolta (#39)
verifica / controlli (push) Successful in 18s
verifica / prove (push) Successful in 13m5s
verifica / installatore (push) Successful in 4m11s
verifica / immagine (push) Successful in 14m4s

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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-13 14:41:34 +01:00
1 parent bf03cb45a5
commit badd1681a0
55 files changed
+5395 -134

No files matched your search

@@ -0,0 +1,576 @@
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Diagnostics;
using Febe.Core.Collection.Downloads;
using Febe.Core.Collection.Privacy;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.SitoDiProva;
using Febe.Sonda;
using Febe.Tests.Collection.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Collection;
/// <summary>
/// The diagnostic report (issue #39) holds no data value: whatever names, numbers, captions, cursors, signed addresses
/// and cookies reach the recorder, the exported file keeps only closed lists, counts, sizes, times and patterns. The
/// inputs are synthetic, written here with invented values; failure messages never print a value, only its position.
/// </summary>
[TestClass]
public sealed class DiagnosticPrivacyTests
{
/// <summary>Values that stand for personal data: none may reach the report, in any case.</summary>
private static readonly string[] Secrets =
[
"marta", "prova", "bianchi", "jerry", "lucia", "5512345678", "17841401234567", "didascalia", "giornata", "spiaggia",
"QVFIUjBz", "CzX9abQ1kLm", "Zq81abcdEF", "65AABBCC", "sessionid", "segretissimo", "csrftoken", "Tk9QRVNTVA", "esempio",
"ritratto_", "ciaone", "marta_92", "luca", "bruno",
// Names made of words of the closed list (StructureWords): only the map rule and the compound rule hide them.
"the_artist", "street_style", "max_mark",
];
/// <summary>
/// The keys of <see cref="UnknownBody"/> that are fields and not data, written by hand: the structure in the report
/// may hold these (and the fields of the cleaned samples), never any other key. Independent of the word list.
/// </summary>
private static readonly string[] UnknownBodyFields =
["risultati", "voci", "chiave", "valore", "utenti", "seguito", "nome", "a", "b", "menzioni", "post", "fissato", "count", "intestazioni", "versione",
"data", "counts", "node", "tags", "edges", "seen", "items", "pk"];
private const string ProfileBody = """
{
"profilo": {
"numero": "5512345678",
"nome": "marta.prova",
"nome_visibile": "Marta Bianchi",
"riservato": false,
"seguito": true,
"pubblicazioni": 18,
"ritratto": [
{ "indirizzo": "https://cdn.esempio/v/t51/ritratto_marta.jpg?oh=Zq81abcdEF&oe=65AABBCC", "larghezza": 160, "altezza": 160 }
]
},
"raccolte": []
}
""";
private const string UnknownBody = """
{
"risultati": {
"voci": [
{ "chiave": "QVFIUjBzcursore", "valore": "Didascalia: giornata in spiaggia con jerry e lucia, ciaone!" }
]
},
"utenti": {
"marta.prova": { "seguito": true },
"jerry": { "nome": "jerry" },
"17841401234567": { "a": 1 },
"Città di Lucia": { "b": 2 },
"marta_92": { "seguito": true },
"luca": { "seguito": false },
"the_artist": { "seguito": true },
"street_style": { "seguito": false }
},
"max_mark": { "versione": 1 },
"menzioni": "@marta_92 e @luca",
"post": { "CzX9abQ1kLm": { "fissato": true } },
"bruno": [ { "count": 1 } ],
"intestazioni": "sessionid=segretissimo123; csrftoken=Tk9QRVNTVA",
"versione": 3
}
""";
/// <summary>
/// Maps keyed by names made of words of the closed list, in the shapes a same-shape rule misses: counts, empty values
/// and lists of codes, entries with different optional fields, a list of maps with one entry each.
/// </summary>
private const string UnknownMapsBody = """
{
"data": {
"counts": { "the_artist": 3, "street_style": 5 },
"node": {
"tags": { "the_artist": [], "street_style": [ "c1" ] },
"edges": {
"seen": { "the_artist": { "pk": "1", "seen": 2 }, "street_style": { "pk": "2" } }
},
"items": [ { "the_artist": { "pk": "1" } }, { "street_style": { "pk": "2" } } ]
}
}
}
""";
[TestMethod]
public void TheReportHoldsNoNameNumberCaptionCursorAddressOrCookie()
{
var clock = new ManualClock(new DateTimeOffset(2026, 11, 13, 8, 0, 0, TimeSpan.Zero), TestZones.Rome);
long? current = 41;
var diagnostics = new CollectionDiagnostics(clock, () => current) { SiteMap = SiteMap.LoadTestSite() };
var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadTestSite()), clock) { Diagnostics = diagnostics };
diagnostics.SessionStarted(41, clock.Now, 0.93);
// The page: navigations, responses with sizes, a dropped body, and the bodies through the readers.
diagnostics.OnNavigation(new NavigationDescriptor(HostKind.Site, Site("/profilo/marta.prova/?dopo=QVFIUjBz"), "sito.esempio", "/profilo/marta.prova/", clock.Now));
diagnostics.OnNavigation(new NavigationDescriptor(HostKind.Site, Site("/post/CzX9abQ1kLm/"), "sito.esempio", "/post/CzX9abQ1kLm/", clock.Now, SameDocument: true));
diagnostics.OnNavigation(new NavigationDescriptor(HostKind.Other, "https://altro.esempio/marta.prova", "altro.esempio", "/marta.prova", clock.Now));
var profile = Response("r1", HostKind.Site, "/dati/profilo/marta.prova/", "?dopo=QVFIUjBz");
var unknown = Response("r2", HostKind.Site, "/dati/5512345678/lucia.bianchi/", "?cursore=QVFIUjBz");
var picture = Response("r3", HostKind.Cdn, "/v/t51/ritratto_marta.jpg", "?oh=Zq81abcdEF&oe=65AABBCC", "image/jpeg", "Image");
var other = Response("r4", HostKind.Other, "/collect/marta.prova.gif", "?u=jerry", "image/gif", "Ping");
var dropped = Response("r5", HostKind.Site, "/api/v1/users/5512345678/info/", "", "application/json; charset=utf-8", "XHR");
var page = Response("r6", HostKind.Site, "/post/CzX9abQ1kLm/", "", "text/html", "Document", mainFrame: true);
var odd = Response("r7", HostKind.Site, "/marta.prova/", "", "text/marta.prova", "marta");
foreach (var response in new[] { profile, unknown, picture, other, dropped, page, odd })
{
diagnostics.OnResponse(response);
diagnostics.OnLoadingFinished(response.RequestId, 2048);
}
diagnostics.OnBodyDropped("r5", BodyDropReason.Timeout);
using (var body = JsonDocument.Parse(ProfileBody))
{
Assert.AreEqual(ReadShape.Recognized, capture.Accept(profile, body.RootElement.Clone())?.Result.Shape);
}
using (var body = JsonDocument.Parse(UnknownBody))
{
Assert.AreEqual(ReadShape.Unrecognized, capture.Accept(unknown, body.RootElement.Clone())?.Result.Shape);
Assert.IsNull(capture.Accept(other, body.RootElement.Clone()), "A body of another host is not read.");
}
var maps = Response("r9", HostKind.Site, "/dati/mappe/", "");
diagnostics.OnResponse(maps);
using (var body = JsonDocument.Parse(UnknownMapsBody))
{
Assert.AreEqual(ReadShape.Unrecognized, capture.Accept(maps, body.RootElement.Clone())?.Result.Shape);
}
// The recipes and the engine: names where codes are expected become «altro».
diagnostics.PageOpened(41, SitePages.Profile, ok: true);
diagnostics.PageOpened(41, "marta.prova", ok: false);
diagnostics.TargetClicked(41, SiteTargets.ProfileStoryRing, TargetCheckStatus.Clicked);
diagnostics.TargetClicked(41, "jerry", TargetCheckStatus.NotFound);
diagnostics.StepJudged(41, CollectionDiagnostics.VerdictUnknown);
diagnostics.StepJudged(41, "Didascalia di lucia");
diagnostics.RecipeEnded(41, RecipeKind.ProfileCheck, RecipeStatus.StoppedBySignal, "http-429", 1, 0);
diagnostics.RecipeEnded(41, RecipeKind.ProfileCheck, RecipeStatus.Failed, "marta.prova@esempio", 0, 0, "Errore di marta.prova");
diagnostics.RecipeEnded(41, RecipeKind.ProfileCheck, RecipeStatus.Failed, null, 0, 0, nameof(TimeoutException));
diagnostics.SignalRaised(new Signal(SignalLevel.Throttle, "http-429", Site("/profilo/marta.prova/?dopo=QVFIUjBz"), clock.Now));
diagnostics.SignalRaised(new Signal(SignalLevel.Challenge, "jerry.ciaone", "https://sito.esempio/challenge/?next=/jerry/", clock.Now));
diagnostics.PermitDenied(null, ActionKind.ProfileOpen, DenialReason.HourlyBudgetReached);
diagnostics.FilesQueued(41, EntryKind.Post, 3, nameof(SaveOutcome.Created), skipped: 1);
diagnostics.FilesQueued(41, EntryKind.Post, 1, "segretissimo");
diagnostics.DownloadSettled(new DownloadProgress(17841401234567, 5512345678, 5512345678, EntryKind.Post, DownloadStep.Stored, 2048));
clock.Now = clock.Now.AddMinutes(7);
current = null;
diagnostics.SessionEnded(41, clock.Now, SessionOutcome.Throttled, SessionStopCause.BreakerOpen, RecipeStatus.StoppedBySignal);
// Outside sessions: Alberto at the browser.
diagnostics.OnNavigation(new NavigationDescriptor(HostKind.Site, Site("/profilo/jerry/"), "sito.esempio", "/profilo/jerry/", clock.Now));
diagnostics.OnResponse(Response("r8", HostKind.Site, "/storie/jerry/17841401234567/", ""));
diagnostics.SignalRaised(new Signal(SignalLevel.Disconnect, SignalRules.SessionCookieMissingCode, null, clock.Now));
diagnostics.DownloadSettled(new DownloadProgress(17841401234567, 5512345678, 5512345678, EntryKind.Story, DownloadStep.Failed));
diagnostics.DownloadSettled(new DownloadProgress(1, 2, 3, EntryKind.Story, DownloadStep.Retried) { Cause = DownloadCauses.Of(404) });
diagnostics.DownloadSettled(new DownloadProgress(1, 2, 3, EntryKind.Story, DownloadStep.Failed) { Cause = "https://cdn.esempio/marta.prova.jpg" });
var text = Export(diagnostics.Collect(), clock);
Assert.AreEqual(0, diagnostics.Faults);
using var report = JsonDocument.Parse(text);
Assert.AreEqual(1, report.RootElement.GetProperty("sessioni").GetArrayLength());
Assert.AreEqual(1, report.RootElement.GetProperty("fuoriSessione").GetArrayLength());
StringAssert.Contains(text, "\"structure\"", "The unknown shape is there, by its keys.");
foreach (var hiddenMap in new[] { "{data:{counts:{#},node:{tags:{#:[]},edges:{seen:{#:{pk,seen}}},items:[{#:{pk}}]}}}" })
{
StringAssert.Contains(text, hiddenMap, "The maps are there, without their names.");
}
var tokens = new SensitiveTokens(SanitizerAllowlist.Default);
foreach (var input in new[] { ProfileBody, UnknownBody, UnknownMapsBody })
{
using var document = JsonDocument.Parse(input);
tokens.Add(document.RootElement);
}
ReportLeaks.AssertClean(text, Secrets, tokens.Effective, ReportLeaks.FieldKeys(UnknownBodyFields));
}
[TestMethod]
public void TheLogOnDiskHoldsNoValueEither()
{
using var folder = new TempFolder("diagnostica");
var clock = new ManualClock(new DateTimeOffset(2026, 11, 13, 8, 0, 0, TimeSpan.Zero), TestZones.Rome);
var log = new DiagnosticLog(folder.Combine("diagnostica"), clock);
var diagnostics = new CollectionDiagnostics(clock, () => 7, log) { SiteMap = SiteMap.LoadTestSite() };
diagnostics.SessionStarted(7, clock.Now, 1);
diagnostics.OnResponse(Response("l1", HostKind.Site, "/profilo/marta.prova/", "?dopo=QVFIUjBz"));
diagnostics.ReadObserved(Response("l2", HostKind.Site, "/dati/marta.prova/", ""), new ReadResult { Shape = ReadShape.Unrecognized }, "{utenti:{#:{seguito}}}");
diagnostics.SignalRaised(new Signal(SignalLevel.Throttle, "marta.prova", Site("/marta.prova/"), clock.Now));
diagnostics.SessionEnded(7, clock.Now, SessionOutcome.Completed, SessionStopCause.WorkDone);
diagnostics.Dispose();
var written = string.Concat(Directory.EnumerateFiles(log.Folder).Select(File.ReadAllText));
Assert.IsGreaterThan(0, written.Length);
for (var i = 0; i < Secrets.Length; i++)
{
Assert.IsFalse(written.Contains(Secrets[i], StringComparison.OrdinalIgnoreCase), $"Secret #{i} is in the log.");
}
Assert.IsFalse(written.Contains("://", StringComparison.Ordinal), "An address is in the log.");
}
private static string Export(IReadOnlyList<SessionTrace> traces, IClock clock)
{
using var stream = new MemoryStream();
DiagnosticReport.Write(stream, traces, new DiagnosticReportHeader("0.0.0-prove", "docker", clock.Now, TestZones.Rome));
return Encoding.UTF8.GetString(stream.ToArray());
}
private static string Site(string pathAndQuery) => "https://sito.esempio" + pathAndQuery;
private static ResponseDescriptor Response(string id, HostKind host, string path, string query, string mime = "application/json", string? resourceType = "Fetch", bool mainFrame = false)
{
var origin = host switch
{
HostKind.Site => "sito.esempio",
HostKind.Cdn => "cdn.esempio",
_ => "altro.esempio",
};
return new ResponseDescriptor(id, host, "https://" + origin + path + query, origin, path, 200, mime, resourceType, mainFrame, DateTimeOffset.UnixEpoch);
}
}
/// <summary>
/// The diagnostic report end to end on the local test site, with a real Chromium: a recipe, the export, and none of the
/// world's names, captions, codes or identifiers in the file. Never Instagram.
/// </summary>
[TestClass]
[TestCategory(SyntheticSite.Category)]
[DoNotParallelize]
public sealed class DiagnosticPrivacyIntegrationTests
{
private static SharedChromium? s_chromium;
private static string? s_unavailable;
private static SharedChromium Chromium => s_chromium ?? throw new InvalidOperationException("Browser non avviato.");
[ClassInitialize]
public static async Task StartAsync(TestContext context)
{
s_unavailable = SharedChromium.UnavailableReason();
if (s_unavailable is null)
{
s_chromium = await SharedChromium.StartAsync();
}
}
[ClassCleanup]
public static async Task StopAsync()
{
if (s_chromium is not null)
{
await s_chromium.DisposeAsync();
s_chromium = null;
}
}
[TestInitialize]
public void RequireBrowser()
{
if (s_unavailable is not null)
{
Assert.Inconclusive(s_unavailable);
}
}
[TestMethod]
[Timeout(90_000, CooperativeCancellation = true)]
public async Task ARecipeOnTheTestSiteLeavesNoValueOfTheWorldInTheReport()
{
await using var h = await CollectionHarness.CreateAsync(Chromium, diagnostics: true);
var diagnostics = h.Diagnostics!;
diagnostics.SessionStarted(h.Session.SessionId, h.Clock.Now, 1);
var marta = await h.AddAccountAsync("marta.prova");
var outcome = await h.RunAsync(RecipeKind.ProfileCheck, marta.Id);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status);
await h.RunAsync(RecipeKind.FollowingSweep);
diagnostics.SessionEnded(h.Session.SessionId, h.Clock.Now, SessionOutcome.Completed, SessionStopCause.WorkDone);
using var stream = new MemoryStream();
DiagnosticReport.Write(stream, diagnostics.Collect(), new DiagnosticReportHeader("0.0.0-prove", "docker", h.Clock.Now, TestZones.Rome));
var text = Encoding.UTF8.GetString(stream.ToArray());
using var report = JsonDocument.Parse(text);
var session = report.RootElement.GetProperty("sessioni").EnumerateArray().Single();
Assert.IsGreaterThan(0, session.GetProperty("responses").GetArrayLength(), "The page was seen.");
Assert.IsTrue(session.GetProperty("recipes").EnumerateArray().Any(r => r.GetProperty("kind").GetString() == nameof(RecipeKind.ProfileCheck)));
// Every name, display name, caption, post code, highlight title and identifier of the synthetic world.
var world = new List<string>();
lock (h.Site.World.Gate)
{
foreach (var account in h.Site.World.Accounts)
{
world.Add(account.Username);
world.Add(account.DisplayName);
world.Add(account.Id);
world.AddRange(account.Posts.SelectMany(p => new[] { p.Code, p.Caption, p.Id }));
world.AddRange(account.Stories.Select(s => s.Id));
world.AddRange(account.Highlights.SelectMany(x => new[] { x.Title, x.Id }));
}
}
var vocabulary = ReportLeaks.Vocabulary(SiteMap.LoadTestSite());
var worldTokens = world.SelectMany(SensitiveTokens.Tokenize).Where(t => !vocabulary.Contains(t)).ToHashSet(StringComparer.Ordinal);
Assert.IsGreaterThan(20, worldTokens.Count);
ReportLeaks.AssertClean(text, [], worldTokens, ReportLeaks.FieldKeys([]));
Assert.AreEqual(0, diagnostics.Faults);
}
}
/// <summary>The checks the privacy tests share; their messages name positions and kinds, never values.</summary>
internal static partial class ReportLeaks
{
private static readonly string[] CdpResourceTypes =
[
"Document", "Stylesheet", "Image", "Media", "Font", "Script", "TextTrack", "XHR", "Fetch", "Prefetch", "EventSource",
"WebSocket", "Manifest", "SignedExchange", "Ping", "CSPViolationReport", "Preflight", "FedCM", "Other",
];
/// <summary>
/// No explicit secret and no sensitive token anywhere; no address, mail or query; every pattern made of words of the
/// site and placeholders; every key of a key structure one of <paramref name="fieldKeys"/> (checked against real
/// fields, not against the word list under test); every other text value from a closed list or a time.
/// </summary>
public static void AssertClean(string text, IReadOnlyList<string> secrets, IReadOnlySet<string> sensitive, IReadOnlySet<string> fieldKeys)
{
for (var i = 0; i < secrets.Count; i++)
{
Assert.IsFalse(text.Contains(secrets[i], StringComparison.OrdinalIgnoreCase), $"Secret #{i} is in the report.");
}
var leaked = SensitiveTokens.Tokenize(text).Distinct().Count(sensitive.Contains);
Assert.AreEqual(0, leaked, "Sensitive tokens of the inputs are in the report (count only).");
Assert.IsFalse(text.Contains("://", StringComparison.Ordinal), "An address is in the report.");
Assert.IsFalse(text.Contains('@', StringComparison.Ordinal), "A mail or a handle is in the report.");
Assert.IsFalse(text.Contains('?', StringComparison.Ordinal), "A query is in the report.");
using var report = JsonDocument.Parse(text);
var literals = Literals(SiteMap.LoadTestSite()).Concat(Literals(SiteMap.LoadInstagram())).ToHashSet(StringComparer.Ordinal);
var allowed = ClosedValues();
var position = 0;
Walk(report.RootElement, null, (name, value) =>
{
position++;
switch (name)
{
case "pattern":
Assert.IsTrue(IsPattern(value, literals), $"Pattern #{position} has a segment that is not a word of the site.");
break;
case "structure":
Assert.IsTrue(value == "(nessuna struttura)" || StructureShape().IsMatch(value), $"Structure #{position} has an odd character.");
Assert.IsTrue(
value == "(nessuna struttura)" || StructureKeys().Split(value).Where(k => k.Length > 0).All(k => k == "#" || fieldKeys.Contains(k)),
$"Structure #{position} has a key that is not a field of the samples or of the body.");
Assert.IsTrue(
value == "(nessuna struttura)" || StructureKeys().Split(value).Where(k => k.Length > 0).All(k => k == "#" || StructureWords.IsStructural(k)),
$"Structure #{position} has a key that is not made of words of the closed list.");
break;
case "error":
Assert.IsTrue(value == CollectionDiagnostics.Other || TypeName().IsMatch(value), $"Error #{position} is not a type name.");
break;
case "cause":
Assert.IsTrue(
value is DownloadCauses.Network or DownloadCauses.Connection or DownloadCauses.Write or DownloadCauses.BadAddress or DownloadCauses.HostNotAllowed or DownloadCauses.RefusedAfterRenewal
|| value == CollectionDiagnostics.Other || HttpCause().IsMatch(value),
$"Cause #{position} is not from the closed list.");
break;
case "start" or "end" or "at" or "creato":
Assert.IsTrue(DateTimeOffset.TryParse(value, System.Globalization.CultureInfo.InvariantCulture, out _), $"Time #{position} is not a time.");
break;
case "versione" or "edizione" or "fuso" or "rapporto":
break;
default:
Assert.IsTrue(allowed.Contains(value) || CollectionDiagnostics.MimeOf(value) == value, $"Value #{position} ({name}) is not from a closed list.");
break;
}
});
}
/// <summary>
/// The keys that are fields: every key of the cleaned samples of <c>tests/campioni</c> (their data keys were already
/// replaced by the sanitizer), every whole key of the shipped reader vocabularies, and <paramref name="extra"/>.
/// </summary>
public static HashSet<string> FieldKeys(IEnumerable<string> extra)
{
var keys = new HashSet<string>(extra, StringComparer.Ordinal);
foreach (var file in Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni"), "*.json", SearchOption.AllDirectories))
{
using var document = JsonDocument.Parse(File.ReadAllText(file));
AddKeys(document.RootElement, keys, vocabulary: false);
}
foreach (var name in new[] { "lettori.instagram.json", "lettori.prova.json" })
{
using var document = JsonDocument.Parse(SiteMap.ReadEmbeddedText(name));
AddKeys(document.RootElement, keys, vocabulary: true);
}
return keys;
}
/// <summary>Words the report is made of by itself (keys, enums, pages, targets, the site's own words).</summary>
public static HashSet<string> Vocabulary(SiteMap map)
{
var words = new HashSet<string>(StringComparer.Ordinal);
foreach (var value in ClosedValues().Concat(Literals(map)).Concat(PropertyNames()).Append(DiagnosticReport.Title).Append(TestZones.Rome.Id))
{
words.UnionWith(SensitiveTokens.Tokenize(value));
}
return words;
}
private static HashSet<string> ClosedValues()
{
var values = new HashSet<string>(StringComparer.Ordinal)
{
CollectionDiagnostics.Other, CollectionDiagnostics.VerdictRecognized, CollectionDiagnostics.VerdictEmpty,
CollectionDiagnostics.VerdictUnknown, CollectionDiagnostics.CompletedOutcome, "http-429", SignalRules.SessionCookieMissingCode,
"0", "1xx", "2xx", "3xx", "4xx", "5xx", string.Empty,
};
values.UnionWith(SitePages.All);
values.UnionWith(SiteTargets.All);
// The signal codes of the rule files shipped with Febe (segnali.json, segnali.prova.json): a closed list too.
foreach (var rules in new[] { SignalRules.LoadDefault(), SignalRules.LoadTestSite() })
{
values.UnionWith(rules.Rules.Select(r => r.Code));
if (rules.EmptyPages is { } empty)
{
values.Add(empty.Code);
}
}
values.UnionWith(CdpResourceTypes);
foreach (var type in new[]
{
typeof(SessionOutcome), typeof(SessionStopCause), typeof(RecipeStatus), typeof(RecipeKind), typeof(SignalLevel), typeof(ActionKind),
typeof(DenialReason), typeof(EntryKind), typeof(DownloadStep), typeof(BodyDropReason), typeof(HostKind), typeof(TargetCheckStatus),
typeof(SaveOutcome),
})
{
values.UnionWith(Enum.GetNames(type));
}
return values;
}
private static IEnumerable<string> PropertyNames() =>
[
"rapporto", "versione", "edizione", "creato", "fuso", "giorni", "sessioni", "fuoriSessione", "session", "start", "end", "outcome",
"stopCause", "stoppedBy", "mood", "inProgress", "pages", "navigations", "responses", "unknownShapes", "steps", "targets", "recipes",
"signals", "denials", "filesQueued", "downloads", "downloadedBytes", "overflow", "page", "pattern", "hostKind", "sameDocument",
"count", "resourceType", "mime", "status", "bytes", "maxBytes", "recognized", "empty", "unrelated", "unrecognized", "notSite",
"notRead", "contents", "profiles", "dropped", "reason", "structure", "verdict", "target", "kind", "signal", "actions",
"newEntries", "level", "code", "action", "saves", "files", "skipped", "step", "requests", "ok", "cdn", "error", "cause", "late",
"righeRovinate", "erroriRegistratore", "fileIlleggibili", "sessioniSenzaFine",
];
private static IEnumerable<string> Literals(SiteMap map) =>
SitePages.All
.Select(map.PatternOf)
.OfType<string>()
.SelectMany(p => p.Split('/', StringSplitOptions.RemoveEmptyEntries))
.Where(s => !s.StartsWith('{'));
private static bool IsPattern(string pattern, HashSet<string> literals)
{
if (!pattern.StartsWith('/'))
{
return OtherHostPattern().IsMatch(pattern);
}
return pattern.Split('/', StringSplitOptions.RemoveEmptyEntries).All(segment =>
segment is PathPatterns.Number or PathPatterns.Text
|| PathPatterns.IsKnownSegment(segment)
|| literals.Contains(segment)
|| Placeholder().IsMatch(segment));
}
/// <summary>The keys of a sample, or the dotted key paths written in a vocabulary, split into whole keys.</summary>
private static void AddKeys(JsonElement element, HashSet<string> keys, bool vocabulary)
{
switch (element.ValueKind)
{
case JsonValueKind.Object:
foreach (var property in element.EnumerateObject())
{
if (!vocabulary)
{
keys.Add(property.Name);
}
AddKeys(property.Value, keys, vocabulary);
}
break;
case JsonValueKind.Array:
foreach (var item in element.EnumerateArray())
{
AddKeys(item, keys, vocabulary);
}
break;
case JsonValueKind.String when vocabulary:
keys.UnionWith(element.GetString()!.Split('.', StringSplitOptions.RemoveEmptyEntries).Where(k => !k.Contains(' ', StringComparison.Ordinal)));
break;
}
}
private static void Walk(JsonElement element, string? name, Action<string, string> visit)
{
switch (element.ValueKind)
{
case JsonValueKind.Object:
foreach (var property in element.EnumerateObject())
{
Walk(property.Value, property.Name, visit);
}
break;
case JsonValueKind.Array:
foreach (var item in element.EnumerateArray())
{
Walk(item, name, visit);
}
break;
case JsonValueKind.String:
visit(name ?? string.Empty, element.GetString() ?? string.Empty);
break;
}
}
[GeneratedRegex(@"^(cdn|altro)( \*\.[a-z0-9]+)?$", RegexOptions.CultureInvariant)]
private static partial Regex OtherHostPattern();
[GeneratedRegex(@"^\{[a-z]+\}$", RegexOptions.CultureInvariant)]
private static partial Regex Placeholder();
[GeneratedRegex(@"^[\p{L}\p{N}_\-#{}:,\[\]…]*$", RegexOptions.CultureInvariant)]
private static partial Regex StructureShape();
[GeneratedRegex(@"[{}:,\[\]…]", RegexOptions.CultureInvariant)]
private static partial Regex StructureKeys();
[GeneratedRegex(@"^[A-Z][A-Za-z0-9_]*$", RegexOptions.CultureInvariant)]
private static partial Regex TypeName();
[GeneratedRegex(@"^http-[1-5][0-9]{2}$", RegexOptions.CultureInvariant)]
private static partial Regex HttpCause();
}
@@ -0,0 +1,846 @@
using System.Text;
using System.Text.Json;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Diagnostics;
using Febe.Core.Collection.Downloads;
using Febe.Core.Collection.Privacy;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Sonda;
using Febe.Tests.Support;
namespace Febe.Tests.Collection;
/// <summary>
/// The pieces of the diagnostic report (issue #39): path patterns, page names of the site map, the strict key structure,
/// the recorder with its caps and its buckets, the log of two weeks and the exported file. The proof that the report holds
/// no data value is <see cref="DiagnosticPrivacyTests"/>.
/// </summary>
[TestClass]
public sealed class DiagnosticsTests
{
private static readonly DateTimeOffset Start = new(2026, 11, 13, 8, 0, 0, TimeSpan.Zero);
// ---- Path patterns (moved from the probe into Core) ----
[TestMethod]
[DataRow("/mario.rossi/", "/{testo}/")]
[DataRow("/api/v1/feed/user/5512345678/", "/api/v1/feed/user/{numero}/")]
[DataRow("/p/AbC12x/", "/p/{testo}/")]
[DataRow("/stories/highlights/17912345678901234/", "/stories/highlights/{numero}/")]
[DataRow("/graphql/query", "/graphql/query")]
[DataRow("/profilo/marta.prova/?dopo=QVFI#x", "/{testo}/{testo}/")]
[DataRow("", "")]
public void APathPatternKeepsOnlyTheWordsOfTheSite(string path, string expected)
{
Assert.AreEqual(expected, PathPatterns.Of(path));
Assert.AreEqual(PathPatterns.Of(path.Split('?')[0]), RequestShapes.PathPattern(path.Split('?')[0]), "The probe uses the same code.");
}
[TestMethod]
[DataRow("/v/t51.2885-15/foto_n.jpg", "jpg")]
[DataRow("/o1/v/t16/video.MP4", "mp4")]
[DataRow("/profilo/marta.prova", null)]
[DataRow("/senza-estensione/", null)]
[DataRow("/file.", null)]
[DataRow(null, null)]
public void OnlyKnownFileExtensionsAreKept(string? path, string? expected) =>
Assert.AreEqual(expected, PathPatterns.ExtensionOf(path));
// ---- Page names of the site map ----
[TestMethod]
public void AnAddressIsNamedByThePageWithMoreWordsOfItsOwnFirst()
{
var instagram = SiteMap.LoadInstagram();
Assert.AreEqual(SitePages.HighlightViewer, instagram.Classify("/stories/highlights/17912345678901234/"), "Not the stories of «highlights».");
Assert.AreEqual(SitePages.StoryViewer, instagram.Classify("/stories/marta.prova/3456789012345678901/"));
Assert.AreEqual(SitePages.Post, instagram.Classify("/p/CzX9abQ1kLm/"));
Assert.AreEqual(SitePages.Profile, instagram.Classify("/marta.prova/"), "The profile comes last.");
Assert.AreEqual(SitePages.Home, instagram.Classify("/"));
Assert.IsNull(instagram.Classify("/api/v1/users/web_profile_info/"));
Assert.IsNull(instagram.Classify("/graphql/query"));
Assert.IsNull(instagram.Classify(null));
Assert.AreEqual("/{username}/", instagram.PatternOf(SitePages.Profile));
Assert.AreEqual("/stories/highlights/{highlight}/", instagram.PatternOf(SitePages.HighlightViewer));
Assert.IsNull(instagram.PatternOf(SitePages.Following), "Not set on Instagram yet.");
var test = SiteMap.LoadTestSite();
Assert.AreEqual(SitePages.Following, test.Classify("/profilo/marta.prova/seguiti/"));
Assert.AreEqual(SitePages.Profile, test.Classify("/profilo/marta.prova/"), "The shape without a query before the same shape with one.");
Assert.AreEqual(SitePages.ReelsFrom, test.Classify("/profilo/marta.prova/reel/"));
Assert.AreEqual(SitePages.StoryViewer, test.Classify("/storie/marta.prova/12345/"));
Assert.AreEqual("/profilo/{username}/", test.PatternOf(SitePages.ProfileFrom), "Never the query of the shape.");
}
[TestMethod]
[DataRow("/challenge/")]
[DataRow("/explore/")]
[DataRow("/reels/")]
[DataRow("/direct/")]
[DataRow("/accounts/")]
[DataRow("/p/")]
[DataRow("/stories/")]
public void AFixedWordOfTheSiteIsNotAProfile(string path)
{
var instagram = SiteMap.LoadInstagram();
Assert.IsNull(instagram.Classify(path), "A placeholder never takes a word of the site.");
var diagnostics = new CollectionDiagnostics(new ManualClock(Start)) { SiteMap = instagram };
diagnostics.OnNavigation(new NavigationDescriptor(HostKind.Site, "https://indirizzo.non.usato" + path + "?next=/marta.prova/", "indirizzo.non.usato", path, Start));
var navigation = diagnostics.Snapshot(Start).Single().Navigations.Single();
Assert.IsNull(navigation.Page);
Assert.AreEqual(path, navigation.Pattern, "The word itself, not «/{testo}/» and not «/{username}/».");
Assert.AreEqual(SitePages.Profile, instagram.Classify("/marta_92/"), "A real profile is still one.");
Assert.IsNull(SiteMap.LoadTestSite().Classify("/profilo/seguiti/"), "Nor a word of the map itself.");
}
[TestMethod]
public void AShapeWrittenInTheDataFolderIsReducedLikeAnyPath()
{
// Alberto fills «following» with his own address instead of «/{username}/following/».
var map = SiteMap.Parse("""
{
"site": "instagram",
"pages": {
"profile": "/{username}/",
"following": "/alberto.rossi/following/",
"followingFrom": "/alberto.rossi/following/{cursor}/{nome}/1234/",
"post": "/p/{code}/"
}
}
""", "bersagli.instagram.json");
Assert.AreEqual("/{testo}/following/", map.PatternOf(SitePages.Following));
Assert.AreEqual("/{testo}/following/{cursor}/{testo}/{numero}/", map.PatternOf(SitePages.FollowingFrom), "Only the placeholders of the shipped maps.");
Assert.AreEqual("/p/{code}/", map.PatternOf(SitePages.Post));
var clock = new ManualClock(Start);
var diagnostics = new CollectionDiagnostics(clock, () => 1) { SiteMap = map };
diagnostics.SessionStarted(1, clock.Now, 1);
diagnostics.PageOpened(1, SitePages.Following, ok: true);
diagnostics.OnNavigation(new NavigationDescriptor(HostKind.Site, "https://indirizzo.non.usato/alberto.rossi/following/", "indirizzo.non.usato", "/alberto.rossi/following/", clock.Now));
diagnostics.OnResponse(Response("f1", HostKind.Site, "/alberto.rossi/following/", mime: "text/html", resourceType: "Document", mainFrame: true));
var trace = diagnostics.Snapshot(clock.Now).Single();
Assert.AreEqual("/{testo}/following/", trace.Pages.Single().Pattern);
Assert.AreEqual((SitePages.Following, "/{testo}/following/"), (trace.Navigations.Single().Page, trace.Navigations.Single().Pattern));
Assert.AreEqual("/{testo}/following/", trace.Responses.Single().Pattern);
}
// ---- Strict key structure ----
[TestMethod]
public void TheStrictKeyStructureHidesNamesUsedAsKeys()
{
using var body = JsonDocument.Parse("""
{
"utenti": {
"marta.prova": { "seguito": true },
"jerry": { "nome": "Jerry" },
"luca": { "x": 1 }
},
"17841401234567": { "a": 1 },
"Città": { "b": 2 },
"stato": "ok"
}
""");
var strict = KeyStructure.DescribeStrict(body.RootElement);
Assert.AreEqual("{stato,#:{#:{seguito}}}", strict, "Nor «utenti», «luca» and «jerry»: not words of the closed list.");
Assert.AreEqual("{utenti:{marta.prova:{seguito},jerry:{nome},luca:{x}},Città:{b},stato,#:{a}}", KeyStructure.Describe(body.RootElement), "The event of «formato non riconosciuto» is unchanged.");
Assert.IsTrue(KeyStructure.IsDataKey("marta.prova"));
Assert.IsTrue(KeyStructure.IsDataKey("a@b"));
Assert.IsTrue(KeyStructure.IsDataKey("due parole"));
Assert.IsTrue(KeyStructure.IsDataKey("17841401234567"));
Assert.IsFalse(KeyStructure.IsDataKey("image_versions2"));
Assert.IsFalse(KeyStructure.IsDataKey("ultima-storia"));
Assert.AreEqual(KeyStructure.IsDataKey("lucia.rossi"), SensitiveTokens.IsDataKey("lucia.rossi"), "The probe uses the same rule.");
}
[TestMethod]
public void AKeyThatIsNotMadeOfWordsOfTheClosedListIsHiddenEvenWhenTheBodyDoesNotRepeatIt()
{
// A map keyed by user and by post, with no name repeated as a value (only «@marta_92» inside a text).
using var body = JsonDocument.Parse("""
{
"data": {
"users": { "marta_92": { "is_private": false, "follower_count": 3 }, "jerry": { "is_private": true } },
"media": { "CzX9abQ1kLm": { "taken_at": 1, "image_versions2": { "width": 1 } } },
"page_info": { "has_next_page": true, "end_cursor": "QVFIUjBz", "next_max_id": "x" },
"max": { "a": 1 },
"__typename": "XDTUserDict",
"text": "con @marta_92"
}
}
""");
var strict = KeyStructure.DescribeStrict(body.RootElement);
Assert.AreEqual(
"{data:{users:{#:{is_private,follower_count}},media:{#:{taken_at,image_versions2:{width}}},page_info:{has_next_page,end_cursor,#},__typename,text,#:{#}}}",
strict);
foreach (var name in new[] { "marta_92", "jerry", "CzX9abQ1kLm" })
{
Assert.IsFalse(StructureWords.IsStructural(name), "A name or a post code is not structure.");
}
Assert.IsFalse(StructureWords.IsStructural("max"), "A word that is also a first name passes only inside a compound key.");
Assert.IsTrue(StructureWords.IsStructural("next_max_id"));
Assert.IsTrue(StructureWords.IsStructural("pubblicazioni"), "The words of the test site's vocabulary.");
Assert.IsFalse(StructureWords.IsStructural("marta.prova"));
Assert.IsFalse(StructureWords.IsStructural("17841401234567"));
}
[TestMethod]
public void NamesMadeOfWordsOfTheListAreHiddenAsEntriesOfAMapAndCompoundOnlyWordsNeverStandTogether()
{
// Two first names together are a name, not a key: a compound-only word passes only next to a word of the list.
Assert.IsFalse(StructureWords.IsStructural("max_mark"));
Assert.IsFalse(StructureWords.IsStructural("mark-max"));
Assert.IsTrue(StructureWords.IsStructural("max_music"), "«music» is a word of the list: only the map rule can hide it.");
Assert.IsTrue(StructureWords.IsKnownKey("user"));
Assert.IsTrue(StructureWords.IsKnownKey("owner"));
Assert.IsFalse(StructureWords.IsKnownKey("the_artist"));
Assert.IsFalse(StructureWords.IsKnownKey("max"), "A known key is still a structural one.");
// A map keyed by user name, every name made of words of the list, none repeated as a value: the shape of the
// values gives it away. «user» and «owner» of a post have the same shape too, and stay: the readers know them.
using var body = JsonDocument.Parse("""
{
"users": { "the_artist": { "is_private": false }, "max_music": { "is_private": true } },
"playlists": { "street_style": [ { "pk": 1 } ], "live_music": [ { "pk": 2 } ] },
"item": { "user": { "pk": 1, "username": "x" }, "owner": { "pk": 1, "username": "x" }, "caption": { "text": "y" } },
"max_mark": { "count": 1 },
"status": "ok"
}
""");
var strict = KeyStructure.DescribeStrict(body.RootElement);
Assert.AreEqual(
"{users:{#:{is_private}},playlists:{#:[{pk}]},item:{user:{pk,username},owner:{pk,username},caption:{text}},status,#:{#}}",
strict);
foreach (var name in new[] { "the_artist", "max_music", "street_style", "live_music", "max_mark" })
{
Assert.IsFalse(strict.Contains(name, StringComparison.OrdinalIgnoreCase), "A name is in the structure.");
}
}
[TestMethod]
public void NamesMadeOfWordsOfTheListAreHiddenInMapsOfPlainValuesEmptyValuesAndUnlikeEntries()
{
// Maps keyed by user name, every name made of words of the list, none repeated as a value. Known fields among
// the entries stay.
(string Map, string Expected)[] cases =
[
// Counts and flags: a key with a plain value stays only when it is a field.
("""{ "the_artist": 3, "street_style": 5, "like_count": 2 }""", "{like_count,#}"),
("""{ "max_music": true, "live_music": false }""", "{#}"),
("""{ "the_artist": null }""", "{#}"),
// Empty values and lists of codes.
("""{ "the_artist": [], "street_style": [], "carousel_media": [] }""", "{carousel_media:[],#:[]}"),
("""{ "the_artist": {}, "street_style": {} }""", "{#:{}}"),
("""{ "the_artist": [ "c1" ], "street_style": [ "c2", "c3" ] }""", "{#:[]}"),
("""{ "the_artist": [], "street_style": [ "c1" ] }""", "{#:[]}"),
("""{ "the_artist": [], "street_style": [ { "pk": "2" } ] }""", "{#:[]}"),
("""{ "the_artist": {}, "street_style": { "pk": "2" } }""", "{#:{}}"),
// Entries with different optional fields: only «pk» in common, or one field more.
("""{ "the_artist": { "pk": "1", "seen": 2 }, "street_style": { "pk": "2" }, "live_music": { "pk": "3", "is_private": true } }""", "{#:{pk,seen}}"),
("""{ "the_artist": { "seen": 1, "is_private": true }, "street_style": { "seen": 2 } }""", "{#:{seen,is_private}}"),
("""{ "the_artist": { "pk": "1", "seen": 1, "is_private": true }, "street_style": { "pk": "2", "like_count": 1, "follower_count": 3 } }""", "{#:{pk,seen,is_private}}"),
("""{ "the_artist": [ { "pk": "1", "seen": 1 } ], "street_style": [ { "pk": "2" } ] }""", "{#:[{pk,seen}]}"),
// A list of maps with one entry each.
("""[ { "the_artist": { "pk": "1" } }, { "street_style": { "pk": "2" } } ]""", "[{#:{pk}}]"),
// Not a map: the fields of a post stay, and so do the keys every element of a list has.
("""{ "user": { "pk": 1 }, "owner": { "pk": 2 }, "caption": { "text": "y" }, "image_versions2": { "candidates": [] } }""",
"{user:{pk},owner:{pk},caption:{text},image_versions2:{candidates:[]}}"),
("""[ { "pk": 1, "is_private": true }, { "pk": 2, "is_private": false, "seen": 1 } ]""", "[{pk,is_private}]"),
];
foreach (var (map, expected) in cases)
{
using var body = JsonDocument.Parse("{ \"data\": " + map + " }");
var strict = KeyStructure.DescribeStrict(body.RootElement);
Assert.AreEqual("{data:" + expected + "}", strict);
foreach (var name in new[] { "the_artist", "street_style", "max_music", "live_music" })
{
Assert.IsFalse(strict.Contains(name, StringComparison.OrdinalIgnoreCase), "A name is in the structure.");
}
}
Assert.IsTrue(StructureWords.IsFieldKey("is_private"));
Assert.IsTrue(StructureWords.IsFieldKey("user"));
Assert.IsFalse(StructureWords.IsFieldKey("the_artist"));
Assert.IsFalse(StructureWords.IsFieldKey("max"), "A field is still structural.");
}
// ---- The recorder ----
[TestMethod]
public void ListsStopAtTheirCapsAndCountWhatTheyLeaveOut()
{
var clock = new ManualClock(Start);
long? current = 5;
var diagnostics = new CollectionDiagnostics(clock, () => current);
diagnostics.SessionStarted(5, clock.Now, 1.0);
for (var i = 0; i < CollectionDiagnostics.MaxPages + 5; i++)
{
diagnostics.PageOpened(5, SitePages.Profile, ok: true);
}
for (var i = 0; i < CollectionDiagnostics.MaxUnknownShapes + 2; i++)
{
diagnostics.ReadObserved(Response($"u{i}", HostKind.Site, "/api/forma/"), new ReadResult { Shape = ReadShape.Unrecognized }, $"{{chiave{Letters(i)}}}");
}
for (var i = 0; i < CollectionDiagnostics.MaxSignals + 3; i++)
{
diagnostics.SignalRaised(new Signal(SignalLevel.Throttle, "http-429", null, clock.Now));
}
for (var i = 0; i < CollectionDiagnostics.MaxRecipes + 4; i++)
{
diagnostics.RecipeEnded(5, RecipeKind.ProfileCheck, RecipeStatus.Completed, null, 1, 0);
}
current = null;
diagnostics.SessionEnded(5, clock.Now, SessionOutcome.Completed, SessionStopCause.WorkDone);
// Outside sessions: response groups by depth of the address and resource type.
string[] types = ["Document", "Image", "Media", "Font", "Script", "XHR", "Fetch", "Ping", "Other", "Manifest"];
for (var i = 0; i < CollectionDiagnostics.MaxResponseGroups + 7; i++)
{
var path = string.Concat(Enumerable.Repeat("/x", 1 + (i / types.Length))) + "/";
diagnostics.OnResponse(Response($"g{i}", HostKind.Site, path, resourceType: types[i % types.Length]));
}
var session = diagnostics.Recent.Single();
Assert.HasCount(CollectionDiagnostics.MaxPages, session.Pages);
Assert.AreEqual(5, session.Overflow.Pages);
Assert.HasCount(CollectionDiagnostics.MaxUnknownShapes, session.UnknownShapes);
Assert.AreEqual(2, session.Overflow.UnknownShapes);
Assert.HasCount(CollectionDiagnostics.MaxSignals, session.Signals);
Assert.AreEqual(3, session.Overflow.Signals);
Assert.HasCount(CollectionDiagnostics.MaxRecipes, session.Recipes);
Assert.AreEqual(4, session.Overflow.Recipes);
Assert.AreEqual(SessionStopCause.WorkDone, session.StopCause);
// An overflowing body is counted once, not again when it is read (nor once per block of a page).
var late = Response("over", HostKind.Site, "/y/y/y/y/y/y/y/y/y/y/y/y/y/y/y/y/y/y/y/y/y/y/y/y/y/");
diagnostics.OnResponse(late);
diagnostics.OnLoadingFinished("over", 10);
diagnostics.ReadObserved(late, new ReadResult { Shape = ReadShape.Recognized }, null);
diagnostics.ReadObserved(late, ReadResult.EmptyResult, null);
var outside = diagnostics.Snapshot(clock.Now).Single();
Assert.IsNull(outside.Session);
Assert.HasCount(CollectionDiagnostics.MaxResponseGroups, outside.Responses);
Assert.AreEqual(8, outside.Overflow.Responses);
Assert.AreEqual(0, outside.Overflow.Requests);
Assert.AreEqual(0, diagnostics.Faults);
}
[TestMethod]
public void OnlyBodiesStillWaitingCountAsForgottenAndLateNewsIsCountedWhereItArrives()
{
var clock = new ManualClock(Start);
long? current = 6;
var diagnostics = new CollectionDiagnostics(clock, () => current);
diagnostics.SessionStarted(6, clock.Now, 1);
// A long session: thousands of images and data responses, each settled (size, reading or drop).
for (var i = 0; i < 6000; i++)
{
var image = Response($"img{i}", HostKind.Cdn, "/v/t51/foto.jpg", mime: "image/jpeg", resourceType: "Image");
diagnostics.OnResponse(image);
diagnostics.OnLoadingFinished(image.RequestId, 100);
if (i % 3 == 0)
{
var data = Response($"dat{i}", HostKind.Site, "/api/v1/feed/", resourceType: "XHR");
diagnostics.OnResponse(data);
diagnostics.OnLoadingFinished(data.RequestId, 50);
if (i % 2 == 0)
{
diagnostics.ReadObserved(data, ReadResult.EmptyResult, null);
}
else
{
diagnostics.OnBodyDropped(data.RequestId, BodyDropReason.NotJson);
}
}
}
// One body that never got its outcome, then enough new responses to push it out.
var waiting = Response("waiting", HostKind.Site, "/api/v1/feed/", resourceType: "XHR");
diagnostics.OnResponse(waiting);
for (var i = 0; i < 4100; i++)
{
diagnostics.OnResponse(Response($"open{i}", HostKind.Cdn, "/v/t51/video.mp4", mime: "video/mp4", resourceType: "Media"));
}
var trace = diagnostics.Snapshot(clock.Now).Single();
Assert.AreEqual(1, trace.Overflow.Requests, "Only the body still waiting; settled responses and media without a size are not losses.");
var feed = trace.Responses.Single(r => r.Pattern == "/api/v1/feed/");
Assert.AreEqual((2001, 1000, 1000), (feed.Count, feed.Empty, feed.Dropped.Single().Count));
Assert.AreEqual(600_000L, trace.Responses.Single(r => r.Pattern == "cdn *.jpg").Bytes);
// The session ends; what arrives afterwards for its responses goes to the trace open now, as late.
var last = Response("last", HostKind.Site, "/api/v1/feed/", resourceType: "XHR");
diagnostics.OnResponse(last);
current = null;
diagnostics.SessionEnded(6, clock.Now, SessionOutcome.Completed, SessionStopCause.WorkDone);
diagnostics.OnLoadingFinished("last", 70);
diagnostics.ReadObserved(last, ReadResult.EmptyResult, null);
var ended = diagnostics.Recent.Single();
Assert.AreEqual(2002, ended.Responses.Single(r => r.Pattern == "/api/v1/feed/").Count);
Assert.AreEqual(1000, ended.Responses.Single(r => r.Pattern == "/api/v1/feed/").Empty, "A closed trace is not changed.");
var outside = diagnostics.Snapshot(clock.Now).Single();
Assert.IsNull(outside.Session);
Assert.AreEqual(2, outside.Overflow.Late);
Assert.AreEqual(0, outside.Responses.Count);
Assert.AreEqual(0, diagnostics.Faults);
}
[TestMethod]
public void AFailedRecipeSaysTheTypeOfItsErrorAndAFailedDownloadItsCause()
{
var clock = new ManualClock(Start);
var diagnostics = new CollectionDiagnostics(clock, () => 8);
diagnostics.SessionStarted(8, clock.Now, 1);
diagnostics.RecipeEnded(8, RecipeKind.Highlight, RecipeStatus.Failed, null, 2, 0, nameof(TimeoutException));
diagnostics.RecipeEnded(8, RecipeKind.Highlight, RecipeStatus.Failed, null, 2, 0, "System.Collections.Generic.List`1 di marta.prova");
diagnostics.DownloadSettled(new DownloadProgress(1, 2, 3, EntryKind.Post, DownloadStep.Retried) { Cause = DownloadCauses.Of(503) });
diagnostics.DownloadSettled(new DownloadProgress(1, 2, 3, EntryKind.Post, DownloadStep.Retried) { Cause = DownloadCauses.Of(503) });
diagnostics.DownloadSettled(new DownloadProgress(1, 2, 3, EntryKind.Post, DownloadStep.Failed) { Cause = DownloadCauses.Of(null) });
diagnostics.DownloadSettled(new DownloadProgress(1, 2, 3, EntryKind.Post, DownloadStep.Stored, 10));
diagnostics.SessionEnded(8, clock.Now, SessionOutcome.Completed, SessionStopCause.WorkDone);
var trace = diagnostics.Recent.Single();
CollectionAssert.AreEqual(new[] { nameof(TimeoutException), CollectionDiagnostics.Other }, trace.Recipes.Select(r => r.Error).ToArray());
Assert.AreEqual(2, trace.Downloads.Single(d => d.Cause == "http-503").Count);
Assert.AreEqual(DownloadStep.Failed, trace.Downloads.Single(d => d.Cause == DownloadCauses.Network).Step);
Assert.IsNull(trace.Downloads.Single(d => d.Step == DownloadStep.Stored).Cause);
}
[TestMethod]
public void WhatTheCaptureSeesGoesToTheSessionInProgressOrToTheDayOutsideSessions()
{
var clock = new ManualClock(Start);
long? current = null;
var diagnostics = new CollectionDiagnostics(clock, () => current) { SiteMap = SiteMap.LoadTestSite() };
// Alberto at the browser before any session: the day outside sessions.
diagnostics.OnNavigation(new NavigationDescriptor(HostKind.Site, "http://sito/profilo/a/", "sito", "/profilo/a/", clock.Now));
current = 9;
diagnostics.SessionStarted(9, clock.Now, 0.87654);
var document = Response("d1", HostKind.Site, "/profilo/marta.prova/", mime: "text/html", resourceType: "Document", mainFrame: true);
diagnostics.OnResponse(document);
diagnostics.OnLoadingFinished("d1", 50_000);
diagnostics.ReadObserved(document, new ReadResult { Shape = ReadShape.Recognized, Contents = [] }, null);
diagnostics.ReadObserved(document, ReadResult.EmptyResult, null);
var image = Response("i1", HostKind.Cdn, "/v/t51/foto.jpg", mime: "image/jpeg", resourceType: "Image");
diagnostics.OnResponse(image);
diagnostics.OnLoadingFinished("i1", 120_000);
var data = Response("x1", HostKind.Site, "/api/dati/", resourceType: "Fetch");
diagnostics.OnResponse(data);
diagnostics.OnBodyDropped("x1", BodyDropReason.Timeout);
diagnostics.PermitDenied(null, ActionKind.ProfileOpen, DenialReason.HourlyBudgetReached);
diagnostics.FilesQueued(9, EntryKind.Post, 3, nameof(SaveOutcome.Created), skipped: 1);
diagnostics.FilesQueued(9, EntryKind.Post, 0, nameof(SaveOutcome.Known));
diagnostics.StepJudged(9, CollectionDiagnostics.VerdictRecognized);
diagnostics.TargetClicked(9, SiteTargets.ProfileStoryRing, TargetCheckStatus.Clicked);
current = null;
diagnostics.SessionEnded(9, clock.Now, SessionOutcome.Stopped, SessionStopCause.StoppedEarly, RecipeStatus.TargetNotFound);
// After the session: a download, outside sessions; a late body of the session's request goes nowhere new.
diagnostics.DownloadSettled(new DownloadProgress(1, 2, 3, EntryKind.Post, DownloadStep.Stored, 120_000));
diagnostics.DownloadSettled(new DownloadProgress(1, 2, 3, EntryKind.Post, DownloadStep.Retried));
diagnostics.ReadObserved(document, ReadResult.EmptyResult, null);
var session = diagnostics.Recent.Single();
Assert.AreEqual(9L, session.Session);
Assert.AreEqual(0.88, session.Mood);
Assert.AreEqual(SessionStopCause.StoppedEarly, session.StopCause);
Assert.AreEqual(RecipeStatus.TargetNotFound, session.StoppedBy);
Assert.IsFalse(session.InProgress);
var page = session.Responses.Single(r => r.Page == SitePages.Profile);
Assert.AreEqual("/profilo/{username}/", page.Pattern);
Assert.AreEqual((1, 50_000L, 1, 1, 0), (page.Count, page.Bytes, page.Recognized, page.Empty, page.NotRead));
var cdn = session.Responses.Single(r => r.HostKind == HostKind.Cdn);
Assert.AreEqual(("cdn *.jpg", 1, 120_000L), (cdn.Pattern, cdn.NotRead, cdn.MaxBytes));
var dropped = session.Responses.Single(r => r.Pattern == PathPatterns.Of("/api/dati/"));
Assert.AreEqual(BodyDropReason.Timeout, dropped.Dropped.Single().Reason);
Assert.AreEqual(new DenialCount(ActionKind.ProfileOpen, DenialReason.HourlyBudgetReached, 1), session.Denials.Single());
Assert.AreEqual(new QueuedFiles(EntryKind.Post, "Created", 1, 3, 1), session.FilesQueued.Single(q => q.Outcome == "Created"));
Assert.AreEqual(new TargetCount(SiteTargets.ProfileStoryRing, TargetCheckStatus.Clicked, 1), session.Targets.Single());
var outside = diagnostics.Snapshot(clock.Now).Single();
Assert.IsNull(outside.Session);
Assert.IsTrue(outside.InProgress);
Assert.AreEqual(SitePages.Profile, outside.Navigations.Single().Page);
Assert.AreEqual(2, outside.Downloads.Count);
Assert.AreEqual(120_000L, outside.DownloadedBytes);
Assert.AreEqual(0, outside.Responses.Count, "The late body is not a response of the day outside sessions.");
Assert.AreEqual(1, outside.Overflow.Late, "It is counted as late where it arrived.");
}
[TestMethod]
public void TheDayOutsideSessionsIsKeptAtTheEndOfItsLocalDayAndOpenSessionsWhenFebeStops()
{
var clock = new ManualClock(new DateTimeOffset(2026, 11, 13, 21, 0, 0, TimeSpan.Zero), TestZones.Rome);
var diagnostics = new CollectionDiagnostics(clock);
diagnostics.SignalRaised(new Signal(SignalLevel.Throttle, "http-429", "https://sito/profilo/marta.prova/", clock.Now));
clock.Now = clock.Now.AddHours(2); // 00:00 in Rome: a new local day
diagnostics.SignalRaised(new Signal(SignalLevel.Throttle, "http-429", null, clock.Now));
var yesterday = diagnostics.Recent.Single();
Assert.IsNull(yesterday.Session);
Assert.IsFalse(yesterday.InProgress);
Assert.HasCount(1, yesterday.Signals);
diagnostics.SessionStarted(12, clock.Now, 1);
diagnostics.PageOpened(12, SitePages.Home, ok: true);
diagnostics.Dispose();
diagnostics.PageOpened(12, SitePages.Home, ok: true);
var traces = diagnostics.Recent;
Assert.HasCount(3, traces);
var stopped = traces.Single(t => t.Session == 12);
Assert.IsTrue(stopped.InProgress);
Assert.AreEqual(SessionStopCause.Shutdown, stopped.StopCause);
Assert.HasCount(1, stopped.Pages, "Nothing is recorded after the flush.");
Assert.HasCount(1, traces.Single(t => t.Session is null && t.Start >= clock.Now).Signals);
}
[TestMethod]
public void NamesOutsideTheClosedListsBecomeOther()
{
var clock = new ManualClock(Start);
var diagnostics = new CollectionDiagnostics(clock, () => 3);
diagnostics.SessionStarted(3, clock.Now, 1);
diagnostics.PageOpened(3, "marta.prova", ok: false);
diagnostics.TargetClicked(3, "marta.prova", TargetCheckStatus.NotFound);
diagnostics.StepJudged(3, "marta.prova");
diagnostics.RecipeEnded(3, RecipeKind.ProfileCheck, RecipeStatus.StoppedBySignal, "https://sito/marta.prova", 0, 0);
diagnostics.FilesQueued(3, EntryKind.Post, 1, "marta.prova");
diagnostics.OnResponse(Response("m1", HostKind.Other, "/marta.prova", mime: "text/marta prova", resourceType: "marta.prova"));
diagnostics.SessionEnded(3, clock.Now, SessionOutcome.Completed, SessionStopCause.WorkDone);
var trace = diagnostics.Recent.Single();
Assert.AreEqual(CollectionDiagnostics.Other, trace.Pages.Single().Page);
Assert.IsNull(trace.Pages.Single().Pattern);
Assert.AreEqual(CollectionDiagnostics.Other, trace.Targets.Single().Target);
Assert.AreEqual(CollectionDiagnostics.Other, trace.Steps.Single().Verdict);
Assert.AreEqual(CollectionDiagnostics.Other, trace.Recipes.Single().Signal);
Assert.AreEqual(CollectionDiagnostics.Other, trace.FilesQueued.Single().Outcome);
var response = trace.Responses.Single();
Assert.AreEqual((CollectionDiagnostics.Other, "text/altro", CollectionDiagnostics.Other), (response.Pattern, response.Mime, response.ResourceType));
Assert.AreEqual("image/jpeg", CollectionDiagnostics.MimeOf("image/JPEG; charset=binary"));
Assert.AreEqual(CollectionDiagnostics.Other, CollectionDiagnostics.MimeOf("marta/prova"));
}
// ---- The log ----
[TestMethod]
public void TheLogKeepsTwoWeeksSkipsDamagedLinesAndTouchesNoOtherFile()
{
using var folder = new TempFolder("diagnostica");
var clock = new ManualClock(new DateTimeOffset(2026, 11, 13, 9, 0, 0, TimeSpan.Zero), TestZones.Rome);
var log = new DiagnosticLog(folder.Combine("diagnostica"), clock);
Directory.CreateDirectory(log.Folder);
var today = LocalCalendar.Today(clock.Now, clock.LocalZone);
File.WriteAllText(Path.Combine(log.Folder, DiagnosticLog.FileNameFor(today.AddDays(-14))), "{}\n");
File.WriteAllText(Path.Combine(log.Folder, DiagnosticLog.FileNameFor(today.AddDays(-20))), "{}\n");
var kept = Path.Combine(log.Folder, DiagnosticLog.FileNameFor(today.AddDays(-13)));
File.WriteAllText(kept, "{\"session\":1,\"start\":\"2026-10-31T09:00:00+00:00\",\"inProgress\":false}\n{\"session\":tronca");
var other = Path.Combine(log.Folder, "appunti.txt");
File.WriteAllText(other, "di Alberto");
var diagnostics = new CollectionDiagnostics(clock, log: log);
diagnostics.SessionStarted(2, clock.Now, 1.1);
diagnostics.PageOpened(2, SitePages.Home, ok: true);
diagnostics.RecipeEnded(2, RecipeKind.FollowingSweep, RecipeStatus.Completed, null, 1, 4);
clock.Now = clock.Now.AddMinutes(9);
diagnostics.SessionEnded(2, clock.Now, SessionOutcome.Completed, SessionStopCause.PlannedEnd);
var contents = log.ReadAll();
Assert.AreEqual(1, contents.DamagedLines);
CollectionAssert.AreEqual(new long?[] { 1, 2 }, contents.Traces.Select(t => t.Session).ToArray(), "Oldest first.");
var read = contents.Traces[1];
Assert.AreEqual(SessionStopCause.PlannedEnd, read.StopCause);
Assert.AreEqual(SitePages.Home, read.Pages.Single().Page);
Assert.AreEqual(RecipeKind.FollowingSweep, read.Recipes.Single().Kind);
Assert.AreEqual(clock.Now, read.End);
Assert.IsFalse(File.Exists(Path.Combine(log.Folder, DiagnosticLog.FileNameFor(today.AddDays(-14)))));
Assert.IsFalse(File.Exists(Path.Combine(log.Folder, DiagnosticLog.FileNameFor(today.AddDays(-20)))));
Assert.IsTrue(File.Exists(kept));
Assert.IsTrue(File.Exists(other), "Only its own files, by their name.");
Assert.IsTrue(File.Exists(Path.Combine(log.Folder, DiagnosticLog.FileNameFor(today))));
// Febe stopped in the middle of a line of today: the next trace starts on a line of its own.
var todayFile = Path.Combine(log.Folder, DiagnosticLog.FileNameFor(today));
File.AppendAllText(todayFile, "{\"session\":3,\"start\":\"2026-11-13T09:");
diagnostics.SessionStarted(4, clock.Now, 1);
diagnostics.SessionEnded(4, clock.Now, SessionOutcome.Completed, SessionStopCause.WorkDone);
var afterTear = log.ReadAll();
Assert.AreEqual(2, afterTear.DamagedLines, "The torn line only, besides the one of 13 days ago.");
CollectionAssert.AreEqual(new long?[] { 1, 2, 4 }, afterTear.Traces.Select(t => t.Session).ToArray());
Assert.AreEqual(2, diagnostics.Gather().DamagedLines);
// Two weeks later the day of the session is gone too.
clock.Now = clock.Now.AddDays(14);
Assert.HasCount(0, log.ReadAll().Traces);
Assert.IsFalse(diagnostics.Collect().Any(t => t.Session is not null), "Nothing left in the log, nor in memory beyond the days kept.");
}
[TestMethod]
public void ATraceWhoseWriteFailedIsStillInTheReportAndTheReportSaysSo()
{
using var folder = new TempFolder("diagnostica");
var clock = new ManualClock(new DateTimeOffset(2026, 11, 13, 9, 0, 0, TimeSpan.Zero), TestZones.Rome);
// A file where the folder of the log should be: every write fails.
var blocked = folder.Combine("diagnostica");
File.WriteAllText(blocked, "non una cartella");
var diagnostics = new CollectionDiagnostics(clock, log: new DiagnosticLog(blocked, clock));
diagnostics.SessionStarted(5, clock.Now, 1);
diagnostics.PageOpened(5, SitePages.Home, ok: true);
diagnostics.SessionEnded(5, clock.Now, SessionOutcome.Completed, SessionStopCause.WorkDone);
diagnostics.SessionStarted(6, clock.Now, 1);
var gathered = diagnostics.Gather();
CollectionAssert.AreEqual(new long?[] { 5, 6 }, gathered.Traces.Select(t => t.Session).ToArray(), "The finished one from memory, the open one in progress, once each.");
Assert.IsFalse(gathered.Traces[0].InProgress);
Assert.IsTrue(gathered.Traces[1].InProgress);
Assert.IsGreaterThan(0, gathered.RecorderFaults);
using var stream = new MemoryStream();
DiagnosticReport.Write(stream, gathered.Traces, new DiagnosticReportHeader("0.1.2", "docker", clock.Now, TestZones.Rome, DamagedLines: 3, RecorderFaults: gathered.RecorderFaults));
using var json = JsonDocument.Parse(stream.ToArray());
Assert.AreEqual(3, json.RootElement.GetProperty("righeRovinate").GetInt32());
Assert.AreEqual(gathered.RecorderFaults, json.RootElement.GetProperty("erroriRegistratore").GetInt32());
}
[TestMethod]
public void ADayFileThatCannotBeReadIsCountedAndTheOtherDaysAreStillThere()
{
using var folder = new TempFolder("diagnostica");
var clock = new ManualClock(new DateTimeOffset(2026, 11, 13, 9, 0, 0, TimeSpan.Zero), TestZones.Rome);
var log = new DiagnosticLog(folder.Combine("diagnostica"), clock);
var diagnostics = new CollectionDiagnostics(clock, log: log);
diagnostics.SessionStarted(1, clock.Now, 1);
diagnostics.SessionEnded(1, clock.Now.AddMinutes(5), SessionOutcome.Completed, SessionStopCause.WorkDone);
clock.Now = clock.Now.AddDays(1);
diagnostics.SessionStarted(2, clock.Now, 1);
diagnostics.SessionEnded(2, clock.Now.AddMinutes(5), SessionOutcome.Completed, SessionStopCause.WorkDone);
var yesterday = Path.Combine(log.Folder, DiagnosticLog.FileNameFor(LocalCalendar.Today(clock.Now, clock.LocalZone).AddDays(-1)));
// Another program (a backup, a synchronization, an antivirus) holds yesterday's file without sharing it.
DiagnosticLogContents contents;
DiagnosticCollection gathered;
using (new FileStream(yesterday, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
contents = log.ReadAll();
gathered = new CollectionDiagnostics(clock, log: log).Gather();
}
Assert.AreEqual(1, contents.UnreadableFiles);
Assert.AreEqual(0, contents.DamagedLines);
CollectionAssert.AreEqual(new long?[] { 2 }, contents.Traces.Select(t => t.Session).ToArray(), "Today is still read.");
Assert.AreEqual(1, gathered.UnreadableFiles, "The report is told that a day is missing.");
Assert.AreEqual(0, gathered.RecorderFaults, "Not the whole log lost: one file.");
Assert.AreEqual(1, gathered.Traces.Count);
using var stream = new MemoryStream();
DiagnosticReport.Write(stream, gathered.Traces, new DiagnosticReportHeader("0.1.2", "docker", clock.Now, TestZones.Rome, UnreadableFiles: gathered.UnreadableFiles));
using var json = JsonDocument.Parse(stream.ToArray());
Assert.AreEqual(1, json.RootElement.GetProperty("fileIlleggibili").GetInt32());
Assert.AreEqual(2, log.ReadAll().Traces.Count, "Released: both days again.");
}
[TestMethod]
public void ASessionCutShortByACrashIsStillInTheReportAsASessionWithoutAnEnd()
{
using var folder = new TempFolder("diagnostica");
var clock = new ManualClock(new DateTimeOffset(2026, 11, 13, 9, 0, 0, TimeSpan.Zero), TestZones.Rome);
var folderOfLog = folder.Combine("diagnostica");
var before = new CollectionDiagnostics(clock, log: new DiagnosticLog(folderOfLog, clock));
before.SessionStarted(7, clock.Now, 1);
Assert.AreEqual(1, new DiagnosticLog(folderOfLog, clock).ReadAll().Traces.Count, "The start is in the log at once.");
before.PageOpened(7, SitePages.Home, ok: true);
clock.Now = clock.Now.AddMinutes(6);
before.RecipeEnded(7, RecipeKind.FollowingSweep, RecipeStatus.Completed, null, 2, 3);
clock.Now = clock.Now.AddMinutes(1);
before.RecipeEnded(7, RecipeKind.ProfileCheck, RecipeStatus.Completed, null, 1, 0);
// While it runs, the report has it once, as it is now (not as its last line in the log).
var running = before.Gather();
Assert.AreEqual(2, running.Traces.Single().Recipes.Count);
Assert.AreEqual(0, running.UnfinishedSessions);
// Febe is killed: no end, no flush. After the restart the session is there up to its last line in progress.
clock.Now = clock.Now.AddMinutes(30);
var after = new CollectionDiagnostics(clock, log: new DiagnosticLog(folderOfLog, clock));
var gathered = after.Gather();
var trace = gathered.Traces.Single();
Assert.AreEqual(7, trace.Session);
Assert.IsTrue(trace.InProgress);
Assert.IsNull(trace.StopCause);
Assert.AreEqual(SitePages.Home, trace.Pages.Single().Page);
Assert.AreEqual(RecipeKind.FollowingSweep, trace.Recipes.Single().Kind, "The checkpoint at the end of the first recipe; the second came too soon after it.");
Assert.AreEqual(1, gathered.UnfinishedSessions);
using var stream = new MemoryStream();
DiagnosticReport.Write(stream, gathered.Traces, new DiagnosticReportHeader("0.1.2", "docker", clock.Now, TestZones.Rome, UnfinishedSessions: gathered.UnfinishedSessions));
using var json = JsonDocument.Parse(stream.ToArray());
Assert.AreEqual(1, json.RootElement.GetProperty("sessioniSenzaFine").GetInt32());
// A session that ends, and one closed by a shutdown, are not without an end; each is in the report once.
after.SessionStarted(8, clock.Now, 1);
after.RecipeEnded(8, RecipeKind.FollowingSweep, RecipeStatus.Completed, null, 1, 0);
after.SessionEnded(8, clock.Now.AddMinutes(2), SessionOutcome.Completed, SessionStopCause.WorkDone);
after.SessionStarted(9, clock.Now.AddMinutes(3), 1);
after.Dispose();
var last = new CollectionDiagnostics(clock, log: new DiagnosticLog(folderOfLog, clock)).Gather();
CollectionAssert.AreEqual(new long?[] { 7, 8, 9 }, last.Traces.Select(t => t.Session).ToArray());
Assert.IsFalse(last.Traces[1].InProgress);
Assert.AreEqual(SessionStopCause.Shutdown, last.Traces[2].StopCause);
Assert.AreEqual(1, last.UnfinishedSessions, "Only the one of the crash.");
}
[TestMethod]
public void AnEndWhoseWriteFailedIsWrittenLaterAndTheSessionDoesNotLookCutShortAfterARestart()
{
using var folder = new TempFolder("diagnostica");
var clock = new ManualClock(new DateTimeOffset(2026, 11, 13, 9, 0, 0, TimeSpan.Zero), TestZones.Rome);
var folderOfLog = folder.Combine("diagnostica");
var before = new CollectionDiagnostics(clock, log: new DiagnosticLog(folderOfLog, clock));
var today = Path.Combine(folderOfLog, DiagnosticLog.FileNameFor(LocalCalendar.Today(clock.Now, clock.LocalZone)));
// The start is written; the end is not (another program holds the file for a moment).
before.SessionStarted(7, clock.Now, 1);
using (new FileStream(today, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
before.SessionEnded(7, clock.Now.AddMinutes(5), SessionOutcome.Completed, SessionStopCause.WorkDone);
}
Assert.AreEqual(1, before.Faults, "The failed write is counted.");
Assert.IsTrue(new DiagnosticLog(folderOfLog, clock).ReadAll().Traces.Single().InProgress, "Only the start is in the log so far.");
// The next line written brings the end along.
before.SessionStarted(8, clock.Now.AddMinutes(10), 1);
before.SessionEnded(8, clock.Now.AddMinutes(15), SessionOutcome.Completed, SessionStopCause.WorkDone);
// The same with the report: gathering it writes what is still waiting.
before.SessionStarted(9, clock.Now.AddMinutes(20), 1);
using (new FileStream(today, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
before.SessionEnded(9, clock.Now.AddMinutes(25), SessionOutcome.Completed, SessionStopCause.WorkDone);
}
Assert.AreEqual(2, before.Faults);
Assert.AreEqual(0, before.Gather().UnfinishedSessions);
// Febe is killed and restarted: every session ended, none without an end.
var after = new CollectionDiagnostics(clock, log: new DiagnosticLog(folderOfLog, clock)).Gather();
CollectionAssert.AreEqual(new long?[] { 7, 8, 9 }, after.Traces.Select(t => t.Session).ToArray());
Assert.IsTrue(after.Traces.All(t => !t.InProgress && t.StopCause == SessionStopCause.WorkDone));
Assert.AreEqual(0, after.UnfinishedSessions);
Assert.AreEqual(2, before.Faults, "Nothing failed again.");
}
[TestMethod]
public void ASignalReportedStraightToTheBreakerIsInTheTraceOnceEvenWhenTheDetectorSaidItToo()
{
var clock = new ManualClock(Start);
long? current = 3;
var diagnostics = new CollectionDiagnostics(clock, () => current);
diagnostics.SessionStarted(3, clock.Now, 1);
// The session cookie lost: the connection tells the breaker, never the detector.
var lost = new Signal(SignalLevel.Disconnect, SignalRules.SessionCookieMissingCode, "https://sito.esempio/accedi/", clock.Now);
diagnostics.BreakerChanged(new BreakerState(BreakerStatus.Disconnected, null, lost, null));
// A throttle the detector saw: the breaker changes first, then the detector raises it; once in the trace.
clock.Now = clock.Now.AddMinutes(1);
var throttle = new Signal(SignalLevel.Throttle, "http-429", null, clock.Now);
diagnostics.BreakerChanged(new BreakerState(BreakerStatus.Throttled, clock.Now.AddHours(1), throttle, null));
diagnostics.SignalRaised(throttle);
// The breaker reopening is not a signal.
diagnostics.BreakerChanged(new BreakerState(BreakerStatus.Closed, null, throttle, null));
diagnostics.SessionEnded(3, clock.Now, SessionOutcome.Throttled, SessionStopCause.BreakerOpen);
var trace = diagnostics.Recent.Single();
CollectionAssert.AreEqual(
new[] { SignalRules.SessionCookieMissingCode, "http-429" },
trace.Signals.Select(s => s.Code).ToArray());
Assert.AreEqual(SignalLevel.Disconnect, trace.Signals[0].Level);
}
// ---- The exported file ----
[TestMethod]
public void TheReportIsIndentedJsonWithoutBomWithItsHeadAndLocalTimes()
{
var clock = new ManualClock(new DateTimeOffset(2026, 11, 13, 9, 30, 0, TimeSpan.Zero), TestZones.Rome);
var diagnostics = new CollectionDiagnostics(clock);
diagnostics.SessionStarted(4, clock.Now, 1);
diagnostics.SessionEnded(4, clock.Now.AddMinutes(5), SessionOutcome.Throttled, SessionStopCause.BreakerOpen);
diagnostics.SignalRaised(new Signal(SignalLevel.Challenge, "challenge-url", "https://sito/challenge/", clock.Now));
using var stream = new MemoryStream();
DiagnosticReport.Write(stream, diagnostics.Collect(), new DiagnosticReportHeader("0.1.2", "windows", clock.Now, TestZones.Rome));
var bytes = stream.ToArray();
Assert.AreEqual((byte)'{', bytes[0], "No BOM.");
var text = Encoding.UTF8.GetString(bytes);
StringAssert.Contains(text, "\n \"rapporto\": \"diagnostica della raccolta\"", "Indented.");
using var json = JsonDocument.Parse(text);
var root = json.RootElement;
Assert.AreEqual("0.1.2", root.GetProperty("versione").GetString());
Assert.AreEqual("windows", root.GetProperty("edizione").GetString());
Assert.AreEqual("2026-11-13T10:30:00+01:00", root.GetProperty("creato").GetString());
Assert.AreEqual(DiagnosticReport.ZoneName(TestZones.Rome), root.GetProperty("fuso").GetString());
Assert.AreNotEqual(CollectionDiagnostics.Other, root.GetProperty("fuso").GetString());
Assert.AreEqual(14, root.GetProperty("giorni").GetInt32());
Assert.AreEqual(0, root.GetProperty("righeRovinate").GetInt32());
Assert.AreEqual(0, root.GetProperty("erroriRegistratore").GetInt32());
var session = root.GetProperty("sessioni").EnumerateArray().Single();
Assert.AreEqual(4, session.GetProperty("session").GetInt64());
Assert.AreEqual("BreakerOpen", session.GetProperty("stopCause").GetString());
Assert.AreEqual("Throttled", session.GetProperty("outcome").GetString());
Assert.AreEqual("2026-11-13T10:30:00+01:00", session.GetProperty("start").GetString(), "Times in Alberto's zone.");
var outside = root.GetProperty("fuoriSessione").EnumerateArray().Single();
Assert.IsFalse(outside.TryGetProperty("session", out _));
Assert.AreEqual("challenge-url", outside.GetProperty("signals")[0].GetProperty("code").GetString());
Assert.AreEqual("febe-diagnostica-2026-11-13.json", DiagnosticReport.FileName(new DateTimeOffset(2026, 11, 13, 22, 59, 0, TimeSpan.Zero), TestZones.Rome));
Assert.AreEqual("febe-diagnostica-2026-11-14.json", DiagnosticReport.FileName(new DateTimeOffset(2026, 11, 13, 23, 0, 0, TimeSpan.Zero), TestZones.Rome), "The local day.");
}
[TestMethod]
public void TheZoneOfTheWindowsEditionIsWrittenToo()
{
// The clock of Febe for Windows has TimeZoneInfo.Local, whose name there is a Windows one, with spaces.
var windows = TimeZoneInfo.CreateCustomTimeZone("W. Europe Standard Time", TimeSpan.FromHours(1), "W. Europe Standard Time", "W. Europe Standard Time");
using var stream = new MemoryStream();
DiagnosticReport.Write(stream, [], new DiagnosticReportHeader("0.1.2", "windows", Start, windows));
using var json = JsonDocument.Parse(stream.ToArray());
var zone = json.RootElement.GetProperty("fuso").GetString();
Assert.AreNotEqual(CollectionDiagnostics.Other, zone);
Assert.IsTrue(zone is "W._Europe_Standard_Time" || zone!.StartsWith("Europe/", StringComparison.Ordinal), zone);
}
private static ResponseDescriptor Response(string id, HostKind host, string path, string mime = "application/json", string? resourceType = "Fetch", bool mainFrame = false, int status = 200) =>
new(id, host, "https://indirizzo.non.usato" + path, "indirizzo.non.usato", path, status, mime, resourceType, mainFrame, Start);
private static string Letters(int i)
{
var sb = new StringBuilder();
do
{
sb.Append((char)('a' + (i % 26)));
i /= 26;
}
while (i > 0);
return sb.ToString();
}
}
@@ -122,9 +122,14 @@ public sealed class DownloadQueueTests
var fetcher = ScriptedFetcher.Network("net::ERR_INTERNET_DISCONNECTED");
var queue = Queue(library, temp, fetcher, options: new DownloadOptions { StagingFolder = temp.Combine("dati", "temporanei"), MaxConcurrent = 1 });
var steps = new List<DownloadProgress>();
queue.Progress += (_, step) => steps.Add(step);
var report = await queue.RunOnceAsync(CancellationToken.None);
Assert.AreEqual(1, fetcher.Calls, "Every file would fail the same way: the pass ends.");
Assert.IsNotNull(report.PausedUntil);
var waiting = steps.Single();
Assert.AreEqual(DownloadStep.Retried, waiting.Step, "The diagnostic report says why the file is still waiting (issue #39).");
Assert.AreEqual(DownloadCauses.Connection, waiting.Cause);
foreach (var id in entries)
{
Assert.AreEqual(0, (await library.Db.Media.ListByEntryAsync(id)).Single().Attempts, "The router restarting is not the file's fault.");
@@ -8,6 +8,7 @@ using Febe.Browser.Recipes;
using Febe.Browser.Targets;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Diagnostics;
using Febe.Core.Collection.Downloads;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
@@ -127,13 +128,21 @@ internal sealed class CollectionHarness : IAsyncDisposable
/// <summary>The engine session the recipes run in (a real row: events refer to it).</summary>
public TestSession Session { get; private set; } = new();
public static async Task<CollectionHarness> CreateAsync(SharedChromium chromium, RecipeOptions? options = null, double factor = 10)
/// <summary>The recorder of the diagnostic report, when asked for: what the page does goes to <see cref="Session"/>.</summary>
public CollectionDiagnostics? Diagnostics { get; private set; }
public static async Task<CollectionHarness> CreateAsync(SharedChromium chromium, RecipeOptions? options = null, double factor = 10, bool diagnostics = false)
{
var site = await SyntheticSite.StartAsync();
var temp = new TempFolder("raccolta");
var library = await TestLibrary.CreateAsync(temp);
var clock = new CompressedClock(factor, TestZones.Rome);
var harness = new CollectionHarness(chromium, site, temp, library, clock);
if (diagnostics)
{
harness.Diagnostics = new CollectionDiagnostics(clock, () => harness.Session.SessionId);
}
harness.Pipeline = await CollectionPipeline.StartAsync(new CollectionPipelineOptions
{
Cdp = chromium.Cdp,
@@ -147,6 +156,7 @@ internal sealed class CollectionHarness : IAsyncDisposable
Random = new SeededRandom(20261013),
StagingFolder = temp.Combine("dati", "temporanei"),
Recipes = options ?? new RecipeOptions(),
Diagnostics = harness.Diagnostics,
});
harness.Session = new TestSession((await library.Db.Sessions.StartAsync(clock.Now)).Id);
await harness.SignInAsync();
@@ -0,0 +1,209 @@
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);
}
}
+56
View File
@@ -1,7 +1,12 @@
using System.Net;
using System.Text.Json;
using Febe.Core.Collection;
using Febe.Core.Engine;
using Febe.Sonda;
using Febe.Tests.Collection;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Febe.Web.Api;
using Febe.Web.Demo;
namespace Febe.Tests.Web;
@@ -129,6 +134,57 @@ public sealed class DemoPart2Tests
Assert.IsTrue(normal.All(i => !i.Bool("open")));
}
[TestMethod]
public async Task TheDiagnosticReportFollowsTheSceneAndNamesNobody()
{
var finished = s_demo!.World.Today.Count;
Assert.IsGreaterThan(0, finished, "the demo day has sessions");
var names = (await s_demo.Storage.Accounts.ListAsync()).Select(a => a.Username).ToList();
names.AddRange(["marta.demo", "giulia.corre.demo", "tuo.profilo"]);
var vocabulary = ReportLeaks.Vocabulary(SiteMap.LoadInstagram());
var sensitive = names.SelectMany(SensitiveTokens.Tokenize).Where(t => !vocabulary.Contains(t)).ToHashSet(StringComparer.Ordinal);
Assert.IsGreaterThan(20, sensitive.Count);
async Task<JsonElement> ReportAsync(string scene)
{
using var response = await Client.GetAsync($"{ActivityApi.DiagnosticsPath}?scena={scene}");
var text = await response.Content.ReadAsStringAsync();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{scene}: {text}");
Assert.AreEqual("attachment", response.Content.Headers.ContentDisposition?.DispositionType);
Assert.AreEqual("no-store", response.Headers.CacheControl?.ToString());
ReportLeaks.AssertClean(text, names, sensitive, ReportLeaks.FieldKeys([]));
return JsonDocument.Parse(text).RootElement.Clone();
}
var normal = await ReportAsync("normale");
Assert.AreEqual("windows", normal.Str("edizione"), "the demo looks like the desktop by default");
var sessions = normal.Items("sessioni").ToList();
Assert.HasCount(finished, sessions);
Assert.IsTrue(sessions.All(s => s.Str("outcome") == nameof(Febe.Core.Domain.SessionOutcome.Completed) && !s.Bool("inProgress")));
Assert.IsTrue(sessions.All(s => s.Items("responses").Any() && s.Items("recipes").Any()));
Assert.AreEqual(0, sessions.Sum(s => s.Items("signals").Count()));
Assert.HasCount(1, normal.Items("fuoriSessione").ToList());
var running = (await ReportAsync("sessione")).Items("sessioni").ToList();
Assert.HasCount(finished + 1, running);
Assert.IsTrue(running[^1].Bool("inProgress"), "the session in progress comes last");
var stopped = (await ReportAsync("fermo")).Items("sessioni").ToList();
Assert.HasCount(finished, stopped);
Assert.AreEqual(nameof(SessionStopCause.BreakerOpen), stopped[^1].Str("stopCause"));
Assert.AreEqual(DemoDiagnosticSource.ChallengeCode, stopped[^1].Items("signals").Single().Str("code"));
Assert.IsTrue(stopped.Take(stopped.Count - 1).All(s => s.Str("stopCause") != nameof(SessionStopCause.BreakerOpen)));
foreach (var scene in new[] { "scollegato", "errore" })
{
var empty = await ReportAsync(scene);
Assert.AreEqual(0, empty.GetProperty("sessioni").GetArrayLength(), scene);
Assert.AreEqual(0, empty.GetProperty("fuoriSessione").GetArrayLength(), scene);
}
Assert.AreEqual("docker", (await ReportAsync("normale&veste=docker")).Str("edizione"));
}
[TestMethod]
public async Task EverySettingsPageHasItsData()
{
@@ -0,0 +1,139 @@
using System.Globalization;
using System.Net;
using System.Text;
using System.Text.Json;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Diagnostics;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Tests.Web.Part2Support;
using Febe.Tests.Web.Support;
using Febe.Web;
using Febe.Web.Api;
using Febe.Web.Connection;
using Febe.Web.Engine;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web;
/// <summary>
/// «Esporta il rapporto di diagnostica» in Attività (issue #39, spec §7.9): a JSON attachment named after the local day,
/// never cached, with the traces of the recorder and what is missing from them; empty without one; answered also when
/// a configuration problem keeps the engine off (empty: nothing ran).
/// </summary>
[TestClass]
public sealed class DiagnosticReportApiTests
{
[TestMethod]
public async Task TheReportIsAJsonAttachmentOfTheLocalDayNeverCached()
{
var source = new FixedDiagnostics();
await using var server = await Part2.StartAsync(services: s => s.AddSingleton<IDiagnosticSource>(source));
source.Traces = Traces(server.Clock.Now);
source.DamagedLines = 2;
source.Faults = 1;
using var response = await server.Client.GetAsync(ActivityApi.DiagnosticsPath);
var bytes = await response.Content.ReadAsByteArrayAsync();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, Encoding.UTF8.GetString(bytes));
Assert.AreEqual("application/json", response.Content.Headers.ContentType?.MediaType);
Assert.AreEqual("utf-8", response.Content.Headers.ContentType?.CharSet);
Assert.AreEqual("no-store", response.Headers.CacheControl?.ToString());
var disposition = response.Content.Headers.ContentDisposition;
Assert.IsNotNull(disposition);
Assert.AreEqual("attachment", disposition.DispositionType);
var day = LocalCalendar.Today(server.Clock.Now, server.Clock.LocalZone).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
Assert.AreEqual($"febe-diagnostica-{day}.json", disposition.FileName?.Trim('"'));
Assert.AreEqual((byte)'{', bytes[0], "UTF-8 without BOM");
using var report = JsonDocument.Parse(bytes);
var root = report.RootElement;
Assert.AreEqual(DiagnosticReport.Title, root.GetProperty("rapporto").GetString());
Assert.AreEqual(server.App.Services.GetRequiredService<FebeWebOptions>().Version, root.GetProperty("versione").GetString());
Assert.AreEqual("docker", root.GetProperty("edizione").GetString());
Assert.AreEqual(DiagnosticReport.ZoneName(server.Clock.LocalZone), root.GetProperty("fuso").GetString());
Assert.AreEqual(14, root.GetProperty("giorni").GetInt32());
Assert.AreEqual(2, root.GetProperty("righeRovinate").GetInt32(), "The report says what it misses.");
Assert.AreEqual(1, root.GetProperty("erroriRegistratore").GetInt32());
var session = root.GetProperty("sessioni").EnumerateArray().Single();
Assert.AreEqual(7, session.GetProperty("session").GetInt64());
Assert.AreEqual(nameof(SessionStopCause.BreakerOpen), session.GetProperty("stopCause").GetString());
Assert.AreEqual(1, root.GetProperty("fuoriSessione").GetArrayLength());
Assert.AreEqual(1, source.Calls);
}
[TestMethod]
public async Task TheWindowsLookSaysWindows()
{
await using var server = await Part2.StartAsync(FebeEdition.Desktop);
using var response = await server.Client.GetAsync(ActivityApi.DiagnosticsPath);
using var report = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.AreEqual("windows", report.RootElement.GetProperty("edizione").GetString());
}
[TestMethod]
public async Task WithoutARecorderTheReportIsThereAndEmpty()
{
await using var server = await Part2.StartAsync();
using var response = await server.Client.GetAsync(ActivityApi.DiagnosticsPath);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
using var report = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.AreEqual(0, report.RootElement.GetProperty("sessioni").GetArrayLength());
Assert.AreEqual(0, report.RootElement.GetProperty("fuoriSessione").GetArrayLength());
}
[TestMethod]
public async Task TheReportIsAnsweredEvenWithAConfigurationProblem()
{
CollectionAssert.Contains(ConfigurationGateMiddleware.AllowedApi.ToList(), ActivityApi.DiagnosticsPath);
var problem = new ConfigurationProblem("password-mancante", "Manca la password dell'interfaccia", "Spiegazione.", "Rimedio.");
await using var server = await Part2.StartAsync(services: s => s.AddSingleton<IConfigurationProblems>(new FixedProblems(problem)));
var (blocked, _, _) = await server.GetAsync("/api/duplicates/count");
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, blocked, "the gate is closed for the rest");
var (status, text, _) = await server.GetAsync(ActivityApi.DiagnosticsPath);
Assert.AreEqual(HttpStatusCode.OK, status, text);
using var report = JsonDocument.Parse(text);
Assert.AreEqual(DiagnosticReport.Title, report.RootElement.GetProperty("rapporto").GetString());
Assert.AreEqual(0, report.RootElement.GetProperty("sessioni").GetArrayLength(), "The engine never started.");
}
private static List<SessionTrace> Traces(DateTimeOffset now) =>
[
new SessionTrace
{
Session = 7,
Start = now - TimeSpan.FromMinutes(40),
End = now - TimeSpan.FromMinutes(30),
Outcome = SessionOutcome.Stopped,
StopCause = SessionStopCause.BreakerOpen,
Mood = 0.9,
Pages = [new PageVisit(now - TimeSpan.FromMinutes(39), SitePages.Home, "/", true)],
Signals = [new SignalLine(now - TimeSpan.FromMinutes(30), SignalLevel.Challenge, "challenge-url")],
},
new SessionTrace { Session = null, Start = now - TimeSpan.FromMinutes(20), InProgress = true },
];
private sealed class FixedDiagnostics : IDiagnosticSource
{
public IReadOnlyList<SessionTrace> Traces { get; set; } = [];
public int Calls { get; private set; }
public int DamagedLines { get; set; }
public int Faults { get; set; }
public Task<IReadOnlyList<SessionTrace>> ListAsync(CancellationToken ct)
{
Calls++;
return Task.FromResult(Traces);
}
public Task<DiagnosticCollection> GatherAsync(CancellationToken ct)
{
Calls++;
return Task.FromResult(new DiagnosticCollection(Traces, DamagedLines, Faults));
}
}
}