Il browser di Febe a volte era bianco o non mostrava nulla. Le cause erano
diverse e si correggono insieme.
- Pagina iniziale. Se il browser è a riposo su about:blank e Alberto lo apre
(«Usa il browser», «Apri il browser»), Febe lo porta sulla home del sito
quando è collegato, altrimenti sulla pagina di accesso. È un'azione di
Alberto, sotto il suo permesso di guida, non del motore: Febe aspetta che
la sessione finisca e prende il turno della pagina.
Il nuovo pulsante «Pagina iniziale» sta nella barra della finestra di
Windows e nella vista remota. Su about:blank la barra dice «Il browser è a
riposo su una pagina vuota». «Indietro» non torna più sulla pagina di
riposo.
- Disconnessione. «Apri il browser» nella striscia rossa apre la pagina di
accesso. Con --accesso-di-prova il primo controllo all'avvio non segnala
più una disconnessione finta.
- Windows: la finestra resta.
- Lasciare una pagina di Febe non nasconde più la finestra «Browser di
Febe» e non la rimette a riposo: finisce solo il permesso tenuto dalla
pagina (cancel con pageLeft, IConnectionService.ReleaseAsync).
- Sullo schermo la finestra ha il suo pulsante nella barra delle
applicazioni, così ridurla a icona non la fa sparire. Dopo 2 minuti
ridotta a icona torna fuori vista (S2).
- Se lo schermo è troppo piccolo, la finestra si restringe all'area di
lavoro e la pagina si rimpicciolisce con ZoomFactor, con le stesse misure
CSS.
- I bordi della pagina si riapplicano, con NotifyParentWindowPositionChanged,
quando la finestra si mostra, si sposta o riparte il processo GPU.
- Una pagina che non risponde mentre Alberto guida resta com'è.
- IBrowserWindow.ShowAsync lascia il posto a
IConnectionService.ShowBrowserAsync.
- Docker: fotogrammi che ripartono. La vista remota ha un watchdog. Riavvia
i fotogrammi dopo una pagina nuova caricata senza fotogrammi e dopo circa
2 s di silenzio. L'attesa raddoppia fino a 30 s finché la pagina resta
ferma. Se il riavvio non porta nulla, la vista riceve un'immagine ferma
(Page.captureScreenshot, già fra i comandi ammessi).
RemoteViewSession ha ora un registro vero: avvii, riavvii e silenzi vanno
a livello Info, categoria «vista», senza indirizzi.
Se dopo 8 s non arriva nessuna immagine, l'interfaccia mostra «Nessuna
immagine dal browser» con «Riprova».
Nessun comando CDP nuovo e nessuna dipendenza nuova. Aggiornati PROTOCOLLO.md
e la guida (Primo collegamento, Attività e arresti, Installazione Windows,
Problemi comuni).
Prove nuove:
- ScreencastWatchdogTests, RemoteViewFramesTests (Chromium vero, solo CI
Linux)
- Home e Indietro in RemoteViewStartTests
- RemoteViewSocketTests
- ConnectionApiTests
- BrowserStartPageTests
- BrowserWindowDecisionTests e BrowserWindowTests (WebView2 vero)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
263 lines
9.4 KiB
C#
263 lines
9.4 KiB
C#
using System.Globalization;
|
|
using System.Text;
|
|
using System.Text.RegularExpressions;
|
|
using Febe.Browser.Diagnostics;
|
|
using Febe.Core.Abstractions;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Febe.App;
|
|
|
|
/// <summary>
|
|
/// The log of Febe, the same in both shells (spec §8.2, §13.2): one file per local day in <c>Dati/registro</c>
|
|
/// (<c>febe-AAAA-MM-GG.log</c>), kept fourteen days, at most 20 MB a day, and the same lines on the console, if any
|
|
/// (<c>docker logs</c>). Only actions and outcomes: every message passes through <see cref="Scrub"/>, which removes
|
|
/// addresses (signed CDN addresses, tokens); exceptions are written as type and first line only. Passwords, cookies,
|
|
/// keys and response bodies never reach this class.
|
|
/// </summary>
|
|
public sealed partial class FebeLog : IDisposable
|
|
{
|
|
public const int DefaultKeepDays = 14;
|
|
|
|
public const long DefaultMaxBytesPerDay = 20L * 1024 * 1024;
|
|
|
|
private const string Prefix = "febe-";
|
|
private const string Extension = ".log";
|
|
|
|
private readonly Lock _gate = new();
|
|
private readonly string? _folder;
|
|
private readonly TextWriter? _console;
|
|
private readonly IClock _clock;
|
|
private readonly int _keepDays;
|
|
private readonly long _maxBytesPerDay;
|
|
private StreamWriter? _file;
|
|
private DateOnly _day;
|
|
private long _written;
|
|
private bool _capped;
|
|
private bool _disposed;
|
|
|
|
/// <param name="folder">Dati/registro; null writes to the console only (configuration problems, tests).</param>
|
|
/// <param name="console">Console writer; null for none.</param>
|
|
/// <param name="clock">Time of the lines and of the daily file.</param>
|
|
/// <param name="keepDays">Days of files kept.</param>
|
|
/// <param name="maxBytesPerDay">Above this the day's file stops growing (the console still gets the lines).</param>
|
|
public FebeLog(string? folder, TextWriter? console, IClock clock, int keepDays = DefaultKeepDays, long maxBytesPerDay = DefaultMaxBytesPerDay)
|
|
{
|
|
_folder = folder is null ? null : Path.GetFullPath(folder);
|
|
_console = console;
|
|
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
|
_keepDays = Math.Max(1, keepDays);
|
|
_maxBytesPerDay = maxBytesPerDay;
|
|
}
|
|
|
|
/// <summary>Lowest level written to the console; the file gets everything from Information up.</summary>
|
|
public LogLevel ConsoleLevel { get; init; } = LogLevel.Information;
|
|
|
|
/// <summary>The log folder, when there is one.</summary>
|
|
public string? Folder => _folder;
|
|
|
|
public void Info(string source, string message) => Write(LogLevel.Information, source, message);
|
|
|
|
public void Warn(string source, string message, Exception? exception = null) => Write(LogLevel.Warning, source, message, exception);
|
|
|
|
public void Error(string source, string message, Exception? exception = null) => Write(LogLevel.Error, source, message, exception);
|
|
|
|
/// <summary>Writes one line. Never throws: a log that cannot be written must not stop Febe.</summary>
|
|
public void Write(LogLevel level, string source, string message, Exception? exception = null)
|
|
{
|
|
if (level < LogLevel.Information)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var now = _clock.Now;
|
|
var local = TimeZoneInfo.ConvertTime(now, _clock.LocalZone);
|
|
var text = Scrub(message);
|
|
if (exception is not null)
|
|
{
|
|
text += $" ({exception.GetType().Name}: {Scrub(FirstLine(exception.Message))})";
|
|
}
|
|
|
|
var line = string.Create(CultureInfo.InvariantCulture, $"{local:yyyy-MM-dd HH:mm:ss.fff zzz} {Label(level)} [{source}] {text}");
|
|
lock (_gate)
|
|
{
|
|
if (_disposed)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (_console is not null && level >= ConsoleLevel)
|
|
{
|
|
try
|
|
{
|
|
_console.WriteLine(line);
|
|
}
|
|
catch (IOException)
|
|
{
|
|
}
|
|
}
|
|
|
|
WriteFileLocked(DateOnly.FromDateTime(local.DateTime), line);
|
|
}
|
|
}
|
|
|
|
/// <summary>The adapter for the browser layer (it logs only CDP command names, states and counts).</summary>
|
|
/// <param name="category">The category of the lines (the remote view writes as «vista»).</param>
|
|
public IBrowserLog ForBrowser(string category = "browser") => new DelegateBrowserLog((level, message, exception) => Write(
|
|
level switch
|
|
{
|
|
BrowserLogLevel.Error => LogLevel.Error,
|
|
BrowserLogLevel.Warning => LogLevel.Warning,
|
|
BrowserLogLevel.Information => LogLevel.Information,
|
|
_ => LogLevel.Debug,
|
|
},
|
|
category,
|
|
message,
|
|
exception));
|
|
|
|
/// <summary>The adapter for ASP.NET Core (warnings and errors only; messages scrubbed like every other line).</summary>
|
|
public ILoggerProvider ForAspNet() => new Provider(this);
|
|
|
|
public void Dispose()
|
|
{
|
|
lock (_gate)
|
|
{
|
|
_disposed = true;
|
|
_file?.Dispose();
|
|
_file = null;
|
|
}
|
|
}
|
|
|
|
/// <summary>Removes addresses (anything like <c>scheme://…</c>) and line breaks from a message.</summary>
|
|
public static string Scrub(string? message)
|
|
{
|
|
if (string.IsNullOrEmpty(message))
|
|
{
|
|
return string.Empty;
|
|
}
|
|
|
|
var clean = Addresses().Replace(message, "<indirizzo>");
|
|
return clean.Replace('\r', ' ').Replace('\n', ' ');
|
|
}
|
|
|
|
/// <summary>Log files older than <paramref name="keepDays"/> days (today included) are removed; only <c>febe-*.log</c>.</summary>
|
|
public static IReadOnlyList<string> ApplyRetention(string folder, DateOnly today, int keepDays)
|
|
{
|
|
var removed = new List<string>();
|
|
if (!Directory.Exists(folder))
|
|
{
|
|
return removed;
|
|
}
|
|
|
|
var oldestKept = today.AddDays(-(Math.Max(1, keepDays) - 1));
|
|
foreach (var file in Directory.EnumerateFiles(folder, Prefix + "*" + Extension))
|
|
{
|
|
var name = Path.GetFileNameWithoutExtension(file);
|
|
if (DateOnly.TryParseExact(name[Prefix.Length..], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var day) && day < oldestKept)
|
|
{
|
|
try
|
|
{
|
|
File.Delete(file);
|
|
removed.Add(file);
|
|
}
|
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
|
{
|
|
}
|
|
}
|
|
}
|
|
|
|
return removed;
|
|
}
|
|
|
|
public static string FileNameFor(DateOnly day) => Prefix + day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + Extension;
|
|
|
|
private void WriteFileLocked(DateOnly day, string line)
|
|
{
|
|
if (_folder is null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
if (_file is null || day != _day)
|
|
{
|
|
_file?.Dispose();
|
|
_file = null;
|
|
Directory.CreateDirectory(_folder);
|
|
ApplyRetention(_folder, day, _keepDays);
|
|
var path = Path.Combine(_folder, FileNameFor(day));
|
|
var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read);
|
|
_written = stream.Length;
|
|
_file = new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = true };
|
|
_day = day;
|
|
_capped = false;
|
|
}
|
|
|
|
if (_capped)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (_written + line.Length + 1 > _maxBytesPerDay)
|
|
{
|
|
_file.WriteLine("Registro di oggi troppo lungo: le righe successive vanno solo sulla console.");
|
|
_capped = true;
|
|
return;
|
|
}
|
|
|
|
_file.WriteLine(line);
|
|
_written += Encoding.UTF8.GetByteCount(line) + 1;
|
|
}
|
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
|
{
|
|
// The disk is full or the folder went away: the console still has the line.
|
|
_file?.Dispose();
|
|
_file = null;
|
|
}
|
|
}
|
|
|
|
private static string Label(LogLevel level) => level switch
|
|
{
|
|
LogLevel.Critical or LogLevel.Error => "ERRORE ",
|
|
LogLevel.Warning => "AVVISO ",
|
|
_ => "INFO ",
|
|
};
|
|
|
|
private static string FirstLine(string text)
|
|
{
|
|
var line = text.Split('\n')[0].Trim();
|
|
return line.Length > 300 ? line[..300] : line;
|
|
}
|
|
|
|
[GeneratedRegex(@"\b[a-zA-Z][a-zA-Z0-9+.-]*://\S+", RegexOptions.CultureInvariant)]
|
|
private static partial Regex Addresses();
|
|
|
|
private sealed class Provider(FebeLog log) : ILoggerProvider
|
|
{
|
|
public ILogger CreateLogger(string categoryName) => new Logger(log, categoryName);
|
|
|
|
public void Dispose()
|
|
{
|
|
}
|
|
}
|
|
|
|
private sealed class Logger(FebeLog log, string category) : ILogger
|
|
{
|
|
public IDisposable? BeginScope<TState>(TState state)
|
|
where TState : notnull => null;
|
|
|
|
public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Warning;
|
|
|
|
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
|
{
|
|
if (!IsEnabled(logLevel))
|
|
{
|
|
return;
|
|
}
|
|
|
|
var source = category.StartsWith("Febe.", StringComparison.Ordinal) ? "web" : "aspnet";
|
|
log.Write(logLevel, source, formatter(state, exception), exception);
|
|
}
|
|
}
|
|
}
|