Files
Febe/src/Febe.Web/Demo/DemoDiagnostics.cs
T
Alby96andClaude Opus 5.5 badd1681a0
verifica / controlli (push) Successful in 18s
verifica / prove (push) Successful in 13m5s
verifica / installatore (push) Successful in 4m11s
verifica / immagine (push) Successful in 14m4s
Rapporto di diagnostica della raccolta (#39)
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>
2026-11-13 14:41:34 +01:00

235 lines
11 KiB
C#

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.Recipes;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Web.Engine;
using Microsoft.AspNetCore.Http;
namespace Febe.Web.Demo;
/// <summary>
/// The diagnostic report of the demo (issue #39): today's sessions of <see cref="DemoWorld"/> told as traces, with
/// counts that follow the session numbers. It follows the scene: «sessione» adds the session in progress, «fermo» ends
/// the last session with the verification (signal <c>challenge-url</c>, breaker open), «scollegato» and «errore» have
/// nothing (the engine never ran). Like the real report, it holds no name: patterns come from the site map and from
/// <see cref="PathPatterns"/>, every other value from a closed list.
/// </summary>
public sealed class DemoDiagnosticSource(IHttpContextAccessor accessor, DemoWorld world, IClock clock) : IDiagnosticSource
{
/// <summary>The verification of the scene «fermo» (spec §7.6, <c>segnali.json</c>).</summary>
public const string ChallengeCode = "challenge-url";
private const string Json = "application/json";
private const string Html = "text/html";
private static readonly SiteMap Map = SiteMap.LoadInstagram();
public Task<IReadOnlyList<SessionTrace>> ListAsync(CancellationToken ct) =>
Task.FromResult(Build(DemoRequest.Scene(accessor.HttpContext), clock.Now));
/// <summary>The traces of a scene at <paramref name="now"/>, oldest first.</summary>
public IReadOnlyList<SessionTrace> Build(DemoScene scene, DateTimeOffset now)
{
if (scene is DemoScene.Disconnected or DemoScene.Error)
{
return [];
}
var sessions = world.Today.Where(s => s.End <= now).ToList();
var traces = new List<SessionTrace>();
for (var i = 0; i < sessions.Count; i++)
{
var stopped = scene == DemoScene.Stopped && i == sessions.Count - 1;
traces.Add(Trace(i + 1, sessions[i], stopped ? Ending.Stopped : Ending.Finished, i));
}
if (scene == DemoScene.Session)
{
traces.Add(Trace(sessions.Count + 1, DemoEngine.CurrentSession(now), Ending.InProgress, sessions.Count));
}
if (sessions.Count > 0 && scene != DemoScene.Stopped)
{
traces.Add(Outside(sessions[0].End + TimeSpan.FromMinutes(3), sessions));
}
return [.. traces.OrderBy(t => t.Start)];
}
private enum Ending
{
Finished,
Stopped,
InProgress,
}
private static SessionTrace Trace(long id, DemoSession s, Ending ending, int index)
{
var profiles = Math.Max(1, s.ProfilesOpened);
var storyAccounts = s.StoriesViewed == 0 ? 0 : Math.Clamp(s.StoriesViewed / 3, 1, profiles + 2);
var stories = Math.Min(s.NewEntries, s.StoriesViewed);
var posts = s.NewEntries - stories;
var storyBytes = s.NewEntries == 0 ? 0 : s.Bytes * stories / s.NewEntries;
var stopped = ending == Ending.Stopped;
// Pages, spread over the session: the home, the profiles, the stories viewers.
var names = new List<string> { SitePages.Home };
names.AddRange(Enumerable.Repeat(SitePages.Profile, profiles));
names.AddRange(Enumerable.Repeat(SitePages.StoryViewer, storyAccounts));
var step = (s.End - s.Start) / (names.Count + 1);
var pages = names.Select((name, i) => new PageVisit(s.Start + (step * (i + 1)), name, Map.PatternOf(name), true)).ToList();
var navigations = new List<NavigationGroup>
{
new(HostKind.Site, SitePages.Home, Pattern(SitePages.Home), false, 1),
new(HostKind.Site, SitePages.Profile, Pattern(SitePages.Profile), false, profiles),
};
if (storyAccounts > 0)
{
navigations.Add(new(HostKind.Site, SitePages.StoryViewer, Pattern(SitePages.StoryViewer), true, s.StoriesViewed));
}
var dataCalls = (profiles * 3) + s.HistoryPages + 4;
var images = s.StoriesViewed + (profiles * 12);
var videos = s.StoriesViewed / 2;
var responses = new List<ResponseGroup>
{
Group(HostKind.Site, SitePages.Home, Pattern(SitePages.Home), "Document", Html, 1, 412_000) with { Recognized = 1, Contents = 6 },
Group(HostKind.Site, SitePages.Profile, Pattern(SitePages.Profile), "Document", Html, profiles, 388_000) with { Recognized = profiles, Profiles = profiles },
Group(HostKind.Site, null, PathPatterns.Of("/graphql/query"), "Fetch", Json, dataCalls, 24_000) with
{
Recognized = profiles + s.HistoryPages,
Empty = profiles / 4,
Unrelated = dataCalls - profiles - s.HistoryPages - (profiles / 4),
Contents = posts,
Profiles = profiles,
},
Group(HostKind.Site, null, PathPatterns.Of("/ajax/bulk-route-definitions/"), "Fetch", Json, profiles + 2, 3_000) with { Unrelated = profiles + 2 },
Group(HostKind.Cdn, null, "cdn *.jpg", "Image", "image/jpeg", images, 140_000) with { NotRead = images },
Group(HostKind.Other, null, CollectionDiagnostics.Other + " *.js", "Script", "application/javascript", 14, 220_000) with { NotRead = 14 },
};
if (storyAccounts > 0)
{
responses.Add(Group(HostKind.Site, null, PathPatterns.Of("/api/v1/feed/reels_media/"), "XHR", Json, storyAccounts, 36_000) with
{
Recognized = storyAccounts,
Contents = s.StoriesViewed,
});
}
if (videos > 0)
{
responses.Add(Group(HostKind.Cdn, null, "cdn *.mp4", "Media", "video/mp4", videos, 2_400_000) with { NotRead = videos });
}
var recipes = new List<RecipeLine> { new(s.Start + step, RecipeKind.FollowingSweep, RecipeStatus.Completed, null, 2 + storyAccounts, Math.Min(2, posts)) };
recipes.AddRange(Enumerable.Range(0, storyAccounts).Select(i => new RecipeLine(
s.Start + (step * (2 + profiles + i)), RecipeKind.AccountStories, RecipeStatus.Completed, null, 3, i == 0 ? stories : 0)));
recipes.AddRange(Enumerable.Range(0, profiles).Select(i => new RecipeLine(
s.Start + (step * (2 + i)), RecipeKind.ProfileCheck, RecipeStatus.Completed, null, 1, i == 0 ? Math.Max(0, posts - 2) : 0)));
var signals = new List<SignalLine>();
if (stopped)
{
// The last profile check met the verification page: stopped there, nothing after it.
var at = s.End - TimeSpan.FromSeconds(40);
var last = recipes.FindLastIndex(r => r.Kind == RecipeKind.ProfileCheck);
recipes[last] = recipes[last] with { At = at, Status = RecipeStatus.StoppedBySignal, Signal = ChallengeCode, NewEntries = 0 };
signals.Add(new SignalLine(at, SignalLevel.Challenge, ChallengeCode));
pages.Add(new PageVisit(at, SitePages.Profile, Map.PatternOf(SitePages.Profile), false));
navigations.Add(new(HostKind.Site, null, PathPatterns.Of("/challenge/"), false, 1));
responses.Add(Group(HostKind.Site, null, PathPatterns.Of("/challenge/"), "Document", Html, 1, 96_000) with { Unrelated = 1 });
}
var steps = new List<VerdictCount>
{
new(CollectionDiagnostics.VerdictRecognized, 1 + profiles + storyAccounts + s.HistoryPages),
};
if (profiles >= 4)
{
steps.Add(new(CollectionDiagnostics.VerdictEmpty, profiles / 4));
}
var targets = new List<TargetCount>();
if (storyAccounts > 0)
{
targets.Add(new(SiteTargets.HomeStory, TargetCheckStatus.Clicked, storyAccounts));
targets.Add(new(SiteTargets.ViewerNext, TargetCheckStatus.Clicked, Math.Max(0, s.StoriesViewed - storyAccounts)));
targets.Add(new(SiteTargets.ViewerClose, TargetCheckStatus.Clicked, storyAccounts));
}
var queued = new List<QueuedFiles>();
var downloads = new List<DownloadGroup>();
if (stories > 0)
{
queued.Add(new(EntryKind.Story, nameof(SaveOutcome.Created), stories, stories, 0));
downloads.Add(new(EntryKind.Story, DownloadStep.Stored, stories, storyBytes));
}
if (posts > 0)
{
queued.Add(new(EntryKind.Post, nameof(SaveOutcome.Created), posts, posts + (posts / 3), 0));
downloads.Add(new(EntryKind.Post, DownloadStep.Stored, posts + (posts / 3), s.Bytes - storyBytes));
}
queued.Add(new(EntryKind.Post, nameof(SaveOutcome.Known), profiles * 2, 0, 0));
return new SessionTrace
{
Session = id,
Start = s.Start,
End = ending == Ending.InProgress ? null : s.End,
Outcome = ending switch
{
Ending.Stopped => SessionOutcome.Stopped,
Ending.InProgress => SessionOutcome.Running,
_ => SessionOutcome.Completed,
},
StopCause = ending switch
{
Ending.Stopped => SessionStopCause.BreakerOpen,
Ending.InProgress => null,
_ => index % 3 == 2 ? SessionStopCause.WorkDone : SessionStopCause.PlannedEnd,
},
Mood = Math.Round(0.85 + (0.05 * (index % 4)), 2),
InProgress = ending == Ending.InProgress,
Pages = pages,
Navigations = navigations,
Responses = responses,
Steps = steps,
Targets = targets,
Recipes = recipes,
Signals = signals,
FilesQueued = queued,
Downloads = downloads,
DownloadedBytes = s.Bytes,
};
}
/// <summary>Today outside the sessions: files of the queue settled between two sessions.</summary>
private static SessionTrace Outside(DateTimeOffset start, IReadOnlyList<DemoSession> sessions)
{
var files = Math.Clamp(sessions.Sum(s => s.NewEntries) / 6, 1, 12);
return new SessionTrace
{
Session = null,
Start = start,
InProgress = true,
Downloads =
[
new(EntryKind.Post, DownloadStep.Stored, files, files * 1_900_000L),
new(EntryKind.Story, DownloadStep.Duplicate, 1, 0),
],
DownloadedBytes = files * 1_900_000L,
};
}
private static string Pattern(string page) => Map.PatternOf(page) ?? PathPatterns.Text;
private static ResponseGroup Group(HostKind host, string? page, string pattern, string resourceType, string mime, int count, long average) =>
new(host, page, pattern, resourceType, mime, "2xx", count, count * average, average + (average / 10), 0, 0, 0, 0, 0, 0, 0, 0, []);
}