using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Febe.Core.Domain;
namespace Febe.Core.Collection.Diagnostics;
/// The head of an exported report.
/// Febe's version (three numbers).
/// «docker» or «windows».
/// When the report is written.
/// Alberto's time zone: the times of the report are written in it.
/// Days the log keeps.
/// Lines of the log that could not be read («righeRovinate»).
/// Errors the recorder swallowed, failed writes among them («erroriRegistratore»).
/// Day files of the log that could not be read («fileIlleggibili»).
/// Sessions Febe stopped without closing, a crash or a kill («sessioniSenzaFine»).
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);
///
/// 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.
///
public static partial class DiagnosticReport
{
/// The value of «rapporto».
public const string Title = "diagnostica della raccolta";
/// Name of the exported file for the local day of .
public static string FileName(DateTimeOffset now, TimeZoneInfo zone) =>
$"febe-diagnostica-{LocalCalendar.Today(now, zone).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}.json";
/// Writes the report to (left open).
/// Debug builds only: the text holds «://» or «@», which no reduction lets through.
public static void Write(Stream stream, IReadOnlyList 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 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();
}
/// The same trace with its times written in Alberto's zone (same instants, local offset).
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);
///
/// 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.
///
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();
}