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;
///
/// The diagnostic report of the demo (issue #39): today's sessions of 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 challenge-url, 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
/// , every other value from a closed list.
///
public sealed class DemoDiagnosticSource(IHttpContextAccessor accessor, DemoWorld world, IClock clock) : IDiagnosticSource
{
/// The verification of the scene «fermo» (spec §7.6, segnali.json).
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> ListAsync(CancellationToken ct) =>
Task.FromResult(Build(DemoRequest.Scene(accessor.HttpContext), clock.Now));
/// The traces of a scene at , oldest first.
public IReadOnlyList 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();
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 { 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
{
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
{
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 { 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();
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
{
new(CollectionDiagnostics.VerdictRecognized, 1 + profiles + storyAccounts + s.HistoryPages),
};
if (profiles >= 4)
{
steps.Add(new(CollectionDiagnostics.VerdictEmpty, profiles / 4));
}
var targets = new List();
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();
var downloads = new List();
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,
};
}
/// Today outside the sessions: files of the queue settled between two sessions.
private static SessionTrace Outside(DateTimeOffset start, IReadOnlyList 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, []);
}