Misura delle prestazioni dell'interfaccia con 60 aste (#34)
I criteri della specifica §9.11 (frame, blocchi del thread, riga aggiornata entro 100 ms, riconnessione sotto i 2 s, nessun ridisegno della griglia con maniglie e finestra) non li misurava nessuno. Ora il simulatore prende --simulatore-aste N (solo con --simulatore): N aste in elenco, tre su quattro in Attiva, ciclo di 5 s e due autopuntate senza fine per asta, così almeno dieci aste stanno sempre sotto i 4 s; senza l'argomento il simulatore resta quello di sempre. tools/Mimante.Schermate ha la modalità --misura <secondi>, tutta via CDP: uno script nella pagina cronometra frame, compiti dell'interfaccia (timer, frame, eventi del puntatore, ResizeObserver) e messaggi del bot, chiude il canale per la riconnessione, trascina la maniglia e ridimensiona la finestra controllando che i <tr data-id> restino gli stessi nodi, che la griglia non scorra né si virtualizzi e che anche lì nessun compito blocchi il thread; scrive misura.json e misura.txt ed esce con 1 se un criterio vincolante fallisce (anche un solo compito lungo del browser) o la misura non vale (basta un campione con meno di dieci aste in finestra critica; la CPU si riporta soltanto). La password può venire da UI_PASSWORD. prove-a-mano.yml ha il lavoro «prestazioni», dopo carico e schermate per non dividere la CPU, e il commento sul mondo del simulatore è corretto. Le prove dei conti della misura stanno in tests/Mimante.Tests con un riferimento a tools/Mimante.Schermate che esiste solo se la cartella c'è: il contesto dell'immagine non ha tools/ e lì quelle prove restano fuori, così la costruzione dell'immagine non si rompe. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ea6ba27462
commit
d84d396f86
19 files changed
+1812
-43
No files matched your search
@@ -0,0 +1,95 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Mimante.Schermate;
|
||||
|
||||
/// <summary>
|
||||
/// Gli argomenti dello strumento. Tre modi: le schermate (<c><indirizzo> [password] <cartella></c>), le
|
||||
/// proposte grafiche (<c>--mockup [cartella]</c>) e la misura delle prestazioni (<c>--misura <secondi></c> con
|
||||
/// indirizzo e cartella). Senza password fra gli argomenti vale la variabile d'ambiente <c>UI_PASSWORD</c>, così
|
||||
/// la password non resta nella cronologia della shell.
|
||||
/// </summary>
|
||||
public sealed record Arguments
|
||||
{
|
||||
public const int MinMeasureSeconds = 10;
|
||||
public const int MaxMeasureSeconds = 3600;
|
||||
|
||||
public const string Usage = """
|
||||
Uso:
|
||||
Mimante.Schermate <indirizzo> [password] <cartella> [--messaggio]
|
||||
le schermate dell'interfaccia (il bot gira con --simulatore); esce con 1 se una pagina ha errori JavaScript
|
||||
Mimante.Schermate <indirizzo> [password] <cartella> --misura <secondi>
|
||||
la misura delle prestazioni della pagina Aste (specifica §9.11; il bot gira con --simulatore
|
||||
--simulatore-aste 60); scrive misura.json e misura.txt nella cartella; esce con 1 se un criterio
|
||||
vincolante fallisce o la misura non è valida
|
||||
Mimante.Schermate --mockup [cartella]
|
||||
le proposte grafiche di docs/mockup (predefinita docs/mockup/redesign)
|
||||
|
||||
Senza password fra gli argomenti si usa la variabile d'ambiente UI_PASSWORD.
|
||||
Un percorso relativo vale dalla radice del repository.
|
||||
""";
|
||||
|
||||
public bool Help { get; init; }
|
||||
public bool Mockup { get; init; }
|
||||
public bool Message { get; init; }
|
||||
public int? MeasureSeconds { get; init; }
|
||||
public string BaseUrl { get; init; } = "";
|
||||
public string Password { get; init; } = "";
|
||||
public string OutputDir { get; init; } = "";
|
||||
|
||||
/// <summary>Legge gli argomenti; <paramref name="error"/> dice cosa non va (null = tutto a posto).</summary>
|
||||
public static Arguments Parse(IReadOnlyList<string> args, Func<string, string?> env, out string? error)
|
||||
{
|
||||
error = null;
|
||||
if (args.Any(a => a is "--help" or "-h" or "/?")) return new Arguments { Help = true };
|
||||
|
||||
int? seconds = null;
|
||||
var positional = new List<string>();
|
||||
for (var i = 0; i < args.Count; i++)
|
||||
{
|
||||
var a = args[i];
|
||||
if (a == "--misura")
|
||||
{
|
||||
if (i + 1 >= args.Count || !int.TryParse(args[i + 1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var s)
|
||||
|| s is < MinMeasureSeconds or > MaxMeasureSeconds)
|
||||
{
|
||||
error = $"--misura vuole la durata della misura in secondi, da {MinMeasureSeconds} a {MaxMeasureSeconds}";
|
||||
return new Arguments();
|
||||
}
|
||||
seconds = s;
|
||||
i++;
|
||||
}
|
||||
else if (!a.StartsWith("--", StringComparison.Ordinal)) positional.Add(a);
|
||||
}
|
||||
|
||||
if (args.Contains("--mockup"))
|
||||
{
|
||||
if (seconds != null) error = "--mockup e --misura non vanno insieme";
|
||||
return new Arguments { Mockup = true, OutputDir = positional.FirstOrDefault() ?? "docs/mockup/redesign" };
|
||||
}
|
||||
|
||||
string url, password, dir;
|
||||
switch (positional.Count)
|
||||
{
|
||||
case 3:
|
||||
(url, password, dir) = (positional[0], positional[1], positional[2]);
|
||||
break;
|
||||
case 2:
|
||||
(url, dir) = (positional[0], positional[1]);
|
||||
password = env("UI_PASSWORD") ?? "";
|
||||
if (password.Length == 0) error = "manca la password dell'interfaccia: passala come argomento o nella variabile UI_PASSWORD";
|
||||
break;
|
||||
default:
|
||||
error = "servono l'indirizzo del bot e la cartella d'uscita";
|
||||
return new Arguments();
|
||||
}
|
||||
|
||||
return new Arguments
|
||||
{
|
||||
BaseUrl = url.TrimEnd('/'),
|
||||
Password = password,
|
||||
OutputDir = dir,
|
||||
MeasureSeconds = seconds,
|
||||
Message = args.Contains("--messaggio")
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Mimante.Schermate.Misura;
|
||||
|
||||
/// <summary>
|
||||
/// I criteri di accettazione delle prestazioni dell'interfaccia (specifica §9.11) e le soglie della misura. La CPU si
|
||||
/// riporta ma non decide: Chromium senza finestra e senza GPU in CI non è un portatile medio.
|
||||
/// </summary>
|
||||
public static class PerfCriteria
|
||||
{
|
||||
/// <summary>Aste in elenco perché la misura valga.</summary>
|
||||
public const int MinListed = 60;
|
||||
|
||||
/// <summary>Aste in Attiva con il countdown sotto i 4 s, in ogni campione: un campione con meno rende la misura non valida.</summary>
|
||||
public const int MinCritical = 10;
|
||||
|
||||
/// <summary>La finestra critica: countdown sotto questi millisecondi.</summary>
|
||||
public const double CriticalMs = 4000;
|
||||
|
||||
/// <summary>
|
||||
/// Righe disegnate al più durante maniglia e finestra: oltre, la griglia si virtualizza (<c>virtualizeOver</c> di
|
||||
/// <c>wwwroot/js/grid.js</c>) e la prova dei nodi non dice più ciò che deve.
|
||||
/// </summary>
|
||||
public const int MaxDrawnRows = 60;
|
||||
|
||||
/// <summary>Di quanto può scorrere la griglia durante il trascinamento della maniglia (arrotondamenti del browser).</summary>
|
||||
public const double MaxScrollPx = 1;
|
||||
|
||||
/// <summary>CPU della scheda, in percento di un core (non vincolante).</summary>
|
||||
public const double MaxCpuPercent = 15;
|
||||
|
||||
/// <summary>Frame persi ammessi nei countdown.</summary>
|
||||
public const int MaxLostFrames = 0;
|
||||
|
||||
/// <summary>Un intervallo fra due frame oltre 1,5 frame è un frame perso.</summary>
|
||||
public const double LostFrameFactor = 1.5;
|
||||
|
||||
/// <summary>Il blocco più lungo ammesso del thread dell'interfaccia.</summary>
|
||||
public const double MaxBlockMs = 16;
|
||||
|
||||
/// <summary>Dal messaggio del bot alla riga aggiornata a schermo.</summary>
|
||||
public const double MaxRowUpdateMs = 100;
|
||||
|
||||
/// <summary>Dalla chiusura del canale al nuovo elenco a schermo.</summary>
|
||||
public const double MaxReconnectMs = 2000;
|
||||
|
||||
/// <summary>Quante volte si chiude il canale per misurare la riconnessione.</summary>
|
||||
public const int ReconnectTrials = 3;
|
||||
|
||||
/// <summary>Di quanto deve muoversi il pannello perché il trascinamento della maniglia valga.</summary>
|
||||
public const double MinHandleMovePx = 20;
|
||||
}
|
||||
|
||||
/// <summary>Un campione al secondo della pagina Aste durante la misura.</summary>
|
||||
public sealed record PerfSample(int Listed, int Active, int Critical, int Drawn, bool Connected);
|
||||
|
||||
/// <summary>Il riassunto dei campioni: quante aste c'erano in elenco e quante in finestra critica.</summary>
|
||||
public sealed record SampleStats(int Count, int MinListed, int MinCritical, double MedianCritical, double CriticalShare, int MaxDrawn);
|
||||
|
||||
/// <summary>
|
||||
/// I frame di una fase: la durata di un frame, i frame persi e quanto è arrivato in ritardo il frame peggiore
|
||||
/// (<see cref="Blocks"/>: frame in ritardo oltre la soglia; è un limite superiore del blocco del thread, perché anche il
|
||||
/// compositore senza GPU salta un frame da solo).
|
||||
/// </summary>
|
||||
public sealed record FrameStats(int Intervals, double FrameMs, int LostFrames, double WorstGapMs, int Blocks, double WorstBlockMs);
|
||||
|
||||
/// <summary>Una distribuzione di tempi in millisecondi, con quanti superano il limite.</summary>
|
||||
public sealed record Distribution(int Count, double P50, double P95, double P99, double Max, int Over);
|
||||
|
||||
/// <summary>
|
||||
/// Le righe della griglia prima e dopo un trascinamento o un ridimensionamento: un <c><tr data-id></c> ancora
|
||||
/// in vista dev'essere lo stesso nodo. Righe entrate o uscite per lo scorrimento virtuale non contano.
|
||||
/// </summary>
|
||||
public sealed record RowIdentity(int Before, int After, int Kept, IReadOnlyList<string> Replaced, IReadOnlyList<string> Duplicated)
|
||||
{
|
||||
public bool Intact => Replaced.Count == 0 && Duplicated.Count == 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// La griglia durante una fase con le maniglie o con la finestra: di quanto è scorsa al massimo dal punto di partenza,
|
||||
/// quante righe ha disegnato al massimo e se si è virtualizzata (righe spaziatrici).
|
||||
/// </summary>
|
||||
public sealed record GridState(double ScrollMovedPx, int MaxDrawn, bool Virtual);
|
||||
|
||||
/// <summary>
|
||||
/// Una fase con le maniglie o con la finestra: righe, frame (solo riportati: gli eventi via DevTools non seguono il
|
||||
/// ritmo dei frame), compiti dell'interfaccia e compiti lunghi del browser (vincolanti come nella misura), di quanto si
|
||||
/// è mosso il pannello e la griglia.
|
||||
/// </summary>
|
||||
public sealed record GesturePhase(RowIdentity Rows, FrameStats Frames, Distribution Tasks, IReadOnlyList<double> LongTasksMs, double MovedPx, GridState Grid);
|
||||
|
||||
/// <summary>Un criterio: vincolante o solo riportato, superato o no, con il valore misurato e il limite.</summary>
|
||||
public sealed record PerfCheck(string Key, string Label, bool Binding, bool Passed, string Value, string Limit);
|
||||
|
||||
/// <summary>Tutto ciò che la misura ha raccolto, prima del giudizio.</summary>
|
||||
public sealed record PerfInputs
|
||||
{
|
||||
public required int Seconds { get; init; }
|
||||
public required IReadOnlyList<PerfSample> Samples { get; init; }
|
||||
public required IReadOnlyList<double> FrameIntervals { get; init; }
|
||||
public required IReadOnlyList<double> RowUpdatesMs { get; init; }
|
||||
public required IReadOnlyList<double> HandlersMs { get; init; }
|
||||
|
||||
/// <summary>Le funzioni date dall'interfaccia a timer e <c>requestAnimationFrame</c>, cronometrate una per una.</summary>
|
||||
public required IReadOnlyList<double> TasksMs { get; init; }
|
||||
|
||||
public required IReadOnlyList<double> LongTasksMs { get; init; }
|
||||
public double? CpuPercent { get; init; }
|
||||
public required GesturePhase Drag { get; init; }
|
||||
public required GesturePhase Resize { get; init; }
|
||||
public required IReadOnlyList<double?> ReconnectsMs { get; init; }
|
||||
public required IReadOnlyList<string> Errors { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Il risultato: i criteri, se la misura vale e, se non vale, perché.</summary>
|
||||
public sealed record PerfReport
|
||||
{
|
||||
public required DateTimeOffset At { get; init; }
|
||||
public required string Url { get; init; }
|
||||
public required int Seconds { get; init; }
|
||||
public required SampleStats Samples { get; init; }
|
||||
public required FrameStats Frames { get; init; }
|
||||
public required Distribution RowUpdate { get; init; }
|
||||
public required Distribution Handler { get; init; }
|
||||
|
||||
/// <summary>Tutti i compiti dell'interfaccia: messaggi del bot, timer, frame (i blocchi del thread).</summary>
|
||||
public required Distribution Tasks { get; init; }
|
||||
|
||||
public required int LongTasks { get; init; }
|
||||
public required double LongestTaskMs { get; init; }
|
||||
public double? CpuPercent { get; init; }
|
||||
public required GesturePhase Drag { get; init; }
|
||||
public required GesturePhase Resize { get; init; }
|
||||
public required IReadOnlyList<double?> ReconnectsMs { get; init; }
|
||||
public required IReadOnlyList<string> Errors { get; init; }
|
||||
public required IReadOnlyList<PerfCheck> Checks { get; init; }
|
||||
public required bool Valid { get; init; }
|
||||
public required IReadOnlyList<string> InvalidReasons { get; init; }
|
||||
|
||||
/// <summary>La misura vale e ogni criterio vincolante è superato.</summary>
|
||||
public bool Passed => Valid && Checks.All(c => !c.Binding || c.Passed);
|
||||
|
||||
/// <summary>0 = superata; 1 = un criterio vincolante fallito o misura non valida.</summary>
|
||||
public int ExitCode => Passed ? 0 : 1;
|
||||
}
|
||||
|
||||
/// <summary>I conti della misura: logica pura, senza browser (provata in <c>PerfAnalysisTests</c>).</summary>
|
||||
public static class PerfAnalysis
|
||||
{
|
||||
/// <summary>
|
||||
/// I frame da una serie di intervalli fra due <c>requestAnimationFrame</c>. La durata di un frame è la mediana
|
||||
/// (16,7 ms a 60 Hz); un intervallo oltre 1,5 frame ne ha persi tanti quanti ne mancano; il blocco del thread è
|
||||
/// quanto un intervallo supera un frame (un compito di 40 ms ritarda il frame di 40 ms).
|
||||
/// </summary>
|
||||
public static FrameStats Frames(IReadOnlyList<double> intervals, double blockLimitMs = PerfCriteria.MaxBlockMs)
|
||||
{
|
||||
var valid = intervals.Where(d => d > 0 && double.IsFinite(d)).ToList();
|
||||
if (valid.Count == 0) return new FrameStats(0, 0, 0, 0, 0, 0);
|
||||
var frame = Percentile(valid, 0.5);
|
||||
int lost = 0, blocks = 0;
|
||||
double worstBlock = 0;
|
||||
foreach (var d in valid)
|
||||
{
|
||||
if (d > frame * PerfCriteria.LostFrameFactor) lost += Math.Max(1, (int)Math.Round(d / frame) - 1);
|
||||
var block = d - frame;
|
||||
if (block > blockLimitMs) blocks++;
|
||||
worstBlock = Math.Max(worstBlock, block);
|
||||
}
|
||||
return new FrameStats(valid.Count, Round(frame), lost, Round(valid.Max()), blocks, Round(Math.Max(0, worstBlock)));
|
||||
}
|
||||
|
||||
/// <summary>Mediana, 95° e 99° percentile, massimo e quanti valori superano <paramref name="limit"/>.</summary>
|
||||
public static Distribution Distribution(IReadOnlyList<double> values, double limit)
|
||||
{
|
||||
var v = values.Where(double.IsFinite).ToList();
|
||||
if (v.Count == 0) return new Distribution(0, 0, 0, 0, 0, 0);
|
||||
return new Distribution(v.Count, Round(Percentile(v, 0.5)), Round(Percentile(v, 0.95)), Round(Percentile(v, 0.99)), Round(v.Max()),
|
||||
v.Count(x => x > limit));
|
||||
}
|
||||
|
||||
/// <summary>Percentile con il metodo del rango più vicino (0 < <paramref name="p"/> ≤ 1).</summary>
|
||||
public static double Percentile(IReadOnlyList<double> values, double p)
|
||||
{
|
||||
if (values.Count == 0) return 0;
|
||||
var sorted = values.Order().ToArray();
|
||||
var rank = (int)Math.Ceiling(p * sorted.Length);
|
||||
return sorted[Math.Clamp(rank - 1, 0, sorted.Length - 1)];
|
||||
}
|
||||
|
||||
public static SampleStats Samples(IReadOnlyList<PerfSample> samples)
|
||||
{
|
||||
if (samples.Count == 0) return new SampleStats(0, 0, 0, 0, 0, 0);
|
||||
var critical = samples.Select(s => (double)s.Critical).ToList();
|
||||
return new SampleStats(samples.Count, samples.Min(s => s.Listed), samples.Min(s => s.Critical), Percentile(critical, 0.5),
|
||||
Math.Round((double)samples.Count(s => s.Critical >= PerfCriteria.MinCritical) / samples.Count, 3), samples.Max(s => s.Drawn));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Confronta le righe disegnate prima e dopo: ogni riga è (id, segno del nodo), dove il segno lo dà la pagina al
|
||||
/// nodo la prima volta che lo vede. Stesso id con un segno diverso = la riga è stata ridisegnata; lo stesso id due
|
||||
/// volte = una riga doppia. Le righe che ci sono solo prima o solo dopo (scorrimento virtuale, asta nuova) no.
|
||||
/// </summary>
|
||||
public static RowIdentity CompareRows(IReadOnlyList<(string Id, long Token)> before, IReadOnlyList<(string Id, long Token)> after)
|
||||
{
|
||||
var duplicated = after.GroupBy(r => r.Id).Where(g => g.Count() > 1).Select(g => g.Key).Order(StringComparer.Ordinal).ToList();
|
||||
var was = new Dictionary<string, long>(StringComparer.Ordinal);
|
||||
foreach (var (id, token) in before) was.TryAdd(id, token);
|
||||
int kept = 0;
|
||||
var replaced = new SortedSet<string>(StringComparer.Ordinal);
|
||||
foreach (var (id, token) in after)
|
||||
{
|
||||
if (!was.TryGetValue(id, out var old)) continue;
|
||||
if (old == token) kept++;
|
||||
else replaced.Add(id);
|
||||
}
|
||||
return new RowIdentity(before.Count, after.Count, kept, replaced.ToList(), duplicated);
|
||||
}
|
||||
|
||||
/// <summary>I compiti dell'interfaccia di una fase: la gestione dei messaggi più timer, frame, eventi e osservatori.</summary>
|
||||
public static Distribution Tasks(IReadOnlyList<double> handlers, IReadOnlyList<double> tasks) =>
|
||||
Distribution([.. handlers, .. tasks], PerfCriteria.MaxBlockMs);
|
||||
|
||||
/// <summary>
|
||||
/// La griglia da una serie di osservazioni (scorrimento verticale, righe disegnate, virtualizzata) prese durante una
|
||||
/// fase, la prima al punto di partenza.
|
||||
/// </summary>
|
||||
public static GridState Grid(IReadOnlyList<(double Scroll, int Drawn, bool Virtual)> seen)
|
||||
{
|
||||
if (seen.Count == 0) return new GridState(0, 0, false);
|
||||
var start = seen[0].Scroll;
|
||||
return new GridState(Round(seen.Max(s => Math.Abs(s.Scroll - start))), seen.Max(s => s.Drawn), seen.Any(s => s.Virtual));
|
||||
}
|
||||
|
||||
/// <summary>Il giudizio: se la misura vale e, criterio per criterio, se è superato.</summary>
|
||||
public static PerfReport Evaluate(PerfInputs input, string url, DateTimeOffset at)
|
||||
{
|
||||
var samples = Samples(input.Samples);
|
||||
var frames = Frames(input.FrameIntervals);
|
||||
var rows = Distribution(input.RowUpdatesMs, PerfCriteria.MaxRowUpdateMs);
|
||||
var handlers = Distribution(input.HandlersMs, PerfCriteria.MaxBlockMs);
|
||||
var tasks = Tasks(input.HandlersMs, input.TasksMs);
|
||||
|
||||
var invalid = new List<string>();
|
||||
if (samples.Count == 0) invalid.Add("nessun campione della pagina Aste");
|
||||
else
|
||||
{
|
||||
if (samples.MinListed < PerfCriteria.MinListed)
|
||||
invalid.Add($"in elenco fino a {samples.MinListed} aste, ne servono almeno {PerfCriteria.MinListed} (bot con --simulatore --simulatore-aste 60)");
|
||||
if (samples.MinCritical < PerfCriteria.MinCritical)
|
||||
invalid.Add($"in almeno un campione solo {samples.MinCritical} aste in Attiva sotto i 4 s, ne servono {PerfCriteria.MinCritical} " +
|
||||
$"in ogni campione (mediana {Num(samples.MedianCritical)}, almeno {PerfCriteria.MinCritical} nel {Pct(samples.CriticalShare)} dei campioni)");
|
||||
if (input.Samples.Any(s => !s.Connected)) invalid.Add("il canale con il bot è caduto durante la misura");
|
||||
}
|
||||
if (frames.Intervals < input.Seconds * 10) invalid.Add($"solo {frames.Intervals} frame in {input.Seconds} s: requestAnimationFrame non gira");
|
||||
if (rows.Count == 0) invalid.Add("nessun aggiornamento di riga dal bot durante la misura");
|
||||
if (input.Drag.MovedPx < PerfCriteria.MinHandleMovePx) invalid.Add($"la maniglia del pannello si è mossa di {Num(input.Drag.MovedPx)} px");
|
||||
if (input.Drag.Grid.ScrollMovedPx > PerfCriteria.MaxScrollPx)
|
||||
invalid.Add($"la griglia è scorsa di {Num(input.Drag.Grid.ScrollMovedPx)} px durante il trascinamento della maniglia");
|
||||
if (input.Drag.Rows.After == 0) invalid.Add("nessuna riga in vista dopo il trascinamento della maniglia");
|
||||
if (input.Resize.Rows.After == 0) invalid.Add("nessuna riga in vista dopo il ridimensionamento");
|
||||
foreach (var (name, phase) in new[] { ("il trascinamento della maniglia", input.Drag), ("il ridimensionamento", input.Resize) })
|
||||
{
|
||||
if (phase.Grid.Virtual)
|
||||
invalid.Add($"durante {name} la griglia era virtualizzata (più di {PerfCriteria.MaxDrawnRows} aste in elenco?): la prova delle righe non vale");
|
||||
else if (phase.Grid.MaxDrawn > PerfCriteria.MaxDrawnRows)
|
||||
invalid.Add($"durante {name} la griglia aveva {phase.Grid.MaxDrawn} righe disegnate, al più {PerfCriteria.MaxDrawnRows}");
|
||||
}
|
||||
|
||||
var reconnects = input.ReconnectsMs;
|
||||
var worstReconnect = reconnects.Count > 0 && reconnects.All(r => r != null) ? reconnects.Max(r => r!.Value) : (double?)null;
|
||||
var longTasks = input.LongTasksMs.Count + input.Drag.LongTasksMs.Count + input.Resize.LongTasksMs.Count;
|
||||
var blocksPassed = tasks.Count > 0 && tasks.Over == 0 && input.Drag.Tasks.Over == 0 && input.Resize.Tasks.Over == 0 && longTasks == 0;
|
||||
|
||||
var checks = new List<PerfCheck>
|
||||
{
|
||||
new("cpu", "CPU della scheda", false, input.CpuPercent is { } cpu && cpu < PerfCriteria.MaxCpuPercent,
|
||||
input.CpuPercent is { } c ? Num(c) + " %" : "non misurata", $"< {Num(PerfCriteria.MaxCpuPercent)} % (solo riportata: Chromium senza GPU)"),
|
||||
new("frames", "Frame persi nei countdown", true, frames.LostFrames <= PerfCriteria.MaxLostFrames,
|
||||
$"{frames.LostFrames} su {frames.Intervals} (frame di {Num(frames.FrameMs)} ms, intervallo peggiore {Num(frames.WorstGapMs)} ms)",
|
||||
$"{PerfCriteria.MaxLostFrames} (intervallo oltre {Num(PerfCriteria.LostFrameFactor)} frame)"),
|
||||
new("blocks", "Blocchi del thread dell'interfaccia", true, blocksPassed,
|
||||
$"misura {TasksText(tasks)}; maniglia {TasksText(input.Drag.Tasks)}; finestra {TasksText(input.Resize.Tasks)}; " +
|
||||
$"compiti lunghi del browser (oltre 50 ms) {input.LongTasksMs.Count} + {input.Drag.LongTasksMs.Count} + {input.Resize.LongTasksMs.Count}",
|
||||
$"nessuno oltre {Num(PerfCriteria.MaxBlockMs)} ms e nessun compito lungo, in tutte e tre le fasi"),
|
||||
new("row_update", "Riga aggiornata dopo il messaggio", true, rows.Count > 0 && rows.Over == 0,
|
||||
$"{rows.Count} aggiornamenti: mediana {Num(rows.P50)} ms, 99° {Num(rows.P99)} ms, massimo {Num(rows.Max)} ms, {rows.Over} oltre il limite",
|
||||
$"entro {Num(PerfCriteria.MaxRowUpdateMs)} ms"),
|
||||
new("reconnect", "Riconnessione", true, worstReconnect is { } w && w < PerfCriteria.MaxReconnectMs,
|
||||
reconnects.Count == 0 ? "non misurata" : string.Join(", ", reconnects.Select(r => r is { } x ? Num(x) + " ms" : "non riuscita")),
|
||||
$"< {Num(PerfCriteria.MaxReconnectMs)} ms"),
|
||||
new("drag", "Trascinamento della maniglia", true, input.Drag.Rows.Intact,
|
||||
RowsText(input.Drag), "nessuna riga ridisegnata"),
|
||||
new("resize", "Ridimensionamento della finestra", true, input.Resize.Rows.Intact,
|
||||
RowsText(input.Resize), "nessuna riga ridisegnata"),
|
||||
new("js_errors", "Errori JavaScript", true, input.Errors.Count == 0, input.Errors.Count.ToString(CultureInfo.InvariantCulture), "0")
|
||||
};
|
||||
|
||||
return new PerfReport
|
||||
{
|
||||
At = at,
|
||||
Url = url,
|
||||
Seconds = input.Seconds,
|
||||
Samples = samples,
|
||||
Frames = frames,
|
||||
RowUpdate = rows,
|
||||
Handler = handlers,
|
||||
Tasks = tasks,
|
||||
LongTasks = input.LongTasksMs.Count,
|
||||
LongestTaskMs = input.LongTasksMs.Count > 0 ? Round(input.LongTasksMs.Max()) : 0,
|
||||
CpuPercent = input.CpuPercent is { } cpuValue ? Round(cpuValue) : null,
|
||||
Drag = input.Drag,
|
||||
Resize = input.Resize,
|
||||
ReconnectsMs = reconnects,
|
||||
Errors = input.Errors,
|
||||
Checks = checks,
|
||||
Valid = invalid.Count == 0,
|
||||
InvalidReasons = invalid
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Il resoconto da leggere: esito, criteri, condizioni della prova.</summary>
|
||||
public static string Text(PerfReport r)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine($"Misura delle prestazioni dell'interfaccia (specifica §9.11), {r.At.ToLocalTime():yyyy-MM-dd HH:mm:ss}");
|
||||
sb.AppendLine($"Indirizzo {r.Url}, pagina Aste, {r.Seconds} s");
|
||||
sb.AppendLine();
|
||||
sb.AppendLine("Esito: " + (!r.Valid ? "NON VALIDA" : r.Passed ? "SUPERATA" : "NON SUPERATA"));
|
||||
foreach (var reason in r.InvalidReasons) sb.AppendLine(" misura non valida: " + reason);
|
||||
sb.AppendLine();
|
||||
foreach (var c in r.Checks)
|
||||
{
|
||||
var mark = c.Passed ? "ok " : c.Binding ? "NO " : "oltre";
|
||||
sb.AppendLine($"[{mark}] {c.Label}{(c.Binding ? "" : " (non vincolante)")}: {c.Value}; limite {c.Limit}");
|
||||
}
|
||||
sb.AppendLine();
|
||||
sb.AppendLine("Condizioni");
|
||||
var s = r.Samples;
|
||||
sb.AppendLine($" campioni {s.Count}, aste in elenco almeno {s.MinListed}, righe disegnate fino a {s.MaxDrawn}");
|
||||
sb.AppendLine($" aste in Attiva sotto i 4 s: almeno {s.MinCritical}, mediana {Num(s.MedianCritical)}, " +
|
||||
$"almeno {PerfCriteria.MinCritical} nel {Pct(s.CriticalShare)} dei campioni");
|
||||
sb.AppendLine($" gestione di un messaggio: mediana {Num(r.Handler.P50)} ms, 99° {Num(r.Handler.P99)} ms, massimo {Num(r.Handler.Max)} ms");
|
||||
sb.AppendLine($" ritardo del frame peggiore {Num(r.Frames.WorstBlockMs)} ms, frame in ritardo oltre {Num(PerfCriteria.MaxBlockMs)} ms: {r.Frames.Blocks}");
|
||||
sb.AppendLine($" compiti lunghi (PerformanceObserver, oltre 50 ms): {r.LongTasks}, il più lungo {Num(r.LongestTaskMs)} ms");
|
||||
sb.AppendLine($" maniglia: pannello mosso di {Num(r.Drag.MovedPx)} px, {GridText(r.Drag.Grid)}, compiti lunghi {LongText(r.Drag.LongTasksMs)}, " +
|
||||
$"frame persi {r.Drag.Frames.LostFrames} (solo riportati)");
|
||||
sb.AppendLine($" finestra: {GridText(r.Resize.Grid)}, compiti lunghi {LongText(r.Resize.LongTasksMs)}, " +
|
||||
$"frame persi durante il ridimensionamento {r.Resize.Frames.LostFrames} (solo riportati)");
|
||||
foreach (var e in r.Errors) sb.AppendLine(" errore: " + e);
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static string RowsText(GesturePhase p) =>
|
||||
$"{p.Rows.Kept} righe rimaste le stesse su {p.Rows.Before} prima e {p.Rows.After} dopo" +
|
||||
(p.Rows.Replaced.Count > 0 ? $", ridisegnate {p.Rows.Replaced.Count} ({string.Join(", ", p.Rows.Replaced.Take(5))})" : "") +
|
||||
(p.Rows.Duplicated.Count > 0 ? $", doppie {p.Rows.Duplicated.Count}" : "");
|
||||
|
||||
private static string TasksText(Distribution d) =>
|
||||
$"{d.Count} compiti (messaggi, timer, frame, eventi): 99° {Num(d.P99)} ms, il più lungo {Num(d.Max)} ms, {d.Over} oltre il limite";
|
||||
|
||||
private static string GridText(GridState g) =>
|
||||
$"griglia scorsa di {Num(g.ScrollMovedPx)} px, fino a {g.MaxDrawn} righe disegnate{(g.Virtual ? ", virtualizzata" : "")}";
|
||||
|
||||
private static string LongText(IReadOnlyList<double> longTasks) =>
|
||||
longTasks.Count == 0 ? "0" : $"{longTasks.Count} (il più lungo {Num(Round(longTasks.Max()))} ms)";
|
||||
|
||||
private static double Round(double v) => Math.Round(v, 2);
|
||||
|
||||
private static string Num(double v) => v.ToString(v == Math.Floor(v) ? "0" : "0.##", CultureInfo.GetCultureInfo("it-IT"));
|
||||
|
||||
private static string Pct(double share) => Num(Math.Round(share * 100, 1)) + "%";
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using Mimante.Schermate.Cdp;
|
||||
|
||||
namespace Mimante.Schermate.Misura;
|
||||
|
||||
/// <summary>
|
||||
/// La misura delle prestazioni (<c>--misura <secondi></c>), tutta via CDP: la pagina Aste del bot avviato con
|
||||
/// <c>--simulatore --simulatore-aste 60</c>, già con l'accesso fatto e lo strumento di <see cref="PerfScript"/> dentro.
|
||||
///
|
||||
/// <para>Fasi: attesa dell'elenco pieno; qualche secondo di assestamento; la misura vera (frame, messaggi, CPU, un
|
||||
/// campione al secondo); la maniglia del pannello trascinata avanti e indietro; la finestra ristretta e riallargata;
|
||||
/// tre chiusure del canale con il bot. Con maniglia e finestra si guarda che nessuna riga venga ridisegnata e che la
|
||||
/// griglia non scorra né si virtualizzi, e i compiti dell'interfaccia si cronometrano come nella misura.</para>
|
||||
/// </summary>
|
||||
public sealed class PerfRun(CdpClient cdp, string session, Func<string, Task<JsonElement>> eval, Func<int, int, Task> viewport, CancellationToken ct)
|
||||
{
|
||||
public const int Width = 1600;
|
||||
public const int Height = 1000;
|
||||
|
||||
/// <summary>Quanto aspettare che l'elenco arrivi a <see cref="PerfCriteria.MinListed"/> aste.</summary>
|
||||
private static readonly TimeSpan FillTimeout = TimeSpan.FromSeconds(90);
|
||||
|
||||
private static readonly TimeSpan Settle = TimeSpan.FromSeconds(5);
|
||||
|
||||
public async Task<PerfInputs> RunAsync(int seconds, Func<IReadOnlyList<string>> errors, Action<string> progress)
|
||||
{
|
||||
await WaitForListAsync(progress).ConfigureAwait(false);
|
||||
await Task.Delay(Settle, ct).ConfigureAwait(false);
|
||||
|
||||
progress($"misura per {seconds} s");
|
||||
var samples = new List<PerfSample>();
|
||||
await eval("__mimantePerf.start()").ConfigureAwait(false);
|
||||
var cpu0 = await MetricsAsync().ConfigureAwait(false);
|
||||
var sw = Stopwatch.StartNew();
|
||||
while (sw.Elapsed < TimeSpan.FromSeconds(seconds))
|
||||
{
|
||||
await Task.Delay(1000, ct).ConfigureAwait(false);
|
||||
if (await SampleAsync().ConfigureAwait(false) is { } s) samples.Add(s);
|
||||
}
|
||||
var cpu1 = await MetricsAsync().ConfigureAwait(false);
|
||||
var steady = await eval("__mimantePerf.take()").ConfigureAwait(false);
|
||||
|
||||
progress("maniglia del pannello");
|
||||
var drag = await DragAsync().ConfigureAwait(false);
|
||||
progress("ridimensionamento della finestra");
|
||||
var resize = await ResizeAsync().ConfigureAwait(false);
|
||||
progress("riconnessione");
|
||||
var reconnects = new List<double?>();
|
||||
for (var i = 0; i < PerfCriteria.ReconnectTrials; i++)
|
||||
{
|
||||
reconnects.Add(await ReconnectAsync().ConfigureAwait(false));
|
||||
await Task.Delay(2000, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new PerfInputs
|
||||
{
|
||||
Seconds = seconds,
|
||||
Samples = samples,
|
||||
FrameIntervals = Numbers(steady, "frames"),
|
||||
RowUpdatesMs = Numbers(steady, "rowUpdates"),
|
||||
HandlersMs = Numbers(steady, "handlers"),
|
||||
TasksMs = Numbers(steady, "tasks"),
|
||||
LongTasksMs = Numbers(steady, "longTasks"),
|
||||
CpuPercent = Cpu(cpu0, cpu1),
|
||||
Drag = drag,
|
||||
Resize = resize,
|
||||
ReconnectsMs = reconnects,
|
||||
Errors = errors().Distinct().ToList()
|
||||
};
|
||||
}
|
||||
|
||||
private async Task WaitForListAsync(Action<string> progress)
|
||||
{
|
||||
await eval("location.hash = '#/aste'").ConfigureAwait(false);
|
||||
var sw = Stopwatch.StartNew();
|
||||
var said = false;
|
||||
while (sw.Elapsed < FillTimeout)
|
||||
{
|
||||
var s = await SampleAsync().ConfigureAwait(false);
|
||||
if (s is { Listed: >= PerfCriteria.MinListed, Drawn: > 0 }) return;
|
||||
if (!said && sw.Elapsed > TimeSpan.FromSeconds(5))
|
||||
{
|
||||
progress($"aspetto l'elenco: {s?.Listed ?? 0} aste su {PerfCriteria.MinListed}");
|
||||
said = true;
|
||||
}
|
||||
await Task.Delay(1000, ct).ConfigureAwait(false);
|
||||
}
|
||||
progress("l'elenco non si è riempito: la misura prosegue e risulterà non valida");
|
||||
}
|
||||
|
||||
private async Task<PerfSample?> SampleAsync()
|
||||
{
|
||||
var v = await eval("__mimantePerf.sample()").ConfigureAwait(false);
|
||||
if (v.ValueKind != JsonValueKind.Object) return null;
|
||||
return new PerfSample(Int(v, "listed"), Int(v, "active"), Int(v, "critical"), Int(v, "drawn"),
|
||||
v.TryGetProperty("connected", out var c) && c.ValueKind == JsonValueKind.True);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// La maniglia fra elenco e pannello: premuta, portata a sinistra, a destra e riportata, senza scorrere. Lo
|
||||
/// scorrimento e le righe disegnate si guardano prima, dopo ogni tratto e alla fine (<see cref="PerfAnalysis.Grid"/>).
|
||||
/// </summary>
|
||||
private async Task<GesturePhase> DragAsync()
|
||||
{
|
||||
var handle = await eval("__mimantePerf.handle()").ConfigureAwait(false);
|
||||
if (handle.ValueKind != JsonValueKind.Object)
|
||||
return new GesturePhase(new RowIdentity(0, 0, 0, [], []), PerfAnalysis.Frames([]), PerfAnalysis.Tasks([], []), [], 0, PerfAnalysis.Grid([]));
|
||||
double x = Double(handle, "x"), y = Double(handle, "y"), panel0 = Double(handle, "panel");
|
||||
var grid = new List<(double, int, bool)>();
|
||||
var at = 0.0;
|
||||
async Task MoveAsync(double target)
|
||||
{
|
||||
const int steps = 20;
|
||||
var from = at;
|
||||
for (var i = 1; i <= steps; i++)
|
||||
{
|
||||
at = from + (target - from) * i / steps;
|
||||
await MouseAsync("mouseMoved", x + at, y, 1).ConfigureAwait(false);
|
||||
await Task.Delay(16, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
var before = await RowsAsync().ConfigureAwait(false);
|
||||
grid.Add(await GridAsync().ConfigureAwait(false));
|
||||
await eval("__mimantePerf.start()").ConfigureAwait(false);
|
||||
await MouseAsync("mousePressed", x, y, 1).ConfigureAwait(false);
|
||||
// Da dove si è a 240 px a sinistra (pannello più largo), poi a 240 px a destra, poi di nuovo al punto di
|
||||
// partenza: i limiti del pannello fermano prima, ma lo spostamento fra i due estremi resta.
|
||||
double widest = panel0, narrowest = panel0;
|
||||
foreach (var target in new[] { -240.0, 240.0, 0.0 })
|
||||
{
|
||||
await MoveAsync(target).ConfigureAwait(false);
|
||||
grid.Add(await GridAsync().ConfigureAwait(false));
|
||||
var now = await eval("__mimantePerf.handle()").ConfigureAwait(false);
|
||||
if (now.ValueKind != JsonValueKind.Object) continue;
|
||||
widest = Math.Max(widest, Double(now, "panel"));
|
||||
narrowest = Math.Min(narrowest, Double(now, "panel"));
|
||||
}
|
||||
await MouseAsync("mouseReleased", x, y, 0).ConfigureAwait(false);
|
||||
var moved = widest - narrowest;
|
||||
await Task.Delay(300, ct).ConfigureAwait(false);
|
||||
var taken = await eval("__mimantePerf.take()").ConfigureAwait(false);
|
||||
grid.Add(await GridAsync().ConfigureAwait(false));
|
||||
var after = await RowsAsync().ConfigureAwait(false);
|
||||
return Phase(before, after, taken, Math.Round(moved, 1), grid);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// La finestra da 1600×1000 a 1150×800 (il pannello resta di fianco) e ritorno, a passi di 40 ms; la griglia si
|
||||
/// guarda a ogni passo.
|
||||
/// </summary>
|
||||
private async Task<GesturePhase> ResizeAsync()
|
||||
{
|
||||
var before = await RowsAsync().ConfigureAwait(false);
|
||||
var grid = new List<(double, int, bool)> { await GridAsync().ConfigureAwait(false) };
|
||||
await eval("__mimantePerf.start()").ConfigureAwait(false);
|
||||
const int steps = 20;
|
||||
foreach (var i in Enumerable.Range(1, steps).Concat(Enumerable.Range(0, steps).Reverse()))
|
||||
{
|
||||
await viewport(Width - 450 * i / steps, Height - 200 * i / steps).ConfigureAwait(false);
|
||||
await Task.Delay(40, ct).ConfigureAwait(false);
|
||||
grid.Add(await GridAsync().ConfigureAwait(false));
|
||||
}
|
||||
await viewport(Width, Height).ConfigureAwait(false);
|
||||
await Task.Delay(500, ct).ConfigureAwait(false);
|
||||
var taken = await eval("__mimantePerf.take()").ConfigureAwait(false);
|
||||
grid.Add(await GridAsync().ConfigureAwait(false));
|
||||
var after = await RowsAsync().ConfigureAwait(false);
|
||||
return Phase(before, after, taken, 0, grid);
|
||||
}
|
||||
|
||||
/// <summary>Una fase dai numeri di <c>__mimantePerf.take()</c>: frame, compiti e compiti lunghi, non solo i frame.</summary>
|
||||
private static GesturePhase Phase(IReadOnlyList<(string Id, long Token)> before, IReadOnlyList<(string Id, long Token)> after,
|
||||
JsonElement taken, double movedPx, IReadOnlyList<(double, int, bool)> grid) =>
|
||||
new(PerfAnalysis.CompareRows(before, after),
|
||||
PerfAnalysis.Frames(Numbers(taken, "frames")),
|
||||
PerfAnalysis.Tasks(Numbers(taken, "handlers"), Numbers(taken, "tasks")),
|
||||
Numbers(taken, "longTasks"),
|
||||
movedPx,
|
||||
PerfAnalysis.Grid(grid));
|
||||
|
||||
/// <summary>Scorrimento verticale, righe disegnate e virtualizzazione della griglia in questo momento.</summary>
|
||||
private async Task<(double, int, bool)> GridAsync()
|
||||
{
|
||||
var g = await eval("__mimantePerf.grid()").ConfigureAwait(false);
|
||||
if (g.ValueKind != JsonValueKind.Object) return (0, 0, false);
|
||||
return (Double(g, "scroll"), Int(g, "drawn"), g.TryGetProperty("virtual", out var v) && v.ValueKind == JsonValueKind.True);
|
||||
}
|
||||
|
||||
/// <summary>Chiude il canale dalla pagina e misura fino al nuovo elenco a schermo; null = non riuscita.</summary>
|
||||
private async Task<double?> ReconnectAsync()
|
||||
{
|
||||
var r = await eval("__mimantePerf.reconnect()").ConfigureAwait(false);
|
||||
if (r.ValueKind != JsonValueKind.Object || !r.TryGetProperty("ok", out var ok) || ok.ValueKind != JsonValueKind.True) return null;
|
||||
return Double(r, "ms");
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<(string Id, long Token)>> RowsAsync()
|
||||
{
|
||||
var v = await eval("__mimantePerf.rows()").ConfigureAwait(false);
|
||||
if (v.ValueKind != JsonValueKind.Array) return [];
|
||||
return v.EnumerateArray()
|
||||
.Where(p => p.ValueKind == JsonValueKind.Array && p.GetArrayLength() == 2)
|
||||
.Select(p => (p[0].ToString(), p[1].TryGetInt64(out var t) ? t : 0L))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private Task MouseAsync(string type, double x, double y, int buttons) =>
|
||||
cdp.SendAsync("Input.dispatchMouseEvent", new
|
||||
{
|
||||
type, x, y, button = type == "mouseMoved" && buttons == 0 ? "none" : "left", buttons, clickCount = type == "mouseMoved" ? 0 : 1
|
||||
}, session, ct);
|
||||
|
||||
/// <summary>TaskDuration e Timestamp di <c>Performance.getMetrics</c>, in secondi.</summary>
|
||||
private async Task<(double Task, double Time)?> MetricsAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var r = await cdp.SendAsync("Performance.getMetrics", sessionId: session, ct: ct).ConfigureAwait(false);
|
||||
double? task = null, time = null;
|
||||
foreach (var m in r.GetProperty("metrics").EnumerateArray())
|
||||
{
|
||||
var name = m.GetProperty("name").GetString();
|
||||
if (name == "TaskDuration") task = m.GetProperty("value").GetDouble();
|
||||
else if (name == "Timestamp") time = m.GetProperty("value").GetDouble();
|
||||
}
|
||||
return task is { } t && time is { } s ? (t, s) : null;
|
||||
}
|
||||
catch (CdpException) { return null; }
|
||||
}
|
||||
|
||||
/// <summary>Il tempo del thread della scheda sul tempo trascorso, in percento di un core.</summary>
|
||||
public static double? Cpu((double Task, double Time)? start, (double Task, double Time)? end) =>
|
||||
start is { } a && end is { } b && b.Time > a.Time ? Math.Round((b.Task - a.Task) / (b.Time - a.Time) * 100, 1) : null;
|
||||
|
||||
private static IReadOnlyList<double> Numbers(JsonElement obj, string name) =>
|
||||
obj.ValueKind == JsonValueKind.Object && obj.TryGetProperty(name, out var a) && a.ValueKind == JsonValueKind.Array
|
||||
? a.EnumerateArray().Where(x => x.ValueKind == JsonValueKind.Number).Select(x => x.GetDouble()).ToList()
|
||||
: [];
|
||||
|
||||
private static int Int(JsonElement o, string name) => o.TryGetProperty(name, out var v) && v.TryGetInt32(out var i) ? i : 0;
|
||||
|
||||
private static double Double(JsonElement o, string name) =>
|
||||
o.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number ? v.GetDouble() : 0;
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
namespace Mimante.Schermate.Misura;
|
||||
|
||||
/// <summary>
|
||||
/// Lo strumento di misura dentro la pagina, messo con <c>Page.addScriptToEvaluateOnNewDocument</c> prima di ogni
|
||||
/// altro script: <c>window.__mimantePerf</c>.
|
||||
///
|
||||
/// <list type="bullet">
|
||||
/// <item>un ciclo di <c>requestAnimationFrame</c> che registra l'intervallo fra due frame (frame persi);</item>
|
||||
/// <item>i compiti dell'interfaccia cronometrati uno per uno (i blocchi del thread): le funzioni passate a
|
||||
/// <c>setTimeout</c>, <c>setInterval</c> e <c>requestAnimationFrame</c>, gli ascoltatori degli eventi del puntatore,
|
||||
/// della rotella, dello scorrimento e della finestra (la maniglia di <c>split.js</c>), le funzioni dei
|
||||
/// <c>ResizeObserver</c> e la gestione di ogni messaggio del bot;</item>
|
||||
/// <item>un involucro di <c>window.WebSocket</c>: ogni <c>auction.delta</c> si cronometra dall'evento del messaggio
|
||||
/// al primo frame dopo la sua gestione (ws.js → state.js → aste.js → grid.js aggiornano la riga in modo sincrono, e
|
||||
/// quel frame è il primo che la mostra); <c>reconnect()</c> chiude il canale e misura fino al nuovo elenco
|
||||
/// (<c>snapshot</c>) a schermo;</item>
|
||||
/// <item>un <c>PerformanceObserver</c> dei compiti lunghi del browser (scatta solo sopra 50 ms, quindi prende anche
|
||||
/// layout e stile che i cronometri non vedono): uno solo, in qualunque fase, fa fallire il criterio dei blocchi;</item>
|
||||
/// <item><c>sample()</c> conta le aste in elenco e quelle in Attiva in finestra critica dallo stato della pagina
|
||||
/// (<c>/js/state.js</c>, lo stesso modulo dell'interfaccia); <c>rows()</c> dà a ogni <c><tr data-id></c> un
|
||||
/// segno, per riconoscere un nodo ridisegnato; <c>grid()</c> dice lo scorrimento, le righe disegnate e se la griglia
|
||||
/// è virtualizzata.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public static class PerfScript
|
||||
{
|
||||
private const string Source = """
|
||||
(() => {
|
||||
if (window.__mimantePerf) return;
|
||||
const now = () => performance.now();
|
||||
const round = v => Math.round(v * 100) / 100;
|
||||
const P = {
|
||||
recording: false, frames: [], rowUpdates: [], handlers: [], tasks: [], longTasks: [],
|
||||
pending: [], sockets: 0, socket: null, lastOpen: 0, reconnecting: null
|
||||
};
|
||||
|
||||
// I compiti dell'interfaccia: ogni funzione data a un timer o a requestAnimationFrame, cronometrata. Gli id restano
|
||||
// quelli del browser, quindi clearTimeout, clearInterval e cancelAnimationFrame non cambiano.
|
||||
const nativeRaf = window.requestAnimationFrame.bind(window);
|
||||
const timed = fn => function (...a) {
|
||||
const s = now();
|
||||
try { return fn.apply(this, a); }
|
||||
finally { if (P.recording) P.tasks.push(round(now() - s)); }
|
||||
};
|
||||
for (const name of ['setTimeout', 'setInterval']) {
|
||||
const native = window[name].bind(window);
|
||||
window[name] = (fn, ...rest) => native(typeof fn === 'function' ? timed(fn) : fn, ...rest);
|
||||
}
|
||||
window.requestAnimationFrame = fn => nativeRaf(typeof fn === 'function' ? timed(fn) : fn);
|
||||
|
||||
// Gli ascoltatori del puntatore, della rotella, dello scorrimento e della finestra e le funzioni dei ResizeObserver:
|
||||
// i compiti di maniglia e ridimensionamento. La stessa funzione ha sempre lo stesso involucro, così
|
||||
// removeEventListener la ritrova (split.js toglie pointermove e pointerup a fine trascinamento).
|
||||
const watched = /^(?:pointer|mouse)|^(?:wheel|scroll|resize)$/;
|
||||
const wrappers = new WeakMap();
|
||||
const wrapped = fn => { let w = wrappers.get(fn); if (!w) { w = timed(fn); wrappers.set(fn, w); } return w; };
|
||||
const nativeAdd = EventTarget.prototype.addEventListener;
|
||||
const nativeRemove = EventTarget.prototype.removeEventListener;
|
||||
EventTarget.prototype.addEventListener = function (type, fn, ...rest) {
|
||||
return nativeAdd.call(this, type, typeof fn === 'function' && watched.test(type) ? wrapped(fn) : fn, ...rest);
|
||||
};
|
||||
EventTarget.prototype.removeEventListener = function (type, fn, ...rest) {
|
||||
return nativeRemove.call(this, type, typeof fn === 'function' && watched.test(type) ? (wrappers.get(fn) || fn) : fn, ...rest);
|
||||
};
|
||||
const NativeResizeObserver = window.ResizeObserver;
|
||||
if (NativeResizeObserver) {
|
||||
window.ResizeObserver = class extends NativeResizeObserver {
|
||||
constructor(fn) { super(typeof fn === 'function' ? timed(fn) : fn); }
|
||||
};
|
||||
}
|
||||
|
||||
let last = 0;
|
||||
const loop = t => {
|
||||
if (P.recording && last > 0) P.frames.push(round(t - last));
|
||||
last = t;
|
||||
if (P.pending.length) {
|
||||
const n = now();
|
||||
for (const r of P.pending) { if (P.recording) P.rowUpdates.push(round(n - r.t0)); }
|
||||
P.pending.length = 0;
|
||||
}
|
||||
const rc = P.reconnecting;
|
||||
if (rc && rc.snapshotAt > 0) rc.done(now());
|
||||
nativeRaf(loop);
|
||||
};
|
||||
nativeRaf(loop);
|
||||
|
||||
try {
|
||||
new PerformanceObserver(list => {
|
||||
if (!P.recording) return;
|
||||
for (const e of list.getEntries()) P.longTasks.push(round(e.duration));
|
||||
}).observe({ type: 'longtask' });
|
||||
} catch { /* browser senza longtask */ }
|
||||
|
||||
const Native = window.WebSocket;
|
||||
class PerfSocket extends Native {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
P.sockets++;
|
||||
P.socket = this;
|
||||
this.__perfIndex = P.sockets;
|
||||
this.addEventListener('open', () => { P.lastOpen = now(); });
|
||||
}
|
||||
get onmessage() { return this.__perfHandler || null; }
|
||||
set onmessage(fn) {
|
||||
this.__perfHandler = fn;
|
||||
super.onmessage = typeof fn !== 'function' ? fn : ev => {
|
||||
const start = now();
|
||||
const t0 = ev.timeStamp > 0 && ev.timeStamp <= start ? ev.timeStamp : start;
|
||||
const m = typeof ev.data === 'string' ? /^\{"t":"([^"]+)"/.exec(ev.data) : null;
|
||||
try { return fn.call(this, ev); }
|
||||
finally {
|
||||
const end = now();
|
||||
const type = m ? m[1] : '';
|
||||
if (P.recording) P.handlers.push(round(end - start));
|
||||
if (type === 'auction.delta' && P.recording) P.pending.push({ t0 });
|
||||
const rc = P.reconnecting;
|
||||
if (type === 'snapshot' && rc && this.__perfIndex > rc.socketIndex && !rc.snapshotAt) rc.snapshotAt = end;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
window.WebSocket = PerfSocket;
|
||||
|
||||
let token = 0;
|
||||
window.__mimantePerf = {
|
||||
start() {
|
||||
P.frames = []; P.rowUpdates = []; P.handlers = []; P.tasks = []; P.longTasks = []; P.pending = [];
|
||||
last = 0;
|
||||
P.recording = true;
|
||||
return true;
|
||||
},
|
||||
take() {
|
||||
P.recording = false;
|
||||
const out = { frames: P.frames, rowUpdates: P.rowUpdates, handlers: P.handlers, tasks: P.tasks, longTasks: P.longTasks };
|
||||
P.frames = []; P.rowUpdates = []; P.handlers = []; P.tasks = []; P.longTasks = [];
|
||||
return out;
|
||||
},
|
||||
async sample() {
|
||||
const { state, remainingMs } = await import('/js/state.js');
|
||||
let listed = 0, active = 0, critical = 0;
|
||||
for (const r of state.auctions.values()) {
|
||||
listed++;
|
||||
if (r.outcome || r.mode !== 'attiva') continue;
|
||||
active++;
|
||||
const ms = remainingMs(r);
|
||||
if (ms != null && ms > 0 && ms < __CRITICAL_MS__) critical++;
|
||||
}
|
||||
const drawn = document.querySelectorAll('.aste-list tbody tr[data-id]').length;
|
||||
return { listed, active, critical, drawn, connected: !!state.connected };
|
||||
},
|
||||
rows() {
|
||||
return [...document.querySelectorAll('.aste-list tbody tr[data-id]')]
|
||||
.map(tr => [tr.dataset.id, tr.__perfToken || (tr.__perfToken = ++token)]);
|
||||
},
|
||||
handle() {
|
||||
const h = document.querySelector('.split .vsplit');
|
||||
if (!h) return null;
|
||||
const r = h.getBoundingClientRect();
|
||||
const panel = document.querySelector('.split .panel');
|
||||
return { x: r.left + r.width / 2, y: r.top + r.height / 2, panel: panel ? panel.getBoundingClientRect().width : 0 };
|
||||
},
|
||||
grid() {
|
||||
const list = document.querySelector('.aste-list');
|
||||
return {
|
||||
scroll: list ? list.scrollTop : 0,
|
||||
drawn: document.querySelectorAll('.aste-list tbody tr[data-id]').length,
|
||||
virtual: !!document.querySelector('.aste-list tbody tr.spacer-row')
|
||||
};
|
||||
},
|
||||
reconnect() {
|
||||
return new Promise(resolve => {
|
||||
const s = P.socket;
|
||||
if (!s || s.readyState !== 1) { resolve({ ok: false, reason: 'canale non aperto' }); return; }
|
||||
const rc = { start: now(), socketIndex: s.__perfIndex, snapshotAt: 0 };
|
||||
const timer = setTimeout(() => { P.reconnecting = null; resolve({ ok: false, reason: 'nessun elenco nuovo entro 10 s' }); }, 10000);
|
||||
rc.done = at => { clearTimeout(timer); P.reconnecting = null; resolve({ ok: true, ms: round(at - rc.start), openMs: round(P.lastOpen - rc.start) }); };
|
||||
P.reconnecting = rc;
|
||||
s.close();
|
||||
});
|
||||
}
|
||||
};
|
||||
})();
|
||||
""";
|
||||
|
||||
/// <summary>Lo script con le soglie della misura.</summary>
|
||||
public static string Build() =>
|
||||
Source.Replace("__CRITICAL_MS__", PerfCriteria.CriticalMs.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||
}
|
||||
@@ -1,36 +1,53 @@
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using Mimante.Schermate;
|
||||
using Mimante.Schermate.Cdp;
|
||||
using Mimante.Schermate.Misura;
|
||||
|
||||
// Uso: dotnet run --project tools/Mimante.Schermate -- <indirizzo> <password dell'interfaccia> <cartella>
|
||||
// Uso: dotnet run --project tools/Mimante.Schermate -- <indirizzo> [password dell'interfaccia] <cartella>
|
||||
// Esempio: dotnet run --project tools/Mimante.Schermate -- http://localhost:8080 dev docs/schermate
|
||||
// Il bot deve girare sul simulatore (--simulatore) per avere aste da fotografare.
|
||||
// Esce con 1 se una pagina ha errori JavaScript.
|
||||
// Esce con 1 se una pagina ha errori JavaScript. Senza password fra gli argomenti vale UI_PASSWORD.
|
||||
//
|
||||
// Proposte grafiche: dotnet run --project tools/Mimante.Schermate -- --mockup [cartella]
|
||||
// (predefinita docs/mockup/redesign): fotografa ogni <variante>/<pagina>.html in chiaro e in scuro
|
||||
// in <cartella>/immagini, poi il foglio di confronto (confronto.html) se c'è.
|
||||
//
|
||||
// Prestazioni (specifica §9.11): dotnet run --project tools/Mimante.Schermate -- <indirizzo> <cartella> --misura 120
|
||||
// con il bot in --simulatore --simulatore-aste 60; misura.json e misura.txt nella cartella (Misura/PerfRun.cs).
|
||||
|
||||
var mockup = args.Length >= 1 && args[0] == "--mockup";
|
||||
if (!mockup && args.Length < 3)
|
||||
var parsed = Arguments.Parse(args, Environment.GetEnvironmentVariable, out var argError);
|
||||
if (parsed.Help)
|
||||
{
|
||||
Console.Error.WriteLine("Uso: Mimante.Schermate <indirizzo> <password> <cartella> | --mockup [cartella]");
|
||||
Console.WriteLine(Arguments.Usage);
|
||||
return 0;
|
||||
}
|
||||
if (argError != null)
|
||||
{
|
||||
Console.Error.WriteLine(argError);
|
||||
Console.Error.WriteLine();
|
||||
Console.Error.WriteLine(Arguments.Usage);
|
||||
return 2;
|
||||
}
|
||||
|
||||
var baseUrl = mockup ? "" : args[0].TrimEnd('/');
|
||||
var password = mockup ? "" : args[1];
|
||||
var mockup = parsed.Mockup;
|
||||
var measureSeconds = parsed.MeasureSeconds;
|
||||
var baseUrl = parsed.BaseUrl;
|
||||
var password = parsed.Password;
|
||||
// Un percorso relativo vale dalla radice del repository: `dotnet run` parte nella cartella del progetto.
|
||||
var dirArg = mockup ? (args.Length > 1 ? args[1] : "docs/mockup/redesign") : args[2];
|
||||
var dirArg = parsed.OutputDir;
|
||||
var outDir = Path.IsPathRooted(dirArg) ? dirArg : Path.GetFullPath(Path.Combine(RepoRoot(), dirArg));
|
||||
Directory.CreateDirectory(outDir);
|
||||
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5));
|
||||
// La misura dura quanto chiesto più accesso, attesa dell'elenco e fasi con maniglie, finestra e riconnessione.
|
||||
using var cts = new CancellationTokenSource(measureSeconds is { } m ? TimeSpan.FromSeconds(m) + TimeSpan.FromMinutes(5) : TimeSpan.FromMinutes(5));
|
||||
var ct = cts.Token;
|
||||
var profile = Path.Combine(Path.GetTempPath(), $"mimante-schermate-{Environment.ProcessId}");
|
||||
await using var chromium = await ChromiumProcess.StartAsync(profile, ct);
|
||||
await using var cdp = await CdpClient.ConnectAsync(chromium.Endpoint, ct);
|
||||
|
||||
var errors = new List<string>();
|
||||
int? measureExit = null;
|
||||
var loaded = new SemaphoreSlim(0);
|
||||
string? session = null;
|
||||
cdp.Event += (method, p, s) =>
|
||||
@@ -103,6 +120,14 @@ async Task Shot(string name, string hash, string? script = null, int waitMs = 25
|
||||
Console.WriteLine($"{name}.png{(errors.Count > before ? $" ({errors.Count - before} errori)" : "")}");
|
||||
}
|
||||
|
||||
// L'accesso all'interfaccia dalla pagina /accesso già aperta.
|
||||
async Task Login()
|
||||
{
|
||||
await Eval($"document.querySelector('input[type=password]').value = {JsonSerializer.Serialize(password)}; document.querySelector('form').submit();");
|
||||
await loaded.WaitAsync(TimeSpan.FromSeconds(20), ct);
|
||||
await Task.Delay(1500, ct);
|
||||
}
|
||||
|
||||
async Task Capture(string file)
|
||||
{
|
||||
var png = await cdp.SendAsync("Page.captureScreenshot", new { format = "png" }, session, ct);
|
||||
@@ -142,15 +167,39 @@ if (mockup)
|
||||
Console.WriteLine("confronto.png");
|
||||
}
|
||||
}
|
||||
else if (measureSeconds is { } seconds)
|
||||
{
|
||||
// Lo strumento di misura entra in ogni documento prima degli script della pagina (l'involucro di WebSocket
|
||||
// deve esserci prima che ws.js apra il canale).
|
||||
await cdp.SendAsync("Page.addScriptToEvaluateOnNewDocument", new { source = PerfScript.Build() }, session, ct);
|
||||
await cdp.SendAsync("Performance.enable", new { timeDomain = "timeTicks" }, session, ct);
|
||||
await Viewport(PerfRun.Width, PerfRun.Height);
|
||||
await SystemTheme("dark");
|
||||
await Navigate(baseUrl + "/accesso");
|
||||
await Login();
|
||||
|
||||
var run = new PerfRun(cdp, session!, Eval, Viewport, ct);
|
||||
var inputs = await run.RunAsync(seconds, () => errors.ToList(), text => Console.WriteLine("misura: " + text));
|
||||
var report = PerfAnalysis.Evaluate(inputs, baseUrl, DateTimeOffset.Now);
|
||||
var text = PerfAnalysis.Text(report);
|
||||
var json = JsonSerializer.Serialize(report, new JsonSerializerOptions
|
||||
{
|
||||
WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||
});
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, "misura.json"), json, ct);
|
||||
await File.WriteAllTextAsync(Path.Combine(outDir, "misura.txt"), text, ct);
|
||||
Console.WriteLine();
|
||||
Console.Write(text);
|
||||
Console.WriteLine($"Risultati in {outDir} (misura.json, misura.txt)");
|
||||
measureExit = report.ExitCode;
|
||||
}
|
||||
else
|
||||
{
|
||||
await Viewport(1600, 1000);
|
||||
await SystemTheme("dark");
|
||||
await Navigate(baseUrl + "/accesso");
|
||||
await Shot("00-accesso-interfaccia", "", null, 500);
|
||||
await Eval($"document.querySelector('input[type=password]').value = {JsonSerializer.Serialize(password)}; document.querySelector('form').submit();");
|
||||
await loaded.WaitAsync(TimeSpan.FromSeconds(20), ct);
|
||||
await Task.Delay(1500, ct);
|
||||
await Login();
|
||||
|
||||
const string clickFirst = "document.querySelector('.split tbody tr[data-id]')?.click()";
|
||||
await Shot("01-aste", "#/aste", clickFirst, 4000);
|
||||
@@ -161,7 +210,7 @@ else
|
||||
// L'accesso a Bidoo, prima sezione delle Impostazioni, con il riquadro aperto e un testo incollato a mano (non si
|
||||
// invia). Nel simulatore il riquadro parte chiuso, come con un utente collegato.
|
||||
await Shot("03-accesso", "#/impostazioni", "document.querySelector('.access-box').open = true; document.querySelector('textarea.paste').value = \"curl 'https://it.bidoo.com/' -b '__stattrb=…; PHPSESSID=…' -H 'user-agent: …'\"", 1500);
|
||||
if (args.Contains("--messaggio"))
|
||||
if (parsed.Message)
|
||||
{
|
||||
// Il messaggio a schermo per un'informazione importante: senza token Telegram il
|
||||
// messaggio di prova risponde che manca la configurazione.
|
||||
@@ -191,6 +240,9 @@ else
|
||||
|
||||
try { await cdp.SendAsync("Browser.close", timeout: TimeSpan.FromSeconds(3)); } catch { }
|
||||
|
||||
// La misura ha il suo esito (gli errori JavaScript sono uno dei suoi criteri).
|
||||
if (measureExit is { } exit) return exit;
|
||||
|
||||
if (errors.Count == 0)
|
||||
{
|
||||
Console.WriteLine($"Nessun errore JavaScript. Schermate in {outDir}");
|
||||
|
||||
Reference in new issue
Block a user