From d84d396f86b1df5cba6ea200443dd33e1cbc0da5 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Fri, 27 Nov 2026 09:46:39 +0100 Subject: [PATCH] Misura delle prestazioni dell'interfaccia con 60 aste (#34) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 , 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 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 --- .gitea/workflows/prove-a-mano.yml | 83 +++- CLAUDE.md | 8 +- docs/architettura.md | 3 + docs/guida/Sviluppo.md | 48 ++- docs/processo.md | 9 +- src/Mimante/Config/EnvConfig.cs | 25 +- src/Mimante/Host/Bot.cs | 2 +- src/Mimante/Host/BotWorld.cs | 40 +- src/Mimante/Host/SimulatorPlan.cs | 50 +++ src/Mimante/Simulator/SimWorld.cs | 38 +- tests/Mimante.Tests/Mimante.Tests.csproj | 16 + .../Mimante.Tests/Packaging/PipelineTests.cs | 47 +++ tests/Mimante.Tests/PerfAnalysisTests.cs | 352 +++++++++++++++++ tests/Mimante.Tests/SimulatorPlanTests.cs | 154 ++++++++ tools/Mimante.Schermate/Arguments.cs | 95 +++++ .../Mimante.Schermate/Misura/PerfAnalysis.cs | 373 ++++++++++++++++++ tools/Mimante.Schermate/Misura/PerfRun.cs | 246 ++++++++++++ tools/Mimante.Schermate/Misura/PerfScript.cs | 188 +++++++++ tools/Mimante.Schermate/Program.cs | 78 +++- 19 files changed, 1812 insertions(+), 43 deletions(-) create mode 100644 src/Mimante/Host/SimulatorPlan.cs create mode 100644 tests/Mimante.Tests/PerfAnalysisTests.cs create mode 100644 tests/Mimante.Tests/SimulatorPlanTests.cs create mode 100644 tools/Mimante.Schermate/Arguments.cs create mode 100644 tools/Mimante.Schermate/Misura/PerfAnalysis.cs create mode 100644 tools/Mimante.Schermate/Misura/PerfRun.cs create mode 100644 tools/Mimante.Schermate/Misura/PerfScript.cs diff --git a/.gitea/workflows/prove-a-mano.yml b/.gitea/workflows/prove-a-mano.yml index 1ed6952..1677e1d 100644 --- a/.gitea/workflows/prove-a-mano.yml +++ b/.gitea/workflows/prove-a-mano.yml @@ -5,7 +5,10 @@ # dice anche quanto pesa l'immagine; # schermate il bot con --simulatore dentro il lavoro (non nell'immagine), contro un PostgreSQL di servizio, e # tools/Mimante.Schermate con il Chromium di Debian: deve finire con «Nessun errore JavaScript» e le -# schermate restano come artefatto da guardare (e da copiare in docs/schermate per il README). +# schermate restano come artefatto da guardare (e da copiare in docs/schermate per il README); +# prestazioni dopo gli altri due (la misura vuole la macchina libera), il bot con --simulatore --simulatore-aste 60 +# e tools/Mimante.Schermate --misura 120: i criteri della specifica §9.11 sulla pagina Aste (#34), con +# misura.json e misura.txt come artefatto; fallisce se un criterio vincolante fallisce o la misura non vale. # Stesso demone Docker del PostgreSQL vero: nessuna porta pubblicata, prove dell'immagine su rete interna, pulizia sempre. name: prove-a-mano @@ -114,7 +117,8 @@ jobs: - name: Compilazione run: dotnet build Mimante.slnx -c Release -nologo - # Con --simulatore gira anche il mondo del sito vero, come sul PC: legge l'elenco pubblico delle aste, senza utente. + # Con --simulatore e senza utente Bidoo collegato gira solo il simulatore interno (Bot.Services.cs, SwitchWorldAsync): + # nessuna richiesta al sito vero. - name: Bot con --simulatore run: | mkdir -p out @@ -146,3 +150,78 @@ jobs: path: out/bot.log retention-days: 7 if-no-files-found: ignore + + # La misura delle prestazioni dell'interfaccia (specifica §9.11, #34). Un lavoro a sé, dopo carico e schermate: due + # lavori in parallelo sullo stesso runner si rubano la CPU e la misura non direbbe nulla dell'interfaccia. Parte anche + # se gli altri due falliscono. La password dell'interfaccia arriva allo strumento da UI_PASSWORD, non dalla riga. + prestazioni: + needs: [carico, schermate] + if: ${{ !cancelled() }} + runs-on: ubuntu-latest + timeout-minutes: 30 + container: + image: node:24-trixie + services: + postgres: + image: postgres:18 + env: + POSTGRES_USER: admin + POSTGRES_DB: autobidder + POSTGRES_HOST_AUTH_METHOD: trust + options: >- + --health-cmd "pg_isready -U admin -d autobidder" + --health-interval 5s + --health-timeout 5s + --health-retries 20 + env: + DB_HOST: postgres + DB_PASSWORD: prova + UI_PASSWORD: prova + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: "10.0.x" + + - name: Chromium e caratteri di Debian + run: | + apt-get update -qq + DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends chromium fonts-liberation fonts-dejavu-core > /dev/null + chromium --version + + - name: Compilazione + run: dotnet build Mimante.slnx -c Release -nologo + + # Sessanta aste, tre su quattro in Attiva, ciclo di 5 s: almeno dieci insieme sotto i 4 s (SimulatorPlan.ForLoad). + - name: Bot con --simulatore --simulatore-aste 60 + run: | + mkdir -p out + nohup dotnet src/Mimante/bin/Release/net10.0/Mimante.dll --config "$PWD/out/config" --simulatore --simulatore-aste 60 > out/bot.log 2>&1 & + for _ in $(seq 1 60); do + curl -fsS http://localhost:8080/salute > /dev/null 2>&1 && break + sleep 2 + done + curl -fsS http://localhost:8080/salute > /dev/null + echo "bot pronto" + + - name: Misura delle prestazioni (120 s) + run: dotnet tools/Mimante.Schermate/bin/Release/net10.0/Mimante.Schermate.dll http://localhost:8080 out/prestazioni --misura 120 + + - name: Risultati della misura + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v3 + with: + name: prestazioni + path: out/prestazioni + retention-days: 30 + if-no-files-found: warn + + - name: Registro del bot (prestazioni) + if: failure() + uses: actions/upload-artifact@v3 + with: + name: registro-bot-prestazioni + path: out/bot.log + retention-days: 7 + if-no-files-found: ignore diff --git a/CLAUDE.md b/CLAUDE.md index d893d53..77230ac 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -97,10 +97,14 @@ dotnet run --project src/Mimante -- --config "$PWD/tools/dev/config" --simulator # Immagine e screenshot per il README docker build -f docker/Dockerfile --build-arg VERSION=1.9.1 -t mimante:dev . dotnet run --project tools/Mimante.Schermate -- http://localhost:8080 dev docs/schermate # bot con --simulatore; Chrome o Edge del PC; --messaggio il messaggio a schermo + +# Prestazioni dell'interfaccia (specifica §9.11): bot con --simulatore --simulatore-aste 60, password da UI_PASSWORD +dotnet run --project tools/Mimante.Schermate -- http://localhost:8080 out/prestazioni --misura 120 ``` -`--config ` e `--simulatore` servono solo allo sviluppo fuori dal container (predefinito -`/config`, sito vero): nessuna variabile d'ambiente oltre a quelle di §10.1 della specifica. +`--config `, `--simulatore` e, con questo, `--simulatore-aste ` (N aste in elenco, per la misura +delle prestazioni) servono solo allo sviluppo fuori dal container (predefinito `/config`, sito vero): nessuna +variabile d'ambiente oltre a quelle di §10.1 della specifica. Il rilascio è un tag `vX.Y.Z` uguale a `` in `Directory.Build.props` (`.gitea/workflows/rilascio.yml`). Non stampare mai token o password. diff --git a/docs/architettura.md b/docs/architettura.md index 6537bd3..b0c6a42 100644 --- a/docs/architettura.md +++ b/docs/architettura.md @@ -475,6 +475,9 @@ La sessione (`SessionStore`) è `/config/sessione/sessione.json` cifrato AES-256 Avversari con profili (aggressivo, cecchino, autopuntata, principiante, costo affondato). Serve a test, riscaldamento all'avvio, schermate del README e alla modalità debug (`--simulatore`). Non è la realtà: ciò che il modello impara lì resta in `ml-sim/*`. +Con `--simulatore-aste N` (`Host/SimulatorPlan`) il mondo tiene N aste in elenco, quasi tutte in Attiva, con un ciclo +di 5 s e due autopuntate senza fine per asta: il carico della misura delle prestazioni dell'interfaccia +(`tools/Mimante.Schermate --misura`, specifica §9.11). ## Sicurezza diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md index f19192c..ff35725 100644 --- a/docs/guida/Sviluppo.md +++ b/docs/guida/Sviluppo.md @@ -66,8 +66,9 @@ $env:DB_HOST="localhost"; $env:DB_PASSWORD="dev"; $env:UI_PASSWORD="dev" dotnet run --project src/Mimante -- --config "$PWD/tools/dev/config" --simulatore ``` -L'interfaccia è su `http://localhost:8080`, password `dev`. `--config ` e `--simulatore` servono solo allo -sviluppo fuori dal contenitore: nel contenitore la cartella è `/config` e il mondo è sempre il sito vero. +L'interfaccia è su `http://localhost:8080`, password `dev`. `--config `, `--simulatore` e +`--simulatore-aste ` servono solo allo sviluppo fuori dal contenitore: nel contenitore la cartella è `/config` e il +mondo è sempre il sito vero. **Da VS Code** (`.vscode/`): la configurazione «Mimante (locale, PostgreSQL di sviluppo)» fa lo stesso con il debugger; le attività `build`, `build release`, `postgres`, `verifica`, `bot in locale`, `schermate` e `immagine` @@ -92,6 +93,11 @@ I dati del simulatore hanno `auctions.type = 'sim'` e il modello sta in `ml-sim/ memoria. Ogni lettura dell'archivio filtra per mondo: **nessun dato del simulatore deve finire nel modello vero**. Il riscatto delle puntate gratis nel simulatore non esiste. +Di solito il simulatore ha 14 aste, ne mette 8 in elenco al primo giro e ne tiene 6 in corso. Con +`--simulatore-aste ` (da 1 a 500, solo insieme a `--simulatore`) ne tiene **N** in elenco, tre su quattro in +Attiva, con un ciclo di 5 secondi e aste che non chiudono (`Host/SimulatorPlan`): è il carico per la misura delle +prestazioni qui sotto. Senza l'argomento il simulatore è quello di sempre. + ## Le regole del progetto, in breve L'elenco completo è in `CLAUDE.md`; il perché di ogni tabella in `docs/architettura.md`. @@ -124,7 +130,41 @@ dotnet run --project tools/Mimante.Schermate -- http://localhost:8080 dev docs/s Lo strumento usa il Chrome o l'Edge del PC e fotografa le pagine in `docs/schermate/`. Esce con 1 se una pagina ha errori JavaScript. Dopo ogni modifica all'interfaccia deve finire con «Nessun errore JavaScript», e le schermate vanno -guardate. +guardate. Senza la password fra gli argomenti (`... http://localhost:8080 docs/schermate`) lo strumento usa la +variabile `UI_PASSWORD`, così non resta nella cronologia della shell; `--help` elenca i modi. + +## La misura delle prestazioni + +I criteri della specifica (§9.11) per la pagina Aste si misurano con lo stesso strumento, contro il bot avviato con 60 +aste: + +```powershell +dotnet run --project src/Mimante -- --config "$PWD/tools/dev/config" --simulatore --simulatore-aste 60 +dotnet run --project tools/Mimante.Schermate -- http://localhost:8080 out/prestazioni --misura 120 # UI_PASSWORD +``` + +Lo strumento entra nella pagina Aste, aspetta l'elenco pieno e, per i secondi chiesti, guarda la pagina dall'interno +(`tools/Mimante.Schermate/Misura`, tutto via DevTools come le schermate): + +| Criterio | Come si misura | Limite | +|---|---|---| +| Frame persi nei countdown | intervalli fra due `requestAnimationFrame` oltre 1,5 frame | nessuno | +| Blocchi del thread | ogni funzione data dall'interfaccia a un timer, a `requestAnimationFrame` o a un `ResizeObserver`, ogni ascoltatore del puntatore, dello scorrimento e della finestra e la gestione di ogni messaggio, cronometrati uno per uno; più i compiti lunghi del browser (oltre 50 ms, anche layout e stile). Vale per la misura e per le fasi di maniglia e finestra | nessuno oltre 16 ms, nessun compito lungo | +| Riga aggiornata | da un messaggio `auction.delta` al primo frame dopo la sua gestione | entro 100 ms | +| Riconnessione | il canale chiuso dalla pagina, fino al nuovo elenco a schermo (tre prove) | sotto i 2 s | +| Maniglia e finestra | la maniglia del pannello trascinata e la finestra ristretta: nessun `` ancora in vista diventa un nodo nuovo | nessuna riga ridisegnata | +| Errori JavaScript | come per le schermate | nessuno | +| CPU della scheda | tempo dei compiti della scheda sul tempo trascorso | sotto il 15%, **solo riportata** | + +La CPU non decide: Chromium senza finestra e senza GPU non è un portatile medio. La misura **non vale** se in elenco ci +sono meno di 60 aste, se anche un solo campione (uno al secondo) ha meno di 10 aste in Attiva sotto i 4 s, se il +canale cade, se non arrivano aggiornamenti, se la maniglia non si muove, se la griglia scorre durante il trascinamento +o se durante maniglia e finestra ha più di 60 righe disegnate o si virtualizza (più di 60 aste in elenco: la prova dei +nodi non direbbe nulla). Un compito lungo del browser, in qualunque fase, fa fallire i blocchi del thread. Solo i frame +persi durante maniglia e finestra si riportano e basta: gli eventi mandati via DevTools non seguono il ritmo dei frame. + +Nella cartella restano `misura.json` (tutti i numeri) e `misura.txt` (da leggere). Lo strumento esce con 1 se la misura +non vale o se un criterio vincolante fallisce. In CI la fa il lavoro `prestazioni` di `prove-a-mano.yml`. ## L'immagine @@ -147,7 +187,7 @@ demone Docker del PostgreSQL vero: per questo nessun flusso pubblica porte. | `verifica.yml` | A ogni push su qualunque ramo, e a mano | `controlli` (sintassi, versione, pacchetti, CHANGELOG, nessuna risorsa esterna, gitleaks su tutta la storia), `prove` (build con avvisi come errori e tutti i test, con un `postgres:18` di servizio), `immagine` (costruzione, prova su una rete interna fino a `/salute` verde, Trivy). Da `main` pubblica `:main` e `:sha-` | | `rilascio.yml` | Su un tag `v*` | Rifiuta un tag diverso da ``, rifà le prove, pubblica `:X.Y.Z` e `:latest`, crea il rilascio con la sezione del CHANGELOG e `mimante-unraid-X.Y.Z.xml`. Un tag con il trattino (`v2.0.0-rc.1`) è una prova: solo `:X.Y.Z-rc.N` | | `pulizia.yml` | Ogni notte e a mano | Toglie i resti delle prove di Mimante e le etichette `sha-` oltre le 10 più recenti | -| `prove-a-mano.yml` | Solo a mano, prima di un rilascio | `carico` (un milione di righe esportate con `--memory=1g`, poi una seconda annullata) e `schermate` (il bot in `--simulatore` e lo strumento delle schermate). L'esito va in `docs/stato.md` | +| `prove-a-mano.yml` | Solo a mano, prima di un rilascio | `carico` (un milione di righe esportate con `--memory=1g`, poi una seconda annullata), `schermate` (il bot in `--simulatore` e lo strumento delle schermate) e, dopo questi due, `prestazioni` (il bot con `--simulatore-aste 60` e la misura di 120 s, risultati come artefatto). L'esito va in `docs/stato.md` | I controlli veloci si lanciano anche a mano: `bash .gitea/scripts/controlli.sh`. Segreto del repository: `REGISTRY_TOKEN`; senza, l'immagine si prova ma non si pubblica. diff --git a/docs/processo.md b/docs/processo.md index 796eb0b..de8d83d 100644 --- a/docs/processo.md +++ b/docs/processo.md @@ -96,7 +96,14 @@ rete Docker interna con un PostgreSQL usa e getta. se il bot cade, se Docker lo uccide per memoria, se il picco di memoria residente supera 768 MB o se restano file a metà (`prova-carico.sh`, `prova-carico.js`). Dice anche quanto pesa l'immagine; - `schermate`: il bot con `--simulatore` dentro il lavoro e `tools/Mimante.Schermate` con il Chromium - di Debian; deve finire con «Nessun errore JavaScript», le schermate restano come artefatto. + di Debian; deve finire con «Nessun errore JavaScript», le schermate restano come artefatto; + - `prestazioni` (#34): dopo `carico` e `schermate`, anche se falliscono (due lavori insieme sullo + stesso runner si rubano la CPU e la misura non direbbe nulla), il bot con `--simulatore + --simulatore-aste 60` e `tools/Mimante.Schermate --misura 120` (la password da `UI_PASSWORD`). Misura + i criteri della specifica §9.11 sulla pagina Aste (docs/guida/Sviluppo.md, «La misura delle + prestazioni»); `misura.json` e `misura.txt` restano come artefatto. Fallisce se un criterio + vincolante fallisce o se la misura non vale (meno di 60 aste, un campione con meno di 10 in + finestra critica, griglia che scorre o si virtualizza durante maniglia e finestra). L'esito va in `docs/stato.md`. - **`pulizia.yml`**, ogni notte e a mano: toglie i contenitori, le reti e i volumi lasciati dalle prove di Mimante e le etichette `sha-` più vecchie del pacchetto `mimante`. Il resto del demone lo pulisce diff --git a/src/Mimante/Config/EnvConfig.cs b/src/Mimante/Config/EnvConfig.cs index c1398e1..96bc2f7 100644 --- a/src/Mimante/Config/EnvConfig.cs +++ b/src/Mimante/Config/EnvConfig.cs @@ -32,13 +32,26 @@ public sealed class EnvConfig /// public bool SimulatorMode { get; init; } + /// + /// Quante aste tiene in elenco il simulatore (--simulatore-aste N, da 1 a + /// ): per la misura delle prestazioni dell'interfaccia + /// (specifica §9.11). Vale solo insieme a --simulatore; null = il simulatore di sempre. + /// + public int? SimulatorAuctions { get; init; } + + /// Il limite di --simulatore-aste: oltre, il simulatore misurerebbe sé stesso. + public const int MaxSimulatorAuctions = 500; + public bool HasDbHost => !string.IsNullOrWhiteSpace(DbHost); public bool HasDbPassword => !string.IsNullOrEmpty(DbPassword); public bool HasUiPassword => !string.IsNullOrEmpty(UiPassword); public DbConfig ToDbConfig() => new(DbHost, DbPort, DbUser, DbPassword ?? "", DbName); - /// Legge l'ambiente e gli argomenti (--config cartella solo per lo sviluppo). + /// + /// Legge l'ambiente e gli argomenti, che servono solo allo sviluppo: --config cartella, + /// --simulatore e, con questo, --simulatore-aste N. Un numero non valido si ignora. + /// public static EnvConfig Read(Func env, string[] args) { var rawHost = env("DB_HOST")?.Trim(); @@ -55,6 +68,13 @@ public sealed class EnvConfig if (args[i] == "--config") configDir = Path.GetFullPath(args[i + 1]); } var simulator = args.Contains("--simulatore"); + int? simulatorAuctions = null; + for (var i = 0; simulator && i < args.Length - 1; i++) + { + if (args[i] == "--simulatore-aste" && + int.TryParse(args[i + 1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) && n is > 0 and <= MaxSimulatorAuctions) + simulatorAuctions = n; + } return new EnvConfig { @@ -68,7 +88,8 @@ public sealed class EnvConfig HttpPort = httpPort, ConfigDir = configDir, TimeZone = NonEmpty(env("TZ")) ?? "Europe/Rome", - SimulatorMode = simulator + SimulatorMode = simulator, + SimulatorAuctions = simulatorAuctions }; } diff --git a/src/Mimante/Host/Bot.cs b/src/Mimante/Host/Bot.cs index fcc6892..71d17ef 100644 --- a/src/Mimante/Host/Bot.cs +++ b/src/Mimante/Host/Bot.cs @@ -50,7 +50,7 @@ public sealed partial class Bot : IAsyncDisposable await bot.StartServicesAsync(ct).ConfigureAwait(false); host.Log.Info("AVVIO", $"{AppInfo.Name} {AppInfo.Version} pronto: database {db.Config.Describe()}, " + - $"{(host.Env.SimulatorMode ? "modalità debug con il simulatore" : "sito vero")}"); + $"{(!host.Env.SimulatorMode ? "sito vero" : host.Env.SimulatorAuctions is { } n ? $"modalità debug con il simulatore a {n} aste" : "modalità debug con il simulatore")}"); return bot; } catch diff --git a/src/Mimante/Host/BotWorld.cs b/src/Mimante/Host/BotWorld.cs index fbb9a03..f60018e 100644 --- a/src/Mimante/Host/BotWorld.cs +++ b/src/Mimante/Host/BotWorld.cs @@ -24,6 +24,7 @@ public sealed class BotWorld : IAsyncDisposable { private readonly CancellationTokenSource _cts; private readonly List _jobs = new(); + private SimulatorPlan _plan = SimulatorPlan.Default; public string Name { get; } public bool IsSimulator => Name == Worlds.Simulator; @@ -88,10 +89,21 @@ public sealed class BotWorld : IAsyncDisposable "ml/", "monitor/auctions", null, session != null, parent).ConfigureAwait(false); } - /// Il simulatore interno (solo con --simulatore, per test e debug). + /// + /// Il simulatore interno (solo con --simulatore, per test e debug); con --simulatore-aste N + /// porta N aste in elenco (). + /// public static async Task CreateSimulatorAsync(Bot bot, CancellationToken parent) { - var sim = await SimulatedBidoo.StartAsync(new SimWorld(seed: Environment.TickCount)).ConfigureAwait(false); + var plan = SimulatorPlan.From(bot.Host.Env.SimulatorAuctions); + var simWorld = new SimWorld(seed: Environment.TickCount, populate: false) + { + TargetAuctions = plan.WorldAuctions, + FixedFreqSeconds = plan.FreqSeconds, + EndlessAuctions = plan.Load + }; + simWorld.Populate(); + var sim = await SimulatedBidoo.StartAsync(simWorld).ConfigureAwait(false); var simRefs = sim.References(bot.ReferencesProvider.Current); Func refs = () => simRefs; var transport = new BidooTransport(refs, 0); @@ -107,8 +119,10 @@ public sealed class BotWorld : IAsyncDisposable account.SetStatus(SessionStatus.Simulator, "modalità debug: stai vedendo il simulatore"); var risk = new RiskManager(new MemoryDocumentStore(), new MemoryRiskLedger(), log: bot.Log); - return await BuildAsync(bot, Worlds.Simulator, refs, transport, lane, api, account, risk, new LatencyModel(new MemoryDocumentStore()), + var world = await BuildAsync(bot, Worlds.Simulator, refs, transport, lane, api, account, risk, new LatencyModel(new MemoryDocumentStore()), "ml-sim/", "monitor/auctions-sim", sim, true, parent).ConfigureAwait(false); + world._plan = plan; + return world; } private static async Task BuildAsync(Bot bot, string name, Func refs, BidooTransport transport, BidLane lane, @@ -211,18 +225,17 @@ public sealed class BotWorld : IAsyncDisposable : $"Sito vero senza utente collegato: segue le aste e impara, non punta. Collega l'utente da Accesso a Bidoo per puntare. {Monitor.Auctions.Count} aste in elenco"); } - /// Al primo giro nel simulatore l'elenco non è vuoto: qualche asta in ogni modo, per vedere il bot all'opera. + /// + /// Al primo giro nel simulatore l'elenco non è vuoto: qualche asta in ogni modo, per vedere il bot all'opera + /// (con --simulatore-aste quante ne chiede, quasi tutte in Attiva). + /// private async Task SeedSimulatorAsync(CancellationToken ct) { if (Sim == null) return; - var ids = Sim.World.Read(w => w.Auctions.Where(a => a.Status == "ON").Select(a => a.Id).Take(8).ToList()); + var ids = Sim.World.Read(w => w.Auctions.Where(a => a.Status == "ON").Select(a => a.Id).Take(_plan.SeedAuctions).ToList()); var i = 0; foreach (var id in ids) - { - var mode = i switch { < 3 => RunMode.Active, 7 => RunMode.Stopped, _ => RunMode.Watch }; - await Monitor.AddAsync(new AddAuctionRequest(id, "catalogo", mode), ct).ConfigureAwait(false); - i++; - } + await Monitor.AddAsync(new AddAuctionRequest(id, "catalogo", _plan.SeedMode(i++)), ct).ConfigureAwait(false); } /// Di fondo: ogni 6 ore (la prima dopo 10 minuti) le puntate dei vincitori mancanti. @@ -251,13 +264,14 @@ public sealed class BotWorld : IAsyncDisposable if (Sim == null || !await _topUp.WaitAsync(0, ct).ConfigureAwait(false)) return; try { + var target = _plan.RunningAuctions; var running = Monitor.Auctions.Count(a => !a.IsFinished); - if (running >= 6) return; + if (running >= target) return; var ids = Sim.World.Read(w => w.Auctions.Where(a => a.Status == "ON").Select(a => a.Id).ToList()) - .Where(id => Monitor.Find(id) == null).Take(6 - running).ToList(); + .Where(id => Monitor.Find(id) == null).Take(target - running).ToList(); var i = 0; foreach (var id in ids) - await Monitor.AddAsync(new AddAuctionRequest(id, "catalogo", i++ % 3 == 0 ? RunMode.Active : RunMode.Watch), ct).ConfigureAwait(false); + await Monitor.AddAsync(new AddAuctionRequest(id, "catalogo", _plan.TopUpMode(i++)), ct).ConfigureAwait(false); } catch (OperationCanceledException) { } finally { _topUp.Release(); } diff --git a/src/Mimante/Host/SimulatorPlan.cs b/src/Mimante/Host/SimulatorPlan.cs new file mode 100644 index 0000000..75feadb --- /dev/null +++ b/src/Mimante/Host/SimulatorPlan.cs @@ -0,0 +1,50 @@ +using Mimante.Config; +using Mimante.Engine; + +namespace Mimante.Host; + +/// +/// Quante aste ha il simulatore e come entrano in elenco. Senza --simulatore-aste vale +/// , il simulatore di sempre: 14 aste nel mondo, 8 in elenco al primo giro +/// (tre in Attiva, una in Ferma), un rabbocco che ne tiene 6 in corso, la frequenza di ogni prodotto. +/// +/// Con --simulatore-aste N (, per la misura delle prestazioni +/// dell'interfaccia, specifica §9.11) il mondo ha un margine di aste oltre le N in elenco, il seme e +/// il rabbocco ne tengono N, tre su quattro in Attiva, e ogni asta ha un ciclo di +/// secondi: a ogni puntata il ciclo riparte pieno e gli avversari +/// puntano a 0,7-3 s dalla fine, così con un ciclo corto un'asta passa sotto i 4 s gran parte del +/// tempo e dieci aste in finestra critica insieme sono la regola, non il caso. +/// +public sealed record SimulatorPlan(int WorldAuctions, int SeedAuctions, int RunningAuctions, int? FreqSeconds, bool Load) +{ + /// Il ciclo delle aste nella prova di carico. + public const int LoadFreqSeconds = 5; + + /// Il simulatore senza --simulatore-aste. + public static SimulatorPlan Default { get; } = new(14, 8, 6, null, false); + + /// + /// aste in elenco. Il mondo ne ha un quarto in più (almeno 14): alcune + /// sono programmate o sospese, e quelle concluse tornano solo dopo qualche minuto, e il rabbocco + /// deve trovare aste nuove da mettere in elenco. + /// + public static SimulatorPlan ForLoad(int auctions) + { + var n = Math.Clamp(auctions, 1, EnvConfig.MaxSimulatorAuctions); + return new SimulatorPlan(Math.Max(14, n + n / 4 + 4), n, n, LoadFreqSeconds, true); + } + + /// Da --simulatore-aste: null = il simulatore di sempre. + public static SimulatorPlan From(int? auctions) => auctions is { } n ? ForLoad(n) : Default; + + /// Il modo dell'asta numero (da zero) messa in elenco al primo giro. + public RunMode SeedMode(int index) => Load + ? LoadMode(index) + : index switch { < 3 => RunMode.Active, 7 => RunMode.Stopped, _ => RunMode.Watch }; + + /// Il modo dell'asta numero di un rabbocco. + public RunMode TopUpMode(int index) => Load ? LoadMode(index) : index % 3 == 0 ? RunMode.Active : RunMode.Watch; + + /// Tre su quattro in Attiva: le aste in finestra critica che contano per la misura sono quelle. + private static RunMode LoadMode(int index) => index % 4 == 3 ? RunMode.Watch : RunMode.Active; +} diff --git a/src/Mimante/Simulator/SimWorld.cs b/src/Mimante/Simulator/SimWorld.cs index d5e2061..c2bb4a6 100644 --- a/src/Mimante/Simulator/SimWorld.cs +++ b/src/Mimante/Simulator/SimWorld.cs @@ -30,6 +30,9 @@ public sealed class SimBidder public int Spent { get; set; } public bool Quit { get; set; } + /// Non smette mai (le autopuntate della prova di carico, ). + public bool Endless { get; init; } + /// Millisecondi dalla fine a cui punterà in questo ciclo; null = in questo ciclo non punta. public double? PlannedAtMs { get; set; } } @@ -99,6 +102,20 @@ public sealed class SimWorld /// Quante aste tenere in vita (le concluse vengono sostituite). public int TargetAuctions { get; set; } = 14; + /// + /// Il ciclo di ogni asta nuova in secondi, uguale per tutte; null = quello del prodotto. Serve alla + /// prova di carico (--simulatore-aste): con un ciclo corto molte aste stanno insieme sotto i 4 s. + /// + public int? FixedFreqSeconds { get; set; } + + /// + /// Aste che non chiudono, per la prova di carico (--simulatore-aste): ognuna ha due autopuntate + /// senza limite e senza stanchezza, e gli avversari delle aste già in corso alla nascita del mondo sono + /// pronti dal primo ciclo. Senza (il simulatore di sempre) il primo ciclo lo tiene vivo solo una puntata + /// del bot e le aste chiudono quando gli avversari si stancano; la misura vuole invece un elenco stabile. + /// + public bool EndlessAuctions { get; set; } + /// Probabilità per ciclo che un'asta resti senza avversari (e chiuda). public double Fatigue { get; set; } = 1.0; @@ -179,14 +196,14 @@ public sealed class SimWorld } } - private SimAuction NewAuction(Product p, long openAt) + private SimAuction NewAuction(Product p, long openAt, int? freq = null) { var id = (_nextId++).ToString(CultureInfo.InvariantCulture); var slug = Slug(p.Name) + "_" + id; var a = new SimAuction { Id = id, ProductId = p.Id, Name = p.Name, Slug = slug, CategoryTag = p.Tag, Value = p.Value, - Shipping = p.Shipping, FreqSeconds = p.Freq, ExpiryUnix = openAt + Shipping = p.Shipping, FreqSeconds = freq ?? FixedFreqSeconds ?? p.Freq, ExpiryUnix = openAt }; var count = 2 + _rng.Next(6); @@ -208,6 +225,11 @@ public sealed class SimWorld } }); } + if (EndlessAuctions) + { + foreach (var name in new[] { "auto_carico", "auto_prova" }) + a.Bidders.Add(new SimBidder { Name = name, Profile = SimProfile.AutoBid, MaxBids = int.MaxValue, Endless = true }); + } return a; } @@ -223,6 +245,7 @@ public sealed class SimWorld b.Spent++; } a.ExpiryUnix = now + 3 + _rng.Next(a.FreqSeconds); + if (EndlessAuctions) PlanBidders(a); } private static string Slug(string name) @@ -310,6 +333,12 @@ public sealed class SimWorld { a.ExpiryUnix = nowUnix + a.FreqSeconds; a.CycleNumber++; + PlanBidders(a); + } + + /// Chi degli avversari punta in questo ciclo, e a quanti millisecondi dalla fine. + private void PlanBidders(SimAuction a) + { var depth = a.PriceCents; foreach (var b in a.Bidders) @@ -326,7 +355,7 @@ public sealed class SimWorld SimProfile.Aggressive => 0.01 + depth / 200_000.0, _ => 0.012 } * Fatigue; - if (_rng.NextDouble() < quit) { b.Quit = true; continue; } + if (!b.Endless && _rng.NextDouble() < quit) { b.Quit = true; continue; } var freqMs = a.FreqSeconds * 1000.0; b.PlannedAtMs = b.Profile switch @@ -398,8 +427,7 @@ public sealed class SimWorld { lock (_sync) { - var p = Products[0] with { Freq = freq }; - var a = NewAuction(p, NowUnix); + var a = NewAuction(Products[0], NowUnix, freq); if (!withOpponents) a.Bidders.Clear(); a.Bidders.Insert(0, new SimBidder { Name = "apri_asta", Profile = SimProfile.Beginner, MaxBids = 1 }); AddBid(a, "apri_asta", NowUnix - 1, auto: false, paid: true); diff --git a/tests/Mimante.Tests/Mimante.Tests.csproj b/tests/Mimante.Tests/Mimante.Tests.csproj index 19cd171..8be959e 100644 --- a/tests/Mimante.Tests/Mimante.Tests.csproj +++ b/tests/Mimante.Tests/Mimante.Tests.csproj @@ -16,6 +16,22 @@ + + + ..\..\tools\Mimante.Schermate\Mimante.Schermate.csproj + + + + + + + + diff --git a/tests/Mimante.Tests/Packaging/PipelineTests.cs b/tests/Mimante.Tests/Packaging/PipelineTests.cs index 0908b76..cd5971d 100644 --- a/tests/Mimante.Tests/Packaging/PipelineTests.cs +++ b/tests/Mimante.Tests/Packaging/PipelineTests.cs @@ -1,4 +1,5 @@ using System.Text.RegularExpressions; +using System.Xml.Linq; using Xunit; namespace Mimante.Tests.Packaging; @@ -119,6 +120,15 @@ public sealed partial class PipelineTests Assert.Contains("--simulatore", Job(workflow, "schermate")); Assert.DoesNotContain("--simulatore", Code(Job(workflow, "carico"))); + // The performance trial (#34) runs alone after the others, with 60 simulated auctions, and gets the password of + // the interface from UI_PASSWORD, never on its command line. + var performance = Code(Job(workflow, "prestazioni")); + Assert.Contains("needs: [carico, schermate]", performance); + Assert.Contains("--simulatore --simulatore-aste 60", performance); + Assert.Contains("Mimante.Schermate.dll http://localhost:8080 out/prestazioni --misura 120", performance); + Assert.DoesNotContain("$UI_PASSWORD", performance); + Assert.Contains("uses: actions/upload-artifact@v3", performance); + var load = Code(Script("prova-carico.sh")); Assert.Contains("docker network create --internal", load); Assert.Contains("--memory=1g", load); @@ -166,6 +176,43 @@ public sealed partial class PipelineTests Assert.StartsWith("#!/usr/bin/env bash", File.ReadAllText(file)); } + /// + /// The build stage of docker/Dockerfile compiles tests/Mimante.Tests with only src/ and tests/ in the context + /// (.dockerignore drops tools/): a reference of the test project outside those two folders must depend on the + /// project being there, and the tests that need it must leave the compilation when it is not (issue #34). + /// + [Fact] + public void TheImageBuildsTheTestsWithoutTools() + { + var ignore = Read(".dockerignore").Split('\n').Select(l => l.Trim()).ToList(); + Assert.Contains("tools", ignore); + var dockerfile = Read("docker", "Dockerfile"); + Assert.DoesNotContain("COPY tools", dockerfile); + + var project = XDocument.Parse(Read("tests", "Mimante.Tests", "Mimante.Tests.csproj")); + var properties = project.Descendants("PropertyGroup").Elements() + .ToDictionary(e => e.Name.LocalName, e => e.Value, StringComparer.OrdinalIgnoreCase); + string Expand(string value) => + Regex.Replace(value, @"\$\((?

[A-Za-z0-9_]+)\)", m => properties.GetValueOrDefault(m.Groups["p"].Value, m.Value)); + + foreach (var reference in project.Descendants("ProjectReference")) + { + var path = Expand((string?)reference.Attribute("Include") ?? "").Replace('\\', '/'); + var inContext = !path.StartsWith("../../", StringComparison.Ordinal) + || path.StartsWith("../../src/", StringComparison.Ordinal) || path.StartsWith("../../tests/", StringComparison.Ordinal); + if (inContext) continue; + var condition = Expand((string?)reference.Parent?.Attribute("Condition") ?? "").Replace('\\', '/'); + Assert.True(condition.Contains($"Exists('{path}')", StringComparison.Ordinal), $"{path}: reference without Exists(...)"); + var removed = project.Descendants("Compile") + .Where(c => Expand((string?)c.Parent?.Attribute("Condition") ?? "").Replace('\\', '/') == $"!Exists('{path}')") + .Select(c => (string?)c.Attribute("Remove")) + .ToList(); + Assert.NotEmpty(removed); + } + Assert.Contains("Exists('../../tools/Mimante.Schermate/Mimante.Schermate.csproj')", + Expand(Read("tests", "Mimante.Tests", "Mimante.Tests.csproj")).Replace('\\', '/')); + } + // ---- helpers ---- private static string Workflow(string name) => Read(".gitea", "workflows", name); diff --git a/tests/Mimante.Tests/PerfAnalysisTests.cs b/tests/Mimante.Tests/PerfAnalysisTests.cs new file mode 100644 index 0000000..a623374 --- /dev/null +++ b/tests/Mimante.Tests/PerfAnalysisTests.cs @@ -0,0 +1,352 @@ +using Mimante.Schermate; +using Mimante.Schermate.Misura; +using Xunit; + +namespace Mimante.Tests; + +///

+/// I conti della misura delle prestazioni dell'interfaccia (tools/Mimante.Schermate --misura, specifica §9.11, +/// issue #34): frame, distribuzioni, righe ridisegnate, giudizio e argomenti dello strumento. +/// +public class PerfAnalysisTests +{ + private static List Steady(int count, double frame = 16.67) => Enumerable.Repeat(frame, count).ToList(); + + [Fact] + public void Frame_regolari_non_perdono_nulla() + { + var f = PerfAnalysis.Frames(Steady(600)); + Assert.Equal(600, f.Intervals); + Assert.Equal(16.67, f.FrameMs); + Assert.Equal(0, f.LostFrames); + Assert.Equal(0, f.Blocks); + } + + [Fact] + public void Un_intervallo_lungo_conta_i_frame_che_mancano_e_il_blocco() + { + var intervals = Steady(300); + intervals.Add(50); // due frame saltati, il thread fermo 33 ms + intervals.Add(24); // sotto 1,5 frame: ritardo, non frame perso + var f = PerfAnalysis.Frames(intervals); + Assert.Equal(2, f.LostFrames); + Assert.Equal(1, f.Blocks); + Assert.Equal(33.33, f.WorstBlockMs, 2); + Assert.Equal(50, f.WorstGapMs); + } + + [Fact] + public void La_durata_del_frame_segue_lo_schermo() + { + // A 30 Hz un intervallo di 33 ms è normale. + var f = PerfAnalysis.Frames(Steady(200, 33.3)); + Assert.Equal(33.3, f.FrameMs); + Assert.Equal(0, f.LostFrames); + } + + [Fact] + public void Senza_frame_niente_conti() + { + var f = PerfAnalysis.Frames([]); + Assert.Equal(0, f.Intervals); + Assert.Equal(0, f.LostFrames); + } + + [Fact] + public void Percentili_al_rango_piu_vicino() + { + var values = Enumerable.Range(1, 100).Select(i => (double)i).ToList(); + var d = PerfAnalysis.Distribution(values, 95); + Assert.Equal(100, d.Count); + Assert.Equal(50, d.P50); + Assert.Equal(95, d.P95); + Assert.Equal(99, d.P99); + Assert.Equal(100, d.Max); + Assert.Equal(5, d.Over); + Assert.Equal(0, PerfAnalysis.Distribution([], 100).Count); + } + + [Fact] + public void Una_riga_ancora_in_vista_con_un_nodo_nuovo_e_ridisegnata() + { + var before = new List<(string, long)> { ("1", 1), ("2", 2), ("3", 3) }; + var after = new List<(string, long)> { ("1", 1), ("2", 9), ("3", 3) }; + var r = PerfAnalysis.CompareRows(before, after); + Assert.False(r.Intact); + Assert.Equal(new[] { "2" }, r.Replaced); + Assert.Equal(2, r.Kept); + } + + [Fact] + public void Riordino_e_scorrimento_virtuale_non_sono_errori() + { + // Lo stesso nodo spostato (insertBefore) tiene il suo segno; una riga uscita di vista e una entrata non contano. + var before = new List<(string, long)> { ("1", 1), ("2", 2), ("3", 3) }; + var after = new List<(string, long)> { ("3", 3), ("1", 1), ("4", 4) }; + var r = PerfAnalysis.CompareRows(before, after); + Assert.True(r.Intact); + Assert.Equal(2, r.Kept); + Assert.Equal(3, r.Before); + Assert.Equal(3, r.After); + } + + [Fact] + public void Una_riga_doppia_e_un_errore() + { + var r = PerfAnalysis.CompareRows([("1", 1)], [("1", 1), ("1", 5)]); + Assert.False(r.Intact); + Assert.Equal(new[] { "1" }, r.Duplicated); + } + + [Fact] + public void Una_misura_buona_supera_tutti_i_criteri_vincolanti() + { + var report = PerfAnalysis.Evaluate(Good(), "http://localhost:8080", DateTimeOffset.UnixEpoch); + Assert.True(report.Valid, string.Join("; ", report.InvalidReasons)); + Assert.True(report.Passed); + Assert.Equal(0, report.ExitCode); + Assert.Contains("SUPERATA", PerfAnalysis.Text(report)); + } + + [Fact] + public void La_CPU_alta_si_riporta_ma_non_fa_fallire() + { + var report = PerfAnalysis.Evaluate(Good() with { CpuPercent = 60 }, "x", DateTimeOffset.UnixEpoch); + var cpu = Assert.Single(report.Checks, c => c.Key == "cpu"); + Assert.False(cpu.Binding); + Assert.False(cpu.Passed); + Assert.True(report.Passed); + Assert.Contains("non vincolante", PerfAnalysis.Text(report)); + } + + [Theory] + [InlineData("frames")] + [InlineData("blocks")] + [InlineData("row_update")] + [InlineData("reconnect")] + [InlineData("drag")] + [InlineData("resize")] + [InlineData("js_errors")] + public void Un_criterio_vincolante_fallito_esce_con_uno(string key) + { + var input = Good(); + input = key switch + { + "frames" => input with { FrameIntervals = [.. input.FrameIntervals, 70] }, + "blocks" => input with { TasksMs = [.. input.TasksMs, 22] }, + "row_update" => input with { RowUpdatesMs = [.. input.RowUpdatesMs, 140] }, + "reconnect" => input with { ReconnectsMs = [400, null, 380] }, + "drag" => input with { Drag = input.Drag with { Rows = PerfAnalysis.CompareRows([("1", 1)], [("1", 2)]) } }, + "resize" => input with { Resize = input.Resize with { Rows = PerfAnalysis.CompareRows([("1", 1), ("2", 2)], [("1", 1), ("2", 7)]) } }, + _ => input with { Errors = ["eccezione: TypeError"] } + }; + var report = PerfAnalysis.Evaluate(input, "x", DateTimeOffset.UnixEpoch); + Assert.True(report.Valid); + Assert.False(Assert.Single(report.Checks, c => c.Key == key).Passed); + Assert.Equal(1, report.ExitCode); + Assert.Contains("NON SUPERATA", PerfAnalysis.Text(report)); + } + + [Fact] + public void Un_frame_saltato_senza_compiti_lunghi_non_e_un_blocco_del_thread() + { + var input = Good(); + var report = PerfAnalysis.Evaluate(input with { FrameIntervals = [.. input.FrameIntervals, 33.4] }, "x", DateTimeOffset.UnixEpoch); + Assert.False(Assert.Single(report.Checks, c => c.Key == "frames").Passed); + Assert.True(Assert.Single(report.Checks, c => c.Key == "blocks").Passed); + + var browser = PerfAnalysis.Evaluate(input with { LongTasksMs = [64] }, "x", DateTimeOffset.UnixEpoch); + Assert.False(Assert.Single(browser.Checks, c => c.Key == "blocks").Passed); + } + + [Fact] + public void Con_meno_di_dieci_aste_in_finestra_critica_la_misura_non_vale() + { + var samples = Enumerable.Range(0, 120).Select(i => new PerfSample(60, 45, i % 2 == 0 ? 12 : 7, 60, true)).ToList(); + var report = PerfAnalysis.Evaluate(Good() with { Samples = samples }, "x", DateTimeOffset.UnixEpoch); + Assert.False(report.Valid); + Assert.Contains(report.InvalidReasons, r => r.Contains("sotto i 4 s")); + Assert.Equal(1, report.ExitCode); + Assert.Contains("NON VALIDA", PerfAnalysis.Text(report)); + } + + [Fact] + public void Basta_un_campione_con_meno_di_dieci_aste_in_finestra_critica() + { + // Nessuna tolleranza: 119 campioni buoni e uno con 9 aste sotto i 4 s non bastano (richiesta della issue #34). + var samples = Enumerable.Range(0, 120).Select(i => new PerfSample(60, 45, i == 77 ? 9 : 22, 60, true)).ToList(); + var report = PerfAnalysis.Evaluate(Good() with { Samples = samples }, "x", DateTimeOffset.UnixEpoch); + Assert.False(report.Valid); + Assert.Contains(report.InvalidReasons, r => r.Contains("solo 9 aste")); + + var exactly = Enumerable.Range(0, 120).Select(_ => new PerfSample(60, 45, 10, 60, true)).ToList(); + Assert.True(PerfAnalysis.Evaluate(Good() with { Samples = exactly }, "x", DateTimeOffset.UnixEpoch).Valid); + } + + [Fact] + public void Una_griglia_che_scorre_durante_la_maniglia_rende_la_misura_non_valida() + { + var input = Good(); + var grid = PerfAnalysis.Grid([(0, 60, false), (0, 60, false), (38, 60, false), (0, 60, false)]); + Assert.Equal(38, grid.ScrollMovedPx); + var report = PerfAnalysis.Evaluate(input with { Drag = input.Drag with { Grid = grid } }, "x", DateTimeOffset.UnixEpoch); + Assert.False(report.Valid); + Assert.Contains(report.InvalidReasons, r => r.Contains("scorsa di 38 px")); + } + + [Theory] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(true, true)] + public void Una_griglia_virtualizzata_o_troppo_lunga_rende_la_misura_non_valida(bool virtualized, bool inResize) + { + var input = Good(); + var grid = PerfAnalysis.Grid([(0, 60, false), (0, virtualized ? 30 : 61, virtualized)]); + var report = PerfAnalysis.Evaluate(inResize ? input with { Resize = input.Resize with { Grid = grid } } : input with { Drag = input.Drag with { Grid = grid } }, + "x", DateTimeOffset.UnixEpoch); + Assert.False(report.Valid); + Assert.Contains(report.InvalidReasons, r => r.Contains(inResize ? "ridimensionamento" : "maniglia") && r.Contains(virtualized ? "virtualizzata" : "61 righe")); + } + + [Fact] + public void La_griglia_si_misura_dal_punto_di_partenza() + { + Assert.Equal(new GridState(0, 0, false), PerfAnalysis.Grid([])); + var g = PerfAnalysis.Grid([(120, 58, false), (118, 60, false), (125.5, 59, false)]); + Assert.Equal(5.5, g.ScrollMovedPx); + Assert.Equal(60, g.MaxDrawn); + Assert.False(g.Virtual); + } + + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(true, true)] + public void I_blocchi_di_maniglia_e_finestra_fanno_fallire(bool inResize, bool longTask) + { + var input = Good(); + GesturePhase Slow(GesturePhase p) => longTask + ? p with { LongTasksMs = [72] } + : p with { Tasks = PerfAnalysis.Tasks([0.4, 0.5], [3, 21]) }; + var changed = inResize ? input with { Resize = Slow(input.Resize) } : input with { Drag = Slow(input.Drag) }; + var report = PerfAnalysis.Evaluate(changed, "x", DateTimeOffset.UnixEpoch); + Assert.True(report.Valid, string.Join("; ", report.InvalidReasons)); + Assert.False(Assert.Single(report.Checks, c => c.Key == "blocks").Passed); + Assert.Equal(1, report.ExitCode); + Assert.Contains(inResize ? "finestra: griglia" : "maniglia: pannello", PerfAnalysis.Text(report)); + } + + [Fact] + public void Con_meno_di_sessanta_aste_in_elenco_la_misura_non_vale() + { + var samples = Enumerable.Range(0, 120).Select(_ => new PerfSample(14, 3, 12, 14, true)).ToList(); + var report = PerfAnalysis.Evaluate(Good() with { Samples = samples }, "x", DateTimeOffset.UnixEpoch); + Assert.False(report.Valid); + Assert.Contains(report.InvalidReasons, r => r.Contains("--simulatore-aste 60")); + } + + [Fact] + public void Una_maniglia_che_non_si_muove_rende_la_misura_non_valida() + { + var input = Good(); + var report = PerfAnalysis.Evaluate(input with { Drag = input.Drag with { MovedPx = 0 } }, "x", DateTimeOffset.UnixEpoch); + Assert.False(report.Valid); + } + + [Fact] + public void La_CPU_e_il_tempo_dei_compiti_sul_tempo_trascorso() + { + Assert.Equal(12.5, PerfRun.Cpu((10, 100), (12.5, 120))); + Assert.Null(PerfRun.Cpu(null, (1, 2))); + Assert.Null(PerfRun.Cpu((1, 5), (2, 5))); + } + + [Fact] + public void Lo_script_della_pagina_ha_le_soglie_dentro() + { + var js = PerfScript.Build(); + Assert.DoesNotContain("__CRITICAL_MS__", js); + Assert.Contains("ms < 4000", js); + Assert.Contains("window.WebSocket = PerfSocket", js); + Assert.Contains("nativeRaf(loop)", js); + Assert.Contains("window.requestAnimationFrame = fn =>", js); + Assert.Contains("EventTarget.prototype.removeEventListener", js); + Assert.Contains("window.ResizeObserver = class", js); + Assert.Contains("grid()", js); + } + + // ── Argomenti ─────────────────────────────────────────────────────── + + private static Arguments Parse(string? envPassword, params string[] args) => + Arguments.Parse(args, k => k == "UI_PASSWORD" ? envPassword : null, out _); + + [Fact] + public void Le_schermate_di_sempre_hanno_tre_argomenti() + { + var a = Arguments.Parse(["http://localhost:8080/", "dev", "docs/schermate", "--messaggio"], _ => null, out var error); + Assert.Null(error); + Assert.Equal("http://localhost:8080", a.BaseUrl); + Assert.Equal("dev", a.Password); + Assert.Equal("docs/schermate", a.OutputDir); + Assert.True(a.Message); + Assert.Null(a.MeasureSeconds); + } + + [Fact] + public void Senza_password_fra_gli_argomenti_vale_UI_PASSWORD() + { + var a = Parse("dall-ambiente", "http://localhost:8080", "out/misura", "--misura", "120"); + Assert.Equal("dall-ambiente", a.Password); + Assert.Equal("out/misura", a.OutputDir); + Assert.Equal(120, a.MeasureSeconds); + + Arguments.Parse(["http://localhost:8080", "out"], _ => null, out var error); + Assert.Contains("UI_PASSWORD", error); + } + + [Theory] + [InlineData("5")] + [InlineData("4000")] + [InlineData("due")] + public void La_durata_della_misura_va_da_dieci_secondi_a_un_ora(string value) + { + Arguments.Parse(["http://localhost:8080", "dev", "out", "--misura", value], _ => null, out var error); + Assert.Contains("--misura", error); + Arguments.Parse(["http://localhost:8080", "dev", "out", "--misura"], _ => null, out var missing); + Assert.Contains("--misura", missing); + } + + [Fact] + public void Mockup_e_aiuto() + { + Assert.True(Parse(null, "--help").Help); + var m = Parse(null, "--mockup"); + Assert.True(m.Mockup); + Assert.Equal("docs/mockup/redesign", m.OutputDir); + Assert.Equal("altrove", Parse(null, "--mockup", "altrove").OutputDir); + Assert.Contains("--misura", Arguments.Usage); + } + + private static PerfInputs Good() + { + var rows = new List<(string, long)> { ("1", 1), ("2", 2), ("3", 3) }; + var gesture = new GesturePhase(PerfAnalysis.CompareRows(rows, rows), PerfAnalysis.Frames(Steady(60)), + PerfAnalysis.Tasks([0.3, 0.4], [1.2, 2.5, 0.8]), [], 0, PerfAnalysis.Grid([(0, 60, false), (0, 60, false)])); + return new PerfInputs + { + Seconds = 120, + Samples = Enumerable.Range(0, 120).Select(_ => new PerfSample(60, 45, 22, 60, true)).ToList(), + FrameIntervals = Steady(7200), + RowUpdatesMs = Enumerable.Range(0, 5000).Select(i => 5.0 + i % 20).ToList(), + HandlersMs = Enumerable.Range(0, 5000).Select(i => 0.2 + i % 3 * 0.1).ToList(), + TasksMs = Enumerable.Range(0, 2400).Select(i => 0.5 + i % 7 * 0.3).ToList(), + LongTasksMs = [], + CpuPercent = 8, + Drag = gesture with { MovedPx = 240 }, + Resize = gesture, + ReconnectsMs = [450, 470, 430], + Errors = [] + }; + } +} diff --git a/tests/Mimante.Tests/SimulatorPlanTests.cs b/tests/Mimante.Tests/SimulatorPlanTests.cs new file mode 100644 index 0000000..a716f06 --- /dev/null +++ b/tests/Mimante.Tests/SimulatorPlanTests.cs @@ -0,0 +1,154 @@ +using Mimante.Config; +using Mimante.Engine; +using Mimante.Host; +using Mimante.Simulator; +using Xunit; + +namespace Mimante.Tests; + +/// +/// --simulatore-aste N: il simulatore a N aste per la misura delle prestazioni dell'interfaccia +/// (specifica §9.11, issue #34). Senza l'argomento il simulatore resta quello di sempre. +/// +public class SimulatorPlanTests +{ + private static EnvConfig Read(params string[] args) => EnvConfig.Read(_ => null, args); + + [Fact] + public void L_argomento_vale_solo_con_il_simulatore() + { + Assert.Equal(60, Read("--simulatore", "--simulatore-aste", "60").SimulatorAuctions); + Assert.Equal(60, Read("--simulatore-aste", "60", "--simulatore").SimulatorAuctions); + Assert.Null(Read("--simulatore-aste", "60").SimulatorAuctions); + Assert.False(Read("--simulatore-aste", "60").SimulatorMode); + Assert.Null(Read("--simulatore").SimulatorAuctions); + } + + [Theory] + [InlineData("0")] + [InlineData("-3")] + [InlineData("501")] + [InlineData("sessanta")] + [InlineData("")] + public void Un_numero_non_valido_lascia_il_simulatore_di_sempre(string value) + { + var env = Read("--simulatore", "--simulatore-aste", value); + Assert.True(env.SimulatorMode); + Assert.Null(env.SimulatorAuctions); + Assert.Same(SimulatorPlan.Default, SimulatorPlan.From(env.SimulatorAuctions)); + } + + [Fact] + public void L_argomento_in_fondo_senza_numero_non_rompe_la_lettura() + { + var env = Read("--simulatore", "--simulatore-aste"); + Assert.True(env.SimulatorMode); + Assert.Null(env.SimulatorAuctions); + } + + [Fact] + public void Senza_argomento_il_simulatore_resta_quello_di_sempre() + { + var plan = SimulatorPlan.From(null); + Assert.Equal(14, plan.WorldAuctions); + Assert.Equal(8, plan.SeedAuctions); + Assert.Equal(6, plan.RunningAuctions); + Assert.Null(plan.FreqSeconds); + Assert.False(plan.Load); + // Tre in Attiva, l'ottava in Ferma, le altre in Osserva; il rabbocco una su tre in Attiva. + Assert.Equal(new[] { RunMode.Active, RunMode.Active, RunMode.Active, RunMode.Watch, RunMode.Watch, RunMode.Watch, RunMode.Watch, RunMode.Stopped }, + Enumerable.Range(0, 8).Select(plan.SeedMode)); + Assert.Equal(new[] { RunMode.Active, RunMode.Watch, RunMode.Watch, RunMode.Active, RunMode.Watch, RunMode.Watch }, + Enumerable.Range(0, 6).Select(plan.TopUpMode)); + + // Il mondo di sempre: 14 aste, ciascuna con la frequenza del suo prodotto. + var world = new SimWorld(seed: 5); + Assert.Equal(14, world.Auctions.Count); + Assert.Null(world.FixedFreqSeconds); + Assert.False(world.EndlessAuctions); + Assert.Contains(world.Auctions, a => a.FreqSeconds == 15); + } + + [Fact] + public void Con_sessanta_aste_il_mondo_ha_margine_e_quasi_tutte_puntano() + { + var plan = SimulatorPlan.ForLoad(60); + Assert.True(plan.Load); + Assert.Equal(60, plan.SeedAuctions); + Assert.Equal(60, plan.RunningAuctions); + Assert.Equal(SimulatorPlan.LoadFreqSeconds, plan.FreqSeconds); + Assert.True(plan.WorldAuctions >= 60 + 10, $"mondo di {plan.WorldAuctions} aste"); + + var seed = Enumerable.Range(0, plan.SeedAuctions).Select(plan.SeedMode).ToList(); + Assert.Equal(45, seed.Count(m => m == RunMode.Active)); + Assert.DoesNotContain(RunMode.Stopped, seed); + Assert.Equal(RunMode.Active, plan.TopUpMode(0)); + + // Il mondo ha abbastanza aste aperte (programmate comprese) per il seme. + var world = NewWorld(plan, seed: 9, out _); + Assert.Equal(plan.WorldAuctions, world.Auctions.Count); + Assert.True(world.Auctions.Count(a => a.Status == "ON") >= plan.SeedAuctions); + Assert.All(world.Auctions, a => Assert.Equal(5, a.FreqSeconds)); + } + + [Fact] + public void Poche_aste_chiedono_comunque_il_mondo_minimo() + { + var plan = SimulatorPlan.ForLoad(3); + Assert.Equal(14, plan.WorldAuctions); + Assert.Equal(3, plan.SeedAuctions); + } + + [Fact] + public void Un_asta_di_prova_tiene_la_sua_frequenza_anche_con_il_ciclo_fisso() + { + var world = new SimWorld(seed: 1, populate: false) { FixedFreqSeconds = 5 }; + Assert.Equal(12, world.AddRunningAuction(seconds: 8, freq: 12).FreqSeconds); + } + + /// + /// La ragione del ciclo di 5 s e delle aste che non chiudono: con le sole puntate degli avversari (il bot ne + /// aggiunge altre), fra le aste che il seme mette in Attiva ce ne sono sempre almeno dieci insieme sotto i 4 s, + /// e in due minuti di prova nessuna chiude. + /// + [Fact] + public void Con_il_ciclo_di_cinque_secondi_dieci_aste_in_Attiva_stanno_insieme_sotto_i_quattro_secondi() + { + var plan = SimulatorPlan.ForLoad(60); + var world = NewWorld(plan, seed: 17, out var clock); + var seeded = world.Auctions.Where(a => a.Status == "ON").Take(plan.SeedAuctions).ToList(); + var active = seeded.Where((_, i) => plan.SeedMode(i) == RunMode.Active).Select(a => a.Id).ToHashSet(); + + int samples = 0, min = int.MaxValue; + long total = 0; + for (var ms = 0; ms < 120_000; ms += 100) + { + clock.Advance(TimeSpan.FromMilliseconds(100)); + world.Tick(); + if (ms < 10_000) continue; // il primo ciclo parte da scadenze sparse + var nowMs = world.NowUnixMs; + var critical = world.Auctions.Count(a => active.Contains(a.Id) && a.Status == "ON" && a.Started + && a.ExpiryUnix * 1000 - nowMs is > 0 and < 4000); + samples++; + total += critical; + min = Math.Min(min, critical); + } + Assert.True(min >= 10, $"nel momento peggiore solo {min} aste in Attiva sotto i 4 s (in media {(double)total / samples:0.#})"); + Assert.DoesNotContain(seeded, a => a.Status == "OFF"); + } + + private static SimWorld NewWorld(SimulatorPlan plan, int seed, out FakeClock clock) + { + var c = new FakeClock(new DateTimeOffset(2026, 11, 27, 12, 0, 0, TimeSpan.Zero)); + var world = new SimWorld(seed, () => c.Now, populate: false) { TargetAuctions = plan.WorldAuctions, FixedFreqSeconds = plan.FreqSeconds, EndlessAuctions = plan.Load }; + world.Populate(); + clock = c; + return world; + } + + private sealed class FakeClock(DateTimeOffset start) + { + public DateTimeOffset Now { get; private set; } = start; + public void Advance(TimeSpan by) => Now += by; + } +} diff --git a/tools/Mimante.Schermate/Arguments.cs b/tools/Mimante.Schermate/Arguments.cs new file mode 100644 index 0000000..d5d3df0 --- /dev/null +++ b/tools/Mimante.Schermate/Arguments.cs @@ -0,0 +1,95 @@ +using System.Globalization; + +namespace Mimante.Schermate; + +/// +/// Gli argomenti dello strumento. Tre modi: le schermate (<indirizzo> [password] <cartella>), le +/// proposte grafiche (--mockup [cartella]) e la misura delle prestazioni (--misura <secondi> con +/// indirizzo e cartella). Senza password fra gli argomenti vale la variabile d'ambiente UI_PASSWORD, così +/// la password non resta nella cronologia della shell. +/// +public sealed record Arguments +{ + public const int MinMeasureSeconds = 10; + public const int MaxMeasureSeconds = 3600; + + public const string Usage = """ +Uso: + Mimante.Schermate [password] [--messaggio] + le schermate dell'interfaccia (il bot gira con --simulatore); esce con 1 se una pagina ha errori JavaScript + Mimante.Schermate [password] --misura + 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; } = ""; + + /// Legge gli argomenti; dice cosa non va (null = tutto a posto). + public static Arguments Parse(IReadOnlyList args, Func 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(); + 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") + }; + } +} diff --git a/tools/Mimante.Schermate/Misura/PerfAnalysis.cs b/tools/Mimante.Schermate/Misura/PerfAnalysis.cs new file mode 100644 index 0000000..5ac66c8 --- /dev/null +++ b/tools/Mimante.Schermate/Misura/PerfAnalysis.cs @@ -0,0 +1,373 @@ +using System.Globalization; +using System.Text; + +namespace Mimante.Schermate.Misura; + +/// +/// 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. +/// +public static class PerfCriteria +{ + /// Aste in elenco perché la misura valga. + public const int MinListed = 60; + + /// Aste in Attiva con il countdown sotto i 4 s, in ogni campione: un campione con meno rende la misura non valida. + public const int MinCritical = 10; + + /// La finestra critica: countdown sotto questi millisecondi. + public const double CriticalMs = 4000; + + /// + /// Righe disegnate al più durante maniglia e finestra: oltre, la griglia si virtualizza (virtualizeOver di + /// wwwroot/js/grid.js) e la prova dei nodi non dice più ciò che deve. + /// + public const int MaxDrawnRows = 60; + + /// Di quanto può scorrere la griglia durante il trascinamento della maniglia (arrotondamenti del browser). + public const double MaxScrollPx = 1; + + /// CPU della scheda, in percento di un core (non vincolante). + public const double MaxCpuPercent = 15; + + /// Frame persi ammessi nei countdown. + public const int MaxLostFrames = 0; + + /// Un intervallo fra due frame oltre 1,5 frame è un frame perso. + public const double LostFrameFactor = 1.5; + + /// Il blocco più lungo ammesso del thread dell'interfaccia. + public const double MaxBlockMs = 16; + + /// Dal messaggio del bot alla riga aggiornata a schermo. + public const double MaxRowUpdateMs = 100; + + /// Dalla chiusura del canale al nuovo elenco a schermo. + public const double MaxReconnectMs = 2000; + + /// Quante volte si chiude il canale per misurare la riconnessione. + public const int ReconnectTrials = 3; + + /// Di quanto deve muoversi il pannello perché il trascinamento della maniglia valga. + public const double MinHandleMovePx = 20; +} + +/// Un campione al secondo della pagina Aste durante la misura. +public sealed record PerfSample(int Listed, int Active, int Critical, int Drawn, bool Connected); + +/// Il riassunto dei campioni: quante aste c'erano in elenco e quante in finestra critica. +public sealed record SampleStats(int Count, int MinListed, int MinCritical, double MedianCritical, double CriticalShare, int MaxDrawn); + +/// +/// I frame di una fase: la durata di un frame, i frame persi e quanto è arrivato in ritardo il frame peggiore +/// (: frame in ritardo oltre la soglia; è un limite superiore del blocco del thread, perché anche il +/// compositore senza GPU salta un frame da solo). +/// +public sealed record FrameStats(int Intervals, double FrameMs, int LostFrames, double WorstGapMs, int Blocks, double WorstBlockMs); + +/// Una distribuzione di tempi in millisecondi, con quanti superano il limite. +public sealed record Distribution(int Count, double P50, double P95, double P99, double Max, int Over); + +/// +/// Le righe della griglia prima e dopo un trascinamento o un ridimensionamento: un <tr data-id> ancora +/// in vista dev'essere lo stesso nodo. Righe entrate o uscite per lo scorrimento virtuale non contano. +/// +public sealed record RowIdentity(int Before, int After, int Kept, IReadOnlyList Replaced, IReadOnlyList Duplicated) +{ + public bool Intact => Replaced.Count == 0 && Duplicated.Count == 0; +} + +/// +/// 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). +/// +public sealed record GridState(double ScrollMovedPx, int MaxDrawn, bool Virtual); + +/// +/// 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. +/// +public sealed record GesturePhase(RowIdentity Rows, FrameStats Frames, Distribution Tasks, IReadOnlyList LongTasksMs, double MovedPx, GridState Grid); + +/// Un criterio: vincolante o solo riportato, superato o no, con il valore misurato e il limite. +public sealed record PerfCheck(string Key, string Label, bool Binding, bool Passed, string Value, string Limit); + +/// Tutto ciò che la misura ha raccolto, prima del giudizio. +public sealed record PerfInputs +{ + public required int Seconds { get; init; } + public required IReadOnlyList Samples { get; init; } + public required IReadOnlyList FrameIntervals { get; init; } + public required IReadOnlyList RowUpdatesMs { get; init; } + public required IReadOnlyList HandlersMs { get; init; } + + /// Le funzioni date dall'interfaccia a timer e requestAnimationFrame, cronometrate una per una. + public required IReadOnlyList TasksMs { get; init; } + + public required IReadOnlyList LongTasksMs { get; init; } + public double? CpuPercent { get; init; } + public required GesturePhase Drag { get; init; } + public required GesturePhase Resize { get; init; } + public required IReadOnlyList ReconnectsMs { get; init; } + public required IReadOnlyList Errors { get; init; } +} + +/// Il risultato: i criteri, se la misura vale e, se non vale, perché. +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; } + + /// Tutti i compiti dell'interfaccia: messaggi del bot, timer, frame (i blocchi del thread). + 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 ReconnectsMs { get; init; } + public required IReadOnlyList Errors { get; init; } + public required IReadOnlyList Checks { get; init; } + public required bool Valid { get; init; } + public required IReadOnlyList InvalidReasons { get; init; } + + /// La misura vale e ogni criterio vincolante è superato. + public bool Passed => Valid && Checks.All(c => !c.Binding || c.Passed); + + /// 0 = superata; 1 = un criterio vincolante fallito o misura non valida. + public int ExitCode => Passed ? 0 : 1; +} + +/// I conti della misura: logica pura, senza browser (provata in PerfAnalysisTests). +public static class PerfAnalysis +{ + /// + /// I frame da una serie di intervalli fra due requestAnimationFrame. 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). + /// + public static FrameStats Frames(IReadOnlyList 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))); + } + + /// Mediana, 95° e 99° percentile, massimo e quanti valori superano . + public static Distribution Distribution(IReadOnlyList 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)); + } + + /// Percentile con il metodo del rango più vicino (0 < ≤ 1). + public static double Percentile(IReadOnlyList 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 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)); + } + + /// + /// 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. + /// + 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(StringComparer.Ordinal); + foreach (var (id, token) in before) was.TryAdd(id, token); + int kept = 0; + var replaced = new SortedSet(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); + } + + /// I compiti dell'interfaccia di una fase: la gestione dei messaggi più timer, frame, eventi e osservatori. + public static Distribution Tasks(IReadOnlyList handlers, IReadOnlyList tasks) => + Distribution([.. handlers, .. tasks], PerfCriteria.MaxBlockMs); + + /// + /// La griglia da una serie di osservazioni (scorrimento verticale, righe disegnate, virtualizzata) prese durante una + /// fase, la prima al punto di partenza. + /// + 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)); + } + + /// Il giudizio: se la misura vale e, criterio per criterio, se è superato. + 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(); + 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 + { + 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 + }; + } + + /// Il resoconto da leggere: esito, criteri, condizioni della prova. + 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 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)) + "%"; +} diff --git a/tools/Mimante.Schermate/Misura/PerfRun.cs b/tools/Mimante.Schermate/Misura/PerfRun.cs new file mode 100644 index 0000000..ca3838c --- /dev/null +++ b/tools/Mimante.Schermate/Misura/PerfRun.cs @@ -0,0 +1,246 @@ +using System.Diagnostics; +using System.Text.Json; +using Mimante.Schermate.Cdp; + +namespace Mimante.Schermate.Misura; + +/// +/// La misura delle prestazioni (--misura <secondi>), tutta via CDP: la pagina Aste del bot avviato con +/// --simulatore --simulatore-aste 60, già con l'accesso fatto e lo strumento di dentro. +/// +/// 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. +/// +public sealed class PerfRun(CdpClient cdp, string session, Func> eval, Func viewport, CancellationToken ct) +{ + public const int Width = 1600; + public const int Height = 1000; + + /// Quanto aspettare che l'elenco arrivi a aste. + private static readonly TimeSpan FillTimeout = TimeSpan.FromSeconds(90); + + private static readonly TimeSpan Settle = TimeSpan.FromSeconds(5); + + public async Task RunAsync(int seconds, Func> errors, Action progress) + { + await WaitForListAsync(progress).ConfigureAwait(false); + await Task.Delay(Settle, ct).ConfigureAwait(false); + + progress($"misura per {seconds} s"); + var samples = new List(); + 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(); + 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 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 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); + } + + /// + /// 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 (). + /// + private async Task 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); + } + + /// + /// 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. + /// + private async Task 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); + } + + /// Una fase dai numeri di __mimantePerf.take(): frame, compiti e compiti lunghi, non solo i frame. + 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)); + + /// Scorrimento verticale, righe disegnate e virtualizzazione della griglia in questo momento. + 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); + } + + /// Chiude il canale dalla pagina e misura fino al nuovo elenco a schermo; null = non riuscita. + private async Task 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> 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); + + /// TaskDuration e Timestamp di Performance.getMetrics, in secondi. + 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; } + } + + /// Il tempo del thread della scheda sul tempo trascorso, in percento di un core. + 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 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; +} diff --git a/tools/Mimante.Schermate/Misura/PerfScript.cs b/tools/Mimante.Schermate/Misura/PerfScript.cs new file mode 100644 index 0000000..1d450e2 --- /dev/null +++ b/tools/Mimante.Schermate/Misura/PerfScript.cs @@ -0,0 +1,188 @@ +namespace Mimante.Schermate.Misura; + +/// +/// Lo strumento di misura dentro la pagina, messo con Page.addScriptToEvaluateOnNewDocument prima di ogni +/// altro script: window.__mimantePerf. +/// +/// +/// un ciclo di requestAnimationFrame che registra l'intervallo fra due frame (frame persi); +/// i compiti dell'interfaccia cronometrati uno per uno (i blocchi del thread): le funzioni passate a +/// setTimeout, setInterval e requestAnimationFrame, gli ascoltatori degli eventi del puntatore, +/// della rotella, dello scorrimento e della finestra (la maniglia di split.js), le funzioni dei +/// ResizeObserver e la gestione di ogni messaggio del bot; +/// un involucro di window.WebSocket: ogni auction.delta 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); reconnect() chiude il canale e misura fino al nuovo elenco +/// (snapshot) a schermo; +/// un PerformanceObserver 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; +/// sample() conta le aste in elenco e quelle in Attiva in finestra critica dallo stato della pagina +/// (/js/state.js, lo stesso modulo dell'interfaccia); rows() dà a ogni <tr data-id> un +/// segno, per riconoscere un nodo ridisegnato; grid() dice lo scorrimento, le righe disegnate e se la griglia +/// è virtualizzata. +/// +/// +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(); + }); + } + }; +})(); +"""; + + /// Lo script con le soglie della misura. + public static string Build() => + Source.Replace("__CRITICAL_MS__", PerfCriteria.CriticalMs.ToString(System.Globalization.CultureInfo.InvariantCulture)); +} diff --git a/tools/Mimante.Schermate/Program.cs b/tools/Mimante.Schermate/Program.cs index 43c4d4c..fe6e11d 100644 --- a/tools/Mimante.Schermate/Program.cs +++ b/tools/Mimante.Schermate/Program.cs @@ -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 -- +// Uso: dotnet run --project tools/Mimante.Schermate -- [password dell'interfaccia] // 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 /.html in chiaro e in scuro // in /immagini, poi il foglio di confronto (confronto.html) se c'è. +// +// Prestazioni (specifica §9.11): dotnet run --project tools/Mimante.Schermate -- --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 | --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(); +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}");