Files
Febe/src/Febe.Web/Api/ActivityApi.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

181 lines
8.3 KiB
C#

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;
using Microsoft.AspNetCore.Routing;
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, 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) =>
ApiHttp.Json(await IncidentsAsync(history, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.IncidentListDto));
endpoints.MapGet("/api/alerts", async (IFebeStorage storage, IClock clock, CancellationToken ct) =>
ApiHttp.Json(await AlertsAsync(storage, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.AlertListDto));
endpoints.MapGet("/api/browser/preview", async (IBrowserPreview preview, CancellationToken ct) =>
{
var frame = await preview.GetLatestAsync(ct).ConfigureAwait(false);
var dto = frame is null
? new BrowserPreviewDto(false, null, null, null)
: new BrowserPreviewDto(true, WithoutQuery(frame.Url), frame.At.ToUnixTimeMilliseconds(), "/api/browser/preview/frame?v=" + frame.At.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture));
return ApiHttp.Json(dto, FebeJsonContext.Default.BrowserPreviewDto);
});
endpoints.MapGet("/api/browser/preview/frame", async (HttpContext context, IBrowserPreview preview, CancellationToken ct) =>
{
var frame = await preview.GetLatestAsync(ct).ConfigureAwait(false);
if (frame is null)
{
throw new NotFoundException("Nessuna immagine del browser in questo momento.");
}
context.Response.Headers.CacheControl = "no-store";
return Results.Bytes(frame.Jpeg, "image/jpeg");
});
endpoints.MapGet("/api/duplicates/count", async (IFebeStorage storage, CancellationToken ct) =>
{
var download = await storage.Duplicates.CountPendingAsync(DuplicateOrigin.Download, ct).ConfigureAwait(false);
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);
ArgumentNullException.ThrowIfNull(clock);
var now = clock.Now;
var zone = clock.LocalZone;
var items = await history.ListAsync(now - TimeSpan.FromDays(HistoryDays), now + TimeSpan.FromMinutes(1), ct).ConfigureAwait(false);
var dtos = items.Select(i => new IncidentDto(
i.Id,
ApiMapping.Local(i.At, now, zone),
Level(i.Level),
Title(i.Level),
i.Signal,
WithoutQuery(i.Url),
i.StoppedUntil is { } until ? ApiMapping.Local(until, now, zone) : null,
i.ResolvedAt is { } resolved ? ApiMapping.Local(resolved, now, zone) : null,
i.IsOpen,
i.Note)).ToList();
var throttles = items.Count(i => i.Level == SignalLevel.Throttle && i.At >= now - TimeSpan.FromDays(7));
var advice = throttles >= 3
? $"{ItalianText.Count(throttles, "rallentamento", "rallentamenti")} negli ultimi sette giorni: conviene passare a un profilo più prudente o seguire meno account (Impostazioni, Limiti e comportamento)."
: null;
return new IncidentListDto(dtos, throttles, advice);
}
/// <summary>The alerts of the last <see cref="HistoryDays"/> days (at most 50), from the timeline.</summary>
public static async Task<AlertListDto> AlertsAsync(IFebeStorage storage, IClock clock, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(clock);
var now = clock.Now;
var zone = clock.LocalZone;
var events = await storage.Events.ListAsync(
new EventQuery { From = now - TimeSpan.FromDays(HistoryDays), Codes = AlertCatalog.Codes, Limit = 50 },
ct).ConfigureAwait(false);
var items = events.Select(e =>
{
var kind = AlertCatalog.KindOf(e.Code);
return new AlertItemDto(
e.Id,
ApiMapping.Local(e.At, now, zone),
kind is { } k ? JsonNamingPolicy.CamelCase.ConvertName(k.ToString()) : "deliveryFailed",
e.Severity switch
{
EventSeverity.Error => "error",
EventSeverity.Warning => "warning",
EventSeverity.Success => "success",
_ => "info",
},
kind is { } known ? AlertCatalog.Title(known) : "Avviso non inviato",
kind is { } alert ? AlertCatalog.FromEvent(alert, e, zone).Message : e.Message,
e.AccountId);
}).ToList();
return new AlertListDto(items, HistoryDays);
}
public static string Level(SignalLevel level) => level switch
{
SignalLevel.Throttle => "throttle",
SignalLevel.Challenge => "challenge",
_ => "disconnect",
};
public static string Title(SignalLevel level) => level switch
{
SignalLevel.Throttle => "Rallentamento",
SignalLevel.Challenge => "Verifica richiesta",
_ => "Disconnessione",
};
/// <summary>An address without its query string and fragment (signed addresses never reach the page).</summary>
public static string? WithoutQuery(string? url)
{
if (string.IsNullOrWhiteSpace(url))
{
return null;
}
var cut = url.IndexOfAny(['?', '#']);
return cut < 0 ? url : url[..cut];
}
}