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>
This commit is contained in:
1 parent
bf03cb45a5
commit
badd1681a0
55 files changed
+5395
-134
No files matched your search
@@ -2,9 +2,11 @@ using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Web.Demo;
|
||||
using Febe.Web.Engine;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@@ -14,13 +16,20 @@ namespace Febe.Web.Api;
|
||||
|
||||
/// <summary>
|
||||
/// What the Attività page needs beside the engine snapshot (spec §7.6, §7.9, mockups 06 and 11): the history of the
|
||||
/// stops, the still frame of the browser, the probable duplicates waiting for Alberto.
|
||||
/// stops, the still frame of the browser, the probable duplicates waiting for Alberto, the diagnostic report.
|
||||
/// </summary>
|
||||
public static class ActivityApi
|
||||
{
|
||||
/// <summary>Days of stops shown by the page.</summary>
|
||||
public const int HistoryDays = 14;
|
||||
|
||||
/// <summary>
|
||||
/// «Esporta il rapporto di diagnostica» (issue #39, spec §7.9): the traces of the engine sessions of the last two
|
||||
/// weeks as a JSON file to send, with no data value in it. Also answered with a configuration problem, where the
|
||||
/// engine never started and the report is empty.
|
||||
/// </summary>
|
||||
public const string DiagnosticsPath = "/api/engine/diagnostica";
|
||||
|
||||
public static void Map(IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
endpoints.MapGet("/api/engine/incidents", async (IIncidentHistory history, IClock clock, CancellationToken ct) =>
|
||||
@@ -56,8 +65,37 @@ public static class ActivityApi
|
||||
var import = await storage.Duplicates.CountPendingAsync(DuplicateOrigin.Import, ct).ConfigureAwait(false);
|
||||
return ApiHttp.Json(new DuplicateCountsDto(download, import), FebeJsonContext.Default.DuplicateCountsDto);
|
||||
});
|
||||
|
||||
endpoints.MapGet(DiagnosticsPath, async (HttpContext context, IDiagnosticSource source, FebeWebOptions options, IClock clock, CancellationToken ct) =>
|
||||
{
|
||||
var gathered = await source.GatherAsync(ct).ConfigureAwait(false);
|
||||
var now = clock.Now;
|
||||
var zone = clock.LocalZone;
|
||||
var edition = options.Demo ? DemoRequest.Edition(context) ?? FebeEdition.Desktop : options.Edition;
|
||||
|
||||
// Written whole before answering: a failure becomes an error message, never half a file.
|
||||
using var buffer = new MemoryStream();
|
||||
DiagnosticReport.Write(
|
||||
buffer,
|
||||
gathered.Traces,
|
||||
new DiagnosticReportHeader(
|
||||
options.Version,
|
||||
EditionName(edition),
|
||||
now,
|
||||
zone,
|
||||
DamagedLines: gathered.DamagedLines,
|
||||
RecorderFaults: gathered.RecorderFaults,
|
||||
UnreadableFiles: gathered.UnreadableFiles,
|
||||
UnfinishedSessions: gathered.UnfinishedSessions));
|
||||
context.Response.Headers.ContentDisposition = $"attachment; filename=\"{DiagnosticReport.FileName(now, zone)}\"";
|
||||
context.Response.Headers.CacheControl = "no-store";
|
||||
return Results.Bytes(buffer.ToArray(), "application/json; charset=utf-8");
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>The «edizione» of the diagnostic report.</summary>
|
||||
public static string EditionName(FebeEdition edition) => edition == FebeEdition.Desktop ? "windows" : "docker";
|
||||
|
||||
public static async Task<IncidentListDto> IncidentsAsync(IIncidentHistory history, IClock clock, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(history);
|
||||
|
||||
@@ -44,9 +44,13 @@ public static class HealthEndpoint
|
||||
/// </summary>
|
||||
public sealed class ConfigurationGateMiddleware(RequestDelegate next, IConfigurationProblems problems)
|
||||
{
|
||||
/// <summary>API addresses still answered while there is a problem.</summary>
|
||||
/// <summary>
|
||||
/// API addresses still answered while there is a problem. The diagnostic report is among them, so that its address
|
||||
/// never answers with an error: it holds no data value, and with a configuration problem it is empty (the engine
|
||||
/// never started, nothing was recorded).
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyList<string> AllowedApi =
|
||||
["/api/capabilities", "/api/preferences", "/api/accesso", "/api/uscita", "/api/engine", "/api/eventi"];
|
||||
["/api/capabilities", "/api/preferences", "/api/accesso", "/api/uscita", "/api/engine", "/api/eventi", ActivityApi.DiagnosticsPath];
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
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, []);
|
||||
}
|
||||
@@ -30,6 +30,10 @@ public sealed class DemoEngine(IClock clock, DemoWorld world, IFebeStorage stora
|
||||
return sessions.Count > 0 ? sessions[^1].End - TimeSpan.FromSeconds(40) : now - TimeSpan.FromMinutes(25);
|
||||
}
|
||||
|
||||
/// <summary>The session in progress of the scene «sessione»: started two and a half minutes ago.</summary>
|
||||
public static DemoSession CurrentSession(DateTimeOffset now) =>
|
||||
new(now - TimeSpan.FromMinutes(2.5), now, 2, 6, 0, 18_000_000, 2);
|
||||
|
||||
public async Task<EngineSnapshot> GetSnapshotAsync(CancellationToken ct = default)
|
||||
{
|
||||
var scene = CurrentScene;
|
||||
@@ -40,9 +44,7 @@ public sealed class DemoEngine(IClock clock, DemoWorld world, IFebeStorage stora
|
||||
var inWindow = now >= world.WindowStart && now < world.WindowEnd;
|
||||
var sessions = scene is DemoScene.Disconnected or DemoScene.Error ? [] : world.Today.Where(s => s.End <= now).ToList();
|
||||
var stopAt = StopInstant(now);
|
||||
var current = scene == DemoScene.Session
|
||||
? new DemoSession(now - TimeSpan.FromMinutes(2.5), now, 2, 6, 0, 18_000_000, 2)
|
||||
: null;
|
||||
var current = scene == DemoScene.Session ? CurrentSession(now) : null;
|
||||
var accounts = await storage.Accounts.ListAsync(ct).ConfigureAwait(false);
|
||||
var marta = accounts.FirstOrDefault(a => a.Username == "marta.demo")?.Username ?? world.MineUsername;
|
||||
|
||||
|
||||
@@ -99,6 +99,7 @@ public sealed class DemoHost : IAsyncDisposable
|
||||
services.AddSingleton<IConnectionService, DemoConnectionService>();
|
||||
services.AddSingleton<IBrowserPreview, DemoBrowserPreview>();
|
||||
services.AddSingleton<IIncidentHistory, DemoIncidentHistory>();
|
||||
services.AddSingleton<IDiagnosticSource, DemoDiagnosticSource>();
|
||||
services.AddSingleton<IDataFolderChange, DemoDataFolderChange>();
|
||||
services.AddSingleton(demoImport);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
|
||||
namespace Febe.Web.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// The traces of the diagnostic report (issue #39) for «Esporta il rapporto di diagnostica» in Attività: the finished
|
||||
/// ones of the last two weeks and the ones in progress, oldest first. They hold no data value
|
||||
/// (<see cref="SessionTrace"/>).
|
||||
/// </summary>
|
||||
public interface IDiagnosticSource
|
||||
{
|
||||
Task<IReadOnlyList<SessionTrace>> ListAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// The traces with what the report must say about itself (damaged lines of the log, errors of the recorder). By
|
||||
/// default the traces of <see cref="ListAsync"/> with nothing lost.
|
||||
/// </summary>
|
||||
async Task<DiagnosticCollection> GatherAsync(CancellationToken ct) =>
|
||||
new(await ListAsync(ct).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
/// <summary>The traces of the recorder of the running Febe (its log in <c>Dati/diagnostica</c>, and what is open).</summary>
|
||||
public sealed class RecordedDiagnosticSource(CollectionDiagnostics diagnostics) : IDiagnosticSource
|
||||
{
|
||||
public Task<IReadOnlyList<SessionTrace>> ListAsync(CancellationToken ct) =>
|
||||
Task.Run(diagnostics.Collect, ct);
|
||||
|
||||
public Task<DiagnosticCollection> GatherAsync(CancellationToken ct) =>
|
||||
Task.Run(diagnostics.Gather, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The default when the composition registers no recorder (tests, a start with a configuration problem, where the
|
||||
/// engine never started): nothing was recorded, so the report has empty lists.
|
||||
/// </summary>
|
||||
public sealed class NoDiagnosticSource : IDiagnosticSource
|
||||
{
|
||||
public Task<IReadOnlyList<SessionTrace>> ListAsync(CancellationToken ct) =>
|
||||
Task.FromResult<IReadOnlyList<SessionTrace>>([]);
|
||||
}
|
||||
@@ -67,6 +67,7 @@ public static class FebeWeb
|
||||
services.TryAddSingleton<IConfigurationProblems, NoConfigurationProblems>();
|
||||
services.TryAddSingleton<IConnectionService, UnavailableConnectionService>();
|
||||
services.TryAddSingleton<IBrowserPreview, NoBrowserPreview>();
|
||||
services.TryAddSingleton<IDiagnosticSource, NoDiagnosticSource>();
|
||||
services.TryAddSingleton<IIncidentHistory>(sp => new StoredIncidentHistory(sp.GetRequiredService<IFebeStorage>()));
|
||||
services.TryAddSingleton<IAlertTestSender, NoTelegramSender>();
|
||||
services.TryAddSingleton<IDataFolderChange, FixedDataFolder>();
|
||||
|
||||
@@ -13,7 +13,7 @@ Qui sotto le convenzioni per chi continua il lavoro (composizione di Server e De
|
||||
| `Hosting/` | `EmbeddedWwwroot`: `IFileProvider` sulle risorse incorporate `wwwroot/…` (o su una cartella, per sviluppo) |
|
||||
| `Security/` | Controlli di §13.1: Host, Origin, gettone del desktop, password e blocco della veste Docker, intestazioni |
|
||||
| `Api/` | Endpoint minimi, DTO (`Dtos.cs`), contesto JSON generato (`FebeJsonContext`), conversioni (`ApiMapping`) |
|
||||
| `Engine/` | `IEngineControl` (comandi al motore), `EngineHostControl`, `OfflineEngine` (nessun motore), `BrowserUseTracker`, `IEngineSettingsControl` (limiti al motore), `IBrowserPreview` (anteprima), `IIncidentHistory` (incidenti) |
|
||||
| `Engine/` | `IEngineControl` (comandi al motore), `EngineHostControl`, `OfflineEngine` (nessun motore), `BrowserUseTracker`, `IEngineSettingsControl` (limiti al motore), `IBrowserPreview` (anteprima), `IIncidentHistory` (incidenti), `IDiagnosticSource` (rapporto di diagnostica) |
|
||||
| `Library/` | `FebeLibrary` (archivio + disposizione, `HashIndex`, `DownloadDuplicates`), `LibraryChanges`, esportazione CSV, collegamenti a Instagram, nomi utente, `IDataFolderChange`, `FolderSizes`, `RebuildJob` |
|
||||
| `Connection/` | Contratto condiviso con il lato server del collegamento: `IConnectionService`, `IConfigurationProblems`, `PROTOCOLLO.md` (vista remota `/api/vista`); `UnavailableConnectionService` è il ripiego |
|
||||
| `Import/` | `ImportHub`: l'`ImportService` registrato dalla composizione, oppure uno costruito sulla libreria |
|
||||
@@ -68,6 +68,7 @@ Tutti con un ripiego registrato con `TryAdd`; la composizione registra i propri
|
||||
| `IEngineSettingsControl` | `StoredEngineSettingsControl`: salva le impostazioni del motore nell'archivio | `new EngineHostSettingsControl(engineHost)`: le applica anche al motore che gira |
|
||||
| `IBrowserPreview` | `NoBrowserPreview` (nessuna anteprima) | Chi ha il browser: `GetLatestAsync` restituisce l'ultima schermata JPEG (`BrowserFrame`) con l'indirizzo |
|
||||
| `IIncidentHistory` | `StoredIncidentHistory` (dall'archivio) | Di solito nessuno |
|
||||
| `IDiagnosticSource` (`Engine/DiagnosticSource.cs`) | `NoDiagnosticSource`: niente registrato, il rapporto ha gli elenchi vuoti (prove, avvio con un problema di configurazione) | `Febe.App`: `RecordedDiagnosticSource` sul registratore `CollectionDiagnostics` (registro in `Dati/diagnostica`, 14 giorni, e sessioni in corso); dimostrazione: `DemoDiagnosticSource`, secondo la scena |
|
||||
| `IAlertTestSender` (Core) | `NoTelegramSender`: nessun messaggio parte (dimostrazione, prove), la risposta lo dice | La composizione (`Febe.App`, le due vesti): `TelegramAlertChannel` (Core, `Alerts/Telegram.cs`), lo stesso canale che usa `AlertService` |
|
||||
| `IDataFolderChange` | `FixedDataFolder`: la cartella dei dati non si cambia dall'interfaccia | Desktop: `DesktopDataFolderChange` registra la scelta e `DataFolderMove` sposta la cartella al prossimo avvio, con copia verificata (SHA-256) |
|
||||
| `ImportService` (Core) | `ImportHub` ne costruisce uno sulla libreria (Docker: solo sotto `FebeWebOptions.ImportRoot`, di serie `/importa`; desktop: qualsiasi cartella) | La composizione, se vuole opzioni diverse (ffmpeg, cartella sorgente) |
|
||||
@@ -119,6 +120,7 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe.
|
||||
| `GET /api/engine/incidents` | Incidenti degli ultimi 14 giorni (rallentamenti, verifiche, arresti), con un consiglio dopo 3 rallentamenti in 7 giorni |
|
||||
| `POST /api/engine/recipes/{ricetta}/resume` | «Riattiva» una ricetta sospesa dopo tre problemi di fila (`IEngineControl.ResumeRecipeAsync`: metodo con un'implementazione predefinita che risponde «non era sospesa», così le altre implementazioni non cambiano). Attività mostra le ricette sospese da `snapshot.suspendedRecipes` |
|
||||
| `GET /api/alerts` | Avvisi degli ultimi 14 giorni (§13.3, sezione «Avvisi» di Attività): righe della cronologia con i codici di `AlertCatalog.Codes`, compresi gli avvisi non arrivati |
|
||||
| `GET /api/engine/diagnostica` | «Esporta il rapporto di diagnostica» (issue #39, §7.9): file JSON `febe-diagnostica-aaaa-mm-gg.json` (giorno locale) in allegato, `no-store`, UTF-8 senza BOM, da `DiagnosticReport.Write` con le tracce di `IDiagnosticSource`. Nessun valore dei dati: solo conteggi, misure, orari, codici da elenchi chiusi e forme degli indirizzi. In testa `righeRovinate`, `erroriRegistratore`, `fileIlleggibili` e `sessioniSenzaFine` (`IDiagnosticSource.GatherAsync`). Risponde anche con un problema di configurazione (`ConfigurationGateMiddleware.AllowedApi`), con gli elenchi vuoti: il motore non è partito |
|
||||
| `GET /api/browser/preview`, `GET /api/browser/preview/frame` | Anteprima del browser in Attività: indirizzo e immagine JPEG (`no-store`, 404 se non c'è) |
|
||||
| `GET /api/duplicates/count`, `GET /api/duplicates?after=`, `POST /api/duplicates/{pairId}` (`{ decision, applyToAll }`) | Doppioni dopo uno scaricamento (§9.5): `keepLarger`, `keepExisting`, `keepBoth`; niente si decide da solo |
|
||||
| `GET/PUT /api/settings/general`, `POST /api/settings/naming-preview`, `/pick-folder`, `/data-folder` | Cartelle (cambio della libreria solo desktop), schema dei nomi con anteprima, tema, avvio, area di notifica |
|
||||
@@ -197,7 +199,7 @@ Moduli ES, nessuna dipendenza, nessuna build. Durante lo sviluppo si servono da
|
||||
- `text.js`: `t('chiave.sotto', { n, … })` (forme `singolare|plurale` scelte da `n`), `number` (punti delle migliaia),
|
||||
`decimal`, `bytes`, `duration`, `around` («verso le 15:30»), `ago` («2 ore fa»), `dayName`.
|
||||
- `api.js`: `api(percorso, { method, body, signal, raw })` (lancia `ApiError` con il messaggio italiano del server),
|
||||
`download`, `withCarried`. I parametri `scena`, `veste`, `tema` della dimostrazione restano negli indirizzi interni e
|
||||
`download(percorso, corpo, nomeDiRiserva)` (POST con il corpo; GET con corpo `null`), `withCarried`. I parametri `scena`, `veste`, `tema` della dimostrazione restano negli indirizzi interni e
|
||||
viaggiano verso l'API (intestazioni `X-Febe-Scena`, `X-Febe-Veste`).
|
||||
- `engine.js`: `onEngine`, `onLibrary`, `refreshEngine`. In dimostrazione niente SSE: si chiede il motore ogni 30 s
|
||||
(così le schermate senza finestra finiscono).
|
||||
@@ -230,8 +232,8 @@ scrive mai nella libreria vera e non usa la rete.
|
||||
di configurazione); tema: `?tema=chiaro|scuro`; veste: `?veste=desktop|windows|docker`.
|
||||
- Indirizzi diretti: `/account?dialogo=aggiungi`, `/account/3/impostazioni`, `/account/2?tipo=storie`,
|
||||
`/importa?passo=3` (revisione di un'importazione già analizzata), `/doppioni`, `/impostazioni/collegamento?scena=scollegato&veste=docker`.
|
||||
- Seconda parte (`Demo/DemoPart2.cs`, `Demo/DemoImport.cs`): collegamento, anteprima del browser e incidenti secondo la
|
||||
scena; tre doppioni dopo uno scaricamento; una sorgente da importare generata in `importa/Backup del vecchio disco`
|
||||
- Seconda parte (`Demo/DemoPart2.cs`, `Demo/DemoImport.cs`, `Demo/DemoDiagnostics.cs`): collegamento, anteprima del
|
||||
browser, incidenti e rapporto di diagnostica secondo la scena; tre doppioni dopo uno scaricamento; una sorgente da importare generata in `importa/Backup del vecchio disco`
|
||||
(copie identiche, varianti, cartelle senza account, file non riconosciuti) e già analizzata all'avvio.
|
||||
- I dati stanno in `Demo/DemoSeeder.cs` (`Specs`); le prove `tests/Febe.Tests/Web/DemoTests.cs` controllano che i
|
||||
conti tornino.
|
||||
|
||||
@@ -104,9 +104,12 @@ export function eventsUrl() {
|
||||
return withCarried('/api/eventi');
|
||||
}
|
||||
|
||||
/** Downloads an answer as a file (CSV export). */
|
||||
/**
|
||||
* Downloads an answer as a file: a POST with the body (CSV export), or a GET when the body is null (diagnostic report).
|
||||
* Through api(), so the carried scene and shell travel with it.
|
||||
*/
|
||||
export async function download(path, body, fallbackName) {
|
||||
const response = await api(path, { method: 'POST', body, raw: true });
|
||||
const response = await api(path, body === null ? { raw: true } : { method: 'POST', body, raw: true });
|
||||
const blob = await response.blob();
|
||||
const disposition = response.headers.get('Content-Disposition') || '';
|
||||
const match = /filename="?([^";]+)"?/.exec(disposition);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// ones that are not stops, like a backfill completed or a disk almost full). It updates by itself from the event
|
||||
// stream (the demo asks every 30 seconds). The red strip of a stop is drawn by the page frame.
|
||||
|
||||
import { api, withCarried } from '../core/api.js';
|
||||
import { api, download, withCarried } from '../core/api.js';
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
import { dotOf, refreshEngine } from '../core/engine.js';
|
||||
import { openBrowser } from '../core/shell.js';
|
||||
@@ -97,7 +97,39 @@ function drawActions(page, state) {
|
||||
: h('button.btn', {
|
||||
type: 'button', onclick: pause, disabled: ['Off', 'NotConnected'].includes(s.mode), 'aria-label': t('attivita.pausa'),
|
||||
}, icon('pause'), h('span.testo-btn', t('attivita.pausa')));
|
||||
page.actions(first, h('button.btn', { type: 'button', onclick: openBrowser, 'aria-label': t('attivita.apriBrowser') }, icon('app-window'), h('span.testo-btn', t('attivita.apriBrowser'))));
|
||||
page.actions(
|
||||
first,
|
||||
h('button.btn', { type: 'button', onclick: openBrowser, 'aria-label': t('attivita.apriBrowser') }, icon('app-window'), h('span.testo-btn', t('attivita.apriBrowser'))),
|
||||
diagnosticsButton(),
|
||||
);
|
||||
}
|
||||
|
||||
// True while a report is being exported. The title row is rebuilt at every engine update, so the button of the click
|
||||
// may be gone by the end: the flag, not the button, says whether an export is running.
|
||||
let exporting = false;
|
||||
|
||||
/** «Diagnostica»: the report of the last two weeks of sessions, with no name in it, to send after a test gone wrong (#39). */
|
||||
function diagnosticsButton() {
|
||||
const button = h('button.btn', {
|
||||
type: 'button', title: t('attivita.esportaDiagnostica'), 'aria-label': t('attivita.esportaDiagnostica'), disabled: exporting,
|
||||
}, icon('file-down'), h('span.testo-btn', t('attivita.diagnostica')));
|
||||
button.onclick = async () => {
|
||||
if (exporting) return;
|
||||
exporting = true;
|
||||
button.disabled = true;
|
||||
try {
|
||||
await download('/api/engine/diagnostica', null, 'febe-diagnostica.json');
|
||||
toast(t('attivita.diagnosticaEsportata'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
exporting = false;
|
||||
// The button on the page now, which may not be this one.
|
||||
for (const shown of document.querySelectorAll('[data-diagnostica]')) shown.disabled = false;
|
||||
}
|
||||
};
|
||||
button.dataset.diagnostica = '';
|
||||
return button;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------- now
|
||||
|
||||
@@ -496,6 +496,9 @@
|
||||
"pausa": "Metti in pausa",
|
||||
"riprendi": "Riprendi",
|
||||
"apriBrowser": "Apri il browser",
|
||||
"diagnostica": "Diagnostica",
|
||||
"esportaDiagnostica": "Esporta il rapporto di diagnostica",
|
||||
"diagnosticaEsportata": "Rapporto di diagnostica esportato: il file è nei download del browser. Contiene solo conteggi, tempi e forme degli indirizzi, nessun nome né contenuto: puoi mandarlo così com'è.",
|
||||
"anteprima": "Anteprima del browser di Febe",
|
||||
"anteprimaOra": "Immagine delle {ora}",
|
||||
"anteprimaVuota": "Il browser è sulla pagina vuota fino alla prossima sessione",
|
||||
|
||||
Reference in new issue
Block a user