Files
Febe/src/Febe.Core/Collection/Diagnostics/DiagnosticReport.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

140 lines
6.7 KiB
C#

using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Febe.Core.Domain;
namespace Febe.Core.Collection.Diagnostics;
/// <summary>The head of an exported report.</summary>
/// <param name="Version">Febe's version (three numbers).</param>
/// <param name="Edition">«docker» or «windows».</param>
/// <param name="Created">When the report is written.</param>
/// <param name="Zone">Alberto's time zone: the times of the report are written in it.</param>
/// <param name="Days">Days the log keeps.</param>
/// <param name="DamagedLines">Lines of the log that could not be read («righeRovinate»).</param>
/// <param name="RecorderFaults">Errors the recorder swallowed, failed writes among them («erroriRegistratore»).</param>
/// <param name="UnreadableFiles">Day files of the log that could not be read («fileIlleggibili»).</param>
/// <param name="UnfinishedSessions">Sessions Febe stopped without closing, a crash or a kill («sessioniSenzaFine»).</param>
public sealed record DiagnosticReportHeader(
string Version,
string Edition,
DateTimeOffset Created,
TimeZoneInfo Zone,
int Days = DiagnosticLog.DefaultDays,
int DamagedLines = 0,
int RecorderFaults = 0,
int UnreadableFiles = 0,
int UnfinishedSessions = 0);
/// <summary>
/// The file Alberto sends after a live test that went wrong (issue #39, «Esporta il rapporto di diagnostica»):
/// UTF-8 JSON without BOM, indented, with the traces of the engine sessions and of the days outside sessions. Like
/// the traces, it holds no data value: no address, user name, cookie, body or free text.
/// </summary>
public static partial class DiagnosticReport
{
/// <summary>The value of «rapporto».</summary>
public const string Title = "diagnostica della raccolta";
/// <summary>Name of the exported file for the local day of <paramref name="now"/>.</summary>
public static string FileName(DateTimeOffset now, TimeZoneInfo zone) =>
$"febe-diagnostica-{LocalCalendar.Today(now, zone).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}.json";
/// <summary>Writes the report to <paramref name="stream"/> (left open).</summary>
/// <exception cref="InvalidOperationException">Debug builds only: the text holds «://» or «@», which no reduction lets through.</exception>
public static void Write(Stream stream, IReadOnlyList<SessionTrace> traces, DiagnosticReportHeader header)
{
ArgumentNullException.ThrowIfNull(stream);
ArgumentNullException.ThrowIfNull(traces);
ArgumentNullException.ThrowIfNull(header);
var zone = header.Zone;
using var buffer = new MemoryStream();
using (var writer = new Utf8JsonWriter(buffer, new JsonWriterOptions { Indented = true }))
{
writer.WriteStartObject();
writer.WriteString("rapporto", Title);
writer.WriteString("versione", Safe(header.Version));
writer.WriteString("edizione", Safe(header.Edition));
writer.WriteString("creato", Local(header.Created, zone));
writer.WriteString("fuso", Safe(ZoneName(zone)));
writer.WriteNumber("giorni", header.Days);
// Not zero: the report is not the whole story (lines of the log lost, writes or readings that failed, day
// files that could not be read, sessions cut short by a crash).
writer.WriteNumber("righeRovinate", Math.Max(0, header.DamagedLines));
writer.WriteNumber("erroriRegistratore", Math.Max(0, header.RecorderFaults));
writer.WriteNumber("fileIlleggibili", Math.Max(0, header.UnreadableFiles));
writer.WriteNumber("sessioniSenzaFine", Math.Max(0, header.UnfinishedSessions));
WriteTraces(writer, "sessioni", traces.Where(t => t.Session is not null), zone);
WriteTraces(writer, "fuoriSessione", traces.Where(t => t.Session is null), zone);
writer.WriteEndObject();
}
#if DEBUG
var text = Encoding.UTF8.GetString(buffer.GetBuffer(), 0, (int)buffer.Length);
if (text.Contains("://", StringComparison.Ordinal) || text.Contains('@', StringComparison.Ordinal))
{
throw new InvalidOperationException("Il rapporto di diagnostica contiene un indirizzo o un nome: una riduzione non ha funzionato.");
}
#endif
buffer.Position = 0;
buffer.CopyTo(stream);
stream.WriteByte((byte)'\n');
}
private static void WriteTraces(Utf8JsonWriter writer, string name, IEnumerable<SessionTrace> traces, TimeZoneInfo zone)
{
writer.WriteStartArray(name);
foreach (var trace in traces.OrderBy(t => t.Start))
{
JsonSerializer.Serialize(writer, InZone(trace, zone), DiagnosticsJsonContext.Default.SessionTrace);
}
writer.WriteEndArray();
}
/// <summary>The same trace with its times written in Alberto's zone (same instants, local offset).</summary>
private static SessionTrace InZone(SessionTrace trace, TimeZoneInfo zone) => trace with
{
Start = Local(trace.Start, zone),
End = trace.End is { } end ? Local(end, zone) : null,
Pages = [.. trace.Pages.Select(p => p with { At = Local(p.At, zone) })],
Recipes = [.. trace.Recipes.Select(r => r with { At = Local(r.At, zone) })],
Signals = [.. trace.Signals.Select(s => s with { At = Local(s.At, zone) })],
};
private static DateTimeOffset Local(DateTimeOffset instant, TimeZoneInfo zone) => TimeZoneInfo.ConvertTime(instant, zone);
/// <summary>
/// The IANA name of the zone («Europe/Rome»), also on Windows, whose own names have spaces («W. Europe Standard
/// Time»), the one of the computer's region when the Windows name covers several («Europe/Rome» rather than
/// «Europe/Berlin» in Italy); the Windows name with its spaces as underscores when there is no IANA one.
/// </summary>
internal static string ZoneName(TimeZoneInfo zone)
{
string? region = null;
try
{
region = RegionInfo.CurrentRegion.TwoLetterISORegionName;
}
catch (ArgumentException)
{
// No region (invariant culture): the zone's main IANA name.
}
if (region is { Length: 2 } && TimeZoneInfo.TryConvertWindowsIdToIanaId(zone.Id, region, out var regional))
{
return regional;
}
return TimeZoneInfo.TryConvertWindowsIdToIanaId(zone.Id, out var iana) ? iana : zone.Id.Replace(' ', '_');
}
private static string Safe(string? text) => text is not null && SafeText().IsMatch(text) ? text : CollectionDiagnostics.Other;
[GeneratedRegex("^[A-Za-z0-9_./+-]{1,64}$", RegexOptions.CultureInvariant)]
private static partial Regex SafeText();
}