Compare commits
101
Commits
v0.1.0
...
fbc40fb5a1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fbc40fb5a1 | ||
|
|
31bbbf8bb7 | ||
|
|
b3a7c31e5a | ||
|
|
5b278a848a | ||
|
|
2e1d81d4b8 | ||
|
|
b74d2db793 | ||
|
|
e73292516d | ||
|
|
7d5c6505bd | ||
|
|
44f7f93783 | ||
|
|
4b35178880 | ||
|
|
fe4ef9f048 | ||
|
|
c5361ba8fe | ||
|
|
68100b0295 | ||
|
|
e24ebd24f0 | ||
|
|
483d57b89a | ||
|
|
086b603801 | ||
|
|
46d780c826 | ||
|
|
5988c503f7 | ||
|
|
7513f41d4d | ||
|
|
7a9c235552 | ||
|
|
d07ed07db6 | ||
|
|
248e9f74ce | ||
|
|
65988f2863 | ||
|
|
016bbf73eb | ||
|
|
0f11fc5220 | ||
|
|
7a70b464f3 | ||
|
|
19920dfd7e | ||
|
|
eb7db4d2bf | ||
|
|
b0f71936e0 | ||
|
|
0a6dd19595 | ||
|
|
3719adc2d9 | ||
|
|
fbb9e602b9 | ||
|
|
1f16d29130 | ||
|
|
5fdbf8075a | ||
|
|
1eed504446 | ||
|
|
80c1345fbb | ||
|
|
058c0e8a4d | ||
|
|
00c3d8bdf4 | ||
|
|
5dc9b4c6ae | ||
|
|
309ace91de | ||
|
|
d6df98f766 | ||
|
|
ef23421d2d | ||
|
|
62941b104d | ||
|
|
67568ae36f | ||
|
|
1b2faa4c7a | ||
|
|
1b767d517d | ||
|
|
d07b072bf8 | ||
|
|
724c0752cf | ||
|
|
3bcbbbf7c1 | ||
|
|
9ce61d26ce | ||
|
|
9d959f910b | ||
|
|
afbd0b4a1a | ||
|
|
f86c794fa4 | ||
|
|
5f968c69d9 | ||
|
|
f09ce4f2d5 | ||
|
|
198e48d4f8 | ||
|
|
815bd44a62 | ||
|
|
f7de7f5642 | ||
|
|
e035cfd20a | ||
|
|
d9d8a296b1 | ||
|
|
d9da3b07cb | ||
|
|
010ba794be | ||
|
|
2144f755dc | ||
|
|
5e7cb73a85 | ||
|
|
56fd29be80 | ||
|
|
1bff405384 | ||
|
|
d56c24f900 | ||
|
|
af5383a3ea | ||
|
|
3170fbd8b6 | ||
|
|
a48899f522 | ||
|
|
7bcb9f5f5a | ||
|
|
f48b6abac4 | ||
|
|
7aaa93fe3b | ||
|
|
a144d611ac | ||
|
|
1b5a8d4dcd | ||
|
|
7a54eceaaf | ||
|
|
f324105371 | ||
|
|
4a4e85cc7f | ||
|
|
5397d31e13 | ||
|
|
02e5cfe79c | ||
|
|
f243118f36 | ||
|
|
6e95aef5cc | ||
|
|
bff054dcf6 | ||
|
|
7fffa53c90 | ||
|
|
66a3fc7db6 | ||
|
|
d1e29aa7a4 | ||
|
|
7d8ea22381 | ||
|
|
f35b0a7301 | ||
|
|
91080a2664 | ||
|
|
e5e2b6864f | ||
|
|
7b0b0339f7 | ||
|
|
cf618d8986 | ||
|
|
a305a9ed2a | ||
|
|
2ef098226b | ||
|
|
3f222448ee | ||
|
|
ccfd8b5c08 | ||
|
|
d642b55b74 | ||
|
|
f7237145aa | ||
|
|
a6623e5736 | ||
|
|
a25f60970d | ||
|
|
edade61b72 |
No files matched your search
@@ -0,0 +1,4 @@
|
||||
# Proprietari del codice: Gitea chiede la loro revisione a ogni richiesta di unione che tocca i file indicati.
|
||||
# In Gitea le regole sono espressioni regolari di Go, non schemi alla maniera di .gitignore (docs.gitea.com, «Code Owners»).
|
||||
# Alberto è il proprietario di tutto il repository.
|
||||
.* @Alby96
|
||||
@@ -0,0 +1,5 @@
|
||||
blank_issues_enabled: true
|
||||
contact_links:
|
||||
- name: Guida di Febe
|
||||
url: https://gitea.encke-hake.ts.net/Alby96/Febe/wiki
|
||||
about: Installazione, primo collegamento, limiti, problemi comuni e sicurezza
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
name: Difetto
|
||||
about: Febe fa qualcosa di sbagliato, o non fa ciò che dovrebbe
|
||||
title: "Difetto: "
|
||||
---
|
||||
|
||||
<!--
|
||||
Mai in una segnalazione: password, cookie, gettoni (Telegram, registro), codici di verifica, campioni grezzi della
|
||||
sonda o corpi di risposta di Instagram. Il registro di Febe non li contiene: se ne incolli un pezzo, controlla
|
||||
comunque prima di inviare.
|
||||
-->
|
||||
|
||||
## Che cosa succede
|
||||
|
||||
<!-- Che cosa vedi, con il testo esatto dei messaggi. -->
|
||||
|
||||
## Che cosa ti aspettavi
|
||||
|
||||
## Come rifarlo
|
||||
|
||||
1.
|
||||
2.
|
||||
|
||||
## Dove
|
||||
|
||||
- Veste: Docker (Unraid, Compose) / Windows (installato, portabile)
|
||||
- Versione di Febe (Impostazioni ▸ Informazioni, o etichetta dell'immagine):
|
||||
- Profilo di prudenza:
|
||||
- Contro Instagram vero o contro il sito di prova:
|
||||
|
||||
## Registro
|
||||
|
||||
<!-- Le righe del registro intorno al problema (/dati/registro/febe-AAAA-MM-GG.log o %LOCALAPPDATA%\Febe\registro). -->
|
||||
|
||||
```text
|
||||
```
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
name: Proposta
|
||||
about: Una funzione nuova o un cambiamento di comportamento
|
||||
title: "Proposta: "
|
||||
---
|
||||
|
||||
## Il problema
|
||||
|
||||
<!-- Che cosa non riesci a fare oggi, o che cosa ti costa troppo. -->
|
||||
|
||||
## La proposta
|
||||
|
||||
## Regole di §2 toccate
|
||||
|
||||
<!-- Una proposta che chiede di contattare Instagram fuori dal browser, di cambiare il browser, di scavalcare una
|
||||
verifica, di scrivere su Instagram o di aggiungere una dipendenza va discussa prima di tutto (docs/SPECIFICA.md, §2). -->
|
||||
|
||||
- [ ] Nessuna
|
||||
- [ ] Sì, quali e perché:
|
||||
|
||||
## Come capiremo che è fatta
|
||||
|
||||
-
|
||||
@@ -0,0 +1,67 @@
|
||||
<!--
|
||||
Una richiesta di unione per ramo, piccola quanto basta per leggerla tutta. Titolo in italiano: che cosa cambia.
|
||||
Si unisce in main solo con la verifica verde sull'ultimo commit (docs/processo.md). Togli i commenti che non servono.
|
||||
-->
|
||||
|
||||
## Sintesi
|
||||
|
||||
<!-- Che cosa fa questa richiesta, in due o tre frasi. -->
|
||||
|
||||
## Perché
|
||||
|
||||
<!-- Il problema, la richiesta di Alberto o la segnalazione (#numero) da cui nasce. -->
|
||||
|
||||
## Che cosa cambia
|
||||
|
||||
<!-- Per punti: comportamento, parti toccate, scelte nuove (con la riga in docs/decisioni.md), effetti su Docker o Windows. -->
|
||||
|
||||
-
|
||||
|
||||
## Come è stato provato
|
||||
|
||||
<!-- Comandi e risultati, copiati così come sono usciti. Poi, con la stessa franchezza, che cosa NON è stato provato e perché. -->
|
||||
|
||||
```text
|
||||
dotnet build Febe.slnx -warnaserror
|
||||
dotnet test tests/Febe.Tests
|
||||
```
|
||||
|
||||
Non provato:
|
||||
|
||||
-
|
||||
|
||||
## Rischi e ritorno indietro
|
||||
|
||||
<!-- Che cosa può andare storto, come ce ne si accorge, come si torna indietro (di solito: annullare il commit di unione con git revert -m 1). Dati, migrazioni, impostazioni o segreti da sistemare a mano. -->
|
||||
|
||||
## Controlli prima di unire
|
||||
|
||||
Le regole di §2 della specifica (docs/SPECIFICA.md), che valgono sempre:
|
||||
|
||||
- [ ] 1. Verso Instagram parla solo il browser di Febe: nessuna connessione verso domini di Instagram o Meta, salvo il CDN alle condizioni di §6.5
|
||||
- [ ] 2. Il browser si usa così com'è: niente stealth, user agent, impronta, fuso o lingua cambiati, headless, intestazioni riscritte, proxy, più account; comandi CDP solo dall'elenco di §6.1
|
||||
- [ ] 3. Niente scavalcamenti: CAPTCHA, verifiche e codici non si risolvono in automatico, Febe si ferma e avvisa
|
||||
- [ ] 4. Un account, una rete, un motore; i cookie non si copiano da una macchina all'altra
|
||||
- [ ] 5. Sola lettura: niente mi piace, segui, commenti, messaggi, reazioni
|
||||
- [ ] 6. Solo ciò che l'account di Alberto vede già
|
||||
- [ ] 7. Ogni azione del motore verso il sito passa dal Governatore (IGovernor)
|
||||
- [ ] 8. Al primo segnale di §7.6 ci si ferma, senza nuovi tentativi automatici
|
||||
- [ ] 9. Nessuna prova, script o verifica contatta Instagram (solo tools/Febe.SitoDiProva) e nessuno apre i campioni grezzi della sonda (solo le copie ripulite di tests/campioni)
|
||||
- [ ] 10. Nessun formato di risposta inventato: i lettori si scrivono su campioni reali ripuliti
|
||||
- [ ] 11. Mai password, cookie, gettoni, tasti o corpi di risposta nei registri, nei messaggi di errore o nell'output della CI; i campioni grezzi fuori da git
|
||||
- [ ] 12. La libreria non cancella e non sostituisce file da sola
|
||||
- [ ] 13. Nessuna dipendenza fuori dall'elenco chiuso di §3 (Directory.Packages.props), se Alberto non l'ha approvata
|
||||
- [ ] 14. Resoconto onesto: ciò che non è stato verificato è scritto qui sopra
|
||||
|
||||
E le convenzioni:
|
||||
|
||||
- [ ] La verifica è verde sull'ultimo commit: controlli, prove (nessuna saltata), installatore, immagine
|
||||
- [ ] Nel motore niente DateTime.Now, Task.Delay o Random diretti (IClock, IRandomSource)
|
||||
- [ ] Codice e commenti in inglese; interfaccia, documenti e messaggi in italiano
|
||||
- [ ] Ogni scelta tecnica nuova ha la sua riga in docs/decisioni.md
|
||||
- [ ] Una schermata cambiata è stata confrontata con il suo mockup (§10.7)
|
||||
- [ ] Le righe per CHANGELOG.md e docs/stato.md sono scritte qui sotto (le aggiunge chi integra)
|
||||
|
||||
### Per CHANGELOG.md e docs/stato.md
|
||||
|
||||
-
|
||||
Executable
+36
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env bash
|
||||
# Prepara il contenitore Debian del lavoro «prove» (node:24-trixie: Debian 13 con Node, che serve alle azioni) perché
|
||||
# nessuna prova si salti: Chromium vero della distribuzione (su Ubuntu è uno snap, che nei contenitori non va) con le
|
||||
# sue lingue, Xvfb, ffmpeg e ffprobe, makensis (NSIS) e zip, la lingua it_IT.UTF-8, fusi orari, ICU e gli stessi
|
||||
# caratteri dell'immagine di Febe. Node c'è già (prova della pagina di accesso); setpriv, getent e l'utente nobody
|
||||
# (65534) vengono con Debian (prove dell'avvio del contenitore).
|
||||
#
|
||||
# .gitea/scripts/ambiente-prove.sh
|
||||
set -euo pipefail
|
||||
|
||||
sudo=""
|
||||
[[ "$(id -u)" == 0 ]] || sudo="sudo"
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
$sudo apt-get update -qq
|
||||
$sudo apt-get install -y -qq --no-install-recommends \
|
||||
chromium chromium-l10n \
|
||||
xvfb \
|
||||
ffmpeg \
|
||||
nsis zip \
|
||||
locales tzdata libicu76 ca-certificates \
|
||||
fonts-noto-color-emoji fonts-liberation fonts-dejavu-core \
|
||||
util-linux procps > /dev/null
|
||||
$sudo sed -i 's/^# *\(it_IT.UTF-8 UTF-8\)/\1/' /etc/locale.gen
|
||||
$sudo locale-gen > /dev/null
|
||||
|
||||
echo "== Strumenti delle prove"
|
||||
chromium --version
|
||||
command -v Xvfb
|
||||
ffmpeg -version | head -n 1 || true
|
||||
ffprobe -version | head -n 1 || true
|
||||
echo "makensis $(makensis -VERSION)"
|
||||
echo "node $(node --version)"
|
||||
locale -a | grep -i '^it_IT\.utf8$'
|
||||
for strumento in setpriv getent stat chown sh; do command -v "$strumento" > /dev/null || { echo "Manca $strumento." >&2; exit 1; }; done
|
||||
getent passwd 65534 > /dev/null && getent group 65534 > /dev/null || { echo "Mancano l'utente o il gruppo 65534 (nobody)." >&2; exit 1; }
|
||||
Executable
+102
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env bash
|
||||
# Controlli veloci prima di compilare (lavoro «controlli» della CI): pochi secondi, e fermano subito gli errori che
|
||||
# altrimenti si scoprirebbero dopo mezz'ora di prove. Si lanciano anche a mano, dalla radice del repository:
|
||||
#
|
||||
# bash .gitea/scripts/controlli.sh
|
||||
#
|
||||
# 1. ogni script di shell del repository è sintassi valida (bash -n; sh -n per quelli in sh) e ha le righe Unix; gli
|
||||
# script Node della CI (.gitea/scripts/*.js) sono JavaScript valido (node --check);
|
||||
# 2. i flussi della CI non hanno tabulazioni (YAML non le accetta come rientro);
|
||||
# 3. nessun file contiene segni di conflitto rimasti da un'unione;
|
||||
# 4. la versione di Directory.Build.props è nella forma x.y.z[-qualcosa], quella che installer/costruisci.sh accetta;
|
||||
# 5. ogni progetto elencato in Febe.slnx esiste;
|
||||
# 6. ogni file JSON del repository si legge (configurazioni, campioni ripuliti, criteri di Chromium).
|
||||
set -uo pipefail
|
||||
|
||||
radice="$(git rev-parse --show-toplevel)" || exit 2
|
||||
cd "$radice" || exit 2
|
||||
errori=0
|
||||
|
||||
errore() {
|
||||
echo "ERRORE: $*" >&2
|
||||
errori=$((errori + 1))
|
||||
}
|
||||
|
||||
echo "== Script di shell"
|
||||
quanti=0
|
||||
while IFS= read -r -d '' script; do
|
||||
quanti=$((quanti + 1))
|
||||
bash -n "$script" || errore "$script: sintassi bash non valida."
|
||||
if head -n 1 "$script" | grep -Eq '^#!(/usr/bin/env )?/?(bin/)?sh( |$)'; then
|
||||
sh -n "$script" || errore "$script: sintassi sh non valida."
|
||||
fi
|
||||
if grep -q $'\r' "$script"; then
|
||||
errore "$script ha righe Windows (CR): bash non le regge (.gitattributes chiede eol=lf)."
|
||||
fi
|
||||
done < <(git ls-files -z -- '*.sh')
|
||||
echo " $quanti script controllati"
|
||||
|
||||
echo "== Script Node della CI"
|
||||
if command -v node > /dev/null; then
|
||||
quanti=0
|
||||
while IFS= read -r -d '' script; do
|
||||
quanti=$((quanti + 1))
|
||||
node --check "$script" || errore "$script: JavaScript non valido."
|
||||
done < <(git ls-files -z -- '.gitea/scripts/*.js')
|
||||
echo " $quanti script controllati"
|
||||
else
|
||||
errore "manca node: gli script Node della CI non si possono controllare."
|
||||
fi
|
||||
|
||||
echo "== Flussi della CI"
|
||||
while IFS= read -r -d '' flusso; do
|
||||
if grep -n $'\t' "$flusso" > /dev/null; then
|
||||
errore "$flusso contiene tabulazioni: in YAML il rientro si fa con gli spazi."
|
||||
fi
|
||||
done < <(git ls-files -z -- '.gitea/workflows/*.yml' '.gitea/workflows/*.yaml')
|
||||
|
||||
echo "== Segni di conflitto"
|
||||
if conflitti=$(git grep -n -I -E '^(<{7}|>{7})( |$)' -- . ':!*.png' ':!*.jpg'); then
|
||||
errore "segni di conflitto rimasti:"
|
||||
echo "$conflitti" >&2
|
||||
fi
|
||||
|
||||
echo "== Versione"
|
||||
versione=$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' Directory.Build.props)
|
||||
if [[ "$(printf '%s\n' "$versione" | grep -c .)" != "1" ]]; then
|
||||
errore "Directory.Build.props deve avere una sola <Version>."
|
||||
elif [[ ! "$versione" =~ ^[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?$ ]]; then
|
||||
errore "versione «$versione» non valida: serve x.y.z, eventualmente con -qualcosa."
|
||||
else
|
||||
echo " $versione"
|
||||
fi
|
||||
|
||||
echo "== Progetti della soluzione"
|
||||
while IFS= read -r progetto; do
|
||||
[[ -f "$progetto" ]] || errore "Febe.slnx elenca $progetto, che non esiste."
|
||||
done < <(sed -n 's:.*<Project Path="\([^"]*\)".*:\1:p' Febe.slnx)
|
||||
echo " $(grep -c '<Project Path=' Febe.slnx) progetti"
|
||||
|
||||
echo "== File JSON"
|
||||
if command -v node > /dev/null; then
|
||||
# Un solo processo per tutti i file; stampa i file che non si leggono, uno per riga.
|
||||
guasti=$(git ls-files -z -- '*.json' | node -e '
|
||||
const fs = require("fs");
|
||||
const files = fs.readFileSync(0, "utf8").split("\0").filter(Boolean);
|
||||
for (const f of files) {
|
||||
try { JSON.parse(fs.readFileSync(f, "utf8").replace(/^/, "")); } catch (e) { console.log(f + ": " + e.message); }
|
||||
}
|
||||
console.error(" " + files.length + " file controllati");')
|
||||
if [[ -n "$guasti" ]]; then
|
||||
errore "JSON non valido:"
|
||||
echo "$guasti" >&2
|
||||
fi
|
||||
else
|
||||
errore "manca node: i file JSON non si possono controllare."
|
||||
fi
|
||||
|
||||
if ((errori > 0)); then
|
||||
echo "Controlli falliti: $errori." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Controlli superati."
|
||||
Executable
+53
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env bash
|
||||
# Costruzione dell'immagine Docker di Febe con il builder buildx dell'esecuzione (docker-container), sempre con gli
|
||||
# stessi argomenti e le stesse etichette: la costruzione che si pubblica esce intera dalla cache di quella che si è
|
||||
# provata e scansionata, quindi gli strati sono gli stessi.
|
||||
#
|
||||
# costruisci-immagine.sh archivio <file.tar> <nome locale> archivio dell'immagine, per docker load e per Trivy
|
||||
# costruisci-immagine.sh pubblica <nome:etichetta>... spinta sul registro da buildx: le credenziali sono
|
||||
# già nella configurazione del client, il demone non
|
||||
# parla mai con il registro (proverebbe HTTPS)
|
||||
#
|
||||
# L'immagine è un manifest semplice, senza attestazioni (--provenance=false --sbom=false). Con le attestazioni, che
|
||||
# buildx aggiunge da sé, sarebbe un indice: Gitea tiene ogni manifest figlio come una versione a sé, sha256:… senza
|
||||
# etichetta, con la configurazione e gli strati, e togliere dal registro un'etichetta :sha- toglierebbe solo l'indice.
|
||||
# Con un manifest semplice gli strati stanno nella versione dell'etichetta, e la pulizia del registro li libera davvero.
|
||||
#
|
||||
# Variabili richieste: BUILDER, VERSIONE, GIT_COMMIT, FLUSSO (verifica o rilascio), ESECUZIONE (gitea.run_id).
|
||||
# Le etichette febe.ci.* dicono quale flusso, esecuzione, ramo e commit hanno costruito l'immagine. Non servono alla
|
||||
# pulizia: stanno anche nelle immagini pubblicate e Docker le copia in ogni contenitore creato da quelle, anche in un
|
||||
# Febe vero. Per questo qui non si mette mai febe.ci.prova, il segno dei soli contenitori di prova (prova-immagine.sh):
|
||||
# lo controlla PipelineTests.
|
||||
set -euo pipefail
|
||||
|
||||
modo="${1:?Indica il modo: archivio o pubblica.}"
|
||||
shift
|
||||
cd "$(git rev-parse --show-toplevel)"
|
||||
|
||||
comuni=(--builder "${BUILDER:?}" -f docker/Dockerfile --provenance=false --sbom=false
|
||||
--build-arg "VERSION=${VERSIONE:?}" --build-arg "GIT_COMMIT=${GIT_COMMIT:?}"
|
||||
--label "febe.ci.workflow=${FLUSSO:?}" --label "febe.ci.run=${ESECUZIONE:?}"
|
||||
--label "febe.ci.ref=${GITHUB_REF_NAME:-}" --label "febe.ci.commit=${GITHUB_SHA:-}")
|
||||
|
||||
case "$modo" in
|
||||
archivio)
|
||||
archivio="${1:?Indica il file .tar da scrivere.}"
|
||||
nome="${2:?Indica il nome locale, per esempio febe-ci:123.}"
|
||||
mkdir -p "$(dirname "$archivio")"
|
||||
docker buildx build "${comuni[@]}" --output "type=docker,name=$nome,dest=$archivio" .
|
||||
echo "Archivio dell'immagine: $archivio ($(du -h "$archivio" | cut -f1))"
|
||||
;;
|
||||
pubblica)
|
||||
(($# > 0)) || { echo "Indica almeno un nome:etichetta da pubblicare." >&2; exit 2; }
|
||||
etichette=()
|
||||
for nome in "$@"; do
|
||||
etichette+=(-t "$nome")
|
||||
done
|
||||
docker buildx build "${comuni[@]}" "${etichette[@]}" --push .
|
||||
printf 'Pubblicata: %s\n' "$@"
|
||||
;;
|
||||
*)
|
||||
echo "Modo sconosciuto: «$modo» (archivio o pubblica)." >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
Executable
+87
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env bash
|
||||
# Prova dell'immagine appena costruita, sul demone Docker del runner. Ogni contenitore gira SENZA RETE
|
||||
# (--network none): Febe non può raggiungere alcun sito, tanto meno Instagram (regola 1), e il controllo di salute
|
||||
# passa dalla rete interna del contenitore.
|
||||
# Ogni contenitore porta l'etichetta febe.ci.prova=<esecuzione>, messa qui con «docker run --label» e mai in
|
||||
# un'immagine: è il segno con cui pulizia-docker.sh riconosce un contenitore di prova, insieme al nome
|
||||
# febe-prova-<esecuzione>. Le etichette febe.ci.* dell'immagine non bastano: Docker le copia in ogni contenitore, anche
|
||||
# in un Febe vero avviato da un'immagine pubblicata.
|
||||
#
|
||||
# .gitea/scripts/prova-immagine.sh <immagine> [esecuzione]
|
||||
#
|
||||
# 1. Chromium della distribuzione risponde e i criteri di Febe (niente password salvate) sono al loro posto;
|
||||
# 2. la lingua it_IT.UTF-8 è generata;
|
||||
# 3. il contenitore parte come dice la guida (profilo seccomp di Febe, password dell'interfaccia, PUID/PGID
|
||||
# predefiniti), il controllo di salute dell'immagine diventa «healthy» e «febe --controllo-salute» risponde;
|
||||
# 4. allo stop si ferma da solo, entro i 30 secondi che la guida concede.
|
||||
# La password è casuale, vive solo nell'ambiente del client Docker e non si stampa mai.
|
||||
set -euo pipefail
|
||||
|
||||
immagine="${1:?Indica quale immagine provare.}"
|
||||
esecuzione="${2:-${ESECUZIONE:-locale}}"
|
||||
radice="$(git rev-parse --show-toplevel)"
|
||||
etichette=(--label "febe.ci.prova=$esecuzione")
|
||||
nome="febe-prova-$esecuzione"
|
||||
|
||||
# Toglie il contenitore di prova di questa esecuzione (anche quello di un tentativo precedente), ma solo se porta il
|
||||
# segno della prova: un contenitore con lo stesso nome e senza segno resta, e «docker run --name» si ferma.
|
||||
togli() {
|
||||
local segno
|
||||
segno=$(docker container inspect -f '{{index .Config.Labels "febe.ci.prova"}}' "$nome" 2> /dev/null) || return 0
|
||||
if [[ "$segno" == "$esecuzione" ]]; then
|
||||
docker rm -f -v "$nome" > /dev/null 2>&1 || true
|
||||
fi
|
||||
}
|
||||
trap togli EXIT
|
||||
togli
|
||||
|
||||
echo "== Chromium e criteri di Febe"
|
||||
docker run --rm --network none "${etichette[@]}" --entrypoint /usr/bin/chromium "$immagine" --version
|
||||
docker run --rm --network none "${etichette[@]}" --entrypoint sh "$immagine" -c \
|
||||
'test -s /etc/chromium/policies/managed/febe.json && test -s /usr/share/febe/seccomp.json && echo "criteri di Chromium e profilo seccomp presenti"'
|
||||
|
||||
echo "== Lingua italiana"
|
||||
docker run --rm --network none "${etichette[@]}" --entrypoint sh "$immagine" -c 'locale -a | grep -i "^it_IT\.utf8$"'
|
||||
|
||||
echo "== Avvio, salute e arresto"
|
||||
FEBE_PASSWORD="$(head -c 32 /dev/urandom | base64 | tr -dc 'A-Za-z0-9')"
|
||||
export FEBE_PASSWORD
|
||||
docker run -d --name "$nome" --network none "${etichette[@]}" \
|
||||
--security-opt "seccomp=$radice/docker/chromium/seccomp.json" \
|
||||
--stop-timeout 30 -e FEBE_PASSWORD "$immagine" > /dev/null
|
||||
unset FEBE_PASSWORD
|
||||
|
||||
# Il primo controllo di salute dell'immagine arriva 30 secondi dopo l'avvio (HEALTHCHECK --interval=30s): fino a 3 minuti.
|
||||
stato=""
|
||||
for _ in $(seq 1 36); do
|
||||
if [[ "$(docker inspect -f '{{.State.Running}}' "$nome")" != "true" ]]; then
|
||||
echo "Il contenitore si è fermato da solo (codice $(docker inspect -f '{{.State.ExitCode}}' "$nome")). Registro:" >&2
|
||||
docker logs --tail 80 "$nome" >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
stato="$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{end}}' "$nome")"
|
||||
[[ "$stato" == "healthy" || "$stato" == "unhealthy" ]] && break
|
||||
sleep 5
|
||||
done
|
||||
if [[ "$stato" != "healthy" ]]; then
|
||||
echo "Il controllo di salute dice «${stato:-niente}» invece di «healthy». Registro:" >&2
|
||||
docker logs --tail 80 "$nome" >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
if ! docker exec "$nome" /app/febe --controllo-salute > /dev/null; then
|
||||
echo "febe --controllo-salute non risponde «ok» dentro il contenitore. Registro:" >&2
|
||||
docker logs --tail 80 "$nome" >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
echo "salute: healthy, e febe --controllo-salute risponde"
|
||||
|
||||
inizio=$(date +%s)
|
||||
docker stop -t 30 "$nome" > /dev/null
|
||||
durata=$(($(date +%s) - inizio))
|
||||
codice="$(docker inspect -f '{{.State.ExitCode}}' "$nome")"
|
||||
echo "arresto in ${durata} s (codice di uscita $codice)"
|
||||
if ((durata >= 30)); then
|
||||
echo "Febe non si è fermato da solo entro 30 secondi: Docker l'ha dovuto uccidere. Registro:" >&2
|
||||
docker logs --tail 80 "$nome" >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
Executable
+858
@@ -0,0 +1,858 @@
|
||||
#!/usr/bin/env bash
|
||||
# Pulizia del demone Docker del runner e del registro dei container. Il demone è lo stesso che costruisce Encelado,
|
||||
# Mimante e gli altri progetti di Alberto (e molto probabilmente quello delle applicazioni di Unraid), e ci può girare
|
||||
# anche un Febe vero. Dal 21 ottobre 2026 (decisione di Alberto) la pulizia toglie anche ciò che non serve più a
|
||||
# nessuno, di qualunque progetto: le immagini che nessun contenitore usa, la cache di costruzione, i resti di
|
||||
# act_runner. Mai un contenitore, un volume o una rete che non sia della CI.
|
||||
#
|
||||
# Della CI di Febe si toglie ciò che si può provare suo. Le etichette febe.ci.workflow, febe.ci.run, febe.ci.ref e
|
||||
# febe.ci.commit dicono da dove viene un'immagine, ma NON scelgono che cosa togliere: stanno anche nelle immagini
|
||||
# pubblicate (:main, :sha-, :X.Y.Z, :latest), e Docker le copia in ogni contenitore creato da quelle, quindi le porta
|
||||
# anche un Febe vero. Ciò che si toglie si riconosce così:
|
||||
# - contenitori di prova: l'etichetta febe.ci.prova=<esecuzione>, che mette solo prova-immagine.sh con
|
||||
# «docker run --label» e che nessuna immagine porta (lo controlla PipelineTests), E il nome esatto
|
||||
# febe-prova-<la stessa esecuzione> (gli altri contenitori della prova, senza nome, girano con --rm e Docker li
|
||||
# toglie da sé appena finiscono);
|
||||
# - immagini provate: il nome locale febe-ci:<esecuzione>, tolto per nome, mai per identificativo e mai con -f. Se la
|
||||
# stessa immagine ha anche un nome del registro, si toglie solo febe-ci:<esecuzione>; se un contenitore la usa, resta;
|
||||
# - builder buildx: il contenitore buildx_buildkit_febe-ci-<esecuzione>0, con l'immagine moby/buildkit, e il suo
|
||||
# volume …_state, che contengono la cache di costruzione di quell'esecuzione;
|
||||
# - l'immagine febe:ci lasciata dal vecchio flusso di verifica (prima del 20 ottobre 2026), se nessuno la usa.
|
||||
# Di act_runner si tolgono i resti dei lavori: act_runner chiama tutto ciò che crea per un lavoro
|
||||
# GITEA-ACTIONS-TASK-<numero del compito>… (il contenitore del lavoro, i suoi volumi <nome> e <nome>-env, la sua rete
|
||||
# <nome>-<lavoro>-network). Solo i contenitori fermi e i volumi e le reti che nessun contenitore usa, più vecchi di 90
|
||||
# minuti: un lavoro che parte li crea e li usa subito. Il volume act-toolcache (la cache degli strumenti, condivisa fra
|
||||
# i lavori) resta.
|
||||
#
|
||||
# pulizia-docker.sh esecuzione <id> tutto ciò che ha creato l'esecuzione <id> (all'inizio e alla fine del suo
|
||||
# lavoro «immagine», sempre)
|
||||
# pulizia-docker.sh penzolanti le immagini senza nome che nessun contenitore usa e la cache di costruzione
|
||||
# penzolante del demone (quella che nessuna immagine condivide) non usata da
|
||||
# 24 ore, di tutti i progetti (alla fine di ogni lavoro «immagine», dopo
|
||||
# «esecuzione»)
|
||||
# pulizia-docker.sh residui [minuti] i resti di esecuzioni interrotte, più vecchi di N minuti (predefinito 90: un
|
||||
# lavoro dura al massimo 60 minuti, quindi nessuno di essi è ancora vivo)
|
||||
# pulizia-docker.sh settimanale residui, febe:ci, immagini senza nome più vecchie di 72 ore: la pulizia
|
||||
# stretta di prima del 21 ottobre 2026, ora solo a mano
|
||||
# pulizia-docker.sh completa residui, febe:ci, resti di act_runner, le immagini che nessun contenitore
|
||||
# usa create più di 24 ore fa, la cache di costruzione non usata da 24 ore e,
|
||||
# con REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti
|
||||
# (flusso «pulizia», ogni lunedì e a mano)
|
||||
# pulizia-docker.sh <modo> --prova elenca che cosa toglierebbe e non toglie nulla: solo comandi che leggono
|
||||
# (sul registro solo GET)
|
||||
#
|
||||
# Gli argomenti si controllano tutti prima di toccare Docker: un'opzione diversa da --prova (--dry-run, -n, --Prova) o
|
||||
# un argomento in più (prova senza trattini) fermano tutto con codice 2, invece di far partire la pulizia vera al posto
|
||||
# della prova.
|
||||
#
|
||||
# Mai docker system prune, container prune, volume prune o network prune; mai image prune -a o builder prune -a senza
|
||||
# il filtro delle 24 ore; mai un contenitore, un volume o una rete che non sia della CI. Le immagini le toglie Docker
|
||||
# stesso (image prune), che non toglie mai un'immagine usata da un contenitore, nemmeno fermo; con -a, però, le toglie i
|
||||
# nomi in più, e lo script li scrive (nella prova li stima, secondo lo store). Sul registro mai main, latest o una
|
||||
# versione X.Y.Z: solo le etichette sha-<esadecimale> della verifica.
|
||||
#
|
||||
# Nei modi «residui», «settimanale» e «completa» un contenitore di prova si toglie solo se è fermo. Uno ancora acceso
|
||||
# dopo 90 minuti (il suo lavoro è stato ucciso proprio durante la prova del contenitore) resta dov'è: lo si segnala, con
|
||||
# il comando per toglierlo a mano. I builder sono l'eccezione: sono sempre accesi e la loro cache se ne va solo
|
||||
# togliendo il contenitore; si riconoscono dal nome esatto e dall'immagine di buildkit, mai da un'etichetta.
|
||||
#
|
||||
# Un oggetto già sparito non è un errore: la pulizia si può ripetere. Nei modi «esecuzione», «penzolanti» e «residui»
|
||||
# un problema diventa un avviso (un lavoro verde non diventa rosso per la pulizia, che il flusso del lunedì ripete); nei
|
||||
# modi «settimanale» e «completa» fa fallire il lavoro, perché qualcuno lo guardi. Il registro è l'eccezione: un
|
||||
# rifiuto della sua API è solo un avviso, e il lunedì dopo si riprova.
|
||||
#
|
||||
# Variabili per il registro (modo «completa»): REGISTRY_TOKEN (token con «package: read and write», mai stampato),
|
||||
# GITEA_API (l'API del server, per esempio https://gitea.example/api/v1) e PROPRIETARIO (il proprietario del pacchetto
|
||||
# febe). La scelta delle versioni da togliere sta in versioni-registro.js, accanto a questo script.
|
||||
set -uo pipefail
|
||||
|
||||
uso() {
|
||||
[[ -z "${1:-}" ]] || echo "$1" >&2
|
||||
echo "Uso: $0 esecuzione <id> | penzolanti | residui [minuti] | settimanale | completa [--prova]" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
prova=0
|
||||
argomenti=()
|
||||
for argomento in "$@"; do
|
||||
case "$argomento" in
|
||||
--prova) prova=1 ;;
|
||||
-*) uso "Opzione sconosciuta: «$argomento». L'unica è --prova." ;;
|
||||
*) argomenti+=("$argomento") ;;
|
||||
esac
|
||||
done
|
||||
modo="${argomenti[0]:-}"
|
||||
case "$modo" in
|
||||
esecuzione) ((${#argomenti[@]} == 2)) || uso "Il modo esecuzione vuole il numero dell'esecuzione e nient'altro." ;;
|
||||
residui) ((${#argomenti[@]} <= 2)) || uso "Il modo residui vuole al più i minuti." ;;
|
||||
penzolanti | settimanale | completa) ((${#argomenti[@]} == 1)) || uso "Il modo $modo non vuole altri argomenti: «${argomenti[1]}»." ;;
|
||||
*) uso ;;
|
||||
esac
|
||||
cartella_script="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
problemi=0
|
||||
|
||||
# In prova: i contenitori (identificativo e nome) e i nomi di immagine che la pulizia vera toglierebbe, perché gli
|
||||
# elenchi che seguono li trattino come già tolti (un volume usato solo da un contenitore che se ne andrebbe, per
|
||||
# esempio, se ne andrebbe anche lui).
|
||||
previsti=()
|
||||
nomi_previsti=()
|
||||
|
||||
# Per il riepilogo: quanti oggetti per tipo, nell'ordine in cui compaiono, e lo spazio recuperato da Docker.
|
||||
declare -A conteggi=()
|
||||
tipi=()
|
||||
note=()
|
||||
|
||||
# La cache di costruzione che si pota è quella del builder del demone, «default». docker builder è un alias di docker
|
||||
# buildx quando c'è il plugin, e buildx lavora sul builder corrente: nel lavoro «immagine» è quello dell'esecuzione
|
||||
# (setup-buildx-action lo crea con --use), che il modo «esecuzione» ha appena tolto. Gli altri comandi buildx di questo
|
||||
# script indicano il builder per nome.
|
||||
export BUILDX_BUILDER=default
|
||||
|
||||
avviso() {
|
||||
echo "::warning::$*"
|
||||
problemi=$((problemi + 1))
|
||||
}
|
||||
|
||||
# Un avviso che non fa diventare rosso il lavoro: per il registro.
|
||||
segnala() {
|
||||
echo "::warning::$*"
|
||||
}
|
||||
|
||||
conta() {
|
||||
[[ -n "${conteggi[$1]+x}" ]] || tipi+=("$1")
|
||||
conteggi[$1]=$((${conteggi[$1]:-0} + 1))
|
||||
}
|
||||
|
||||
# Vero se la prima parola è fra quelle che seguono.
|
||||
fra() {
|
||||
local cercata="$1" voce
|
||||
shift
|
||||
for voce in "$@"; do
|
||||
[[ "$voce" == "$cercata" ]] && return 0
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# Minuti trascorsi da un istante RFC 3339 come lo scrive Docker (Created di un contenitore o di un'immagine, CreatedAt
|
||||
# di un volume, {{json .Created}} di una rete, fra virgolette), con o senza frazioni di secondo, con «Z» o con lo scarto
|
||||
# dall'ora universale (+02:00). Se non si legge, 0: nel dubbio l'oggetto è giovane e resta.
|
||||
eta_minuti() {
|
||||
local creato="${1:-}" secondi
|
||||
creato="${creato//\"/}"
|
||||
[[ "$creato" =~ ^([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2})(\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})$ ]] \
|
||||
|| { echo 0; return; }
|
||||
secondi=$(date -u -d "${BASH_REMATCH[1]}${BASH_REMATCH[3]}" +%s 2> /dev/null) || { echo 0; return; }
|
||||
echo $((($(date -u +%s) - secondi) / 60))
|
||||
}
|
||||
|
||||
durata() {
|
||||
local minuti="$1"
|
||||
if ((minuti >= 2 * 1440)); then
|
||||
echo "$((minuti / 1440)) giorni"
|
||||
elif ((minuti >= 120)); then
|
||||
echo "$((minuti / 60)) ore"
|
||||
else
|
||||
echo "$minuti minuti"
|
||||
fi
|
||||
}
|
||||
|
||||
# Fra i contenitori dati (identificativi, uno per riga), quelli che restano dopo questa pulizia: in prova senza quelli
|
||||
# che la pulizia vera toglierebbe.
|
||||
restanti() {
|
||||
local id
|
||||
while read -r id; do
|
||||
[[ -n "$id" ]] || continue
|
||||
fra "$id" "${previsti[@]}" || echo "$id"
|
||||
done <<< "${1:-}"
|
||||
}
|
||||
|
||||
# I contenitori di prova della CI, uno per riga «id nome»: l'etichetta febe.ci.prova (dell'esecuzione indicata, o di
|
||||
# qualunque se il primo argomento è vuoto) e il nome esatto febe-prova-<valore dell'etichetta>. Gli stati che seguono
|
||||
# restringono la scelta (Docker li unisce in OR). Esce con 1 se Docker non risponde.
|
||||
contenitori_di_prova() {
|
||||
local run="$1"
|
||||
shift
|
||||
local stati=() stato elenco id nome valore
|
||||
for stato in "$@"; do stati+=(--filter "status=$stato"); done
|
||||
elenco=$(docker ps -a --no-trunc --filter "label=febe.ci.prova${run:+=$run}" "${stati[@]}" \
|
||||
--format '{{.ID}} {{.Names}} {{.Label "febe.ci.prova"}}') || return 1
|
||||
while read -r id nome valore; do
|
||||
[[ -n "${id:-}" && "${valore:-}" =~ ^[0-9]+$ && "${nome:-}" == "febe-prova-$valore" ]] || continue
|
||||
[[ -z "$run" || "$valore" == "$run" ]] || continue
|
||||
echo "$id $nome"
|
||||
done <<< "$elenco"
|
||||
}
|
||||
|
||||
# Toglie un contenitore con i suoi volumi anonimi (in prova lo elenca soltanto). Con «forza» anche se è acceso: solo
|
||||
# per quelli dell'esecuzione stessa e per i builder. Esce con 0 se il contenitore se ne va (o se ne andrebbe).
|
||||
togli_contenitore() {
|
||||
local id="$1" nome="$2" opzioni=(-v)
|
||||
[[ "${3:-}" == forza ]] && opzioni=(-f -v)
|
||||
if ((prova)); then
|
||||
echo " toglierei il contenitore $nome"
|
||||
previsti+=("$id" "$nome")
|
||||
return 0
|
||||
fi
|
||||
if docker rm "${opzioni[@]}" "$id" > /dev/null 2>&1; then
|
||||
echo " contenitore $nome tolto"
|
||||
return 0
|
||||
fi
|
||||
docker container inspect "$id" > /dev/null 2>&1 && avviso "Non riesco a togliere il contenitore $nome."
|
||||
return 1
|
||||
}
|
||||
|
||||
# Toglie il nome locale febe-ci:<esecuzione> (o febe:ci), mai l'immagine per identificativo e mai con -f: se l'immagine
|
||||
# ha anche un altro nome (del registro, per esempio) quello resta; se un contenitore la usa, resta tutto.
|
||||
togli_immagine() {
|
||||
local riferimento="$1" nomi
|
||||
[[ "$riferimento" =~ ^febe-ci:[0-9]+$ ]] || [[ "$riferimento" == febe:ci ]] \
|
||||
|| { avviso "Nome di immagine inatteso: «$riferimento»."; return 1; }
|
||||
nomi=$(docker image inspect -f '{{len .RepoTags}}' "$riferimento" 2> /dev/null) || return 1
|
||||
if [[ "$nomi" == 1 && -n "$(restanti "$(docker ps -a -q --no-trunc --filter "ancestor=$riferimento")")" ]]; then
|
||||
echo " immagine $riferimento in uso da un contenitore: resta"
|
||||
return 1
|
||||
fi
|
||||
if ((prova)); then
|
||||
echo " toglierei l'immagine $riferimento"
|
||||
nomi_previsti+=("$riferimento")
|
||||
return 0
|
||||
fi
|
||||
if docker image rm "$riferimento" > /dev/null 2>&1; then
|
||||
echo " immagine $riferimento tolta"
|
||||
return 0
|
||||
fi
|
||||
avviso "Non riesco a togliere l'immagine $riferimento."
|
||||
return 1
|
||||
}
|
||||
|
||||
# Un builder buildx della CI: prima con buildx (se questo client lo conosce), poi contenitore e volume per nome, perché
|
||||
# un lavoro diverso da quello che l'ha creato non ne ha la configurazione. Il contenitore si toglie solo se gira
|
||||
# l'immagine di buildkit, e il volume solo quando il contenitore non c'è più.
|
||||
togli_builder() {
|
||||
local builder="$1"
|
||||
[[ "$builder" =~ ^febe-ci-[0-9]+$ ]] || { avviso "Nome di builder inatteso: «$builder»."; return 1; }
|
||||
local contenitore="buildx_buildkit_${builder}0" volume="buildx_buildkit_${builder}0_state" immagine esito=1
|
||||
if ((!prova)) && docker buildx rm -f "$builder" > /dev/null 2>&1; then
|
||||
echo " builder $builder tolto"
|
||||
esito=0
|
||||
fi
|
||||
if immagine=$(docker container inspect -f '{{.Config.Image}}' "$contenitore" 2> /dev/null); then
|
||||
if [[ "$immagine" != *moby/buildkit* ]]; then
|
||||
avviso "Il contenitore $contenitore non è un builder buildx (immagine «$immagine»): resta."
|
||||
return 1
|
||||
fi
|
||||
togli_contenitore "$contenitore" "$contenitore" forza && esito=0
|
||||
if ((!prova)) && docker container inspect "$contenitore" > /dev/null 2>&1; then
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
if docker volume inspect "$volume" > /dev/null 2>&1; then
|
||||
if ((prova)); then
|
||||
echo " toglierei il volume $volume"
|
||||
esito=0
|
||||
elif docker volume rm -f "$volume" > /dev/null 2>&1; then
|
||||
echo " volume $volume tolto"
|
||||
esito=0
|
||||
else
|
||||
avviso "Non riesco a togliere il volume $volume."
|
||||
fi
|
||||
fi
|
||||
return "$esito"
|
||||
}
|
||||
|
||||
# Un volume o una rete di act_runner. Docker stesso non toglie un volume che un contenitore usa, né una rete con un
|
||||
# contenitore acceso collegato.
|
||||
togli_volume() {
|
||||
local nome="$1"
|
||||
if ((prova)); then
|
||||
echo " toglierei il volume $nome"
|
||||
return 0
|
||||
fi
|
||||
if docker volume rm "$nome" > /dev/null 2>&1; then
|
||||
echo " volume $nome tolto"
|
||||
return 0
|
||||
fi
|
||||
docker volume inspect "$nome" > /dev/null 2>&1 && avviso "Non riesco a togliere il volume $nome."
|
||||
return 1
|
||||
}
|
||||
|
||||
togli_rete() {
|
||||
local id="$1" nome="$2"
|
||||
if ((prova)); then
|
||||
echo " toglierei la rete $nome"
|
||||
return 0
|
||||
fi
|
||||
if docker network rm "$id" > /dev/null 2>&1; then
|
||||
echo " rete $nome tolta"
|
||||
return 0
|
||||
fi
|
||||
docker network inspect "$id" > /dev/null 2>&1 && avviso "Non riesco a togliere la rete $nome."
|
||||
return 1
|
||||
}
|
||||
|
||||
# Vero se nessun contenitore, acceso o fermo, usa il volume o la rete (in prova: nessuno che la pulizia vera
|
||||
# lascerebbe). Nel dubbio (Docker non risponde) falso: resta.
|
||||
nessuno_usa() {
|
||||
local tipo="$1" nome="$2" utenti
|
||||
if [[ "$tipo" == volume ]]; then
|
||||
utenti=$(docker ps -a -q --no-trunc --filter "volume=$nome") || return 1
|
||||
else
|
||||
utenti=$(docker ps -a -q --no-trunc --filter "network=$nome") || return 1
|
||||
fi
|
||||
[[ -z "$(restanti "$utenti")" ]]
|
||||
}
|
||||
|
||||
esecuzione() {
|
||||
local run="${1:-}"
|
||||
[[ "$run" =~ ^[0-9]+$ ]] || { echo "Indica il numero dell'esecuzione (gitea.run_id), non «$run»." >&2; exit 2; }
|
||||
echo "== Pulizia dell'esecuzione $run"
|
||||
local elenco id nome
|
||||
if elenco=$(contenitori_di_prova "$run"); then
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" ]] && togli_contenitore "$id" "$nome" forza
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare i contenitori di prova dell'esecuzione $run."
|
||||
fi
|
||||
togli_immagine "febe-ci:$run"
|
||||
togli_builder "febe-ci-$run"
|
||||
}
|
||||
|
||||
residui() {
|
||||
local minuti="${1:-90}"
|
||||
[[ "$minuti" =~ ^[0-9]+$ ]] || { echo "I minuti devono essere un numero, non «$minuti»." >&2; exit 2; }
|
||||
echo "== Resti di esecuzioni interrotte della CI di Febe, più vecchi di $minuti minuti"
|
||||
local elenco id nome eta riferimento builder
|
||||
|
||||
# Contenitori di prova fermi: si tolgono. Senza -f: se nel frattempo uno ripartisse, Docker lo lascia stare.
|
||||
if elenco=$(contenitori_di_prova "" exited created dead); then
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minuti)) && togli_contenitore "$id" "$nome" && conta "contenitori di prova della CI di Febe"
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare i contenitori di prova fermi."
|
||||
fi
|
||||
|
||||
# Contenitori di prova ancora accesi: non si toccano, si segnalano.
|
||||
if elenco=$(contenitori_di_prova "" running restarting paused); then
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
if ((eta >= minuti)); then
|
||||
avviso "Il contenitore di prova $nome è acceso da $eta minuti: il suo lavoro si è interrotto durante la prova. La pulizia non toglie contenitori accesi; se nessuna esecuzione lo usa più, toglilo a mano: docker rm -f -v $nome"
|
||||
fi
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare i contenitori di prova accesi."
|
||||
fi
|
||||
|
||||
# Immagini provate: solo i nomi febe-ci:<esecuzione>.
|
||||
if elenco=$(docker image ls --filter "reference=febe-ci" --format '{{.Repository}}:{{.Tag}}'); then
|
||||
while read -r riferimento; do
|
||||
[[ "${riferimento:-}" =~ ^febe-ci:[0-9]+$ ]] || continue
|
||||
eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$riferimento" 2> /dev/null)")
|
||||
((eta >= minuti)) && togli_immagine "$riferimento" && conta "immagini febe-ci"
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare le immagini febe-ci."
|
||||
fi
|
||||
|
||||
# Builder buildx. Il filtro per nome di Docker cerca una parte del nome: il nome esatto si controlla qui.
|
||||
if elenco=$(docker ps -a --no-trunc --filter "name=buildx_buildkit_febe-ci-" --format '{{.ID}} {{.Names}}'); then
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
nome="${nome#/}"
|
||||
[[ "$nome" =~ ^buildx_buildkit_(febe-ci-[0-9]+)0$ ]] || continue
|
||||
builder="${BASH_REMATCH[1]}"
|
||||
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minuti)) && togli_builder "$builder" && conta "builder buildx della CI di Febe"
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare i builder buildx."
|
||||
fi
|
||||
}
|
||||
|
||||
# I resti della CI di Febe e l'immagine febe:ci del vecchio flusso (modi «settimanale» e «completa»).
|
||||
resti_della_ci() {
|
||||
residui 90
|
||||
echo "== Immagine febe:ci del vecchio flusso di verifica"
|
||||
if docker image inspect febe:ci > /dev/null 2>&1; then
|
||||
togli_immagine febe:ci && conta "immagini febe-ci"
|
||||
fi
|
||||
}
|
||||
|
||||
# act_runner chiama i suoi oggetti GITEA-ACTIONS-TASK-<numero del compito>, seguito da «_WORKFLOW-…» o, nelle versioni
|
||||
# più vecchie, da «-WORKFLOW-…» con un'impronta in fondo.
|
||||
nome_act='^GITEA-ACTIONS-TASK-[0-9]+[-_]'
|
||||
|
||||
resti_di_act_runner() {
|
||||
local minuti="$1" elenco id nome eta
|
||||
echo "== Resti di act_runner (GITEA-ACTIONS-TASK-…) più vecchi di $minuti minuti: contenitori fermi, volumi e reti che nessun contenitore usa"
|
||||
|
||||
# Contenitori fermi. Il filtro per nome di Docker cerca una parte del nome: l'inizio esatto si controlla qui. Senza
|
||||
# -f: Docker non toglie un contenitore acceso.
|
||||
if elenco=$(docker ps -a --no-trunc --filter "name=GITEA-ACTIONS-TASK-" --filter "status=exited" \
|
||||
--filter "status=created" --filter "status=dead" --format '{{.ID}} {{.Names}}'); then
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
nome="${nome#/}"
|
||||
[[ "$nome" =~ $nome_act ]] || continue
|
||||
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minuti)) && togli_contenitore "$id" "$nome" && conta "contenitori fermi di act_runner"
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare i contenitori di act_runner."
|
||||
fi
|
||||
|
||||
# Volumi che nessun contenitore usa, nemmeno fermo.
|
||||
if elenco=$(docker volume ls -q --filter "name=GITEA-ACTIONS-TASK-"); then
|
||||
while read -r nome; do
|
||||
[[ -n "${nome:-}" && "$nome" =~ $nome_act ]] || continue
|
||||
eta=$(eta_minuti "$(docker volume inspect -f '{{.CreatedAt}}' "$nome" 2> /dev/null)")
|
||||
((eta >= minuti)) || continue
|
||||
nessuno_usa volume "$nome" && togli_volume "$nome" && conta "volumi di act_runner"
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare i volumi di act_runner."
|
||||
fi
|
||||
|
||||
# Reti a cui nessun contenitore è collegato, nemmeno fermo. Created di una rete è un istante di Go, che il modello
|
||||
# stampa come «2026-10-21 06:17:03 +0200 CEST»: in JSON è RFC 3339.
|
||||
if elenco=$(docker network ls --no-trunc --filter "name=GITEA-ACTIONS-TASK-" --format '{{.ID}} {{.Name}}'); then
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" && "${nome:-}" =~ $nome_act ]] || continue
|
||||
eta=$(eta_minuti "$(docker network inspect -f '{{json .Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minuti)) || continue
|
||||
nessuno_usa network "$nome" && togli_rete "$id" "$nome" && conta "reti di act_runner"
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare le reti di act_runner."
|
||||
fi
|
||||
}
|
||||
|
||||
# Le immagini dei contenitori, accesi o fermi, tranne quelli che la pulizia toglierebbe: «identificativo immagine» una
|
||||
# per riga, l'immagine come la si è data a docker run (un nome o un identificativo). Solo lettura: serve all'elenco
|
||||
# della prova.
|
||||
immagini_in_uso() {
|
||||
local elenco id nome
|
||||
elenco=$(docker ps -a --no-trunc --format '{{.ID}} {{.Names}}') || return 1
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
fra "$id" "${previsti[@]}" && continue
|
||||
fra "${nome#/}" "${previsti[@]}" && continue
|
||||
docker container inspect -f '{{.Image}} {{.Config.Image}}' "$id" 2> /dev/null
|
||||
done <<< "$elenco"
|
||||
return 0
|
||||
}
|
||||
|
||||
# Il nome completo di un nome d'immagine, come lo ordina Docker: docker.io/library/ o docker.io/ davanti ai nomi di
|
||||
# Docker Hub scritti senza dominio, :latest se manca l'etichetta.
|
||||
nome_completo() {
|
||||
local nome="$1" primo
|
||||
[[ "${nome##*/}" == *:* ]] || nome="$nome:latest"
|
||||
if [[ "$nome" != */* ]]; then
|
||||
echo "docker.io/library/$nome"
|
||||
return
|
||||
fi
|
||||
primo="${nome%%/*}"
|
||||
if [[ "$primo" == *.* || "$primo" == *:* || "$primo" == localhost ]]; then
|
||||
echo "$nome"
|
||||
else
|
||||
echo "docker.io/$nome"
|
||||
fi
|
||||
}
|
||||
|
||||
# In prova: i nomi che «image prune -a» toglierebbe a un'immagine che un contenitore usa (i nomi e le immagini dei
|
||||
# contenitori, come li scrivono docker image ls e docker container inspect), uno per riga. L'immagine resta, ma i nomi
|
||||
# in più no (moby). Con lo store classico Docker toglie i nomi in ordine alfabetico del nome completo e si ferma
|
||||
# all'ultimo, l'unico che rifiuta di togliere perché un contenitore usa l'immagine (daemon/images/image_prune.go e
|
||||
# image_delete.go, isSingleReference): può andarsene anche il nome da cui il contenitore è stato creato. Con containerd
|
||||
# restano i nomi da cui i contenitori sono stati creati e, se uno la usa per identificativo e nessun nome resterebbe,
|
||||
# l'ultimo in ordine alfabetico (daemon/containerd/image_prune.go).
|
||||
nomi_che_perde() {
|
||||
local id="$1" nomi="$2" configurazioni="$3" nome completo configurazione resto per_id=0 ordinati quanti
|
||||
local -A protetti=()
|
||||
local -a lista=() via=()
|
||||
ordinati=$(while read -r nome; do
|
||||
[[ -n "$nome" ]] && printf '%s %s\n' "$(nome_completo "$nome")" "$nome"
|
||||
done <<< "$nomi" | LC_ALL=C sort)
|
||||
quanti=$(grep -c . <<< "$ordinati")
|
||||
((quanti > 1)) || return 0
|
||||
if [[ "$store" != containerd ]]; then
|
||||
sed '$d' <<< "$ordinati" | cut -d' ' -f2-
|
||||
return 0
|
||||
fi
|
||||
read -r -a lista <<< "$configurazioni"
|
||||
for configurazione in "${lista[@]}"; do
|
||||
if [[ "$id" == "$configurazione"* || "$id" == "sha256:$configurazione"* ]]; then
|
||||
per_id=1
|
||||
elif [[ "$configurazione" == *@* ]]; then
|
||||
[[ "${configurazione#*@}" == "$id" ]] && per_id=1
|
||||
resto="${configurazione%%@*}"
|
||||
[[ "${resto##*/}" == *:* ]] && protetti[$(nome_completo "$resto")]=1
|
||||
else
|
||||
protetti[$(nome_completo "$configurazione")]=1
|
||||
fi
|
||||
done
|
||||
while read -r completo nome; do
|
||||
[[ -n "${protetti[$completo]:-}" ]] || via+=("$nome")
|
||||
done <<< "$ordinati"
|
||||
if ((per_id && ${#via[@]} == quanti)); then
|
||||
unset "via[$((quanti - 1))]"
|
||||
fi
|
||||
((${#via[@]} == 0)) || printf '%s\n' "${via[@]}"
|
||||
return 0
|
||||
}
|
||||
|
||||
# In prova: le immagini che la potatura toglierebbe, con dimensione ed età. Nessun contenitore le usa (a parte quelli
|
||||
# che questa pulizia toglierebbe) e sono state create più di N minuti fa; con «senza-nome» solo quelle senza nome. Con
|
||||
# «tutte», di un'immagine che un contenitore usa, i nomi in più che Docker le toglierebbe. È una stima fatta qui: nella
|
||||
# pulizia vera decide Docker (image prune).
|
||||
elenca_immagini() {
|
||||
local minimo="$1" quali="$2" usate elenco id nome breve dimensione eta quante=0 configurazione
|
||||
local -A nomi=() elenco_nomi=() dimensioni=() aveva_nomi=() usata_da=()
|
||||
local ordine=()
|
||||
if ! usate=$(immagini_in_uso) \
|
||||
|| ! elenco=$(docker image ls --no-trunc --format '{{.ID}}|{{.Repository}}:{{.Tag}}|{{.Size}}'); then
|
||||
avviso "Non riesco a elencare le immagini."
|
||||
return 0
|
||||
fi
|
||||
if [[ "$store" != classico ]] && ((minimo > 0)); then
|
||||
echo " (l'età qui è quella dell'immagine, dalla costruzione; con lo store di containerd la pulizia vera conta da quando il nome è arrivato sul demone, e un nome riscaricato tiene la data di prima: l'elenco è solo indicativo)"
|
||||
fi
|
||||
while read -r id configurazione; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
usata_da[$id]="${usata_da[$id]:+${usata_da[$id]} }$configurazione"
|
||||
done <<< "$usate"
|
||||
while IFS='|' read -r id nome dimensione; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
if [[ -z "${dimensioni[$id]+x}" ]]; then
|
||||
ordine+=("$id")
|
||||
dimensioni[$id]="${dimensione:-?}"
|
||||
nomi[$id]=""
|
||||
elenco_nomi[$id]=""
|
||||
fi
|
||||
[[ "$nome" == "<none>:<none>" ]] && continue
|
||||
aveva_nomi[$id]=1
|
||||
fra "$nome" "${nomi_previsti[@]}" && continue
|
||||
nomi[$id]="${nomi[$id]:+${nomi[$id]}, }$nome"
|
||||
[[ "$nome" == *":<none>" ]] || elenco_nomi[$id]+="$nome"$'\n'
|
||||
done <<< "$elenco"
|
||||
for id in "${ordine[@]}"; do
|
||||
# Un'immagine i cui nomi la pulizia toglie qui sopra se ne va già con l'ultimo.
|
||||
[[ -n "${aveva_nomi[$id]:-}" && -z "${nomi[$id]}" ]] && continue
|
||||
breve="${id#sha256:}"
|
||||
if [[ -n "${usata_da[$id]+x}" ]]; then
|
||||
# Un contenitore la usa: resta. Con -a, però, Docker le toglie i nomi in più.
|
||||
[[ "$quali" == tutte && -n "${elenco_nomi[$id]}" ]] || continue
|
||||
eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minimo)) || continue
|
||||
while read -r nome; do
|
||||
[[ -n "$nome" ]] || continue
|
||||
echo " toglierei il nome $nome; l'immagine ${breve:0:12} resta, perché la usa un contenitore"
|
||||
quante=$((quante + 1))
|
||||
conta "nomi tolti a immagini che restano"
|
||||
done < <(nomi_che_perde "$id" "${elenco_nomi[$id]}" "${usata_da[$id]}")
|
||||
continue
|
||||
fi
|
||||
[[ "$quali" == senza-nome && -n "${aveva_nomi[$id]:-}" ]] && continue
|
||||
eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minimo)) || continue
|
||||
nome="${nomi[$id]}"
|
||||
[[ -n "$nome" ]] || nome="un'immagine senza nome"
|
||||
echo " toglierei $nome (${breve:0:12}) · ${dimensioni[$id]} · creata $(durata "$eta") fa"
|
||||
quante=$((quante + 1))
|
||||
if [[ "$quali" == senza-nome ]]; then
|
||||
conta "immagini senza nome"
|
||||
else
|
||||
conta "immagini che nessun contenitore usa"
|
||||
fi
|
||||
done
|
||||
((quante > 0)) || echo " nessuna"
|
||||
}
|
||||
|
||||
# In prova: quanta cache di costruzione ha il demone. Quanta ne toglierebbe la potatura Docker non lo dice senza
|
||||
# toglierla: al più quella che nessuno sta usando («RECLAIMABLE» di docker system df).
|
||||
elenca_cache() {
|
||||
local riga tipo dimensione recuperabile
|
||||
riga=$(docker system df --format '{{.Type}}|{{.Size}}|{{.Reclaimable}}' 2> /dev/null | grep '^Build Cache|')
|
||||
if [[ -z "$riga" ]]; then
|
||||
echo " docker system df non dice quanta cache di costruzione c'è"
|
||||
return 0
|
||||
fi
|
||||
IFS='|' read -r tipo dimensione recuperabile <<< "$riga"
|
||||
echo " la cache di costruzione del demone occupa $dimensione; ne toglierei al più $recuperabile, la parte che nessuno sta usando"
|
||||
note+=("cache di costruzione: $dimensione in tutto, al più $recuperabile da togliere")
|
||||
}
|
||||
|
||||
# Lo store delle immagini del demone: «containerd» (io.containerd.snapshotter.v1, predefinito nelle installazioni nuove
|
||||
# di Docker Engine dalla 29) o «classico» (overlay2 e gli altri driver di prima). Ne dipende da quando contano le 24 ore
|
||||
# di image prune --filter until: con lo store classico dalla costruzione dell'immagine (Created della configurazione),
|
||||
# con containerd da quando il nome è arrivato sul demone (CreatedAt del suo record, che un nuovo pull dello stesso nome
|
||||
# non cambia).
|
||||
store=""
|
||||
rileva_store() {
|
||||
local stato
|
||||
if ! stato=$(docker info --format '{{json .DriverStatus}}' 2> /dev/null); then
|
||||
store=sconosciuto
|
||||
elif [[ "$stato" == *io.containerd.snapshotter* ]]; then
|
||||
store=containerd
|
||||
else
|
||||
store=classico
|
||||
fi
|
||||
case "$store" in
|
||||
containerd) echo "== Store delle immagini del demone: containerd (le 24 ore contano da quando un nome è arrivato sul demone)" ;;
|
||||
classico) echo "== Store delle immagini del demone: classico (le 24 ore contano dalla costruzione dell'immagine)" ;;
|
||||
*) echo "== Store delle immagini del demone: non lo so, docker info non risponde" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Ogni immagine con ciascuno dei suoi nomi, «identificativo nome» una per riga (<none>:<none> se non ne ha).
|
||||
immagini_e_nomi() {
|
||||
docker image ls --no-trunc --format '{{.ID}} {{.Repository}}:{{.Tag}}' 2> /dev/null
|
||||
}
|
||||
|
||||
# Lo spazio recuperato secondo Docker: «Total reclaimed space: 1.2GB» (docker) o «Total: 1.2GB» (buildx).
|
||||
spazio_recuperato() {
|
||||
local riga
|
||||
riga=$(grep -E '^Total' <<< "$1" | tail -n 1 | sed -E 's/^Total( reclaimed space)?:[[:space:]]*//')
|
||||
echo "${riga:-0B}"
|
||||
}
|
||||
|
||||
# Una potatura di immagini di Docker: i nomi tolti, quante immagini e quanto spazio. Un errore è un avviso. I nomi si
|
||||
# confrontano prima e dopo: con -a Docker toglie anche i nomi in più di un'immagine che un contenitore usa e che resta,
|
||||
# e il registro del lavoro lo dice.
|
||||
pota_immagini() {
|
||||
local cosa="$1" uscita prima dopo recuperato prima_nomi dopo_nomi dopo_id id nome breve
|
||||
shift
|
||||
prima_nomi=$(immagini_e_nomi)
|
||||
prima=$(cut -d' ' -f1 <<< "$prima_nomi" | sort -u | grep -c .)
|
||||
if ! uscita=$("$@" 2>&1); then
|
||||
avviso "Non riesco a togliere le $cosa: $(tail -n 1 <<< "$uscita")"
|
||||
return 0
|
||||
fi
|
||||
dopo_nomi=$(immagini_e_nomi)
|
||||
dopo_id=$(cut -d' ' -f1 <<< "$dopo_nomi" | sort -u)
|
||||
dopo=$(grep -c . <<< "$dopo_id")
|
||||
while read -r id nome; do
|
||||
[[ -n "${nome:-}" && "$nome" != *":<none>" ]] || continue
|
||||
grep -qxF -- "$id $nome" <<< "$dopo_nomi" && continue
|
||||
if grep -qxF -- "$id" <<< "$dopo_id"; then
|
||||
breve="${id#sha256:}"
|
||||
echo " tolto il nome $nome; l'immagine ${breve:0:12} resta"
|
||||
conta "nomi tolti a immagini che restano"
|
||||
else
|
||||
echo " tolta $nome"
|
||||
fi
|
||||
done <<< "$prima_nomi"
|
||||
recuperato=$(spazio_recuperato "$uscita")
|
||||
if [[ "$prima" =~ ^[0-9]+$ && "$dopo" =~ ^[0-9]+$ ]]; then
|
||||
echo " $cosa: $((prima - dopo)) tolte, $recuperato recuperati"
|
||||
note+=("$cosa: $((prima - dopo)) tolte ($prima prima, $dopo dopo), $recuperato recuperati")
|
||||
else
|
||||
echo " $cosa: $recuperato recuperati"
|
||||
note+=("$cosa: $recuperato recuperati")
|
||||
fi
|
||||
}
|
||||
|
||||
# Una potatura della cache di costruzione: quanto spazio. Un errore è un avviso.
|
||||
pota_cache() {
|
||||
local cosa="$1" uscita recuperato
|
||||
shift
|
||||
if ! uscita=$("$@" 2>&1); then
|
||||
avviso "Non riesco a togliere la $cosa: $(tail -n 1 <<< "$uscita")"
|
||||
return 0
|
||||
fi
|
||||
recuperato=$(spazio_recuperato "$uscita")
|
||||
echo " $cosa: $recuperato recuperati"
|
||||
note+=("$cosa: $recuperato recuperati")
|
||||
}
|
||||
|
||||
# Una chiamata all'API di Gitea con il token del registro, che sta solo nell'intestazione di curl e mai nel registro
|
||||
# del lavoro. Stampa il codice HTTP: 000 se Gitea non risponde.
|
||||
chiedi() {
|
||||
local metodo="$1" indirizzo="$2" uscita="$3" codice
|
||||
codice=$(curl -sS --max-time 30 -X "$metodo" -H "Authorization: token $REGISTRY_TOKEN" -H "Accept: application/json" \
|
||||
-o "$uscita" -w '%{http_code}' "$indirizzo") || true
|
||||
echo "${codice:-000}"
|
||||
}
|
||||
|
||||
spiega() {
|
||||
case "$1" in
|
||||
000) echo "niente (Gitea non risponde)" ;;
|
||||
401) echo "401: il token non vale" ;;
|
||||
403) echo "403: il token non ha il permesso «package: read and write»" ;;
|
||||
*) echo "$1" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Le etichette sha- del pacchetto febe oltre le 10 più recenti, con l'API dei pacchetti di Gitea 28:
|
||||
# GET /api/v1/packages/{proprietario}/container/febe?page=N&limit=50 le versioni, una pagina alla volta finché
|
||||
# ne arriva una vuota (il server può darne
|
||||
# meno di 50 per pagina)
|
||||
# DELETE /api/v1/packages/{proprietario}/container/febe/{versione} una versione (risponde 204)
|
||||
# Quali togliere lo sceglie versioni-registro.js; qui si ricontrolla la forma sha-<esadecimale> prima di ogni DELETE.
|
||||
# Ogni rifiuto dell'API è un avviso che non fa diventare rosso il lavoro. Le versioni sha256:… senza etichetta (i
|
||||
# manifest figli di un indice, con gli strati) non si toccano mai: l'API non dice se un'etichetta le usa ancora. Si
|
||||
# dice solo quante sono; la CI pubblica manifest semplici (costruisci-immagine.sh), quindi non dovrebbero essercene, e
|
||||
# quelle che nessuna etichetta usa le toglie una regola di pulizia di Gitea (docs/processo.md, «Registro dei container»).
|
||||
registro() {
|
||||
local tenere=10
|
||||
echo "== Registro: le etichette sha- del pacchetto febe oltre le $tenere più recenti"
|
||||
if [[ -z "${REGISTRY_TOKEN:-}" ]]; then
|
||||
echo " Manca il segreto REGISTRY_TOKEN: il registro non si tocca."
|
||||
return 0
|
||||
fi
|
||||
if [[ -z "${GITEA_API:-}" || -z "${PROPRIETARIO:-}" ]]; then
|
||||
segnala "Mancano GITEA_API o PROPRIETARIO: il registro non si tocca."
|
||||
return 0
|
||||
fi
|
||||
local programma
|
||||
for programma in curl node; do
|
||||
command -v "$programma" > /dev/null || { segnala "Manca $programma: il registro non si tocca."; return 0; }
|
||||
done
|
||||
local base="${GITEA_API%/}/packages/$PROPRIETARIO/container/febe" cartella pagina codice scelte
|
||||
cartella=$(mktemp -d) || { segnala "Non riesco a creare una cartella temporanea: il registro non si tocca."; return 0; }
|
||||
for ((pagina = 1; ; pagina++)); do
|
||||
if ((pagina > 200)); then
|
||||
segnala "Più di 200 pagine di versioni sul registro: il registro non si tocca."
|
||||
rm -rf "$cartella"
|
||||
return 0
|
||||
fi
|
||||
codice=$(chiedi GET "$base?page=$pagina&limit=50" "$cartella/pagina-$pagina.json")
|
||||
if [[ "$codice" == 404 && "$pagina" == 1 ]]; then
|
||||
echo " Il pacchetto febe non è ancora sul registro: niente da togliere."
|
||||
rm -rf "$cartella"
|
||||
return 0
|
||||
fi
|
||||
if [[ "$codice" != 200 ]]; then
|
||||
segnala "L'API dei pacchetti di Gitea risponde $(spiega "$codice") alla pagina $pagina delle versioni: il registro non si tocca."
|
||||
rm -rf "$cartella"
|
||||
return 0
|
||||
fi
|
||||
case "$(tr -d '[:space:]' < "$cartella/pagina-$pagina.json")" in
|
||||
"[]" | null) break ;;
|
||||
esac
|
||||
done
|
||||
local senza_etichetta quante
|
||||
if ! scelte=$(node "$cartella_script/versioni-registro.js" "$tenere" "$cartella"/pagina-*.json) \
|
||||
|| ! senza_etichetta=$(node "$cartella_script/versioni-registro.js" senza-etichetta "$cartella"/pagina-*.json); then
|
||||
segnala "Non riesco a leggere le versioni del pacchetto febe: il registro non si tocca."
|
||||
rm -rf "$cartella"
|
||||
return 0
|
||||
fi
|
||||
rm -rf "$cartella"
|
||||
quante=$(grep -c . <<< "$senza_etichetta")
|
||||
if ((quante > 0)); then
|
||||
echo " $quante versioni senza etichetta (sha256:…, i manifest di un indice con i loro strati): restano, questa pulizia non le tocca mai (docs/processo.md, «Registro dei container»)"
|
||||
note+=("registro: $quante versioni sha256:… senza etichetta, che restano")
|
||||
fi
|
||||
if [[ -z "$scelte" ]]; then
|
||||
echo " niente da togliere"
|
||||
return 0
|
||||
fi
|
||||
local versione creata
|
||||
while IFS=$'\t' read -r versione creata; do
|
||||
[[ -n "${versione:-}" ]] || continue
|
||||
if [[ ! "$versione" =~ ^sha-[0-9a-f]{7,40}$ ]]; then
|
||||
segnala "Versione inattesa «$versione» fra quelle da togliere: resta."
|
||||
continue
|
||||
fi
|
||||
if ((prova)); then
|
||||
echo " toglierei $versione (pubblicata il $creata)"
|
||||
conta "etichette sha- sul registro"
|
||||
continue
|
||||
fi
|
||||
codice=$(chiedi DELETE "$base/$versione" /dev/null)
|
||||
if [[ "$codice" == 204 ]]; then
|
||||
echo " $versione tolta (pubblicata il $creata)"
|
||||
conta "etichette sha- sul registro"
|
||||
else
|
||||
segnala "Non riesco a togliere $versione dal registro: l'API risponde $(spiega "$codice")."
|
||||
fi
|
||||
done <<< "$scelte"
|
||||
}
|
||||
|
||||
# La cache con lo stesso limite del lunedì: senza, a ogni push di ogni ramo se ne andrebbero gli strati intermedi e le
|
||||
# cache montate (RUN --mount=type=cache) che le costruzioni degli altri progetti hanno appena usato.
|
||||
penzolanti() {
|
||||
echo "== Immagini senza nome che nessun contenitore usa e cache di costruzione penzolante non usata da 24 ore, di tutti i progetti"
|
||||
if ((prova)); then
|
||||
elenca_immagini 0 senza-nome
|
||||
elenca_cache
|
||||
return 0
|
||||
fi
|
||||
pota_immagini "immagini senza nome" docker image prune -f
|
||||
pota_cache "cache di costruzione penzolante" docker builder prune -f --filter "until=24h"
|
||||
}
|
||||
|
||||
settimanale() {
|
||||
resti_della_ci
|
||||
echo "== Immagini senza nome più vecchie di 72 ore che nessun contenitore usa"
|
||||
if ((prova)); then
|
||||
elenca_immagini 4320 senza-nome
|
||||
else
|
||||
pota_immagini "immagini senza nome" docker image prune -f --filter "until=72h"
|
||||
fi
|
||||
}
|
||||
|
||||
# Tutto ciò che fa «settimanale» (le immagini senza nome più vecchie di 72 ore sono fra quelle che nessun contenitore
|
||||
# usa create più di 24 ore fa) e in più i resti di act_runner, le immagini e la cache di tutti e il registro. Prima i
|
||||
# contenitori, così le loro immagini, i loro volumi e le loro reti restano senza nessuno che li usi.
|
||||
completa() {
|
||||
resti_della_ci
|
||||
resti_di_act_runner 90
|
||||
echo "== Immagini che nessun contenitore usa, create più di 24 ore fa, di tutti i progetti"
|
||||
if ((prova)); then
|
||||
elenca_immagini 1440 tutte
|
||||
else
|
||||
pota_immagini "immagini che nessun contenitore usa" docker image prune -a -f --filter "until=24h"
|
||||
fi
|
||||
echo "== Cache di costruzione del demone non usata da più di 24 ore"
|
||||
if ((prova)); then
|
||||
elenca_cache
|
||||
else
|
||||
pota_cache "cache di costruzione" docker builder prune -a -f --filter "until=24h"
|
||||
fi
|
||||
registro
|
||||
}
|
||||
|
||||
riepilogo() {
|
||||
local tipo riga
|
||||
if ((prova)); then
|
||||
echo "== Riepilogo della prova (che cosa toglierei; non è stato tolto nulla)"
|
||||
else
|
||||
echo "== Riepilogo"
|
||||
fi
|
||||
for tipo in "${tipi[@]}"; do
|
||||
echo " $tipo: ${conteggi[$tipo]}"
|
||||
done
|
||||
for riga in "${note[@]}"; do
|
||||
echo " $riga"
|
||||
done
|
||||
((${#tipi[@]} + ${#note[@]} > 0)) || echo " niente"
|
||||
}
|
||||
|
||||
command -v docker > /dev/null || { echo "Manca il client Docker: niente da pulire." >&2; exit 2; }
|
||||
((prova)) && echo "Prova: elenco che cosa toglierei, senza togliere nulla."
|
||||
case "$modo" in
|
||||
esecuzione) esecuzione "${argomenti[1]:-}" ;;
|
||||
penzolanti) penzolanti ;;
|
||||
residui) residui "${argomenti[1]:-90}" ;;
|
||||
settimanale | completa)
|
||||
rileva_store
|
||||
docker system df || true
|
||||
if [[ "$modo" == settimanale ]]; then settimanale; else completa; fi
|
||||
docker system df || true
|
||||
riepilogo
|
||||
;;
|
||||
*) uso ;;
|
||||
esac
|
||||
|
||||
if ((problemi > 0)); then
|
||||
echo "Pulizia finita con $problemi avvisi."
|
||||
[[ "$modo" == settimanale || "$modo" == completa ]] && exit 1
|
||||
fi
|
||||
exit 0
|
||||
Executable
+106
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env bash
|
||||
# Riepilogo dei risultati delle prove (file .trx di «dotnet test --logger trx»): superate, fallite e saltate per ogni
|
||||
# file, i nomi delle fallite e i motivi delle saltate. Lo scrive nel registro e, se il runner lo offre, nel riepilogo
|
||||
# del lavoro (GITHUB_STEP_SUMMARY). Nessun corpo di risposta né dato personale: solo nomi di prove e messaggi.
|
||||
#
|
||||
# .gitea/scripts/riepilogo-prove.sh <cartella dei .trx> [saltate ammesse]
|
||||
#
|
||||
# Esce con 1 se una prova è fallita, se le saltate sono più di quelle ammesse (predefinito 0: nella CI ci sono
|
||||
# Chromium, Xvfb, ffmpeg, NSIS e Node, quindi nessuna prova ha motivo di saltarsi) o se non c'è nessun risultato.
|
||||
set -euo pipefail
|
||||
|
||||
cartella="${1:?Indica la cartella con i file .trx.}"
|
||||
ammesse="${2:-${PROVE_SALTATE_AMMESSE:-0}}"
|
||||
[[ "$ammesse" =~ ^[0-9]+$ ]] || { echo "Il numero di prove saltate ammesse deve essere un intero, non «$ammesse»." >&2; exit 2; }
|
||||
|
||||
shopt -s nullglob
|
||||
file=("$cartella"/*.trx)
|
||||
if (( ${#file[@]} == 0 )); then
|
||||
echo "Nessun risultato delle prove in $cartella: le prove non sono partite." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
riepilogo="$(mktemp)"
|
||||
trap 'rm -f "$riepilogo"' EXIT
|
||||
|
||||
fallite_totali=0
|
||||
saltate_totali=0
|
||||
{
|
||||
echo "### Prove"
|
||||
echo
|
||||
echo "| Risultati | Totale | Superate | Fallite | Saltate |"
|
||||
echo "|---|---:|---:|---:|---:|"
|
||||
} > "$riepilogo"
|
||||
|
||||
for trx in "${file[@]}"; do
|
||||
nome="$(basename "$trx")"
|
||||
# Un risultato per riga (i .trx sono XML su più righe), poi nome, esito e primo messaggio di ciascuno.
|
||||
righe="$(tr '\r\n' ' ' < "$trx" | sed 's/<UnitTestResult /\n<UnitTestResult /g' | awk '
|
||||
function attributo(testo, chiave, inizio) {
|
||||
if (match(testo, chiave "=\"[^\"]*\"")) {
|
||||
return substr(testo, RSTART + length(chiave) + 2, RLENGTH - length(chiave) - 3)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
function testo_xml(s) {
|
||||
gsub(/
/, "", s); gsub(/
/, " ", s); gsub(/'/, "\047", s); gsub(/"/, "\"", s)
|
||||
gsub(/</, "<", s); gsub(/>/, ">", s); gsub(/&/, "\\&", s); gsub(/[ \t]+/, " ", s)
|
||||
return s
|
||||
}
|
||||
/^<UnitTestResult / {
|
||||
testata = $0
|
||||
sub(/>.*/, "", testata)
|
||||
messaggio = ""
|
||||
if (match($0, /<Message>[^<]*<\/Message>/)) {
|
||||
messaggio = substr($0, RSTART + 9, RLENGTH - 19)
|
||||
}
|
||||
printf "%s\t%s\t%s\n", attributo(testata, "outcome"), testo_xml(attributo(testata, "testName")), testo_xml(messaggio)
|
||||
}')"
|
||||
|
||||
totale=0; superate=0; fallite=0; saltate=0
|
||||
if [[ -n "$righe" ]]; then
|
||||
totale=$(printf '%s\n' "$righe" | wc -l)
|
||||
superate=$(printf '%s\n' "$righe" | awk -F'\t' '$1 == "Passed"' | wc -l)
|
||||
fallite=$(printf '%s\n' "$righe" | awk -F'\t' '$1 == "Failed" || $1 == "Error" || $1 == "Timeout" || $1 == "Aborted"' | wc -l)
|
||||
fi
|
||||
saltate=$((totale - superate - fallite))
|
||||
fallite_totali=$((fallite_totali + fallite))
|
||||
saltate_totali=$((saltate_totali + saltate))
|
||||
|
||||
echo "== $nome: totale $totale · superate $superate · fallite $fallite · saltate $saltate"
|
||||
echo "| \`$nome\` | $totale | $superate | $fallite | $saltate |" >> "$riepilogo"
|
||||
|
||||
if (( fallite > 0 )); then
|
||||
echo " Fallite:"
|
||||
# Le righe in più si leggono e si scartano (niente «head»: con pipefail il SIGPIPE fermerebbe lo script).
|
||||
printf '%s\n' "$righe" | awk -F'\t' '$1 == "Failed" || $1 == "Error" || $1 == "Timeout" || $1 == "Aborted" {
|
||||
if (++n > 50) next; m = $3; if (length(m) > 300) m = substr(m, 1, 300) "…"; print " - " $2 ": " m }'
|
||||
fi
|
||||
|
||||
if (( saltate > 0 )); then
|
||||
echo " Saltate, per motivo:"
|
||||
# Il motivo senza la cornice di MSTest («Il metodo … ha generato un'eccezione. Assert.Inconclusive.»).
|
||||
printf '%s\n' "$righe" | awk -F'\t' '$1 != "Passed" && $1 != "Failed" && $1 != "Error" && $1 != "Timeout" && $1 != "Aborted" {
|
||||
m = $3; sub(/^.*Assert\.Inconclusive\. */, "", m); if (m == "") m = "(nessun motivo)"; print m }' \
|
||||
| sort | uniq -c | sort -rn | awk 'NR <= 30 { sub(/^ */, " "); print }'
|
||||
fi
|
||||
done
|
||||
|
||||
esito=0
|
||||
{
|
||||
echo
|
||||
echo "Fallite: $fallite_totali · saltate: $saltate_totali (ammesse: $ammesse)."
|
||||
} >> "$riepilogo"
|
||||
if (( fallite_totali > 0 )); then
|
||||
echo "Prove fallite: $fallite_totali (i file .trx sono fra gli artefatti dell'esecuzione)." >&2
|
||||
esito=1
|
||||
fi
|
||||
if (( saltate_totali > ammesse )); then
|
||||
echo "Prove saltate: $saltate_totali, più delle $ammesse ammesse. Qui ci sono Chromium, Xvfb, ffmpeg, NSIS e Node: una prova che si salta segnala un ambiente rotto, non una prova superata." >&2
|
||||
esito=1
|
||||
fi
|
||||
|
||||
if [[ -n "${GITHUB_STEP_SUMMARY:-}" ]]; then
|
||||
cat "$riepilogo" >> "$GITHUB_STEP_SUMMARY" || true
|
||||
fi
|
||||
exit "$esito"
|
||||
Executable
+54
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env bash
|
||||
# Scansione delle vulnerabilità dell'immagine Docker con Trivy, a versione fissa (strumento.sh), sull'archivio prodotto
|
||||
# dalla costruzione (docker save o buildx --output type=docker): non serve il demone, e si scansiona proprio
|
||||
# l'immagine provata. Pacchetti di Debian e dipendenze .NET di Febe (i file *.deps.json).
|
||||
#
|
||||
# .gitea/scripts/scansione-immagine.sh <immagine.tar> [cartella dei rapporti]
|
||||
#
|
||||
# La regola (docs/processo.md, «Rilievi di sicurezza»):
|
||||
# - CRITICAL con una correzione disponibile: il lavoro fallisce e l'immagine non si pubblica;
|
||||
# - HIGH, e CRITICAL ancora senza correzione: si riportano nel registro e in trivy.json, senza fermare nulla.
|
||||
# Le eccezioni stanno solo in .trivyignore, alla radice del repository: un identificativo per riga, con la scadenza
|
||||
# (exp:AAAA-MM-GG) e, sulla riga sopra, il motivo scritto e chi l'ha deciso.
|
||||
set -euo pipefail
|
||||
|
||||
radice="$(git rev-parse --show-toplevel)"
|
||||
archivio="${1:?Manca il file .tar da scansionare.}"
|
||||
rapporti="${2:-$radice/out/sicurezza}"
|
||||
lavoro="${RUNNER_TEMP:-/tmp}"
|
||||
strumenti="$lavoro/febe-strumenti"
|
||||
|
||||
[[ -s "$archivio" ]] || { echo "Manca l'archivio dell'immagine: $archivio" >&2; exit 2; }
|
||||
bash "$radice/.gitea/scripts/strumento.sh" trivy "$strumenti"
|
||||
mkdir -p "$rapporti"
|
||||
|
||||
# Niente barre di avanzamento, niente controllo di versioni nuove, niente dati d'uso.
|
||||
export TRIVY_NO_PROGRESS=true TRIVY_SKIP_VERSION_CHECK=true TRIVY_DISABLE_TELEMETRY=true
|
||||
export TRIVY_CACHE_DIR="$lavoro/febe-trivy-cache"
|
||||
comuni=(image --input "$archivio" --scanners vuln --timeout 20m)
|
||||
if [[ -f "$radice/.trivyignore" ]]; then
|
||||
comuni+=(--ignorefile "$radice/.trivyignore")
|
||||
echo "Eccezioni in .trivyignore: $(grep -c -E '^[^#[:space:]]' "$radice/.trivyignore" || true)"
|
||||
fi
|
||||
|
||||
echo "== Vulnerabilità HIGH e CRITICAL (rapporto: non fermano il lavoro)"
|
||||
"$strumenti/trivy" "${comuni[@]}" --severity HIGH,CRITICAL --format json --output "$rapporti/trivy.json" --exit-code 0
|
||||
"$strumenti/trivy" convert --format table "$rapporti/trivy.json"
|
||||
|
||||
if command -v jq > /dev/null; then
|
||||
conteggio=$(jq -r '[.Results[]?.Vulnerabilities[]?] as $v
|
||||
| "HIGH \([$v[] | select(.Severity == "HIGH")] | length) · CRITICAL \([$v[] | select(.Severity == "CRITICAL")] | length), di cui correggibili \([$v[] | select(.Severity == "CRITICAL" and ((.FixedVersion // "") != ""))] | length)"' "$rapporti/trivy.json")
|
||||
echo "Trovate: $conteggio."
|
||||
if [[ -n "${GITHUB_STEP_SUMMARY:-}" ]]; then
|
||||
printf "### Sicurezza dell'immagine (Trivy)\n\n%s.\n" "$conteggio" >> "$GITHUB_STEP_SUMMARY" || true
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "== CRITICAL con una correzione disponibile (fermano il lavoro)"
|
||||
if "$strumenti/trivy" "${comuni[@]}" --skip-db-update --skip-java-db-update --severity CRITICAL --ignore-unfixed \
|
||||
--format table --exit-code 1; then
|
||||
echo "Nessuna vulnerabilità CRITICAL con una correzione disponibile."
|
||||
else
|
||||
echo "Vulnerabilità CRITICAL con una correzione disponibile: l'immagine non passa. Aggiorna il pacchetto o la dipendenza (docs/processo.md, «Rilievi di sicurezza»)." >&2
|
||||
exit 1
|
||||
fi
|
||||
Executable
+47
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env bash
|
||||
# Cerca segreti (gettoni, chiavi, password) con gitleaks, a versione fissa (strumento.sh), in tutta la storia del
|
||||
# commit verificato: ogni commit da cui discende, non solo l'ultimo. Ogni ramo si controlla al suo push (main a ogni
|
||||
# unione), così un rilievo su un ramo non blocca gli altri. Un segreto non compare mai per intero: --redact lo
|
||||
# sostituisce con REDACTED nel registro e nel rapporto, e qui si stampano solo regola, file, riga, commit e impronta.
|
||||
#
|
||||
# .gitea/scripts/segreti.sh [cartella del rapporto]
|
||||
#
|
||||
# Che cosa fare con un rilievo: docs/processo.md, «Rilievi di sicurezza». In breve: un segreto vero si revoca subito
|
||||
# (toglierlo dalla storia non basta); un falso allarme già controllato (un dato di prova finto) si mette in
|
||||
# .gitleaksignore con la sua impronta e, sulla riga sopra, un commento che dice che cos'è e chi l'ha controllato.
|
||||
set -euo pipefail
|
||||
|
||||
radice="$(git rev-parse --show-toplevel)"
|
||||
rapporti="${1:-$radice/out/sicurezza}"
|
||||
strumenti="${RUNNER_TEMP:-/tmp}/febe-strumenti"
|
||||
|
||||
if [[ "$(git -C "$radice" rev-parse --is-shallow-repository)" == "true" ]]; then
|
||||
echo "Il clone è parziale: per cercare in tutta la storia serve actions/checkout con fetch-depth: 0." >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
bash "$radice/.gitea/scripts/strumento.sh" gitleaks "$strumenti"
|
||||
mkdir -p "$rapporti"
|
||||
rapporto="$rapporti/gitleaks.json"
|
||||
|
||||
argomenti=(git "$radice" --log-opts="--full-history HEAD" --redact --no-banner --no-color --exit-code 1 --log-level warn
|
||||
--report-format json --report-path "$rapporto")
|
||||
[[ -f "$radice/.gitleaks.toml" ]] && argomenti+=(--config "$radice/.gitleaks.toml")
|
||||
[[ -f "$radice/.gitleaksignore" ]] && argomenti+=(--gitleaks-ignore-path "$radice/.gitleaksignore")
|
||||
|
||||
commit=$(git -C "$radice" rev-list --count HEAD)
|
||||
stato=0
|
||||
"$strumenti/gitleaks" "${argomenti[@]}" || stato=$?
|
||||
if ((stato == 0)); then
|
||||
echo "Nessun segreto in $commit commit."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [[ -s "$rapporto" ]] && command -v jq > /dev/null; then
|
||||
quanti=$(jq 'length' "$rapporto")
|
||||
echo "Possibili segreti: $quanti (in $commit commit). Regola, file:riga, commit, impronta per .gitleaksignore:" >&2
|
||||
jq -r '.[] | " \(.RuleID) \(.File):\(.StartLine) commit \(.Commit[0:12]) impronta \(.Fingerprint)"' "$rapporto" >&2
|
||||
else
|
||||
echo "gitleaks è uscito con $stato: vedi il registro qui sopra e il rapporto $rapporto." >&2
|
||||
fi
|
||||
exit "$stato"
|
||||
Executable
+60
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env bash
|
||||
# Installa uno dei due strumenti esterni della CI, gli unici approvati da Alberto e solo per la CI (20 ottobre 2026):
|
||||
# gitleaks (segreti nella storia) e Trivy (vulnerabilità dell'immagine). Versione fissa, archivio scaricato dalla
|
||||
# release del progetto e installato solo se la sua impronta SHA-256 coincide con quella scritta qui. Le impronte sono
|
||||
# quelle dei file *_checksums.txt delle release, ricontrollate il 20 ottobre 2026 sull'archivio scaricato e
|
||||
# sull'impronta che GitHub mostra per l'allegato.
|
||||
#
|
||||
# .gitea/scripts/strumento.sh gitleaks|trivy <cartella>
|
||||
#
|
||||
# Per aggiornare uno strumento si cambiano versione e impronta insieme, in un commit solo, con una riga in
|
||||
# docs/decisioni.md. Mai «latest», mai le azioni di terzi (trivy-action fu compromessa a marzo 2026, CVE-2026-33634),
|
||||
# mai uno script di installazione scaricato al volo.
|
||||
set -euo pipefail
|
||||
|
||||
nome="${1:?Indica lo strumento: gitleaks o trivy.}"
|
||||
cartella="${2:?Indica la cartella in cui installarlo.}"
|
||||
|
||||
case "$nome" in
|
||||
gitleaks)
|
||||
versione="8.30.1"
|
||||
archivio="gitleaks_${versione}_linux_x64.tar.gz"
|
||||
indirizzo="https://github.com/gitleaks/gitleaks/releases/download/v${versione}/${archivio}"
|
||||
sha256="551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb"
|
||||
;;
|
||||
trivy)
|
||||
versione="0.75.0"
|
||||
archivio="trivy_${versione}_Linux-64bit.tar.gz"
|
||||
indirizzo="https://github.com/aquasecurity/trivy/releases/download/v${versione}/${archivio}"
|
||||
sha256="c6e65abddb348e25f10549df887045629cf28cc72453cd1c63acb717316b3f3f"
|
||||
;;
|
||||
*)
|
||||
echo "Strumento sconosciuto: «$nome» (gitleaks o trivy)." >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
piattaforma="$(uname -s)-$(uname -m)"
|
||||
if [[ "$piattaforma" != "Linux-x86_64" ]]; then
|
||||
echo "Gli archivi fissati qui sono per Linux x86_64, non per $piattaforma." >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if [[ -x "$cartella/$nome" ]] && [[ -f "$cartella/$nome.sha256" ]] && [[ "$(cat "$cartella/$nome.sha256")" == "$sha256" ]]; then
|
||||
echo "== $nome $versione già installato in $cartella"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
temporanea="$(mktemp -d)"
|
||||
trap 'rm -rf "$temporanea"' EXIT
|
||||
echo "== $nome $versione"
|
||||
curl -fsSL --retry 3 --retry-delay 5 --max-time 600 -o "$temporanea/$archivio" "$indirizzo"
|
||||
if ! echo "$sha256 $temporanea/$archivio" | sha256sum -c --quiet -; then
|
||||
echo "L'impronta SHA-256 di $archivio non è quella attesa: $nome non si installa." >&2
|
||||
exit 1
|
||||
fi
|
||||
mkdir -p "$cartella"
|
||||
tar -xzf "$temporanea/$archivio" -C "$cartella" "$nome"
|
||||
chmod 0755 "$cartella/$nome"
|
||||
echo "$sha256" > "$cartella/$nome.sha256"
|
||||
"$cartella/$nome" --version | head -n 1 || true
|
||||
@@ -0,0 +1,82 @@
|
||||
"use strict";
|
||||
// Chooses the tags to remove from Gitea's container registry (pulizia-docker.sh, mode «completa»). It only reads the
|
||||
// files it is given: no network, no writes, so it is tested with a JSON file.
|
||||
//
|
||||
// node versioni-registro.js <how many to keep> <page.json>...
|
||||
// node versioni-registro.js senza-etichetta <page.json>...
|
||||
//
|
||||
// Each file is a page of the answer of GET /api/v1/packages/{owner}/container/febe of Gitea 28: a list of versions with
|
||||
// «type», «name», «version» and «created_at» (an empty page may be «[]» or «null»). Only the versions of the container
|
||||
// package «febe» count, and a version found in two pages counts once. Both forms print, oldest first and one per line,
|
||||
// «version<TAB>created».
|
||||
//
|
||||
// With a number N: the sha-<7 to 40 hex digits> tags beyond the N newest by creation date. Everything else always
|
||||
// stays: main, latest, the X.Y.Z releases (X.Y.Z-rc.N too), the digests (sha256:…), any other tag and a sha- tag
|
||||
// without a date that can be read.
|
||||
//
|
||||
// With «senza-etichetta»: the untagged versions, sha256:<64 hex digits>. They are the manifests of an image index,
|
||||
// which Gitea keeps as versions of their own with the configuration and the layers; nothing here removes them (Gitea
|
||||
// cannot be asked through this API whether a tag still uses one), the cleanup only says how many there are.
|
||||
//
|
||||
// If a file is not a JSON list it exits with 2 and prints nothing: when in doubt nothing is removed.
|
||||
// Messages are in Italian, like every message of the CI.
|
||||
const fs = require("fs");
|
||||
|
||||
const [mode, ...pages] = process.argv.slice(2);
|
||||
const untagged = mode === "senza-etichetta";
|
||||
if (!(untagged || /^[0-9]+$/.test(mode || "")) || pages.length === 0) {
|
||||
console.error("Uso: node versioni-registro.js <quante tenere> | senza-etichetta <pagina.json>...");
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const shaTag = /^sha-[0-9a-f]{7,40}$/;
|
||||
const digest = /^sha256:[0-9a-f]{64}$/;
|
||||
const versions = new Map();
|
||||
for (const file of pages) {
|
||||
let page;
|
||||
try {
|
||||
page = JSON.parse(fs.readFileSync(file, "utf8").replace(/^/, ""));
|
||||
} catch (error) {
|
||||
console.error(`${file}: ${error.message}`);
|
||||
process.exit(2);
|
||||
}
|
||||
if (page === null) {
|
||||
continue;
|
||||
}
|
||||
if (!Array.isArray(page)) {
|
||||
console.error(`${file}: non è un elenco di versioni`);
|
||||
process.exit(2);
|
||||
}
|
||||
for (const version of page) {
|
||||
if (version && version.type === "container" && version.name === "febe" && typeof version.version === "string") {
|
||||
versions.set(version.version, version);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const dated = (version) => ({
|
||||
name: version.version,
|
||||
created: String(version.created_at),
|
||||
time: Date.parse(version.created_at),
|
||||
id: Number(version.id) || 0,
|
||||
});
|
||||
|
||||
let chosen;
|
||||
if (untagged) {
|
||||
chosen = [...versions.values()]
|
||||
.filter((version) => digest.test(version.version))
|
||||
.map(dated)
|
||||
.sort((a, b) => (Number.isFinite(a.time) ? a.time : 0) - (Number.isFinite(b.time) ? b.time : 0) || a.id - b.id);
|
||||
} else {
|
||||
chosen = [...versions.values()]
|
||||
.filter((version) => shaTag.test(version.version))
|
||||
.map(dated)
|
||||
.filter((version) => Number.isFinite(version.time))
|
||||
.sort((a, b) => b.time - a.time || b.id - a.id)
|
||||
.slice(Number(mode))
|
||||
.reverse();
|
||||
}
|
||||
|
||||
for (const version of chosen) {
|
||||
process.stdout.write(`${version.name}\t${version.created}\n`);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
# Pulizia del lunedì (alle 4:17, ora del server di Gitea) e a mano (Actions ▸ pulizia ▸ Esegui) del demone Docker del
|
||||
# runner e del registro dei container. A mano, con «Solo prova» spuntato, elenca che cosa toglierebbe e non toglie
|
||||
# nulla: da lanciare prima della prima pulizia vera e dopo ogni cambio dello script.
|
||||
# Ogni esecuzione di verifica e di rilascio toglie già ciò che crea e, per tutti, le immagini senza nome e la cache di
|
||||
# costruzione penzolante non usata da 24 ore. Qui, dal 21 ottobre 2026 (decisione di Alberto: eliminare tutto ciò che
|
||||
# non serve più), si toglie anche ciò che non serve più a nessuno, di qualunque progetto (pulizia-docker.sh completa):
|
||||
# - i resti della CI di Febe: contenitori di prova fermi (etichetta febe.ci.prova e nome febe-prova-<esecuzione>, mai
|
||||
# le etichette febe.ci.* che un Febe vero eredita dall'immagine), nomi locali febe-ci:<esecuzione>, builder
|
||||
# febe-ci-<esecuzione>, l'immagine febe:ci del vecchio flusso;
|
||||
# - i resti di act_runner: contenitori fermi, volumi e reti GITEA-ACTIONS-TASK-… che nessun contenitore usa, più
|
||||
# vecchi di 90 minuti;
|
||||
# - le immagini che nessun contenitore usa, né acceso né fermo, create più di 24 ore fa (di un'immagine in uso Docker
|
||||
# toglie i nomi in più), e la cache di costruzione del demone non usata da 24 ore. Le immagini di base
|
||||
# (node:24-trixie, moby/buildkit, …) si riscaricano alla prima esecuzione che le chiede;
|
||||
# - con il segreto REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti; mai main, latest o X.Y.Z.
|
||||
# Mai system prune, container prune, volume prune o network prune; mai un contenitore, un volume o una rete che non sia
|
||||
# della CI. Un contenitore di prova ancora acceso si segnala e il lavoro diventa rosso; un rifiuto dell'API del
|
||||
# registro è solo un avviso. Dettagli in .gitea/scripts/pulizia-docker.sh e in docs/processo.md, «Pulizia».
|
||||
name: pulizia
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "17 4 * * 1"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
prova:
|
||||
description: "Solo prova: elenca che cosa toglierebbe e non toglie nulla"
|
||||
type: boolean
|
||||
required: false
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: pulizia
|
||||
cancel-in-progress: false
|
||||
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
|
||||
jobs:
|
||||
docker:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# Gitea 28 mette nell'evento la casella «prova» come testo, "true" o "false"; il lunedì l'evento non ha input e
|
||||
# la pulizia è quella vera. Un avvio con l'API passa il valore così com'è: qualunque altro («True», «1») ferma il
|
||||
# lavoro senza toccare nulla. Il token del registro va solo nell'ambiente di questo passo e non si stampa mai.
|
||||
- name: Pulizia completa del demone Docker e del registro
|
||||
env:
|
||||
PROVA: ${{ gitea.event.inputs.prova }}
|
||||
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||
GITEA_API: ${{ gitea.server_url }}/api/v1
|
||||
PROPRIETARIO: ${{ gitea.repository_owner }}
|
||||
run: |
|
||||
case "${PROVA:-}" in
|
||||
true) bash .gitea/scripts/pulizia-docker.sh completa --prova ;;
|
||||
"" | false) bash .gitea/scripts/pulizia-docker.sh completa ;;
|
||||
*)
|
||||
VALORE=$(printf '%s' "$PROVA" | tr -c 'A-Za-z0-9' '_' | cut -c 1-20)
|
||||
echo "::error::La casella «prova» vale true o false, non «$VALORE»: non tolgo nulla."
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -3,9 +3,12 @@
|
||||
# e tutte le prove passano. Senza prove verdi non si costruisce né si rilascia nulla;
|
||||
# 2. windows: Febe.exe in un file solo, il programma di installazione NSIS e lo zip portabile (installer/costruisci.sh,
|
||||
# gira su Linux);
|
||||
# 3. immagine: l'immagine Docker (le prove girano anche dentro la build), pubblicata sul registro dei container di
|
||||
# Gitea come <registro>/<proprietario>/febe:X.Y.Z e :latest (solo per le versioni senza trattino). Il lavoro dice
|
||||
# se l'ha pubblicata;
|
||||
# 3. immagine: dopo l'installatore, l'immagine Docker (le prove girano anche dentro la build), provata senza rete e
|
||||
# scansionata con Trivy come nella verifica (una CRITICAL con correzione ferma tutto), poi pubblicata sul registro
|
||||
# dei container di Gitea come <registro>/<proprietario>/febe:X.Y.Z e :latest (solo per le versioni senza
|
||||
# trattino). Il lavoro dice se l'ha pubblicata, e alla fine toglie sempre immagini, contenitori, cache e builder
|
||||
# dell'esecuzione, poi le immagini senza nome e la cache di costruzione penzolante non usata da 24 ore di tutti i
|
||||
# progetti del demone;
|
||||
# 4. release: solo dopo le prove, l'installatore e l'immagine. Crea la release (o la completa, se esiste già) con
|
||||
# installatore, zip portabile, modello Unraid e l'archivio per Docker Compose (compose.yml con il profilo seccomp
|
||||
# accanto); le note dicono dove sta l'immagine, o che non è stata pubblicata.
|
||||
@@ -29,6 +32,7 @@ on:
|
||||
jobs:
|
||||
prove:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
@@ -60,6 +64,7 @@ jobs:
|
||||
windows:
|
||||
runs-on: ubuntu-latest
|
||||
needs: prove
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
@@ -89,7 +94,14 @@ jobs:
|
||||
|
||||
immagine:
|
||||
runs-on: ubuntu-latest
|
||||
needs: prove
|
||||
# Dopo l'installatore: :X.Y.Z e :latest escono solo se anche la release potrà uscire.
|
||||
needs: [prove, windows]
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
FLUSSO: rilascio
|
||||
ESECUZIONE: ${{ gitea.run_id }}
|
||||
BUILDER: febe-ci-${{ gitea.run_id }}
|
||||
PROVA: febe-ci:${{ gitea.run_id }}
|
||||
outputs:
|
||||
immagine: ${{ steps.nome.outputs.immagine }}
|
||||
pubblicata: ${{ steps.pubblicazione.outputs.pubblicata }}
|
||||
@@ -97,6 +109,12 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# Ciò che un'esecuzione interrotta non ha potuto togliere, e un tentativo precedente di questa stessa esecuzione.
|
||||
- name: Resti di esecuzioni interrotte
|
||||
run: |
|
||||
bash .gitea/scripts/pulizia-docker.sh residui 90
|
||||
bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE"
|
||||
|
||||
- name: Versione, registro e nome dell'immagine
|
||||
id: nome
|
||||
run: |
|
||||
@@ -105,6 +123,9 @@ jobs:
|
||||
[ -n "$REGISTRY" ] || REGISTRY=$(echo "${{ gitea.server_url }}" | sed -E 's#^https?://##; s#/.*$##')
|
||||
OWNER=$(echo "${{ gitea.repository_owner }}" | tr '[:upper:]' '[:lower:]')
|
||||
echo "VERSION=$V" >> "$GITHUB_ENV"
|
||||
echo "VERSIONE=$V" >> "$GITHUB_ENV"
|
||||
echo "GIT_COMMIT=${GITHUB_SHA::12}" >> "$GITHUB_ENV"
|
||||
echo "ARCHIVIO=${RUNNER_TEMP:-/tmp}/febe-$ESECUZIONE.tar" >> "$GITHUB_ENV"
|
||||
echo "REGISTRY=$REGISTRY" >> "$GITHUB_ENV"
|
||||
echo "IMAGE=$REGISTRY/$OWNER/febe" >> "$GITHUB_ENV"
|
||||
echo "registro=$REGISTRY" >> "$GITHUB_OUTPUT"
|
||||
@@ -113,19 +134,32 @@ jobs:
|
||||
# Un builder buildx proprio, che sa che il registro di casa risponde in HTTP.
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
name: febe-ci-${{ gitea.run_id }}
|
||||
driver: docker-container
|
||||
buildkitd-config-inline: |
|
||||
[registry."${{ steps.nome.outputs.registro }}"]
|
||||
http = true
|
||||
insecure = true
|
||||
|
||||
# Gli stessi argomenti ed etichette della pubblicazione (costruisci-immagine.sh): quella esce dalla cache di questa.
|
||||
- name: Costruzione dell'immagine (le prove girano dentro la build)
|
||||
run: |
|
||||
docker buildx build -f docker/Dockerfile \
|
||||
--build-arg VERSION="$VERSION" \
|
||||
--build-arg GIT_COMMIT="${GITHUB_SHA::12}" \
|
||||
-t "$IMAGE:$VERSION" --load .
|
||||
docker run --rm --entrypoint /usr/bin/chromium "$IMAGE:$VERSION" --version
|
||||
bash .gitea/scripts/costruisci-immagine.sh archivio "$ARCHIVIO" "$PROVA"
|
||||
docker load -i "$ARCHIVIO"
|
||||
|
||||
- name: Prova del contenitore, senza rete
|
||||
run: bash .gitea/scripts/prova-immagine.sh "$PROVA" "$ESECUZIONE"
|
||||
|
||||
- name: Vulnerabilità dell'immagine (Trivy)
|
||||
run: bash .gitea/scripts/scansione-immagine.sh "$ARCHIVIO" out/sicurezza
|
||||
|
||||
- name: Rapporto di Trivy
|
||||
if: ${{ !cancelled() }}
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: sicurezza-immagine
|
||||
path: out/sicurezza/trivy.json
|
||||
if-no-files-found: ignore
|
||||
|
||||
- name: Segreto per il registro
|
||||
id: segreto
|
||||
@@ -156,16 +190,13 @@ jobs:
|
||||
AUTH=$(printf '%s:%s' "$UTENTE" "$TOKEN" | base64 -w0)
|
||||
jq --arg r "$REGISTRY" --arg a "$AUTH" '.auths[$r].auth = $a' "$CONFIG/config.json" > "$CONFIG/config.json.nuovo"
|
||||
mv "$CONFIG/config.json.nuovo" "$CONFIG/config.json"
|
||||
TAGS="-t $IMAGE:$VERSION"
|
||||
NOMI="$IMAGE:$VERSION"
|
||||
case "$VERSION" in
|
||||
*-*) echo "Versione di anteprima: :latest non si sposta." ;;
|
||||
*) TAGS="$TAGS -t $IMAGE:latest" ;;
|
||||
*) NOMI="$NOMI $IMAGE:latest" ;;
|
||||
esac
|
||||
# La stessa costruzione di prima (dalla cache del builder), questa volta spinta sul registro.
|
||||
docker buildx build -f docker/Dockerfile \
|
||||
--build-arg VERSION="$VERSION" \
|
||||
--build-arg GIT_COMMIT="${GITHUB_SHA::12}" \
|
||||
$TAGS --push .
|
||||
# La stessa costruzione di prima (dalla cache del builder), questa volta spinta sul registro da buildx.
|
||||
bash .gitea/scripts/costruisci-immagine.sh pubblica $NOMI
|
||||
echo "pubblicata=si" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Credenziali tolte
|
||||
@@ -176,12 +207,22 @@ jobs:
|
||||
jq --arg r "$REGISTRY" 'if .auths then .auths |= del(.[$r]) else . end' "$CONFIG" > "$CONFIG.nuovo" && mv "$CONFIG.nuovo" "$CONFIG"
|
||||
fi
|
||||
|
||||
- name: Pulizia (sempre)
|
||||
if: always()
|
||||
run: |
|
||||
if [ -n "${ARCHIVIO:-}" ]; then rm -f "$ARCHIVIO"; fi
|
||||
bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE"
|
||||
# Poi, per tutti i progetti del demone, ciò che nessuno usa: immagini senza nome e cache di costruzione
|
||||
# penzolante non usata da 24 ore. Non fa mai fallire il lavoro.
|
||||
bash .gitea/scripts/pulizia-docker.sh penzolanti || echo "::warning::La pulizia di ciò che nessuno usa non è riuscita."
|
||||
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
# Le prove sono verdi, l'installatore c'è e l'immagine si è costruita: pubblicata, o non pubblicata per la sola
|
||||
# mancanza del segreto (il lavoro «immagine» lo dice e le note lo riportano). Se la costruzione o la spinta sul
|
||||
# registro falliscono, non esce nessuna release.
|
||||
# mancanza del segreto (il lavoro «immagine» lo dice e le note lo riportano). Se la costruzione, la prova del
|
||||
# contenitore, la scansione o la spinta sul registro falliscono, non esce nessuna release.
|
||||
needs: [prove, windows, immagine]
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
|
||||
+286
-28
@@ -1,18 +1,155 @@
|
||||
# Verifica a ogni push e a ogni pull request: compilazione con gli avvisi come errori
|
||||
# (compreso Febe.Desktop, che si compila anche da Linux) e tutte le prove.
|
||||
# Le prove che richiedono Chromium e Xvfb si saltano da sole se il runner non li ha.
|
||||
# Verifica: a ogni push su qualunque ramo (i tag li prende rilascio.yml) e a mano (Actions ▸ verifica ▸ Esegui).
|
||||
# I suoi quattro lavori sono i controlli richiesti per unire in main (docs/processo.md):
|
||||
# controlli sintassi degli script, flussi senza tabulazioni, segni di conflitto, versione, progetti della
|
||||
# soluzione, JSON; segreti in tutta la storia con gitleaks (versione e impronta fissate);
|
||||
# prove compilazione di tutta la soluzione con gli avvisi come errori e tutte le prove di tests/Febe.Tests
|
||||
# (mai «dotnet test» sulla soluzione intera: tests/Febe.Tests.Windows gira solo su Windows) con
|
||||
# Chromium, Xvfb, ffmpeg, NSIS e Node veri in un contenitore Debian 13: nessuna prova deve saltarsi.
|
||||
# Il mondo sintetico del sito di prova ha il seme 13 e, per la categoria SitoDiProva, anche il seme di
|
||||
# questa esecuzione, scritto nel registro per rifare un errore;
|
||||
# installatore Febe-Setup-<versione>-ci.<numero>.exe e lo zip portabile, artefatti per 14 giorni;
|
||||
# immagine dopo l'installatore: l'immagine Docker costruita con buildx, provata senza rete (parte, salute,
|
||||
# Chromium, it_IT) e scansionata con Trivy (si ferma per una CRITICAL con correzione); solo dopo un push
|
||||
# su main la pubblica come :main e :sha-<7 caratteri> (:latest resta al rilascio). Alla fine, sempre,
|
||||
# toglie immagini, contenitori, cache e builder di questa esecuzione, poi le immagini senza nome e la
|
||||
# cache di costruzione penzolante non usata da 24 ore di tutti i progetti del demone.
|
||||
#
|
||||
# Runner: act_runner con l'etichetta ubuntu-latest.
|
||||
# Niente «pull_request»: in Gitea una richiesta di unione mostra lo stato del suo ultimo commit, che il push del ramo
|
||||
# ha già verificato; pull_request rifarebbe tutto sullo stesso commit (refs/pull/N/head) sull'unico runner.
|
||||
# Runner: act_runner con l'etichetta ubuntu-latest, un lavoro alla volta. I lavori parlano con il demone Docker del
|
||||
# server, lo stesso di Encelado, Mimante e degli altri progetti: niente montaggi della cartella del lavoro in altri
|
||||
# contenitori (sul server i percorsi sono diversi); le immagini passano come archivi e contesti di costruzione.
|
||||
# Che cosa di Gitea 28 si usa e perché: docs/decisioni.md (20 ottobre 2026) e docs/processo.md.
|
||||
name: verifica
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, febe-v1]
|
||||
pull_request:
|
||||
branches: ["**"]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
seme:
|
||||
description: "Seme del mondo sintetico per la seconda passata delle prove (vuoto: 1000 più il numero dell'esecuzione)"
|
||||
required: false
|
||||
default: ""
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Su un ramo conta l'ultimo push: l'esecuzione precedente si annulla. Su main ogni commit ha il suo gruppo, così ogni
|
||||
# unione arriva fino in fondo e pubblica la sua :sha-. L'evento fa parte del gruppo: un'esecuzione a mano non annulla
|
||||
# mai quella di un push, che è l'unica a scrivere gli stati del commit richiesti per unire (un lavoro annullato lascia
|
||||
# lo stato «failure», e workflow_dispatch non ne scrive).
|
||||
concurrency:
|
||||
group: verifica-${{ gitea.event_name }}-${{ gitea.ref }}${{ gitea.ref == 'refs/heads/main' && format('-{0}', gitea.sha) || '' }}
|
||||
cancel-in-progress: ${{ gitea.ref != 'refs/heads/main' }}
|
||||
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
|
||||
env:
|
||||
DOTNET_NOLOGO: "1"
|
||||
DOTNET_CLI_TELEMETRY_OPTOUT: "1"
|
||||
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: "1"
|
||||
|
||||
jobs:
|
||||
prove:
|
||||
controlli:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
# Tutta la storia: gitleaks legge ogni commit da cui discende quello verificato.
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Script, flussi, conflitti, versione, soluzione e JSON
|
||||
run: bash .gitea/scripts/controlli.sh
|
||||
|
||||
- name: Segreti in tutta la storia (gitleaks)
|
||||
run: bash .gitea/scripts/segreti.sh out/sicurezza
|
||||
|
||||
- name: Rapporto di gitleaks (segreti oscurati)
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: rapporto-gitleaks
|
||||
path: out/sicurezza/gitleaks.json
|
||||
retention-days: 14
|
||||
if-no-files-found: ignore
|
||||
|
||||
prove:
|
||||
needs: controlli
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
# Debian 13 con Node 24: Chromium vero della distribuzione, come nell'immagine di Febe (su Ubuntu è uno snap), e
|
||||
# Node per le azioni e per la prova della pagina di accesso.
|
||||
# Memoria condivisa più ampia dei 64 MB predefiniti: le prove dell'interfaccia usano un Chromium senza finestra.
|
||||
container:
|
||||
image: node:24-trixie
|
||||
options: --shm-size=1g
|
||||
env:
|
||||
FEBE_CHROMIUM: /usr/bin/chromium
|
||||
SEME_RICHIESTO: ${{ gitea.event.inputs.seme }}
|
||||
NUMERO: ${{ gitea.run_number }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# Prima di tutto, così un seme chiesto a mano e sbagliato ferma subito il lavoro.
|
||||
- name: Semi del mondo sintetico
|
||||
id: semi
|
||||
run: |
|
||||
seme="${SEME_RICHIESTO:-}"
|
||||
[ -n "$seme" ] || seme=$((1000 + ${NUMERO:-0}))
|
||||
if ! [[ "$seme" =~ ^-?[0-9]{1,9}$ ]]; then
|
||||
echo "Seme non valido: «$seme» (serve un intero di al massimo nove cifre)." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "seme=$seme" >> "$GITHUB_OUTPUT"
|
||||
echo "Mondo sintetico: seme 13 per tutte le prove, seme $seme per la seconda passata (categoria SitoDiProva)."
|
||||
echo "Per rifarla: FEBE_SEME_PROVA=$seme dotnet test tests/Febe.Tests --filter \"TestCategory=SitoDiProva\""
|
||||
|
||||
- name: Chromium, Xvfb, ffmpeg, NSIS e lingua italiana
|
||||
run: bash .gitea/scripts/ambiente-prove.sh
|
||||
|
||||
- uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: "10.0.x"
|
||||
|
||||
- name: Compilazione di tutta la soluzione (avvisi = errori)
|
||||
run: dotnet build Febe.slnx -c Release -nologo -warnaserror
|
||||
|
||||
- name: Prove, seme 13
|
||||
run: >-
|
||||
dotnet test tests/Febe.Tests -c Release --no-build --nologo
|
||||
--logger "trx;LogFileName=prove-seme-13.trx" --results-directory out/prove
|
||||
|
||||
- name: Prove del sito di prova, seme dell'esecuzione
|
||||
if: ${{ !cancelled() && steps.semi.outputs.seme != '' }}
|
||||
env:
|
||||
FEBE_SEME_PROVA: ${{ steps.semi.outputs.seme }}
|
||||
run: >-
|
||||
dotnet test tests/Febe.Tests -c Release --no-build --nologo --filter "TestCategory=SitoDiProva"
|
||||
--logger "trx;LogFileName=prove-seme-$FEBE_SEME_PROVA.trx" --results-directory out/prove
|
||||
|
||||
- name: Riepilogo delle prove
|
||||
if: ${{ !cancelled() }}
|
||||
run: bash .gitea/scripts/riepilogo-prove.sh out/prove 0
|
||||
|
||||
- name: Risultati delle prove
|
||||
if: ${{ !cancelled() }}
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: risultati-prove
|
||||
path: out/prove/*.trx
|
||||
retention-days: 14
|
||||
if-no-files-found: warn
|
||||
|
||||
installatore:
|
||||
needs: prove
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
NUMERO: ${{ gitea.run_number }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
@@ -20,37 +157,158 @@ jobs:
|
||||
with:
|
||||
dotnet-version: "10.0.x"
|
||||
|
||||
- name: Compilazione (avvisi = errori)
|
||||
run: dotnet build Febe.slnx -c Release -nologo -warnaserror
|
||||
- name: NSIS e zip
|
||||
run: |
|
||||
SUDO=""; [ "$(id -u)" = 0 ] || SUDO=sudo
|
||||
$SUDO apt-get update -qq
|
||||
$SUDO apt-get install -y -qq nsis zip > /dev/null
|
||||
|
||||
- name: Prove
|
||||
run: >-
|
||||
dotnet test tests/Febe.Tests -c Release --no-build --nologo
|
||||
--logger "trx;LogFileName=prove.trx" --results-directory out/prove
|
||||
- name: Febe.exe, programma di installazione e zip portabile (versione di prova)
|
||||
run: |
|
||||
V=$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' Directory.Build.props | head -n 1)
|
||||
echo "Versione di questa esecuzione: $V-ci.$NUMERO"
|
||||
bash installer/costruisci.sh "$V-ci.$NUMERO"
|
||||
|
||||
- name: Risultati
|
||||
if: always()
|
||||
- name: Artefatti per Windows
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: risultati-prove
|
||||
path: out/prove/*.trx
|
||||
if-no-files-found: ignore
|
||||
name: windows
|
||||
path: |
|
||||
out/Febe-Setup-*.exe
|
||||
out/Febe-*-portabile.zip
|
||||
retention-days: 14
|
||||
if-no-files-found: error
|
||||
|
||||
# Dopo l'installatore, non solo dopo le prove: :main e :sha- escono solo da un commit con tutta la verifica verde.
|
||||
# Sull'unico runner i lavori vanno comunque uno alla volta, quindi la durata non cambia.
|
||||
immagine:
|
||||
needs: [prove, installatore]
|
||||
runs-on: ubuntu-latest
|
||||
needs: prove
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
FLUSSO: verifica
|
||||
ESECUZIONE: ${{ gitea.run_id }}
|
||||
NUMERO: ${{ gitea.run_number }}
|
||||
BUILDER: febe-ci-${{ gitea.run_id }}
|
||||
PROVA: febe-ci:${{ gitea.run_id }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Costruzione dell'immagine Docker (senza pubblicarla; le prove girano anche dentro la build)
|
||||
# Ciò che un'esecuzione interrotta (annullata, scaduta) non ha potuto togliere, e un tentativo precedente di
|
||||
# questa stessa esecuzione.
|
||||
- name: Resti di esecuzioni interrotte
|
||||
run: |
|
||||
docker version
|
||||
docker build -f docker/Dockerfile \
|
||||
--build-arg VERSION=ci \
|
||||
--build-arg GIT_COMMIT="${GITHUB_SHA::12}" \
|
||||
-t febe:ci .
|
||||
bash .gitea/scripts/pulizia-docker.sh residui 90
|
||||
bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE"
|
||||
|
||||
- name: L'immagine parte e mostra la pagina di errore senza password
|
||||
# Registro: la variabile REGISTRY delle Actions, se c'è, altrimenti l'host dell'indirizzo del server (ROOT_URL).
|
||||
- name: Versione, registro e nomi
|
||||
id: nome
|
||||
env:
|
||||
REGISTRO_SCELTO: ${{ vars.REGISTRY }}
|
||||
SERVER: ${{ gitea.server_url }}
|
||||
PROPRIETARIO: ${{ gitea.repository_owner }}
|
||||
run: |
|
||||
docker run --rm --entrypoint /usr/bin/chromium febe:ci --version
|
||||
docker run --rm --entrypoint sh febe:ci -c 'locale -a | grep -i it_IT && ls /etc/chromium/policies/managed/'
|
||||
V=$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' Directory.Build.props | head -n 1)
|
||||
REGISTRY="$REGISTRO_SCELTO"
|
||||
[ -n "$REGISTRY" ] || REGISTRY=$(echo "$SERVER" | sed -E 's#^https?://##; s#/.*$##')
|
||||
OWNER=$(echo "$PROPRIETARIO" | tr '[:upper:]' '[:lower:]')
|
||||
{
|
||||
echo "VERSIONE=$V-ci.$NUMERO"
|
||||
echo "GIT_COMMIT=${GITHUB_SHA::12}"
|
||||
echo "REGISTRY=$REGISTRY"
|
||||
echo "IMAGE=$REGISTRY/$OWNER/febe"
|
||||
echo "ARCHIVIO=${RUNNER_TEMP:-/tmp}/febe-$ESECUZIONE.tar"
|
||||
} >> "$GITHUB_ENV"
|
||||
echo "registro=$REGISTRY" >> "$GITHUB_OUTPUT"
|
||||
echo "Immagine $V-ci.$NUMERO del commit ${GITHUB_SHA::12}, provata come $PROVA; registro $REGISTRY/$OWNER/febe"
|
||||
|
||||
# Un builder buildx di questa esecuzione (con la sua cache), che sa che il registro di casa risponde in HTTP.
|
||||
- name: Builder buildx dell'esecuzione
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
name: febe-ci-${{ gitea.run_id }}
|
||||
driver: docker-container
|
||||
buildkitd-config-inline: |
|
||||
[registry."${{ steps.nome.outputs.registro }}"]
|
||||
http = true
|
||||
insecure = true
|
||||
|
||||
- name: Costruzione dell'immagine (dentro girano compilazione e prove)
|
||||
run: |
|
||||
bash .gitea/scripts/costruisci-immagine.sh archivio "$ARCHIVIO" "$PROVA"
|
||||
docker load -i "$ARCHIVIO"
|
||||
|
||||
- name: Prova del contenitore, senza rete
|
||||
run: bash .gitea/scripts/prova-immagine.sh "$PROVA" "$ESECUZIONE"
|
||||
|
||||
- name: Vulnerabilità dell'immagine (Trivy)
|
||||
run: bash .gitea/scripts/scansione-immagine.sh "$ARCHIVIO" out/sicurezza
|
||||
|
||||
- name: Rapporto di Trivy
|
||||
if: ${{ !cancelled() }}
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: sicurezza-immagine
|
||||
path: out/sicurezza/trivy.json
|
||||
retention-days: 14
|
||||
if-no-files-found: ignore
|
||||
|
||||
- name: Pubblicare?
|
||||
id: segreto
|
||||
env:
|
||||
TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||
EVENTO: ${{ gitea.event_name }}
|
||||
RIFERIMENTO: ${{ gitea.ref }}
|
||||
run: |
|
||||
if [ "$EVENTO" != push ] || [ "$RIFERIMENTO" != refs/heads/main ]; then
|
||||
echo "Si pubblica solo dopo un push su main: qui l'immagine è costruita, provata e scansionata."
|
||||
echo "presente=no" >> "$GITHUB_OUTPUT"
|
||||
elif [ -z "$TOKEN" ]; then
|
||||
echo "::warning::Manca il segreto REGISTRY_TOKEN: l'immagine di main è costruita, provata e scansionata ma non pubblicata. Aggiungilo (token con package: read and write) e rilancia la verifica di questo commit."
|
||||
echo "presente=no" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "presente=si" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Pubblicazione come :main e :sha-<commit>
|
||||
if: steps.segreto.outputs.presente == 'si'
|
||||
env:
|
||||
TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||
UTENTE: ${{ gitea.actor }}
|
||||
run: |
|
||||
# Le credenziali vanno nella configurazione del client: buildx le passa al builder, il demone non c'entra (e
|
||||
# proverebbe HTTPS). Non si stampano mai.
|
||||
CONFIG="${DOCKER_CONFIG:-$HOME/.docker}"
|
||||
mkdir -p "$CONFIG"
|
||||
[ -s "$CONFIG/config.json" ] || echo '{}' > "$CONFIG/config.json"
|
||||
AUTH=$(printf '%s:%s' "$UTENTE" "$TOKEN" | base64 -w0)
|
||||
jq --arg r "$REGISTRY" --arg a "$AUTH" '.auths[$r].auth = $a' "$CONFIG/config.json" > "$CONFIG/config.json.nuovo"
|
||||
mv "$CONFIG/config.json.nuovo" "$CONFIG/config.json"
|
||||
NOMI=("$IMAGE:sha-${GITHUB_SHA::7}")
|
||||
# :main solo se main è ancora a questo commit: un'esecuzione arrivata in ritardo non lo riporta indietro.
|
||||
# Il passo gira con «bash -e -o pipefail»: senza «|| CIMA=""» un errore di ls-remote chiuderebbe il passo
|
||||
# prima dell'avviso, e non uscirebbe nemmeno la :sha-.
|
||||
CIMA=$(git ls-remote origin refs/heads/main 2> /dev/null | cut -f1) || CIMA=""
|
||||
if [ "$CIMA" = "$GITHUB_SHA" ]; then
|
||||
NOMI+=("$IMAGE:main")
|
||||
elif [ -z "$CIMA" ]; then
|
||||
echo "::warning::Non riesco a leggere la cima di main: si pubblica solo :sha-${GITHUB_SHA::7} e :main resta dov'è."
|
||||
else
|
||||
echo "main è già andato avanti (${CIMA::7}): si pubblica solo :sha-${GITHUB_SHA::7}."
|
||||
fi
|
||||
bash .gitea/scripts/costruisci-immagine.sh pubblica "${NOMI[@]}"
|
||||
|
||||
- name: Pulizia (sempre)
|
||||
if: always()
|
||||
run: |
|
||||
CONFIG="${DOCKER_CONFIG:-$HOME/.docker}/config.json"
|
||||
if [ -s "$CONFIG" ] && [ -n "${REGISTRY:-}" ]; then
|
||||
jq --arg r "$REGISTRY" 'if .auths then .auths |= del(.[$r]) else . end' "$CONFIG" > "$CONFIG.nuovo" \
|
||||
&& mv "$CONFIG.nuovo" "$CONFIG" || echo "::warning::Non riesco a togliere le credenziali da $CONFIG."
|
||||
fi
|
||||
if [ -n "${ARCHIVIO:-}" ]; then rm -f "$ARCHIVIO"; fi
|
||||
bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE"
|
||||
# Poi, per tutti i progetti del demone, ciò che nessuno usa: immagini senza nome e cache di costruzione
|
||||
# penzolante non usata da 24 ore. Non fa mai fallire il lavoro.
|
||||
bash .gitea/scripts/pulizia-docker.sh penzolanti || echo "::warning::La pulizia di ciò che nessuno usa non è riuscita."
|
||||
+2
-11
@@ -379,17 +379,6 @@ MigrationBackup/
|
||||
# Fody - auto-generated XML schema
|
||||
FodyWeavers.xsd
|
||||
|
||||
# VS Code files for those working on multiple tools
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
*.code-workspace
|
||||
|
||||
# Local History for Visual Studio Code
|
||||
.history/
|
||||
|
||||
# Windows Installer files from build outputs
|
||||
*.cab
|
||||
*.msi
|
||||
@@ -401,12 +390,14 @@ FodyWeavers.xsd
|
||||
*.sln.iml
|
||||
|
||||
# ---> VisualStudioCode
|
||||
# Della cartella .vscode entra nel repository solo la configurazione condivisa (guida: Sviluppo, «Da VS Code»).
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
!.vscode/*.code-snippets
|
||||
*.code-workspace
|
||||
|
||||
# Local History for Visual Studio Code
|
||||
.history/
|
||||
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"recommendations": ["ms-dotnettools.csdevkit", "ms-dotnettools.csharp"]
|
||||
}
|
||||
Vendored
+182
@@ -0,0 +1,182 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Febe per Windows · sito di prova",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "compila e avvia il sito di prova",
|
||||
"postDebugTask": "ferma il sito di prova",
|
||||
"program": "${workspaceFolder}/src/Febe.Desktop/bin/Debug/net10.0-windows/Febe.exe",
|
||||
"args": [
|
||||
"--dati",
|
||||
"${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\dati",
|
||||
"--libreria",
|
||||
"${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\libreria",
|
||||
"--sito-di-prova",
|
||||
"http://127.0.0.1:8481",
|
||||
"--accesso-di-prova",
|
||||
"--prima-sessione",
|
||||
"30",
|
||||
"--sviluppo"
|
||||
],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"console": "internalConsole",
|
||||
"logging": { "moduleLoad": false },
|
||||
"linux": { "preLaunchTask": "solo su Windows" },
|
||||
"osx": { "preLaunchTask": "solo su Windows" },
|
||||
"presentation": { "group": "1-windows", "order": 1 }
|
||||
},
|
||||
{
|
||||
"name": "Sito di prova + Febe per Windows",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "compila",
|
||||
"program": "${workspaceFolder}/tools/Febe.SitoDiProva/bin/Debug/net10.0/febe-sito-di-prova.dll",
|
||||
"args": ["--porta", "8481", "--porta-cdn", "8482"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"console": "internalConsole",
|
||||
"serverReadyAction": {
|
||||
"action": "startDebugging",
|
||||
"pattern": "Sito di prova: http://",
|
||||
"name": "Febe per Windows · contro il sito già avviato",
|
||||
"killOnServerStop": true
|
||||
},
|
||||
"checkForDevCert": false,
|
||||
"logging": { "moduleLoad": false },
|
||||
"linux": { "preLaunchTask": "solo su Windows" },
|
||||
"osx": { "preLaunchTask": "solo su Windows" },
|
||||
"presentation": { "group": "1-windows", "order": 2 }
|
||||
},
|
||||
{
|
||||
"name": "Febe per Windows · contro il sito già avviato",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/src/Febe.Desktop/bin/Debug/net10.0-windows/Febe.exe",
|
||||
"args": [
|
||||
"--dati",
|
||||
"${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\dati",
|
||||
"--libreria",
|
||||
"${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\libreria",
|
||||
"--sito-di-prova",
|
||||
"http://127.0.0.1:8481",
|
||||
"--accesso-di-prova",
|
||||
"--prima-sessione",
|
||||
"30",
|
||||
"--sviluppo"
|
||||
],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"console": "internalConsole",
|
||||
"logging": { "moduleLoad": false },
|
||||
"presentation": { "hidden": true }
|
||||
},
|
||||
{
|
||||
"name": "Febe Server · dimostrazione (--demo)",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "compila",
|
||||
"program": "${workspaceFolder}/src/Febe.Server/bin/Debug/net10.0/febe.dll",
|
||||
"args": ["--demo"],
|
||||
"env": { "FEBE_INTERFACCIA": "${workspaceFolder}/src/Febe.Web/wwwroot" },
|
||||
"windows": {
|
||||
"env": {
|
||||
"FEBE_INTERFACCIA": "${workspaceFolder}/src/Febe.Web/wwwroot",
|
||||
"TEMP": "${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\temporanei",
|
||||
"TMP": "${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\temporanei"
|
||||
}
|
||||
},
|
||||
"cwd": "${workspaceFolder}",
|
||||
"console": "internalConsole",
|
||||
"serverReadyAction": { "action": "openExternally", "pattern": "Apri (https?://\\S+)" },
|
||||
"checkForDevCert": false,
|
||||
"logging": { "moduleLoad": false },
|
||||
"presentation": { "group": "2-strumenti", "order": 1 }
|
||||
},
|
||||
{
|
||||
"name": "Sito di prova",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "compila",
|
||||
"program": "${workspaceFolder}/tools/Febe.SitoDiProva/bin/Debug/net10.0/febe-sito-di-prova.dll",
|
||||
"args": ["--porta", "8481", "--porta-cdn", "8482"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"console": "internalConsole",
|
||||
"logging": { "moduleLoad": false },
|
||||
"presentation": { "group": "2-strumenti", "order": 2 }
|
||||
},
|
||||
{
|
||||
"name": "Simulazione 30 giorni (prudente)",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "compila",
|
||||
"program": "${workspaceFolder}/src/Febe.Server/bin/Debug/net10.0/febe.dll",
|
||||
"args": ["--simula", "30g", "--profilo", "prudente"],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"console": "internalConsole",
|
||||
"logging": { "moduleLoad": false },
|
||||
"presentation": { "group": "2-strumenti", "order": 3 }
|
||||
},
|
||||
{
|
||||
"name": "Febe Server · sito di prova (solo Linux)",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "compila e avvia il sito di prova",
|
||||
"postDebugTask": "ferma il sito di prova",
|
||||
"program": "${workspaceFolder}/src/Febe.Server/bin/Debug/net10.0/febe.dll",
|
||||
"args": [
|
||||
"--dati",
|
||||
"${env:HOME}/FebeSviluppo/${workspaceFolderBasename}/dati",
|
||||
"--libreria",
|
||||
"${env:HOME}/FebeSviluppo/${workspaceFolderBasename}/libreria",
|
||||
"--importa",
|
||||
"${env:HOME}/FebeSviluppo/${workspaceFolderBasename}/importa",
|
||||
"--ascolta",
|
||||
"127.0.0.1",
|
||||
"--sito-di-prova",
|
||||
"http://127.0.0.1:8481",
|
||||
"--accesso-di-prova",
|
||||
"--prima-sessione",
|
||||
"30"
|
||||
],
|
||||
"env": {
|
||||
"FEBE_PASSWORD": "prova",
|
||||
"FEBE_INTERFACCIA": "${workspaceFolder}/src/Febe.Web/wwwroot"
|
||||
},
|
||||
"cwd": "${workspaceFolder}",
|
||||
"console": "internalConsole",
|
||||
"terminateChildProcesses": true,
|
||||
"serverReadyAction": {
|
||||
"action": "openExternally",
|
||||
"pattern": "Interfaccia sulla porta (\\d+)",
|
||||
"uriFormat": "http://127.0.0.1:%s/"
|
||||
},
|
||||
"checkForDevCert": false,
|
||||
"logging": { "moduleLoad": false },
|
||||
"windows": { "preLaunchTask": "solo su Linux", "postDebugTask": "", "args": ["--aiuto"] },
|
||||
"osx": { "preLaunchTask": "solo su Linux", "postDebugTask": "", "args": ["--aiuto"] },
|
||||
"presentation": { "group": "3-linux", "order": 1 }
|
||||
},
|
||||
{
|
||||
"name": "⚠ Febe per Windows · Instagram vero (dati veri)",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "${input:confermaInstagramVero}",
|
||||
"program": "${workspaceFolder}/src/Febe.Desktop/bin/Debug/net10.0-windows/Febe.exe",
|
||||
"args": [],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"console": "internalConsole",
|
||||
"logging": { "moduleLoad": false },
|
||||
"linux": { "preLaunchTask": "solo su Windows" },
|
||||
"osx": { "preLaunchTask": "solo su Windows" },
|
||||
"presentation": { "group": "9-instagram-vero", "order": 1 }
|
||||
}
|
||||
],
|
||||
"inputs": [
|
||||
{
|
||||
"id": "confermaInstagramVero",
|
||||
"type": "pickString",
|
||||
"description": "INSTAGRAM VERO con l'account e i dati veri di Alberto. Invio avvia, Esc annulla.",
|
||||
"options": [{ "label": "Sì, avvia Febe con Instagram vero", "value": "compila" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"dotnet.defaultSolution": "Febe.slnx"
|
||||
}
|
||||
Vendored
+202
@@ -0,0 +1,202 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "compila",
|
||||
"detail": "dotnet build Febe.slnx -warnaserror: tutta la soluzione, gli avvisi sono errori; con -tl:off -clp:ForceNoAlign ogni errore sta su una riga e finisce nel pannello Problemi",
|
||||
"type": "process",
|
||||
"command": "dotnet",
|
||||
"args": [
|
||||
"build",
|
||||
"${workspaceFolder}/Febe.slnx",
|
||||
"-warnaserror",
|
||||
"-nologo",
|
||||
"-tl:off",
|
||||
"-clp:ForceNoAlign"
|
||||
],
|
||||
"group": { "kind": "build", "isDefault": true },
|
||||
"problemMatcher": "$msCompile",
|
||||
"presentation": { "clear": true }
|
||||
},
|
||||
{
|
||||
"label": "prove",
|
||||
"detail": "dotnet test tests/Febe.Tests: tutte le prove (senza Chromium e Xvfb quelle con il browser vero risultano saltate)",
|
||||
"type": "process",
|
||||
"command": "dotnet",
|
||||
"args": [
|
||||
"test",
|
||||
"${workspaceFolder}/tests/Febe.Tests",
|
||||
"-nologo",
|
||||
"-tl:off",
|
||||
"-clp:ForceNoAlign"
|
||||
],
|
||||
"group": { "kind": "test", "isDefault": true },
|
||||
"problemMatcher": "$msCompile",
|
||||
"presentation": { "clear": true }
|
||||
},
|
||||
{
|
||||
"label": "prove Windows",
|
||||
"detail": "dotnet test tests/Febe.Tests.Windows: le prove con WebView2 vero e un Dispatcher di WPF, solo su Windows (aprono per qualche istante la finestra «Browser di Febe»)",
|
||||
"type": "process",
|
||||
"command": "dotnet",
|
||||
"args": [
|
||||
"test",
|
||||
"${workspaceFolder}/tests/Febe.Tests.Windows",
|
||||
"-nologo",
|
||||
"-tl:off",
|
||||
"-clp:ForceNoAlign"
|
||||
],
|
||||
"group": "test",
|
||||
"problemMatcher": "$msCompile",
|
||||
"presentation": { "clear": true }
|
||||
},
|
||||
{
|
||||
"label": "prove con filtro",
|
||||
"detail": "dotnet test tests/Febe.Tests --filter …: una prova o un gruppo, per nome",
|
||||
"type": "process",
|
||||
"command": "dotnet",
|
||||
"args": [
|
||||
"test",
|
||||
"${workspaceFolder}/tests/Febe.Tests",
|
||||
"--filter",
|
||||
"${input:filtroDelleProve}",
|
||||
"-nologo",
|
||||
"-tl:off",
|
||||
"-clp:ForceNoAlign"
|
||||
],
|
||||
"group": "test",
|
||||
"problemMatcher": "$msCompile",
|
||||
"presentation": { "clear": true }
|
||||
},
|
||||
{
|
||||
"label": "sito di prova",
|
||||
"detail": "dotnet run --project tools/Febe.SitoDiProva: http://127.0.0.1:8481, CDN su 127.0.0.2:8482 (dove Febe lo cerca), dati sintetici del seme 13; in sfondo, pronto alla riga «Sito di prova: http://…»",
|
||||
"type": "process",
|
||||
"command": "dotnet",
|
||||
"args": [
|
||||
"run",
|
||||
"--project",
|
||||
"${workspaceFolder}/tools/Febe.SitoDiProva",
|
||||
"--",
|
||||
"--porta",
|
||||
"8481",
|
||||
"--porta-cdn",
|
||||
"8482"
|
||||
],
|
||||
"isBackground": true,
|
||||
"problemMatcher": {
|
||||
"base": "$msCompile",
|
||||
"owner": "sito-di-prova",
|
||||
"background": {
|
||||
"activeOnStart": true,
|
||||
"beginsPattern": "(?!)",
|
||||
"endsPattern": "^Sito di prova: http://"
|
||||
}
|
||||
},
|
||||
"presentation": { "panel": "dedicated", "clear": true }
|
||||
},
|
||||
{
|
||||
"label": "pubblica Febe.exe",
|
||||
"detail": "dotnet publish di Febe.Desktop in un file solo, come installer/costruisci.sh: out/pubblicazione/Febe.exe (Release, win-x64)",
|
||||
"type": "process",
|
||||
"command": "dotnet",
|
||||
"args": [
|
||||
"publish",
|
||||
"${workspaceFolder}/src/Febe.Desktop/Febe.Desktop.csproj",
|
||||
"-c",
|
||||
"Release",
|
||||
"-r",
|
||||
"win-x64",
|
||||
"--self-contained",
|
||||
"true",
|
||||
"-p:PublishSingleFile=true",
|
||||
"-p:IncludeNativeLibrariesForSelfExtract=true",
|
||||
"-p:EnableCompressionInSingleFile=true",
|
||||
"-nologo",
|
||||
"-o",
|
||||
"${workspaceFolder}/out/pubblicazione",
|
||||
"-tl:off",
|
||||
"-clp:ForceNoAlign"
|
||||
],
|
||||
"group": "build",
|
||||
"problemMatcher": "$msCompile",
|
||||
"presentation": { "clear": true }
|
||||
},
|
||||
{
|
||||
"label": "immagine Docker (serve Docker Desktop)",
|
||||
"detail": "docker build -f docker/Dockerfile -t febe .: compilazione e prove dentro l'immagine; serve un demone Docker avviato",
|
||||
"type": "process",
|
||||
"command": "docker",
|
||||
"args": ["build", "-f", "docker/Dockerfile", "-t", "febe", "."],
|
||||
"group": "build",
|
||||
"problemMatcher": [],
|
||||
"presentation": { "clear": true }
|
||||
},
|
||||
{
|
||||
"label": "compila e avvia il sito di prova",
|
||||
"detail": "Prima del debug contro il sito di prova: compila, poi avvia il sito (se è già aperto, lo usa così com'è)",
|
||||
"dependsOrder": "sequence",
|
||||
"dependsOn": ["compila", "sito di prova"],
|
||||
"hide": true,
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "ferma il sito di prova",
|
||||
"detail": "A fine debug: chiude l'attività «sito di prova» con l'input fermaIlSitoDiProva (comando workbench.action.tasks.terminate); echo stampa solo il suo argomento",
|
||||
"type": "process",
|
||||
"command": "echo",
|
||||
"args": ["${input:fermaIlSitoDiProva}"],
|
||||
"windows": { "command": "cmd.exe", "args": ["/d", "/c", "echo", "${input:fermaIlSitoDiProva}"] },
|
||||
"hide": true,
|
||||
"problemMatcher": [],
|
||||
"presentation": { "reveal": "never", "echo": false, "close": true }
|
||||
},
|
||||
{
|
||||
"label": "solo su Linux",
|
||||
"detail": "Ferma una configurazione che gira solo su Linux",
|
||||
"type": "process",
|
||||
"command": "sh",
|
||||
"args": [
|
||||
"-c",
|
||||
"echo 'Questa configurazione gira solo su Linux: il browser di Febe Server è Chromium su Xvfb.' >&2; exit 1"
|
||||
],
|
||||
"windows": {
|
||||
"command": "powershell.exe",
|
||||
"args": [
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-Command",
|
||||
"Write-Host 'Questa configurazione gira solo su Linux: il browser di Febe Server è Chromium su Xvfb. Su Windows usa «Febe per Windows · sito di prova».'; exit 1"
|
||||
]
|
||||
},
|
||||
"hide": true,
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "solo su Windows",
|
||||
"detail": "Ferma una configurazione che gira solo su Windows",
|
||||
"type": "process",
|
||||
"command": "sh",
|
||||
"args": [
|
||||
"-c",
|
||||
"echo 'Questa configurazione gira solo su Windows: Febe per Windows è WPF e WebView2. Su Linux usa «Febe Server · sito di prova (solo Linux)».' >&2; exit 1"
|
||||
],
|
||||
"hide": true,
|
||||
"problemMatcher": []
|
||||
}
|
||||
],
|
||||
"inputs": [
|
||||
{
|
||||
"id": "filtroDelleProve",
|
||||
"type": "promptString",
|
||||
"description": "Filtro di dotnet test, per esempio FullyQualifiedName~Febe.Tests.Docs (oppure solo una parte del nome: IconTests)",
|
||||
"default": "FullyQualifiedName~Febe.Tests.Docs"
|
||||
},
|
||||
{
|
||||
"id": "fermaIlSitoDiProva",
|
||||
"type": "command",
|
||||
"command": "workbench.action.tasks.terminate",
|
||||
"args": "sito di prova"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,5 +1,87 @@
|
||||
# Novità
|
||||
|
||||
## 0.1.2 (in preparazione)
|
||||
|
||||
Correzioni:
|
||||
|
||||
- **Febe legge le risposte vere di Instagram.** Instagram manda i dati di storie e raccolte come `text/javascript`, e
|
||||
Febe leggeva solo le risposte dichiarate JSON: le scartava tutte. Ora legge anche quelle (mai i file di script) e il
|
||||
JSON che la pagina porta con sé. I lettori sono scritti sulle risposte che il browser di Alberto ha ricevuto il 21
|
||||
ottobre, ripulite, e il vocabolario di Instagram è «confermato».
|
||||
- La mappa di Instagram ha le pagine viste nel traffico vero (home, profilo, post, storie, raccolte): girano giro dei
|
||||
seguiti, controllo del profilo, storico e post singolo. Storie, raccolte e schede Taggati e Reel aspettano i bersagli
|
||||
dei comandi, che si raccolgono con la nuova procedura «A bis» di `docs/prove-dal-vivo.md`.
|
||||
- Le risposte che non parlano di contenuti (promozioni, «storia vista», registri) non fermano più le ricette come
|
||||
«formato non riconosciuto».
|
||||
- Le ricette del profilo prendono intestazione, griglia e raccolte anche quando arrivano in risposte diverse, e uno
|
||||
storico non si chiude più per il «non ce n'è altro» di una risposta che parla d'altro. L'elenco dei seguiti non salva
|
||||
i profili suggeriti.
|
||||
- Il visualizzatore delle raccolte funziona anche se l'indirizzo non dice quale contenuto è a video, e si chiude
|
||||
sempre, anche dopo un errore imprevisto.
|
||||
- Una ricetta che la configurazione non lascia girare risulta «Da configurare»: non conta più come guasto, non viene
|
||||
sospesa e non si ripianifica. Al primo avvio con i file nuovi le ricette sospese per colpa dei file vecchi ripartono
|
||||
da sole, con una riga in Attività.
|
||||
- Barra laterale: dice «Collegato» quando il cookie di sessione c'è, anche se il nome dell'account non è ancora noto.
|
||||
- «Post singolo»: i controlli accodati per recuperare un indirizzo scaduto o completare una serie non vengono più
|
||||
annullati dalla coda prima di partire.
|
||||
|
||||
Sviluppo e qualità:
|
||||
|
||||
- `febe-sonda da-har`: un HAR esportato dal browser diventa campioni grezzi da ripulire con `ripulisci` e
|
||||
`verifica`; `tools/bersagli/raccogli-bersagli.js` raccoglie in sola lettura ruolo e nome dei comandi.
|
||||
- La ripulitura tiene `latest_reel_media` come data e mette un riempitivo neutro sotto le chiavi che sembrano segreti,
|
||||
così gitleaks non scambia i dati finti per segreti veri.
|
||||
|
||||
- Prove dell'interfaccia senza attese a tempo fisso (#8): le risposte in ritardo si trattengono finché la prova non le
|
||||
rilascia, e ciò che non deve succedere si controlla quando la pagina ha finito le sue richieste. Restano verdi anche
|
||||
con Chrome rallentato 20 volte.
|
||||
- **Pulizia della CI**: oltre a ciò che crea, la CI toglie ciò che non serve più a nessuno sul demone Docker del runner.
|
||||
Dopo ogni lavoro «immagine» se ne vanno le immagini senza nome e la cache di costruzione che nessuno usa da 24 ore.
|
||||
Ogni lunedì se ne vanno le immagini che nessun contenitore usa e la cache più vecchie di 24 ore, i resti dei lavori di
|
||||
act_runner e, con `REGISTRY_TOKEN`, le `:sha-` del registro oltre le 10 più recenti (mai `:main`, `:latest` o una
|
||||
versione). Non tocca mai un contenitore, un volume o una rete che non sia della CI. A mano, «Solo prova» elenca che
|
||||
cosa toglierebbe senza togliere nulla (`docs/processo.md`, «Pulizia»).
|
||||
- Immagine Docker: si pubblica come manifest semplice, senza attestazioni, così togliere un'etichetta dal registro ne
|
||||
libera davvero gli strati.
|
||||
|
||||
## 0.1.1
|
||||
|
||||
Versione correttiva: **Febe per Windows si collega**. Con la 0.1.0 il browser di Febe non diventava mai pronto e
|
||||
l'accesso a Instagram non poteva cominciare.
|
||||
|
||||
Correzioni:
|
||||
|
||||
- **Febe per Windows**: il browser di Febe parte al primo tentativo. Prima WebView2 partiva, ma subito dopo veniva
|
||||
toccato fuori dal suo thread; l'errore era scambiato per un avvio fallito, e il browser veniva chiuso e riavviato
|
||||
per sempre.
|
||||
- Febe per Windows: un «Scollega» premuto durante un nuovo tentativo di avvio poteva lasciare due browser nella finestra
|
||||
e la sessione sul disco. «Esci» non resta più fermo dietro un avvio di WebView2.
|
||||
- Collegamento: prima del primo giro il pannello dice «Collegato» e «Nome non ancora noto», non più «Collegato come @».
|
||||
- Storico: la fine dello storico di un account dà una sola riga negli Avvisi, con il testo intero. Lo storico si chiude
|
||||
anche se subito dopo l'ultima pagina arrivano un segnale, un'interruzione o il controllo del profilo: prima l'account
|
||||
restava «Storico in corso» per sempre.
|
||||
- Vista remota (Docker): aprirne una mentre un'altra la sostituisce, o mentre la pagina sta cambiando, non dà più «Il
|
||||
browser di Febe non risponde».
|
||||
- Libreria: al primo avvio poteva restare su «La libreria è ancora vuota» invece del benvenuto con «Collegati a
|
||||
Instagram», se lo stato del motore arrivava dopo quello della libreria. Ora aspetta di sapere se Febe è collegato.
|
||||
|
||||
Sviluppo e qualità:
|
||||
|
||||
- **CI a ogni push e a ogni unione** (`docs/processo.md`):
|
||||
- controlli e gitleaks;
|
||||
- tutte le prove con Chromium vero e dati sintetici, con un seme diverso a ogni esecuzione;
|
||||
- installatore per Windows;
|
||||
- immagine Docker provata senza rete e scansionata con Trivy.
|
||||
|
||||
Dopo ogni unione in `main` l'immagine esce come `:main` e `:sha-<commit>`. Ogni esecuzione toglie ciò che ha creato,
|
||||
e c'è una pulizia settimanale.
|
||||
- **Sviluppo da VS Code**: attività e configurazioni di debug in `.vscode/` (guida, «Sviluppo» ▸ «Da VS Code»).
|
||||
- Prove: `tests/Febe.Tests` verdi anche su Windows, e prove nuove con WebView2 vero in `tests/Febe.Tests.Windows`. Due
|
||||
prove che la CI ha fatto girare per la prima volta con Chromium vero fallivano a volte, e ora sono stabili: la vista
|
||||
remota durante un cambio di pagina (#3, un difetto del prodotto, corretto) e il pulsante Indietro con modifiche non
|
||||
salvate (#5, la prova passava per caso).
|
||||
- Sito di prova: `/benvenuto`, la pagina di accesso che Febe apre in sviluppo.
|
||||
|
||||
## 0.1.0
|
||||
|
||||
Prima versione, **anteprima**: il programma è completo e provato contro il sito di prova locale, ma non ha mai
|
||||
|
||||
@@ -10,6 +10,7 @@ All'inizio di ogni sessione leggi docs/stato.md.
|
||||
- Avviare in modalità dimostrativa: `dotnet run --project src/Febe.Server -- --demo`
|
||||
- Simulare il motore: `dotnet run --project src/Febe.Server -- --simula 30g --profilo prudente`
|
||||
- Immagine Docker: `docker build -f docker/Dockerfile -t febe .`
|
||||
- Da VS Code: attività e configurazioni di debug in `.vscode/` (guida: `docs/guida/Sviluppo.md`, «Da VS Code»); Febe per Windows di sviluppo tiene i dati in `%USERPROFILE%\FebeSviluppo\<cartella del checkout>`, mai in `%LOCALAPPDATA%\Febe`.
|
||||
|
||||
## Regole che non si discutono (specifica §2)
|
||||
1. IMPORTANTE: non contattare mai Instagram da prove, script o verifiche tue. Si usa solo tools/Febe.SitoDiProva. Le prove dal vivo le lancia Alberto.
|
||||
@@ -38,6 +39,11 @@ Conserva: tappa in corso, file modificati, controlli ancora da eseguire, domande
|
||||
|
||||
## Repository e rilascio
|
||||
- Repository: Gitea di casa, https://gitea.encke-hake.ts.net/Alby96/Febe (ramo main). Non è GitHub: niente strumenti GitHub.
|
||||
- CI in `.gitea/workflows/`: `verifica.yml` a ogni push e pull request, `rilascio.yml` a ogni tag `vX.Y.Z` (immagine Docker sul registro di Gitea, installatore Windows e release).
|
||||
- Processo (rami `<tipo>/<argomento>`, commit piccoli, una richiesta di unione per ramo, verifica verde per unire in main, commit di unione, rilasci, correzioni urgenti): docs/processo.md.
|
||||
- CI in `.gitea/workflows/`, script comuni in `.gitea/scripts/`:
|
||||
- `verifica.yml` a ogni push su qualunque ramo (non sui tag) e a mano, niente pull_request: controlli e gitleaks; compilazione di tutta la soluzione e tutte le prove di `tests/Febe.Tests` con Chromium, Xvfb, ffmpeg e NSIS veri in Debian, nessuna saltata, anche con il seme dell'esecuzione (`FEBE_SEME_PROVA`); installatore e zip `-ci.<numero>`; immagine provata senza rete e scansionata con Trivy. Dopo un push su main pubblica `:main` e `:sha-<commit>` (con il segreto `REGISTRY_TOKEN`; senza, un avviso).
|
||||
- `rilascio.yml` a ogni tag `vX.Y.Z`: immagine `:X.Y.Z` (e `:latest`) sul registro di Gitea, installatore Windows e release.
|
||||
- `pulizia.yml` ogni lunedì e a mano (con «Solo prova» elenca e non toglie nulla): resti della CI di Febe e di act_runner, immagini che nessun contenitore usa e cache di costruzione più vecchie di 24 ore, di tutti i progetti; con `REGISTRY_TOKEN` le `:sha-` oltre le 10 più recenti, mai `main`, `latest` o `X.Y.Z`. Mai contenitori, volumi o reti che non siano della CI, mai `system prune`. Ogni lavoro «immagine» toglie alla fine anche le immagini senza nome e la cache penzolante non usata da 24 ore.
|
||||
- Le prove nella CI passano solo da `tests/Febe.Tests`, mai `dotnet test` sulla soluzione intera.
|
||||
- La versione sta solo in `Directory.Build.props` (`<Version>`); il tag deve coincidere.
|
||||
- Guida per l'uso: wiki del repository (sorgenti in `docs/guida/`).
|
||||
@@ -1,7 +1,7 @@
|
||||
<Project>
|
||||
<!-- Proprietà comuni a tutti i progetti di Febe. La versione si cambia solo qui. -->
|
||||
<PropertyGroup>
|
||||
<Version>0.1.0</Version>
|
||||
<Version>0.1.1</Version>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<LangVersion>14</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
</Folder>
|
||||
<Folder Name="/tests/">
|
||||
<Project Path="tests/Febe.Tests/Febe.Tests.csproj" />
|
||||
<Project Path="tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/tools/">
|
||||
<Project Path="tools/Febe.Sonda/Febe.Sonda.csproj" />
|
||||
|
||||
@@ -6,7 +6,7 @@ Febe non costruisce richieste verso Instagram: usa un browser vero, in cui Alber
|
||||
|
||||
> Scaricare con un programma è contro le condizioni d'uso di Instagram. Febe va piano per ridurre il rischio per l'account, ma non può azzerarlo.
|
||||
|
||||
**Stato: versione 0.1.0, anteprima.** Il programma è completo e provato contro un sito di prova locale; prima di usarlo su Instagram serve la sonda di M0 (vedi [docs/stato.md](docs/stato.md)).
|
||||
**Stato: versione 0.1.1, anteprima.** Il programma è completo e provato contro un sito di prova locale. Dal 25 ottobre 2026 legge le risposte vere di Instagram (lettori scritti su risposte reali ripulite); storie e raccolte aspettano i bersagli dei comandi, e nulla è ancora stato provato dal vivo (vedi [docs/stato.md](docs/stato.md)).
|
||||
|
||||
## Documenti
|
||||
|
||||
|
||||
+20
-13
@@ -7,7 +7,10 @@
|
||||
# -t 192.168.30.23:3000/alby96/febe:0.1.0 .
|
||||
#
|
||||
# Stadi:
|
||||
# build restore e compilazione di tutta la soluzione con gli avvisi come errori;
|
||||
# progetti solo i file che il restore legge (soluzione, props, progetti), trovati da soli: un progetto nuovo in
|
||||
# Febe.slnx non chiede di cambiare questo file;
|
||||
# build restore (in cache finché quei file non cambiano) e compilazione di tutta la soluzione con gli avvisi come
|
||||
# errori;
|
||||
# test tutte le prove: un'immagine con prove rosse non esiste. Qui non ci sono Chromium né Xvfb, quindi le prove
|
||||
# con il browser vero risultano «inconcludenti» (saltate) e girano solo dove ci sono (CI, sviluppo);
|
||||
# publish Febe.Server autosufficiente per linux-x64: nell'immagine non serve il runtime .NET;
|
||||
@@ -18,24 +21,25 @@
|
||||
|
||||
ARG DOTNET_VERSION=10.0
|
||||
|
||||
# ─────────────────────────────────────────────────────────────── progetti
|
||||
# I file che il restore legge, ciascuno nella sua cartella. Questo stadio rigira a ogni modifica, ma il suo risultato
|
||||
# cambia solo con loro: la copia nello stadio build, e quindi il restore, restano in cache (BuildKit confronta il
|
||||
# contenuto). Un progetto aggiunto a Febe.slnx (per esempio tests/Febe.Tests.Windows) arriva qui senza toccare il file.
|
||||
FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} AS progetti
|
||||
WORKDIR /src
|
||||
COPY . .
|
||||
RUN mkdir -p /progetti \
|
||||
&& find . -type f \( -name '*.slnx' -o -name '*.csproj' -o -name 'Directory.*.props' -o -name 'Directory.*.targets' \
|
||||
-o -iname 'nuget.config' -o -name 'global.json' \) -exec cp --parents '{}' /progetti/ ';' \
|
||||
&& test -f /progetti/Febe.slnx
|
||||
|
||||
# ─────────────────────────────────────────────────────────────── build
|
||||
FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} AS build
|
||||
WORKDIR /src
|
||||
ENV DOTNET_NOLOGO=1 DOTNET_CLI_TELEMETRY_OPTOUT=1
|
||||
|
||||
# Prima i file di progetto: il restore resta in cache finché non cambiano.
|
||||
COPY Directory.Build.props Directory.Packages.props Febe.slnx ./
|
||||
COPY src/Febe.Core/Febe.Core.csproj src/Febe.Core/
|
||||
COPY src/Febe.Data/Febe.Data.csproj src/Febe.Data/
|
||||
COPY src/Febe.Browser/Febe.Browser.csproj src/Febe.Browser/
|
||||
COPY src/Febe.Web/Febe.Web.csproj src/Febe.Web/
|
||||
COPY src/Febe.App/Febe.App.csproj src/Febe.App/
|
||||
COPY src/Febe.Server/Febe.Server.csproj src/Febe.Server/
|
||||
COPY src/Febe.Desktop.Core/Febe.Desktop.Core.csproj src/Febe.Desktop.Core/
|
||||
COPY src/Febe.Desktop/Febe.Desktop.csproj src/Febe.Desktop/
|
||||
COPY tests/Febe.Tests/Febe.Tests.csproj tests/Febe.Tests/
|
||||
COPY tools/Febe.Sonda/Febe.Sonda.csproj tools/Febe.Sonda/
|
||||
COPY tools/Febe.SitoDiProva/Febe.SitoDiProva.csproj tools/Febe.SitoDiProva/
|
||||
COPY --from=progetti /progetti/ ./
|
||||
RUN dotnet restore Febe.slnx \
|
||||
&& dotnet restore src/Febe.Server/Febe.Server.csproj -r linux-x64
|
||||
|
||||
@@ -73,8 +77,11 @@ LABEL org.opencontainers.image.title="Febe" \
|
||||
# Chromium della distribuzione con le sue lingue, il display virtuale, ffmpeg (miniature dei video importati), ICU e
|
||||
# le librerie del runtime .NET autosufficiente, caratteri di sistema con le emoji, certificati, fusi orari, la lingua
|
||||
# italiana generata, tini come processo 1 (raccoglie i processi di Chromium), setpriv (util-linux) per PUID/PGID.
|
||||
# Prima gli aggiornamenti di sicurezza della distribuzione già pubblicati, anche quelli arrivati dopo l'immagine di
|
||||
# base: la scansione della CI non deve trovare correzioni disponibili e non applicate.
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
RUN apt-get update \
|
||||
&& apt-get upgrade -y --no-install-recommends \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
chromium chromium-l10n \
|
||||
xvfb \
|
||||
|
||||
@@ -226,3 +226,90 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
||||
| 2026-10-13 | Prove dell'interfaccia in un Chromium senza finestra guidato col protocollo DevTools diretto (`UiBrowser`, solo 127.0.0.1), inconcludenti senza Chromium | Come `tools/schermate`; il client CDP di Febe accetta solo letture |
|
||||
| 2026-10-14 | Revisione avversaria di tutto il codice (7 aree, ogni rilievo verificato da un secondo revisore indipendente): 54 rilievi confermati e corretti con prove di regressione, 2 smentiti, 3 incerti corretti dove il rimedio era sicuro | §14, regola 14: resoconti onesti |
|
||||
| 2026-10-14 | Restano noti e accettati: «Tieni il più grande» scrive con il proprio SafeFileWriter e non passa dal lucchetto per account di `LibraryIngest` (un'importazione e uno scaricamento con gli stessi byte nello stesso istante potrebbero entrare entrambi); le prove d'interfaccia con browser vero aspettano fino a 30 s | Finestra rarissima, nessuna perdita di dati: al più un doppione esatto da togliere a mano |
|
||||
| 2026-10-20 | Il seme del mondo sintetico del sito di prova si sceglie con la variabile `FEBE_SEME_PROVA` (13 se manca), letta da `SyntheticSite` (`tests/Febe.Tests/Support`), l'unico modo in cui le prove avviano il sito; le classi che lo avviano stanno nella categoria `SitoDiProva`, e una prova controlla che nessuna lo avvii per altre vie o resti fuori dalla categoria. `SyntheticSiteSeedTests` controlla senza browser, per 300 semi, la forma del mondo su cui contano le prove d'insieme e i lettori sulle pagine servite | La CI rifà quelle prove con un seme diverso a ogni esecuzione, scritto nel registro, senza raddoppiare la durata di tutta la suite; senza la variabile non cambia nulla; un errore si rifà con lo stesso seme |
|
||||
| 2026-10-20 | Dockerfile: i file che il restore legge (soluzione, `Directory.*.props`, progetti) si trovano da soli in uno stadio `progetti` invece che da un elenco scritto a mano; lo stadio finale applica gli aggiornamenti della distribuzione (`apt-get upgrade`) prima di installare i pacchetti | Un progetto nuovo in `Febe.slnx` (come `tests/Febe.Tests.Windows`) non rompe più la costruzione dell'immagine e il restore resta in cache (BuildKit confronta il contenuto copiato); la scansione Trivy della CI non deve trovare correzioni di Debian già pubblicate ma non applicate perché l'immagine di base è più vecchia |
|
||||
| 2026-10-20 | Codice comune della CI in script di `.gitea/scripts/` (lanciati con `bash`), non in azioni composite locali | Uno script si prova con `bash -n` nel lavoro «controlli» e si lancia anche a mano; le azioni composite di act hanno comportamenti propri (ambiente, `if`, passi finali) che qui non si possono provare prima della prima esecuzione vera |
|
||||
| 2026-10-20 | Strumenti esterni della CI: solo gitleaks 8.30.1 e Trivy 0.75.0 (approvati da Alberto il 20 ottobre, solo nella CI), scaricati dalle release come binari e installati solo se l'impronta SHA-256 scritta in `strumento.sh` coincide (verificata sull'archivio, sul file `*_checksums.txt` e sull'impronta mostrata da GitHub); nessuna azione di terzi per eseguirli | `trivy-action` e `setup-trivy` furono compromesse a marzo 2026 (CVE-2026-33634, Trivy 0.69.4–0.69.6): un'etichetta si sposta, un'impronta no. Trivy 0.75.0 e non 0.76.0: almeno due settimane di vita prima di entrare nella CI |
|
||||
| 2026-10-20 | gitleaks su tutta la storia del commit verificato (`fetch-depth: 0`, ogni commit da cui discende; ogni ramo si controlla al suo push, così il rilievo di un ramo non blocca gli altri) con `--redact`; nessun `.gitleaks.toml` né elenco di eccezioni per ora: un'approssimazione locale delle 221 regole predefinite (le espressioni regolari pubblicate, applicate da uno script nostro: gitleaks non gira fuori dalla CI) non ha trovato rilievi veri, e i gettoni finti delle prove non hanno la forma completa che le regole cercano | Un falso allarme futuro si toglie con la sua impronta in `.gitleaksignore` e un commento accanto, mai disattivando una regola; un segreto vero si revoca prima di tutto (`docs/processo.md`) |
|
||||
| 2026-10-20 | Trivy sull'archivio dell'immagine provata (non dal demone): una vulnerabilità CRITICAL con correzione disponibile ferma il lavoro, le HIGH (e le CRITICAL senza correzione) si riportano nel registro e in `trivy.json` (artefatto di 14 giorni); eccezioni solo in `.trivyignore`, con motivo scritto e scadenza `exp:` | La regola chiesta da Alberto; scansionare l'archivio vuol dire scansionare proprio l'immagine provata, senza dipendere dal socket del demone |
|
||||
| 2026-10-20 | La prova del contenitore (`prova-immagine.sh`) gira sempre con `--network none`: Chromium, criteri, lingua, poi l'avvio come da guida (profilo seccomp, password casuale passata solo nell'ambiente del client) fino a «healthy», `febe --controllo-salute` e l'arresto entro 30 secondi | Regola 1: un'immagine appena costruita non deve poter raggiungere Instagram nemmeno per sbaglio; il controllo di salute passa dalla rete interna del contenitore |
|
||||
| 2026-10-20 | Le etichette `febe.ci.workflow`, `febe.ci.run`, `febe.ci.ref`, `febe.ci.commit` dell'immagine dicono solo da dove viene; `pulizia-docker.sh` sceglie che cosa togliere da segni che nessuna immagine porta: contenitori di prova con l'etichetta `febe.ci.prova=<esecuzione>` (messa solo da `docker run --label` in `prova-immagine.sh`) e il nome esatto `febe-prova-<esecuzione>`; immagini solo per il nome locale `febe-ci:<esecuzione>`, mai per identificativo né con `-f`; builder per nome esatto e immagine `moby/buildkit`. Alla fine di ogni lavoro tutto ciò dell'esecuzione; all'inizio del lavoro successivo e ogni settimana i resti più vecchi di 90 minuti, ma dei contenitori di prova solo quelli fermi (uno acceso si segnala); più le immagini senza nome oltre 72 ore. Mai `system prune`, `builder prune`, `volume prune`. `PipelineTests` fa girare la pulizia contro un client Docker finto con un Febe vero acceso e uno fermo | Docker copia le etichette dell'immagine in ogni contenitore: un Febe vero avviato da `:main`, `:X.Y.Z` o `:latest` sullo stesso demone porta `febe.ci.run`, e un rilascio rilanciato ha lo stesso numero di esecuzione dell'immagine pubblicata (rilievo bloccante della revisione). Il demone è lo stesso di Encelado, Mimante e degli altri progetti; un lavoro dura al massimo 60 minuti, quindi un resto di 90 minuti è orfano; i builder sono sempre accesi e la loro cache se ne va solo con il contenitore |
|
||||
| 2026-10-20 | `verifica` a ogni push su qualunque ramo (`branches: ["**"]`, quindi mai sui tag) e a mano (`workflow_dispatch`, con un seme facoltativo); niente `pull_request` | In Gitea i controlli di una richiesta di unione sono gli stati del suo ultimo commit, che il push del ramo ha già verificato; `pull_request` girerebbe sullo stesso commit (`refs/pull/N/head`, non un'unione di prova) e sull'unico runner raddoppierebbe tutto. Niente richieste da fork: un solo autore, rami nello stesso repository |
|
||||
| 2026-10-20 | Concorrenza di `verifica`: il gruppo comprende l'evento e il ramo; su un ramo l'esecuzione nuova annulla quella in corso dello stesso evento; su main ogni commit ha il suo gruppo e nessuna si annulla; `:main` si sposta solo se main è ancora a quel commit, e se la cima di main non si legge si pubblica solo `:sha-` con un avviso | Il runner fa un lavoro alla volta; ogni unione in main deve arrivare a pubblicare la sua `:sha-`, e un'esecuzione in ritardo non deve riportare indietro `:main`. Con l'evento nel gruppo un'esecuzione a mano non annulla quella del push: in Gitea un lavoro annullato lascia lo stato «failure» e `workflow_dispatch` non scrive stati, quindi la richiesta di unione resterebbe bloccata. Gitea 28 valuta le espressioni di `concurrency.group` e `cancel-in-progress` (`services/actions/concurrency.go`) |
|
||||
| 2026-10-20 | Lavoro «prove» nel contenitore `node:24-trixie` (Debian 13 con Node 24), con Chromium, Xvfb, ffmpeg, NSIS e la lingua italiana installati a ogni esecuzione; il riepilogo non ammette prove saltate; seconda passata della categoria `SitoDiProva` con il seme 1000 + numero dell'esecuzione, o quello chiesto a mano | Su Ubuntu Chromium è uno snap; le azioni JavaScript girano dentro il contenitore del lavoro e vogliono Node; un'immagine di CI costruita da noi non può fare da contenitore del lavoro, perché act_runner la scaricherebbe da un registro e quello di casa è in HTTP; nella CI una prova saltata vuol dire un ambiente rotto, non una prova superata |
|
||||
| 2026-10-20 | Installatore di ogni esecuzione con versione `<Version>-ci.<numero>` e immagine con etichetta `org.opencontainers.image.version` uguale; dopo ogni unione in main l'immagine va sul registro come `:main` e `:sha-<7 caratteri>`, mai `:latest`, che resta del rilascio | Decisione di Alberto del 20 ottobre; la versione di prova non si confonde con una versione rilasciata e `installer/costruisci.sh` la accetta già |
|
||||
| 2026-10-20 | Artefatti con `actions/upload-artifact@v3` e `retention-days: 14` (risultati delle prove, installatore e zip, rapporti di sicurezza) | La v4 rifiuta di girare dove il server non è github.com (prende Gitea per GHES) e la sua copia per Gitea sarebbe un'azione nuova, non approvata; il backend v3 di Gitea 28 rispetta `retentionDays` (`routers/api/actions/artifacts.go`) |
|
||||
| 2026-10-20 | `permissions: contents: read` in `verifica` e `pulizia`; i riepiloghi delle prove e di Trivy vanno nel registro e anche in `GITHUB_STEP_SUMMARY` | Gitea 28 applica `permissions` al gettone del lavoro (docs.gitea.com, «Actions job token permissions»), che così non può scrivere nel repository; i riepiloghi dei lavori esistono da Gitea 1.27 ma compaiono solo se il runner li carica, quindi il registro resta la fonte |
|
||||
| 2026-10-20 | Ciò che la CI usa di Gitea 28 e di act_runner: `concurrency` con espressioni, `timeout-minutes` dei lavori (lo applica il runner), `workflow_dispatch` con `inputs`, `schedule`, `defaults.run.shell`, `container` del lavoro, contesti `gitea.*`, `vars` e `secrets`; gli stati dei commit si chiamano «verifica / <lavoro> (push)» (`modules/actions/workflows.go`) e solo push, pull_request e release ne creano | Controllato sul codice di Gitea `release/v28` e su docs.gitea.com il 20 ottobre 2026; ciò che solo la prima esecuzione vera può provare è in `docs/processo.md` |
|
||||
| 2026-10-20 | Processo in `docs/processo.md`: rami `<tipo>/<argomento>` da `main`, commit piccoli in italiano, una richiesta di unione per ramo con il modello di `.gitea/` (comprese le 14 regole di §2), unione con commit di unione e ramo cancellato; `main` protetto con i quattro lavori di `verifica` come controlli richiesti e «blocca se indietro»; tag `v*` protetti; Alberto proprietario di tutto (`CODEOWNERS`) | Decisione di Alberto del 20 ottobre (processo da grande azienda); con il ramo aggiornato il commit di unione ha lo stesso contenuto del commit verificato, quindi in `main` entra solo codice provato. Le approvazioni richieste dipendono da chi apre le richieste (Gitea non conta quella dell'autore): domanda aperta per Alberto |
|
||||
| 2026-10-20 | Nella verifica il lavoro «immagine» viene dopo «prove» e «installatore» (`needs: [prove, installatore]`) | `:main` e `:sha-` devono uscire solo da un commit con tutta la verifica verde, come dice `docs/docker.md`; sull'unico runner i lavori vanno comunque uno alla volta, quindi la durata non cambia. Su un ramo, se l'installatore fallisce l'immagine si salta: la richiesta di unione è già bloccata dall'installatore |
|
||||
| 2026-10-20 | Anche nel rilascio il lavoro «immagine» viene dopo «prove» e «windows» (`needs: [prove, windows]`) | Come nella verifica: `:X.Y.Z` e `:latest` si pubblicano solo se anche la release potrà uscire; prima, con l'installatore rosso, l'immagine usciva senza release |
|
||||
| 2026-10-20 | Nuovo progetto di prove `tests/Febe.Tests.Windows` (`net10.0-windows`, WPF, solo MSTest e riferimenti ai progetti, nella soluzione): WebView2 vero su un thread STA con un `Dispatcher` di WPF vero, il sito di prova in processo; si compila anche da Linux (`EnableWindowsTargeting`), gira solo su Windows, senza runtime WebView2 è inconcludente | L'errore che bloccava Febe per Windows (14 e 19 ottobre) si vedeva solo con WebView2 vero e un thread dell'interfaccia vero: le prove su Linux con il finto `IWebView2DevTools` non potevano coglierlo |
|
||||
| 2026-10-20 | `WebView2Host` legge sul thread dell'interfaccia, durante l'avvio, i valori che servono altrove (versione di WebView2, numero del processo del browser) e li espone come valori semplici; nessun membro di un oggetto di WebView2 si legge fuori da quel thread | Causa dell'errore: `Version` leggeva `BrowserVersionString` dell'ambiente da un thread del pool, dopo `ConfigureAwait(false)`, e WebView2 lanciava `InvalidOperationException` |
|
||||
| 2026-10-20 | Nel ciclo di avvio di `WebView2Browser` si riprova solo l'eccezione dell'avvio stesso: stato e riga «Browser di Febe pronto» stanno fuori dal blocco dei tentativi | La riga del registro, dentro il `try`, trasformava ogni avvio riuscito in un avvio fallito: chiusura del WebView buono e nuovi tentativi per sempre |
|
||||
| 2026-10-20 | Avvio, ripartenza e arresto di `WebView2Host` uno alla volta (un `SemaphoreSlim` preso sul thread dell'interfaccia); l'arresto aspetta al più 30 s chi è in corso, poi chiude quello che c'è | Ognuno aspetta WebView2 sul thread dell'interfaccia e fra un'attesa e l'altra potevano intrecciarsi (per esempio una ripartenza dopo un arresto del processo e «Scollega»); l'uscita da Febe non deve restare appesa a un avvio che WebView2 non completa |
|
||||
| 2026-10-20 | Arresto del processo del browser: annunciato solo dopo che il gestore di `ProcessFailed` è tornato e solo per il WebView in uso (numero di generazione); se capita durante un avvio fa fallire quell'avvio; la ripartenza (e quella dopo un «Scollega» la cui ripartenza fallisce) usa gli stessi tentativi del primo avvio, un solo ciclo alla volta sul pool | Modello dei thread di WebView2: niente chiusure né ricreazioni dentro i suoi gestori. Prima: un solo tentativo, poi browser morto fino al riavvio di Febe; dopo «Scollega» restava fermo anche il motore, perché l'errore non era di cartella e `DisconnectAsync` non lo gestiva |
|
||||
| 2026-10-20 | `WebView2CdpSession.Attach` chiama i gestori di `Reconnected` uno per uno: l'errore di uno va nel registro e non esce da `Attach` (l'avviso resta sincrono) | `Attach` è dentro l'avvio del nuovo WebView: un'eccezione di chi ascolta avrebbe disfatto un avvio riuscito, ancora e ancora |
|
||||
| 2026-10-20 | La finestra dell'interfaccia apre gli indirizzi esterni nel browser predefinito dopo che il gestore di WebView2 è tornato (in coda sul dispatcher) | La shell di Windows può far girare un ciclo di messaggi suo e WebView2 non regge di essere richiamato dentro i propri gestori |
|
||||
| 2026-10-20 | Le prove per Windows hanno un `CompressedClock` e un fuso «mezzogiorno» propri, copie di quelli della suite per Linux; `Febe.Desktop` concede gli `internal` a `Febe.Tests.Windows` e `WebView2Host` espone la sua finestra come `internal` (da leggere sul thread dell'interfaccia) | Un progetto di prove non può dipendere dall'altro; la finestra serve alle prove del primo piano e del fuori vista |
|
||||
| 2026-10-20 | Un solo WebView alla volta in `WebView2Host`: l'avvio, dentro la sezione esclusiva, non fa nulla se un WebView è già collegato, chiude prima i resti di uno morto, e se fallisce chiude da sé ciò che ha creato (il ciclo dei tentativi non chiude più niente da fuori); la ripartenza dopo un arresto del processo usa lo stesso avvio; chiudere un WebView ne cambia la generazione, così i suoi eventi tardivi non contano | Revisione del ramo: un «Scollega» durante i tentativi del primo avvio faceva partire il browser, poi il tentativo in attesa ne apriva un secondo nella stessa finestra senza chiudere il primo. Il processo orfano teneva il profilo: il «Scollega» dopo aspettava 20 s e non cancellava la sessione di Instagram, l'uscita aspettava 15 s a vuoto |
|
||||
| 2026-10-20 | All'uscita il primo avvio e il ciclo di ripartenza di `WebView2Browser` smettono subito di aspettare WebView2: `WebView2Host.StartAsync` onora il suo token (un avvio non ancora cominciato non comincia, uno in corso finisce da sé e l'arresto chiude ciò che lascia, anche se arriva dopo i 30 s); `WebView2Browser.DisposeAsync` aspetta il ciclo al più 30 s. «Scollega», una volta cominciato, va fino in fondo e resta coperto dai 30 s dell'arresto | Revisione del ramo: il limite di 30 s copriva solo un «Scollega» in corso. `FebeApp` aspetta `RunAsync` prima di chiudere il browser, e `RunAsync` e il ciclo aspettavano WebView2 senza limite; interrompere «Scollega» a metà lascerebbe invece fermo il motore |
|
||||
| 2026-10-20 | Collegamento, pannello «collegato» senza nome dell'account (subito dopo «Ho finito», prima del primo giro): titolo «Collegato» e sotto «Nome non ancora noto», come il riquadro di stato | Provando a mano su Windows la pagina diceva «Collegato come @»; il mockup 10 mostra solo il caso con il nome |
|
||||
| 2026-10-20 | Prove portabili fra Linux e Windows: i percorsi attesi si calcolano come li calcola il sistema (`Path.GetFullPath` per il profilo del browser e per `/importa`, `LibraryLayout.ToStored` per il percorso mostrato in Docker) invece di essere scritti alla Linux | Febe per Windows gira su Windows e le prove devono passare dove gira il prodotto; su Linux il testo atteso è identico a prima, quindi lì non cambia nulla |
|
||||
| 2026-10-20 | Prova della cartella dei dati su una condivisione: su Linux il montaggio cifs iniettato come prima, su Windows un percorso UNC verso `febe-prova.invalid`, riconosciuto dalla sola forma; il controllo «niente scritto nella cartella dei dati» resta solo su Linux | Stesso comportamento sui due sistemi, ognuno con il suo modo di riconoscere la rete (su Windows non c'è tabella dei montaggi); guardare dentro un UNC vorrebbe dire interrogare la rete, e un nome `.invalid` (RFC 6761) non risponde mai |
|
||||
| 2026-10-20 | `TestLibrary.LoseDatabaseAsync`: su Windows un'eliminazione che trova il file in uso da un altro programma (`0x80070020`) si ripete ogni 50 ms, per al più 5 s | Su Windows un file aperto da un altro programma non si elimina. Su questo PC, con Defender attivo, succedeva circa 3 volte su 40 esecuzioni di `Febe.Tests.Library`: il file era libero dopo 6–17 ms e il Restart Manager non vedeva nessun processo che lo tenesse, quindi non è un collegamento di Febe rimasto aperto. Su Linux eliminare un file aperto riesce sempre e non si ripete nulla |
|
||||
| 2026-10-20 | Prova di `costruisci.sh`: su Windows prima Git Bash (accanto a git sul PATH, poi nelle cartelle del suo installatore), altrimenti un bash sul PATH che non sia il lanciatore di WSL (`System32\bash.exe`, alias in `WindowsApps`); senza bash la prova è inconcludente invece di passare in silenzio | Dal PATH di PowerShell il primo bash è il lanciatore di WSL, che senza distribuzione fallisce («execvpe(/bin/bash) failed») e non vede lo script col percorso di Windows; su Linux si usa come prima il primo bash sul PATH |
|
||||
| 2026-10-20 | «Storico completato» lo scrive solo il motore (`SessionComposer.FinishBackfillAsync`: @nome, post in libreria, che cosa succede ora); la ricetta Storico non scrive più una riga sua. Il motore chiude lo storico ogni volta che il cammino è arrivato in fondo (`BackfillFinished`), anche se poi la corsa finisce con un segnale o un'interruzione | Due righe nella cronologia e in «Avvisi» per lo stesso storico (@marta.prova, 14:31): la corta della ricetta e quella del motore. La notifica era già una sola e col testo del motore, perché la riga della ricetta (`CollectionWriter.EventAsync`) non passa da `EngineEvents` e `AlertService` non la vede. Con un segnale subito dopo l'ultima pagina l'account restava «Storico in corso» per sempre |
|
||||
| 2026-10-20 | Anche lo storico completato dal controllo del profilo (profilo tutto nella prima pagina) lo chiude il motore, con la sua riga (`BackfillFinished` del controllo, solo per un account «Storico in corso»). A inizio sessione il motore chiude gli account rimasti «Storico in corso» con lo storico già completato; la fase dello Storico rilegge gli account invece di usare quelli di inizio sessione | Con due account «Storico in corso» quello piccolo restava così per sempre, senza riga né avviso: dalla sessione dopo non era più candidato dello Storico. Rileggere gli account evita una seconda riga quando lo Storico della stessa sessione sceglierebbe proprio quello appena chiuso |
|
||||
| 2026-10-20 | Quando chiude uno storico, il motore toglie subito dalla coda il suo «Storico» e, se l'account resta in pausa, gli altri compiti pianificati; non rimette in coda la corsa dello Storico arrivata in fondo e poi fermata da un segnale | La Coda mostrava fino alla sessione dopo (dopo una verifica, fino a «Riprendi») uno Storico da fare per un account già «Aggiornato» o «In pausa». I comandi di Alberto restano |
|
||||
| 2026-10-20 | Vista remota: `Page.startScreencast` si manda di nuovo solo se Chromium risponde -32000 «Not attached to an active page», con pause da 100 a 500 ms e per al più 5 s di orologio vero (`ScreencastSession.InactivePageBudget`); collegamento chiuso, nessuna risposta o qualunque altro rifiuto danno subito «Il browser di Febe non risponde». Nessun comando CDP nuovo | Issue #3. Dal `ReadyToCommitNavigation` di una navigazione con un nuovo RenderFrameHost fino al suo commit, DevTools punta già al documento nuovo non ancora attivo e i comandi di pagina gestiti dal browser falliscono così (`page_handler.cc`, `AssureTopLevelActiveFrame`); con RenderDocument, attivo in Chromium, vale per ogni navigazione, anche verso la pagina di riposo. Ci cadevano la vista aperta insieme alla pagina di accesso, dopo un riposo del motore o durante una sessione |
|
||||
| 2026-10-20 | Sostituzione di una vista remota: `BrowserRemoteViewHost.OpenAsync` tiene un permesso «Alberto usa il browser» di passaggio dalla fine della vista vecchia all'avvio della nuova; l'ospite della vista usa `IFebeBrowser` invece di `ChromiumBrowser` | Fra le due viste i permessi scendevano a zero: il motore si svegliava e riportava la pagina a riposo proprio mentre la vista nuova avviava i fotogrammi (il fallimento della CI, issue #3), e avrebbe potuto cominciare una sessione. L'interfaccia permette di provarlo senza browser |
|
||||
| 2026-10-20 | Prova con Chromium vero del ritentativo della vista remota (`RemoteViewDuringNavigationTests`): una pagina del sito locale delle prove (`/occupata`) tiene occupato il renderer per 2 s, così la navigazione verso un'altra pagina dello stesso sito resta fra «ready to commit» e il commit e `Page.startScreencast` ci cade apposta; se in nessun giro Chromium rifiuta il primo avvio, la prova risulta inconcludente e non superata | Revisione dell'issue #3: TwoViews… prova solo il permesso di passaggio, e una vista aperta dall'ospite dopo l'inizio di una navigazione non incontra il rifiuto (`Page.getFrameTree` risponde solo dopo il commit). Con Chrome 155 sulla macchina di sviluppo, in un esperimento a parte con lo stesso codice di Febe, il rifiuto è arrivato in 18 giri su 18 e la vista si è aperta al sesto tentativo; con il testo atteso cambiato la stessa sequenza fallisce. Verso about:blank da una pagina del sito il commit avviene in un altro renderer: quel caso non serve allo scopo |
|
||||
| 2026-10-20 | VS Code: configurazione condivisa in `.vscode/` (`launch.json`, `tasks.json`, `extensions.json`, `settings.json` con la sola `dotnet.defaultSolution`); debug con il tipo `coreclr` dell'estensione C#, che non legge `launchSettings.json` (lo cerca in `{cwd}/Properties`, e `cwd` è la radice del repository) | Il tipo `dotnet` del C# Dev Kit accetta solo il progetto e un profilo di `launchSettings.json`: niente argomenti, variabili d'ambiente, attività prima e dopo, `serverReadyAction`. Con `coreclr` tutto sta in un file solo |
|
||||
| 2026-10-20 | Febe per Windows di sviluppo da VS Code con `--dati %USERPROFILE%\FebeSviluppo\<checkout>\dati` e `--libreria %USERPROFILE%\FebeSviluppo\<checkout>\libreria` (`${workspaceFolderBasename}`: una cartella per checkout); il debug avvia `Febe.exe`, non `dotnet Febe.dll` | Mai la cartella vera `%LOCALAPPDATA%\Febe`; fuori dal repository perché profilo del browser e libreria crescono e non devono finire in un commit. Una per checkout perché il blocco contro le istanze doppie dipende dalla cartella dei dati (F5 in un secondo worktree mostrava il Febe del primo e finiva subito) e un database migrato da un ramo più nuovo non si apre con una versione più vecchia. Con `Febe.exe` il percorso del processo è quello di Febe e non di `dotnet.exe` (lo usa l'avvio con il computer) |
|
||||
| 2026-10-20 | Attività di compilazione, prove e pubblicazione con `-tl:off -clp:ForceNoAlign` oltre al comando della guida | Registro classico, come nella CI: ogni errore su una riga sola, senza le righe che il terminal logger ridisegna nel terminale; `$msCompile` lo porta nel pannello Problemi (provato con un errore voluto) |
|
||||
| 2026-10-20 | Il sito di prova è un'attività di sfondo, pronta alla riga «Sito di prova: http://» (`activeOnStart`, con `beginsPattern` «(?!)», che non trova mai nulla); a fine debug la ferma un input che esegue `workbench.action.tasks.terminate` | VS Code legge `activeOnStart`, non `activeBegins`: senza, il debug aspettava il sito per sempre. Con «(?!)» nessuna riga successiva rimette l'attività «al lavoro». VS Code non ha un'attività che ne chiuda un'altra: un input di tipo `command` è l'unico modo per farlo da `postDebugTask`. Limite noto: se il sito non è più in corso, il comando apre l'elenco delle attività da terminare (la guida dice di premere Esc) |
|
||||
| 2026-10-20 | «Sito di prova + Febe per Windows» non è un compound: la configurazione del sito avvia Febe con `serverReadyAction` (`startDebugging`, `killOnServerStop`) quando il sito scrive di essere pronto | Un compound avvia tutto insieme e senza ordine: Febe con `--accesso-di-prova` poteva cercare il sito prima che ascoltasse |
|
||||
| 2026-10-20 | Le configurazioni legate a un sistema (Febe per Windows; Febe Server con il sito di prova, cioè Chromium su Xvfb) sugli altri sistemi si fermano con un messaggio (attività «solo su Windows» e «solo su Linux»; il server riceve anche solo `--aiuto`) | VS Code non sa nascondere una configurazione per sistema operativo: le proprietà `windows`, `linux` e `osx` contano solo all'avvio |
|
||||
| 2026-10-20 | «⚠ Febe per Windows · Instagram vero (dati veri)» chiede conferma prima di compilare e partire (una scelta sola, Esc annulla) | Regola 1: le prove dal vivo le lancia Alberto; un F5 distratto non deve aprire Instagram con l'account e il database veri |
|
||||
| 2026-10-20 | Tutte le configurazioni di debug usano la Console di debug (`internalConsole`), mai il terminale integrato (Febe per Windows non ha una console: il suo registro resta nella cartella dei dati, `registro`); le attività sono di tipo `process`, senza shell | Il terminale integrato e le attività `shell` caricano il profilo di PowerShell: su questo PC il profilo attiva l'ambiente conda di Pinokio, che mette in testa al `PATH` e in `DOTNET_ROOT` un .NET senza SDK e con il solo runtime 8. Lì `dotnet build` non trova l'SDK e Febe (net10.0) non parte («You must install or update .NET»), né come `febe.dll` né come `febe.exe`. Console di debug e attività `process` usano l'ambiente di VS Code |
|
||||
| 2026-10-20 | La dimostrazione da VS Code serve l'interfaccia dai sorgenti (`FEBE_INTERFACCIA`), apre da sola il browser (`serverReadyAction`) e su Windows tiene la cartella temporanea in `%USERPROFILE%\FebeSviluppo\<checkout>\temporanei` (`TEMP`, `TMP`) | Si modifica `wwwroot` e si ricarica senza ricompilare. Fermata dal debugger, la dimostrazione non può cancellare la sua cartella (una trentina di MB): così resta fra i dati di sviluppo invece di accumularsi in `%TEMP%` |
|
||||
| 2026-10-20 | I file di `.vscode/` sono JSON rigido, senza commenti: le spiegazioni stanno nella guida (pagina «Sviluppo», «Da VS Code»), nei campi `detail` delle attività e in queste righe | Il controllo «File JSON» della CI legge ogni `*.json` tracciato con `JSON.parse`, e con i commenti `//` il lavoro «controlli» falliva a ogni push dopo l'unione. VS Code legge anche il JSON rigido, così il ramo non dipende da come la CI tratta i commenti |
|
||||
| 2026-10-20 | `src/Febe.Desktop/Properties/launchSettings.json` con un solo profilo, «Sito di prova»: `--dati` e `--libreria` in `%USERPROFILE%\FebeSviluppo\comune`, `--sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 30 --sviluppo` | `dotnet run --project src/Febe.Desktop` e i comandi del C# Dev Kit (▷ «Debug project associated with this file», «Start New Instance», «C#: …») avviavano Febe senza opzioni: Instagram vero e dati veri, senza la conferma della configurazione ⚠. `dotnet run` e il Dev Kit leggono quel profilo ed espandono `%USERPROFILE%` (provato); se un altro strumento non lo facesse, Febe rifiuta il percorso non completo e non parte. Una cartella comune perché il file non conosce il checkout. Instagram vero dal terminale: `dotnet run --project src/Febe.Desktop --no-launch-profile` |
|
||||
| 2026-10-20 | Le prove dell'interfaccia aspettano lo stato finale di una pagina, mai uno di passaggio come il mosaico vuoto che la Libreria mette sullo schermo prima della risposta di `/api/library/days` | Issue #5: `TheBackButtonAsksBeforeLosingUnsavedChanges` aspettava `.vuoto-pagina` o `.mosaico`, ma una libreria vuota con Febe non collegato finisce sul benvenuto; la prova passava solo se il primo controllo cadeva nei circa 10 ms in cui c'è il mosaico vuoto (provato con Chrome: con il primo controllo ritardato di 5 ms o più falliva sempre) |
|
||||
| 2026-10-20 | Lo stato vuoto della Libreria senza filtri segue il collegamento finché è sullo schermo: se il motore risponde dopo la libreria, al suo arrivo compare il benvenuto del primo avvio; quando Febe si collega, il benvenuto lascia il posto alla libreria vuota. Si ridisegna solo quando cambia tipo. La prova trattiene `/api/engine` fino a un suo segnale e toglie `EventSource` (l'interfaccia ripiega su `/api/engine`) | Prima la scelta si faceva una volta sola, alla risposta della libreria: con il motore in ritardo il primo avvio mostrava la libreria vuota invece dei due pulsanti di §10.3, e ci restava (provato con Chrome trattenendo `/api/engine`). Un segnale invece di un ritardo: l'ordine delle risposte non dipende dalla velocità della macchina |
|
||||
| 2026-10-20 | Finché lo stato del motore non è noto, la Libreria vuota senza filtri non mostra nessuno stato vuoto: un riquadro vuoto con `aria-busy`, come il mosaico mentre carica, che il primo stato del motore sostituisce con il benvenuto o con «La libreria è ancora vuota». La prova aspetta quel riquadro, il conteggio «0 …» e nessuno stato vuoto | Senza il motore non si sa se è il primo avvio: «La libreria è ancora vuota» mostrata nell'attesa era falsa al primo avvio e poi lasciava il posto al benvenuto con un salto della pagina (rilievo della revisione). Il riquadro della barra laterale dice già «Caricamento…» finché il motore non risponde, e il motore arriva comunque: il flusso `/api/eventi` lo manda appena si apre e, senza flusso, l'interfaccia lo richiede a intervalli |
|
||||
| 2026-10-21 | Nelle prove dell'interfaccia una risposta è in ritardo perché la prova la trattiene, mai per un tempo fisso. `UiBrowser.Requests` (al posto di `FetchDelays`) trattiene le richieste scelte finché la prova non le rilascia (`__hold`, `__release`: il rilascio chiude la regola, così lo stesso indirizzo si può trattenere di nuovo, e trattenerlo due volte insieme è un errore), conta quelle partite (`__started`) e quelle finite (`__done`: dopo la continuazione della pagina e, se lo legge, dopo il corpo della risposta) e registra ogni richiesta della pagina (`__asked`). La prova aspetta che la pagina abbia chiesto, fa ciò che deve venire prima (lasciare la pagina, cambiare filtro), rilascia e controlla quando la pagina ne ha finito | Issue #8: `APageLeftWhileLoadingLeavesNothingBehind` tornava alla Libreria 200 ms dopo `navigate('/attivita')`. Su una macchina lenta Attività non aveva ancora caricato `activity.js` e `day-strip.js`: la pagina era lasciata prima di montarsi, `/api/alerts` non partiva mai e l'attesa scadeva dopo 30 s. Con Chrome rallentato 20 volte (`Emulation.setCPUThrottlingRate`, solo in locale) falliva 3 volte su 3 con lo stesso messaggio e la stessa riga, e in 4 giri su 5 i due moduli arrivavano dopo il ritorno alla Libreria (fra 212 e 549 ms). `ABrowserPageLeftWhileLoadingNeverTakesTheBrowser` aveva una finestra di 150 ms, e la sua regola di 600 ms tratteneva anche un `begin` mandato per errore, che arrivava al server dopo il controllo: con la pagina Browser rotta apposta la prova passava. Una regola rilasciata restava e valeva per prima: un secondo `__hold` dello stesso indirizzo lasciava passare subito la richiesta, e la prova avrebbe lasciato la pagina a risposta già arrivata (rilievo della revisione) |
|
||||
| 2026-10-21 | Che dopo «Ho finito», dopo «Riprendi» o lasciando una pagina il browser non sia preso né restituito un'altra volta, le prove lo controllano quando la pagina è quieta (`WaitForQuietAsync`: nessuna richiesta in volo, quindi ogni comando è arrivato al server e la pagina ha finito il seguito di ogni risposta, comprese le richieste che fa partire lì; non aspetta ciò che la pagina rimanda, come le richieste di un osservatore, di un fotogramma, di un timer, del flusso degli eventi o di un modulo che si carica dopo, e qui basta perché il comando sbagliato partirebbe lasciando la pagina o nel seguito di una risposta) sull'elenco delle richieste della pagina (`__asked`) e su quelle viste dal server; non dopo una pausa di 300 o 500 ms. La vista chiusa sul server si aspetta | Con la pausa una macchina lenta poteva controllare prima che il comando sbagliato arrivasse, e la prova passava lo stesso; dopo «Riprendi» la vista chiusa si controllava dopo 300 ms, e lì una macchina lenta faceva fallire la prova. Con copie dell'interfaccia rotte apposta (un «cancel» dopo «Ho finito» nelle pagine Browser e Collegamento, un «begin» dopo «Riprendi», un «begin» che parte solo dopo una risposta del motore) le quattro prove falliscono in ogni giro provato, anche con Chrome rallentato 20 volte. La quiete non copre ciò che parte più tardi (rilievo della revisione): sulla Libreria con 40 elementi, al primo momento senza richieste in volo le 11 righe del mosaico, chieste da un IntersectionObserver dopo il disegno dei giorni, non erano ancora partite in 3 giri su 6 |
|
||||
| 2026-10-21 | La prova dei tasti della vista remota li manda quando il WebSocket della pagina è aperto (`__sockets` di `UiBrowser.Requests`), non 300 ms dopo che il server ha aperto la vista; la prova del mouse scrive meta e fotogramma senza pausa | Il server apre la vista prima di rispondere al socket (`RemoteViewSocket.HandleAsync`) e la pagina scarta i messaggi finché il socket non è aperto: su una macchina più lenta di 300 ms i tasti andavano persi e la prova falliva dopo 30 s. Ciò che il server scrive resta nella vista finché il socket non è aperto e la pagina ascolta da subito, quindi la pausa del mouse non serviva: il primo fotogramma sullo schermo dice già che il socket è aperto |
|
||||
| 2026-10-21 | I ridisegni rimandati di una pagina (`later`: 150 ms in «In evidenza») le prove li aspettano come timer: `PageTimers` dice quali timeout erano in sospeso in un dato momento e quando sono finiti; dopo un cambio di dimensione si aspetta un ResizeObserver della prova, chiamato dopo quelli della pagina, e i timer che quelli hanno lasciato. Il trascinamento della maniglia della fascia aspetta ogni passo nel campo dell'ora prima del successivo; l'intestazione dell'account non ha più una pausa fra un'azione e l'altra | Con pause di 500 e 600 ms il ridisegno sbagliato poteva arrivare dopo il controllo. Con 60 ms fra un passo e l'altro una macchina lenta può consegnare più passi come un solo movimento: la prova vedeva solo l'ultimo e non provava più che la maniglia segua tutto il trascinamento. La pausa dell'intestazione non proteggeva nulla: ogni giro aspetta già il menu ridisegnato. Con copie rotte apposta (ridisegno non annullato, osservatore non staccato, tessere tardive disegnate, trascinamento che finisce al primo passo) le prove falliscono in ogni giro provato, anche a 20x; il ridisegno non annullato si vede quando è ancora in sospeso al cambio di filtro, come prima (in tutti i giri provati lo era) |
|
||||
| 2026-10-21 | `APageLeftWhileLoadingLeavesNothingBehind` controlla che Attività, lasciata mentre carica, non lasci né il timer di un minuto, né l'ascolto della libreria, né avvisi sulla Libreria; e che, aperta, a una modifica della libreria si ricarichi. La modifica la prova la manda alla pagina come la manda il flusso degli eventi (un evento «libreria» sul suo `EventSource`, che chiama subito chi ascolta) e ne ha conferma quando la Libreria richiede i suoi giorni; gli avvisi li registra un MutationObserver, anche quelli già spariti | Rilievo della revisione: il controllo «niente di Attività sulla Libreria» guardava solo `main`, dove Attività non disegna (la sua cornice ne esce prima ancora che il modulo si carichi), e poteva fallire solo per un nodo messo lì direttamente. Con copie rotte apposta la prova di prima passava con l'ascolto della libreria rimasto e con l'errore delle richieste annullate mostrato sulla Libreria; ora le trova entrambe, a velocità normale e con Chrome rallentato 20 volte. Una modifica pubblicata sul server non darebbe lo stesso ordine: il flusso si iscrive alle modifiche in un `Task.Run`, senza dire quando, e le raccoglie per 300 ms |
|
||||
| 2026-10-21 | La pulizia toglie anche ciò che non serve più a nessuno, di qualunque progetto, e non più solo ciò che è della CI di Febe. Alla fine di ogni lavoro «immagine» (verifica e rilascio), dopo la pulizia dell'esecuzione, `pulizia-docker.sh penzolanti`: `docker image prune -f` e `docker builder prune -f --filter until=24h` (senza `-a`), che non fa mai fallire il lavoro. Ogni lunedì e a mano `pulizia-docker.sh completa`: i resti della CI di Febe come prima, i resti di act_runner, `docker image prune -a -f --filter until=24h`, `docker builder prune -a -f --filter until=24h`, con `REGISTRY_TOKEN` le `:sha-` del registro oltre le 10 più recenti, `docker system df` prima e dopo e un riepilogo. Mai `system prune`, `container prune`, `volume prune`, `network prune`, né un contenitore, un volume o una rete che non sia della CI. Per ciò che nessuno usa sostituisce il «mai le immagini degli altri progetti, mai la cache di costruzione del demone, mai le immagini col nome del registro» del 20 ottobre | Decisione di Alberto del 21 ottobre: «aggiungi il prune delle immagini non più utilizzate nel workflow di Actions, in modo da eliminare tutto quello che non serve più». Docker stesso non toglie mai un'immagine usata da un contenitore, acceso o fermo, quindi le applicazioni di Unraid e un Febe vero tengono le loro; le 24 ore lasciano stare ciò che un'altra costruzione ha appena prodotto (per la cache contano dall'ultimo uso; per le immagini dipende dallo store, riga sullo store più sotto). Il prezzo è scritto in `docs/processo.md` («Pulizia»): le immagini di base si riscaricano, le costruzioni ritrovano meno cache, un'immagine costruita a mano e tenuta senza contenitore va ricostruita. `docker builder prune` senza `-a` toglie ciò che nessuna immagine condivide: BuildKit salta solo i record interni, del frontend e condivisi (`cache/manager.go`), quindi senza un limite d'età a ogni push di ogni ramo se ne andrebbero anche gli strati intermedi e le cache montate che le costruzioni degli altri progetti hanno appena usato, e la finestra di 24 ore del lunedì non servirebbe. Per questo anche dopo ogni esecuzione `until=24h`, che BuildKit confronta con l'ultimo uso (rilievo della revisione: il compito chiedeva il comando senza filtro, che non è innocuo per gli altri progetti; se Alberto lo preferisce, basta togliere il filtro) |
|
||||
| 2026-10-21 | Resti di act_runner: contenitori fermi (`exited`, `created`, `dead`), volumi e reti il cui nome comincia con `GITEA-ACTIONS-TASK-<numero>` seguito da `_` o `-`, più vecchi di 90 minuti; volumi e reti solo se nessun contenitore, nemmeno fermo, li usa (`docker ps -a --filter volume=…` e `network=…`). Contenitori e volumi senza `-f`; il volume `act-toolcache` resta | act_runner dà a tutto ciò che crea per un lavoro il prefisso `GITEA-ACTIONS-TASK-<id del compito>` (`internal/app/run/runner.go`); act chiama il contenitore `<prefisso>_WORKFLOW-<flusso>_JOB-<lavoro>` (`createSimpleContainerName`; le versioni più vecchie `-WORKFLOW-…-JOB-…-<impronta>`), i volumi `<nome>` e `<nome>-env`, la rete `<nome>-<lavoro>-network`, e monta `act-toolcache`, la cache degli strumenti di tutti i lavori (`pkg/runner/run_context.go`; controllato su gitea.com il 21 ottobre). Un lavoro vivo ha il contenitore acceso e usa volumi e rete; i 90 minuti, come per i resti della CI di Febe, coprono l'istante in cui un lavoro che parte li ha creati e non ancora usati, se un giorno il runner farà più lavori insieme. Il `Created` di una rete si legge con `{{json .Created}}`: senza, il modello lo stampa nel formato di Go e non in RFC 3339 |
|
||||
| 2026-10-21 | Registro: con `REGISTRY_TOKEN` la pulizia del lunedì toglie le etichette `sha-<da 7 a 40 cifre esadecimali>` del pacchetto container `febe` oltre le 10 più recenti per data di creazione, con l'API dei pacchetti di Gitea 28: `GET /api/v1/packages/{proprietario}/container/febe?page=N&limit=50` fino alla prima pagina vuota e `DELETE /api/v1/packages/{proprietario}/container/febe/{versione}` (risponde 204). Sceglie `.gitea/scripts/versioni-registro.js` (Node, senza rete, provato con `tests/Febe.Tests/Packaging/versioni-registro.json`); lo script ricontrolla la forma prima di ogni DELETE. Mai `main`, `latest`, `X.Y.Z` (anche `-rc.N`), i digest o altro; un rifiuto dell'API è un avviso, non un lavoro rosso; il token sta solo nell'intestazione di curl e non si stampa | Percorsi controllati sul codice di Gitea `release/v28` (`routers/api/v1/api.go`: `ListPackageVersions` e `DeletePackageVersion` nel gruppo `/packages/{username}`, con token e ambito «package»; `routers/api/v1/packages/package.go`: `page` e `limit`, versioni interne escluse, DELETE con 204) e su docs.gitea.com («List package versions», «Delete a package version»). In Gitea ogni etichetta di un contenitore è una versione del pacchetto con i suoi file: togliere `sha-…` non tocca `main` o una versione che puntano allo stesso manifest, e i blob rimasti senza riferimenti li toglie la pulizia dei pacchetti di Gitea (`[cron.cleanup_packages]`), purché l'immagine sia un manifest semplice e non un indice (riga seguente sulle attestazioni). Le versioni `sha256:…` senza etichetta non si toccano mai: si contano soltanto. Node e non jq: Node c'è in ogni contenitore dei lavori (lo usano le azioni) e nelle prove, jq non c'è in `node:24-trixie` né in Git Bash. Prende il posto della regola di pulizia dei pacchetti suggerita il 20 ottobre |
|
||||
| 2026-10-21 | L'immagine di Febe si costruisce e si pubblica senza attestazioni: `--provenance=false --sbom=false` fra gli argomenti comuni di `.gitea/scripts/costruisci-immagine.sh` (l'archivio provato e la spinta sul registro), così sul registro ogni etichetta è un manifest semplice | Con il builder `docker-container` buildx aggiunge da sé l'attestazione di provenienza (`mode=min`; docs.docker.com, «Build attestations») e l'immagine spinta diventa un indice con due figli spinti per digest, l'immagine e l'attestazione. Gitea tiene ogni figlio come una versione a sé, `sha256:…` senza etichetta, a cui sono legati configurazione e strati (release/v28, `routers/api/packages/container/manifest.go`: `processOciImageManifest` lega i blob alla versione del manifest stesso con `createFileFromBlobReference`, `processOciImageIndex` salva solo l'indice e le proprietà `container.manifest.reference`), e togliere un'etichetta toglie solo i file di quella versione: gli strati sarebbero rimasti per sempre (rilievo della revisione). Con un manifest semplice gli strati stanno nella versione dell'etichetta, e quando nessuna versione li usa più li cancella `[cron.cleanup_packages]` (attiva per impostazione predefinita, `@midnight`, `OLDER_THAN = 24h`: `custom/conf/app.example.ini`). Si perde l'attestazione di provenienza, che nessuno legge: da dove viene l'immagine lo dicono le etichette `febe.ci.*` e quelle OCI. Le versioni `sha256:…` (spinte a mano, o con più piattaforme; la CI non ha ancora pubblicato nulla, perché manca `REGISTRY_TOKEN`) lo script non le tocca, perché l'API dei pacchetti non dice se un indice le rimanda ancora, e ne scrive il numero; se servisse, le toglie una regola di pulizia di Gitea con schema `sha256:.+` e 7 giorni, che salta quelle rimandate e sempre `latest` (`services/packages/container/cleanup.go`, `ShouldBeSkipped`; schema confrontato con tutta la versione, `(?i)\A…\z`) |
|
||||
| 2026-10-21 | Prova della pulizia: `pulizia.yml` ha l'input `prova` (`type: boolean`, `default: false`, «Solo prova») e il passo passa `gitea.event.inputs.prova` allo script, che con `--prova` elenca che cosa toglierebbe (immagini con dimensione ed età, cache di costruzione, resti della CI di Febe e di act_runner, etichette del registro) con soli comandi che leggono e, sul registro, soli GET. Nella pulizia vera le immagini le sceglie Docker; nella prova le stima lo script con la stessa regola, contando come già tolti i contenitori che la pulizia toglierebbe prima | Gitea 28 mostra un input booleano come una casella (`templates/repo/actions/workflow_dispatch_inputs.tmpl`) e nell'evento lo scrive come testo, «true» o «false» (`routers/web/repo/actions/view.go`, `Run`: `strconv.FormatBool(ctx.FormBool(name))`); il lunedì l'evento non ha input, e la stringa vuota vuol dire pulizia vera. Il passo accetta solo «true» (la prova) e «false» o niente (la pulizia vera): un avvio con l'API passa il valore così com'è (`routers/api/v1/repo/action.go`, `ActionsDispatchWorkflow`: `inputs[name] = value`, senza conversione), e qualunque altro valore («True», «1») ferma il lavoro con un errore senza toccare nulla. Allo stesso modo lo script, prima di chiamare Docker, rifiuta con codice 2 ogni opzione diversa da `--prova` e ogni argomento in più: una prova scritta in un altro modo (`--dry-run`, `-n`, `prova`) prima faceva partire la pulizia vera con codice 0 (rilievo della revisione) |
|
||||
| 2026-10-21 | `pulizia-docker.sh` gira con `BUILDX_BUILDER=default`: la cache che pota è quella del builder del demone | Con il plugin buildx `docker builder` diventa `docker buildx` (`cmd/docker/builder.go` del client Docker), che lavora sul builder corrente: nel lavoro «immagine» è quello dell'esecuzione, che `setup-buildx-action` crea con `--use` (`src/context.ts`) e che il modo «esecuzione» ha già tolto. I comandi buildx che toccano i builder di Febe li indicano per nome |
|
||||
| 2026-10-21 | Il lavoro «controlli» legge anche gli script Node della CI (`node --check .gitea/scripts/*.js`) | Come `bash -n` per gli script di shell: un errore di sintassi in `versioni-registro.js` si vede in pochi secondi, non alla pulizia del lunedì |
|
||||
| 2026-10-21 | Nei modi «settimanale» e «completa» la pulizia legge lo store delle immagini del demone (`docker info --format '{{json .DriverStatus}}'`: con `io.containerd.snapshotter.v1` è quello di containerd, altrimenti il classico) e lo scrive all'inizio; con containerd, o se non lo sa, la prova avverte che le età che elenca sono solo indicative | Da quando contano le 24 ore di `image prune --filter until` dipende dallo store (rilievo della revisione). Con quello classico Docker confronta il `Created` della configurazione, cioè la costruzione (moby, `daemon/images/image_prune.go`: `img.Created.After(until)`); con quello di containerd il `CreatedAt` del record dell'immagine sul demone (`daemon/containerd/image_list.go`: `image.CreatedAt.Before(until)`), che containerd conserva quando lo stesso nome viene riscaricato. Nessun comando mostra quel `CreatedAt` (`docker image ls` dà il `Created` della configurazione anche con containerd), quindi la prova resta sull'età dalla costruzione e lo dice. Lo store di containerd è il predefinito nelle installazioni nuove di Docker Engine dalla 29; su Unraid è più probabile quello classico. `docker info` solo legge |
|
||||
| 2026-10-21 | Della pulizia del lunedì si dice anche che cosa `image prune -a` toglie alle immagini che un contenitore usa: i nomi in più. La pulizia vera confronta i nomi prima e dopo e scrive, nome per nome, quelli tolti a un'immagine che resta; la prova li stima secondo lo store (classico: tutti tranne l'ultimo in ordine alfabetico del nome completo, `docker.io/library/…` per Docker Hub; containerd: tutti tranne quelli da cui i contenitori sono stati creati, e l'ultimo se un contenitore la usa per identificativo). Il comando resta quello chiesto | Rilievo della revisione: la prova saltava ogni immagine in uso, e i documenti dicevano che un'immagine usata da un contenitore non si tocca. Docker non toglie l'immagine, ma con lo store classico `ImagesPrune` non guarda i contenitori e chiama `ImageDelete` senza forza su ogni riferimento, in ordine alfabetico (`daemon/images/image_prune.go`, uguale in moby v24.0.9, v27.5.1 e master; `reference/store.go`, `lexicalRefs`); `ImageDelete` rifiuta solo l'ultimo riferimento di un'immagine in uso (`image_delete.go`, `isSingleReference`), quindi può sparire proprio il nome da cui il contenitore è stato creato (un'applicazione di Unraid creata da `app:1.2` che si chiama anche `app:latest`). Con containerd `filterImagesUsedByContainers` protegge solo il nome di `Config.Image` e, se il contenitore usa l'immagine per identificativo o digest, l'ultimo nome (`daemon/containerd/image_prune.go`). Il demone finto delle prove fa lo stesso con l'uno e con l'altro store |
|
||||
| 2026-10-25 | I primi campioni reali di Instagram vengono dal file HAR che Alberto ha esportato dal suo browser il 21 ottobre (DevTools, filtro Fetch/XHR), non dalla sonda: le sole risposte utili sono state convertite nel formato grezzo della sonda in una cartella temporanea fuori dal repository, accorciate dal lato grezzo (raccolte: 2 per 4 contenuti, scelti fra foto, video con audio e video senza; pagina successiva: 1 per 3; profili suggeriti: i primi 3), ripulite con `febe-sonda ripulisci` e controllate con `febe-sonda verifica` («Verifica superata»). Del HAR si è letta solo la forma (percorsi, tipi, chiavi), mai valori, intestazioni o cookie; i grezzi convertiti si cancellano a fine lavoro | Richiesta di Alberto del 25 ottobre («vedi tu quale ti risulta più utile»: HAR o guida). La guida descrive richieste costruite a mano verso l'API, con intestazioni copiate, vietate dalle regole 2–4 di §2, e un formato (`GraphImage`, `edge_sidecar_to_children`) che nel HAR non compare: non si usa. Il HAR invece è ciò che la pagina riceve davvero, cioè il campione reale che chiede la regola 10. Accorciare dal lato grezzo tiene i campioni piccoli senza cambiarne la forma; la ripulitura costruisce l'elenco dei frammenti sensibili da tutto il grezzo, quindi accorciare dopo non servirebbe |
|
||||
| 2026-10-25 | La cattura legge come dati anche le risposte `text/javascript` (e ogni tipo che contiene «javascript») che la pagina chiede da sé (risorsa XHR o Fetch), oltre a quelle dichiarate JSON; i file di script non si leggono mai. Una sola regola, `DataResponses.IsData`, per `ResponseTap` e `CaptureCollector` | Nel HAR tutte le risposte GraphQL (`/graphql/query`, `/api/graphql`: storie, raccolte, ricerca) sono `text/javascript`; solo le REST (`/api/v1/…`) sono `application/json`. Con la regola di prima Febe scartava proprio i dati di storie e raccolte: è il motivo per cui non leggeva nulla. Le risposte con il prefisso `for (;;);` (`/ajax/…`: definizioni delle pagine, registri di navigazione) non sono JSON e non portano contenuti: restano scartate |
|
||||
| 2026-10-25 | Del documento principale di una pagina del sito (`text/html`, cornice principale) si leggono i blocchi `<script type="application/json">`: ogni blocco arriva ai lettori come una risposta a sé, con il descrittore del documento, letto mentre si scorre e uno solo in memoria alla volta (`DataResponses.EmbeddedJsonBlocks`); un documento senza blocchi validi si segnala scartato una volta; `febe-sonda da-har` scrive un campione per blocco. Il corpo del documento si chiede con `Network.getResponseBody`, già nell'elenco ammesso | Una pagina aperta per indirizzo (`Page.navigate`, come fanno tutte le ricette) riceve i dati del primo schermo dentro il documento e chiede con XHR solo le pagine successive: senza, la prima pagina di un profilo arriverebbe «vuota». **Da confermare dal vivo**: il HAR del 21 ottobre non conteneva documenti. Se i dati arrivano invece con XHR, la lettura del documento non trova nulla e non cambia niente. Blocco per blocco e non riuniti in un array (rilievo della revisione): riuniti davano una sola lettura con una sola paginazione, la prima del documento, e il «has_next_page» delle raccolte o il «more_available: false» di un post finiva sugli elementi di un altro blocco. Da confermare dal vivo: le regole di testo di `segnali.json` ora vedono anche i blocchi piccoli uno per uno. L'arrivo del documento non cancella più la sua stessa richiesta in corso (la cornice cambia documento prima che il corpo sia finito: si tiene la richiesta con l'identificativo del caricatore nuovo) |
|
||||
| 2026-10-25 | Nel vocabolario dei lettori, `relevance.keys`: se una risposta non contiene nessuna di quelle chiavi è «non pertinente» (`ReadShape.Unrelated`) e si ignora, invece di contare come forma sconosciuta; `CaptureCollector` non la conserva nemmeno, così una pagina che continua a mandare registri si assesta lo stesso. Per Instagram: `image_versions2`, `video_versions`, `carousel_media`, `taken_at`, `username`; per il sito di prova l'elenco è vuoto e tutto resta come prima | Instagram manda molte risposte JSON che non c'entrano con i contenuti (promozioni, il segno «storia vista», registri). Con le risposte `text/javascript` lette, ognuna di queste avrebbe fermato una ricetta come «formato non riconosciuto» ogni volta che il dato atteso tardava. Una risposta che ha le chiavi dei contenuti ma una forma che il vocabolario non descrive resta «formato non riconosciuto» (§6.4). L'elenco non si ricava dal vocabolario: sul sito di prova la forma sconosciuta di prova non ha nessuna sua chiave e deve restare sconosciuta |
|
||||
| 2026-10-25 | `IResponseObserver.OnBodyDropped`: la cattura avvisa quando il corpo di una risposta annunciata non arriverà (troppo grande, caricamento fallito, non JSON, pagina cambiata, browser riavviato), e `CaptureCollector` smette di aspettarlo | Prima un corpo scartato restava «in arrivo» per 15 secondi e `SettleAsync` non si assestava: con le risposte `/ajax/…` di Instagram, che arrivano a ogni scorrimento e cambio di pagina, ogni raffica avrebbe aspettato fino al limite |
|
||||
| 2026-10-25 | `lettori.instagram.json` è «confermato» e compilato soltanto con chiavi che compaiono nei campioni ripuliti (una prova lo controlla chiave per chiave): contenuto `pk`, `code`, `taken_at`, `caption.text`, `image_versions2.candidates`, `video_versions`, `carousel_media` e `carousel_media_count` (chiavi viste ma sempre vuote: nessuna serie nei campioni), `user`/`owner`, `expiring_at`, `video_duration`; versione `url`, `width`, `height`; profilo `pk`/`id`, `username`, `full_name`, `is_private`, `friendship_status.following`, `hd_profile_pic_url_info`/`hd_profile_pic_versions`/`profile_pic_url`, `latest_reel_media`; raccolta `id`, `title`, `user`, `items`; pagina `has_next_page`/`more_available`, `end_cursor`; account collegato `xdt_viewer.user`. Restano vuoti `pinned`, `postCount` e `version.hasAudio` | Regola 10. `has_audio` sta sul contenuto, non sulla versione: ogni versione di `video_versions` conta come file completo (H5 si conferma scaricando). Le versioni video delle storie non hanno dimensioni: si prende la prima (101), che nei post ha le stesse dimensioni e la stessa banda delle altre due. `xdt_viewer.user` ha solo l'identificativo: il lettore lo tiene (`ReadResult.ViewerId`) per riconoscere l'account collegato quando il suo profilo compare altrove (H10 resta aperta) |
|
||||
| 2026-10-25 | L'identificativo di una raccolta si tiene nella forma dell'indirizzo: dal `highlight:17841…` dei dati il lettore toglie un prefisso fatto di sole lettere e due punti. Un oggetto con `id` e `title` è una raccolta solo se ha anche il proprietario o i contenuti (quando il vocabolario li nomina) | Nel HAR i dati dicono `highlight:<17 cifre>` e l'indirizzo del visualizzatore `/stories/highlights/<17 cifre>/`: senza normalizzare, ricetta e visualizzatore non si sarebbero mai riconosciuti. Senza il secondo vincolo una promozione o una sezione di pagina con `id` e `title` diventava una raccolta finta, e quelle vere sarebbero risultate tolte |
|
||||
| 2026-10-25 | Ripulitura: `latest_reel_media` è una data (si tiene); i valori sotto chiavi che hanno l'aspetto di un segreto (`token`, `key`, `secret`, `session`, `cookie`, `auth`, …) diventano un riempitivo neutro della stessa forma (lettere `x`, cifre `7`) invece di un valore finto vario | `latest_reel_media` è la data dell'ultima storia, della stessa natura di `taken_at`. Un valore finto estratto lettera per lettera da un `organic_tracking_token` di 340 caratteri sembra un segreto vero a gitleaks, che nella CI avrebbe fermato il lavoro «controlli» su dati finti; il riempitivo ha la stessa forma e nessuna entropia |
|
||||
| 2026-10-25 | Senza l'identificativo del contenuto nell'indirizzo del visualizzatore (Instagram: `/stories/highlights/{highlight}/`, uguale per tutti i contenuti della raccolta) i contenuti si contano sull'elenco ricevuto: il primo mostrato è il primo dell'elenco e ogni clic su «avanti» ne sposta uno; il conteggio non va mai avanti senza un clic. Un video si lascia entro l'inizio del clic + la sua durata − 1,5 s × umore·ritmo; se non si fa più in tempo, si chiude senza «avanti» e i contenuti dopo non si salvano (evento «visualizzatore-chiuso-prima»). Con l'identificativo nell'indirizzo (le storie, `/stories/{username}/{id}/`) si segue l'indirizzo come prima. In entrambi i modi il permesso StoryView per il contenuto successivo si chiede appena quello attuale è a video, prima dell'attesa di §7.7 (che si conta da quando è comparso); un contenuto comparso da solo dopo l'ultimo dell'elenco non si salva e il visualizzatore si chiude | Nel HAR quattro richieste fatte guardando contenuti diversi di una raccolta hanno lo stesso Referer: l'indirizzo non dice quale contenuto è a video. Regola 7 e §6.3: nella prima versione il permesso arrivava dopo che il contenuto era già comparso, e con umore o ritmo oltre 1 il clic cadeva dopo la fine del video, saltava un contenuto e portava nella raccolta successiva (rilievi della revisione). Meglio perdere contenuti che salvarne di non mostrati. Restano da misurare dal vivo il clic che la pagina ignora (il conteggio andrebbe avanti) e quanto il sito tiene una foto; con la spaziatura di 4 s del Governatore i video più brevi di 4–6 s si chiudono prima |
|
||||
| 2026-10-25 | Anche dopo un errore imprevisto (non dopo un segnale di arresto) la ricetta chiude il visualizzatore e salva ciò che è stato mostrato fin lì. Un visualizzatore che non si chiude con «viewer-close» ferma la ricetta come «bersaglio non trovato», anche dopo un altro arresto (tetto, errore); dopo un annullamento si salva ciò che è stato mostrato e la pagina resta com'è; ciò che un clic apre a un indirizzo che la mappa non riconosce si chiude prima di fermarsi | Un visualizzatore lasciato aperto passa da solo alle storie degli account successivi (§6.3), e solo «bersaglio non trovato» ferma la sessione e mette la pagina a riposo. Prima un indirizzo senza identificativo del contenuto faceva fallire la ricetta con il visualizzatore aperto, e un annullamento (pausa, segnale), che arriva quasi sempre durante l'attesa su una storia, faceva perdere storie già segnate come viste |
|
||||
| 2026-10-25 | Il bersaglio `profile-not-found` è facoltativo per Controllo del profilo, Storico, Taggati e Reel: si cerca solo se la mappa lo imposta; senza, un profilo che non c'è non dà dati ed è giudicato come una pagina vuota | Per Instagram non c'è ancora un segno verificato (H11) e le ricette del profilo devono poter girare con le sole pagine. Con il segno impostato l'account si segna «Non raggiungibile» come prima |
|
||||
| 2026-10-25 | Dopo aver aperto profilo, home ed elenco dei seguiti (e dopo il clic su una scheda) le ricette aspettano il dato atteso, lasciano assestare la pagina e prendono tutto ciò che è arrivato dal segno in poi; Controllo e Storico aspettano anche la prima pagina della griglia (fino a 20 s). La paginazione di un cammino viene solo dalle risposte che portano i suoi elementi, o da una pagina vuota; l'elenco dei seguiti non salva mai un profilo con `IsFollowed` falso (i profili suggeriti), né l'account collegato; la home «è arrivata» con contenuti, una voce della barra delle storie o una pagina, non con soli profili. «Tu» nasce anche da `ViewerId` più un profilo con lo stesso identificativo in una risposta qualunque del giro | Su Instagram intestazione del profilo, griglia, raccolte e home arrivano in risposte diverse, anche dopo la prima; risposte su altro (un post con `more_available:false`, le raccolte con `has_next_page:false`) dicono «non ce n'è altro» di sé stesse e avrebbero chiuso uno storico; i 30 profili suggeriti hanno `friendship_status.following:false`. Sul sito di prova, dove tutto arriva insieme, il comportamento resta quello di prima |
|
||||
| 2026-10-25 | Una ricetta che la mappa dei bersagli o il vocabolario dei lettori non lasciano girare finisce in `NotConfigured` («Da configurare»), non più in «bersaglio non trovato» o «formato non riconosciuto»: non conta per la sospensione, il motore non la pianifica, lo dice una volta per ricetta e per avvio, e annulla con un evento un comando di Alberto che non può partire. Senza il giro dei seguiti le storie dei seguiti si controllano account per account | I rifiuti dei primi file di Instagram, che erano scheletri, contavano come guasti: dopo tre sessioni il motore sospendeva le ricette come se Instagram fosse cambiato, e le sospensioni restavano anche con file nuovi |
|
||||
| 2026-10-25 | All'avvio Febe calcola un'impronta SHA-256 di `lettori.<sito>.json` e `bersagli.<sito>.json` come caricati (incorporati o copia nella cartella Dati, fine riga ignorati) e la conserva in `motore.configurazione-raccolta`; quando cambia, e al primo avvio che la calcola, azzera una volta sospensioni ed errori consecutivi delle ricette, con una riga in Attività se c'era qualcosa da azzerare. Il registro (fonte «raccolta») dice da dove vengono i due file e com'è il vocabolario, quali ricette non possono girare, e avvisa se una copia nella cartella Dati è ancora «ipotesi» mentre quella incorporata è «confermato» o ferma ricette che quella incorporata lascerebbe girare. Mai il contenuto dei file | Le sospensioni contate con i file vecchi non devono sopravvivere a quelli nuovi, e nel database di Alberto con ogni probabilità ce ne sono. Una copia vecchia nella cartella Dati vince sempre su quella incorporata: senza il registro resterebbe invisibile. La cartella `config/` accanto al programma non si legge mai (la riga del 13 ottobre lo dava per vero) |
|
||||
| 2026-10-25 | Lo stato del collegamento nella barra laterale viene dal cookie di sessione (dal modo del motore, o dal servizio di collegamento quando il motore non gira), non dal fatto che l'account «Tu» sia già noto | Su Instagram «Tu» può arrivare molto dopo il collegamento (H10: i dati danno solo l'identificativo dell'account collegato) e la barra diceva «Da collegare» mentre Febe raccoglieva |
|
||||
| 2026-10-25 | `bersagli.instagram.json`: compilate solo le pagine con una prova reale nel HAR del 21 ottobre (i modelli che Instagram stesso manda in `/ajax/bulk-route-definitions/` e i Referer delle richieste della pagina): home `/`, profilo `/{username}/`, post `/p/{code}/`, storie `/stories/{username}/{id}/`, raccolte `/stories/highlights/{highlight}/` senza identificativo del contenuto. Vuoti l'elenco dei seguiti, le pagine di ripresa e tutti i bersagli (H11). La forma delle storie coincide anche con l'indirizzo delle raccolte (nome utente «highlights»): accettato, perché per le storie è «un altro account» e il visualizzatore si chiude, e la ricetta delle raccolte legge solo la sua pagina | Regola 10: niente di inventato. Il HAR non aveva documenti né attributi degli elementi, quindi nessun ruolo né nome accessibile. Girano le ricette che aprono solo pagine (giro dei seguiti, controllo del profilo, storico, post singolo); storie, raccolte, Taggati e Reel aspettano i bersagli |
|
||||
| 2026-10-25 | `febe-sonda da-har --har <file> --a <cartella>`: un HAR esportato dagli strumenti per sviluppatori diventa una cartella di campioni grezzi nel formato della sonda: solo le risposte di dati del sito (`DataResponses.IsData`) e il JSON incorporato nei documenti, mai intestazioni, cookie, query o corpi delle richieste; il nome del file viene dall'operazione GraphQL solo se ha la forma di un nome del codice (finisce con Query, Mutation o Subscription, senza cifre ripetute), altrimenti «risposta» o «documento». Rifiuta un HAR o una cartella dentro un repository e una cartella non vuota | Alberto raccoglie più volentieri dal suo browser di tutti i giorni che con la sonda: così può ripulire e verificare da sé, sulla sua macchina, e mandare solo la copia ripulita (§14.5) |
|
||||
| 2026-10-25 | `tools/bersagli/raccogli-bersagli.js`: i bersagli si raccolgono con uno script in sola lettura che Alberto incolla nella Console del suo browser: un solo ascoltatore dei clic, nessuna modifica alla pagina, niente rete, cookie o archivi; calcola ruolo e nome accessibile come `TargetResolver`, registra la forma degli indirizzi prima e dopo il clic, sostituisce i nomi con NOME e prepara per ogni clic le voci `role`, `name`, `href` e `index` della mappa | Il HAR non porta gli attributi degli elementi; la sonda li registrerebbe, ma chiede di avviare un Chromium a parte. La forma dell'indirizzo dopo il clic dice anche se l'indirizzo delle storie segue ogni storia |
|
||||
| 2026-10-25 | La paginazione di una pagina (griglia, schede, giro dei seguiti, elenco dei seguiti) viene dalla risposta che porta più elementi non ancora incontrati, l'ultima a pari merito; una risposta che riporta solo elementi già letti non conta come pagina successiva né per la sua paginazione. Una risposta vuota senza profilo è la pagina vuota di un cammino solo quando risponde a un suo gesto (pagina di ripresa, scheda, scorrimento), mai all'apertura del profilo; con il profilo dell'account è la griglia vuota anche accanto alle raccolte, se il profilo dice «0 pubblicazioni» | Rilievi della revisione: su Instagram la pagina di un post del profilo stesso («more_available: false») e le raccolte di un account che non ne ha (connessione vuota con «has_next_page: false», forma identica a una griglia vuota) chiudevano lo storico dopo la prima pagina o senza post; sul sito di prova un profilo con raccolte e senza post aspettava 20 s a ogni controllo. Un account Instagram senza post resta così con lo storico aperto: costa un'attesa e una pagina a sessione, mai post persi |
|
||||
| 2026-10-25 | Mentre «Storie di un account» non può girare con la configurazione del sito, la visita di un profilo non seguito non serve le storie: si pianifica all'intervallo del profilo, non conta come lavoro di storie, e il giro dei seguiti non accoda «Storie segnalate dalla barra» (ogni giro segnala di nuovo l'account finché le storie non si vedono). `SyncQueue` non annulla più i «Post singolo» accodati dalla raccolta: li toglie solo per un account che non si contatta, e mentre la ricetta non può girare aspettano | Con i file di Instagram di oggi un profilo non seguito si sarebbe aperto fino a 24 volte più spesso del dovuto senza raccogliere nulla, e la Coda si sarebbe riempita a ogni sessione di storie che non sarebbero mai partite. Un «Post singolo» annullato non tornava più in coda (nessuno ricontrolla gli indirizzi scaduti), mentre §6.5 punto 5 vuole che il recupero passi da lì: difetto precedente a questo lavoro (commit `aff81df`), trovato dalla revisione. Effetto: su Instagram queste ricette ora girano davvero, dentro il loro tetto (Prudente: 10 l'ora, 60 al giorno) |
|
||||
@@ -20,6 +20,31 @@ display virtuale (Xvfb) e la libreria su disco. Si usa dal browser di casa; il b
|
||||
- L'immagine si costruisce solo con le prove verdi: la compilazione e tutte le prove girano dentro la costruzione
|
||||
(quelle con il browser vero lì si saltano da sole, perché nello stadio di compilazione non ci sono Chromium e Xvfb;
|
||||
girano nella CI e in sviluppo).
|
||||
- I pacchetti di Debian sono aggiornati al momento della costruzione (anche le correzioni uscite dopo l'immagine di
|
||||
base). Prima di ogni pubblicazione la CI fa partire il contenitore senza rete fino al controllo di salute e lo
|
||||
scansiona con Trivy: una vulnerabilità CRITICAL con correzione disponibile ferma la pubblicazione
|
||||
(`docs/processo.md`, «Rilievi di sicurezza»).
|
||||
|
||||
## Etichette dell'immagine
|
||||
|
||||
Sul registro di Gitea, `192.168.30.23:3000/alby96/febe`:
|
||||
|
||||
| Etichetta | Che cos'è | Quando cambia |
|
||||
|---|---|---|
|
||||
| `:latest` | l'ultima versione rilasciata senza trattino: quella del modello di Unraid e di `compose.yml` | a ogni rilascio stabile |
|
||||
| `:X.Y.Z` | una versione rilasciata (anche `X.Y.Z-rc.N` per un'anteprima) | mai: serve per tornare a una versione precisa |
|
||||
| `:main` | l'ultimo commit di `main` che ha passato la verifica | a ogni unione in `main`: per provare, non per l'archivio vero |
|
||||
| `:sha-<7 caratteri>` | un commit di `main` preciso | mai; sul registro restano le 10 più recenti |
|
||||
|
||||
Ogni immagine costruita dalla CI dice da dove viene, nelle etichette Docker `febe.ci.workflow`, `febe.ci.run`,
|
||||
`febe.ci.ref` e `febe.ci.commit` e in `org.opencontainers.image.version` e `.revision`:
|
||||
`docker inspect --format '{{json .Config.Labels}}' <immagine>`. Docker copia queste etichette anche nel contenitore di
|
||||
Febe: la pulizia della CI non le usa per scegliere che cosa togliere, quindi un Febe sullo stesso Docker del runner
|
||||
della CI non viene mai toccato, né la sua immagine, anche a contenitore fermo. Su quel Docker, però, la pulizia del
|
||||
lunedì toglie le immagini che nessun contenitore usa e che sono state create più di 24 ore fa: un'immagine di Febe
|
||||
tenuta senza contenitore (una versione precedente, per tornare indietro) se ne va, e si riscarica dal registro, dove
|
||||
`:X.Y.Z` resta. E se l'immagine del Febe vero ha più nomi (`:latest` e `:0.1.0`, per esempio), resta, ma con uno solo:
|
||||
gli altri la pulizia li toglie (`docs/processo.md`, «Pulizia»).
|
||||
|
||||
## Volumi
|
||||
|
||||
|
||||
+4
-3
@@ -37,9 +37,10 @@ seguire; passa al tuo account solo quando hai visto come si comporta.
|
||||
Questa guida descrive ciò che c'è nel programma, non ciò che si spera. Alcune cose dipendono da prove che si possono
|
||||
fare solo con Instagram o su Windows:
|
||||
|
||||
- **Raccolta da Instagram: non ancora attiva.** Le ricette, il motore, la libreria e gli scaricamenti funzionano e sono
|
||||
provati contro un sito di prova locale. Su Instagram le ricette si rifiutano di girare («la mappa dei bersagli non è
|
||||
ancora compilata») finché la sonda passiva non ha confermato le ipotesi H1–H11. Vedi
|
||||
- **Raccolta da Instagram: in parte attiva (25 ottobre 2026).** Febe legge le risposte vere di Instagram (lettori
|
||||
scritti su risposte reali, ripulite). Girano giro dei seguiti, controllo del profilo, storico e post singolo: foto e
|
||||
video dei post e dei reel. Storie, raccolte in evidenza e schede Taggati e Reel aspettano i bersagli dei comandi
|
||||
(ipotesi H11) e rispondono «la mappa dei bersagli non è ancora compilata». Non è ancora stato provato dal vivo. Vedi
|
||||
[Ipotesi da verificare](Ipotesi-da-verificare).
|
||||
- **Versione per Windows: pronta, non ancora provata su un Windows vero.** Programma di installazione e versione
|
||||
portabile ci sono; le prove che si fanno solo su Windows (S1–S3) sono aperte. Vedi
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
# Ipotesi da verificare
|
||||
|
||||
Febe è costruito su alcune ipotesi che non si possono provare senza Instagram (voci **H**) o senza i due browser veri
|
||||
(voci **S**). Finché una voce non è provata, non ci si costruisce sopra: per questo la raccolta da Instagram non è
|
||||
ancora attiva. Lo stato aggiornato e i dettagli tecnici sono in `docs/sonda/esito.md` e `docs/sonda/esito-locale.md`
|
||||
nel repository; i passi precisi delle prove in `docs/prove-dal-vivo.md`.
|
||||
(voci **S**). Finché una voce non è provata, non ci si costruisce sopra. Lo stato aggiornato e i dettagli tecnici sono
|
||||
in `docs/sonda/esito.md` e `docs/sonda/esito-locale.md` nel repository; i passi precisi delle prove in
|
||||
`docs/prove-dal-vivo.md`.
|
||||
|
||||
**Dal 25 ottobre 2026** Febe legge le risposte vere di Instagram: i lettori sono scritti sulle risposte che il tuo
|
||||
browser ha ricevuto il 21 ottobre (un file HAR), ripulite. Girano le ricette che aprono solo pagine (giro dei seguiti,
|
||||
controllo del profilo, storico, post singolo). Storie, raccolte in evidenza e schede Taggati e Reel aspettano i
|
||||
**bersagli** (H11): i nomi e i ruoli di pulsanti come l'anello delle storie, «avanti» e la X, che nel HAR non c'erano.
|
||||
|
||||
Le prove dal vivo le fai **tu**, con l'**account di prova**, mai con l'account principale prima di aver visto Febe
|
||||
all'opera. Se in qualunque momento compare una verifica, un CAPTCHA o un avviso dell'account: fermati, risolvi a mano,
|
||||
@@ -14,28 +19,32 @@ locali, mai Instagram; **da provare** = serve una prova tua.
|
||||
|
||||
## Voci H: Instagram
|
||||
|
||||
Si provano tutte con la **sonda passiva** (parte A di `docs/prove-dal-vivo.md`): avvii `febe-sonda registra`, navighi
|
||||
tu in Instagram seguendo l'elenco (pagina iniziale, un profilo pubblico, un privato che segui, delle storie, una
|
||||
raccolta, le schede taggati e reel, l'elenco dei seguiti, un post), la sonda registra ciò che la pagina riceve; poi
|
||||
Si provano con la **sonda passiva** (parte A di `docs/prove-dal-vivo.md`): avvii `febe-sonda registra`, navighi tu in
|
||||
Instagram seguendo l'elenco (pagina iniziale, un profilo pubblico, un privato che segui, delle storie, una raccolta, le
|
||||
schede taggati e reel, l'elenco dei seguiti, un post), la sonda registra ciò che la pagina riceve; poi
|
||||
`febe-sonda ripulisci` e `febe-sonda verifica` sulla tua macchina, e mandi solo la cartella **ripulita**. La sonda non
|
||||
compie gesti e non apre pagine da sola.
|
||||
|
||||
Più semplice, con il **browser di tutti i giorni** (parte A bis): registri un HAR con il filtro «Tutti», incolli nella
|
||||
Console lo script `tools/bersagli/raccogli-bersagli.js` per i bersagli, poi `febe-sonda da-har`, `ripulisci` e
|
||||
`verifica`, e mandi solo la copia ripulita e il testo dei bersagli.
|
||||
|
||||
| | Ipotesi | Stato | Come la provi |
|
||||
|---|---|---|---|
|
||||
| H1 | La pagina iniziale consegna i post recenti dei profili che segui con i dati completi dei file | Da provare | Sonda, pagina iniziale: scorri piano una decina di post |
|
||||
| H1 | La pagina iniziale consegna i post recenti dei profili che segui con i dati completi dei file | Da provare (il HAR non conteneva la pagina iniziale) | Sonda, pagina iniziale: scorri piano una decina di post |
|
||||
| H2 | La barra delle storie dice quali profili seguiti hanno storie attive e a quando risale l'ultima | Da provare | Sonda, pagina iniziale caricata: passa sopra la prima voce della barra |
|
||||
| H3 | La pagina di un profilo consegna identificativo, pubblico o privato, se lo segui, la prima pagina dei post con serie e video, le raccolte; scorrendo arrivano le pagine successive | Da provare | Sonda: un profilo pubblico che non segui e uno privato che segui, scorrendo 3–4 schermate |
|
||||
| H4 | Aprendo il visualizzatore arriva l'elenco delle storie con gli indirizzi dei file, e si capisce qual è l'ultima | Da provare | Sonda: apri le storie di un seguito dall'anello, guardane 2–3, chiudi con la X prima che passi all'account successivo |
|
||||
| H5 | Per i video arriva almeno un indirizzo con audio e video insieme | Da provare | Sonda: un post video e una storia video |
|
||||
| H3 | La pagina di un profilo consegna identificativo, pubblico o privato, se lo segui, la prima pagina dei post con serie e video, le raccolte; scorrendo arrivano le pagine successive | In parte: forma dell'indirizzo e del profilo viste nel HAR; le risposte della pagina profilo da provare | Sonda: un profilo pubblico che non segui e uno privato che segui, scorrendo 3–4 schermate |
|
||||
| H4 | Aprendo il visualizzatore arriva l'elenco delle storie con gli indirizzi dei file, e si capisce qual è l'ultima | In parte: il visualizzatore delle raccolte riceve l'elenco completo con gli indirizzi; quello delle storie di un account da provare | Sonda: apri le storie di un seguito dall'anello, guardane 2–3, chiudi con la X prima che passi all'account successivo |
|
||||
| H5 | Per i video arriva almeno un indirizzo con audio e video insieme | In parte: tre versioni `.mp4` per video, «ha l'audio» detto dal contenuto; da confermare scaricando | Sonda: un post video e una storia video |
|
||||
| H6 | Le schede «Taggati» e «Reel» si comportano come la griglia | Da provare | Sonda: apri le due schede di un profilo e scorri |
|
||||
| H7 | I file del CDN si scaricano dal browser (`Network.loadNetworkResource`) | Provato in locale (24 MB integri); da provare con il CDN vero | Prima sessione dal vivo (parte B): i file arrivano in Libreria, stato «scaricato» |
|
||||
| H8 | I segnali di arresto si riconoscono da indirizzo e stato HTTP | Da provare (non provocarli di proposito) | Se durante la sonda compare una verifica, annota l'ora e manda la riga ripulita di `navigazioni.jsonl` |
|
||||
| H9 | Un contenuto di una raccolta in evidenza ha lo stesso identificativo che aveva come storia | Da provare | Sonda: apri una raccolta che contiene una storia ancora attiva |
|
||||
| H10 | Identificativo e nome dell'account collegato si ricavano dai dati della pagina, senza leggere i cookie | Da provare | Sonda, pagina iniziale |
|
||||
| H11 | I comandi della pagina si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | Da provare; lo scheletro `bersagli.instagram.json` è pronto | Durante tutta la sonda: passa col puntatore sui comandi elencati prima di usarli; manda le sole righe dei comandi, con i nomi di persona sostituiti |
|
||||
| H9 | Un contenuto di una raccolta in evidenza ha lo stesso identificativo che aveva come storia | Indizio: i contenuti delle raccolte hanno identificativo e scadenza come le storie | Sonda: apri una raccolta che contiene una storia ancora attiva |
|
||||
| H10 | Identificativo e nome dell'account collegato si ricavano dai dati della pagina, senza leggere i cookie | Non basta: i dati danno solo l'identificativo dell'account collegato; Febe lo riconosce quando compare il suo profilo | Sonda, pagina iniziale |
|
||||
| H11 | I comandi della pagina si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | Da provare: il HAR non aveva gli attributi dei comandi. Pagine compilate, bersagli vuoti | Durante tutta la sonda: passa col puntatore sui comandi elencati prima di usarli; manda le sole righe dei comandi, con i nomi di persona sostituiti |
|
||||
|
||||
Finché H1–H11 non sono provate e la mappa dei bersagli e il vocabolario dei lettori non sono compilati sui campioni
|
||||
ripuliti, le ricette su Instagram rispondono «la mappa dei bersagli non è ancora compilata» senza aprire pagine.
|
||||
Finché i bersagli non sono compilati, le ricette che ne hanno bisogno rispondono «la mappa dei bersagli non è ancora
|
||||
compilata» senza aprire pagine; in Attività risultano «Da configurare» e il motore non le pianifica.
|
||||
|
||||
## Voci S: i due browser
|
||||
|
||||
|
||||
@@ -55,7 +55,9 @@ una sua copia, ha la sessione di Instagram.**
|
||||
- Lo stato del collegamento è sempre in fondo alla barra laterale: collegato, da collegare, verifica richiesta, sessione
|
||||
chiusa.
|
||||
- Il tuo profilo compare tra gli account segnato «Tu», con «Post in cui è taggato» attivo: è così che si scaricano i
|
||||
post in cui sei taggato. (Riconoscere il tuo account dai dati della pagina è l'ipotesi H10, ancora da confermare.)
|
||||
post in cui sei taggato. Su Instagram i dati della pagina danno solo l'identificativo del tuo account: Febe ti
|
||||
riconosce quando compare anche il tuo profilo (per esempio la tua voce nella barra delle storie); fino ad allora la
|
||||
barra laterale dice «Collegato» e «Nome non ancora noto». È l'ipotesi H10, ancora da confermare dal vivo.
|
||||
|
||||
Poi aggiungi gli account da seguire: [Account e impostazioni](Account-e-impostazioni).
|
||||
|
||||
|
||||
@@ -33,9 +33,10 @@ dati.
|
||||
|
||||
Controlla in quest'ordine, guardando [Attività](Attivita-e-arresti):
|
||||
|
||||
1. **Raccolta da Instagram non ancora attiva.** Se in «Appena fatto» vedi «non può girare su instagram: la mappa dei
|
||||
bersagli non è ancora compilata», è lo stato attuale del progetto: le ricette su Instagram aspettano i risultati
|
||||
della sonda (ipotesi H1–H11, vedi [Ipotesi da verificare](Ipotesi-da-verificare)). Non è un guasto.
|
||||
1. **Ricetta «Da configurare».** Se in Attività vedi «non può girare su instagram: la mappa dei bersagli non è ancora
|
||||
compilata», è lo stato attuale del progetto per storie, raccolte e schede Taggati e Reel: aspettano i bersagli dei
|
||||
comandi (ipotesi H11, vedi [Ipotesi da verificare](Ipotesi-da-verificare)). Non è un guasto, e quelle ricette non
|
||||
vengono sospese.
|
||||
2. **Non collegato**, **verifica richiesta** o **sessione chiusa**: la barra laterale lo dice. Vedi
|
||||
[Primo collegamento](Primo-collegamento) e [Attività e arresti](Attivita-e-arresti).
|
||||
3. **Fuori fascia** o **giorno non attivo**: Attività dice «Fuori fascia» e quando riprende.
|
||||
|
||||
+79
-5
@@ -46,6 +46,61 @@ dotnet test tests/Febe.Tests --filter "FullyQualifiedName~Febe.Tests.Alerts"
|
||||
- La prova `Febe.Tests.Docs` controlla che questa guida dica tutto ciò che la specifica chiede (§15) e che ogni
|
||||
collegamento fra le pagine porti a una pagina che esiste.
|
||||
|
||||
## Da VS Code
|
||||
|
||||
La cartella `.vscode/` prepara VS Code per Febe: estensioni consigliate (C# Dev Kit e C#), soluzione predefinita
|
||||
`Febe.slnx`, attività e configurazioni di debug. Ogni configurazione compila prima con l'attività `compila`
|
||||
(`dotnet build Febe.slnx -warnaserror`); gli errori del compilatore finiscono nel pannello Problemi.
|
||||
|
||||
| Configurazione (Esegui e debug, F5) | Che cosa fa |
|
||||
|---|---|
|
||||
| Febe per Windows · sito di prova | Avvia il sito di prova come attività di sfondo (porte 8481 e 8482), poi Febe per Windows con `--sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 30 --sviluppo`; a fine debug ferma il sito |
|
||||
| Sito di prova + Febe per Windows | Il sito di prova nel debugger; quando è pronto parte anche Febe per Windows, che si ferma insieme al sito |
|
||||
| Febe Server · dimostrazione (--demo) | La dimostrazione su `http://127.0.0.1:8480`, che si apre da sola nel browser; l'interfaccia viene da `src/Febe.Web/wwwroot` (`FEBE_INTERFACCIA`): modifichi un file e ricarichi la pagina |
|
||||
| Sito di prova | Solo il sito di prova, nel debugger |
|
||||
| Simulazione 30 giorni (prudente) | `--simula 30g --profilo prudente`, con il resoconto nella Console di debug |
|
||||
| Febe Server · sito di prova (solo Linux) | Il server vero, con Chromium su Xvfb, contro il sito di prova: interfaccia su `127.0.0.1:8480`, password `prova` (come root serve anche `--senza-sandbox`, e `FEBE_CHROMIUM` se Chromium non è nel `PATH`). Su Windows e macOS si ferma con un messaggio; anche con «Esegui comunque il debug» stampa solo l'aiuto |
|
||||
| ⚠ Febe per Windows · Instagram vero (dati veri) | Febe senza opzioni: Instagram vero, `%LOCALAPPDATA%\Febe` e `Immagini\Febe`. Solo per le prove dal vivo di Alberto: chiede conferma, e una versione di sviluppo può aggiornare il database vero. Se Febe installato è aperto, prima esci da lui (menu dell'icona ▸ Esci): un solo Febe per cartella dei dati |
|
||||
|
||||
- **Dati di sviluppo.** Febe per Windows di sviluppo tiene dati e libreria in
|
||||
`%USERPROFILE%\FebeSviluppo\<checkout>\dati` e `%USERPROFILE%\FebeSviluppo\<checkout>\libreria`, dove `<checkout>` è
|
||||
il nome della cartella aperta in VS Code (per esempio `Febe`; il server su Linux in `~/FebeSviluppo/<checkout>`):
|
||||
fuori dal repository e mai nella cartella vera. Una cartella per checkout perché su una cartella dei dati gira un
|
||||
Febe solo (un secondo avvio mostra il primo ed esce) e un database scritto da un ramo più nuovo non si apre con una
|
||||
versione più vecchia. Con Febe chiuso si possono cancellare quando vuoi.
|
||||
- Chiudendo la finestra Febe resta nell'area di notifica e il debug continua: per finire, menu dell'icona ▸ Esci oppure
|
||||
Maiusc+F5. Finché Febe gira, `compila` non può sovrascrivere `Febe.exe`.
|
||||
- Il sito di prova usa sempre le porte 8481 e 8482, come attività e come configurazione: uno alla volta.
|
||||
- Se il sito di prova si ferma prima di Febe (terminale chiuso a mano, un guasto, oppure porta occupata e «Esegui
|
||||
comunque il debug»), a fine debug VS Code apre l'elenco delle attività da terminare, con «Termina tutte»: premi Esc.
|
||||
Con «Sito di prova + Febe per Windows» non succede, perché lì il sito sta nel debugger e non c'è un'attività da
|
||||
chiudere.
|
||||
- **Registro.** Nella Console di debug compaiono le righe del sito di prova, della dimostrazione, della simulazione e
|
||||
del server. Febe per Windows non ha una console: lì mostra solo i messaggi del debugger, e il suo registro sta nella
|
||||
cartella dei dati, `%USERPROFILE%\FebeSviluppo\<checkout>\dati\registro\febe-AAAA-MM-GG.log` (con il profilo di
|
||||
`launchSettings.json`, in `FebeSviluppo\comune\dati\registro`). Lì si leggono «Interfaccia sulla porta N», lo stato
|
||||
del browser di Febe e gli errori.
|
||||
- Le configurazioni usano la Console di debug e le attività partono senza shell: il terminale integrato carica il
|
||||
profilo di PowerShell, che può mettere davanti un altro .NET (per esempio quello di un ambiente conda), e allora
|
||||
`dotnet` non trova l'SDK 10 o Febe non parte («You must install or update .NET»). Se nel terminale
|
||||
`dotnet --list-sdks` non mostra il 10, usa le attività, Git Bash oppure `conda deactivate`.
|
||||
- Fermata dal debugger, la dimostrazione non cancella la sua cartella temporanea (`febe-dimostrazione-…`, una trentina
|
||||
di MB): da VS Code su Windows finisce in `%USERPROFILE%\FebeSviluppo\<checkout>\temporanei`, che si svuota quando
|
||||
vuoi. Con `dotnet run --project src/Febe.Server -- --demo` in un terminale, Ctrl+C la chiude in ordine e la cancella.
|
||||
- Fuori da queste configurazioni (`dotnet run --project src/Febe.Desktop`, il pulsante ▷ «Debug project associated
|
||||
with this file» e «Start New Instance» del C# Dev Kit, le sue configurazioni automatiche «C#: …») Febe per Windows
|
||||
prende l'unico profilo di `src/Febe.Desktop/Properties/launchSettings.json`: sito di prova su `http://127.0.0.1:8481`
|
||||
(da avviare a parte, per esempio con l'attività `sito di prova`) e dati in `%USERPROFILE%\FebeSviluppo\comune`, la
|
||||
stessa cartella per tutti i checkout. Instagram vero da un terminale solo con
|
||||
`dotnet run --project src/Febe.Desktop --no-launch-profile`: come la configurazione ⚠, è per le prove dal vivo di
|
||||
Alberto.
|
||||
- Attività (Terminale ▸ Esegui attività): `compila`, `prove` (`dotnet test tests/Febe.Tests`), `prove Windows`
|
||||
(`dotnet test tests/Febe.Tests.Windows`, WebView2 vero: solo su Windows), `prove con filtro`
|
||||
(chiede il filtro, per esempio `FullyQualifiedName~Febe.Tests.Docs`), `sito di prova`, `pubblica Febe.exe` (un file
|
||||
solo in `out/pubblicazione/`, come `installer/costruisci.sh`) e `immagine Docker (serve Docker Desktop)`.
|
||||
- I file di `.vscode/` sono JSON senza commenti, così li legge anche un lettore rigido come quello dei controlli della
|
||||
CI: le spiegazioni stanno in questa sezione, nei campi `detail` delle attività e in `docs/decisioni.md`.
|
||||
|
||||
## Dimostrazione
|
||||
|
||||
```sh
|
||||
@@ -129,12 +184,31 @@ da sole). Vedi [Installazione con Docker e Unraid](Installazione-Docker-e-Unraid
|
||||
## CI e rilascio
|
||||
|
||||
Il repository è sul Gitea di casa (<https://gitea.encke-hake.ts.net/Alby96/Febe>); la CI usa Gitea Actions in
|
||||
`.gitea/workflows/`:
|
||||
`.gitea/workflows/`, con il codice comune in `.gitea/scripts/`. Il processo completo (nomi dei rami, commit,
|
||||
richieste di unione, protezione di `main`, rilievi di sicurezza, rilasci, correzioni urgenti) è in `docs/processo.md`.
|
||||
|
||||
- `verifica.yml`, a ogni push e pull request: compilazione con gli avvisi come errori, tutte le prove, costruzione
|
||||
dell'immagine Docker (senza pubblicarla) e due controlli sull'immagine (Chromium presente, lingua italiana generata);
|
||||
- `rilascio.yml`, a ogni tag `vX.Y.Z`: immagine Docker sul registro di Gitea, installatore Windows e release. Al 13
|
||||
ottobre 2026 è in preparazione: se il file non c'è ancora in `.gitea/workflows/`, il rilascio non è automatico.
|
||||
- `verifica.yml`, a ogni push su qualunque ramo e a mano (non sui tag, non sulle richieste di unione, che mostrano lo
|
||||
stato del loro ultimo commit). Quattro lavori, che sono i controlli richiesti per unire in `main`:
|
||||
- `controlli`: sintassi degli script, file di testo, versione, progetti della soluzione, JSON, e nessun segreto in
|
||||
tutta la storia (gitleaks);
|
||||
- `prove`: compilazione di tutta la soluzione con gli avvisi come errori e tutte le prove di `tests/Febe.Tests` in
|
||||
un contenitore Debian con Chromium, Xvfb, ffmpeg, NSIS e Node veri: nessuna prova si salta;
|
||||
- `installatore`: `Febe-Setup-<versione>-ci.<numero>.exe` e lo zip portabile, fra gli artefatti per 14 giorni;
|
||||
- `immagine`, dopo l'installatore: l'immagine Docker, provata senza rete (parte, diventa «healthy», si ferma) e
|
||||
scansionata con Trivy; dopo un push su `main` va sul registro come `:main` e `:sha-<commit>`. Alla fine si toglie
|
||||
tutto ciò che l'esecuzione ha creato sul demone Docker, che è condiviso con gli altri progetti, e poi, di tutti, le
|
||||
immagini senza nome e la cache di costruzione che nessuno usa da 24 ore;
|
||||
- `rilascio.yml`, a ogni tag `vX.Y.Z`: prove, installatore e zip, immagine provata e scansionata, pubblicata come
|
||||
`:X.Y.Z` e `:latest` (solo per le versioni senza trattino), poi la release;
|
||||
- `pulizia.yml`, ogni lunedì e a mano: i resti delle esecuzioni interrotte e dei lavori di act_runner, le immagini che
|
||||
nessun contenitore usa e la cache di costruzione più vecchie di 24 ore, di tutti i progetti, e sul registro le
|
||||
`:sha-` oltre le 10 più recenti; mai un contenitore, un volume o una rete che non sia della CI. A mano, con «Solo
|
||||
prova», elenca che cosa toglierebbe e non toglie nulla (`docs/processo.md`, «Pulizia»).
|
||||
|
||||
Nella CI le prove del sito di prova (categoria `SitoDiProva`) girano due volte: con il seme 13 e con un seme diverso
|
||||
a ogni esecuzione, scritto nel registro del lavoro. Per rifare un errore con quel seme:
|
||||
`FEBE_SEME_PROVA=<seme> dotnet test tests/Febe.Tests --filter "TestCategory=SitoDiProva"`. I controlli veloci della
|
||||
CI si lanciano anche a mano: `bash .gitea/scripts/controlli.sh`.
|
||||
|
||||
La versione sta solo in `Directory.Build.props` (`<Version>`); il tag deve coincidere.
|
||||
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
# Processo: dal ramo al rilascio
|
||||
|
||||
Come una modifica arriva in `main` e da lì a una versione, con le stesse garanzie di un'azienda che non accetta codice
|
||||
non verificato. Vale per Alberto e per chiunque lavori al repository, persone o agenti. Repository: il Gitea di casa,
|
||||
<https://gitea.encke-hake.ts.net/Alby96/Febe> (non GitHub: niente strumenti di GitHub). Il motivo di ogni scelta è in
|
||||
`docs/decisioni.md`, alle righe del 20 ottobre 2026.
|
||||
|
||||
## In breve
|
||||
|
||||
1. Un ramo per filone di lavoro, nato da `main`.
|
||||
2. Commit piccoli e separati, ciascuno con un messaggio che dice che cosa cambia e perché.
|
||||
3. A ogni push la verifica parte da sola: controlli, prove, installatore, immagine.
|
||||
4. Una richiesta di unione per ramo, con il modello compilato, e una revisione.
|
||||
5. Si unisce in `main` solo con la verifica verde sull'ultimo commit (protezione di `main`), con un commit di unione;
|
||||
il ramo si cancella.
|
||||
6. Dopo l'unione la verifica gira su `main` e pubblica l'immagine `:main` e `:sha-<commit>`.
|
||||
7. Un rilascio è un tag `vX.Y.Z` su `main`.
|
||||
|
||||
## Rami
|
||||
|
||||
- Nome: `<tipo>/<argomento>`, in minuscolo, parole separate da trattini, in italiano. Tipi:
|
||||
|
||||
| Tipo | Per |
|
||||
|---|---|
|
||||
| `funzione/` | una funzione nuova (`funzione/esporta-csv`) |
|
||||
| `correzione/` | un difetto (`correzione/webview2-avvio`) |
|
||||
| `urgente/` | una correzione da rilasciare subito (vedi «Correzioni urgenti») |
|
||||
| `ci/` | flussi, script e immagini della CI (`ci/pipeline-aziendale`) |
|
||||
| `strumenti/` | strumenti di sviluppo (`strumenti/vscode`) |
|
||||
| `documenti/` | solo documenti e guida |
|
||||
| `rilascio/` | la preparazione di una versione (`rilascio/0.2.0`) |
|
||||
|
||||
- Si parte da `main` aggiornato e si resta brevi: giorni, non settimane. Se `main` va avanti, il ramo si aggiorna
|
||||
(pulsante «Aggiorna il ramo» della richiesta di unione, o `git merge origin/main`) prima di unire.
|
||||
- Su `main` non si fa push diretto: ci si arriva solo da una richiesta di unione.
|
||||
|
||||
## Commit
|
||||
|
||||
- Piccoli e logici: ogni commit compila e passa le prove da solo (così `git bisect` funziona).
|
||||
- Messaggio in italiano: la prima riga (al massimo 72 caratteri) dice che cosa cambia; il corpo, dopo una riga vuota,
|
||||
dice perché. Non un elenco di file.
|
||||
- I commit scritti con un agente finiscono con una riga vuota e `Co-Authored-By: …` dell'agente.
|
||||
- Mai nel repository: risultati di compilazione (`bin/`, `obj/`, `out/`), segreti, campioni grezzi della sonda, dati
|
||||
di Alberto.
|
||||
|
||||
## Richieste di unione
|
||||
|
||||
- Una per ramo, con il modello (`.gitea/pull_request_template.md`): sintesi, perché, che cosa cambia, come è stato
|
||||
provato (comandi e risultati, e che cosa non è stato provato), rischi e ritorno indietro, le quattordici regole di
|
||||
§2 della specifica. Le righe per `CHANGELOG.md` e `docs/stato.md` stanno nella richiesta: le aggiunge chi integra.
|
||||
- Revisione: Alberto è il proprietario di tutto (`.gitea/CODEOWNERS`). Le osservazioni si risolvono con commit nuovi
|
||||
sullo stesso ramo, non riscrivendo quelli già rivisti.
|
||||
- Stile di unione: **commit di unione** («Crea un commit di unione»), con il titolo della richiesta; poi il ramo si
|
||||
cancella («Elimina il ramo dopo l'unione», da tenere attivo nelle impostazioni del repository).
|
||||
- Tornare indietro: `git revert -m 1 <commit di unione>` in una nuova richiesta di unione.
|
||||
|
||||
## Controlli richiesti e protezione di main
|
||||
|
||||
I controlli richiesti sono i quattro lavori della verifica, come Gitea li riporta sul commit:
|
||||
`verifica / controlli (push)`, `verifica / prove (push)`, `verifica / installatore (push)`,
|
||||
`verifica / immagine (push)`. Una richiesta di unione mostra lo stato del suo ultimo commit, che il push del ramo ha
|
||||
già verificato: per questo la verifica non gira anche su `pull_request`.
|
||||
|
||||
Regola di protezione di `main` (Impostazioni ▸ Rami ▸ Aggiungi regola; la imposta chi integra, una volta che i
|
||||
quattro controlli sono comparsi almeno una volta):
|
||||
|
||||
| Impostazione | Valore |
|
||||
|---|---|
|
||||
| Schema del ramo | `main` |
|
||||
| Push | disattivato: solo da richiesta di unione |
|
||||
| Push forzato | disattivato |
|
||||
| Controllo di stato | attivo, con gli schemi `verifica / controlli (push)`, `verifica / prove (push)`, `verifica / installatore (push)`, `verifica / immagine (push)` |
|
||||
| Blocca l'unione se la richiesta è indietro rispetto al ramo di base | attivo: con il ramo aggiornato il commit di unione ha lo stesso contenuto del commit verificato |
|
||||
| Approvazioni richieste | 1 se le richieste le apre un account diverso da quello di Alberto; 0 se le apre lui (Gitea non conta l'approvazione dell'autore) |
|
||||
| Annulla le approvazioni superate da nuovi commit | attivo |
|
||||
| Blocca l'unione con revisioni che chiedono modifiche | attivo |
|
||||
| Anche gli amministratori seguono la regola | attivo |
|
||||
|
||||
E nei tag protetti (Impostazioni ▸ Tag): `v*` creabili solo da Alberto.
|
||||
|
||||
## La CI
|
||||
|
||||
Gitea Actions su un solo act_runner (etichetta `ubuntu-latest`, un lavoro alla volta). I lavori parlano con il demone
|
||||
Docker del server, lo stesso che costruisce Encelado, Mimante e gli altri progetti di Alberto. I flussi stanno in
|
||||
`.gitea/workflows/`, il codice comune in `.gitea/scripts/` (si lancia anche a mano).
|
||||
|
||||
| Lavoro | Quando | Che cosa garantisce |
|
||||
|---|---|---|
|
||||
| `controlli` | ogni push | sintassi di tutti gli script di shell (`bash -n`, `sh -n`) e righe Unix; flussi senza tabulazioni; nessun segno di conflitto; versione in `Directory.Build.props` valida; ogni progetto di `Febe.slnx` esiste; ogni JSON si legge; nessun segreto in tutta la storia (gitleaks 8.30.1, `--redact`) |
|
||||
| `prove` | dopo `controlli` | in un contenitore Debian 13 (`node:24-trixie`) con Chromium della distribuzione, Xvfb, ffmpeg, NSIS, Node e la lingua italiana: tutta la soluzione compila con gli avvisi come errori e **tutte** le prove di `tests/Febe.Tests` passano senza saltarsi; quelle della categoria `SitoDiProva` passano anche con il seme dell'esecuzione. Risultati `.trx` fra gli artefatti (14 giorni) |
|
||||
| `installatore` | dopo `prove` | `Febe.exe` in un file solo, `Febe-Setup-<versione>-ci.<numero>.exe` e lo zip portabile si costruiscono, ciascuno sotto i 100 MB; artefatti per 14 giorni |
|
||||
| `immagine` | dopo `installatore` (così `:main` e `:sha-` escono solo da un commit con tutta la verifica verde) | l'immagine si costruisce con buildx (dentro girano compilazione e prove), il contenitore parte **senza rete** come dice la guida e diventa «healthy», Chromium e la lingua italiana ci sono, si ferma entro 30 secondi; Trivy 0.75.0 non trova vulnerabilità CRITICAL con correzione disponibile. Solo dopo un push su `main`: pubblicazione `:main` e `:sha-<commit>` |
|
||||
|
||||
La verifica gira a ogni push su qualunque ramo e a mano (Actions ▸ verifica ▸ Esegui, con un seme facoltativo). Su un
|
||||
ramo un push nuovo annulla l'esecuzione in corso; su `main` ogni unione arriva fino in fondo. Un'esecuzione a mano non
|
||||
annulla mai quella di un push (l'evento fa parte del gruppo di concorrenza): solo il push scrive gli stati del commit
|
||||
che servono per unire, e un lavoro annullato lascerebbe lo stato «failure».
|
||||
|
||||
Altri flussi: `rilascio.yml` a ogni tag (vedi «Rilasci») e `pulizia.yml` ogni lunedì e a mano (vedi «Pulizia»).
|
||||
|
||||
### Il mondo sintetico e il suo seme
|
||||
|
||||
Le prove non contattano mai Instagram: usano il sito di prova (`tools/Febe.SitoDiProva`), con dati sintetici generati
|
||||
da un seme. Nella CI le prove girano con il seme 13 e quelle della categoria `SitoDiProva` di nuovo con il seme
|
||||
`1000 + numero dell'esecuzione`, scritto nel registro del passo «Semi del mondo sintetico». Per rifare un errore, in
|
||||
locale o dalla CI a mano con quel seme:
|
||||
|
||||
```sh
|
||||
FEBE_SEME_PROVA=<seme> dotnet test tests/Febe.Tests --filter "TestCategory=SitoDiProva"
|
||||
```
|
||||
|
||||
### Segreti e variabili
|
||||
|
||||
- `REGISTRY_TOKEN` (segreto del repository): token di Alberto con «package: read and write». Senza, `verifica` e
|
||||
`rilascio` costruiscono, provano e scansionano l'immagine ma non la pubblicano, con un avviso, e restano verdi.
|
||||
- `REGISTRY` (variabile, facoltativa): il registro come lo raggiunge il runner (`192.168.30.23:3000`); se manca si usa
|
||||
l'host dell'indirizzo del server Gitea.
|
||||
- Le credenziali vanno nella configurazione del client Docker del lavoro, mai nel demone, e si tolgono alla fine.
|
||||
Nessun flusso stampa segreti; `PipelineTests` lo controlla a ogni esecuzione.
|
||||
- I segreti sono leggibili da qualunque flusso di questo repository, su qualunque ramo: chi può fare push può leggerli.
|
||||
Per questo il permesso di scrittura sul repository resta ad Alberto e agli account di cui si fida.
|
||||
|
||||
## Registro dei container: le etichette
|
||||
|
||||
Sul registro di Gitea, `192.168.30.23:3000/alby96/febe`:
|
||||
|
||||
| Etichetta | Chi la crea | Quando cambia | Per che cosa |
|
||||
|---|---|---|---|
|
||||
| `:latest` | `rilascio`, solo versioni senza trattino | a ogni rilascio stabile | Unraid e Docker Compose |
|
||||
| `:X.Y.Z` | `rilascio` (anche `X.Y.Z-rc.1` per un'anteprima) | mai | una versione precisa, per tornare indietro |
|
||||
| `:main` | `verifica`, dopo ogni unione in `main` | a ogni unione (mai all'indietro) | provare `main` su un server di prova; non per l'archivio vero |
|
||||
| `:sha-<7 caratteri>` | `verifica`, dopo ogni unione in `main` | mai; restano le 10 più recenti | un commit preciso di `main` |
|
||||
|
||||
Ogni immagine della CI porta le etichette Docker `febe.ci.workflow`, `febe.ci.run`, `febe.ci.ref` e `febe.ci.commit`,
|
||||
oltre a quelle OCI del Dockerfile: da un'immagine si risale all'esecuzione e al commit. Docker le copia in ogni
|
||||
contenitore creato dall'immagine, anche in un Febe vero: per questo la pulizia non le usa mai per scegliere che cosa
|
||||
togliere (vedi «Pulizia»). Le `:sha-` non si accumulano: con il segreto `REGISTRY_TOKEN`, la pulizia del lunedì tiene le
|
||||
10 più recenti e toglie le altre; `:main`, `:latest` e le versioni restano sempre.
|
||||
|
||||
Perché togliere un'etichetta liberi davvero spazio, l'immagine si pubblica come un manifest semplice, senza attestazioni
|
||||
(`--provenance=false --sbom=false` in `.gitea/scripts/costruisci-immagine.sh`): in Gitea ogni etichetta è una versione
|
||||
del pacchetto che tiene la configurazione e gli strati, e i blob che nessuna versione usa più li cancella la pulizia dei
|
||||
pacchetti di Gitea stessa, ogni notte, quando hanno più di 24 ore (`[cron.cleanup_packages]`, attiva per impostazione
|
||||
predefinita). Con le attestazioni, che buildx aggiunge da sé, l'immagine sarebbe un indice: Gitea terrebbe ogni manifest
|
||||
figlio come una versione a sé, `sha256:…` senza etichetta, con gli strati, e togliere l'etichetta toglierebbe solo
|
||||
l'indice. La pulizia del lunedì non tocca mai le versioni `sha256:…` (l'API dei pacchetti non dice se un'etichetta le usa
|
||||
ancora) e scrive quante sono. Se ce ne sono (un'immagine spinta a mano, o con più piattaforme), quelle che nessuna
|
||||
etichetta usa più le toglie una regola di pulizia di Gitea, da impostare una volta sul proprietario del pacchetto
|
||||
(Impostazioni ▸ Pacchetti ▸ regole di pulizia): tipo container, attiva, schema delle versioni da rimuovere `sha256:.+`,
|
||||
più vecchie di 7 giorni (il valore più basso dopo lo zero, che toglierebbe anche un figlio appena spinto e non ancora
|
||||
rimandato dal suo indice), nessun numero da tenere. Gitea confronta lo schema con tutta la versione, salta da sé
|
||||
le versioni `sha256:` che un indice ancora rimanda e sempre `latest`, e applica la regola ogni notte; una regola non deve
|
||||
mai toccare `main` e le versioni.
|
||||
|
||||
## Pulizia
|
||||
|
||||
Il demone Docker è condiviso con gli altri progetti di Alberto e, molto probabilmente, con le applicazioni di Unraid; ci
|
||||
può girare anche un Febe vero, avviato da un'immagine che la CI ha pubblicato e che quindi porta le sue etichette
|
||||
`febe.ci.*`. Dal 21 ottobre 2026, per decisione di Alberto, la pulizia (`.gitea/scripts/pulizia-docker.sh`) toglie due
|
||||
cose: ciò che la CI di Febe può provare suo e ciò che non serve più a nessuno, di qualunque progetto. Mai un
|
||||
contenitore, un volume o una rete che non sia della CI.
|
||||
|
||||
Ciò che è della CI di Febe si riconosce da segni che nessuna immagine porta (le etichette `febe.ci.*` no: Docker le
|
||||
copia in ogni contenitore creato dall'immagine, anche in un Febe vero):
|
||||
|
||||
- contenitori di prova: l'etichetta `febe.ci.prova=<esecuzione>`, che mette solo `prova-immagine.sh` con
|
||||
`docker run --label` e che nessuna immagine porta (lo controlla `PipelineTests`), e insieme il nome esatto
|
||||
`febe-prova-<esecuzione>`;
|
||||
- immagini provate: il nome locale `febe-ci:<esecuzione>`, tolto per nome, mai per identificativo e mai con `-f`. Se la
|
||||
stessa immagine ha anche un nome del registro, quello resta; se un contenitore la usa, resta tutto;
|
||||
- builder buildx: il contenitore `buildx_buildkit_febe-ci-<esecuzione>0` con l'immagine `moby/buildkit` e il suo volume
|
||||
`…_state`.
|
||||
|
||||
Ciò che resta dei lavori di act_runner si riconosce dal nome che act_runner dà a tutto ciò che crea per un lavoro,
|
||||
`GITEA-ACTIONS-TASK-<numero del compito>…`: il contenitore del lavoro, i suoi volumi `<nome>` e `<nome>-env`, la sua
|
||||
rete `<nome>-<lavoro>-network`. Se ne vanno i contenitori fermi e i volumi e le reti che nessun contenitore usa, più
|
||||
vecchi di 90 minuti. Il volume `act-toolcache`, la cache degli strumenti condivisa fra i lavori, resta.
|
||||
|
||||
Ciò che non serve più a nessuno lo toglie Docker stesso (`docker image prune`, `docker builder prune`), che non toglie
|
||||
mai un'immagine usata da un contenitore, acceso o fermo: un'applicazione di Unraid ferma tiene la sua immagine. Se però
|
||||
quell'immagine ha più nomi, `image prune -a` le toglie quelli in più (vedi «Che cosa costa»).
|
||||
|
||||
| Quando | Che cosa si toglie |
|
||||
|---|---|
|
||||
| alla fine di ogni lavoro «immagine» (verifica e rilascio), sempre | il contenitore di prova con i suoi volumi anonimi, l'immagine provata, il builder buildx dell'esecuzione con la sua cache, l'archivio dell'immagine, le credenziali del registro; poi, di tutti i progetti, le immagini senza nome che nessun contenitore usa e la cache di costruzione penzolante del demone, cioè quella che nessuna immagine condivide, non usata da 24 ore (`pulizia-docker.sh penzolanti`). Un errore qui è solo un avviso: il lavoro non diventa rosso |
|
||||
| all'inizio di ogni lavoro «immagine» | i resti di esecuzioni interrotte più vecchi di 90 minuti (un lavoro dura al massimo 60 minuti): contenitori di prova **fermi**, immagini `febe-ci:`, builder; e ciò che ha lasciato un tentativo precedente della stessa esecuzione |
|
||||
| ogni lunedì alle 4:17 e a mano (`pulizia.yml`, `pulizia-docker.sh completa`) | gli stessi resti e l'immagine `febe:ci` del vecchio flusso; i resti di act_runner; **le immagini che nessun contenitore usa create più di 24 ore fa**, di tutti i progetti, anche col nome del registro; la cache di costruzione del demone non usata da più di 24 ore; con il segreto `REGISTRY_TOKEN`, sul registro le `:sha-` oltre le 10 più recenti. Prima e dopo `docker system df`, alla fine un riepilogo di che cosa è andato via |
|
||||
| mai | `docker system prune`, `container prune`, `volume prune`, `network prune`; un contenitore, un volume o una rete che non sia della CI: un Febe vero, anche se porta le etichette `febe.ci.*`, le applicazioni di Unraid, i volumi con i dati, `act-toolcache`; un contenitore di prova ancora acceso di un'altra esecuzione (si segnala con un avviso e il comando per toglierlo: il flusso del lunedì diventa rosso); un'immagine usata da un contenitore, anche fermo (i suoi nomi in più sì: vedi sotto); `image prune -a` e `builder prune -a` senza il filtro delle 24 ore; sul registro `:main`, `:latest` e le versioni `X.Y.Z` |
|
||||
|
||||
Che cosa costa:
|
||||
|
||||
- le immagini di base che fra un lavoro e l'altro nessun contenitore usa (`node:24-trixie` del lavoro «prove»,
|
||||
`moby/buildkit` dei builder, quelle dei lavori degli altri progetti) si riscaricano alla prima esecuzione che le
|
||||
chiede dopo il lunedì: qualche minuto e qualche centinaio di MB in più, una volta. L'immagine dei lavori
|
||||
(`ubuntu-latest`) resta, perché durante la pulizia la usa il lavoro stesso;
|
||||
- da quando contano le 24 ore delle immagini dipende dallo store delle immagini del demone, che la pulizia scrive
|
||||
all'inizio. Con lo store classico (il più probabile su Unraid) contano dalla costruzione dell'immagine: una
|
||||
scaricata ieri ma costruita un mese fa se ne va, e una costruita con una data fissa (costruzioni riproducibili,
|
||||
`SOURCE_DATE_EPOCH`) non è mai protetta dalla finestra. Con lo store di containerd (predefinito nelle installazioni
|
||||
nuove di Docker Engine dalla 29) contano da quando il nome è arrivato sul demone, e un nome riscaricato tiene la data di
|
||||
prima: un'immagine appena riscaricata con un nome che c'era già, e non ancora usata da un contenitore, se ne va. Con
|
||||
tutti e due, un'immagine scaricata e non ancora usata non è al sicuro. La prova dà sempre l'età dalla costruzione, e
|
||||
con containerd lo dice: lì il suo elenco è solo indicativo;
|
||||
- un'immagine costruita a mano e tenuta senza contenitore (per esempio quella di `docker build -t febe .`) se ne va e va
|
||||
ricostruita; una versione di Febe tenuta per tornare indietro si riscarica dal registro, dove `:X.Y.Z` resta;
|
||||
- un'immagine che un contenitore usa resta, ma se ha più nomi `image prune -a` le toglie quelli in più. Con lo store
|
||||
classico resta solo l'ultimo in ordine alfabetico del nome completo, anche quando il contenitore è stato creato da un
|
||||
altro: un'applicazione di Unraid creata da `app:1.2`, se la stessa immagine si chiama anche `app:latest`, continua a
|
||||
girare, ma in locale `app:1.2` non c'è più, e Unraid la mostra da aggiornare o la riscarica. Con lo store di
|
||||
containerd restano i nomi da cui i contenitori sono stati creati. Un Febe vero avviato da `:latest`, se la stessa
|
||||
immagine si chiama anche `:0.1.0`, perde `:0.1.0` e resta `:latest`. La prova elenca questi nomi e la pulizia vera li
|
||||
scrive uno per uno;
|
||||
- la cache di costruzione del builder del demone, con cui costruiscono gli altri progetti: resta quella usata nelle
|
||||
ultime 24 ore. Dopo ogni esecuzione di Febe se ne va quella che nessuna immagine condivide (strati intermedi, cache
|
||||
montate con `RUN --mount=type=cache`) e che nessuno usa da un giorno; il lunedì anche quella condivisa e quella
|
||||
interna di BuildKit, con lo stesso limite. Una costruzione che si ripete almeno una volta al giorno ritrova la sua
|
||||
cache; una più rara la rifà.
|
||||
|
||||
**Prova senza togliere nulla.** Actions ▸ pulizia ▸ Esegui, con «Solo prova» spuntato: il registro del lavoro elenca
|
||||
che cosa toglierebbe (le immagini con dimensione ed età, i nomi in più delle immagini in uso, la cache di costruzione, i
|
||||
resti della CI di Febe e di act_runner, le `:sha-` del registro) e non toglie nulla: solo comandi che leggono, e sul
|
||||
registro solo GET. Si lancia prima della prima pulizia vera e dopo ogni cambio dello script. Dal server, nella cartella
|
||||
del repository:
|
||||
`bash .gitea/scripts/pulizia-docker.sh completa --prova` (il registro solo con `REGISTRY_TOKEN`, `GITEA_API` e
|
||||
`PROPRIETARIO` nell'ambiente). Una prova scritta in un altro modo non diventa la pulizia vera: un'opzione diversa da
|
||||
`--prova` (`--dry-run`, `-n`, `--Prova`) o una parola in più (`prova` senza trattini) fermano lo script con codice 2
|
||||
prima che tocchi Docker, e il flusso accetta per «prova» solo `true` e `false` (un avvio con l'API che passa un altro
|
||||
valore, «True» o «1», si ferma con un errore). Le immagini, nella pulizia vera, le sceglie Docker; nella prova le stima
|
||||
lo script con la stessa regola.
|
||||
|
||||
`PipelineTests` fa girare la pulizia contro un demone finto (`tests/Febe.Tests/Packaging/fake-docker.sh`), con lo store
|
||||
classico e con quello di containerd, con un Febe vero acceso e uno fermo, applicazioni di Unraid accese e ferme (una con
|
||||
due nomi), il lavoro della pulizia stessa, resti veri e finti di act_runner, e contro un'API dei pacchetti finta
|
||||
(`fake-curl.sh`): controlla che cosa resta, che nessun comando vietato parta, che la prova non tocchi nulla e dica ciò
|
||||
che la pulizia vera poi toglie, che una prova scritta male si fermi, e che il token non finisca mai nel registro del
|
||||
lavoro.
|
||||
|
||||
## Rilievi di sicurezza
|
||||
|
||||
- **gitleaks** (lavoro `controlli`). Un segreto vero si **revoca subito** (gettone di Telegram da BotFather, token di
|
||||
Gitea dalle impostazioni dell'utente) e se ne crea uno nuovo: toglierlo dalla storia non basta, perché qualcuno può
|
||||
averlo già. Solo dopo, se serve, si riscrive la storia, d'accordo con Alberto. Un falso allarme (un dato di prova
|
||||
finto, già controllato) si toglie aggiungendo la sua impronta («Fingerprint», nel registro del lavoro o nel
|
||||
rapporto `rapporto-gitleaks`) a `.gitleaksignore`, con un commento sulla riga sopra: che cos'è, chi l'ha
|
||||
controllato, quando. Mai disattivare una regola.
|
||||
- **Trivy** (lavoro `immagine`, anche nel rilascio). Una vulnerabilità CRITICAL con correzione disponibile ferma il
|
||||
lavoro e l'immagine non si pubblica. Che cosa fare: per un pacchetto di Debian di solito basta rilanciare (il
|
||||
Dockerfile applica gli aggiornamenti della distribuzione); per una dipendenza .NET si aggiorna la sua versione in
|
||||
`Directory.Packages.props` (una dipendenza nuova va chiesta ad Alberto); per il runtime .NET si ricostruisce con
|
||||
l'SDK aggiornato. Le HIGH, e le CRITICAL ancora senza correzione, non fermano nulla ma si guardano nel rapporto
|
||||
`sicurezza-immagine` (`trivy.json`) e, se riguardano ciò che Febe usa, diventano una segnalazione. Un'eccezione si
|
||||
scrive solo in `.trivyignore`, alla radice: l'identificativo con una scadenza (`CVE-AAAA-NNNN exp:AAAA-MM-GG`, al
|
||||
massimo 90 giorni) e, sulla riga sopra, il motivo e chi l'ha deciso.
|
||||
- Strumenti: gitleaks e Trivy sono gli unici strumenti esterni della CI, approvati da Alberto, e girano solo nella
|
||||
CI. Si aggiornano cambiando versione e impronta SHA-256 in `.gitea/scripts/strumento.sh`, in una richiesta di
|
||||
unione con una riga in `docs/decisioni.md`, preferendo versioni uscite da almeno due settimane.
|
||||
|
||||
## Rilasci
|
||||
|
||||
1. In un ramo `rilascio/X.Y.Z`: `<Version>` in `Directory.Build.props`, la sezione `## X.Y.Z` di `CHANGELOG.md` (è il
|
||||
testo delle note della release), `docs/stato.md`. Richiesta di unione, verifica verde, unione.
|
||||
2. Sul commit di unione in `main`: `git tag -a vX.Y.Z -m "Febe X.Y.Z"` e `git push origin vX.Y.Z`.
|
||||
3. `rilascio.yml` controlla che il tag coincida con `<Version>`, rifà le prove, costruisce installatore e zip,
|
||||
costruisce, prova e scansiona l'immagine, la pubblica come `:X.Y.Z` (e `:latest` se la versione non ha trattini) e
|
||||
crea la release con installatore, zip, modello di Unraid e archivio per Compose.
|
||||
4. Un'anteprima è `vX.Y.Z-rc.N`: stessa strada, `:latest` non si sposta e la release è segnata come anteprima (come
|
||||
ogni versione `0.x`).
|
||||
5. Se manca `REGISTRY_TOKEN` la release esce senza immagine e lo dice; aggiunto il segreto, si rilancia il flusso del
|
||||
tag e le note si correggono.
|
||||
|
||||
## Correzioni urgenti
|
||||
|
||||
- Se `main` contiene solo ciò che si vuole rilasciare: ramo `urgente/<argomento>` da `main`, richiesta di unione con la
|
||||
verifica verde come sempre (nessuna scorciatoia), poi un rilascio di correzione (`X.Y.Z+1`) come sopra.
|
||||
- Se `main` contiene già lavoro da non rilasciare: ramo `rilascio/X.Y` dal tag della versione in uso, la correzione con
|
||||
`git cherry-pick` (o scritta lì), `<Version>` a `X.Y.Z+1`, tag `vX.Y.Z+1` su quel ramo (il rilascio parte da
|
||||
qualunque tag); poi la stessa correzione entra in `main` con la sua richiesta di unione.
|
||||
|
||||
## Che cosa solo la prima esecuzione vera può provare
|
||||
|
||||
Qui non ci sono runner né demone Docker: i flussi sono stati controllati come testo (struttura, espressioni, `bash -n`
|
||||
di ogni blocco `run`), gli script con un client Docker finto. Restano da vedere alla prima esecuzione: il contenitore
|
||||
`node:24-trixie` con le azioni dentro; le prove con il browser nel contenitore (nessuna saltata); `upload-artifact@v3`
|
||||
con `retention-days`; la concorrenza; il builder buildx con il nome dell'esecuzione; la prova del contenitore senza
|
||||
rete fino a «healthy»; il download e la scansione di Trivy (e se trova CRITICAL da correggere); gitleaks sulla storia;
|
||||
la pubblicazione su `main` con il segreto.
|
||||
|
||||
Della pulizia del 21 ottobre 2026 (script e API provati con un client Docker e un curl finti) restano da vedere: la
|
||||
casella «Solo prova» di Gitea che arriva al lavoro come «true»; i nomi che questo act_runner dà ai suoi contenitori,
|
||||
volumi e reti; che cosa la prova dice di togliere sul demone vero, da leggere prima della prima pulizia vera; poi la
|
||||
pulizia vera: `docker builder prune` passato a buildx con `BUILDX_BUILDER=default`, il tempo e lo spazio recuperato,
|
||||
le immagini riscaricate dopo; con il segreto, l'API dei pacchetti con `REGISTRY_TOKEN` (elenco a pagine e DELETE delle
|
||||
`:sha-`), e che dopo la prima pubblicazione con `--provenance=false --sbom=false` il pacchetto non abbia versioni
|
||||
`sha256:…` (la riga del registro nel lavoro della pulizia, o la pagina del pacchetto su Gitea); la pulizia di ogni
|
||||
esecuzione alla fine del lavoro «immagine».
|
||||
@@ -86,6 +86,110 @@ Quando i lettori e la mappa sono stati scritti sui campioni ripuliti, **cancella
|
||||
|
||||
---
|
||||
|
||||
## A bis. Bersagli e campioni dal browser di tutti i giorni (25 ottobre 2026)
|
||||
|
||||
Scopo: completare ciò che il file HAR del 21 ottobre non poteva dare. Quel file aveva solo le risposte **Fetch/XHR**
|
||||
(il filtro del pannello Rete era su «Fetch/XHR»): nessun documento, quindi nessun dato incorporato nelle pagine, e
|
||||
nessun attributo degli elementi (ruoli, nomi accessibili, collegamenti). Da lì sono venuti i lettori
|
||||
(`lettori.instagram.json`) e le pagine della mappa (`bersagli.instagram.json`), ma i **bersagli** sono ancora vuoti:
|
||||
«Storie di un account», «Raccolta in evidenza», «Taggati» e «Reel» si rifiutano di girare finché non ci sono (H11).
|
||||
Mancano anche le risposte della home, del profilo e della sua griglia, delle storie, delle schede, dell'elenco dei
|
||||
seguiti e di un post con più foto.
|
||||
|
||||
Si raccolgono le due cose nello stesso giro, dal browser che usi tutti i giorni, senza la sonda: un file HAR completo
|
||||
e i bersagli dei comandi che clicchi. **Navighi solo tu**: nessun programma clicca o apre pagine.
|
||||
|
||||
### A bis 1. Prima di cominciare
|
||||
|
||||
- Chrome su Windows, con Instagram aperto e l'accesso già fatto, come il 21 ottobre.
|
||||
- Una cartella **fuori da qualunque repository git**, per esempio `C:\febe-har\2026-10-25` (qui sotto
|
||||
`<cartella>`): lì vanno il file HAR, i campioni grezzi e il testo dei bersagli. Il file HAR contiene i cookie della
|
||||
sessione e i dati di altre persone: **non si invia mai** e non va nel repository (`febe-sonda da-har` rifiuta un
|
||||
file o una cartella dentro un repository).
|
||||
- Il file `tools/bersagli/raccogli-bersagli.js` del repository, aperto in un editor per copiarlo
|
||||
(`tools/bersagli/LEGGIMI.md` dice che cosa registra).
|
||||
- Come in tutta questa guida: se compare una verifica, un CAPTCHA o un avviso dell'account, **fermati**, risolvi a
|
||||
mano, annota l'ora e riferisci.
|
||||
|
||||
### A bis 2. Strumenti per sviluppatori
|
||||
|
||||
1. Con Instagram aperto premi **F12** (oppure Ctrl+Maiusc+I).
|
||||
2. Scheda **Rete**: spunta **Conserva log** e nel filtro dei tipi scegli **Tutti**, **non** «Fetch/XHR»: servono
|
||||
anche i documenti.
|
||||
3. Ricarica la pagina (**F5**) con il pannello aperto: così anche il primo documento della home finisce nel registro.
|
||||
4. Scheda **Console**: incolla tutto il contenuto di `raccogli-bersagli.js` e premi Invio. La prima volta Chrome può
|
||||
chiedere di scrivere una frase di conferma prima di accettare un incolla: scrivila come indica e incolla di nuovo.
|
||||
Deve comparire «Febe: raccolta dei bersagli attiva (sola lettura)».
|
||||
|
||||
Lo script legge soltanto: non clicca, non cambia la pagina, non manda nulla a nessuno, non legge cookie né le memorie
|
||||
del browser. A ogni clic la Console scrive «Febe: clic N registrato». Se la pagina si ricarica del tutto (F5, un
|
||||
indirizzo scritto a mano) la raccolta si perde: **incolla di nuovo lo script**.
|
||||
|
||||
### A bis 3. Che cosa fare, nell'ordine
|
||||
|
||||
Muoviti con calma, come al solito, e annota l'ora d'inizio di ogni passo. I comandi in **grassetto** sono quelli da
|
||||
cliccare: è il clic che registra ruolo e nome accessibile.
|
||||
|
||||
1. **Home.** Attendi il caricamento e scorri piano per una decina di post.
|
||||
2. **Un profilo.** Scrivi nella barra l'indirizzo di un profilo pubblico (è un caricamento completo, come quando Febe
|
||||
apre un profilo), poi **incolla di nuovo lo script** nella Console. Scorri la griglia per 3–4 schermate.
|
||||
3. **Le storie di un seguito.** Dal suo profilo clicca la **foto con l'anello**. Vai avanti di **due** storie
|
||||
cliccando la **zona a destra**. Prima che finiscano, chiudi con la **X**: non lasciare che il visualizzatore passi da
|
||||
solo all'account successivo.
|
||||
4. **Una raccolta in evidenza.** Da un profilo clicca una **raccolta**, vai avanti **una volta** con la zona a destra,
|
||||
chiudi con la **X**.
|
||||
5. **Le schede «Reel» e «Taggati»** di un profilo: clicca la **scheda** e scorri un poco, per ognuna.
|
||||
6. **I tuoi seguiti.** Dal tuo profilo clicca **«Seguiti»** e scorri l'elenco per 3–4 schermate.
|
||||
7. **Un post con più foto** (una serie): aprilo dalla griglia e passa alla foto successiva con la **freccia**.
|
||||
|
||||
Ci si aspetta: nessuna verifica, nessun avviso.
|
||||
|
||||
### A bis 4. Il testo dei bersagli
|
||||
|
||||
1. Nella Console scrivi `febeBersagli()` e premi Invio: i clic registrati vanno negli appunti e la Console dice
|
||||
quanti sono (se la copia non riesce, li scrive nella Console: copiali da lì).
|
||||
2. Incollali in un file di testo nuovo, per esempio `<cartella>\bersagli.txt`. Nei testi i nomi visti negli
|
||||
indirizzi e le `@parole` sono già diventati `NOME`, e negli indirizzi resta solo la forma (`/stories/<x>/<x>/`).
|
||||
**Leggi il file e sostituisci con `NOME` ogni nome di persona rimasto** (nomi scritti per esteso, frasi delle
|
||||
didascalie).
|
||||
|
||||
### A bis 5. Il file HAR
|
||||
|
||||
1. Scheda **Rete**: pulsante per **esportare il HAR** (la freccia verso il basso nella barra del pannello) e salva in
|
||||
`<cartella>\instagram.har`. Se Chrome offre due voci, scegli quella senza dati sensibili; se poi la conversione
|
||||
dice che le risposte sono «senza corpo», esporta di nuovo con l'altra voce.
|
||||
2. Chiudi gli strumenti per sviluppatori.
|
||||
|
||||
### A bis 6. Conversione, ripulitura e verifica (sulla tua macchina)
|
||||
|
||||
```sh
|
||||
febe-sonda da-har --har <cartella>\instagram.har --a <cartella>\grezzi
|
||||
febe-sonda ripulisci --da <cartella>\grezzi --a <cartella>\ripuliti
|
||||
febe-sonda verifica --grezzi <cartella>\grezzi --ripuliti <cartella>\ripuliti
|
||||
```
|
||||
|
||||
Dal repository: `dotnet run --project tools/Febe.Sonda -- da-har …`, e così per gli altri due.
|
||||
|
||||
- `da-har` scrive i campioni grezzi nello stesso formato della sonda, in una cartella **nuova** (rifiuta una cartella
|
||||
già usata). Tiene solo le risposte di dati del sito e i dati incorporati nei documenti; lascia fuori file, immagini,
|
||||
script e ogni altro sito; **non copia mai** intestazioni, cookie, parametri degli indirizzi o corpi delle richieste.
|
||||
Ogni file prende il nome dell'operazione GraphQL quando c'è (per esempio `000012-PolarisStoriesV3HighlightsPageQuery.json`),
|
||||
altrimenti `risposta` o `documento`: mai un pezzo di indirizzo, che può contenere un nome. Stampa solo conteggi.
|
||||
- `ripulisci` va lanciato **una volta sola su tutta la cartella**: i valori finti cambiano a ogni esecuzione.
|
||||
- La verifica deve dire **«Verifica superata»**. Se no, dice in quale file sopravvive un frammento (mai il frammento
|
||||
stesso): **cancella la cartella `ripuliti`**, non inviare nulla e riferisci il messaggio.
|
||||
|
||||
### A bis 7. Che cosa mandare
|
||||
|
||||
1. La cartella **ripulita** (compressa) e il testo della verifica.
|
||||
2. Il file `bersagli.txt`, con i nomi sostituiti.
|
||||
3. Le note: a che ora hai fatto ogni passo, che cosa è andato diversamente da come descritto.
|
||||
|
||||
Mai: il file HAR, la cartella `grezzi`, schermate con nomi di altre persone. Quando lettori e mappa sono stati scritti
|
||||
sui campioni ripuliti, **cancella il file HAR e la cartella `grezzi`** (§14.5).
|
||||
|
||||
---
|
||||
|
||||
## B. Prima sessione dal vivo, dopo M3
|
||||
|
||||
Scopo: vedere Febe fare una sessione vera, piccola, con il profilo **Prudente**, e i file arrivare in libreria.
|
||||
|
||||
+30
-20
@@ -1,24 +1,30 @@
|
||||
# Esito delle ipotesi di M0 (specifica §6.6)
|
||||
|
||||
Stato al 13 ottobre 2026. Finché una voce non ha un esito con le prove, **non ci si costruisce sopra**: per questo i
|
||||
file di Instagram sono ancora scheletri e le ricette si rifiutano di girare su Instagram (vedi in fondo).
|
||||
Stato al 25 ottobre 2026. Finché una voce non ha un esito con le prove, **non ci si costruisce sopra**.
|
||||
|
||||
**25 ottobre 2026: i primi campioni reali.** Alberto ha mandato un file HAR esportato dal suo browser il 21 ottobre
|
||||
(DevTools, filtro Fetch/XHR: niente documenti, immagini né script). Le risposte utili sono state convertite nel formato
|
||||
della sonda fuori dal repository, ripulite e verificate («Verifica superata»): sono in `tests/Febe.Tests/campioni/instagram`
|
||||
(vedi il suo `LEGGIMI.md`). Con quelle `lettori.instagram.json` è compilato e «confermato», e di
|
||||
`bersagli.instagram.json` sono compilate le pagine con una prova reale (vedi in fondo). Le colonne «Stato» qui sotto
|
||||
dicono che cosa il HAR ha provato e che cosa no.
|
||||
|
||||
Legenda: **provato in locale** = misurato su questa macchina con Chromium su Xvfb e pagine locali, mai Instagram;
|
||||
**da provare dal vivo** = serve Alberto, con l'account di prova e la sonda (`docs/prove-dal-vivo.md`, parte A).
|
||||
|
||||
| | Ipotesi | Stato | Come si prova (procedura esatta) | Che cosa ne dipende |
|
||||
|---|---|---|---|---|
|
||||
| H1 | La home consegna i post recenti dei seguiti con i dati completi dei file | **Da provare dal vivo** | Sonda, passo A3.1: aprire la home, attendere il caricamento, scorrere piano per una decina di post. Nei campioni ripuliti cercare risposte con elenchi di contenuti (identificativo, data, versioni delle immagini con dimensioni, figli delle serie) | Giro dei seguiti; `pages.home` di `bersagli.instagram.json`; concetti `content.*` e `version.*` di `lettori.instagram.json` |
|
||||
| H2 | La barra delle storie dice quali seguiti hanno storie attive e a quando risale l'ultima | **Da provare dal vivo** | Passo A3.1: con la home caricata, la sonda registra le risposte della barra; nei ripuliti cercare elenchi di profili con un campo data dell'ultima storia | `profile.latestStoryAt`; bersaglio `home-story` |
|
||||
| H3 | Il profilo consegna identificativo, pubblico/privato, se è seguito, prima pagina dei post con serie e video, elenco delle raccolte; lo scorrimento carica le pagine successive | **Da provare dal vivo** | Passi A3.2 e A3.3: profilo pubblico non seguito e profilo privato seguito, scorrendo 3–4 schermate. Nei ripuliti: un nodo profilo con i campi di stato, pagine di contenuti successive con un punto di ripresa | Controllo del profilo, Storico; `profile.*`, `highlight.*`, `page.*`; `pages.profile`, `pages.profileFrom` (facoltativa: se il sito non riparte da un cursore, lo storico riprende scorrendo) |
|
||||
| H4 | Aprendo il visualizzatore arriva l'elenco delle storie con gli indirizzi dei file, e si capisce qual è l'ultima | **Da provare dal vivo** | Passo A3.4: aprire le storie di un seguito dall'anello del profilo, guardarne 2–3, chiudere con la X **prima** che passi all'account successivo. Nei ripuliti: un elenco di contenuti con data di scadenza; in `navigazioni.jsonl` la forma dell'indirizzo del visualizzatore | Storie di un account; `content.expiresAt`; `pages.storyViewer`; bersagli `profile-story-ring`, `viewer-next`, `viewer-close` |
|
||||
| H5 | Per i video arriva almeno un indirizzo unico con audio e video insieme | **Da provare dal vivo** | Passi A3.2 e A3.4 su un post video e su una storia video. Nei ripuliti: le versioni del video e un campo che dica se hanno l'audio | `version.hasAudio`; scelta della versione di §6.5 punto 1 (se nessuna versione ha audio e video insieme, va riletta §4.9: l'unione delle tracce è fuori dalla versione 1) |
|
||||
| H6 | Le schede «taggati» e «reel» si comportano come la griglia | **Da provare dal vivo** | Passo A3.6: aprire le due schede di un profilo e scorrere | Taggati, Reel; bersagli `profile-tab-tagged`, `profile-tab-reels`; `pages.taggedFrom`, `pages.reelsFrom` |
|
||||
| H1 | La home consegna i post recenti dei seguiti con i dati completi dei file | **Da provare dal vivo**. Il HAR non contiene la home: nessuna risposta del feed | Sonda, passo A3.1: aprire la home, attendere il caricamento, scorrere piano per una decina di post. Nei campioni ripuliti cercare risposte con elenchi di contenuti (identificativo, data, versioni delle immagini con dimensioni, figli delle serie) | Giro dei seguiti; `pages.home` di `bersagli.instagram.json`; concetti `content.*` e `version.*` di `lettori.instagram.json` |
|
||||
| H2 | La barra delle storie dice quali seguiti hanno storie attive e a quando risale l'ultima | **Da provare dal vivo**. Il HAR non contiene la barra delle storie. La data dell'ultima storia di un profilo esiste come `latest_reel_media` (vista nell'autore di un post e nel proprietario di una raccolta) | Passo A3.1: con la home caricata, la sonda registra le risposte della barra; nei ripuliti cercare elenchi di profili con un campo data dell'ultima storia | `profile.latestStoryAt`; bersaglio `home-story` |
|
||||
| H3 | Il profilo consegna identificativo, pubblico/privato, se è seguito, prima pagina dei post con serie e video, elenco delle raccolte; lo scorrimento carica le pagine successive | **In parte**. Forma dell'indirizzo confermata (`/{username}/{?tab}/…`, dalle definizioni delle pagine che Instagram stesso manda); forma del nodo profilo confermata (`pk`, `username`, `is_private`, `friendship_status.following`, `hd_profile_pic_url_info`, `latest_reel_media`). Le risposte della pagina profilo (intestazione, griglia, raccolte, pagine successive) **non** sono nel HAR: da provare dal vivo | Passi A3.2 e A3.3: profilo pubblico non seguito e profilo privato seguito, scorrendo 3–4 schermate. Nei ripuliti: un nodo profilo con i campi di stato, pagine di contenuti successive con un punto di ripresa | Controllo del profilo, Storico; `profile.*`, `highlight.*`, `page.*`; `pages.profile`, `pages.profileFrom` (facoltativa: se il sito non riparte da un cursore, lo storico riprende scorrendo) |
|
||||
| H4 | Aprendo il visualizzatore arriva l'elenco delle storie con gli indirizzi dei file, e si capisce qual è l'ultima | **In parte**. Il visualizzatore delle raccolte riceve l'elenco completo dei contenuti con indirizzi, `taken_at` ed `expiring_at` (`xdt_api__v1__feed__reels_media__connection`, `text/javascript`); la forma dell'indirizzo delle storie è `/stories/{username}/{?initial_media_id}/`. La risposta delle storie di un account (non di una raccolta) e se l'indirizzo segue ogni storia: da provare dal vivo | Passo A3.4: aprire le storie di un seguito dall'anello del profilo, guardarne 2–3, chiudere con la X **prima** che passi all'account successivo. Nei ripuliti: un elenco di contenuti con data di scadenza; in `navigazioni.jsonl` la forma dell'indirizzo del visualizzatore | Storie di un account; `content.expiresAt`; `pages.storyViewer`; bersagli `profile-story-ring`, `viewer-next`, `viewer-close` |
|
||||
| H5 | Per i video arriva almeno un indirizzo unico con audio e video insieme | **In parte**. `video_versions` dà tre versioni `.mp4` (tipi 101, 102, 103: nei post stesse dimensioni e banda); se c'è l'audio lo dice il contenuto (`has_audio`), non la versione. Che il file abbia davvero audio e video insieme si conferma scaricando (prima sessione dal vivo) | Passi A3.2 e A3.4 su un post video e su una storia video. Nei ripuliti: le versioni del video e un campo che dica se hanno l'audio | `version.hasAudio`; scelta della versione di §6.5 punto 1 (se nessuna versione ha audio e video insieme, va riletta §4.9: l'unione delle tracce è fuori dalla versione 1) |
|
||||
| H6 | Le schede «taggati» e «reel» si comportano come la griglia | **Da provare dal vivo**. Nessuna risposta delle schede nel HAR | Passo A3.6: aprire le due schede di un profilo e scorrere | Taggati, Reel; bersagli `profile-tab-tagged`, `profile-tab-reels`; `pages.taggedFrom`, `pages.reelsFrom` |
|
||||
| H7 | I file del CDN si scaricano con `Network.loadNetworkResource`; se no, con la via di riserva di §6.5 | **Da provare dal vivo**. In locale: scaricati integri (24 MB in 2,2 s; foto e video del sito di prova byte per byte) | Dopo la sonda, con la prima sessione dal vivo (parte B): file arrivati in Libreria, stato «scaricato». **Osservazione locale**: dalla pagina di riposo `about:blank` Chromium rifiuta gli indirizzi locali del CDN di prova (`net::ERR_BLOCKED_BY_PRIVATE_NETWORK_ACCESS_CHECKS`); dalle pagine del sito funziona. Con il CDN pubblico va misurato se lo scaricamento regge anche dalla pagina di riposo | `BrowserFileFetcher`; la via `HttpClient` di §6.5 punto 3 **non è scritta**: resta dietro `IFileFetcher` finché H7 non dice che serve. Codici HTTP di «indirizzo scaduto» (in locale 403 e 410) |
|
||||
| H8 | I segnali di arresto si riconoscono da indirizzo e stato HTTP | **Da provare dal vivo** (non provocare segnali di proposito) | Se durante la sonda compare una verifica o un avviso, annotare l'ora e mandare la riga corrispondente di `navigazioni.jsonl` ripulita. Sul sito di prova i casi 429, `/verifica`, sessione terminata e pagine vuote fermano le ricette (prove `StopAndDownloadIntegrationTests`) | `segnali.json` (le regole su Instagram restano ipotesi segnate H8) |
|
||||
| H9 | Un contenuto di una raccolta ha lo stesso identificativo che aveva come storia | **Da provare dal vivo** | Passo A3.5: aprire una raccolta che contenga una storia ancora attiva (o pubblicata e poi messa in evidenza dall'account di prova). Confrontare gli identificativi nei ripuliti: la ripulitura dà a valori uguali lo stesso valore finto | Raccolta in evidenza (collegamento senza riscaricare); sul sito di prova funziona così per costruzione |
|
||||
| H10 | Identificativo e nome dell'account collegato si ricavano dai dati, senza leggere i cookie | **Da provare dal vivo** | Passo A3.1: nei ripuliti della home cercare un nodo che descriva l'account collegato | `viewer` di `lettori.instagram.json`; il profilo «Tu» |
|
||||
| H11 | I bersagli si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | **Da provare dal vivo**. Scheletro pronto: `bersagli.instagram.json` | Durante tutta la sonda: passare col puntatore e cliccare i comandi elencati al passo A3; la sonda registra ruolo, nome accessibile e forma del collegamento in `interazioni.jsonl`. Alberto manda le righe dei soli comandi dell'interfaccia (passo A6) | Tutte le ricette |
|
||||
| H8 | I segnali di arresto si riconoscono da indirizzo e stato HTTP | **Da provare dal vivo** (non provocare segnali di proposito). Nessun segnale nel HAR | Se durante la sonda compare una verifica o un avviso, annotare l'ora e mandare la riga corrispondente di `navigazioni.jsonl` ripulita. Sul sito di prova i casi 429, `/verifica`, sessione terminata e pagine vuote fermano le ricette (prove `StopAndDownloadIntegrationTests`) | `segnali.json` (le regole su Instagram restano ipotesi segnate H8) |
|
||||
| H9 | Un contenuto di una raccolta ha lo stesso identificativo che aveva come storia | **Indizio**. I contenuti di una raccolta hanno `pk` ed `expiring_at` come le storie; che il `pk` sia lo stesso della storia originale va visto con una storia ancora attiva | Passo A3.5: aprire una raccolta che contenga una storia ancora attiva (o pubblicata e poi messa in evidenza dall'account di prova). Confrontare gli identificativi nei ripuliti: la ripulitura dà a valori uguali lo stesso valore finto | Raccolta in evidenza (collegamento senza riscaricare); sul sito di prova funziona così per costruzione |
|
||||
| H10 | Identificativo e nome dell'account collegato si ricavano dai dati, senza leggere i cookie | **Non basta**. `xdt_viewer.user` descrive l'account collegato con il solo identificativo, senza nome: Febe lo tiene (`ReadResult.ViewerId`) e riconosce «Tu» quando il suo profilo compare in un'altra risposta. Da provare dal vivo | Passo A3.1: nei ripuliti della home cercare un nodo che descriva l'account collegato | `viewer` di `lettori.instagram.json`; il profilo «Tu» |
|
||||
| H11 | I bersagli si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | **Da provare dal vivo**. Il HAR non ha documenti né attributi degli elementi: i bersagli restano vuoti. Procedura semplificata in `docs/prove-dal-vivo.md`, parte A bis | Durante tutta la sonda: passare col puntatore e cliccare i comandi elencati al passo A3; la sonda registra ruolo, nome accessibile e forma del collegamento in `interazioni.jsonl`. Alberto manda le righe dei soli comandi dell'interfaccia (passo A6) | Tutte le ricette |
|
||||
| S1 | In WebView2 funzionano corpo delle risposte, gesti e fotogrammi | **Da provare** su Windows. Pronto: `WebView2Browser` (Febe.Desktop) con l'adattatore `WebView2CdpSession` (stesso elenco ammesso del client Chromium, provato su Linux con un finto WebView2) | `docs/prove-dal-vivo.md`, parte C3: Febe per Windows con `--sito-di-prova`, una sessione intera (`Network.getResponseBody`, `Input.dispatchMouseEvent`, `Network.loadNetworkResource`/`IO.read`) e l'anteprima di Attività (`Page.captureScreenshot`). `Page.startScreencast` su Windows non serve (la vista remota è solo di Docker) | `WebView2Browser`, `WebView2CdpSession` |
|
||||
| S2 | Su Windows la pagina carica e scorre con la finestra fuori vista | **Da provare** su Windows. Pronti i tre modi di §6.6, scelti con `Febe.exe --browser finestra\|composizione\|edge` (predefinito `finestra`: fuori dallo schermo, `IsVisible` sempre vero, `--disable-features=CalculateNativeWinOcclusion --disable-backgrounding-occluded-windows`) | `docs/prove-dal-vivo.md`, parte C4: sessione sul sito di prova con il browser fuori vista, con la finestra di Febe ridotta a icona e con lo schermo bloccato; se non regge, `composizione` e poi `edge` | `WebView2Browser`, `CompositionHost`, `EdgeBrowser` |
|
||||
| S3 | L'accesso a mano sopravvive al riavvio | **Provato in locale per Docker/Chromium** (cookie scritto con arresto SIGINT, 3 esecuzioni su 3; vedi `esito-locale.md`); **da provare** su Windows (all'arresto Febe chiude WebView2 e ne aspetta l'uscita prima di finire) e nel contenitore vero | Docker: accedere, riavviare il contenitore, controllare il collegamento. Windows: `docs/prove-dal-vivo.md`, parti C3.7 (sito di prova) e C5 (Instagram, account di prova: Esci e riapri, riavvio di Windows, avvio con il computer) | Profilo del browser nella cartella dei dati |
|
||||
@@ -28,14 +34,18 @@ Legenda: **provato in locale** = misurato su questa macchina con Chromium su Xvf
|
||||
|
||||
## Che cosa è pronto per ricevere gli esiti
|
||||
|
||||
- `src/Febe.Core/Config/bersagli.instagram.json` (copiato in `config/`): **scheletro**. Elenca le pagine e i bersagli
|
||||
di cui le ricette hanno bisogno, tutti vuoti e segnati con l'ipotesi da cui dipendono. Finché una voce necessaria è
|
||||
vuota, la ricetta risponde «non può girare su instagram: la mappa dei bersagli non è ancora compilata (mancano …)»
|
||||
senza aprire pagine e senza chiedere permessi.
|
||||
- `src/Febe.Core/Config/lettori.instagram.json`: **ipotesi**. Contiene solo gli indizi di §6.4 (`pk`, `code`,
|
||||
`taken_at`, `image_versions2.candidates`, `video_versions`, `carousel_media`); ogni altro concetto è vuoto. Con lo
|
||||
stato «ipotesi» le ricette non girano. Va riempito sui campioni ripuliti e portato a «confermato».
|
||||
- `src/Febe.Core/Config/lettori.instagram.json`: **confermato** il 25 ottobre sui campioni reali ripuliti; ogni sua
|
||||
chiave compare in quei campioni (lo controlla `InstagramReaderTests`). Le risposte che non parlano di contenuti
|
||||
(promozioni, «storia vista») si ignorano (`relevance`). Senza riscontro restano vuoti `pinned`, `postCount` e
|
||||
`version.hasAudio`; le serie (`carousel_media`) sono una chiave vista ma sempre vuota nei campioni.
|
||||
- `src/Febe.Core/Config/bersagli.instagram.json`: compilate le **pagine** con una prova reale (home, profilo, post,
|
||||
visualizzatore delle storie e delle raccolte, dalle definizioni delle pagine e dai Referer del HAR); i **bersagli**
|
||||
sono vuoti (H11). Le ricette che non ne hanno bisogno girano; quelle che li usano (storie, raccolte, schede Taggati e
|
||||
Reel) rispondono «la mappa dei bersagli non è ancora compilata (mancano …)» senza aprire pagine e senza chiedere
|
||||
permessi. Questi file si possono sostituire con una copia nella cartella Dati, che vince su quella incorporata.
|
||||
- La cattura legge anche le risposte `text/javascript` chieste dalla pagina (così Instagram manda i dati GraphQL) e il
|
||||
JSON incorporato nel documento della pagina (da confermare dal vivo: il HAR non aveva documenti).
|
||||
- `segnali.json`: regole di partenza, ancora ipotesi H8.
|
||||
- Sonda: `febe-sonda registra`, `ripulisci`, `verifica` (procedura in `docs/prove-dal-vivo.md`).
|
||||
- Sonda: `febe-sonda registra`, `da-har` (da un HAR del browser), `ripulisci`, `verifica` (procedura in `docs/prove-dal-vivo.md`).
|
||||
- Il sito di prova fa girare tutte le ricette con un browser vero (`tests/Febe.Tests/Collection/`): è la prova che la
|
||||
raccolta funziona **quando** mappa e vocabolario saranno compilati, non che Instagram si comporti allo stesso modo.
|
||||
+132
-10
@@ -1,10 +1,64 @@
|
||||
# Stato
|
||||
|
||||
Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché.
|
||||
Aggiornato il 13 ottobre 2026, versione 0.1.0 (anteprima).
|
||||
Aggiornato il 25 ottobre 2026, versione 0.1.1 (anteprima), 0.1.2 in preparazione.
|
||||
|
||||
## In breve
|
||||
|
||||
**25 ottobre 2026: Febe legge le risposte vere di Instagram** (ramo `correzione/lettura-instagram`).
|
||||
|
||||
- **Il guasto**: Instagram manda i dati di storie e raccolte (GraphQL) come `text/javascript`, e la cattura leggeva
|
||||
solo le risposte dichiarate JSON: le scartava tutte. In più `lettori.instagram.json` e `bersagli.instagram.json` erano
|
||||
scheletri e le ricette si rifiutavano di girare.
|
||||
- **I campioni**: Alberto ha mandato un HAR del suo browser (21/10, filtro Fetch/XHR) e una guida. La guida descrive
|
||||
richieste costruite a mano, vietate dalle regole 2–4, e un formato che nel HAR non compare: non si è usata. Del HAR si
|
||||
è letta solo la forma; le 8 risposte utili, accorciate dal lato grezzo, ripulite e verificate («Verifica superata»),
|
||||
sono in `tests/Febe.Tests/campioni/instagram` (vedi il suo `LEGGIMI.md`). I grezzi convertiti sono stati cancellati.
|
||||
- **Che cosa cambia**: la cattura legge le risposte `text/javascript` chieste dalla pagina e il JSON incorporato nel
|
||||
documento (questo da confermare: il HAR non aveva documenti); le risposte che non parlano di contenuti si ignorano;
|
||||
il vocabolario di Instagram è «confermato» e ogni sua chiave compare nei campioni; la mappa ha le pagine viste nel
|
||||
traffico vero, i bersagli no. Le ricette del profilo reggono dati che arrivano in risposte diverse; il visualizzatore
|
||||
delle raccolte conta i contenuti (l'indirizzo non cambia); le ricette che la configurazione non lascia girare sono
|
||||
«Da configurare», non guasti, e le sospensioni dovute ai file vecchi si azzerano da sole al primo avvio.
|
||||
- **Che cosa gira su Instagram**: giro dei seguiti, controllo del profilo, storico, post singolo. **Non ancora**:
|
||||
storie, raccolte, Taggati, Reel (mancano i bersagli, H11) ed elenco dei seguiti (manca l'indirizzo). Nulla è stato
|
||||
provato dal vivo.
|
||||
- **Strumenti per Alberto**: `febe-sonda da-har` (HAR → campioni grezzi, poi `ripulisci` e `verifica`) e
|
||||
`tools/bersagli/raccogli-bersagli.js` (bersagli in sola lettura dalla Console); procedura in
|
||||
`docs/prove-dal-vivo.md`, parte A bis.
|
||||
- **Cancellazione automatica delle immagini delle Actions**: era già attiva dal 21/10 (ogni lavoro «immagine» toglie la
|
||||
sua immagine e le penzolanti; ogni lunedì la pulizia completa, la prima vera lunedì 26/10 alle 4:17). Nulla da
|
||||
cambiare. L'immagine si pubblica sul registro solo con `REGISTRY_TOKEN`, che manca ancora.
|
||||
- Lavoro fatto da più agenti in parallelo, ciascuno su un ramo di lavoro, poi revisione avversaria: 21 rilievi, 17
|
||||
confermati e corretti (uno solo in parte, vedi sotto), e un solo commit. Prove: 783 superate, 76 saltate su Windows
|
||||
(Chromium e Xvfb), da rivedere nella CI.
|
||||
|
||||
**21 ottobre 2026.**
|
||||
|
||||
- **0.1.1 rilasciata**: tag `v0.1.1`, release con installatore, zip portabile, modello Unraid e archivio per Compose.
|
||||
L'immagine Docker non è pubblicata, perché `REGISTRY_TOKEN` manca ancora.
|
||||
- **La pulizia della CI toglie tutto ciò che non serve più** (decisione di Alberto). Dopo ogni lavoro «immagine» se ne
|
||||
vanno le immagini senza nome e la cache di costruzione che nessuno usa da 24 ore: la prima volta 26,31 GB. Ogni
|
||||
lunedì se ne vanno le immagini che nessun contenitore usa, la cache vecchia, i resti di act_runner e le `:sha-` oltre
|
||||
le 10 più recenti. Mai contenitori, volumi o reti che non siano della CI. A mano c'è «Solo prova» (`docs/processo.md`,
|
||||
«Pulizia»).
|
||||
- Le tre prove d'interfaccia trovate instabili dalla CI con Chromium vero sono stabili (#3 e #5 il 20/10, #8 il 21/10).
|
||||
Le prove d'interfaccia non usano più pause a tempo fisso.
|
||||
|
||||
**20 ottobre 2026.** Febe per Windows non riusciva a collegarsi: il browser di Febe non diventava mai pronto (registro di
|
||||
Alberto del 14 e del 19/10). Era un errore di thread, corretto. Febe per Windows ha girato per la prima volta su un
|
||||
Windows vero: collegamento, account e sessioni contro il sito di prova, dall'interfaccia. Lo stesso giorno sono arrivati:
|
||||
|
||||
- la CI da grande azienda (`docs/processo.md`), con prove con Chromium vero, installatore e immagine a ogni push,
|
||||
gitleaks, Trivy e pulizia;
|
||||
- lo sviluppo da VS Code;
|
||||
- le prove verdi anche su Windows;
|
||||
- altre tre correzioni trovate provando: lo storico completato doppio o bloccato, la vista remota durante un cambio di
|
||||
pagina, il pannello «Collegato come @».
|
||||
|
||||
Il lavoro è su sei rami, ciascuno con la sua revisione avversaria, unito in `main` con la PR #2 (CI), la PR
|
||||
d'integrazione #4, la #6 e la #7 (rilascio 0.1.1). Il 21/10 sono seguite la #9 (pulizia) e la #10 (prove d'interfaccia).
|
||||
|
||||
Tutte le tappe M0–M8 sono state realizzate in una volta, su richiesta di Alberto del 13 ottobre 2026, sul ramo
|
||||
`febe-v1`. Il programma è completo e provato **contro il sito di prova locale** (§14.2) con un Chromium vero su Xvfb.
|
||||
**Non ha mai contattato Instagram** (regola 9): per questo le ricette, per costruzione, **si rifiutano di girare su
|
||||
@@ -21,24 +75,92 @@ Instagram** finché la sonda di M0 non ha prodotto i campioni da cui compilare `
|
||||
| M3 | Governatore, interruttore, fascia, sessioni, composizione, avvio graduale, cruscotto, simulazione | Prove del motore verdi; `--simula 30g` per i tre profili: **zero superamenti**, nessuna azione fuori fascia, nessuna pausa sotto il pavimento. **Arresto di M3**: Alberto legge i numeri (`docs/decisioni.md` e il resoconto della simulazione) |
|
||||
| M4 | API, eventi, ossatura, tutte le schermate, tema scuro, finestra stretta, modalità dimostrativa | Schermate confrontate con i mockup (`docs/schermate/`, differenze in `docs/schermate/differenze.md`); gli originali di 02, 04–07, 09, 11–14 non sono stati forniti: confronto sui ritagli della panoramica |
|
||||
| M5 | Composizione reale, vista remota, password, pagina di errore, `/salute`, Dockerfile, compose, modello Unraid | Prova d'insieme del server reale contro il sito di prova; immagine costruita dalla CI sul runner; **non provata su Unraid** |
|
||||
| M6 | Febe per Windows (WPF, WebView2Host, area di notifica, funzioni native), installatore NSIS | `Febe.exe` (file unico) e `Febe-Setup-0.1.0.exe` costruiti su Linux; **mai eseguiti su Windows**: S1–S3 da provare (`docs/prove-dal-vivo.md`, parte C) |
|
||||
| M6 | Febe per Windows (WPF, WebView2Host, area di notifica, funzioni native), installatore NSIS | `Febe.exe` (file unico) e `Febe-Setup-0.1.0.exe` costruiti su Linux. **20/10, su Windows 11 (WebView2 155)**: «Browser di Febe pronto» al primo tentativo; S1 e una sessione di raccolta nelle 11 prove di `tests/Febe.Tests.Windows`. Dall'interfaccia, contro il sito di prova: collegamento, due account, «Controlla ora», 47 file in libreria, sessioni con il browser fuori vista (S2, primo caso), sessione ritrovata dopo un riavvio (S3, primo caso). **Dal vivo, 20/10 alle 19:30** (C5.1, Alberto con l'account di prova, Febe da `main`): accesso riuscito, «Sessione presente nel browser: collegato», nessuna verifica né azione del motore su Instagram. **Da provare**: C5.2–C5.5 (Esci e riapri, riavvio di Windows, avvio con il computer, Scollega), S2 con la finestra ridotta a icona e con lo schermo bloccato, l'installatore su un Windows pulito (C2) |
|
||||
| M7 | Importazione in quattro passi, riconoscitori, doppioni, copia verificata | Prove di importazione verdi; riconoscitore 4K Stogram solo come ipotesi (domanda 4 di §16) |
|
||||
| M8 | Avvisi (interfaccia, notifiche di Windows, Telegram), esportazione CSV, guida | Un arresto simulato produce striscia, notifica e messaggio (prova automatica con canali finti); guida in `docs/guida/`, pubblicata nel wiki |
|
||||
|
||||
Revisione avversaria completata il 14 ottobre (54 rilievi confermati e corretti, vedi `docs/decisioni.md`).
|
||||
|
||||
Prove automatiche: `dotnet test tests/Febe.Tests` — 750 prove, tutte verdi (le prove con il browser vero si
|
||||
saltano da sole dove mancano Chromium e Xvfb, come sul runner della CI).
|
||||
Prove automatiche:
|
||||
|
||||
- `dotnet test tests/Febe.Tests`, nella CI dal 20/10 dentro un contenitore Debian con Chromium, Xvfb, ffmpeg e NSIS:
|
||||
tutte girano, **nessuna saltata** (prima, sul runner, se ne saltavano 66). Le prove del sito di prova girano una
|
||||
seconda volta con il seme `1000 + numero dell'esecuzione`.
|
||||
- Su Windows le prove con Chromium e Xvfb si saltano, e nessuna fallisce.
|
||||
- `dotnet test tests/Febe.Tests.Windows` (solo Windows): 11 prove con WebView2 vero.
|
||||
|
||||
CI: ogni push su ogni ramo passa da quattro controlli (controlli, prove, installatore, immagine). Il processo e la
|
||||
protezione di `main` sono in `docs/processo.md`.
|
||||
|
||||
## Da fare (di Alberto)
|
||||
|
||||
1. **Sonda di M0** con l'account di prova (domanda 2 di §16): `docs/prove-dal-vivo.md`, parte A. Poi mandare i
|
||||
campioni **ripuliti** e le righe di `interazioni.jsonl` dei comandi dell'interfaccia: con quelli si compilano
|
||||
`bersagli.instagram.json` e `lettori.instagram.json` e si portano le ipotesi H1–H11 a un esito.
|
||||
2. **Prima sessione dal vivo** dopo la sonda, con il profilo Prudente su un profilo pubblico (parte B).
|
||||
3. **Windows**: S1–S3 (parte C). **Docker su Unraid**: S3–S6 nel contenitore vero.
|
||||
1. **Bersagli e campioni dal browser di tutti i giorni** (`docs/prove-dal-vivo.md`, parte A bis, una decina di
|
||||
minuti): HAR con il filtro «Tutti» e «Conserva log», lo script `tools/bersagli/raccogli-bersagli.js` nella Console,
|
||||
poi `febe-sonda da-har`, `ripulisci`, `verifica`. Mandare solo la cartella ripulita e il testo dei bersagli: con
|
||||
quelli si compilano i bersagli di storie, raccolte, Taggati e Reel e si confermano la home, il profilo e le storie
|
||||
di un account (H1–H4, H6, H11). In alternativa la sonda (parte A).
|
||||
2. **Prima sessione dal vivo** con il profilo Prudente su un profilo pubblico (parte B): già possibile per giro dei
|
||||
seguiti, controllo del profilo, storico e post singolo. Da guardare: i file in Libreria (H5, H7), «Tu» riconosciuto
|
||||
(H10), nessun «formato non riconosciuto» in Attività.
|
||||
3. **Windows**: C5.2–C5.5 (C5.1, l'accesso con l'account di prova, è riuscito il 20/10), S2 con la finestra ridotta a
|
||||
icona e con lo schermo bloccato, C2 (installatore della 0.1.1 su un Windows pulito). **Docker su Unraid**: S3–S6 nel contenitore
|
||||
vero.
|
||||
4. Le domande aperte di §16 (sono state adottate le proposte della terza colonna, vedi `docs/decisioni.md`).
|
||||
5. Il segreto `REGISTRY_TOKEN` nel repository, perché il rilascio pubblichi l'immagine sul registro di Gitea.
|
||||
5. Il segreto `REGISTRY_TOKEN` nel repository: senza, la CI e il rilascio costruiscono, provano e scansionano
|
||||
l'immagine, ma non la pubblicano (lo dicono con un avviso), e la pulizia non tocca il registro. Il 21/10 mancava
|
||||
ancora. Aggiunto il segreto, si rilancia il flusso del tag `v0.1.1`: l'immagine esce e le note della release si
|
||||
correggono.
|
||||
6. Sicurezza dell'istanza Gitea: la registrazione è aperta, senza CAPTCHA, con quattro account creati da programmi fra
|
||||
agosto e settembre. Il runner `fa94b0298b8d` è registrato per tutta l'istanza e i suoi lavori parlano con il Docker
|
||||
dell'host, quindi un utente registrato potrebbe farci girare un suo flusso. Si consiglia di chiudere la registrazione
|
||||
(`[service] DISABLE_REGISTRATION = true`) o di registrare il runner per il solo utente o repository.
|
||||
7. **Pulizia**: leggere l'elenco della prova del 21/10 (Actions ▸ pulizia, esecuzione #28, «Solo prova») prima della
|
||||
prima pulizia vera, lunedì 26/10 alle 4:17. Attenzione soprattutto allo store delle immagini scritto all'inizio e
|
||||
alle righe «toglierei il nome …» delle immagini in uso con più nomi (app di Unraid).
|
||||
8. Da decidere:
|
||||
- dopo ogni esecuzione la cache di costruzione si toglie solo se nessuno la usa da 24 ore (`--filter until=24h`).
|
||||
Senza filtro, a ogni push se ne andrebbe anche quella appena usata dagli altri progetti; per cambiare basta togliere
|
||||
il filtro in `pulizia-docker.sh penzolanti`;
|
||||
- gli script di shell di `.gitea/` e `installer/` hanno i commenti in italiano, contro «codice e commenti in
|
||||
inglese»: o un'eccezione in `docs/decisioni.md`, o una traduzione in un ramo a parte.
|
||||
|
||||
## Rilievi aperti (20 ottobre)
|
||||
|
||||
- Il motore e le ricette scrivono due righe per lo stesso fatto anche per «formato-non-riconosciuto», e solo nella
|
||||
cronologia per «bersaglio-non-trovato» e «ricetta-fallita». La notifica è una sola. Visto leggendo il codice, da
|
||||
correggere in un cambio a parte, come «storico-completato».
|
||||
- Su Windows il controllo «cartella dei dati in rete» non segue un collegamento simbolico verso una condivisione. Visto
|
||||
leggendo il codice, non provato.
|
||||
- Trivy, nell'immagine del 20/10: una CRITICAL (`libxml2`, CVE-2026-6653) e 246 HIGH, nessuna con una correzione di
|
||||
Debian. La CI si fermerà da sola quando la correzione esisterà e non sarà ancora applicata.
|
||||
- La prima sessione dopo il collegamento: se il primo giro programmato trova Febe senza account, conta come sessione
|
||||
(vuota) e quella vera arriva dopo la pausa minima, circa 20 minuti. È il comportamento della specifica, ma chi ha
|
||||
appena collegato Febe aspetta.
|
||||
|
||||
## Rilievi aperti (25 ottobre)
|
||||
|
||||
- Nessuna di queste modifiche è stata provata con Instagram: la prima sessione dal vivo (parte B) dirà se i dati del
|
||||
primo schermo arrivano nel documento o con XHR, se i file video hanno l'audio (H5) e se si scaricano (H7).
|
||||
- I blocchi JSON dei documenti di Instagram non si sono mai visti (il HAR non aveva documenti): forma e ordine ignoti.
|
||||
Le regole di testo di `segnali.json` ora li guardano uno per uno; un falso segnale si vedrebbe in Attività.
|
||||
- Visualizzatore senza identificativo nell'indirizzo (le raccolte): un clic «avanti» che la pagina ignora non si vede,
|
||||
e il conteggio salverebbe un contenuto non mostrato; una foto che il sito lascia da sola fa restare indietro il
|
||||
conteggio. Da misurare quando i bersagli ci saranno. Con le storie l'indirizzo dice quale storia è a video, se
|
||||
Instagram lo aggiorna (da confermare con lo script dei bersagli).
|
||||
- Un account Instagram senza post resta con lo storico aperto: a ogni sessione costa un'attesa di 20 s e una pagina.
|
||||
- Il pannello «Con queste impostazioni» di un profilo non seguito conta le visite all'intervallo delle storie anche
|
||||
mentre le storie non possono girare (sovrastima).
|
||||
- «Post singolo» accodati per gli indirizzi scaduti ora girano davvero (prima la coda li annullava): dentro il loro
|
||||
tetto, ma sono azioni in più su Instagram.
|
||||
|
||||
## Rilievi aperti (21 ottobre)
|
||||
|
||||
- Le note della release scritte da `rilascio.yml` senza immagine dicono «`:latest` resta sulla versione precedente», ma
|
||||
sul registro un'immagine precedente non c'è mai stata. Da riformulare per il caso della prima pubblicazione.
|
||||
- Un solo timeout di `OpenAsync` all'apertura di `/browser` (`AfterHoFinitoLeavingTheBrowserPageChangesNothingMore`) in
|
||||
migliaia di esecuzioni delle prove d'interfaccia, senza causa trovata. Se ricompare nella CI, va fatto dire a
|
||||
`OpenAsync` quale condizione mancava.
|
||||
- Su questo PC Febe ha avvisato «Disco quasi pieno»: libreria e dati stanno su C:, dove restano circa 12 GB.
|
||||
|
||||
## Rimandato, e perché
|
||||
|
||||
|
||||
+58
-5
@@ -8,10 +8,23 @@ un'applicazione per Windows 10 e 11. La finestra di Febe mostra l'interfaccia; i
|
||||
> rischio per l'account (ritmo umano, tetti, fermo al primo segnale), ma non può azzerarlo. Le storie che Febe apre
|
||||
> risultano viste da te.
|
||||
|
||||
> **Stato.** Questa versione è stata costruita e provata su Linux: tutto ciò che non dipende da Windows ha le sue prove
|
||||
> automatiche, ma **nessuna parte che richiede Windows è ancora stata eseguita su un Windows vero** (finestre, WebView2,
|
||||
> area di notifica, registro, programma di installazione). Le prove da fare sono in fondo a questa pagina e in
|
||||
> `docs/prove-dal-vivo.md`, parte C.
|
||||
> **Stato (20 ottobre 2026).** Con la 0.1.0 il browser di Febe per Windows non diventava mai disponibile, e l'accesso a
|
||||
> Instagram non poteva nemmeno cominciare: WebView2 partiva, ma subito dopo Febe ne leggeva la versione da un thread
|
||||
> diverso da quello dell'interfaccia, WebView2 lo rifiutava e Febe, credendo fallito l'avvio, chiudeva il browser e
|
||||
> riprovava per sempre (nel registro, a ogni tentativo: «WebView2 non parte (InvalidOperationException:
|
||||
> CoreWebView2Environment members can only be accessed from the UI thread.)»). **È corretto**: su un Windows vero
|
||||
> (Windows 11 Pro, runtime WebView2 155.0.4283.62) il browser di Febe parte al primo tentativo, in un paio di secondi.
|
||||
>
|
||||
> Ora ci sono anche **prove automatiche che girano su Windows**, con WebView2 vero e il sito di prova (mai Instagram):
|
||||
> S1 con la finestra fuori vista (navigazione, corpi delle risposte, lettura della pagina, scorrimento con la rotella,
|
||||
> fotogrammi, scaricamenti dal CDN, comandi vietati rifiutati), la finestra che viene in primo piano e torna fuori vista
|
||||
> con il motore fermo nel frattempo, «Scollega», la ripartenza da sola dopo l'arresto del processo del browser, la
|
||||
> «composizione» di S2 e una sessione di raccolta intera, con i file che arrivano nella libreria. Vedi «Prove
|
||||
> automatiche su Windows», più sotto.
|
||||
>
|
||||
> **Restano da provare a mano** (parte C di `docs/prove-dal-vivo.md`): l'installazione su un Windows pulito, S2 con la
|
||||
> finestra di Febe ridotta a icona e con lo schermo bloccato, S3 (il collegamento che sopravvive a «Esci» e al riavvio di
|
||||
> Windows), area di notifica, notifiche, avvio con il computer, e l'accesso vero a Instagram.
|
||||
|
||||
## Che cosa serve
|
||||
|
||||
@@ -173,9 +186,18 @@ della specifica (§6.6); si sceglie con `--browser` e la scelta resta:
|
||||
che lo chiude insieme a Febe.exe, anche se Febe si chiude all'improvviso o da Gestione attività: un Edge rimasto
|
||||
aperto terrebbe la porta 9222 e il browser di Febe non ripartirebbe più.
|
||||
|
||||
Come tutti gli oggetti di WebView2, ambiente, controllo, pagina e ricevitori degli eventi DevTools vivono sul thread
|
||||
dell'interfaccia: Febe li tocca solo da lì (i comandi del motore arrivano da altri thread e ci passano attraverso il
|
||||
dispatcher di WPF), e il resto del programma legge solo valori semplici presi durante l'avvio, come la versione per il
|
||||
registro. Se il processo del browser si chiude da solo, Febe lo fa ripartire con lo stesso profilo e con gli stessi
|
||||
tentativi del primo avvio (5, 15, 30, 60 secondi, poi ogni 5 minuti), e lo stesso se dopo «Scollega» non ripartisse.
|
||||
Nella finestra c'è sempre un solo browser: se «Scollega» lo fa ripartire mentre il primo avvio aspetta il prossimo
|
||||
tentativo, quel tentativo lo trova già in funzione e non ne apre un secondo.
|
||||
|
||||
Le prove da fare su un Windows vero, con la procedura esatta, sono in `docs/prove-dal-vivo.md`, **parte C**. In breve:
|
||||
|
||||
- **S1** — con il sito di prova: una sessione intera (gesti, corpo delle risposte, scaricamenti) e l'anteprima di Attività.
|
||||
- **S1** — con il sito di prova: una sessione intera (gesti, corpo delle risposte, scaricamenti) e l'anteprima di
|
||||
Attività. La parte che non dipende dall'installazione è già una prova automatica su Windows (sotto).
|
||||
- **S2** — la stessa sessione con il browser fuori vista, con la finestra di Febe ridotta a icona e con lo schermo bloccato;
|
||||
poi, se serve, `composizione` e `edge`.
|
||||
- **S3** — accesso a mano, «Esci», riapertura, riavvio di Windows: il collegamento deve restare.
|
||||
@@ -207,11 +229,42 @@ L'icona `src/Febe.Desktop/Febe.ico` (16, 24, 32, 48, 64, 128 e 256 pixel) è dis
|
||||
SkiaSharp e scritta a mano: per rigenerarla dopo un cambio del marchio,
|
||||
`FEBE_RIGENERA_ICONA=1 dotnet test tests/Febe.Tests --filter IconTests`.
|
||||
|
||||
## Prove automatiche su Windows
|
||||
|
||||
`tests/Febe.Tests.Windows` contiene le prove che hanno bisogno di Windows e di WebView2 vero. Si compila anche da Linux
|
||||
(la CI compila tutta la soluzione), ma gira solo su Windows, con il .NET SDK 10 e il runtime WebView2; dove il runtime
|
||||
manca le prove risultano inconcludenti, non rosse:
|
||||
|
||||
```sh
|
||||
dotnet test tests/Febe.Tests.Windows
|
||||
dotnet test tests/Febe.Tests.Windows --filter "FullyQualifiedName~WebView2CdpTests" # una classe sola
|
||||
```
|
||||
|
||||
Ogni prova crea un thread dell'interfaccia di WPF vero (come quello di `Febe.exe`), il proprio sito di prova su porte
|
||||
libere di 127.0.0.1 (il suo «CDN» su 127.0.0.2) e cartelle temporanee in `%TEMP%`: niente tocca la cartella dei dati né
|
||||
la libreria vere. La finestra «Browser di Febe» resta fuori dallo schermo, tranne in due prove che la portano in primo
|
||||
piano per un attimo: una prova il primo piano da solo, l'altra il percorso intero di «Accedi a Instagram» e «Ho finito».
|
||||
Una prova chiude, con il suo numero di processo, il processo del browser che lei stessa ha avviato, per vedere Febe
|
||||
farlo ripartire. Tutte insieme durano due o tre minuti, quasi tutti della sessione di raccolta.
|
||||
|
||||
| Classe | Che cosa prova |
|
||||
|---|---|
|
||||
| `WebView2BrowserStartTests` | Avviato da un thread del pool, come fa la composizione, il browser è pronto al primo tentativo e il registro dice «Browser di Febe pronto: WebView2 …» (l'errore del 14 ottobre) |
|
||||
| `WebView2LifecycleTests` | Un avvio che fallisce davvero si riprova e poi va; primo piano e fuori vista con il permesso di guida; «Scollega»; «Scollega» mentre il primo avvio aspetta di riprovare (un solo browser nella finestra, il «Scollega» dopo riesce subito); «Esci» mentre l'avvio non si completa (non lo aspetta); ripartenza dopo l'arresto del processo; «composizione» di S2 |
|
||||
| `WebView2CdpTests` | S1: i comandi dell'elenco su WebView2 contro il sito di prova, con la finestra fuori vista, e i comandi vietati rifiutati |
|
||||
| `WebView2CollectionTests` | Una sessione vera della composizione (`FebeApp` con `DesktopPlatform`) su WebView2: i file arrivano nella libreria |
|
||||
| `WebView2ConnectionTests` | Il collegamento dal servizio vero della composizione: «Accedi a Instagram» porta in primo piano la finestra con la pagina di accesso (del sito di prova), «Ho finito» trova la sessione e la rimette fuori vista, «Scollega» cancella il profilo e il motore riparte |
|
||||
|
||||
Quello che di `WebView2CdpSession` non chiede Windows (per esempio: un errore di chi ascolta la ripartenza non disfa
|
||||
l'avvio) si prova invece in `tests/Febe.Tests/Desktop/WebView2CdpSessionTests.cs`, con un finto WebView2: gira anche
|
||||
sulla CI per Linux.
|
||||
|
||||
## Problemi comuni
|
||||
|
||||
| Che cosa vedi | Che cosa fare |
|
||||
|---|---|
|
||||
| All'avvio: «Manca il runtime WebView2 di Microsoft» | Installa il runtime dalla pagina ufficiale (il messaggio offre di aprirla), poi riapri Febe |
|
||||
| Nel registro, a ogni tentativo: «WebView2 non parte (InvalidOperationException: CoreWebView2Environment members can only be accessed from the UI thread.)»; «Accedi a Instagram» risponde che il browser di Febe non è in funzione | È l'errore della 0.1.0: il browser di Febe non diventava mai disponibile. Installa una versione successiva alla 0.1.0 |
|
||||
| «La cartella dei dati è su un disco di rete» o «non può scrivere» | Riapri Febe con una cartella dei dati su un disco locale (`--dati`), oppure libera la cartella |
|
||||
| Aprendo Febe si porta solo in primo piano la finestra già aperta | È voluto: un solo Febe per cartella dei dati. Per fermarlo: menu dell'icona ▸ Esci |
|
||||
| Il collegamento risulta perso dopo un riavvio | È l'ipotesi S3: riferiscilo (parte C di `docs/prove-dal-vivo.md`) con l'ora e il registro di quel giorno |
|
||||
|
||||
@@ -24,4 +24,7 @@ public sealed class DeferredRecipeRunner : IRecipeRunner
|
||||
: Task.FromResult(new RecipeOutcome(RecipeStatus.Cancelled, 0, 0, "Il browser non è ancora pronto."));
|
||||
|
||||
public Task RestAsync(CancellationToken ct) => _target?.RestAsync(ct) ?? Task.CompletedTask;
|
||||
|
||||
/// <summary>The real runner's answer; before the browser is up nothing is known, and nothing is held back.</summary>
|
||||
public string? NotConfiguredReason(RecipeKind kind) => _target?.NotConfiguredReason(kind);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ using System.Globalization;
|
||||
using Febe.Browser.Recipes;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
@@ -372,6 +373,7 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
runner.Target = Pipeline.Runner;
|
||||
await CheckCollectionConfigurationAsync(Pipeline, engine, ct).ConfigureAwait(false);
|
||||
var changes = Web.Services.GetRequiredService<LibraryChanges>();
|
||||
_disposables.Add(changes.Attach(Pipeline.Downloads, Clock));
|
||||
_background.Add(Task.Run(() => DownloadLoopAsync(Pipeline.Downloads, ct), CancellationToken.None));
|
||||
@@ -412,6 +414,39 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Which reader vocabulary and target map the collection uses, in the log: where each came from (embedded in Febe or
|
||||
/// the copy in the Data folder) and in what state, never what is in them; a warning when a copy in the Data folder
|
||||
/// hides a better embedded file. Then the engine clears, once, the suspensions and failures of the recipes counted
|
||||
/// against other files (<see cref="EngineHost.ApplyCollectionConfigurationAsync"/>). Before the engine loop starts.
|
||||
/// </summary>
|
||||
private async Task CheckCollectionConfigurationAsync(CollectionPipeline pipeline, EngineHost engine, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var configuration = CollectionConfiguration.Describe(_options.Site.Name, pipeline.Vocabulary, pipeline.SiteMap);
|
||||
foreach (var line in configuration.Lines)
|
||||
{
|
||||
Log.Info("raccolta", line);
|
||||
}
|
||||
|
||||
foreach (var warning in configuration.Warnings)
|
||||
{
|
||||
Log.Warn("raccolta", warning);
|
||||
}
|
||||
|
||||
if (await engine.ApplyCollectionConfigurationAsync(configuration.Fingerprint, ct).ConfigureAwait(false))
|
||||
{
|
||||
Log.Info("raccolta", $"Configurazione della raccolta diversa dall'ultimo avvio (impronta {configuration.Fingerprint[..12]}): sospensioni ed errori contati delle ricette azzerati.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
|
||||
{
|
||||
// Never a reason not to collect: the suspensions stay as they are, «Riattiva» still clears them.
|
||||
Log.Warn("raccolta", "Non riesco a confrontare la configurazione della raccolta con quella dell'ultimo avvio: le ricette sospese restano come sono.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Development with the test site only (<c>--accesso-di-prova</c>): what Alberto does by hand on Instagram — open
|
||||
/// the site once, so that its session cookie exists — then back to the rest page.
|
||||
|
||||
@@ -19,8 +19,17 @@ public sealed record ResponseTapOptions
|
||||
/// <summary>How long to wait for one body before giving up on it (one stuck request must not block the others).</summary>
|
||||
public TimeSpan BodyTimeout { get; init; } = TimeSpan.FromSeconds(15);
|
||||
|
||||
/// <summary>Decides from the declared MIME type whether a body is worth parsing as JSON.</summary>
|
||||
public Func<string, bool> IsJsonMimeType { get; init; } = static mime => mime.Contains("json", StringComparison.OrdinalIgnoreCase);
|
||||
/// <summary>
|
||||
/// Decides from the declared MIME type and the resource type whether a body is worth parsing as JSON
|
||||
/// (<see cref="DataResponses.IsData"/>: JSON, and JavaScript the page fetched itself).
|
||||
/// </summary>
|
||||
public Func<string, string?, bool> IsDataResponse { get; init; } = DataResponses.IsData;
|
||||
|
||||
/// <summary>
|
||||
/// Whether the main document of a site page is read too, for the JSON blocks it embeds
|
||||
/// (<see cref="DataResponses.EmbeddedJsonBlocks"/>).
|
||||
/// </summary>
|
||||
public bool ReadPageDocuments { get; init; } = true;
|
||||
|
||||
/// <summary>Per-resource buffer of the browser (<c>Network.enable</c> maxResourceBufferSize).</summary>
|
||||
public int BrowserResourceBufferBytes { get; init; } = 32 * 1024 * 1024;
|
||||
@@ -37,22 +46,26 @@ public sealed record ResponseTapStats(long Responses, long JsonBodies, long Body
|
||||
/// and the metadata of every response and main-frame navigation to <see cref="IResponseObserver"/>s.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It does not filter by address: readers recognise data by its shape (spec §6.4). Bodies stay in memory for the
|
||||
/// time of the reading, are never written to disk and never logged. Event handlers only queue work; bodies are
|
||||
/// fetched and parsed on a background worker, one at a time.
|
||||
/// It does not filter by address: readers recognise data by its shape (spec §6.4). A body is read when the browser
|
||||
/// declares it as JSON, or as JavaScript fetched by the page (Instagram's GraphQL answers), and the main document of a
|
||||
/// site page is read for the JSON blocks it embeds, each handed to consumers as an answer of its own with the
|
||||
/// document's descriptor. Bodies stay in memory for the time of the reading, are never written to disk and never
|
||||
/// logged. Event handlers only queue work; bodies are fetched and parsed on a background worker, one at a time.
|
||||
/// </remarks>
|
||||
public sealed class ResponseTap : IAsyncDisposable
|
||||
{
|
||||
private static readonly JsonDocumentOptions BodyOptions = new() { MaxDepth = 256 };
|
||||
|
||||
private readonly ICdpSession _cdp;
|
||||
private readonly HostClassifier _hosts;
|
||||
private readonly IClock _clock;
|
||||
private readonly IBrowserLog _log;
|
||||
private readonly ResponseTapOptions _options;
|
||||
private readonly ConcurrentDictionary<string, ResponseDescriptor> _inFlight = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, PendingBody> _inFlight = new(StringComparer.Ordinal);
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<IResponseConsumer> _consumers = [];
|
||||
private readonly List<IResponseObserver> _observers = [];
|
||||
private readonly Channel<ResponseDescriptor> _queue = Channel.CreateUnbounded<ResponseDescriptor>(new UnboundedChannelOptions { SingleReader = true });
|
||||
private readonly Channel<PendingBody> _queue = Channel.CreateUnbounded<PendingBody>(new UnboundedChannelOptions { SingleReader = true });
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private readonly List<IDisposable> _subscriptions = [];
|
||||
private Task? _worker;
|
||||
@@ -181,7 +194,14 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
|
||||
private void OnReconnected(object? sender, EventArgs e)
|
||||
{
|
||||
_inFlight.Clear();
|
||||
foreach (var key in _inFlight.Keys)
|
||||
{
|
||||
if (_inFlight.TryRemove(key, out _))
|
||||
{
|
||||
NotifyDropped(key);
|
||||
}
|
||||
}
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
@@ -240,16 +260,21 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
if (_options.IsJsonMimeType(mime) && status is >= 200 and < 600 && status != 204)
|
||||
if (_options.IsDataResponse(mime, type) && status is >= 200 and < 600 && status != 204)
|
||||
{
|
||||
_inFlight[requestId] = descriptor;
|
||||
_inFlight[requestId] = new PendingBody(descriptor, IsPageDocument: false);
|
||||
}
|
||||
else if (_options.ReadPageDocuments && descriptor.HostKind == HostKind.Site && status is >= 200 and < 300
|
||||
&& DataResponses.IsPageDocument(mime, isMainDocument))
|
||||
{
|
||||
_inFlight[requestId] = new PendingBody(descriptor, IsPageDocument: true);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnLoadingFinished(JsonElement p)
|
||||
{
|
||||
if (!p.TryGetProperty("requestId", out var idElement) || idElement.GetString() is not { } requestId
|
||||
|| !_inFlight.TryRemove(requestId, out var descriptor))
|
||||
|| !_inFlight.TryRemove(requestId, out var pending))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -258,17 +283,19 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
if (length > _options.MaxBodyBytes)
|
||||
{
|
||||
Interlocked.Increment(ref _skipped);
|
||||
NotifyDropped(requestId);
|
||||
return;
|
||||
}
|
||||
|
||||
_queue.Writer.TryWrite(descriptor);
|
||||
_queue.Writer.TryWrite(pending);
|
||||
}
|
||||
|
||||
private void OnLoadingFailed(JsonElement p)
|
||||
{
|
||||
if (p.TryGetProperty("requestId", out var idElement) && idElement.GetString() is { } requestId)
|
||||
if (p.TryGetProperty("requestId", out var idElement) && idElement.GetString() is { } requestId
|
||||
&& _inFlight.TryRemove(requestId, out _))
|
||||
{
|
||||
_inFlight.TryRemove(requestId, out _);
|
||||
NotifyDropped(requestId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,8 +311,16 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
_mainFrameId = frame.TryGetProperty("id", out var id) ? id.GetString() : _mainFrameId;
|
||||
|
||||
// Requests of the previous document that never finished (e.g. a body the page did not read: Chromium then
|
||||
// sends no loadingFinished) will not finish any more: forget them.
|
||||
_inFlight.Clear();
|
||||
// sends no loadingFinished) will not finish any more: forget them. The new document itself is kept: the frame
|
||||
// commits it before its body has finished loading (its request id is the frame's loader id).
|
||||
var loader = frame.TryGetProperty("loaderId", out var l) ? l.GetString() : null;
|
||||
foreach (var key in _inFlight.Keys)
|
||||
{
|
||||
if (key != loader && _inFlight.TryRemove(key, out _))
|
||||
{
|
||||
NotifyDropped(key);
|
||||
}
|
||||
}
|
||||
Publish(frame.TryGetProperty("url", out var u) ? u.GetString() : null, sameDocument: false);
|
||||
}
|
||||
|
||||
@@ -325,64 +360,128 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
|
||||
private async Task WorkAsync(CancellationToken ct)
|
||||
{
|
||||
await foreach (var descriptor in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false))
|
||||
try
|
||||
{
|
||||
IResponseConsumer[] consumers;
|
||||
lock (_gate)
|
||||
await foreach (var pending in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
consumers = [.. _consumers];
|
||||
try
|
||||
{
|
||||
await HandleAsync(pending, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
|
||||
{
|
||||
// One unexpected body must not stop the capture of the following ones. Only the type: the message
|
||||
// of a parsing error may quote the body.
|
||||
_log.Warn($"Cattura: errore imprevisto nella lettura di una risposta ({ex.GetType().Name}).");
|
||||
NotifyDropped(pending.Descriptor.RequestId);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
if (consumers.Length == 0)
|
||||
/// <summary>Fetches one body and hands it to the consumers; tells the observers once when nothing reached them.</summary>
|
||||
private async Task HandleAsync(PendingBody pending, CancellationToken ct)
|
||||
{
|
||||
var descriptor = pending.Descriptor;
|
||||
IResponseConsumer[] consumers;
|
||||
lock (_gate)
|
||||
{
|
||||
consumers = [.. _consumers];
|
||||
}
|
||||
|
||||
if (consumers.Length == 0)
|
||||
{
|
||||
NotifyDropped(descriptor.RequestId);
|
||||
return;
|
||||
}
|
||||
|
||||
byte[]? bytes;
|
||||
try
|
||||
{
|
||||
bytes = await FetchBodyAsync(descriptor.RequestId, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpCommandException or CdpDisconnectedException or BrowserUnavailableException or TimeoutException)
|
||||
{
|
||||
// The body may already be evicted from the browser's buffer, or the page navigated away.
|
||||
Interlocked.Increment(ref _bodyErrors);
|
||||
_log.Debug($"Cattura: corpo non disponibile ({ex.GetType().Name}).");
|
||||
NotifyDropped(descriptor.RequestId);
|
||||
return;
|
||||
}
|
||||
|
||||
var delivered = bytes is null ? 0
|
||||
: pending.IsPageDocument ? await ConsumeDocumentAsync(descriptor, bytes, consumers, ct).ConfigureAwait(false)
|
||||
: await ConsumeBodyAsync(descriptor, bytes, consumers, ct).ConfigureAwait(false);
|
||||
if (delivered == 0)
|
||||
{
|
||||
NotifyDropped(descriptor.RequestId);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The body of a data response, as one answer. Returns how many answers reached the consumers (0 or 1).</summary>
|
||||
private async Task<int> ConsumeBodyAsync(ResponseDescriptor descriptor, byte[] bytes, IResponseConsumer[] consumers, CancellationToken ct)
|
||||
{
|
||||
JsonDocument document;
|
||||
try
|
||||
{
|
||||
document = JsonDocument.Parse(bytes, BodyOptions);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Not JSON after all (e.g. Instagram's «for (;;);» answers of /ajax/, which carry no contents): skipped.
|
||||
Interlocked.Increment(ref _parseErrors);
|
||||
return 0;
|
||||
}
|
||||
|
||||
using (document)
|
||||
{
|
||||
await DeliverAsync(descriptor, document, consumers, ct).ConfigureAwait(false);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The JSON blocks a page document embeds, each handed to the consumers as an answer of its own with the document's
|
||||
/// descriptor, so that a pagination stays with the block that carries it
|
||||
/// (<see cref="DataResponses.EmbeddedJsonBlocks"/>). One block at a time: each is disposed before the next is parsed.
|
||||
/// Returns how many blocks reached the consumers; a document without any is not data, and not a parse error.
|
||||
/// </summary>
|
||||
private async Task<int> ConsumeDocumentAsync(ResponseDescriptor descriptor, byte[] bytes, IResponseConsumer[] consumers, CancellationToken ct)
|
||||
{
|
||||
var delivered = 0;
|
||||
foreach (var block in DataResponses.EmbeddedJsonBlocks(Encoding.UTF8.GetString(bytes)))
|
||||
{
|
||||
using (block)
|
||||
{
|
||||
continue;
|
||||
delivered++;
|
||||
await DeliverAsync(descriptor, block, consumers, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
JsonDocument? document;
|
||||
return delivered;
|
||||
}
|
||||
|
||||
private async Task DeliverAsync(ResponseDescriptor descriptor, JsonDocument body, IResponseConsumer[] consumers, CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref _jsonBodies);
|
||||
foreach (var consumer in consumers)
|
||||
{
|
||||
try
|
||||
{
|
||||
document = await FetchBodyAsync(descriptor.RequestId, ct).ConfigureAwait(false);
|
||||
await consumer.ConsumeAsync(descriptor, body, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpCommandException or CdpDisconnectedException or BrowserUnavailableException or TimeoutException)
|
||||
{
|
||||
// The body may already be evicted from the browser's buffer, or the page navigated away.
|
||||
Interlocked.Increment(ref _bodyErrors);
|
||||
_log.Debug($"Cattura: corpo non disponibile ({ex.GetType().Name}).");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (document is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
using (document)
|
||||
{
|
||||
Interlocked.Increment(ref _jsonBodies);
|
||||
foreach (var consumer in consumers)
|
||||
{
|
||||
try
|
||||
{
|
||||
await consumer.ConsumeAsync(descriptor, document, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn($"Cattura: errore in un lettore ({consumer.GetType().Name}).", ex);
|
||||
}
|
||||
}
|
||||
_log.Warn($"Cattura: errore in un lettore ({consumer.GetType().Name}).", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<JsonDocument?> FetchBodyAsync(string requestId, CancellationToken ct)
|
||||
/// <summary>The decoded bytes of a body, or null when the browser gives none or it cannot be decoded.</summary>
|
||||
private async Task<byte[]?> FetchBodyAsync(string requestId, CancellationToken ct)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(_options.BodyTimeout);
|
||||
@@ -402,34 +501,39 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
}
|
||||
|
||||
var encoded = result.TryGetProperty("base64Encoded", out var b) && b.ValueKind == JsonValueKind.True;
|
||||
byte[] bytes;
|
||||
if (encoded)
|
||||
if (!encoded)
|
||||
{
|
||||
if (!body.TryGetBytesFromBase64(out var decoded))
|
||||
{
|
||||
Interlocked.Increment(ref _parseErrors);
|
||||
return null;
|
||||
}
|
||||
|
||||
bytes = decoded;
|
||||
}
|
||||
else
|
||||
{
|
||||
bytes = Encoding.UTF8.GetBytes(body.GetString() ?? string.Empty);
|
||||
return Encoding.UTF8.GetBytes(body.GetString() ?? string.Empty);
|
||||
}
|
||||
|
||||
try
|
||||
if (!body.TryGetBytesFromBase64(out var decoded))
|
||||
{
|
||||
return JsonDocument.Parse(bytes, new JsonDocumentOptions { MaxDepth = 256 });
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Declared as JSON but it is not (or has a prefix): readers will be told by the probe in M0.
|
||||
Interlocked.Increment(ref _parseErrors);
|
||||
return null;
|
||||
}
|
||||
|
||||
return decoded;
|
||||
}
|
||||
|
||||
/// <summary>Tells the observers that a body they may be waiting for will not come.</summary>
|
||||
private void NotifyDropped(string requestId)
|
||||
{
|
||||
foreach (var observer in SnapshotObservers())
|
||||
{
|
||||
try
|
||||
{
|
||||
observer.OnBodyDropped(requestId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn("Cattura: errore in un osservatore delle risposte.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A body to fetch once its loading has finished.</summary>
|
||||
private sealed record PendingBody(ResponseDescriptor Descriptor, bool IsPageDocument);
|
||||
|
||||
private IResponseObserver[] SnapshotObservers()
|
||||
{
|
||||
lock (_gate)
|
||||
|
||||
@@ -92,11 +92,31 @@ public sealed class CdpCommandNotAllowedException(string method, string message)
|
||||
public sealed class CdpCommandException(string method, int code, string browserMessage)
|
||||
: Exception($"Il comando CDP «{method}» è fallito: {browserMessage} (codice {code}).")
|
||||
{
|
||||
/// <summary>Chromium's generic «server error» code.</summary>
|
||||
public const int ServerErrorCode = -32000;
|
||||
|
||||
/// <summary>
|
||||
/// What Chromium answers to a browser-side page command (<c>Page.startScreencast</c>, <c>Page.captureScreenshot</c>)
|
||||
/// while the page's current document is not «active»: from <c>ReadyToCommitNavigation</c> of a navigation that uses
|
||||
/// a new RenderFrameHost until that navigation commits, DevTools already points at the new, still uncommitted frame
|
||||
/// (content/browser/devtools/protocol/page_handler.cc, <c>AssureTopLevelActiveFrame</c>;
|
||||
/// render_frame_devtools_agent_host.cc, <c>ReadyToCommitNavigation</c>). A new RenderFrameHost comes with a process
|
||||
/// swap, a cross-site or back-forward-cache swap and, with RenderDocument (on by default in current Chromium), with
|
||||
/// every navigation of the page to a new document — the rest page included.
|
||||
/// </summary>
|
||||
public const string InactivePageMessage = "Not attached to an active page";
|
||||
|
||||
public string Method { get; } = method;
|
||||
|
||||
public int Code { get; } = code;
|
||||
|
||||
public string BrowserMessage { get; } = browserMessage;
|
||||
|
||||
/// <summary>
|
||||
/// The page is between two documents (see <see cref="InactivePageMessage"/>): the same command a moment later finds
|
||||
/// the new document committed. A browser that is gone answers differently (closed connection, no answer).
|
||||
/// </summary>
|
||||
public bool IsInactivePage => Code == ServerErrorCode && string.Equals(BrowserMessage, InactivePageMessage, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>The connection to the browser is closed (browser exited, crashed or is restarting).</summary>
|
||||
|
||||
@@ -23,8 +23,8 @@ namespace Febe.Browser.Recipes;
|
||||
public sealed record CollectionSite(string Name, string BaseUrl, HostClassifier Hosts, SessionCookieOptions SessionCookie)
|
||||
{
|
||||
/// <summary>
|
||||
/// Instagram. Its target map and reader vocabulary are still skeletons until M0: every recipe refuses to run and
|
||||
/// says why, without touching the site.
|
||||
/// Instagram. Its reader vocabulary is confirmed on real cleaned samples and its map has the pages seen in real
|
||||
/// traffic, not yet the targets: a recipe that needs a target refuses to run and says why, without touching the site.
|
||||
/// </summary>
|
||||
public static CollectionSite Instagram { get; } = new("instagram", "https://www.instagram.com", HostClassifier.Instagram, SessionCookieOptions.Instagram);
|
||||
|
||||
|
||||
@@ -64,12 +64,16 @@ public sealed class RemoteViewSession : IAsyncDisposable
|
||||
private IDisposable? _lease;
|
||||
private int _buttons;
|
||||
|
||||
public RemoteViewSession(ICdpSession cdp, UserDrivingGate gate, IBrowserLog? log = null)
|
||||
/// <param name="cdp">The page session.</param>
|
||||
/// <param name="gate">Where the «Alberto is driving» lease is taken.</param>
|
||||
/// <param name="log">Where opening and closing are noted (never keys).</param>
|
||||
/// <param name="clock">Wall-clock time for the screencast's start attempts; null: the system clock.</param>
|
||||
public RemoteViewSession(ICdpSession cdp, UserDrivingGate gate, IBrowserLog? log = null, IClock? clock = null)
|
||||
{
|
||||
_cdp = cdp ?? throw new ArgumentNullException(nameof(cdp));
|
||||
_gate = gate ?? throw new ArgumentNullException(nameof(gate));
|
||||
_log = log ?? NullBrowserLog.Instance;
|
||||
Screencast = new ScreencastSession(cdp, _log);
|
||||
Screencast = new ScreencastSession(cdp, _log, clock);
|
||||
}
|
||||
|
||||
public ScreencastSession Screencast { get; }
|
||||
|
||||
@@ -39,10 +39,22 @@ public sealed record ScreencastFrame(
|
||||
/// <c>Page.screencastFrameAck</c>, stopped with <c>Page.stopScreencast</c>. Frames are delivered through
|
||||
/// <see cref="ReadFramesAsync"/> (only the latest ones are kept when the reader is slow) and <see cref="FrameReceived"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A view opened while the page changes document (the rest page after a session, the login page opened together with
|
||||
/// the view) can meet the moment in which Chromium refuses the start with «Not attached to an active page»: the start
|
||||
/// is sent again, a few times, for at most <see cref="InactivePageBudget"/>. Any other failure is reported at once.
|
||||
/// </remarks>
|
||||
public sealed class ScreencastSession : IAsyncDisposable
|
||||
{
|
||||
/// <summary>How long a start refused because the page is between two documents is tried again.</summary>
|
||||
public static readonly TimeSpan InactivePageBudget = TimeSpan.FromSeconds(5);
|
||||
|
||||
private static readonly TimeSpan FirstPause = TimeSpan.FromMilliseconds(100);
|
||||
private static readonly TimeSpan LongestPause = TimeSpan.FromMilliseconds(500);
|
||||
|
||||
private readonly ICdpSession _cdp;
|
||||
private readonly IBrowserLog _log;
|
||||
private readonly IClock _clock;
|
||||
private readonly Channel<ScreencastFrame> _frames = Channel.CreateBounded<ScreencastFrame>(
|
||||
new BoundedChannelOptions(2) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true });
|
||||
|
||||
@@ -54,10 +66,14 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
private int _stopped;
|
||||
private long _framesReceived;
|
||||
|
||||
public ScreencastSession(ICdpSession cdp, IBrowserLog? log = null)
|
||||
/// <param name="cdp">The page session.</param>
|
||||
/// <param name="log">Where the start and stop are noted (never parameters or frames).</param>
|
||||
/// <param name="clock">Wall-clock time for the pauses between start attempts; null: the system clock.</param>
|
||||
public ScreencastSession(ICdpSession cdp, IBrowserLog? log = null, IClock? clock = null)
|
||||
{
|
||||
_cdp = cdp ?? throw new ArgumentNullException(nameof(cdp));
|
||||
_log = log ?? NullBrowserLog.Instance;
|
||||
_clock = clock ?? new SystemClock();
|
||||
}
|
||||
|
||||
/// <summary>Raised on the browser event thread for every frame: handlers must be quick.</summary>
|
||||
@@ -144,20 +160,47 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
_lifetime.Dispose();
|
||||
}
|
||||
|
||||
private Task SendStartAsync(CancellationToken ct)
|
||||
private async Task SendStartAsync(CancellationToken ct)
|
||||
{
|
||||
var o = _options ?? new ScreencastOptions();
|
||||
return _cdp.SendAsync(
|
||||
"Page.startScreencast",
|
||||
new JsonObject
|
||||
var deadline = _clock.Now + InactivePageBudget;
|
||||
var pause = FirstPause;
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
["format"] = "jpeg",
|
||||
["quality"] = Math.Clamp(o.Quality, 0, 100),
|
||||
["maxWidth"] = o.MaxWidth,
|
||||
["maxHeight"] = o.MaxHeight,
|
||||
["everyNthFrame"] = Math.Max(1, o.EveryNthFrame),
|
||||
},
|
||||
ct);
|
||||
await _cdp.SendAsync(
|
||||
"Page.startScreencast",
|
||||
new JsonObject
|
||||
{
|
||||
["format"] = "jpeg",
|
||||
["quality"] = Math.Clamp(o.Quality, 0, 100),
|
||||
["maxWidth"] = o.MaxWidth,
|
||||
["maxHeight"] = o.MaxHeight,
|
||||
["everyNthFrame"] = Math.Max(1, o.EveryNthFrame),
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
if (attempt > 1)
|
||||
{
|
||||
_log.Debug($"Vista remota: fotogrammi avviati al tentativo {attempt.ToString(System.Globalization.CultureInfo.InvariantCulture)}, dopo un cambio di pagina.");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
catch (CdpCommandException ex) when (ex.IsInactivePage && _clock.Now + pause <= deadline)
|
||||
{
|
||||
// A navigation is committing in a new frame of the page: nothing is started on the browser side, the
|
||||
// same start a moment later finds the new document. Past the budget the error goes up as it is.
|
||||
}
|
||||
|
||||
await _clock.Delay(pause, ct).ConfigureAwait(false);
|
||||
if (Volatile.Read(ref _stopped) == 1)
|
||||
{
|
||||
return; // stopped meanwhile (a restart's start in the background): nothing left to start
|
||||
}
|
||||
|
||||
pause = pause * 2 < LongestPause ? pause * 2 : LongestPause;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnReconnected(object? sender, EventArgs e) =>
|
||||
|
||||
@@ -113,7 +113,7 @@ public sealed class WebView2CdpSession : ICdpSession, ICdpConnectionEvents, IAsy
|
||||
_log.Write(BrowserLogLevel.Debug, "CDP: WebView2 collegato.");
|
||||
if (reconnect)
|
||||
{
|
||||
Reconnected?.Invoke(this, EventArgs.Empty);
|
||||
RaiseReconnected();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -275,6 +275,31 @@ public sealed class WebView2CdpSession : ICdpSession, ICdpConnectionEvents, IAsy
|
||||
return JsonElement.ParseValue(ref reader);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="Reconnected"/>, on the thread of <see cref="Attach"/> (WebView2's UI thread), one handler at a time: an
|
||||
/// error of a handler is logged and never reaches <see cref="Attach"/>, so it cannot undo the start of the new
|
||||
/// WebView that called it. Handlers only queue their work (re-enabling a domain is a command, never sent from here).
|
||||
/// </summary>
|
||||
private void RaiseReconnected()
|
||||
{
|
||||
if (Reconnected is not { } handlers)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var handler in handlers.GetInvocationList().Cast<EventHandler>())
|
||||
{
|
||||
try
|
||||
{
|
||||
handler(this, EventArgs.Empty);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_log.Write(BrowserLogLevel.Warning, "CDP: errore in chi ascolta il nuovo collegamento con WebView2.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private IDisposable SubscribeNative(IWebView2DevTools devTools, string eventName) =>
|
||||
devTools.Subscribe(eventName, json => _events.Writer.TryWrite(new QueuedEvent(eventName, json ?? string.Empty, null)));
|
||||
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Engine;
|
||||
|
||||
namespace Febe.Core.Collection;
|
||||
|
||||
/// <summary>One configuration file of the collection as it was loaded.</summary>
|
||||
/// <param name="Name">File name: <c>lettori.instagram.json</c>, <c>bersagli.instagram.json</c>.</param>
|
||||
/// <param name="OverridePath">The editable copy in the Data folder that was loaded; null for the copy embedded in Febe.</param>
|
||||
/// <param name="Text">Its content (for the fingerprint only: never logged).</param>
|
||||
public sealed record CollectionConfigurationFile(string Name, string? OverridePath, string Text)
|
||||
{
|
||||
public bool IsOverride => OverridePath is not null;
|
||||
|
||||
/// <summary>Where it came from, in Italian, for the log: never what is in it.</summary>
|
||||
public string Origin => OverridePath is { } path
|
||||
? $"la copia nella cartella dei dati ({path})"
|
||||
: $"il file incorporato in Febe ({Name})";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The reader vocabulary and target map one site runs on, as the collection pipeline loaded them: where each came from
|
||||
/// (the copy embedded in Febe, or an editable copy in the Data folder, which always wins), its state, the recipes they
|
||||
/// leave unable to run, and a fingerprint of their content. The engine clears the suspensions of the recipes when the
|
||||
/// fingerprint changes (<see cref="EngineHost.ApplyCollectionConfigurationAsync"/>). Nothing here comes from the site.
|
||||
/// </summary>
|
||||
public sealed class CollectionConfiguration
|
||||
{
|
||||
private CollectionConfiguration(
|
||||
string site,
|
||||
ReaderVocabulary vocabulary,
|
||||
SiteMap map,
|
||||
CollectionConfigurationFile vocabularyFile,
|
||||
CollectionConfigurationFile mapFile,
|
||||
ReaderVocabulary? embeddedVocabulary,
|
||||
SiteMap? embeddedMap)
|
||||
{
|
||||
Site = site;
|
||||
Vocabulary = vocabulary;
|
||||
Map = map;
|
||||
VocabularyFile = vocabularyFile;
|
||||
MapFile = mapFile;
|
||||
EmbeddedVocabulary = embeddedVocabulary;
|
||||
EmbeddedMap = embeddedMap;
|
||||
Blocked = BlockedBy(map, vocabulary);
|
||||
Fingerprint = FingerprintOf(site, vocabularyFile, mapFile);
|
||||
}
|
||||
|
||||
/// <summary>The site name of the files (<c>instagram</c>, <c>prova</c>).</summary>
|
||||
public string Site { get; }
|
||||
|
||||
public ReaderVocabulary Vocabulary { get; }
|
||||
|
||||
public SiteMap Map { get; }
|
||||
|
||||
public CollectionConfigurationFile VocabularyFile { get; }
|
||||
|
||||
public CollectionConfigurationFile MapFile { get; }
|
||||
|
||||
/// <summary>The vocabulary embedded in Febe, when there is one (the same as <see cref="Vocabulary"/> without a copy).</summary>
|
||||
public ReaderVocabulary? EmbeddedVocabulary { get; }
|
||||
|
||||
/// <summary>The map embedded in Febe, when there is one (the same as <see cref="Map"/> without a copy).</summary>
|
||||
public SiteMap? EmbeddedMap { get; }
|
||||
|
||||
/// <summary>Recipes these files do not let run (<see cref="RecipeStatus.NotConfigured"/>), in the order of <see cref="RecipeKind"/>.</summary>
|
||||
public IReadOnlyList<RecipeKind> Blocked { get; }
|
||||
|
||||
/// <summary>SHA-256 of the two files as loaded (lower-case hexadecimal), line endings aside.</summary>
|
||||
public string Fingerprint { get; }
|
||||
|
||||
/// <summary>What the log says at start-up: where each file came from and in what state, and what cannot run.</summary>
|
||||
public IReadOnlyList<string> Lines
|
||||
{
|
||||
get
|
||||
{
|
||||
var all = Enum.GetValues<RecipeKind>().Length;
|
||||
var vocabularyState = Vocabulary.Status == VocabularyStatus.Confirmed ? "confermato" : "ipotesi";
|
||||
if (Vocabulary.MissingConcepts.Count > 0)
|
||||
{
|
||||
vocabularyState += $", {Vocabulary.MissingConcepts.Count.ToString(CultureInfo.InvariantCulture)} concetti ancora senza chiavi";
|
||||
}
|
||||
|
||||
var missing = Map.Missing(SitePages.All, SiteTargets.All).Count;
|
||||
var mapState = missing == 0 ? "tutte le voci compilate" : $"{missing.ToString(CultureInfo.InvariantCulture)} voci vuote o assenti";
|
||||
return
|
||||
[
|
||||
$"Vocabolario dei lettori per «{Site}»: {VocabularyFile.Origin}, {vocabularyState}.",
|
||||
$"Mappa dei bersagli per «{Site}»: {MapFile.Origin}, {mapState}.",
|
||||
Blocked.Count == 0
|
||||
? "Con questa configurazione tutte le ricette possono girare."
|
||||
: $"Con questa configurazione non possono girare {Blocked.Count.ToString(CultureInfo.InvariantCulture)} ricette su {all.ToString(CultureInfo.InvariantCulture)}: {Names(Blocked)}.",
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A copy in the Data folder that hides a better embedded file: a vocabulary still «ipotesi» while the embedded one
|
||||
/// is «confermato», or a map that leaves recipes unable to run that the embedded one lets run. A stale copy would
|
||||
/// otherwise keep the new files of an update from ever being used.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> Warnings
|
||||
{
|
||||
get
|
||||
{
|
||||
var warnings = new List<string>();
|
||||
if (VocabularyFile.IsOverride && EmbeddedVocabulary is { } embedded
|
||||
&& Vocabulary.Status == VocabularyStatus.Hypothesis && embedded.Status == VocabularyStatus.Confirmed)
|
||||
{
|
||||
warnings.Add($"Il vocabolario dei lettori in {VocabularyFile.OverridePath} è ancora un'ipotesi, mentre quello incorporato in Febe è confermato: la copia nella cartella dei dati nasconde quello nuovo. Toglila (o aggiornala) e riavvia Febe.");
|
||||
}
|
||||
|
||||
if (MapFile.IsOverride && EmbeddedMap is { } embeddedMap)
|
||||
{
|
||||
var hidden = MissingFrom(Map).Except(MissingFrom(embeddedMap)).ToList();
|
||||
if (hidden.Count > 0)
|
||||
{
|
||||
warnings.Add($"La mappa dei bersagli in {MapFile.OverridePath} lascia ferme ricette che con quella incorporata in Febe potrebbero girare ({Names(hidden)}): la copia nella cartella dei dati nasconde quella nuova. Toglila (o aggiornala) e riavvia Febe.");
|
||||
}
|
||||
}
|
||||
|
||||
return warnings;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Describes what was loaded for <paramref name="site"/>: <paramref name="vocabulary"/> and <paramref name="map"/>
|
||||
/// as the pipeline loaded them (their <c>Source</c> tells a Data-folder copy from the embedded file). The text of a
|
||||
/// copy is read again from its path for the fingerprint.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">A copy in the Data folder cannot be read any more.</exception>
|
||||
public static CollectionConfiguration Describe(string site, ReaderVocabulary vocabulary, SiteMap map)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(site);
|
||||
ArgumentNullException.ThrowIfNull(vocabulary);
|
||||
ArgumentNullException.ThrowIfNull(map);
|
||||
var vocabularyFile = LoadedFile($"lettori.{site}.json", vocabulary.Source);
|
||||
var mapFile = LoadedFile($"bersagli.{site}.json", map.Source);
|
||||
var embeddedVocabulary = vocabularyFile.IsOverride ? Try(() => ReaderVocabulary.LoadEmbedded(vocabularyFile.Name)) : vocabulary;
|
||||
var embeddedMap = mapFile.IsOverride ? Try(() => SiteMap.LoadEmbedded(mapFile.Name)) : map;
|
||||
return new CollectionConfiguration(site, vocabulary, map, vocabularyFile, mapFile, embeddedVocabulary, embeddedMap);
|
||||
}
|
||||
|
||||
/// <summary>The recipes a map and a vocabulary do not let run, by the same rule as the runner's.</summary>
|
||||
public static IReadOnlyList<RecipeKind> BlockedBy(SiteMap map, ReaderVocabulary vocabulary)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(map);
|
||||
ArgumentNullException.ThrowIfNull(vocabulary);
|
||||
return vocabulary.IsUsable ? MissingFrom(map) : Enum.GetValues<RecipeKind>();
|
||||
}
|
||||
|
||||
/// <summary>The recipes whose pages or targets the map lacks, whatever the vocabulary.</summary>
|
||||
private static RecipeKind[] MissingFrom(SiteMap map) =>
|
||||
[.. Enum.GetValues<RecipeKind>().Where(kind =>
|
||||
{
|
||||
var (pages, targets) = RecipeRunner.Requirements(kind);
|
||||
return map.Missing(pages, targets).Count > 0;
|
||||
})];
|
||||
|
||||
private static CollectionConfigurationFile LoadedFile(string name, string? source)
|
||||
{
|
||||
if (source is { Length: > 0 } path && !string.Equals(path, name, StringComparison.Ordinal))
|
||||
{
|
||||
return new CollectionConfigurationFile(name, path, File.ReadAllText(path));
|
||||
}
|
||||
|
||||
return new CollectionConfigurationFile(name, null, SiteMap.ReadEmbeddedText(name));
|
||||
}
|
||||
|
||||
private static T? Try<T>(Func<T> load)
|
||||
where T : class
|
||||
{
|
||||
try
|
||||
{
|
||||
return load();
|
||||
}
|
||||
catch (Exception ex) when (ex is FileNotFoundException or InvalidDataException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string FingerprintOf(string site, CollectionConfigurationFile vocabulary, CollectionConfigurationFile map)
|
||||
{
|
||||
static string Normalized(string text) => text.Replace("\r\n", "\n", StringComparison.Ordinal);
|
||||
var text = string.Join('\n', site, vocabulary.Name, Normalized(vocabulary.Text), map.Name, Normalized(map.Text));
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text)));
|
||||
}
|
||||
|
||||
private static string Names(IEnumerable<RecipeKind> kinds) => string.Join(", ", kinds.Select(RecipeRunner.Name));
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Febe.Core.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// Which responses of the page carry data worth reading (spec §6.2), decided from what the browser declares about
|
||||
/// them, never from the address.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Instagram serves its GraphQL data (<c>/graphql/query</c>, <c>/api/graphql</c>) as <c>text/javascript</c>, and only
|
||||
/// the REST answers (<c>/api/v1/...</c>) as <c>application/json</c> (HAR of Alberto's browser, 21 October 2026). A
|
||||
/// JavaScript type counts only when the page itself fetched it (XHR, Fetch): script files are never parsed.
|
||||
/// </remarks>
|
||||
public static partial class DataResponses
|
||||
{
|
||||
/// <summary>Largest page document whose embedded data is read.</summary>
|
||||
public const int MaxDocumentChars = 16 * 1024 * 1024;
|
||||
|
||||
private static readonly JsonDocumentOptions BlockOptions = new() { MaxDepth = 256 };
|
||||
|
||||
/// <summary>True for a body worth parsing as JSON data.</summary>
|
||||
/// <param name="mimeType">Declared MIME type, without parameters.</param>
|
||||
/// <param name="resourceType">Browser resource type (Document, XHR, Fetch, Script...), when known.</param>
|
||||
public static bool IsData(string mimeType, string? resourceType)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(mimeType);
|
||||
if (mimeType.Contains("json", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return mimeType.Contains("javascript", StringComparison.OrdinalIgnoreCase)
|
||||
&& resourceType is not null
|
||||
&& (resourceType.Equals("XHR", StringComparison.OrdinalIgnoreCase) || resourceType.Equals("Fetch", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>True for an HTML document of the main frame: the data it embeds is read too (<see cref="EmbeddedJsonBlocks"/>).</summary>
|
||||
public static bool IsPageDocument(string mimeType, bool isMainFrameDocument) =>
|
||||
isMainFrameDocument && mimeType.Equals("text/html", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// The JSON blocks a page embeds in <c><script type="application/json"></c> elements, one parsed document per
|
||||
/// block, in document order; none when there is none. Blocks that are not valid JSON are left out.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Single-page sites put the data of the first screen in the document itself and fetch only the following pages:
|
||||
/// without this, the first page of a profile opened by address would arrive «empty». The reader recognizes the data by
|
||||
/// shape wherever it sits inside a block (spec §6.4).
|
||||
/// <para>
|
||||
/// Every block is an answer of its own and is read on its own, like a response: joined to the others, the
|
||||
/// pagination of one block (collections that say «has_next_page» of themselves, a post that says
|
||||
/// «more_available: false» of itself) would end up on the items of another and end a walk early. The blocks are
|
||||
/// parsed lazily, one per step of the enumeration: the caller disposes each before taking the next, so a large
|
||||
/// document never has all its blocks in memory at once.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static IEnumerable<JsonDocument> EmbeddedJsonBlocks(string html)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(html);
|
||||
return html.Length > MaxDocumentChars ? [] : Blocks(html);
|
||||
}
|
||||
|
||||
private static IEnumerable<JsonDocument> Blocks(string html)
|
||||
{
|
||||
for (var match = NextBlock(html, previous: null); match is not null; match = NextBlock(html, match))
|
||||
{
|
||||
var body = match.Groups["body"];
|
||||
if (TryParse(html.AsMemory(body.Index, body.Length)) is { } block)
|
||||
{
|
||||
yield return block;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The block element after <paramref name="previous"/> (the first one when null), or null at the end.</summary>
|
||||
private static Match? NextBlock(string html, Match? previous)
|
||||
{
|
||||
try
|
||||
{
|
||||
var match = previous is null ? JsonScript().Match(html) : previous.NextMatch();
|
||||
return match.Success ? match : null;
|
||||
}
|
||||
catch (RegexMatchTimeoutException)
|
||||
{
|
||||
// A pathological document: the blocks found so far have been given, the rest is left out.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonDocument? TryParse(ReadOnlyMemory<char> text)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonDocument.Parse(text, BlockOptions);
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or ArgumentException)
|
||||
{
|
||||
// Not JSON, or too deep; ArgumentException: text that is not valid UTF-16 (a lone surrogate). Left out.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedRegex("""<script\b[^>]*?\btype\s*=\s*["']?application/json["']?[^>]*>(?<body>.*?)</script\s*>""", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 5000)]
|
||||
private static partial Regex JsonScript();
|
||||
}
|
||||
@@ -73,8 +73,9 @@ public sealed class HostClassifier
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Instagram's public host names: the site and the two CDN families its pages load files from.
|
||||
/// Public knowledge, not response formats; still to be confirmed by the M0 probe.
|
||||
/// Instagram's public host names: the site and the two CDN families its pages load files from. In the HAR of
|
||||
/// 21 October 2026 the data came from www.instagram.com (logging from graph.instagram.com), the video files from
|
||||
/// scontent-*.cdninstagram.com and the scripts from static.cdninstagram.com; fbcdn.net is public knowledge.
|
||||
/// </summary>
|
||||
public static HostClassifier Instagram { get; } = new(
|
||||
["instagram.com"],
|
||||
|
||||
@@ -69,4 +69,13 @@ public interface IResponseObserver
|
||||
void OnResponse(ResponseDescriptor response);
|
||||
|
||||
void OnNavigation(NavigationDescriptor navigation);
|
||||
|
||||
/// <summary>
|
||||
/// The body of a data response announced by <see cref="OnResponse"/> will not reach the consumers: it failed to
|
||||
/// load, was too large, was not JSON after all (Instagram's «for (;;);» answers), or the page moved on. Observers
|
||||
/// that wait for bodies stop waiting for this one.
|
||||
/// </summary>
|
||||
void OnBodyDropped(string requestId)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -127,6 +127,12 @@ public enum ReadShape
|
||||
|
||||
/// <summary>A shape the vocabulary does not describe: event «formato non riconosciuto» (spec §6.4).</summary>
|
||||
Unrecognized,
|
||||
|
||||
/// <summary>
|
||||
/// Nothing the vocabulary speaks about: none of its relevance keys appears anywhere (promotions, logging, a search
|
||||
/// box). Ignored: neither data, nor an empty page, nor an unknown shape (<see cref="ReaderVocabulary.Relevance"/>).
|
||||
/// </summary>
|
||||
Unrelated,
|
||||
}
|
||||
|
||||
/// <summary>Everything one response gave, detached from the JSON document (which is disposed right after).</summary>
|
||||
@@ -146,6 +152,12 @@ public sealed record ReadResult
|
||||
|
||||
public ProfileInfo? Viewer { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Identifier of the connected account, also when the answer describes it with nothing else (Instagram's
|
||||
/// <c>xdt_viewer.user</c>): a profile with this identifier in another answer is the connected account (H10).
|
||||
/// </summary>
|
||||
public string? ViewerId { get; init; }
|
||||
|
||||
/// <summary>For unrecognized responses: the key structure, without any value (spec §6.4).</summary>
|
||||
public string? KeyStructure { get; init; }
|
||||
}
|
||||
@@ -185,6 +185,15 @@ public sealed record ReaderVocabulary
|
||||
/// <summary>The key under which the response describes the connected account (H10).</summary>
|
||||
public VocabularyKeys Viewer { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>
|
||||
/// Keys at least one of which, anywhere in a response, makes it «about contents or profiles». A response that has
|
||||
/// none of them is <see cref="ReadShape.Unrelated"/> and ignored, instead of counting as an unknown shape: a real site
|
||||
/// sends many JSON answers that have nothing to do with contents (Instagram: promotions, logging, «seen» marks).
|
||||
/// Plain key names, not paths. Empty: every response counts (the test site, where any unknown answer is a format
|
||||
/// change).
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> Relevance { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Concepts the collection pipeline cannot work without, still unset. While this is not empty, or the status is
|
||||
/// a hypothesis, recipes refuse to run on the site.
|
||||
@@ -319,6 +328,7 @@ public sealed record ReaderVocabulary
|
||||
Highlight = new HighlightKeys { Id = K(h.Id), Title = K(h.Title), Owner = K(h.Owner), Items = K(h.Items) },
|
||||
Page = new PageKeys { HasMore = K(g.HasMore), Cursor = K(g.Cursor) },
|
||||
Viewer = K(file.Viewer),
|
||||
Relevance = [.. (file.Relevance?.Keys ?? []).Where(k => !string.IsNullOrWhiteSpace(k)).Select(k => k.Trim()).Distinct(StringComparer.Ordinal)],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -342,6 +352,15 @@ internal sealed class VocabularyFile
|
||||
public PageDto? Page { get; set; }
|
||||
|
||||
public List<string>? Viewer { get; set; }
|
||||
|
||||
public RelevanceDto? Relevance { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class RelevanceDto
|
||||
{
|
||||
public string? Note { get; set; }
|
||||
|
||||
public List<string>? Keys { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class ContentDto
|
||||
|
||||
@@ -20,10 +20,12 @@ public sealed class ShapeReader
|
||||
private const int MaxDepth = 64;
|
||||
|
||||
private readonly ReaderVocabulary _v;
|
||||
private readonly HashSet<string> _relevance;
|
||||
|
||||
public ShapeReader(ReaderVocabulary vocabulary)
|
||||
{
|
||||
_v = vocabulary ?? throw new ArgumentNullException(nameof(vocabulary));
|
||||
_relevance = new HashSet<string>(vocabulary.Relevance, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
public ReaderVocabulary Vocabulary => _v;
|
||||
@@ -34,6 +36,12 @@ public sealed class ShapeReader
|
||||
var walk = new Walk();
|
||||
Visit(root, walk, owner: null, highlightId: null, depth: 0);
|
||||
|
||||
if (walk.ViewerId is { } viewerId && walk.Profiles.TryGetValue(viewerId, out var own))
|
||||
{
|
||||
// The connected account described by its identifier only, and its profile elsewhere in the same answer.
|
||||
walk.Profiles[viewerId] = own with { IsViewer = true };
|
||||
}
|
||||
|
||||
var profiles = walk.Profiles.Values.ToList();
|
||||
var viewer = profiles.FirstOrDefault(p => p.IsViewer);
|
||||
if (walk.Contents.Count > 0 || walk.Highlights.Count > 0 || profiles.Count > 0)
|
||||
@@ -46,12 +54,18 @@ public sealed class ShapeReader
|
||||
Highlights = walk.Highlights,
|
||||
Page = walk.Page,
|
||||
Viewer = viewer,
|
||||
ViewerId = viewer?.Id ?? walk.ViewerId,
|
||||
};
|
||||
}
|
||||
|
||||
if (IsEmptyShape(root, walk.Page is not null))
|
||||
{
|
||||
return new ReadResult { Shape = ReadShape.Empty, Page = walk.Page };
|
||||
return new ReadResult { Shape = ReadShape.Empty, Page = walk.Page, ViewerId = walk.ViewerId };
|
||||
}
|
||||
|
||||
if (_relevance.Count > 0 && !HasAnyKey(root, 0))
|
||||
{
|
||||
return new ReadResult { Shape = ReadShape.Unrelated, ViewerId = walk.ViewerId };
|
||||
}
|
||||
|
||||
return new ReadResult { Shape = ReadShape.Unrecognized, Page = walk.Page, KeyStructure = KeyStructure.Describe(root) };
|
||||
@@ -93,9 +107,18 @@ public sealed class ShapeReader
|
||||
_v.Page.Cursor.TryGet(node, out var cursor) ? AsText(cursor) : null);
|
||||
}
|
||||
|
||||
if (_v.Viewer.TryGet(node, out var viewerNode) && ReadProfile(viewerNode) is { } viewer)
|
||||
if (_v.Viewer.TryGet(node, out var viewerNode))
|
||||
{
|
||||
walk.AddProfile(viewer with { IsViewer = true });
|
||||
if (ReadProfile(viewerNode) is { } viewer)
|
||||
{
|
||||
walk.AddProfile(viewer with { IsViewer = true });
|
||||
}
|
||||
else if (viewerNode.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
// Instagram describes the connected account with its identifier only (xdt_viewer.user): kept, so a
|
||||
// profile with the same identifier can be recognized as the connected account (H10).
|
||||
walk.ViewerId ??= AsText(Get(_v.Profile.Id, viewerNode));
|
||||
}
|
||||
}
|
||||
|
||||
if (IsContent(node))
|
||||
@@ -116,7 +139,7 @@ public sealed class ShapeReader
|
||||
walk.AddProfile(highlightOwner);
|
||||
}
|
||||
|
||||
var id = AsText(Get(_v.Highlight.Id, node))!;
|
||||
var id = HighlightId(AsText(Get(_v.Highlight.Id, node))!);
|
||||
var before = walk.Contents.Count;
|
||||
if (_v.Highlight.Items.TryGet(node, out var items))
|
||||
{
|
||||
@@ -160,8 +183,26 @@ public sealed class ShapeReader
|
||||
_v.Content.Id.Has(node) && _v.Content.TakenAt.Has(node)
|
||||
&& (_v.Content.Images.Has(node) || _v.Content.Videos.Has(node) || _v.Content.Children.Has(node));
|
||||
|
||||
/// <summary>
|
||||
/// A highlight collection: identifier and title, and — when the vocabulary names them — an owner or its items, so
|
||||
/// that any other object with an «id» and a «title» (a promotion, a section of a page) is not taken for one.
|
||||
/// </summary>
|
||||
private bool IsHighlight(JsonElement node) =>
|
||||
_v.Highlight.Id.Has(node) && _v.Highlight.Title.Has(node) && AsText(Get(_v.Highlight.Id, node)) is not null;
|
||||
_v.Highlight.Id.Has(node) && _v.Highlight.Title.Has(node) && AsText(Get(_v.Highlight.Id, node)) is not null
|
||||
&& ((!_v.Highlight.Owner.IsSet && !_v.Highlight.Items.IsSet) || _v.Highlight.Owner.Has(node) || _v.Highlight.Items.Has(node));
|
||||
|
||||
/// <summary>
|
||||
/// The identifier of a collection as its address carries it: Instagram writes «highlight:17841…» in the data and
|
||||
/// «/stories/highlights/17841…/» in the address (HAR of 21/10/2026), so a «kind:» prefix made of letters is dropped.
|
||||
/// </summary>
|
||||
internal static string HighlightId(string id)
|
||||
{
|
||||
var colon = id.IndexOf(':', StringComparison.Ordinal);
|
||||
return colon > 0 && colon < id.Length - 1 && id.AsSpan(0, colon).IndexOfAnyExcept(Letters) < 0 ? id[(colon + 1)..] : id;
|
||||
}
|
||||
|
||||
private static readonly System.Buffers.SearchValues<char> Letters =
|
||||
System.Buffers.SearchValues.Create("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_");
|
||||
|
||||
private ContentItem? ReadContent(JsonElement node, Walk walk, ProfileInfo? inheritedOwner, string? highlightId)
|
||||
{
|
||||
@@ -322,6 +363,41 @@ public sealed class ShapeReader
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>True when one of the relevance keys of the vocabulary is a property name anywhere under <paramref name="element"/>.</summary>
|
||||
private bool HasAnyKey(JsonElement element, int depth)
|
||||
{
|
||||
if (depth > MaxDepth)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
if (_relevance.Contains(property.Name) || HasAnyKey(property.Value, depth + 1))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
case JsonValueKind.Array:
|
||||
foreach (var item in element.EnumerateArray())
|
||||
{
|
||||
if (HasAnyKey(item, depth + 1))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Empty»: no list with elements anywhere, and either a recognized pagination or only plain values at the top
|
||||
/// (a bare status or error). Anything richer that nothing recognized is an unknown shape.
|
||||
@@ -464,6 +540,9 @@ public sealed class ShapeReader
|
||||
|
||||
public PageInfo? Page { get; set; }
|
||||
|
||||
/// <summary>Identifier of the connected account when the answer gives no more than that.</summary>
|
||||
public string? ViewerId { get; set; }
|
||||
|
||||
/// <summary>Merges what different parts of a response say about the same profile.</summary>
|
||||
public void AddProfile(ProfileInfo profile)
|
||||
{
|
||||
|
||||
@@ -29,6 +29,7 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
private readonly List<CapturedRead> _reads = [];
|
||||
private readonly Dictionary<string, DateTimeOffset> _pending = new(StringComparer.Ordinal);
|
||||
private long _sequence;
|
||||
private string? _viewerId;
|
||||
|
||||
public CaptureCollector(ShapeReader reader, IClock clock)
|
||||
{
|
||||
@@ -41,6 +42,21 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
/// <summary>How long a data response may stay «on its way» before it is forgotten (its body may never come).</summary>
|
||||
public TimeSpan PendingLifetime { get; init; } = TimeSpan.FromSeconds(15);
|
||||
|
||||
/// <summary>
|
||||
/// Identifier of the connected account in the latest site answer that gave one (<see cref="ReadResult.ViewerId"/>),
|
||||
/// also an answer that is otherwise <see cref="ReadShape.Unrelated"/> and not kept.
|
||||
/// </summary>
|
||||
public string? ViewerId
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _viewerId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sequence number of the last read: pass it to <see cref="Since"/> to get what arrives after now.</summary>
|
||||
public long Mark()
|
||||
{
|
||||
@@ -135,7 +151,10 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Reads one body (also used by tests and the probe samples).</summary>
|
||||
/// <summary>
|
||||
/// Reads one body (also used by tests and the probe samples). Returns null, and keeps nothing, for responses that
|
||||
/// are not the site's or that are <see cref="ReadShape.Unrelated"/>.
|
||||
/// </summary>
|
||||
public CapturedRead? Accept(ResponseDescriptor response, JsonElement body)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(response);
|
||||
@@ -150,6 +169,21 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
}
|
||||
|
||||
var result = _reader.Read(body);
|
||||
if (result.ViewerId is { } viewerId)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_viewerId = viewerId;
|
||||
}
|
||||
}
|
||||
|
||||
if (result.Shape == ReadShape.Unrelated)
|
||||
{
|
||||
// Not about contents (promotions, logging): neither data nor an empty page, and not «something new
|
||||
// arrived» for SettleAsync, or a page that keeps logging would never look settled.
|
||||
return null;
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
var read = new CapturedRead(++_sequence, response, result);
|
||||
@@ -166,7 +200,7 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
void IResponseObserver.OnResponse(ResponseDescriptor response)
|
||||
{
|
||||
if (response.HostKind == HostKind.Site
|
||||
&& response.MimeType.Contains("json", StringComparison.OrdinalIgnoreCase)
|
||||
&& DataResponses.IsData(response.MimeType, response.ResourceType)
|
||||
&& response.Status is >= 200 and < 600 && response.Status != 204)
|
||||
{
|
||||
lock (_gate)
|
||||
@@ -176,6 +210,14 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
}
|
||||
}
|
||||
|
||||
void IResponseObserver.OnBodyDropped(string requestId)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_pending.Remove(requestId);
|
||||
}
|
||||
}
|
||||
|
||||
void IResponseObserver.OnNavigation(NavigationDescriptor navigation)
|
||||
{
|
||||
if (!navigation.SameDocument)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
@@ -98,8 +99,12 @@ public sealed partial class RecipeRunner
|
||||
await run.OpenAsync(
|
||||
byPage ? SitePages.FollowingFrom : SitePages.Following,
|
||||
byPage ? Values(("username", mine.Username), ("cursor", stored!)) : Values(("username", mine.Username))).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(mark, r => r.Profiles.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => r.Profiles.Count > 0, null))
|
||||
|
||||
// Only followed profiles say the list came: the page also receives suggested profiles (not followed) and
|
||||
// Alberto's own profile, which would pass for a list that is not there.
|
||||
bool Listed(ReadResult r) => r.Profiles.Any(p => IsListed(p, mine));
|
||||
var reads = await WaitAndSettleAsync(run, mark, Listed).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, Listed, null))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
@@ -109,7 +114,9 @@ public sealed partial class RecipeRunner
|
||||
while (true)
|
||||
{
|
||||
read += await SaveFollowingPageAsync(run, reads, mine, read).ConfigureAwait(false);
|
||||
var page = LastPage(reads);
|
||||
|
||||
// The pagination of the list, never that of another answer (the suggestions, a post, the collections).
|
||||
var page = PageOf(reads, r => r.Profiles.Where(p => IsListed(p, mine)).Select(p => p.Id), r => r.Shape == ReadShape.Empty);
|
||||
if (catchingUp && ((page?.Cursor is { } c && string.Equals(c, stored, StringComparison.Ordinal)) || read >= readBefore))
|
||||
{
|
||||
catchingUp = false; // back where the last run stopped
|
||||
@@ -133,7 +140,7 @@ public sealed partial class RecipeRunner
|
||||
|
||||
await run.PermitAsync(ActionKind.FollowingListPage, mine.Id).ConfigureAwait(false);
|
||||
var counted = !catchingUp;
|
||||
reads = await ScrollForPageAsync(run, r => r.Profiles.Count > 0).ConfigureAwait(false);
|
||||
reads = await ScrollForPageAsync(run, Listed).ConfigureAwait(false);
|
||||
if (counted)
|
||||
{
|
||||
pages++;
|
||||
@@ -175,12 +182,20 @@ public sealed partial class RecipeRunner
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, progress);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A profile of the following list: not Alberto himself, and not one the answer says he does not follow (Instagram
|
||||
/// sends suggested profiles with «friendship_status.following: false», HAR of 21/10/2026). A profile that does not
|
||||
/// say is taken as listed: it came with the list.
|
||||
/// </summary>
|
||||
private static bool IsListed(ProfileInfo profile, Account mine) =>
|
||||
profile.IsFollowed != false && !profile.IsViewer && profile.Id != mine.InstagramId;
|
||||
|
||||
/// <summary>Stores one page of the following list in reading order; renamed followed accounts are recognized.</summary>
|
||||
private async Task<int> SaveFollowingPageAsync(RecipeRun run, IReadOnlyList<CapturedRead> reads, Account mine, int offset)
|
||||
{
|
||||
var now = Env.Clock.Now;
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
var profiles = reads.SelectMany(r => r.Result.Profiles).Where(p => !p.IsViewer && p.Id != mine.InstagramId && seen.Add(p.Id)).ToList();
|
||||
var profiles = reads.SelectMany(r => r.Result.Profiles).Where(p => IsListed(p, mine) && seen.Add(p.Id)).ToList();
|
||||
var records = new List<FollowingRecord>(profiles.Count);
|
||||
for (var i = 0; i < profiles.Count; i++)
|
||||
{
|
||||
|
||||
@@ -122,6 +122,13 @@ public sealed partial class RecipeRunner
|
||||
|
||||
/// <summary>Items already saved by the caller (they are not saved again).</summary>
|
||||
public HashSet<string> Processed { get; init; } = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// The reads the walk starts from answer a gesture of the walk itself (a resume page, a tab): a bare empty answer
|
||||
/// among them is its empty page. After opening the profile it is not: an empty answer there may be about
|
||||
/// something else (the collections of an account that has none).
|
||||
/// </summary>
|
||||
public bool StartsFromOwnAnswer { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -134,9 +141,9 @@ public sealed partial class RecipeRunner
|
||||
private async Task<RecipeStatus> ProfileCheckAsync(RecipeRun run)
|
||||
{
|
||||
var account = await LoadAccountAsync(run).ConfigureAwait(false);
|
||||
var (current, reads) = await OpenProfileAsync(run, account).ConfigureAwait(false);
|
||||
var (current, reads) = await OpenProfileAsync(run, account, waitForGrid: true).ConfigureAwait(false);
|
||||
account = current;
|
||||
var profile = FindProfile(reads, account)!;
|
||||
var profile = AccountProfile(reads, account)!;
|
||||
|
||||
if (profile.LatestStoryAt is { } latest && latest > (account.LastStoriesCheckAt ?? DateTimeOffset.MinValue)
|
||||
&& account.ContentTypes.HasFlag(ContentTypes.Stories))
|
||||
@@ -174,7 +181,7 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
}
|
||||
|
||||
var page = LastPage(reads);
|
||||
var page = WalkPage(reads, account, walk, ownAnswer: false);
|
||||
if (!sawKnown && account.BackfillCompletedAt is null && account.BackfillCursor is null)
|
||||
{
|
||||
if (page?.HasMore == true && page.Cursor is { } cursor)
|
||||
@@ -184,7 +191,11 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
else if (page?.HasMore == false)
|
||||
{
|
||||
// The whole profile is on the first page, saved just now. For an account «Storico in corso» its history
|
||||
// is complete: the engine closes it, with its line (RecipeOutcome.BackfillFinished). An account that
|
||||
// keeps only the new posts had no history to announce.
|
||||
await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false);
|
||||
run.Finished = account.State == AccountState.Backfilling;
|
||||
}
|
||||
}
|
||||
else if (CollectionWriter.Wants(account, EntryKind.Post) && (account.BackfillCursor is not null || account.BackfillCompletedAt is not null))
|
||||
@@ -214,7 +225,7 @@ public sealed partial class RecipeRunner
|
||||
var before = ParseTime(await settings.GetAsync(keys[2], run.Ct).ConfigureAwait(false));
|
||||
async Task ClearAsync() => await settings.SetManyAsync(keys.ToDictionary(k => k, _ => (string?)null), run.Ct).ConfigureAwait(false);
|
||||
|
||||
if (LastPage(reads)?.HasMore == false)
|
||||
if (WalkPage(reads, account, walk, ownAnswer: false)?.HasMore == false)
|
||||
{
|
||||
if (stored is not null || before is not null)
|
||||
{
|
||||
@@ -230,6 +241,7 @@ public sealed partial class RecipeRunner
|
||||
IReadOnlyList<CapturedRead> start = reads;
|
||||
ResumePoint? catchUpTo = null;
|
||||
var pages = 0;
|
||||
var ownStart = false;
|
||||
if (!tailIsNew)
|
||||
{
|
||||
if (stored is null)
|
||||
@@ -242,13 +254,14 @@ public sealed partial class RecipeRunner
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(walk.ResumePage, Values(("username", account.Username), ("cursor", stored.Cursor))).ConfigureAwait(false);
|
||||
start = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(start, r => r.Contents.Count > 0 || r.Page is not null, null))
|
||||
start = await WaitAndSettleAsync(run, mark, r => IsWalkPage(r, account, walk)).ConfigureAwait(false);
|
||||
if (!run.Judge(start, r => IsWalkPage(r, account, walk), null))
|
||||
{
|
||||
return; // an empty page, counted: the gap stays for the next check
|
||||
}
|
||||
|
||||
pages = 1;
|
||||
ownStart = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -262,6 +275,7 @@ public sealed partial class RecipeRunner
|
||||
{
|
||||
CatchUpTo = catchUpTo,
|
||||
PagesRead = pages,
|
||||
StartsFromOwnAnswer = ownStart,
|
||||
MaxPages = Math.Max(1, Env.Options.GapPagesPerCheck),
|
||||
Stop = floor is { } f ? new KnownStop(true, f) : KnownStop.Any,
|
||||
CheckDownloads = true,
|
||||
@@ -341,14 +355,15 @@ public sealed partial class RecipeRunner
|
||||
IReadOnlyList<CapturedRead> reads;
|
||||
var pages = 0;
|
||||
ResumePoint? catchUpTo = null;
|
||||
var ownStart = true; // a resume page or a tab; not the profile as opened
|
||||
if (target is not null && Env.SiteMap.HasPage(walk.ResumePage))
|
||||
{
|
||||
// Resume where the last run stopped: the page of the site that starts after the stored point.
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(walk.ResumePage, Values(("username", account.Username), ("cursor", target.Cursor))).ConfigureAwait(false);
|
||||
reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => r.Contents.Count > 0 || r.Page is not null, Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
reads = await WaitAndSettleAsync(run, mark, r => IsWalkPage(r, account, walk)).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => IsWalkPage(r, account, walk), Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
@@ -357,15 +372,16 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
else
|
||||
{
|
||||
(account, reads) = await OpenProfileAsync(run, account).ConfigureAwait(false);
|
||||
(account, reads) = await OpenProfileAsync(run, account, waitForGrid: walk.IsGrid).ConfigureAwait(false);
|
||||
ownStart = walk.TabTarget is not null;
|
||||
if (walk.TabTarget is { } tab)
|
||||
{
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.ClickAsync(tab, parameters).ConfigureAwait(false);
|
||||
await Env.Driver.WaitAfterLoadAsync(run.Ct).ConfigureAwait(false);
|
||||
reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => r.Contents.Count > 0 || r.Page is not null, null))
|
||||
reads = await WaitAndSettleAsync(run, mark, r => IsWalkPage(r, account, walk)).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => IsWalkPage(r, account, walk), null))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
@@ -383,6 +399,7 @@ public sealed partial class RecipeRunner
|
||||
{
|
||||
CatchUpTo = catchUpTo,
|
||||
PagesRead = pages,
|
||||
StartsFromOwnAnswer = ownStart,
|
||||
MaxPages = maxPages,
|
||||
Stop = checkOnly ? KnownStop.Any : KnownStop.Never,
|
||||
CheckDownloads = !checkOnly,
|
||||
@@ -394,9 +411,10 @@ public sealed partial class RecipeRunner
|
||||
run.Finished = true;
|
||||
if (walk.IsGrid)
|
||||
{
|
||||
// «Storico completato» in Attività, and the new state of the account, are the engine's: one line per
|
||||
// history, with its numbers (SessionComposer, from RecipeOutcome.BackfillFinished).
|
||||
await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false);
|
||||
await settings.SetAsync(walk.MarkKey(account.Id), null, run.Ct).ConfigureAwait(false);
|
||||
await Writer.EventAsync("storico-completato", $"Storico di {account.Username} completato.", EventSeverity.Success, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -436,10 +454,12 @@ public sealed partial class RecipeRunner
|
||||
var pending = rules.CatchUpTo;
|
||||
var pages = rules.PagesRead;
|
||||
var catchUp = 0;
|
||||
var ownAnswer = rules.StartsFromOwnAnswer;
|
||||
IReadOnlySet<string>? seen = null; // the first page: only what its own answers bring
|
||||
while (true)
|
||||
{
|
||||
var items = PageItems(reads, account, walk);
|
||||
var page = LastPage(reads);
|
||||
var page = WalkPage(reads, account, walk, ownAnswer, seen);
|
||||
if (pending is not null && pending.IsReachedBy(page, items, i => walk.IsChronological && !IsPinned(i, items, walk)))
|
||||
{
|
||||
pending = null; // this page holds the stored point: from here on the walk goes on as usual
|
||||
@@ -478,7 +498,13 @@ public sealed partial class RecipeRunner
|
||||
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
|
||||
var counted = pending is null;
|
||||
reads = await ScrollForPageAsync(run, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
|
||||
// Only items of the walk not read yet say the next page came: an answer about something else that arrives
|
||||
// meanwhile (a post of another account, the collections), or one that brings again a post already read
|
||||
// (the page of that post), neither counts as it nor ends the walk with its pagination.
|
||||
reads = await ScrollForPageAsync(run, r => r.Contents.Any(c => IsWalkItem(c, account, walk) && !rules.Processed.Contains(c.Id))).ConfigureAwait(false);
|
||||
ownAnswer = true;
|
||||
seen = rules.Processed;
|
||||
if (counted)
|
||||
{
|
||||
pages++;
|
||||
@@ -556,7 +582,124 @@ public sealed partial class RecipeRunner
|
||||
|
||||
/// <summary>The posts of a walk page: of the account (tagged: of others), never a story or a collection item.</summary>
|
||||
private static IReadOnlyList<ContentItem> PageItems(IReadOnlyList<CapturedRead> reads, Account account, ProfileWalk walk) =>
|
||||
Contents(reads, c => IsPostLike(c) && (walk.Kind == EntryKind.Tagged ? !IsOwnedBy(c, account) : IsOwnedBy(c, account)));
|
||||
Contents(reads, c => IsWalkItem(c, account, walk));
|
||||
|
||||
/// <summary>An item of a walk: a post of the account (tagged: of another account), never a story or a collection item.</summary>
|
||||
private static bool IsWalkItem(ContentItem item, Account account, ProfileWalk walk) =>
|
||||
IsPostLike(item) && (walk.Kind == EntryKind.Tagged ? !IsOwnedBy(item, account) : IsOwnedBy(item, account));
|
||||
|
||||
/// <summary>An answer that brings items of the walk.</summary>
|
||||
private static bool CarriesWalk(ReadResult result, Account account, ProfileWalk walk) =>
|
||||
result.Contents.Any(c => IsWalkItem(c, account, walk));
|
||||
|
||||
/// <summary>
|
||||
/// An answer to a gesture of the walk (a resume page, a tab) that is a page of it on its own: it brings items of the
|
||||
/// walk, or it is an empty page of it (<see cref="IsEmptyWalkPage"/>).
|
||||
/// </summary>
|
||||
private static bool IsWalkPage(ReadResult result, Account account, ProfileWalk walk) =>
|
||||
CarriesWalk(result, account, walk) || IsEmptyWalkPage(result, account, walk, ownAnswer: true);
|
||||
|
||||
/// <summary>
|
||||
/// The end of a tab with nothing in it: a pagination and no item. With the profile of the account (the test site
|
||||
/// sends it with every page of the tab), when nothing else comes with it, or — on the grid — when that profile says
|
||||
/// it has no posts (the test site sends the collections with the first page of the grid). A bare empty answer only
|
||||
/// when it answers a gesture of the walk (<paramref name="ownAnswer"/>): on Instagram the collections of an account
|
||||
/// that has none are an empty connection with «has_next_page: false», as an empty grid would be, and they come
|
||||
/// with the profile too.
|
||||
/// </summary>
|
||||
private static bool IsEmptyWalkPage(ReadResult result, Account account, ProfileWalk walk, bool ownAnswer) =>
|
||||
result.Page is not null && result.Shape switch
|
||||
{
|
||||
ReadShape.Empty => ownAnswer,
|
||||
ReadShape.Recognized => ProfileIn(result, account) is { } profile
|
||||
&& ((result.Contents.Count == 0 && result.Highlights.Count == 0)
|
||||
|| (walk.IsGrid && profile.PostCount == 0 && !result.Contents.Any(IsPostLike))),
|
||||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The pagination of a walk page: from the answer that brought the most items of the walk not read before
|
||||
/// (<paramref name="seen"/>: the pages already read); when none did, from the last empty page of the walk
|
||||
/// (<paramref name="ownAnswer"/>: the reads answer a gesture of the walk, <see cref="IsEmptyWalkPage"/>). Never from
|
||||
/// an answer about something else, nor from one that only brings again a post already read: on Instagram the page
|
||||
/// of a post says «more_available: false» of its single post and the collections say «has_next_page» of
|
||||
/// themselves (HAR of 21/10/2026), and either would end the walk, or mark the history complete, where the grid
|
||||
/// goes on.
|
||||
/// </summary>
|
||||
private static PageInfo? WalkPage(IReadOnlyList<CapturedRead> reads, Account account, ProfileWalk walk, bool ownAnswer, IReadOnlySet<string>? seen = null) =>
|
||||
PageOf(reads, r => r.Contents.Where(c => IsWalkItem(c, account, walk)).Select(c => c.Id), r => IsEmptyWalkPage(r, account, walk, ownAnswer), seen);
|
||||
|
||||
/// <summary>
|
||||
/// The pagination of a page of a list (a profile tab, the feed, the following list): from the answer that brings
|
||||
/// the most items of the list not met before — in <paramref name="seen"/>, or in an earlier answer of the same page
|
||||
/// with a pagination of its own — the last one on a tie; when none brings any, from the last empty page. An answer
|
||||
/// that only brings again items already met, or fewer new ones than another (the page of a single post next to the
|
||||
/// grid), never gives it.
|
||||
/// </summary>
|
||||
private static PageInfo? PageOf(IEnumerable<CapturedRead> reads, Func<ReadResult, IEnumerable<string>> itemIds, Func<ReadResult, bool> isEmptyPage, IReadOnlySet<string>? seen = null)
|
||||
{
|
||||
var met = new HashSet<string>(StringComparer.Ordinal);
|
||||
PageInfo? withItems = null;
|
||||
var most = 0;
|
||||
PageInfo? empty = null;
|
||||
foreach (var result in reads.Select(r => r.Result).Where(r => r.Page is not null))
|
||||
{
|
||||
var carried = 0;
|
||||
var fresh = 0;
|
||||
foreach (var id in itemIds(result))
|
||||
{
|
||||
carried++;
|
||||
if (met.Add(id) && seen?.Contains(id) != true)
|
||||
{
|
||||
fresh++;
|
||||
}
|
||||
}
|
||||
|
||||
if (fresh > 0)
|
||||
{
|
||||
if (fresh >= most)
|
||||
{
|
||||
most = fresh;
|
||||
withItems = result.Page;
|
||||
}
|
||||
}
|
||||
else if (carried == 0 && isEmptyPage(result))
|
||||
{
|
||||
empty = result.Page;
|
||||
}
|
||||
}
|
||||
|
||||
return withItems ?? empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The profile of the account as all the answers of the page describe it: the same profile can come in several
|
||||
/// of them (the profile itself, the author of the posts, the owner of the collections), each with part of its
|
||||
/// facts. The best described one is completed with what the others say; of the pictures, the largest.
|
||||
/// </summary>
|
||||
private static ProfileInfo? AccountProfile(IReadOnlyList<CapturedRead> reads, Account account)
|
||||
{
|
||||
if (FindProfile(reads, account) is not { } best)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (var other in reads.SelectMany(r => r.Result.Profiles).Where(p => p.Id == best.Id).ToList())
|
||||
{
|
||||
best = best with
|
||||
{
|
||||
DisplayName = best.DisplayName ?? other.DisplayName,
|
||||
IsPrivate = best.IsPrivate ?? other.IsPrivate,
|
||||
IsFollowed = best.IsFollowed ?? other.IsFollowed,
|
||||
PostCount = best.PostCount ?? other.PostCount,
|
||||
Picture = other.Picture is { } picture && (best.Picture is null || picture.Area > best.Picture.Area) ? picture : best.Picture,
|
||||
LatestStoryAt = best.LatestStoryAt ?? other.LatestStoryAt,
|
||||
IsViewer = best.IsViewer || other.IsViewer,
|
||||
};
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>Pinned on top of the profile: the vocabulary says so, or (newest first) the order of the page does.</summary>
|
||||
private bool IsPinned(ContentItem item, IReadOnlyList<ContentItem> page, ProfileWalk walk) =>
|
||||
@@ -586,28 +729,32 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the profile page (1 counted action) and reads its state: missing profile, a name now used by another
|
||||
/// account, private profile not followed (rule 6: not touched). Returns the updated account and the reads.
|
||||
/// Opens the profile page (1 counted action) and reads its state: missing profile (when the map has its marker), a
|
||||
/// name now used by another account, private profile not followed (rule 6: not touched). The profile, the posts
|
||||
/// and the collections may come in different answers, and not together: after the profile the page is left to
|
||||
/// settle, and with <paramref name="waitForGrid"/> the first page of posts is waited for too. Returns the updated
|
||||
/// account and everything the page received.
|
||||
/// </summary>
|
||||
private async Task<(Account Account, IReadOnlyList<CapturedRead> Reads)> OpenProfileAsync(RecipeRun run, Account account)
|
||||
private async Task<(Account Account, IReadOnlyList<CapturedRead> Reads)> OpenProfileAsync(RecipeRun run, Account account, bool waitForGrid = false)
|
||||
{
|
||||
var parameters = Values(("username", account.Username));
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false);
|
||||
if ((await run.FindAsync(SiteTargets.ProfileNotFound, parameters).ConfigureAwait(false)).Found)
|
||||
if (Env.SiteMap.IsTargetConfigured(SiteTargets.ProfileNotFound)
|
||||
&& (await run.FindAsync(SiteTargets.ProfileNotFound, parameters).ConfigureAwait(false)).Found)
|
||||
{
|
||||
await MarkUnreachableAsync(run, account, UnreachableReason.NotFound).ConfigureAwait(false);
|
||||
throw RecipeRun.Stop(RecipeStatus.AccountUnreachable, $"Il profilo {account.Username} non esiste o non è più disponibile.");
|
||||
}
|
||||
|
||||
var reads = await run.WaitForDataAsync(mark, r => ProfileIn(r, account) is not null).ConfigureAwait(false);
|
||||
var reads = await WaitAndSettleAsync(run, mark, r => ProfileIn(r, account) is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => ProfileIn(r, account) is not null, Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
|
||||
var profile = FindProfile(reads, account)!;
|
||||
var profile = AccountProfile(reads, account)!;
|
||||
if (account.InstagramId is { } known && profile.Id != known)
|
||||
{
|
||||
await MarkUnreachableAsync(run, account, UnreachableReason.Renamed).ConfigureAwait(false);
|
||||
@@ -629,9 +776,58 @@ public sealed partial class RecipeRunner
|
||||
account = await Env.Storage.Accounts.GetAsync(account.Id, run.Ct).ConfigureAwait(false) ?? account;
|
||||
}
|
||||
|
||||
if (waitForGrid)
|
||||
{
|
||||
reads = await WaitForGridAsync(run, mark, account, reads).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return (account, reads);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits for <paramref name="expected"/> after <paramref name="mark"/>, then lets the page settle and returns
|
||||
/// everything that arrived since the mark: what one page shows can come in several answers, the expected one not
|
||||
/// always last, and stopping at the first that matches would lose the others. When the expected data does not
|
||||
/// come, returns what came, to be judged.
|
||||
/// </summary>
|
||||
private async Task<IReadOnlyList<CapturedRead>> WaitAndSettleAsync(RecipeRun run, long mark, Func<ReadResult, bool> expected)
|
||||
{
|
||||
var reads = await run.WaitForDataAsync(mark, expected).ConfigureAwait(false);
|
||||
if (!reads.Any(r => r.Result.Shape == ReadShape.Recognized && expected(r.Result)))
|
||||
{
|
||||
return reads;
|
||||
}
|
||||
|
||||
await run.SettleAsync().ConfigureAwait(false);
|
||||
return Env.Capture.Since(mark);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first page of the grid, when it did not come with the profile: the page may ask for it only after drawing
|
||||
/// the profile, later than it takes to settle. Waits for posts of the account or an empty grid that is surely its
|
||||
/// own (<see cref="IsEmptyWalkPage"/>: a bare empty answer may be the collections), then lets the page settle again.
|
||||
/// Nothing is judged here (the profile came): a profile without posts that does not say so only costs the wait.
|
||||
/// </summary>
|
||||
private async Task<IReadOnlyList<CapturedRead>> WaitForGridAsync(RecipeRun run, long mark, Account account, IReadOnlyList<CapturedRead> reads)
|
||||
{
|
||||
var walk = ProfileWalk.Posts;
|
||||
bool Arrived(IReadOnlyList<CapturedRead> list) => PageItems(list, account, walk).Count > 0 || WalkPage(list, account, walk, ownAnswer: false) is not null;
|
||||
if (Arrived(reads))
|
||||
{
|
||||
return reads;
|
||||
}
|
||||
|
||||
var arrived = await Env.Capture.WaitAsync(mark, list => run.Signal is not null || Arrived(list), Env.Options.DataTimeout, Env.Options.Poll, run.Ct).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
if (!Arrived(arrived))
|
||||
{
|
||||
return arrived;
|
||||
}
|
||||
|
||||
await run.SettleAsync().ConfigureAwait(false);
|
||||
return Env.Capture.Since(mark);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scrolls with bursts until a new page of data that satisfies <paramref name="expected"/> arrives, at most
|
||||
/// <see cref="RecipeOptions.BurstsPerPage"/> bursts. Only the expected data ends the bursts: a response the page
|
||||
@@ -669,9 +865,6 @@ public sealed partial class RecipeRunner
|
||||
/// <summary>Outcome message of a page that arrived without data (three in a row raise a throttle signal).</summary>
|
||||
private const string EmptyPageMessage = "La pagina è arrivata vuota: nessun dato da leggere.";
|
||||
|
||||
private static PageInfo? LastPage(IEnumerable<CapturedRead> reads) =>
|
||||
reads.Where(r => r.Result.Page is not null).Select(r => r.Result.Page).LastOrDefault();
|
||||
|
||||
private static DateTimeOffset? ParseTime(string? value) =>
|
||||
DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var time) ? time : null;
|
||||
|
||||
|
||||
@@ -17,34 +17,61 @@ public sealed partial class RecipeRunner
|
||||
await run.PermitAsync(ActionKind.Home, null).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Home).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Profiles.Count > 0).ConfigureAwait(false);
|
||||
run.Judge(reads, r => r.Contents.Count > 0 || r.Profiles.Count > 0, Env.SiteMap.BuildPath(SitePages.Home));
|
||||
|
||||
// The feed and the stories bar may come in different answers: after the first, the page is left to settle.
|
||||
var reads = await WaitAndSettleAsync(run, mark, HomeArrived).ConfigureAwait(false);
|
||||
run.Judge(reads, HomeArrived, Env.SiteMap.BuildPath(SitePages.Home));
|
||||
|
||||
var processed = 0;
|
||||
var sawKnown = await ProcessSweepReadsAsync(run, reads, ref processed).ConfigureAwait(false);
|
||||
var hasMore = reads.Select(r => r.Result.Page).LastOrDefault(p => p is not null)?.HasMore ?? true;
|
||||
var hasMore = FeedPage(reads)?.HasMore ?? true;
|
||||
|
||||
// Everything after the last read taken, so that nothing arriving while the posts are saved is missed.
|
||||
var seen = reads.Count > 0 ? reads[^1].Sequence : mark;
|
||||
for (var burst = 0; burst < Env.Options.SweepMaxBursts && !sawKnown && hasMore; burst++)
|
||||
{
|
||||
var before = Env.Capture.Mark();
|
||||
await Env.Driver.ScrollBurstAsync(run.Ct).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
await run.SettleAsync().ConfigureAwait(false);
|
||||
var more = Env.Capture.Since(before);
|
||||
var more = Env.Capture.Since(seen);
|
||||
if (more.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
seen = more[^1].Sequence;
|
||||
var met = Contents(reads, IsPostLike).Select(c => c.Id).ToHashSet(StringComparer.Ordinal);
|
||||
reads = [.. reads, .. more];
|
||||
sawKnown = await ProcessSweepReadsAsync(run, reads, ref processed).ConfigureAwait(false);
|
||||
hasMore = more.Select(r => r.Result.Page).LastOrDefault(p => p is not null)?.HasMore ?? hasMore;
|
||||
hasMore = FeedPage(more, met)?.HasMore ?? hasMore;
|
||||
}
|
||||
|
||||
await Env.Driver.MaybeDistractionAsync(run.Ct).ConfigureAwait(false);
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The home arrived: posts, an account of the stories bar (it says when its latest story was published) or a page
|
||||
/// of the feed. Profiles alone do not say it: Instagram also sends suggested profiles, not followed (HAR of
|
||||
/// 21/10/2026), and they would pass for a home that is not there.
|
||||
/// </summary>
|
||||
private static bool HomeArrived(ReadResult result) =>
|
||||
result.Contents.Count > 0 || result.Profiles.Any(p => p.LatestStoryAt is not null) || result.Page is not null;
|
||||
|
||||
/// <summary>
|
||||
/// The pagination of the feed: from the answer that brought the most posts not met before (<paramref name="met"/>:
|
||||
/// the earlier answers of the run); when none did, from an answer that brought no contents nor collections (an
|
||||
/// empty feed). Never from an answer that brought only stories or collection items (the collections say
|
||||
/// «has_next_page» of themselves), nor from one that only brings again a post already met (the page of that post
|
||||
/// says «more_available: false» of itself).
|
||||
/// </summary>
|
||||
private static PageInfo? FeedPage(IReadOnlyList<CapturedRead> reads, IReadOnlySet<string>? met = null) =>
|
||||
PageOf(
|
||||
reads,
|
||||
r => r.Contents.Where(IsPostLike).Select(c => c.Id),
|
||||
r => (r.Shape is ReadShape.Empty or ReadShape.Recognized) && r.Contents.Count == 0 && r.Highlights.Count == 0,
|
||||
met);
|
||||
|
||||
/// <summary>Saves the posts not processed yet; returns true once known content has been met.</summary>
|
||||
private Task<bool> ProcessSweepReadsAsync(RecipeRun run, IReadOnlyList<CapturedRead> reads, ref int processed)
|
||||
{
|
||||
@@ -101,11 +128,20 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Alberto's own profile («Tu») from the data the page receives (H10), the first time it is seen.
|
||||
/// Alberto's own profile («Tu») from the data the page receives (H10), the first time it is seen: an answer that
|
||||
/// presents it with its name, or — Instagram's way, whose «xdt_viewer.user» gives only an identifier (HAR of
|
||||
/// 21/10/2026) — the identifier from one answer of the run and the profile with that identifier, name included,
|
||||
/// from any answer of the run (his own entry in the stories bar, for instance).
|
||||
/// </summary>
|
||||
private async Task EnsureMineAsync(IReadOnlyList<CapturedRead> reads, RecipeRun run)
|
||||
{
|
||||
if (reads.Select(r => r.Result.Viewer).FirstOrDefault(v => v is not null) is not { } viewer)
|
||||
var viewer = reads.Select(r => r.Result.Viewer).FirstOrDefault(v => v is not null);
|
||||
if (viewer is null && (reads.Select(r => r.Result.ViewerId).FirstOrDefault(id => id is not null) ?? Env.Capture.ViewerId) is { } viewerId)
|
||||
{
|
||||
viewer = reads.SelectMany(r => r.Result.Profiles).FirstOrDefault(p => p.Id == viewerId);
|
||||
}
|
||||
|
||||
if (viewer is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Runtime.ExceptionServices;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
@@ -11,6 +12,17 @@ public sealed partial class RecipeRunner
|
||||
/// <summary>A story stays on offer for a day (spec §4.3: «storie attive nelle 24 ore»).</summary>
|
||||
private static readonly TimeSpan StoryLifetime = TimeSpan.FromHours(24);
|
||||
|
||||
/// <summary>
|
||||
/// Without the item in the address, how long before a video ends the gesture that leaves it («next», or close) starts
|
||||
/// at the latest: the pointer travel and the pause on the target of §7.7 (up to 1.2 s) with room to spare, multiplied
|
||||
/// by mood and pace like the gesture. The viewer moves on by itself when the video ends, and the address would not
|
||||
/// say so: a «next» pressed after that would skip an item.
|
||||
/// </summary>
|
||||
private static readonly TimeSpan VideoClickLead = TimeSpan.FromSeconds(1.5);
|
||||
|
||||
/// <summary>The placeholder of a viewer address that names the item shown; optional (Instagram's highlight viewer has none).</summary>
|
||||
private const string ItemKey = "id";
|
||||
|
||||
/// <summary>
|
||||
/// Storie di un account (spec §6.3): checks that the budget allows at least ten stories, opens the viewer from the
|
||||
/// stories bar (when the home is on screen) or from the profile, watches the stories one by one with the timings of
|
||||
@@ -66,7 +78,7 @@ public sealed partial class RecipeRunner
|
||||
throw RecipeRun.Stop(RecipeStatus.TargetNotFound, $"{ring.Message} Il profilo di {account.Username} dice però che c'è una storia attiva: la mappa dei bersagli va controllata.");
|
||||
}
|
||||
|
||||
await StoriesCheckedAsync(account, run).ConfigureAwait(false);
|
||||
await StoriesCheckedAsync(account, run.Ct).ConfigureAwait(false);
|
||||
return RecipeStatus.Completed; // no active stories: nothing to open
|
||||
}
|
||||
}
|
||||
@@ -77,13 +89,14 @@ public sealed partial class RecipeRunner
|
||||
var opened = await OpenViewerAsync(run, target, parameters, SitePages.StoryViewer).ConfigureAwait(false);
|
||||
var watched = await WatchViewerAsync(run, SitePages.StoryViewer, "username", account.Username, account, viewerMark, opened).ConfigureAwait(false);
|
||||
var shown = watched.Shown;
|
||||
var ct = watched.StoreToken(run);
|
||||
|
||||
var stories = Contents(Env.Capture.Since(viewerMark), c => IsOwnedBy(c, account));
|
||||
foreach (var id in shown)
|
||||
{
|
||||
if (stories.FirstOrDefault(s => s.Id == id) is { } story)
|
||||
{
|
||||
var saved = await Writer.SaveAsync(account, story, EntryKind.Story, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
var saved = await Writer.SaveAsync(account, story, EntryKind.Story, run.Session.SessionId, ct).ConfigureAwait(false);
|
||||
if (saved.Outcome == SaveOutcome.Created)
|
||||
{
|
||||
run.NewEntries++;
|
||||
@@ -91,12 +104,8 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
}
|
||||
|
||||
await StoriesCheckedAsync(account, run).ConfigureAwait(false);
|
||||
if (watched.Stop is { } stop)
|
||||
{
|
||||
throw stop;
|
||||
}
|
||||
|
||||
await StoriesCheckedAsync(account, ct).ConfigureAwait(false);
|
||||
watched.ThrowIfStopped();
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
@@ -105,10 +114,15 @@ public sealed partial class RecipeRunner
|
||||
/// StoryView permit per content shown) and closes the viewer after the last one. A content that is a story already
|
||||
/// saved is referenced, not downloaded again (H9).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Collections are compared in the form of their address: Instagram writes «highlight:1790…» in its data and
|
||||
/// «/stories/highlights/1790…/» in the address (HAR of 21/10/2026); the reader keeps the second, and the requested
|
||||
/// identifier is taken in either form.
|
||||
/// </remarks>
|
||||
private async Task<RecipeStatus> HighlightAsync(RecipeRun run)
|
||||
{
|
||||
var account = await LoadAccountAsync(run).ConfigureAwait(false);
|
||||
if (run.Request.HighlightId is not { Length: > 0 } highlightId)
|
||||
if (run.Request.HighlightId is not { Length: > 0 } requested)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, "«Raccolta in evidenza» ha bisogno dell'identificativo della raccolta.");
|
||||
}
|
||||
@@ -118,26 +132,38 @@ public sealed partial class RecipeRunner
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, $"«Storie in evidenza» è spento per {account.Username}.");
|
||||
}
|
||||
|
||||
var highlightId = ShapeReader.HighlightId(requested);
|
||||
await EnsureStoryBudgetAsync(run, account).ConfigureAwait(false);
|
||||
var parameters = Values(("username", account.Username));
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(mark, r => r.Highlights.Count > 0 || ProfileIn(r, account) is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => r.Highlights.Count > 0 || r.Profiles.Count > 0, Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
|
||||
// Only this account's profile or collections say the page arrived: profiles suggested beside it do not.
|
||||
var reads = await run.WaitForDataAsync(mark, r => OwnProfileOrCollectionsIn(r, account)).ConfigureAwait(false);
|
||||
if (!reads.Any(r => r.Result.Highlights.Any(h => h.Id == highlightId && IsHighlightOf(h, account))))
|
||||
{
|
||||
// The collections may come in an answer of their own, after the profile: let the page settle first.
|
||||
await run.SettleAsync().ConfigureAwait(false);
|
||||
reads = Env.Capture.Since(mark);
|
||||
}
|
||||
|
||||
if (!run.Judge(reads, r => OwnProfileOrCollectionsIn(r, account), Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
|
||||
if (FindProfile(reads, account) is { } profile)
|
||||
{
|
||||
account = await Writer.ApplyProfileAsync(account, profile, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var listed = reads.SelectMany(r => r.Result.Highlights).Where(h => h.Owner is null || h.Owner.Id == account.InstagramId).ToList();
|
||||
var listed = reads.SelectMany(r => r.Result.Highlights).Where(h => IsHighlightOf(h, account)).ToList();
|
||||
var collections = await Writer.UpsertHighlightsAsync(account, listed, run.Ct).ConfigureAwait(false);
|
||||
if (!collections.TryGetValue(highlightId, out var highlight))
|
||||
{
|
||||
var known = await Env.Storage.Highlights.FindAsync(account.Id, highlightId, run.Ct).ConfigureAwait(false);
|
||||
var known = await Env.Storage.Highlights.FindAsync(account.Id, highlightId, run.Ct).ConfigureAwait(false)
|
||||
?? (requested == highlightId ? null : await Env.Storage.Highlights.FindAsync(account.Id, requested, run.Ct).ConfigureAwait(false));
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, known is null
|
||||
? "La raccolta non è nel profilo."
|
||||
: $"La raccolta «{known.Title}» non è più nel profilo: i suoi file restano.");
|
||||
@@ -145,11 +171,13 @@ public sealed partial class RecipeRunner
|
||||
|
||||
await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false);
|
||||
var viewerMark = Env.Capture.Mark();
|
||||
var opened = await OpenViewerAsync(run, SiteTargets.ProfileHighlight, Values(("id", highlightId), ("username", account.Username)), SitePages.HighlightViewer).ConfigureAwait(false);
|
||||
var target = Values(("id", highlightId), ("username", account.Username), ("title", highlight.Title));
|
||||
var opened = await OpenViewerAsync(run, SiteTargets.ProfileHighlight, target, SitePages.HighlightViewer).ConfigureAwait(false);
|
||||
var watched = await WatchViewerAsync(run, SitePages.HighlightViewer, "highlight", highlightId, account, viewerMark, opened).ConfigureAwait(false);
|
||||
var shown = watched.Shown;
|
||||
var ct = watched.StoreToken(run);
|
||||
|
||||
var items = Contents(Env.Capture.Since(viewerMark), c => c.HighlightId == highlightId);
|
||||
var items = Contents(Env.Capture.Since(viewerMark), c => InCollection(c, highlightId));
|
||||
var ordered = new List<long>();
|
||||
foreach (var id in shown)
|
||||
{
|
||||
@@ -158,7 +186,7 @@ public sealed partial class RecipeRunner
|
||||
continue;
|
||||
}
|
||||
|
||||
var (entry, created) = await Writer.LinkHighlightItemAsync(account, highlight, item, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
var (entry, created) = await Writer.LinkHighlightItemAsync(account, highlight, item, run.Session.SessionId, ct).ConfigureAwait(false);
|
||||
if (created)
|
||||
{
|
||||
run.NewEntries++;
|
||||
@@ -172,15 +200,11 @@ public sealed partial class RecipeRunner
|
||||
|
||||
if (items.Count > 0 && items.All(i => shown.Contains(i.Id)) && ordered.Count == items.Count)
|
||||
{
|
||||
await Env.Storage.Highlights.SetItemsAsync(highlight.Id, ordered, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await Env.Storage.Highlights.UpsertAsync(highlight with { LastCheckedAt = Env.Clock.Now }, run.Ct).ConfigureAwait(false);
|
||||
if (watched.Stop is { } stop)
|
||||
{
|
||||
throw stop;
|
||||
await Env.Storage.Highlights.SetItemsAsync(highlight.Id, ordered, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await Env.Storage.Highlights.UpsertAsync(highlight with { LastCheckedAt = Env.Clock.Now }, ct).ConfigureAwait(false);
|
||||
watched.ThrowIfStopped();
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
@@ -196,15 +220,29 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Clicks what opens a viewer and waits for it; one more click if the first one went unnoticed.</summary>
|
||||
private async Task<IReadOnlyDictionary<string, string>> OpenViewerAsync(RecipeRun run, string target, IReadOnlyDictionary<string, string> parameters, string viewerPage)
|
||||
/// <summary>
|
||||
/// Clicks what opens a viewer and waits for it; one more click if the first one went unnoticed. Returns the address
|
||||
/// shown and when the first click started (the first item cannot have come on screen before). When the click takes
|
||||
/// the page to an address the map does not take for the viewer (its shape in the map may be wrong), what opened is
|
||||
/// closed like a viewer before the recipe stops: left open, it would move on by itself to other accounts.
|
||||
/// </summary>
|
||||
private async Task<ViewerOpening> OpenViewerAsync(RecipeRun run, string target, IReadOnlyDictionary<string, string> parameters, string viewerPage)
|
||||
{
|
||||
var before = await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false);
|
||||
var clickedAt = Env.Clock.Now;
|
||||
for (var attempt = 0; attempt < 2; attempt++)
|
||||
{
|
||||
await run.ClickAsync(target, parameters).ConfigureAwait(false);
|
||||
if (await WaitForViewerAsync(run, viewerPage, previous: null).ConfigureAwait(false) is { } opened)
|
||||
{
|
||||
return opened;
|
||||
return new ViewerOpening(opened, clickedAt);
|
||||
}
|
||||
|
||||
if (!string.Equals(await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false), before, StringComparison.Ordinal))
|
||||
{
|
||||
// The click was noticed, but what opened has not the shape of the viewer: no second click on it.
|
||||
await CloseAsync(run, path => !string.Equals(path, before, StringComparison.Ordinal)).ConfigureAwait(false);
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, $"Dopo il clic l'indirizzo non ha la forma «{viewerPage}» della mappa {Env.SiteMap.Source ?? Env.SiteMap.Site}: ciò che si è aperto è stato chiuso. La forma va controllata.");
|
||||
}
|
||||
|
||||
if (!(await run.FindAsync(target, parameters).ConfigureAwait(false)).Found)
|
||||
@@ -217,141 +255,383 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Watches a viewer that shows <paramref name="opened"/>: reads the item shown from the address of the page, waits
|
||||
/// the time of §7.7, asks a StoryView permit before each «next» (and after the fact when the viewer moved on by
|
||||
/// itself) and closes the viewer after the last item of <paramref name="owner"/>, or as soon as it shows something
|
||||
/// else. On any stop other than a signal the viewer is closed first. Returns the identifiers shown, in order.
|
||||
/// Watches a viewer that shows <paramref name="opened"/>: on each item it first asks the StoryView permit for the
|
||||
/// item after it (before it can come on screen, by a click or by itself), then waits the time of §7.7, and closes
|
||||
/// the viewer after the last item of <paramref name="owner"/>, or as soon as it shows something else. The item
|
||||
/// shown is read from the address when the address carries it (<see cref="FollowAddressAsync"/>), otherwise counted
|
||||
/// (<see cref="FollowCountAsync"/>). On any stop other than a signal, an unexpected error included, the viewer is
|
||||
/// closed first; a viewer that stays open stops the run as a target not found. A cancellation leaves the page as it
|
||||
/// is. Returns the identifiers shown, in order, each under its permit.
|
||||
/// </summary>
|
||||
private async Task<ViewerResult> WatchViewerAsync(RecipeRun run, string viewerPage, string ownerKey, string owner, Account account, long mark, IReadOnlyDictionary<string, string> opened)
|
||||
private async Task<ViewerResult> WatchViewerAsync(RecipeRun run, string viewerPage, string ownerKey, string owner, Account account, long mark, ViewerOpening opened)
|
||||
{
|
||||
var shown = new List<string>();
|
||||
var counted = new HashSet<string>(StringComparer.Ordinal);
|
||||
var pendingPermit = true; // asked before the click that opened the viewer
|
||||
var position = opened;
|
||||
var stuck = 0;
|
||||
var viewer = new ViewerWatch(viewerPage, ownerKey, owner, account, mark);
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
try
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
if (!string.Equals(position[ownerKey], owner, StringComparison.OrdinalIgnoreCase))
|
||||
if (!opened.Position.ContainsKey(ownerKey))
|
||||
{
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
await Writer.EventAsync(
|
||||
"visualizzatore-altro-account",
|
||||
viewerPage == SitePages.StoryViewer
|
||||
? $"Dopo le storie di {account.Username} il visualizzatore è passato a un altro account: chiuso, quelle storie non si salvano."
|
||||
: $"Il visualizzatore è passato a un'altra raccolta di {account.Username}: chiuso senza salvarla.",
|
||||
EventSeverity.Warning,
|
||||
account.Id,
|
||||
run.Session.SessionId,
|
||||
run.Ct).ConfigureAwait(false);
|
||||
return new ViewerResult(shown, null);
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, $"La forma dell'indirizzo «{viewerPage}» nella mappa {Env.SiteMap.Source ?? Env.SiteMap.Site} non dice di chi è il visualizzatore: manca «{{{ownerKey}}}».");
|
||||
}
|
||||
|
||||
var id = position["id"];
|
||||
if (counted.Add(id))
|
||||
if (opened.Position.ContainsKey(ItemKey))
|
||||
{
|
||||
if (!pendingPermit)
|
||||
{
|
||||
// The viewer moved on by itself: this item was shown without asking first; ask now.
|
||||
await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
pendingPermit = false;
|
||||
shown.Add(id);
|
||||
await FollowAddressAsync(run, viewer, opened.Position, shown).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await FollowCountAsync(run, viewer, opened, shown).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The list of the account arrives with the viewer (H4): it tells which item is the last one.
|
||||
var list = await ViewerListAsync(run, mark, viewerPage, owner, account).ConfigureAwait(false);
|
||||
var item = list.FirstOrDefault(i => i.Id == id);
|
||||
var video = item?.Files.FirstOrDefault(f => f.Kind == MediaKind.Video)?.Duration;
|
||||
await Env.Driver.WaitAsync(StoryTimings.Watch(Env.Random, video, Env.Driver.WaitMultiplier), run.Ct).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
|
||||
var current = Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
|
||||
if (current is null)
|
||||
{
|
||||
return new ViewerResult(shown, null); // the viewer closed by itself
|
||||
}
|
||||
|
||||
if (!SamePosition(current, position))
|
||||
{
|
||||
position = current; // it moved on by itself while we watched
|
||||
continue;
|
||||
}
|
||||
|
||||
var index = list.FindIndex(i => i.Id == id);
|
||||
if (list.Count > 0 && index == list.Count - 1)
|
||||
{
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
return new ViewerResult(shown, null);
|
||||
}
|
||||
|
||||
if (!pendingPermit)
|
||||
{
|
||||
await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false);
|
||||
pendingPermit = true;
|
||||
}
|
||||
|
||||
await run.ClickAsync(SiteTargets.ViewerNext).ConfigureAwait(false);
|
||||
var next = await WaitForViewerAsync(run, viewerPage, previous: current).ConfigureAwait(false);
|
||||
if (next is null)
|
||||
{
|
||||
return new ViewerResult(shown, null); // closed after the last item
|
||||
}
|
||||
|
||||
if (SamePosition(next, current))
|
||||
{
|
||||
if (++stuck >= 2)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, "Il visualizzatore non va avanti.");
|
||||
}
|
||||
|
||||
continue; // the click went unnoticed: watch a little more and try again
|
||||
}
|
||||
|
||||
stuck = 0;
|
||||
position = next;
|
||||
return new ViewerResult(shown, null);
|
||||
}
|
||||
}
|
||||
catch (RecipeStopException stop)
|
||||
{
|
||||
if (stop.Status != RecipeStatus.StoppedBySignal)
|
||||
catch (RecipeStopException stop)
|
||||
{
|
||||
// Leave no viewer open: it would move on by itself to other accounts. After a signal the page stays as it is.
|
||||
try
|
||||
{
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
}
|
||||
catch (RecipeStopException)
|
||||
{
|
||||
}
|
||||
var stillOpen = stop.Status == RecipeStatus.StoppedBySignal ? null : await TryCloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
return new ViewerResult(shown, Worse(stop, stillOpen));
|
||||
}
|
||||
|
||||
return new ViewerResult(shown, stop);
|
||||
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
|
||||
{
|
||||
// Not even an unexpected error leaves the viewer open; what was shown until then is saved all the same.
|
||||
var stillOpen = await TryCloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
return new ViewerResult(shown, Worse(RecipeRun.Stop(RecipeStatus.Failed, $"Errore imprevisto in «{Name(run.Request.Kind)}» ({ex.GetType().Name}): {ex.Message}"), stillOpen));
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException cancelled)
|
||||
{
|
||||
// A pause, the session closed by a signal, Alberto taking the browser: the page is left as it is, what was
|
||||
// shown under its permit is saved all the same, then the cancellation goes on.
|
||||
return new ViewerResult(shown, null, ExceptionDispatchInfo.Capture(cancelled));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a viewer showed, and why it stopped early (the caller saves what was shown, then stops).</summary>
|
||||
private sealed record ViewerResult(List<string> Shown, RecipeStopException? Stop);
|
||||
/// <summary>
|
||||
/// Follows a viewer whose address carries the item shown (the test site: «/storie/{username}/{id}/»): every
|
||||
/// position is read from the address, so an item the viewer skipped or showed by itself is known for what it is.
|
||||
/// The permit asked on an item covers the next one, also when it comes by itself; an item that comes by itself
|
||||
/// after what the list gave as the last one had no permit: the viewer is closed and it is not saved.
|
||||
/// </summary>
|
||||
private async Task FollowAddressAsync(RecipeRun run, ViewerWatch viewer, IReadOnlyDictionary<string, string> opened, List<string> shown)
|
||||
{
|
||||
var counted = new HashSet<string>(StringComparer.Ordinal);
|
||||
var permitted = true; // asked before the click that opened the viewer: for the first item on screen
|
||||
var position = opened;
|
||||
var stuck = 0;
|
||||
while (true)
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
if (!viewer.ShowsOwner(position))
|
||||
{
|
||||
await LeaveOtherOwnerAsync(run, viewer).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var id = position[ItemKey];
|
||||
if (counted.Add(id))
|
||||
{
|
||||
if (!permitted)
|
||||
{
|
||||
await CloseEarlyAsync(run, viewer, viewer.Page == SitePages.StoryViewer
|
||||
? $"Il visualizzatore è andato avanti da solo dopo quella che per la pagina era l'ultima storia di {viewer.Account.Username}: chiuso, la storia in più non si salva."
|
||||
: $"Il visualizzatore è andato avanti da solo dopo quello che per la pagina era l'ultimo contenuto della raccolta di {viewer.Account.Username}: chiuso, il contenuto in più non si salva.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
permitted = false;
|
||||
shown.Add(id);
|
||||
}
|
||||
|
||||
var since = Env.Clock.Now;
|
||||
|
||||
// The list of the account arrives with the viewer (H4): it tells which item is the last one.
|
||||
var list = await ViewerListAsync(run, viewer).ConfigureAwait(false);
|
||||
var index = list.FindIndex(i => i.Id == id);
|
||||
var last = list.Count > 0 && index == list.Count - 1;
|
||||
if (!last && !permitted)
|
||||
{
|
||||
// The permit for the item after this one, before it can come on screen.
|
||||
await run.PermitAsync(ActionKind.StoryView, viewer.Account.Id).ConfigureAwait(false);
|
||||
permitted = true;
|
||||
}
|
||||
|
||||
await WatchAsync(run, index < 0 ? null : VideoDuration(list[index]), since, latest: null).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
|
||||
var current = Env.SiteMap.Match(viewer.Page, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
|
||||
if (current is null)
|
||||
{
|
||||
return; // the viewer closed by itself
|
||||
}
|
||||
|
||||
if (!SamePosition(current, position))
|
||||
{
|
||||
position = current; // it moved on by itself while we watched
|
||||
continue;
|
||||
}
|
||||
|
||||
if (last)
|
||||
{
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await run.ClickAsync(SiteTargets.ViewerNext).ConfigureAwait(false);
|
||||
var next = await WaitForViewerAsync(run, viewer.Page, previous: current).ConfigureAwait(false);
|
||||
if (next is null)
|
||||
{
|
||||
return; // closed after the last item
|
||||
}
|
||||
|
||||
if (SamePosition(next, current))
|
||||
{
|
||||
if (++stuck >= 2)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, "Il visualizzatore non va avanti.");
|
||||
}
|
||||
|
||||
continue; // the click went unnoticed: watch a little more and try again
|
||||
}
|
||||
|
||||
stuck = 0;
|
||||
position = next;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Follows a viewer whose address does not say which item is shown: Instagram's highlight viewer stays on
|
||||
/// «/stories/highlights/{id}/» from one item to the next (HAR of 21/10/2026). The items are counted against the
|
||||
/// list the page received for the owner: the first one shown is the first of the list, and each click on «next»
|
||||
/// moves one on. A move the viewer makes by itself cannot be seen, so it is never counted: a video, which moves the
|
||||
/// viewer on when it ends, is left before then (<see cref="VideoClickLead"/>), and when that is no longer possible
|
||||
/// (the Governor's wait for the permit took its time) the viewer is closed without clicking «next», the items after
|
||||
/// it not saved. A photo is never taken as over, because how long the site keeps it is not in the data: should the
|
||||
/// viewer leave one by itself, the count falls behind and its last «next» takes the viewer to another collection,
|
||||
/// where it is closed. A click the page ignores would put the count ahead: nothing in the address or in the data
|
||||
/// tells it yet (to be measured live).
|
||||
/// </summary>
|
||||
private async Task FollowCountAsync(RecipeRun run, ViewerWatch viewer, ViewerOpening opened, List<string> shown)
|
||||
{
|
||||
var position = opened.Position;
|
||||
var index = 0;
|
||||
var appearedAfter = opened.ClickedAt; // the item at «index» did not come on screen before this
|
||||
while (true)
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
if (!viewer.ShowsOwner(position))
|
||||
{
|
||||
await LeaveOtherOwnerAsync(run, viewer).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var since = Env.Clock.Now;
|
||||
var list = await ViewerListAsync(run, viewer).ConfigureAwait(false);
|
||||
if (index >= list.Count)
|
||||
{
|
||||
// The page described nothing (more) for this owner: which item is on screen cannot be told.
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// On screen under the permit asked before it could come: before opening, or on the item before it.
|
||||
var item = list[index];
|
||||
if (!shown.Contains(item.Id, StringComparer.Ordinal))
|
||||
{
|
||||
shown.Add(item.Id);
|
||||
}
|
||||
|
||||
var last = index == list.Count - 1;
|
||||
var video = VideoDuration(item);
|
||||
DateTimeOffset? leaveBy = video is { } duration && duration > TimeSpan.Zero
|
||||
? appearedAfter + duration - TimeSpan.FromTicks((long)(VideoClickLead.Ticks * Env.Driver.WaitMultiplier))
|
||||
: null;
|
||||
if (!last)
|
||||
{
|
||||
// The permit for the item after this one, before it can come on screen; asked only while the viewer
|
||||
// surely has not moved on by itself, and the item still has to be left in time once it is granted.
|
||||
if (!Passed(leaveBy))
|
||||
{
|
||||
await run.PermitAsync(ActionKind.StoryView, viewer.Account.Id).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (Passed(leaveBy))
|
||||
{
|
||||
await CloseEarlyAsync(run, viewer, viewer.Page == SitePages.StoryViewer
|
||||
? $"Una storia video di {viewer.Account.Username} poteva essere già finita, con il visualizzatore andato avanti da solo: chiuso senza cliccare «avanti», le storie successive non si salvano questa volta."
|
||||
: $"Un video della raccolta di {viewer.Account.Username} poteva essere già finito, con il visualizzatore andato avanti da solo: chiuso senza cliccare «avanti», i contenuti successivi non si salvano questa volta.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await WatchAsync(run, video, since, leaveBy).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
|
||||
var current = Env.SiteMap.Match(viewer.Page, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
|
||||
if (current is null)
|
||||
{
|
||||
return; // the viewer closed by itself
|
||||
}
|
||||
|
||||
if (!viewer.ShowsOwner(current))
|
||||
{
|
||||
position = current; // it moved on by itself to another owner while we watched
|
||||
continue;
|
||||
}
|
||||
|
||||
if (last)
|
||||
{
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var pressedAfter = Env.Clock.Now;
|
||||
await run.ClickAsync(SiteTargets.ViewerNext).ConfigureAwait(false);
|
||||
index++;
|
||||
appearedAfter = pressedAfter;
|
||||
position = Env.SiteMap.Match(viewer.Page, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
|
||||
if (position is null)
|
||||
{
|
||||
return; // the viewer closed: the item after was not shown
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True once <paramref name="moment"/> has come (never for none).</summary>
|
||||
private bool Passed(DateTimeOffset? moment) => moment is { } end && Env.Clock.Now >= end;
|
||||
|
||||
/// <summary>
|
||||
/// Waits the time of §7.7 on an item on screen since <paramref name="since"/>: what the recipe waited meanwhile (the
|
||||
/// Governor's spacing before the permit for the next item) is part of it. Never past <paramref name="latest"/>.
|
||||
/// </summary>
|
||||
private async Task WatchAsync(RecipeRun run, TimeSpan? video, DateTimeOffset since, DateTimeOffset? latest)
|
||||
{
|
||||
var until = since + StoryTimings.Watch(Env.Random, video, Env.Driver.WaitMultiplier);
|
||||
if (latest is { } end && end < until)
|
||||
{
|
||||
until = end;
|
||||
}
|
||||
|
||||
var wait = until - Env.Clock.Now;
|
||||
if (wait > TimeSpan.Zero)
|
||||
{
|
||||
await Env.Driver.WaitAsync(wait, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static TimeSpan? VideoDuration(ContentItem item) => item.Files.FirstOrDefault(f => f.Kind == MediaKind.Video)?.Duration;
|
||||
|
||||
/// <summary>The viewer went on to another account or collection: closed, and the event recorded.</summary>
|
||||
private async Task LeaveOtherOwnerAsync(RecipeRun run, ViewerWatch viewer)
|
||||
{
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
await Writer.EventAsync(
|
||||
"visualizzatore-altro-account",
|
||||
viewer.Page == SitePages.StoryViewer
|
||||
? $"Dopo le storie di {viewer.Account.Username} il visualizzatore è passato a un altro account: chiuso, quelle storie non si salvano."
|
||||
: $"Il visualizzatore è passato a un'altra raccolta di {viewer.Account.Username}: chiuso senza salvarla.",
|
||||
EventSeverity.Warning,
|
||||
viewer.Account.Id,
|
||||
run.Session.SessionId,
|
||||
run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The viewer may be on an item not shown under a permit, or not known: closed before the end, without clicking
|
||||
/// «next», and the event recorded. What it may show now is not saved.
|
||||
/// </summary>
|
||||
private async Task CloseEarlyAsync(RecipeRun run, ViewerWatch viewer, string why)
|
||||
{
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
await Writer.EventAsync("visualizzatore-chiuso-prima", why, EventSeverity.Info, viewer.Account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes the viewer on the way out of a stop, unless a signal says to leave the page as it is; never throws, but
|
||||
/// for a cancellation. Returns why the viewer may still be open (it did not close with its command), otherwise null.
|
||||
/// </summary>
|
||||
private async Task<RecipeStopException?> TryCloseViewerAsync(RecipeRun run, string viewerPage)
|
||||
{
|
||||
try
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
return null;
|
||||
}
|
||||
catch (RecipeStopException stop)
|
||||
{
|
||||
// After a signal the page stays as it is; otherwise the command was not found or the viewer did not close.
|
||||
return stop.Status == RecipeStatus.TargetNotFound ? stop : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
|
||||
{
|
||||
// Whether it closed is not known (the browser may be gone): the stop being reported is the first one.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The stop to report: a viewer left open outranks a milder first stop, as a target not found, which makes the
|
||||
/// session stop and put the page at rest.
|
||||
/// </summary>
|
||||
private static RecipeStopException Worse(RecipeStopException first, RecipeStopException? stillOpen) =>
|
||||
stillOpen is null || first.Status == RecipeStatus.TargetNotFound
|
||||
? first
|
||||
: RecipeRun.Stop(RecipeStatus.TargetNotFound, $"{first.Message} {stillOpen.Message}");
|
||||
|
||||
/// <summary>The address a viewer opened on, and when the click that opened it started.</summary>
|
||||
private sealed record ViewerOpening(IReadOnlyDictionary<string, string> Position, DateTimeOffset ClickedAt);
|
||||
|
||||
/// <summary>
|
||||
/// What a viewer showed, and why it stopped early: a stop, or a cancellation. The caller saves what was shown, then
|
||||
/// goes on with the stop (<see cref="ThrowIfStopped"/>).
|
||||
/// </summary>
|
||||
private sealed record ViewerResult(List<string> Shown, RecipeStopException? Stop, ExceptionDispatchInfo? Cancelled = null)
|
||||
{
|
||||
/// <summary>The token to store what was shown with: stopped early, the run's own may be cancelled already, or a moment later (storage only).</summary>
|
||||
public CancellationToken StoreToken(RecipeRun run) => Stop is null && Cancelled is null ? run.Ct : CancellationToken.None;
|
||||
|
||||
/// <summary>Goes on with the cancellation or the stop, once what was shown is stored.</summary>
|
||||
public void ThrowIfStopped()
|
||||
{
|
||||
Cancelled?.Throw();
|
||||
if (Stop is { } stop)
|
||||
{
|
||||
throw stop;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A viewer being watched: its page, the placeholder of its owner in the address, the owner, the account, the mark of its data.</summary>
|
||||
private sealed record ViewerWatch(string Page, string OwnerKey, string Owner, Account Account, long Mark)
|
||||
{
|
||||
/// <summary>True when the address still shows the owner watched (an account, or a collection).</summary>
|
||||
public bool ShowsOwner(IReadOnlyDictionary<string, string> position) =>
|
||||
position.TryGetValue(OwnerKey, out var shown) && string.Equals(shown, Owner, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static bool SamePosition(IReadOnlyDictionary<string, string> a, IReadOnlyDictionary<string, string> b) =>
|
||||
a.Count == b.Count && a.All(p => b.TryGetValue(p.Key, out var v) && string.Equals(v, p.Value, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>The items of the viewer for the owner, as received (waits for them the first time).</summary>
|
||||
private async Task<List<ContentItem>> ViewerListAsync(RecipeRun run, long mark, string viewerPage, string owner, Account account)
|
||||
/// <summary>
|
||||
/// The items of the viewer for the owner, as received (waits for them the first time). The stories of an account are
|
||||
/// only what looks like a story (it expires and is in no collection): a post of the account arriving meanwhile (the
|
||||
/// grid comes in an answer of its own, also after the viewer opened) would hide which story is the last one, or,
|
||||
/// counted by position, move every position after it.
|
||||
/// </summary>
|
||||
private async Task<List<ContentItem>> ViewerListAsync(RecipeRun run, ViewerWatch viewer)
|
||||
{
|
||||
Func<ContentItem, bool> belongs = viewerPage == SitePages.StoryViewer
|
||||
? c => IsOwnedBy(c, account)
|
||||
: c => c.HighlightId == owner;
|
||||
var present = Contents(Env.Capture.Since(mark), belongs);
|
||||
Func<ContentItem, bool> belongs = viewer.Page == SitePages.StoryViewer
|
||||
? c => IsOwnedBy(c, viewer.Account) && c.ExpiresAt is not null && c.HighlightId is null
|
||||
: c => InCollection(c, viewer.Owner);
|
||||
var present = Contents(Env.Capture.Since(viewer.Mark), belongs);
|
||||
if (present.Count > 0)
|
||||
{
|
||||
return present;
|
||||
}
|
||||
|
||||
var reads = await run.WaitForDataAsync(mark, r => r.Contents.Any(belongs)).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(viewer.Mark, r => r.Contents.Any(belongs)).ConfigureAwait(false);
|
||||
run.Judge(reads, r => r.Contents.Any(belongs), null);
|
||||
return Contents(reads, belongs);
|
||||
}
|
||||
@@ -383,10 +663,20 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Closes the viewer with its command and waits until it is gone.</summary>
|
||||
private async Task CloseViewerAsync(RecipeRun run, string viewerPage)
|
||||
/// <summary>Closes the viewer with its command and waits until it is gone; stops the run when it stays open.</summary>
|
||||
private Task CloseViewerAsync(RecipeRun run, string viewerPage) =>
|
||||
CloseAsync(run, path => Env.SiteMap.Match(viewerPage, path) is not null);
|
||||
|
||||
/// <summary>
|
||||
/// Clicks «viewer-close» while the address says something is open (<paramref name="isOpen"/>) and waits until it is
|
||||
/// gone. Never after a signal (the page stays as it is). A command that is not found, or a viewer still open after
|
||||
/// <see cref="RecipeOptions.ViewerTimeout"/>, stops the run as a target not found: the session then stops and the
|
||||
/// page is put at rest.
|
||||
/// </summary>
|
||||
private async Task CloseAsync(RecipeRun run, Func<string, bool> isOpen)
|
||||
{
|
||||
if (Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is null)
|
||||
run.ThrowIfSignal();
|
||||
if (!isOpen(await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -399,19 +689,20 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
|
||||
var deadline = Env.Clock.Now + Env.Options.ViewerTimeout;
|
||||
while (Env.Clock.Now < deadline)
|
||||
while (isOpen(await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)))
|
||||
{
|
||||
if (Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is null)
|
||||
if (Env.Clock.Now >= deadline)
|
||||
{
|
||||
return;
|
||||
run.ThrowIfSignal();
|
||||
throw RecipeRun.Stop(RecipeStatus.TargetNotFound, $"Il visualizzatore non si è chiuso con «{SiteTargets.ViewerClose}»: il bersaglio della mappa va controllato.");
|
||||
}
|
||||
|
||||
await Env.Clock.Delay(Env.Options.Poll, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StoriesCheckedAsync(Account account, RecipeRun run) =>
|
||||
await Env.Storage.Accounts.UpdateChecksAsync(account.Id, new AccountCheckTimes { LastStoriesCheckAt = Env.Clock.Now }, run.Ct).ConfigureAwait(false);
|
||||
private async Task StoriesCheckedAsync(Account account, CancellationToken ct) =>
|
||||
await Env.Storage.Accounts.UpdateChecksAsync(account.Id, new AccountCheckTimes { LastStoriesCheckAt = Env.Clock.Now }, ct).ConfigureAwait(false);
|
||||
|
||||
private async Task MarkUnreachableAsync(RecipeRun run, Account account, UnreachableReason reason)
|
||||
{
|
||||
@@ -433,4 +724,18 @@ public sealed partial class RecipeRunner
|
||||
|
||||
private static ProfileInfo? ProfileIn(ReadResult result, Account account) =>
|
||||
result.Profiles.FirstOrDefault(p => (account.InstagramId is { } id && p.Id == id) || string.Equals(p.Username, account.Username, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>The profile of the account, or one of its collections: what says that its profile page arrived.</summary>
|
||||
private static bool OwnProfileOrCollectionsIn(ReadResult result, Account account) =>
|
||||
ProfileIn(result, account) is not null || result.Highlights.Any(h => IsHighlightOf(h, account));
|
||||
|
||||
/// <summary>A collection of the account: its owner is the account, or the answer does not say whose it is.</summary>
|
||||
private static bool IsHighlightOf(HighlightInfo highlight, Account account) =>
|
||||
highlight.Owner is not { } owner
|
||||
|| (account.InstagramId is { } id && owner.Id == id)
|
||||
|| string.Equals(owner.Username, account.Username, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>An item received inside collection <paramref name="highlightId"/> (both in the form of the address).</summary>
|
||||
private static bool InCollection(ContentItem item, string highlightId) =>
|
||||
item.HighlightId is { } id && string.Equals(ShapeReader.HighlightId(id), highlightId, StringComparison.Ordinal);
|
||||
}
|
||||
@@ -50,11 +50,13 @@ public sealed record RecipeEnvironment
|
||||
/// Common rules: the Governor is asked before every counted action and a refusal stops the recipe in order; a stop
|
||||
/// signal stops it where it is and leaves the page as it is; a missing target stops it with a report, never with
|
||||
/// coordinates; an unknown response shape stops it with <see cref="RecipeStatus.UnrecognizedFormat"/> and an event
|
||||
/// that carries only the key structure. Recipes refuse to run on a site whose map or reader vocabulary is still a
|
||||
/// skeleton (the first Instagram files, to be filled after M0).
|
||||
/// that carries only the key structure. A recipe refuses to run, as <see cref="RecipeStatus.NotConfigured"/>, while the
|
||||
/// site's map lacks a page or target it needs or the reader vocabulary is not usable (Instagram's targets, H11).
|
||||
/// </remarks>
|
||||
public sealed partial class RecipeRunner : IRecipeRunner
|
||||
{
|
||||
private readonly Lock _refusalsGate = new();
|
||||
private readonly HashSet<RecipeKind> _refusalsReported = [];
|
||||
private long? _sessionId;
|
||||
private RecipeKind? _lastKind;
|
||||
|
||||
@@ -83,15 +85,19 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
_ => kind.ToString(),
|
||||
};
|
||||
|
||||
/// <summary>Pages and targets a recipe cannot work without.</summary>
|
||||
/// <summary>
|
||||
/// Pages and targets a recipe cannot work without. «profile-not-found» is not among them: it is looked up only when
|
||||
/// the map sets it, and without it a profile that does not exist gives no data, judged like any page that arrives
|
||||
/// empty.
|
||||
/// </summary>
|
||||
public static (IReadOnlyList<string> Pages, IReadOnlyList<string> Targets) Requirements(RecipeKind kind) => kind switch
|
||||
{
|
||||
RecipeKind.FollowingSweep => ([SitePages.Home], []),
|
||||
RecipeKind.AccountStories => ([SitePages.Profile, SitePages.StoryViewer], [SiteTargets.ProfileStoryRing, SiteTargets.ViewerNext, SiteTargets.ViewerClose]),
|
||||
RecipeKind.ProfileCheck or RecipeKind.Backfill => ([SitePages.Profile], [SiteTargets.ProfileNotFound]),
|
||||
RecipeKind.ProfileCheck or RecipeKind.Backfill => ([SitePages.Profile], []),
|
||||
RecipeKind.Highlight => ([SitePages.Profile, SitePages.HighlightViewer], [SiteTargets.ProfileHighlight, SiteTargets.ViewerNext, SiteTargets.ViewerClose]),
|
||||
RecipeKind.Tagged => ([SitePages.Profile], [SiteTargets.ProfileNotFound, SiteTargets.ProfileTabTagged]),
|
||||
RecipeKind.Reels => ([SitePages.Profile], [SiteTargets.ProfileNotFound, SiteTargets.ProfileTabReels]),
|
||||
RecipeKind.Tagged => ([SitePages.Profile], [SiteTargets.ProfileTabTagged]),
|
||||
RecipeKind.Reels => ([SitePages.Profile], [SiteTargets.ProfileTabReels]),
|
||||
RecipeKind.SinglePost => ([SitePages.Post], []),
|
||||
RecipeKind.FollowingList => ([SitePages.Following], []),
|
||||
_ => ([], []),
|
||||
@@ -112,20 +118,23 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
ArgumentNullException.ThrowIfNull(session);
|
||||
var name = Name(request.Kind);
|
||||
|
||||
var (pages, targets) = Requirements(request.Kind);
|
||||
var missing = Env.SiteMap.Missing(pages, targets);
|
||||
if (missing.Count > 0)
|
||||
// A map or a vocabulary that lacks what the recipe needs is a state of the configuration, not a failure of the
|
||||
// recipe: nothing is done, nothing counts towards suspension, and it is said once per recipe and process (the
|
||||
// engine stops planning it, NotConfiguredReason).
|
||||
if (Refusal(request.Kind) is { } refusal)
|
||||
{
|
||||
var message = $"«{name}» non può girare su {Env.SiteMap.Site}: la mappa dei bersagli non è ancora compilata (mancano {string.Join(", ", missing)}). Va completata con i campioni della sonda di M0 (ipotesi H11).";
|
||||
await Writer.EventAsync("mappa-incompleta", message, EventSeverity.Error, null, session.SessionId, ct).ConfigureAwait(false);
|
||||
return new RecipeOutcome(RecipeStatus.TargetNotFound, 0, 0, message);
|
||||
}
|
||||
bool first;
|
||||
lock (_refusalsGate)
|
||||
{
|
||||
first = _refusalsReported.Add(request.Kind);
|
||||
}
|
||||
|
||||
if (Env.Capture.Reader.Vocabulary.UnusableReason is { } unusable)
|
||||
{
|
||||
var message = $"«{name}» non può girare: {unusable}";
|
||||
await Writer.EventAsync("lettori-incompleti", message, EventSeverity.Error, null, session.SessionId, ct).ConfigureAwait(false);
|
||||
return new RecipeOutcome(RecipeStatus.UnrecognizedFormat, 0, 0, message);
|
||||
if (first)
|
||||
{
|
||||
await Writer.EventAsync(refusal.Code, refusal.Message + SessionComposer.NotConfiguredTail, EventSeverity.Warning, null, session.SessionId, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new RecipeOutcome(RecipeStatus.NotConfigured, 0, 0, refusal.Message);
|
||||
}
|
||||
|
||||
if (Env.Breaker is { } breaker && !breaker.State.AllowsSiteActions)
|
||||
@@ -206,6 +215,28 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public string? NotConfiguredReason(RecipeKind kind) => Refusal(kind)?.Message;
|
||||
|
||||
/// <summary>
|
||||
/// Why the site's configuration does not let <paramref name="kind"/> run, with the code of its timeline line: pages
|
||||
/// or targets missing from the map, or a reader vocabulary that cannot be relied on. Null when it can run.
|
||||
/// </summary>
|
||||
private (string Code, string Message)? Refusal(RecipeKind kind)
|
||||
{
|
||||
var name = Name(kind);
|
||||
var (pages, targets) = Requirements(kind);
|
||||
var missing = Env.SiteMap.Missing(pages, targets);
|
||||
if (missing.Count > 0)
|
||||
{
|
||||
return ("mappa-incompleta", $"«{name}» non può girare su {Env.SiteMap.Site}: la mappa dei bersagli non è ancora compilata (mancano {string.Join(", ", missing)}).");
|
||||
}
|
||||
|
||||
return Env.Capture.Reader.Vocabulary.UnusableReason is { } unusable
|
||||
? ("lettori-incompleti", $"«{name}» non può girare: {unusable}")
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rest page (spec §6.1). After a verification request or a disconnection the page is left as it is, so that
|
||||
/// Alberto sees what happened (spec §7.6): resting is skipped while the breaker says so.
|
||||
|
||||
@@ -31,10 +31,13 @@ public static class SitePages
|
||||
/// <summary>The same list resuming after {cursor} (optional).</summary>
|
||||
public const string FollowingFrom = "followingFrom";
|
||||
|
||||
/// <summary>Shape of the address of the story viewer: {username} and {id} of the story shown.</summary>
|
||||
/// <summary>Shape of the address of the story viewer: {username}, and {id} of the story shown when the address carries it.</summary>
|
||||
public const string StoryViewer = "storyViewer";
|
||||
|
||||
/// <summary>Shape of the address of the highlight viewer: {highlight} and {id} of the item shown.</summary>
|
||||
/// <summary>
|
||||
/// Shape of the address of the highlight viewer: {highlight}, and {id} of the item shown when the address carries it
|
||||
/// (Instagram's does not: «/stories/highlights/{highlight}/» stays the same from item to item).
|
||||
/// </summary>
|
||||
public const string HighlightViewer = "highlightViewer";
|
||||
|
||||
public static IReadOnlyList<string> All { get; } =
|
||||
@@ -178,7 +181,7 @@ public sealed partial class SiteMap
|
||||
/// <summary>The target map of the local test site (embedded <c>bersagli.prova.json</c>).</summary>
|
||||
public static SiteMap LoadTestSite() => LoadEmbedded("bersagli.prova.json");
|
||||
|
||||
/// <summary>The Instagram skeleton (embedded <c>bersagli.instagram.json</c>): every entry is still unset (H11).</summary>
|
||||
/// <summary>The Instagram map (embedded <c>bersagli.instagram.json</c>): the pages seen in real traffic, targets still unset (H11).</summary>
|
||||
public static SiteMap LoadInstagram() => LoadEmbedded("bersagli.instagram.json");
|
||||
|
||||
public static SiteMap LoadOrEmbedded(string? path, string embeddedName) =>
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
{
|
||||
"site": "instagram",
|
||||
"note": "SCHELETRO della prima versione (specifica §6.3, ipotesi H11). Elenca solo le pagine e i bersagli di cui le ricette hanno bisogno, tutti VUOTI: si compilano con i campioni della sonda di M0 (docs/prove-dal-vivo.md, docs/sonda/esito.md). Finché una voce necessaria è vuota, la ricetta che la usa si rifiuta di girare su Instagram e lo dice. Mai coordinate, mai nomi di classi generate: solo ruolo, nome accessibile e forma del collegamento.",
|
||||
"note": "Mappa di Instagram, aggiornata il 25 ottobre 2026 (specifica §6.3). PAGINE: compilate solo quelle che hanno una prova reale nel file HAR del browser di Alberto del 21 ottobre 2026, cioè i modelli di indirizzo che Instagram stesso manda al browser (/ajax/bulk-route-definitions/) e i percorsi del Referer delle richieste fatte dalla pagina: home, profile, post, storyViewer, highlightViewer. Restano vuote, senza prove: following e followingFrom (quindi «Elenco dei seguiti» non gira), profileFrom, reelsFrom e taggedFrom (facoltative). Le parti facoltative dei modelli di Instagram ({?tab}, {?initial_media_id}) non si scrivono: qui ogni segnaposto vale esattamente un segmento. BERSAGLI: tutti ancora VUOTI (ipotesi H11). Il HAR aveva solo risposte Fetch/XHR: nessun documento e nessun attributo degli elementi (ruoli, nomi accessibili, collegamenti). Si compilano con docs/prove-dal-vivo.md, parte A bis (tools/bersagli/raccogli-bersagli.js). Finché una voce necessaria è vuota, la ricetta che la usa si rifiuta di girare su Instagram e lo dice. Mai coordinate, mai nomi di classi generate: solo ruolo, nome accessibile e forma del collegamento.",
|
||||
"pages": {
|
||||
"home": { "path": "", "hypothesis": "H1", "note": "Pagina iniziale con barra delle storie e post recenti dei seguiti." },
|
||||
"profile": { "path": "", "hypothesis": "H3", "note": "Pagina di un profilo; segnaposto {username}." },
|
||||
"profileFrom": { "path": "", "hypothesis": "H3", "note": "Facoltativa: profilo che riparte da un punto di ripresa ({cursor}). Se resta vuota lo storico riprende scorrendo." },
|
||||
"reelsFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Reel." },
|
||||
"taggedFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Taggati." },
|
||||
"post": { "path": "", "hypothesis": "H3", "note": "Pagina di un post; segnaposto {code}." },
|
||||
"following": { "path": "", "hypothesis": "H11", "note": "Elenco dei profili seguiti da Alberto; segnaposto {username}." },
|
||||
"followingFrom": { "path": "", "hypothesis": "H11", "note": "Facoltativa: elenco dei seguiti da un punto di ripresa." },
|
||||
"storyViewer": { "path": "", "hypothesis": "H4", "note": "Forma dell'indirizzo del visualizzatore: {username} e {id} della storia mostrata." },
|
||||
"highlightViewer": { "path": "", "hypothesis": "H9", "note": "Forma dell'indirizzo del visualizzatore delle raccolte: {highlight} e {id}." }
|
||||
"home": { "path": "/", "hypothesis": "H1", "note": "Pagina iniziale con barra delle storie e post recenti dei seguiti. Prova: modello «/» (PolarisFeedRoute) nelle definizioni delle pagine. Che cosa arrivi caricandola (H1) non è nel HAR e resta da provare." },
|
||||
"profile": { "path": "/{username}/", "hypothesis": "H3", "note": "Pagina di un profilo; segnaposto {username}. Prova: modello /{username}/{?tab}/{?view_type}/{?igshid}/ (PolarisProfilePostsTabRoute), senza le parti facoltative. I valori di {?tab} non si vedono nel campione." },
|
||||
"profileFrom": { "path": "", "hypothesis": "H3", "note": "Facoltativa: profilo che riparte da un punto di ripresa ({cursor}). Nessuna prova di un indirizzo del genere: resta vuota e lo storico riprende scorrendo." },
|
||||
"reelsFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Reel. Nessuna prova: la scheda non è nel campione." },
|
||||
"taggedFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Taggati. Nessuna prova: la scheda non è nel campione." },
|
||||
"post": { "path": "/p/{code}/", "hypothesis": "H3", "note": "Pagina di un post; segnaposto {code} (11 caratteri). Prova: il percorso /p/{code}/ nel Referer delle richieste della pagina di un post. Instagram usa anche /{username}/reel/{code}/ (modello /{username}/{permalink_key}/{shortcode}/): Febe apre la forma /p/." },
|
||||
"following": { "path": "", "hypothesis": "H11", "note": "Elenco dei profili seguiti da Alberto; segnaposto {username}. Nessuna prova nel campione: resta vuota e «Elenco dei seguiti» non gira finché non arriva (parte A bis)." },
|
||||
"followingFrom": { "path": "", "hypothesis": "H11", "note": "Facoltativa: elenco dei seguiti da un punto di ripresa. Nessuna prova." },
|
||||
"storyViewer": { "path": "/stories/{username}/{id}/", "hypothesis": "H4", "note": "Forma dell'indirizzo del visualizzatore: {username} e {id} della storia mostrata. Prova: modello /stories/{username}/{?initial_media_id}/ (PolarisStoriesV3Route). DA CONFERMARE che l'indirizzo segua ogni storia (l'{id} cambia a ogni avanzamento) e che porti l'{id} fin dall'apertura: senza {id} questa forma non corrisponde e la ricetta si ferma dicendo che il visualizzatore non si è aperto. Anche /stories/highlights/<cifre>/ ha questa forma, con username «highlights»: per le Storie di un account è «un altro account» e il visualizzatore si chiude; la ricetta delle raccolte legge solo highlightViewer." },
|
||||
"highlightViewer": { "path": "/stories/highlights/{highlight}/", "hypothesis": "H9", "note": "Forma dell'indirizzo del visualizzatore delle raccolte: {highlight} sono le 17 cifre dell'identificativo (nei dati «highlight:<cifre>», ridotto alle cifre dal lettore). Prova: il Referer delle richieste fatte guardando una raccolta e il modello /stories/highlights/{highlight_reel_id}/ (PolarisStoriesV3HighlightsRoute). Non c'è l'{id} del contenuto mostrato: l'indirizzo resta lo stesso mentre si guarda, quindi la posizione nella raccolta non si legge dall'indirizzo." }
|
||||
},
|
||||
"targets": {
|
||||
"home-story": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Voce della barra delle storie per un account ({username})." },
|
||||
|
||||
@@ -1,51 +1,55 @@
|
||||
{
|
||||
"site": "instagram",
|
||||
"status": "ipotesi",
|
||||
"note": "IPOTESI, DA CONFERMARE CON I CAMPIONI DI M0 (specifica §6.4, regola 10). Contiene solo gli indizi che la specifica stessa elenca in §6.4 (pk, code, taken_at, image_versions2.candidates, video_versions, carousel_media); ogni altro concetto è vuoto e si compila sui campioni ripuliti della sonda. Finché lo stato è «ipotesi» o manca un concetto necessario, le ricette si rifiutano di girare su Instagram.",
|
||||
"status": "confermato",
|
||||
"note": "Vocabolario dei lettori per Instagram, compilato il 25 ottobre 2026 sulle risposte reali che il browser di Alberto ha ricevuto il 21 ottobre (file HAR), ripulite con «febe-sonda ripulisci» e conservate in tests/Febe.Tests/campioni/instagram (regola 10). Ogni concetto dice da quali campioni viene; quelli senza riscontro restano vuoti o sono segnati come indizio. I dati di storie e raccolte arrivano come «text/javascript», non come JSON dichiarato: la cattura li legge lo stesso (DataResponses). «viewer»: xdt_viewer.user, visto in raccolta-in-evidenza, descrive l'account collegato con il solo identificativo, senza nome, quindi da solo non basta a riconoscerlo (H10 resta aperta).",
|
||||
"content": {
|
||||
"note": "Indizi di §6.4: chiavi viste in passato, non uno schema. Ipotesi, da confermare con i campioni di M0.",
|
||||
"note": "Un contenuto (XDTMediaDict): post, reel, storia o contenuto di una raccolta. Visti in post-video (/api/v1/media/…/info/), raccolta-in-evidenza e raccolta-pagina-successiva. «user» dei contenuti di una storia ha solo l'identificativo, senza nome: l'autore si eredita dalla raccolta o dalla serie di storie che li contiene. La didascalia è un oggetto con il testo in «text». Serie (carousel_media): chiave vista ma sempre vuota nei campioni, il formato dei figli è un indizio di §6.4 da confermare con un campione di un post con più file.",
|
||||
"id": ["pk"],
|
||||
"code": ["code"],
|
||||
"takenAt": ["taken_at"],
|
||||
"caption": [],
|
||||
"caption": ["caption.text"],
|
||||
"images": ["image_versions2.candidates"],
|
||||
"videos": ["video_versions"],
|
||||
"children": ["carousel_media"],
|
||||
"childCount": [],
|
||||
"owner": [],
|
||||
"childCount": ["carousel_media_count"],
|
||||
"owner": ["user", "owner"],
|
||||
"pinned": [],
|
||||
"expiresAt": [],
|
||||
"duration": []
|
||||
"expiresAt": ["expiring_at"],
|
||||
"duration": ["video_duration"]
|
||||
},
|
||||
"version": {
|
||||
"note": "Da compilare con i campioni di M0 (H3, H5).",
|
||||
"url": [],
|
||||
"width": [],
|
||||
"height": [],
|
||||
"note": "Una versione: candidates di image_versions2 (url, width, height, da 10 a 14 per contenuto) e video_versions (type 101, 102, 103 e url; dimensioni solo nei post, non nelle storie). Se il video ha l'audio lo dice il contenuto (has_audio), non la versione: hasAudio resta vuoto e ogni versione conta come file completo (H5 da confermare scaricando).",
|
||||
"url": ["url"],
|
||||
"width": ["width"],
|
||||
"height": ["height"],
|
||||
"hasAudio": []
|
||||
},
|
||||
"profile": {
|
||||
"note": "Da compilare con i campioni di M0 (H3, H10).",
|
||||
"id": [],
|
||||
"username": [],
|
||||
"displayName": [],
|
||||
"isPrivate": [],
|
||||
"isFollowed": [],
|
||||
"note": "Un profilo (XDTUserDict): visto come autore di un post (user, owner), come proprietario di una raccolta, nella ricerca e nei profili suggeriti. friendship_status.following dice se Alberto lo segue; latest_reel_media è la data dell'ultima storia. Il numero dei post non compare in nessun campione: resta vuoto.",
|
||||
"id": ["pk", "id"],
|
||||
"username": ["username"],
|
||||
"displayName": ["full_name"],
|
||||
"isPrivate": ["is_private"],
|
||||
"isFollowed": ["friendship_status.following"],
|
||||
"postCount": [],
|
||||
"picture": [],
|
||||
"latestStoryAt": []
|
||||
"picture": ["hd_profile_pic_url_info", "hd_profile_pic_versions", "profile_pic_url"],
|
||||
"latestStoryAt": ["latest_reel_media"]
|
||||
},
|
||||
"highlight": {
|
||||
"note": "Da compilare con i campioni di M0 (H3, H9).",
|
||||
"id": [],
|
||||
"title": [],
|
||||
"owner": [],
|
||||
"items": []
|
||||
"note": "Una raccolta in evidenza (XDTReelDict con reel_type highlight_reel): id «highlight:<numero>», title, user e i contenuti in items. Vista in raccolta-in-evidenza e raccolta-pagina-successiva.",
|
||||
"id": ["id"],
|
||||
"title": ["title"],
|
||||
"owner": ["user"],
|
||||
"items": ["items"]
|
||||
},
|
||||
"page": {
|
||||
"note": "Da compilare con i campioni di M0 (H3).",
|
||||
"hasMore": [],
|
||||
"cursor": []
|
||||
"note": "page_info delle connessioni GraphQL (has_next_page, end_cursor) e more_available delle risposte REST. Visti in raccolta-in-evidenza e post-video.",
|
||||
"hasMore": ["has_next_page", "more_available"],
|
||||
"cursor": ["end_cursor"]
|
||||
},
|
||||
"viewer": []
|
||||
"relevance": {
|
||||
"note": "Una risposta che non contiene nessuna di queste chiavi non parla di contenuti né di profili e si ignora: promozioni, registri, il segno «storia vista», le definizioni delle pagine. Senza questo elenco ognuna conterebbe come «formato non riconosciuto».",
|
||||
"keys": ["image_versions2", "video_versions", "carousel_media", "taken_at", "username"]
|
||||
},
|
||||
"viewer": ["xdt_viewer.user"]
|
||||
}
|
||||
@@ -403,6 +403,8 @@ public static class EngineEventCodes
|
||||
public const string ManualCheck = "controlla-ora";
|
||||
public const string RecipeFailed = "ricetta-fallita";
|
||||
public const string SettingsChanged = "impostazioni-motore";
|
||||
public const string RecipeNotConfigured = "configurazione-incompleta";
|
||||
public const string CollectionConfigurationChanged = "configurazione-raccolta";
|
||||
|
||||
/// <summary>Prefix of the per-recipe lines («Appena fatto»): "ricetta." + recipe kind.</summary>
|
||||
public const string RecipePrefix = "ricetta.";
|
||||
|
||||
@@ -74,6 +74,12 @@ public enum RecipeStatus
|
||||
|
||||
/// <summary>Unexpected error; message says what happened.</summary>
|
||||
Failed,
|
||||
|
||||
/// <summary>
|
||||
/// Refused before anything was done: the target map or the reader vocabulary of the site does not have what the
|
||||
/// recipe needs yet. A state of the configuration, not a failure of the recipe: it never counts towards suspension.
|
||||
/// </summary>
|
||||
NotConfigured,
|
||||
}
|
||||
|
||||
/// <summary>Result of a recipe run, used by the scheduler to plan what comes next.</summary>
|
||||
@@ -89,7 +95,10 @@ public sealed record RecipeOutcome(
|
||||
/// <summary>Accounts where the sweep saw new posts (FollowingSweep).</summary>
|
||||
public IReadOnlyList<long> AccountsWithNewPosts { get; init; } = [];
|
||||
|
||||
/// <summary>For Backfill: true when the beginning of the profile has been reached.</summary>
|
||||
/// <summary>
|
||||
/// Backfill: true when the beginning of the profile has been reached. ProfileCheck: true when the check found the
|
||||
/// whole profile of an account «Storico in corso» on its first page (its history is complete as well).
|
||||
/// </summary>
|
||||
public bool BackfillFinished { get; init; }
|
||||
}
|
||||
|
||||
@@ -112,6 +121,13 @@ public interface IRecipeRunner
|
||||
|
||||
/// <summary>Puts the browser on the empty rest page (end of session, pauses, night).</summary>
|
||||
Task RestAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// Why <paramref name="kind"/> cannot run on the configuration of the site in use (target map, reader vocabulary),
|
||||
/// in Italian; null when it can, or when the runner cannot tell. The engine does not plan such a recipe: running it
|
||||
/// would only end in <see cref="RecipeStatus.NotConfigured"/>.
|
||||
/// </summary>
|
||||
string? NotConfiguredReason(RecipeKind kind) => null;
|
||||
}
|
||||
|
||||
/// <summary>Daily byte budget for CDN downloads (category «dati scaricati», spec §7.4).</summary>
|
||||
|
||||
@@ -259,6 +259,11 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
}
|
||||
|
||||
var kind = CheckPolicy.WantsProfileChecks(account) ? EngineTaskKind.ProfileCheck : EngineTaskKind.AccountStories;
|
||||
if (_composer.NotConfiguredReason(CheckPolicy.RecipeOf(kind)) is { } notConfigured)
|
||||
{
|
||||
return new CheckNowResult(CheckNowStatus.Refused, notConfigured + " Il controllo non parte.");
|
||||
}
|
||||
|
||||
var category = kind == EngineTaskKind.ProfileCheck ? ActionKind.ProfileOpen : ActionKind.StoryView;
|
||||
var budget = await _s.Governor.EvaluateBudgetAsync(category, accountId, ct).ConfigureAwait(false);
|
||||
if (!budget.Granted && budget.Reason != DenialReason.AccountNotContactable)
|
||||
@@ -397,6 +402,49 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
return resumed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The collection configuration in use: <paramref name="fingerprint"/> of the reader vocabulary and target map of the
|
||||
/// site as loaded. When it differs from the stored one — or none is stored yet, the first start that knows it —
|
||||
/// every suspension and consecutive failure of the recipes is cleared once, since they were counted against other
|
||||
/// files, with one line in the timeline when there was something to clear; then the fingerprint is stored. Called at
|
||||
/// start-up, before <see cref="StartAsync"/>. True when the configuration had changed.
|
||||
/// </summary>
|
||||
public async Task<bool> ApplyCollectionConfigurationAsync(string fingerprint, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(fingerprint);
|
||||
var settings = _s.Storage.Settings;
|
||||
if (string.Equals(await settings.GetAsync(EngineSettingKeys.CollectionConfiguration, ct).ConfigureAwait(false), fingerprint, StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
await _health.LoadAsync(ct).ConfigureAwait(false);
|
||||
var (suspended, hadFailures) = await _health.ResetAllAsync(ct).ConfigureAwait(false);
|
||||
if (suspended.Count > 0)
|
||||
{
|
||||
var names = string.Join(", ", suspended.Select(k => "«" + ItalianText.Capitalize(SessionComposer.RecipeName(k)) + "»"));
|
||||
await _s.Events.WriteAsync(
|
||||
EventSeverity.Info,
|
||||
EngineEventCodes.CollectionConfigurationChanged,
|
||||
$"La configurazione della raccolta è cambiata: le ricette sospese ripartono ({names}).",
|
||||
ct: ct).ConfigureAwait(false);
|
||||
}
|
||||
else if (hadFailures)
|
||||
{
|
||||
await _s.Events.WriteAsync(
|
||||
EventSeverity.Info,
|
||||
EngineEventCodes.CollectionConfigurationChanged,
|
||||
"La configurazione della raccolta è cambiata: i problemi delle ricette contati finora non valgono più.",
|
||||
ct: ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Stored last: if Febe stops in between, the next start clears again, which changes nothing.
|
||||
await settings.SetAsync(EngineSettingKeys.CollectionConfiguration, fingerprint, ct).ConfigureAwait(false);
|
||||
Wake();
|
||||
_s.Events.Publish(EngineNotificationKind.StateChanged);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Stores and applies new engine settings, then replans.</summary>
|
||||
public async Task ApplySettingsAsync(EngineSettings settings, CancellationToken ct = default)
|
||||
{
|
||||
|
||||
@@ -45,6 +45,12 @@ public static class EngineSettingKeys
|
||||
|
||||
/// <summary>Last completed Giro dei seguiti, Unix milliseconds (it read the stories bar of every followed account).</summary>
|
||||
public const string LastSweep = "motore.ultimo-giro";
|
||||
|
||||
/// <summary>
|
||||
/// Fingerprint of the collection configuration the suspensions and failure counts refer to (reader vocabulary and
|
||||
/// target map of the site, as loaded): when it changes they are cleared once.
|
||||
/// </summary>
|
||||
public const string CollectionConfiguration = "motore.configurazione-raccolta";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -28,6 +28,7 @@ public sealed record RecentAction(
|
||||
RecipeStatus.AccountUnreachable => "Non raggiungibile",
|
||||
RecipeStatus.Cancelled => "Interrotto",
|
||||
RecipeStatus.Failed => "Errore",
|
||||
RecipeStatus.NotConfigured => "Da configurare",
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@ namespace Febe.Core.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// Consecutive failures per recipe and suspended recipes (spec §6.4: after three «formato non riconosciuto» in a row
|
||||
/// the recipe is suspended and the interface says so). Persisted in the settings table.
|
||||
/// the recipe is suspended and the interface says so). Persisted in the settings table. A refusal because the
|
||||
/// configuration of the site is incomplete (<see cref="RecipeStatus.NotConfigured"/>) is not a failure and never
|
||||
/// reaches it; a change of that configuration clears it (<see cref="ResetAllAsync"/>).
|
||||
/// </summary>
|
||||
internal sealed class RecipeHealth
|
||||
{
|
||||
@@ -110,6 +112,26 @@ internal sealed class RecipeHealth
|
||||
return removed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The collection configuration changed: every suspension and every consecutive failure goes, since they were
|
||||
/// counted against other files. Returns the recipes that were suspended and whether any failure was counted.
|
||||
/// </summary>
|
||||
public async Task<(IReadOnlyList<RecipeKind> Suspended, bool HadFailures)> ResetAllAsync(CancellationToken ct)
|
||||
{
|
||||
RecipeKind[] suspended;
|
||||
bool hadFailures;
|
||||
lock (_gate)
|
||||
{
|
||||
suspended = [.. _suspended.Keys.Order()];
|
||||
hadFailures = _failures.Count > 0;
|
||||
_suspended.Clear();
|
||||
_failures.Clear();
|
||||
}
|
||||
|
||||
await SaveAsync(ct).ConfigureAwait(false);
|
||||
return (suspended, hadFailures);
|
||||
}
|
||||
|
||||
private Task SaveAsync(CancellationToken ct)
|
||||
{
|
||||
string failures;
|
||||
|
||||
@@ -14,6 +14,9 @@ namespace Febe.Core.Engine;
|
||||
/// </summary>
|
||||
internal sealed class SessionComposer
|
||||
{
|
||||
/// <summary>What every line about a recipe the configuration does not let run adds (the runner's included).</summary>
|
||||
internal const string NotConfiguredTail = " Febe non la avvia finché la configurazione non è completa, e non la conta fra i problemi della ricetta.";
|
||||
|
||||
private static readonly TimeSpan DefaultWindow = TimeSpan.FromHours(16);
|
||||
|
||||
private readonly EngineServices _s;
|
||||
@@ -24,6 +27,13 @@ internal sealed class SessionComposer
|
||||
private readonly Lock _noticeGate = new();
|
||||
private readonly HashSet<(string Code, long? Account, DateOnly Day)> _notices = [];
|
||||
|
||||
// Recipes the configuration of the site does not let run. The configuration is loaded once per process, so what a
|
||||
// run learned holds until the end, and each recipe is said once (_notConfiguredSaid), not at every session.
|
||||
private readonly Lock _configurationGate = new();
|
||||
private readonly Dictionary<RecipeKind, string> _notConfigured = [];
|
||||
private readonly HashSet<RecipeKind> _notConfiguredSaid = [];
|
||||
private readonly List<string> _notConfiguredToSay = [];
|
||||
|
||||
// The interface calls SyncQueueAsync while a session may be running. A recipe's task is Running in the database
|
||||
// between its start and its bookkeeping, and then has its successor: under this gate the queue is looked at only
|
||||
// when every task is pending, in flight (_inFlight) or already replaced by its successor, never in between.
|
||||
@@ -51,6 +61,7 @@ internal sealed class SessionComposer
|
||||
public async Task<SessionSummary> RunAsync(SessionContext context, EngineTask? outsideWindowTask, CancellationToken ct)
|
||||
{
|
||||
var state = new SessionState(context);
|
||||
await CloseCompletedHistoriesAsync(state, ct).ConfigureAwait(false);
|
||||
var accounts = await SyncQueueAsync(ct).ConfigureAwait(false);
|
||||
|
||||
if (outsideWindowTask is not null)
|
||||
@@ -101,6 +112,7 @@ internal sealed class SessionComposer
|
||||
|
||||
// Normally the next sweep will cover them: explicit checks only when no sweep can run, or after a long gap.
|
||||
var sweepUnavailable = _health.IsSuspended(RecipeKind.FollowingSweep)
|
||||
|| NotConfiguredReason(RecipeKind.FollowingSweep) is not null
|
||||
|| !(await _s.Governor.EvaluateBudgetAsync(ActionKind.Home, null, ct).ConfigureAwait(false)).Granted;
|
||||
var factor = sweepUnavailable ? 1 : 2;
|
||||
var uncovered = accounts.Values
|
||||
@@ -145,18 +157,47 @@ internal sealed class SessionComposer
|
||||
// 5. A few pages of history on one account.
|
||||
if (!light && !Over(state, ct))
|
||||
{
|
||||
await RunBackfillAsync(accounts, state, ct).ConfigureAwait(false);
|
||||
await RunBackfillAsync(state, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return state.Summary();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Accounts still «Storico in corso» whose history is complete: a run closed it but its outcome was never recorded
|
||||
/// (Febe stopped in between), or an earlier version left them so. Closed before the session plans anything, with
|
||||
/// their line (<see cref="FinishBackfillAsync"/>); nothing towards the site.
|
||||
/// </summary>
|
||||
private async Task CloseCompletedHistoriesAsync(SessionState state, CancellationToken ct)
|
||||
{
|
||||
var complete = (await Store.Accounts.ListAsync(ct).ConfigureAwait(false))
|
||||
.Where(a => a.State == AccountState.Backfilling && a.BackfillCompletedAt is not null)
|
||||
.ToList();
|
||||
if (complete.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _queueGate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
foreach (var account in complete)
|
||||
{
|
||||
await FinishBackfillAsync(account, state, Clock.Now, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_queueGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the queue in step with the accounts: a profile check and a story check (as the account wants them) for
|
||||
/// every contactable account, a look at each highlight collection on its profile, a backfill task for every account
|
||||
/// «Storico in corso», a Giro dei seguiti when someone is followed; pending planned tasks of accounts that may not be
|
||||
/// contacted are cancelled. Commands of Alberto are left alone, and so is the task of the recipe in progress: its
|
||||
/// own bookkeeping plans the next one.
|
||||
/// «Storico in corso», a Giro dei seguiti when someone is followed; pending planned tasks the account no longer wants,
|
||||
/// or of accounts that may not be contacted, are cancelled (a «Post singolo» only in the second case). Commands of
|
||||
/// Alberto are left alone, and so is the task of the recipe in progress: its own bookkeeping plans the next one.
|
||||
/// </summary>
|
||||
public async Task<Dictionary<long, Account>> SyncQueueAsync(CancellationToken ct)
|
||||
{
|
||||
@@ -182,7 +223,14 @@ internal sealed class SessionComposer
|
||||
{
|
||||
var tasks = byAccount[account.Id].Where(t => !t.IsManual).ToList();
|
||||
var wanted = WantedKinds(account);
|
||||
foreach (var task in tasks.Where(t => t.Kind != EngineTaskKind.HighlightCheck && !wanted.ContainsKey(t.Kind) && !(t.Kind == EngineTaskKind.AccountStories && t.Priority >= Options.FlaggedStoriesPriority && CheckPolicy.IsContactable(account))))
|
||||
|
||||
// Nothing is planned that the configuration of the site does not let run: it would only be refused.
|
||||
foreach (var kind in wanted.Keys.Where(k => !CanRun(CheckPolicy.RecipeOf(k))).ToList())
|
||||
{
|
||||
wanted.Remove(kind);
|
||||
}
|
||||
|
||||
foreach (var task in tasks.Where(t => !Keeps(t, account, wanted)))
|
||||
{
|
||||
await Store.Tasks.CancelAsync(task.Id, now, ct).ConfigureAwait(false);
|
||||
}
|
||||
@@ -203,12 +251,13 @@ internal sealed class SessionComposer
|
||||
}
|
||||
|
||||
var anyFollowed = accounts.Values.Any(a => a.IsFollowed && CheckPolicy.IsContactable(a));
|
||||
var sweepWanted = anyFollowed && CanRun(RecipeKind.FollowingSweep);
|
||||
var sweeps = pending.Where(t => t.Kind == EngineTaskKind.FollowingSweep && !t.IsManual).ToList();
|
||||
if (anyFollowed && sweeps.Count == 0)
|
||||
if (sweepWanted && sweeps.Count == 0)
|
||||
{
|
||||
await EnsureSweepTaskAsync(_s.Runtime.NextSessionAt ?? now, ct).ConfigureAwait(false);
|
||||
}
|
||||
else if (!anyFollowed)
|
||||
else if (!sweepWanted)
|
||||
{
|
||||
foreach (var sweep in sweeps)
|
||||
{
|
||||
@@ -216,9 +265,28 @@ internal sealed class SessionComposer
|
||||
}
|
||||
}
|
||||
|
||||
await SayNotConfiguredAsync().ConfigureAwait(false);
|
||||
return accounts;
|
||||
}
|
||||
|
||||
/// <summary>Whether <see cref="SyncQueueLockedAsync"/> leaves a pending planned task of the account where it is.</summary>
|
||||
private bool Keeps(EngineTask task, Account account, Dictionary<EngineTaskKind, DateTimeOffset?> wanted) => task.Kind switch
|
||||
{
|
||||
// One per collection: SyncHighlightsAsync.
|
||||
EngineTaskKind.HighlightCheck => true,
|
||||
|
||||
// Queued by the collection, not by the settings of the account: a series the grid did not give whole, an
|
||||
// address that expired (spec §6.5 point 5). Nothing would queue it again, so it waits while the recipe cannot
|
||||
// run, and goes only with an account that may not be contacted.
|
||||
EngineTaskKind.SinglePost => CheckPolicy.IsContactable(account),
|
||||
|
||||
// Flagged by the stories bar: kept until it runs, when it can.
|
||||
EngineTaskKind.AccountStories when task.Priority >= Options.FlaggedStoriesPriority =>
|
||||
wanted.ContainsKey(task.Kind) || (CheckPolicy.IsContactable(account) && CanRun(RecipeKind.AccountStories)),
|
||||
|
||||
_ => wanted.ContainsKey(task.Kind),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// «Raccolta in evidenza» (spec §6.3) for an account that wants «Storie in evidenza»: one task per collection the
|
||||
/// profile check found (payload: its Instagram identifier), due at once for a collection never looked at, then
|
||||
@@ -240,6 +308,11 @@ internal sealed class SessionComposer
|
||||
}
|
||||
}
|
||||
|
||||
if (collections.Count > 0 && !CanRun(RecipeKind.Highlight))
|
||||
{
|
||||
collections.Clear();
|
||||
}
|
||||
|
||||
foreach (var task in planned.Where(t => t.Payload is null || !collections.ContainsKey(t.Payload)))
|
||||
{
|
||||
await Store.Tasks.CancelAsync(task.Id, now, ct).ConfigureAwait(false);
|
||||
@@ -265,11 +338,73 @@ internal sealed class SessionComposer
|
||||
private bool InFlight(long accountId, EngineTaskKind kind, string? payload) =>
|
||||
_inFlight is { } task && task.AccountId == accountId && task.Kind == kind && (payload is null || task.Payload == payload);
|
||||
|
||||
/// <summary>The Giro dei seguiti shown in the queue at the next session.</summary>
|
||||
public Task EnsureSweepTaskAsync(DateTimeOffset dueAt, CancellationToken ct) =>
|
||||
Store.Tasks.EnqueueAsync(
|
||||
/// <summary>The Giro dei seguiti shown in the queue at the next session (when the configuration lets it run).</summary>
|
||||
public async Task EnsureSweepTaskAsync(DateTimeOffset dueAt, CancellationToken ct)
|
||||
{
|
||||
if (!CanRun(RecipeKind.FollowingSweep))
|
||||
{
|
||||
await SayNotConfiguredAsync().ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await Store.Tasks.EnqueueAsync(
|
||||
new EngineTask { Kind = EngineTaskKind.FollowingSweep, DueAt = dueAt, CreatedAt = Clock.Now },
|
||||
ct);
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why the configuration of the site in use (target map, reader vocabulary) does not let <paramref name="kind"/>
|
||||
/// run, as the runner says or as a run of it said; null when it can.
|
||||
/// </summary>
|
||||
internal string? NotConfiguredReason(RecipeKind kind)
|
||||
{
|
||||
lock (_configurationGate)
|
||||
{
|
||||
if (_notConfigured.TryGetValue(kind, out var known))
|
||||
{
|
||||
return known;
|
||||
}
|
||||
}
|
||||
|
||||
return _runner.NotConfiguredReason(kind);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// False when the configuration does not let <paramref name="kind"/> run. The first time, its reason is kept to be
|
||||
/// said in the timeline (<see cref="SayNotConfiguredAsync"/>): once per recipe and process, not at every session.
|
||||
/// </summary>
|
||||
private bool CanRun(RecipeKind kind)
|
||||
{
|
||||
if (NotConfiguredReason(kind) is not { } reason)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
lock (_configurationGate)
|
||||
{
|
||||
if (_notConfiguredSaid.Add(kind))
|
||||
{
|
||||
_notConfiguredToSay.Add(reason);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private async Task SayNotConfiguredAsync()
|
||||
{
|
||||
string[] reasons;
|
||||
lock (_configurationGate)
|
||||
{
|
||||
reasons = [.. _notConfiguredToSay];
|
||||
_notConfiguredToSay.Clear();
|
||||
}
|
||||
|
||||
foreach (var reason in reasons)
|
||||
{
|
||||
await _s.Events.WriteAsync(EventSeverity.Warning, EngineEventCodes.RecipeNotConfigured, reason + NotConfiguredTail, ct: CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private Dictionary<EngineTaskKind, DateTimeOffset?> WantedKinds(Account account)
|
||||
{
|
||||
@@ -284,7 +419,7 @@ internal sealed class SessionComposer
|
||||
if (profile)
|
||||
{
|
||||
// A profile that is not followed shows its stories only on its page: one visit serves both checks.
|
||||
wanted[EngineTaskKind.ProfileCheck] = !account.IsFollowed && stories
|
||||
wanted[EngineTaskKind.ProfileCheck] = VisitServesStories(account)
|
||||
? Earliest(account.NextProfileCheckAt, account.NextStoriesCheckAt)
|
||||
: account.NextProfileCheckAt;
|
||||
}
|
||||
@@ -306,7 +441,21 @@ internal sealed class SessionComposer
|
||||
private static DateTimeOffset? Earliest(DateTimeOffset? a, DateTimeOffset? b) =>
|
||||
a is null || b is null ? null : a < b ? a : b;
|
||||
|
||||
private static bool IsStoryWork(EngineTask task, Dictionary<long, Account> accounts, DateTimeOffset now)
|
||||
/// <summary>
|
||||
/// Whether a visit of the profile also checks its stories, so that it comes at the shorter of the two intervals: a
|
||||
/// profile that is not followed, with «Storie» on, while the configuration lets «Storie di un account» run. Without
|
||||
/// it the visit is a plain profile check (story times are left as they are, for when the stories can run).
|
||||
/// </summary>
|
||||
private bool VisitServesStories(Account account) =>
|
||||
!account.IsFollowed && CheckPolicy.WantsStories(account) && CanRun(RecipeKind.AccountStories);
|
||||
|
||||
/// <summary>Interval of a visit of the profile (<see cref="CheckPolicy.VisitInterval"/> only when it serves the stories).</summary>
|
||||
private TimeSpan VisitInterval(Account account, TimeSpan window) =>
|
||||
VisitServesStories(account)
|
||||
? CheckPolicy.VisitInterval(account, window, Options.MinimumStoryChecksPerDay)
|
||||
: CheckPolicy.ProfileCheckInterval(account);
|
||||
|
||||
private bool IsStoryWork(EngineTask task, Dictionary<long, Account> accounts, DateTimeOffset now)
|
||||
{
|
||||
if (task.Kind == EngineTaskKind.AccountStories)
|
||||
{
|
||||
@@ -317,8 +466,7 @@ internal sealed class SessionComposer
|
||||
return task.Kind == EngineTaskKind.ProfileCheck
|
||||
&& task.AccountId is { } id
|
||||
&& accounts.TryGetValue(id, out var account)
|
||||
&& !account.IsFollowed
|
||||
&& CheckPolicy.WantsStories(account)
|
||||
&& VisitServesStories(account)
|
||||
&& (account.NextStoriesCheckAt is null || account.NextStoriesCheckAt <= now);
|
||||
}
|
||||
|
||||
@@ -331,7 +479,7 @@ internal sealed class SessionComposer
|
||||
{
|
||||
var interval = task.Kind == EngineTaskKind.AccountStories
|
||||
? CheckPolicy.StoryInterval(account, window, Options.MinimumStoryChecksPerDay)
|
||||
: CheckPolicy.VisitInterval(account, window, Options.MinimumStoryChecksPerDay);
|
||||
: VisitInterval(account, window);
|
||||
items.Add((task, CheckPolicy.SelectionWeight(account, now - task.DueAt, interval)));
|
||||
}
|
||||
else
|
||||
@@ -515,6 +663,15 @@ internal sealed class SessionComposer
|
||||
|
||||
var now = Clock.Now;
|
||||
var flagged = new HashSet<long>(outcome.AccountsWithStories);
|
||||
|
||||
// No check is queued that the configuration does not let run: it would only wait, and go at the next session.
|
||||
// Nothing is lost: until their stories are checked, every sweep flags these accounts again.
|
||||
if (flagged.Count > 0 && !CanRun(RecipeKind.AccountStories))
|
||||
{
|
||||
flagged.Clear();
|
||||
await SayNotConfiguredAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var id in flagged)
|
||||
{
|
||||
if (accounts.TryGetValue(id, out var account) && CheckPolicy.IsContactable(account) && CheckPolicy.WantsStories(account))
|
||||
@@ -568,14 +725,16 @@ internal sealed class SessionComposer
|
||||
/// History advances on one account per session, alternating among the accounts «Storico in corso», each up to its
|
||||
/// daily maximum; suspended while the account has too many files waiting or the data budget is reached (§6.3).
|
||||
/// </summary>
|
||||
private async Task RunBackfillAsync(Dictionary<long, Account> accounts, SessionState state, CancellationToken ct)
|
||||
private async Task RunBackfillAsync(SessionState state, CancellationToken ct)
|
||||
{
|
||||
if (_health.IsSuspended(RecipeKind.Backfill) || state.Exhausted.Contains(ActionKind.BackfillPage))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var candidates = accounts.Values
|
||||
// Read again, not taken from the start of the session: a profile check of this session may have completed a
|
||||
// history already (its line is written), and that account is not walked again.
|
||||
var candidates = (await Store.Accounts.ListAsync(ct).ConfigureAwait(false))
|
||||
.Where(a => a.State == AccountState.Backfilling && a.BackfillCompletedAt is null && CheckPolicy.IsContactable(a))
|
||||
.ToList();
|
||||
if (candidates.Count == 0)
|
||||
@@ -583,6 +742,12 @@ internal sealed class SessionComposer
|
||||
return;
|
||||
}
|
||||
|
||||
if (!CanRun(RecipeKind.Backfill))
|
||||
{
|
||||
await SayNotConfiguredAsync().ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var now = Clock.Now;
|
||||
var zone = Clock.LocalZone;
|
||||
var today = LocalCalendar.Today(now, zone);
|
||||
@@ -651,6 +816,25 @@ internal sealed class SessionComposer
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!CanRun(request.Kind))
|
||||
{
|
||||
await SayNotConfiguredAsync().ConfigureAwait(false);
|
||||
if (task is { IsManual: true })
|
||||
{
|
||||
// A command of Alberto that cannot be carried out with these files: dropped, and he is told why.
|
||||
await Store.Tasks.CancelAsync(task.Id, Clock.Now, CancellationToken.None).ConfigureAwait(false);
|
||||
await _s.Events.WriteAsync(
|
||||
EventSeverity.Warning,
|
||||
EngineEventCodes.RecipeNotConfigured,
|
||||
$"La tua richiesta ({RecipeName(request.Kind)}{Of(account)}) è annullata: {NotConfiguredReason(request.Kind)}",
|
||||
account?.Id,
|
||||
state.Context.SessionId,
|
||||
CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
var category = CheckPolicy.CategoryOf(request.Kind);
|
||||
if (state.Exhausted.Contains(category))
|
||||
{
|
||||
@@ -771,6 +955,15 @@ internal sealed class SessionComposer
|
||||
var now = Clock.Now;
|
||||
var kind = request.Kind;
|
||||
var writes = new List<Task>();
|
||||
|
||||
// The history reached the beginning of the profile: the walk of the Storico, however the run ended (a signal or
|
||||
// a cancellation can come right after the last page was stored, and that account would not be walked again),
|
||||
// or a profile check that found the whole profile on its first page. What follows sees the account as it is now.
|
||||
if (kind is RecipeKind.Backfill or RecipeKind.ProfileCheck && outcome.BackfillFinished && account is not null)
|
||||
{
|
||||
account = await FinishBackfillAsync(account, state, now, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
switch (outcome.Status)
|
||||
{
|
||||
case RecipeStatus.Completed:
|
||||
@@ -798,7 +991,12 @@ internal sealed class SessionComposer
|
||||
|
||||
case RecipeStatus.StoppedBySignal:
|
||||
case RecipeStatus.Cancelled:
|
||||
if (task is not null)
|
||||
if (task is not null && kind == RecipeKind.Backfill && outcome.BackfillFinished)
|
||||
{
|
||||
// The walk got to the end before the run stopped: nothing to take up again (closed above).
|
||||
writes.Add(Store.Tasks.CompleteAsync(task.Id, now, ct));
|
||||
}
|
||||
else if (task is not null)
|
||||
{
|
||||
await RequeueAsync(task, outcome.Status == RecipeStatus.Cancelled ? "Interrotta" : "Fermata da un segnale", now).ConfigureAwait(false);
|
||||
}
|
||||
@@ -829,6 +1027,26 @@ internal sealed class SessionComposer
|
||||
$"Formato non riconosciuto durante {RecipeName(kind)}{Of(account)}: Instagram potrebbe aver cambiato le sue risposte.", now).ConfigureAwait(false);
|
||||
break;
|
||||
|
||||
case RecipeStatus.NotConfigured:
|
||||
// Not a failure: the files of the site do not let it run. Never counted towards suspension, not tried
|
||||
// again in this process (the runner has said why); a command of Alberto is dropped, planned work waits.
|
||||
lock (_configurationGate)
|
||||
{
|
||||
_notConfigured.TryAdd(kind, outcome.Message ?? $"«{ItalianText.Capitalize(RecipeName(kind))}» non può girare con la configurazione attuale.");
|
||||
_notConfiguredSaid.Add(kind);
|
||||
}
|
||||
|
||||
if (task is { IsManual: true })
|
||||
{
|
||||
writes.Add(Store.Tasks.CancelAsync(task.Id, now, ct));
|
||||
}
|
||||
else if (task is not null)
|
||||
{
|
||||
await RequeueAsync(task, "Configurazione incompleta", now).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case RecipeStatus.AccountUnreachable:
|
||||
if (task is not null)
|
||||
{
|
||||
@@ -909,9 +1127,10 @@ internal sealed class SessionComposer
|
||||
{
|
||||
case RecipeKind.ProfileCheck:
|
||||
{
|
||||
// A profile not followed is visited at the earlier of its post check and its story check.
|
||||
// A profile not followed is visited at the earlier of its post check and its story check (while the
|
||||
// stories can run: otherwise only for its posts).
|
||||
var next = now + CheckPolicy.NextCheckDelay(_s.Random, CheckPolicy.ProfileCheckInterval(account));
|
||||
DateTimeOffset? storiesNext = !account.IsFollowed && CheckPolicy.WantsStories(account)
|
||||
DateTimeOffset? storiesNext = VisitServesStories(account)
|
||||
? now + CheckPolicy.NextStoryCheckDelay(_s.Random, CheckPolicy.StoryInterval(account, window, Options.MinimumStoryChecksPerDay))
|
||||
: null;
|
||||
state.LastVisitNext = storiesNext;
|
||||
@@ -947,27 +1166,8 @@ internal sealed class SessionComposer
|
||||
break;
|
||||
}
|
||||
|
||||
case RecipeKind.Backfill when outcome.BackfillFinished:
|
||||
{
|
||||
var fresh = await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? account;
|
||||
await Store.Accounts.SetBackfillAsync(account.Id, fresh.BackfillCursor, now, ct).ConfigureAwait(false);
|
||||
var newState = fresh.KeepUpdated ? AccountState.UpToDate : AccountState.Paused;
|
||||
await Store.Accounts.SetStateAsync(account.Id, newState, now, null, ct).ConfigureAwait(false);
|
||||
var total = await Store.Entries.CountDiscoveredAsync(account.Id, EntryKind.Post, DateTimeOffset.UnixEpoch, now.AddSeconds(1), ct).ConfigureAwait(false);
|
||||
var tail = fresh.KeepUpdated
|
||||
? " Da ora lo tengo aggiornato."
|
||||
: " «Tieni aggiornato» è spento: l'account resta in pausa.";
|
||||
await _s.Events.WriteAsync(
|
||||
EventSeverity.Success,
|
||||
EngineEventCodes.BackfillCompleted,
|
||||
$"Storico di {ItalianText.Handle(account.Username)} completato: {ItalianText.Count(total, "post", "post")} in libreria.{tail}",
|
||||
account.Id,
|
||||
state.Context.SessionId,
|
||||
ct).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
|
||||
case RecipeKind.Backfill:
|
||||
// A history completed: FinishBackfillAsync, from ApplyOutcomeAsync.
|
||||
case RecipeKind.Backfill when !outcome.BackfillFinished:
|
||||
if (contactable)
|
||||
{
|
||||
// Behind the other accounts «Storico in corso»: they alternate.
|
||||
@@ -980,6 +1180,43 @@ internal sealed class SessionComposer
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The history of the account is complete: «Aggiornato» (or «In pausa» with «Tieni aggiornato» off) and the one
|
||||
/// «storico completato» line of Attività, which is also the alert (spec §13.3). The recipes write no line of their
|
||||
/// own for it. Called once per history: after it the account is no longer «Storico in corso». Returns the account
|
||||
/// as it is now.
|
||||
/// </summary>
|
||||
private async Task<Account> FinishBackfillAsync(Account account, SessionState state, DateTimeOffset now, CancellationToken ct)
|
||||
{
|
||||
var fresh = await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? account;
|
||||
await Store.Accounts.SetBackfillAsync(account.Id, fresh.BackfillCursor, now, ct).ConfigureAwait(false);
|
||||
var newState = fresh.KeepUpdated ? AccountState.UpToDate : AccountState.Paused;
|
||||
await Store.Accounts.SetStateAsync(account.Id, newState, now, null, ct).ConfigureAwait(false);
|
||||
|
||||
// The Coda follows at once, not at the next session: no «Storico» left for the account, and nothing planned
|
||||
// for an account that stays paused. Commands of Alberto stay; the task in flight is settled by its outcome.
|
||||
foreach (var task in await Store.Tasks.ListPendingAsync(10_000, ct).ConfigureAwait(false))
|
||||
{
|
||||
if (task.AccountId == account.Id && !task.IsManual && (newState == AccountState.Paused || task.Kind == EngineTaskKind.Backfill))
|
||||
{
|
||||
await Store.Tasks.CancelAsync(task.Id, now, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
var total =await Store.Entries.CountDiscoveredAsync(account.Id, EntryKind.Post, DateTimeOffset.UnixEpoch, now.AddSeconds(1), ct).ConfigureAwait(false);
|
||||
var tail = fresh.KeepUpdated
|
||||
? " Da ora lo tengo aggiornato."
|
||||
: " «Tieni aggiornato» è spento: l'account resta in pausa.";
|
||||
await _s.Events.WriteAsync(
|
||||
EventSeverity.Success,
|
||||
EngineEventCodes.BackfillCompleted,
|
||||
$"Storico di {ItalianText.Handle(account.Username)} completato: {ItalianText.Count(total, "post", "post")} in libreria.{tail}",
|
||||
account.Id,
|
||||
state.Context.SessionId,
|
||||
ct).ConfigureAwait(false);
|
||||
return await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? fresh;
|
||||
}
|
||||
|
||||
private async Task PauseAfterSingleDownloadAsync(Account account, DateTimeOffset now, SessionState state, CancellationToken ct)
|
||||
{
|
||||
await Store.Accounts.SetStateAsync(account.Id, AccountState.Paused, now, null, ct).ConfigureAwait(false);
|
||||
@@ -1100,6 +1337,7 @@ internal sealed class SessionComposer
|
||||
RecipeStatus.UnrecognizedFormat => "Formato non riconosciuto",
|
||||
RecipeStatus.AccountUnreachable => "Non raggiungibile",
|
||||
RecipeStatus.Cancelled => "Interrotto",
|
||||
RecipeStatus.NotConfigured => "Configurazione della raccolta incompleta",
|
||||
_ => "Non riuscito",
|
||||
};
|
||||
return (title, detail);
|
||||
|
||||
@@ -12,16 +12,31 @@ namespace Febe.Desktop.Browser;
|
||||
/// <summary>
|
||||
/// The browser of Instagram on Windows as the shared composition sees it (<see cref="IFebeBrowser"/>): a
|
||||
/// <see cref="WebView2Host"/> started with retries like <see cref="ChromiumBrowser"/> starts Chromium, started again
|
||||
/// when its browser process goes away, and emptied by «Scollega» (spec §4.1) once WebView2 has closed.
|
||||
/// (with the same retries) when its browser process goes away, and emptied by «Scollega» (spec §4.1) once WebView2 has
|
||||
/// closed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Only a failed start is retried: what follows a start that worked (the log line, the state) is outside the retries,
|
||||
/// and reads only plain values of the host, never WebView2 objects — this class runs on the threads of the composition,
|
||||
/// while every WebView2 object lives on the UI thread (the error of 14 October 2026: the version of WebView2 read here,
|
||||
/// on a thread-pool thread, threw after every successful start, and the start was undone and retried for ever).
|
||||
/// </remarks>
|
||||
internal sealed class WebView2Browser : IFebeBrowser
|
||||
{
|
||||
private static readonly TimeSpan[] Retry = [TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5)];
|
||||
|
||||
/// <summary>How long stopping waits for the restart loop to end before closing WebView2 anyway.</summary>
|
||||
private static readonly TimeSpan StopWait = TimeSpan.FromSeconds(30);
|
||||
|
||||
private readonly WebView2BrowserSettings _settings;
|
||||
private readonly FebePlatformContext _context;
|
||||
private readonly IClock _wallClock;
|
||||
private readonly BrowserOptions _options;
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private readonly Lock _gate = new();
|
||||
private Task? _restartLoop;
|
||||
private bool _restartWanted;
|
||||
private Exception? _restartFailure;
|
||||
private volatile bool _started;
|
||||
private volatile string? _lastError;
|
||||
|
||||
@@ -39,7 +54,7 @@ internal sealed class WebView2Browser : IFebeBrowser
|
||||
ui,
|
||||
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now)),
|
||||
context.Log);
|
||||
Host.BrowserProcessFailed += (_, _) => _ = RecoverAsync();
|
||||
Host.BrowserProcessFailed += (_, _) => RequestRestart(null);
|
||||
}
|
||||
|
||||
/// <summary>The host: window «Browser di Febe», WebView2, CDP.</summary>
|
||||
@@ -63,35 +78,10 @@ internal sealed class WebView2Browser : IFebeBrowser
|
||||
|
||||
public async Task RunAsync(CancellationToken ct)
|
||||
{
|
||||
for (var attempt = 0; !ct.IsCancellationRequested; attempt++)
|
||||
using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct, _lifetime.Token);
|
||||
if (await StartWithRetriesAsync(token => Host.StartAsync(_options, token), stop.Token).ConfigureAwait(false))
|
||||
{
|
||||
try
|
||||
{
|
||||
await Host.StartAsync(_options, ct).ConfigureAwait(false);
|
||||
_started = true;
|
||||
_lastError = null;
|
||||
_context.Log.Info("browser", $"Browser di Febe pronto: WebView2 {Host.Version}, pagina {WindowWidth.ToString(CultureInfo.InvariantCulture)}×{WindowHeight.ToString(CultureInfo.InvariantCulture)}, {BrowserHostingNames.Name(_settings.Hosting)}, fuori vista.");
|
||||
return;
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_lastError = $"WebView2 non parte ({ex.GetType().Name}: {FirstLine(ex.Message)}).";
|
||||
var wait = Retry[Math.Min(attempt, Retry.Length - 1)];
|
||||
_context.Log.Error("browser", $"{_lastError} Nuovo tentativo fra {wait.TotalSeconds.ToString("0", CultureInfo.InvariantCulture)} s.");
|
||||
await Host.ResetAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await _wallClock.Delay(wait, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
_context.Log.Info("browser", ReadyMessage("Browser di Febe pronto"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,56 +91,218 @@ internal sealed class WebView2Browser : IFebeBrowser
|
||||
|
||||
public Task HideFromUserAsync(CancellationToken ct) => Host.HideFromUserAsync();
|
||||
|
||||
/// <summary>«Scollega»: WebView2 closes and its process exits, <c>Dati\browser</c> is deleted, the browser starts empty.</summary>
|
||||
/// <summary>
|
||||
/// «Scollega»: WebView2 closes and its process exits, <c>Dati\browser</c> is deleted, the browser starts empty. When
|
||||
/// the profile cannot be deleted completely an <see cref="IOException"/> says so (the browser starts again anyway);
|
||||
/// when WebView2 does not start again, the same retries as at start-up bring it back in the background, and
|
||||
/// «Scollega» has still done its part (the connection service starts the engine again either way).
|
||||
/// </summary>
|
||||
public async Task RestartWithEmptyProfileAsync(CancellationToken ct)
|
||||
{
|
||||
Exception? deletion = null;
|
||||
async Task DeleteProfileQuietlyAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await DeleteProfileAsync().ConfigureAwait(true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
deletion = ex;
|
||||
}
|
||||
}
|
||||
|
||||
var restarted = false;
|
||||
try
|
||||
{
|
||||
await Host.RestartAsync(DeleteProfileAsync, ct).ConfigureAwait(false);
|
||||
await Host.RestartAsync(DeleteProfileQuietlyAsync, ct).ConfigureAwait(false);
|
||||
MarkStarted();
|
||||
restarted = true;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
catch (Exception ex) when (ex is not (OutOfMemoryException or ObjectDisposedException))
|
||||
{
|
||||
throw new IOException($"La cartella del browser ({ProfileDirectory}) non si è potuta cancellare del tutto: esci da Febe e cancellala tu, contiene la sessione di Instagram.", ex);
|
||||
// The start that follows the deletion failed: never a dead browser after «Scollega».
|
||||
RequestRestart(ex);
|
||||
}
|
||||
|
||||
_context.Log.Info("browser", "Profilo del browser cancellato; il browser è ripartito vuoto.");
|
||||
if (deletion is not null)
|
||||
{
|
||||
throw new IOException($"La cartella del browser ({ProfileDirectory}) non si è potuta cancellare del tutto: esci da Febe e cancellala tu, contiene la sessione di Instagram.", deletion);
|
||||
}
|
||||
|
||||
_context.Log.Info("browser", restarted
|
||||
? "Profilo del browser cancellato; il browser è ripartito vuoto."
|
||||
: "Profilo del browser cancellato; il browser ripartirà vuoto.");
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync() => Host.DisposeAsync();
|
||||
|
||||
/// <summary>The browser process of WebView2 went away by itself: it starts again with the same profile.</summary>
|
||||
private async Task RecoverAsync()
|
||||
/// <summary>
|
||||
/// Stops the retries, waits for the restart loop to notice (it stops waiting for WebView2 as soon as
|
||||
/// <c>_lifetime</c> is cancelled; at most <see cref="StopWait"/> in any case), then closes WebView2 and its window.
|
||||
/// <c>_lifetime</c> stays undisposed on purpose: a late caller may still read its (cancelled) token.
|
||||
/// </summary>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _lifetime.CancelAsync().ConfigureAwait(false);
|
||||
Task? restarting;
|
||||
lock (_gate)
|
||||
{
|
||||
restarting = _restartLoop;
|
||||
}
|
||||
|
||||
if (restarting is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await restarting.WaitAsync(StopWait).ConfigureAwait(false);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
_context.Log.Warn("browser", "WebView2: la ripartenza del browser non si è fermata in tempo; Febe si chiude lo stesso.");
|
||||
}
|
||||
}
|
||||
|
||||
await Host.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs <paramref name="start"/> until it works (true) or <paramref name="ct"/> is cancelled (false), waiting
|
||||
/// <see cref="Retry"/> between attempts. With <paramref name="failedFirst"/> the first attempt already failed with it.
|
||||
/// Only an exception of the start itself is a failed start; this method never throws.
|
||||
/// </summary>
|
||||
private async Task<bool> StartWithRetriesAsync(Func<CancellationToken, Task> start, CancellationToken ct, Exception? failedFirst = null)
|
||||
{
|
||||
var attempt = 0;
|
||||
if (failedFirst is not null && !await AfterFailedStartAsync(failedFirst, attempt++, ct).ConfigureAwait(false))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await start(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ct.IsCancellationRequested && ex is (OperationCanceledException or ObjectDisposedException))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
if (!await AfterFailedStartAsync(ex, attempt++, ct).ConfigureAwait(false))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
MarkStarted();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A start failed: it is said, and the next attempt waits. False when cancelled. What the failed start created it
|
||||
/// closed itself, inside the host: a close from here could catch a browser that «Scollega» started meanwhile.
|
||||
/// </summary>
|
||||
private async Task<bool> AfterFailedStartAsync(Exception error, int attempt, CancellationToken ct)
|
||||
{
|
||||
var wait = Retry[Math.Min(attempt, Retry.Length - 1)];
|
||||
_lastError = $"WebView2 non parte ({error.GetType().Name}: {FirstLine(error.Message)}).";
|
||||
_context.Log.Error("browser", $"{_lastError} Nuovo tentativo fra {wait.TotalSeconds.ToString("0", CultureInfo.InvariantCulture)} s.");
|
||||
try
|
||||
{
|
||||
await Host.RestartAsync(null, CancellationToken.None).ConfigureAwait(false);
|
||||
_context.Log.Info("browser", "Browser di Febe ripartito dopo l'arresto del suo processo.");
|
||||
await _wallClock.Delay(wait, ct).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
_started = false;
|
||||
_lastError = $"WebView2 non riparte ({ex.GetType().Name}).";
|
||||
_context.Log.Error("browser", _lastError);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Deletes the profile; a process of WebView2 may still hold a file for a moment.</summary>
|
||||
private void MarkStarted()
|
||||
{
|
||||
_started = true;
|
||||
_lastError = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The browser must start again (its process went away by itself, or the start after «Scollega» failed with
|
||||
/// <paramref name="failure"/>): one loop at a time starts it, with the retries of the first start, on the thread
|
||||
/// pool — never inside an event handler of WebView2. A request that comes while the loop runs makes it go round
|
||||
/// again. The loop only starts what is not running: when another way in (the first start, «Scollega») brought the
|
||||
/// browser back first, its attempt finds it running and is done.
|
||||
/// </summary>
|
||||
private void RequestRestart(Exception? failure)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_lifetime.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_restartWanted = true;
|
||||
_restartFailure ??= failure;
|
||||
_restartLoop ??= Task.Run(RestartLoopAsync);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RestartLoopAsync()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
Exception? failure;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_restartWanted || _lifetime.IsCancellationRequested)
|
||||
{
|
||||
_restartLoop = null;
|
||||
return;
|
||||
}
|
||||
|
||||
_restartWanted = false;
|
||||
failure = _restartFailure;
|
||||
_restartFailure = null;
|
||||
}
|
||||
|
||||
if (await StartWithRetriesAsync(token => Host.StartAsync(_options, token), _lifetime.Token, failure).ConfigureAwait(false))
|
||||
{
|
||||
_context.Log.Info("browser", ReadyMessage("Browser di Febe ripartito"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Plain values only (the version was read on the UI thread during the start).</summary>
|
||||
private string ReadyMessage(string what) =>
|
||||
$"{what}: WebView2 {Host.Version ?? "di versione sconosciuta"}, pagina {WindowWidth.ToString(CultureInfo.InvariantCulture)}×{WindowHeight.ToString(CultureInfo.InvariantCulture)}, {BrowserHostingNames.Name(_settings.Hosting)}, fuori vista.";
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the profile — off the UI thread, it can be large — retrying while a process of WebView2 still holds a
|
||||
/// file for a moment.
|
||||
/// </summary>
|
||||
private async Task DeleteProfileAsync()
|
||||
{
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(ProfileDirectory))
|
||||
await Task.Run(() =>
|
||||
{
|
||||
Directory.Delete(ProfileDirectory, recursive: true);
|
||||
}
|
||||
|
||||
if (Directory.Exists(ProfileDirectory))
|
||||
{
|
||||
Directory.Delete(ProfileDirectory, recursive: true);
|
||||
}
|
||||
}).ConfigureAwait(true);
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when ((ex is IOException or UnauthorizedAccessException) && attempt < 10)
|
||||
{
|
||||
await Task.Delay(500).ConfigureAwait(true);
|
||||
await _wallClock.Delay(TimeSpan.FromMilliseconds(500), CancellationToken.None).ConfigureAwait(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Threading;
|
||||
@@ -35,27 +36,49 @@ internal sealed record WebView2HostOptions(BrowserHosting Hosting, string Additi
|
||||
/// «Ho finito»; using and closing it marks the browser as used for «Riprendi».</item>
|
||||
/// <item>Stopping closes the WebView and waits for its browser process to exit, so the session is on disk (S3);
|
||||
/// <see cref="RestartAsync"/> («Scollega») does the same before deleting the profile.</item>
|
||||
/// <item>Every WebView2 call runs on the UI thread through its dispatcher.</item>
|
||||
/// <item>Threads: every WebView2 object (environment, controller, <c>CoreWebView2</c>, its settings and DevTools
|
||||
/// receivers) and the window are touched only on the UI thread, through its dispatcher; WebView2 throws on any other
|
||||
/// thread. Callers on other threads (the composition, the engine) get only plain values captured on the UI thread
|
||||
/// during the start (<see cref="Version"/>, <see cref="BrowserProcessId"/>), the CDP session, and tasks. Start,
|
||||
/// restart and stop run one at a time.</item>
|
||||
/// <item>One WebView at a time, whoever starts it (the first start and its retries, «Scollega», the start after a
|
||||
/// crash): a start finds the WebView running and does nothing, closes what a dead one left before creating a new one,
|
||||
/// and when it fails it closes what it created itself. Events of a closed WebView never count.</item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
internal sealed class WebView2Host : IBrowserHost
|
||||
{
|
||||
private static readonly TimeSpan ExitWait = TimeSpan.FromSeconds(15);
|
||||
|
||||
/// <summary>How long stopping waits for a start or restart in progress before closing what there is.</summary>
|
||||
private static readonly TimeSpan StopWait = TimeSpan.FromSeconds(30);
|
||||
|
||||
private readonly Dispatcher _ui;
|
||||
private readonly WebView2HostOptions _settings;
|
||||
private readonly FebeLog _log;
|
||||
private readonly WebView2CdpSession _session;
|
||||
|
||||
// Start, restart and dispose each await WebView2 on the UI thread: without this they could interleave there.
|
||||
private readonly SemaphoreSlim _lifecycle = new(1, 1);
|
||||
|
||||
// The fields below are touched on the UI thread only.
|
||||
private BrowserOptions? _options;
|
||||
private BrowserWindow? _window;
|
||||
private CoreWebView2Environment? _environment;
|
||||
private CoreWebView2Controller? _controller;
|
||||
private CoreWebView2? _core;
|
||||
private CompositionHost? _composition;
|
||||
private CoreWebView2DevTools? _devTools;
|
||||
private TaskCompletionSource? _exited;
|
||||
private IDisposable? _lease;
|
||||
private int _generation;
|
||||
private bool _starting;
|
||||
private bool _crashedWhileStarting;
|
||||
private bool _closing;
|
||||
private bool _restarting;
|
||||
|
||||
// Plain values read on the UI thread during the start: any thread may read them.
|
||||
private volatile string? _version;
|
||||
private int _browserProcessId;
|
||||
|
||||
public WebView2Host(Dispatcher ui, WebView2HostOptions settings, FebeLog log)
|
||||
{
|
||||
@@ -79,18 +102,41 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
/// <summary>True while a WebView is attached (commands can be sent).</summary>
|
||||
public bool IsAttached => _session.IsAttached;
|
||||
|
||||
/// <summary>The version of the WebView2 runtime in use (for the log).</summary>
|
||||
public string? Version => _environment?.BrowserVersionString;
|
||||
/// <summary>
|
||||
/// The version of the WebView2 runtime of the browser in use (for the log), read on the UI thread when it started;
|
||||
/// null before the first start. Any thread: it is a plain value, never a member of a WebView2 object.
|
||||
/// </summary>
|
||||
public string? Version => _version;
|
||||
|
||||
/// <summary>Raised on the UI thread when the browser process of WebView2 went away by itself (the owner restarts).</summary>
|
||||
/// <summary>The browser process of WebView2 when it last started (0 before the first start). Any thread.</summary>
|
||||
public int BrowserProcessId => Volatile.Read(ref _browserProcessId);
|
||||
|
||||
/// <summary>The window «Browser di Febe» (null before the first start). UI thread only, like every WPF object.</summary>
|
||||
internal BrowserWindow? Window => _window;
|
||||
|
||||
/// <summary>
|
||||
/// Raised on the UI thread when the browser process of WebView2 went away by itself (the owner restarts), after the
|
||||
/// handler of WebView2's own event has returned: WebView2 does not support closing and recreating inside it.
|
||||
/// </summary>
|
||||
public event EventHandler? BrowserProcessFailed;
|
||||
|
||||
/// <summary>Creates the window (once), the environment and the controller, and attaches the CDP session.</summary>
|
||||
/// <summary>
|
||||
/// Creates the window (once), the environment and the controller, and attaches the CDP session — unless a WebView
|
||||
/// is already running, because another way in started it («Scollega», the start after a crash): then it does nothing
|
||||
/// and the start counts as done. A failed start leaves nothing open. When <paramref name="ct"/> is cancelled (Febe
|
||||
/// is exiting) the caller stops waiting at once, even while WebView2 has not answered: a start not yet begun does not
|
||||
/// begin, one under way on the UI thread ends by itself, and stopping closes what it leaves.
|
||||
/// </summary>
|
||||
public Task StartAsync(BrowserOptions options, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
_options = options;
|
||||
return OnUiAsync(StartCoreAsync);
|
||||
var start = OnUiAsync(() => ExclusiveAsync(() =>
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return StartCoreAsync();
|
||||
}));
|
||||
return UntilCancelledAsync(start, ct);
|
||||
}
|
||||
|
||||
public Task ShowToUserAsync() => OnUiAsync(() =>
|
||||
@@ -104,8 +150,18 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
window.Activate();
|
||||
window.Topmost = true;
|
||||
window.Topmost = false;
|
||||
_controller?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic);
|
||||
|
||||
// The lease first: once the window is on screen the engine must be still, whatever happens to the focus.
|
||||
TakeLease();
|
||||
try
|
||||
{
|
||||
_controller?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic);
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
||||
{
|
||||
// The browser process is gone (it is starting again): the window is on screen anyway.
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
@@ -119,55 +175,50 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
/// <summary>
|
||||
/// Closes the WebView, waits for its browser process to exit (the profile is free and written), runs
|
||||
/// <paramref name="whileStopped"/> — «Scollega» deletes the profile there — and starts it again. <see cref="Cdp"/>
|
||||
/// stays the same object. The browser starts again even when <paramref name="whileStopped"/> fails; its error is
|
||||
/// thrown afterwards.
|
||||
/// stays the same object. The browser starts again even when <paramref name="whileStopped"/> fails with an
|
||||
/// <see cref="IOException"/> or <see cref="UnauthorizedAccessException"/>; that error is thrown afterwards. A failed
|
||||
/// start throws its own error and, like a failed <see cref="StartAsync"/>, leaves nothing open. Once begun it goes
|
||||
/// to the end whatever <paramref name="ct"/> says (the profile with the Instagram session must go, and the engine
|
||||
/// starts again after it); stopping waits for it at most <see cref="StopWait"/>.
|
||||
/// </summary>
|
||||
public Task RestartAsync(Func<Task>? whileStopped, CancellationToken ct) => OnUiAsync(async () =>
|
||||
public Task RestartAsync(Func<Task>? whileStopped, CancellationToken ct) => OnUiAsync(() => ExclusiveAsync(async () =>
|
||||
{
|
||||
_restarting = true;
|
||||
try
|
||||
ObjectDisposedException.ThrowIf(_closing, this);
|
||||
Exception? failure = null;
|
||||
await CloseWebViewAsync().ConfigureAwait(true);
|
||||
if (whileStopped is not null)
|
||||
{
|
||||
await CloseWebViewAsync().ConfigureAwait(true);
|
||||
Exception? failure = null;
|
||||
try
|
||||
{
|
||||
if (whileStopped is not null)
|
||||
{
|
||||
await whileStopped().ConfigureAwait(true);
|
||||
}
|
||||
await whileStopped().ConfigureAwait(true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
failure = ex;
|
||||
}
|
||||
|
||||
await StartCoreAsync().ConfigureAwait(true);
|
||||
if (failure is not null)
|
||||
{
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
finally
|
||||
|
||||
await StartCoreAsync().ConfigureAwait(true);
|
||||
if (failure is not null)
|
||||
{
|
||||
_restarting = false;
|
||||
ExceptionDispatchInfo.Throw(failure);
|
||||
}
|
||||
});
|
||||
|
||||
/// <summary>Closes what a failed start left, so that the next start begins clean.</summary>
|
||||
public Task ResetAsync() => OnUiAsync(CloseWebViewAsync);
|
||||
}));
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await OnUiAsync(async () =>
|
||||
{
|
||||
_closing = true;
|
||||
ReleaseLease();
|
||||
await CloseWebViewAsync().ConfigureAwait(true);
|
||||
_window?.CloseForGood();
|
||||
_window = null;
|
||||
}).ConfigureAwait(false);
|
||||
await OnUiAsync(() => ExclusiveAsync(
|
||||
async () =>
|
||||
{
|
||||
_closing = true;
|
||||
ReleaseLease();
|
||||
await CloseWebViewAsync().ConfigureAwait(true);
|
||||
_window?.CloseForGood();
|
||||
_window = null;
|
||||
},
|
||||
StopWait)).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or TaskCanceledException)
|
||||
{
|
||||
@@ -177,9 +228,71 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
await _session.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>True while a WebView is in the window and attached to the session (its browser process did not die).</summary>
|
||||
private bool IsRunning => _controller is not null && _session.IsAttached;
|
||||
|
||||
/// <summary>
|
||||
/// UI thread, one at a time (<see cref="ExclusiveAsync"/>): the only place a WebView is created, so the window never
|
||||
/// holds two. A WebView already running stays (the start is done); what a dead one left is closed first; a failed
|
||||
/// start closes what it created.
|
||||
/// </summary>
|
||||
private async Task StartCoreAsync()
|
||||
{
|
||||
_ui.VerifyAccess();
|
||||
ObjectDisposedException.ThrowIf(_closing, this);
|
||||
var options = _options ?? throw new InvalidOperationException("Opzioni del browser mancanti.");
|
||||
|
||||
// Started already, by «Scollega» or by the start after a crash, while this start waited for its turn or for its
|
||||
// next attempt: a second WebView would orphan the first, whose browser process then holds the profile.
|
||||
if (IsRunning)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// A WebView whose browser process died (the session is detached) is closed before the new one exists.
|
||||
await CloseWebViewAsync().ConfigureAwait(true);
|
||||
_starting = true;
|
||||
_crashedWhileStarting = false;
|
||||
try
|
||||
{
|
||||
await CreateWebViewAsync(options).ConfigureAwait(true);
|
||||
|
||||
// The browser process went away while the start awaited WebView2: this start failed, the caller retries.
|
||||
if (_crashedWhileStarting)
|
||||
{
|
||||
throw new InvalidOperationException("Il processo del browser WebView2 si è chiuso durante l'avvio.");
|
||||
}
|
||||
|
||||
// Stopping gave up waiting for this start (WebView2 took longer than StopWait) and closed what there was:
|
||||
// what this start created goes too.
|
||||
ObjectDisposedException.ThrowIf(_closing, this);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// Nothing stays open after a failed start, whoever retries it and whenever: here, inside the same step.
|
||||
await CloseAfterFailedStartAsync().ConfigureAwait(true);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_starting = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CloseAfterFailedStartAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await CloseWebViewAsync().ConfigureAwait(true);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_log.Warn("browser", "WebView2: quello che l'avvio non riuscito ha lasciato aperto non si è chiuso del tutto.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CreateWebViewAsync(BrowserOptions options)
|
||||
{
|
||||
if (_window is null)
|
||||
{
|
||||
var window = new BrowserWindow(options.WindowWidth, options.WindowHeight, _settings.Icon);
|
||||
@@ -196,24 +309,31 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
var profile = Path.GetFullPath(options.ProfileDirectory);
|
||||
Directory.CreateDirectory(profile);
|
||||
var environmentOptions = new CoreWebView2EnvironmentOptions { AdditionalBrowserArguments = _settings.AdditionalBrowserArguments };
|
||||
_environment = await CoreWebView2Environment.CreateAsync(null, profile, environmentOptions).ConfigureAwait(true);
|
||||
var environment = await CoreWebView2Environment.CreateAsync(null, profile, environmentOptions).ConfigureAwait(true);
|
||||
_environment = environment;
|
||||
_exited = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_environment.BrowserProcessExited += OnBrowserProcessExited;
|
||||
environment.BrowserProcessExited += OnBrowserProcessExited;
|
||||
|
||||
// Read here, on the UI thread, for the log line the composition writes from another thread: a member of the
|
||||
// environment read there throws «CoreWebView2Environment members can only be accessed from the UI thread».
|
||||
_version = environment.BrowserVersionString;
|
||||
|
||||
var hwnd = _window.Handle;
|
||||
CoreWebView2Controller controller;
|
||||
if (_settings.Hosting == BrowserHosting.Composition)
|
||||
{
|
||||
var composition = await _environment.CreateCoreWebView2CompositionControllerAsync(hwnd).ConfigureAwait(true);
|
||||
var composition = await environment.CreateCoreWebView2CompositionControllerAsync(hwnd).ConfigureAwait(true);
|
||||
controller = composition;
|
||||
_controller = controller;
|
||||
_composition = new CompositionHost(hwnd, () => _window?.PageBounds ?? default);
|
||||
_composition.Attach(composition);
|
||||
_controller = composition;
|
||||
}
|
||||
else
|
||||
{
|
||||
_controller = await _environment.CreateCoreWebView2ControllerAsync(hwnd).ConfigureAwait(true);
|
||||
controller = await environment.CreateCoreWebView2ControllerAsync(hwnd).ConfigureAwait(true);
|
||||
_controller = controller;
|
||||
}
|
||||
|
||||
var controller = _controller;
|
||||
controller.BoundsMode = CoreWebView2BoundsMode.UseRawPixels;
|
||||
controller.Bounds = _window.PageBounds;
|
||||
|
||||
@@ -221,6 +341,8 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
controller.IsVisible = true;
|
||||
|
||||
var core = controller.CoreWebView2;
|
||||
_core = core;
|
||||
Volatile.Write(ref _browserProcessId, unchecked((int)core.BrowserProcessId));
|
||||
var s = core.Settings;
|
||||
s.IsPasswordAutosaveEnabled = false;
|
||||
s.IsGeneralAutofillEnabled = false;
|
||||
@@ -228,11 +350,14 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
s.IsZoomControlEnabled = false;
|
||||
s.IsPinchZoomEnabled = false;
|
||||
s.IsSwipeNavigationEnabled = false;
|
||||
|
||||
// Events of an earlier WebView (closed, or crashed) must not act on this one.
|
||||
var generation = ++_generation;
|
||||
core.NewWindowRequested += OnNewWindowRequested;
|
||||
core.DownloadStarting += (_, e) => e.Cancel = true;
|
||||
core.PermissionRequested += (_, e) => e.State = CoreWebView2PermissionState.Deny;
|
||||
core.SourceChanged += (_, _) => _window?.ShowAddress(Addresses.WithoutQuery(core.Source));
|
||||
core.ProcessFailed += OnProcessFailed;
|
||||
core.ProcessFailed += (sender, e) => OnProcessFailed(generation, sender, e);
|
||||
core.Navigate(CdpPageExtensions.RestUrl);
|
||||
|
||||
_devTools = new CoreWebView2DevTools(_ui, core);
|
||||
@@ -240,19 +365,37 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
await _session.SendAsync("Page.enable", null, CancellationToken.None).ConfigureAwait(true);
|
||||
}
|
||||
|
||||
/// <summary>Closes the controller and waits for the browser process to exit (the profile is written). UI thread.</summary>
|
||||
/// <summary>
|
||||
/// Closes the controller and waits for the browser process to exit (the profile is written). UI thread. From here on
|
||||
/// the events of the WebView being closed belong to an old generation: they change nothing.
|
||||
/// </summary>
|
||||
private async Task CloseWebViewAsync()
|
||||
{
|
||||
_ui.VerifyAccess();
|
||||
_generation++;
|
||||
_session.Detach();
|
||||
_devTools?.Close();
|
||||
_devTools = null;
|
||||
_core = null;
|
||||
var exited = _exited;
|
||||
if (_composition is { } composition)
|
||||
{
|
||||
_composition = null;
|
||||
try
|
||||
{
|
||||
composition.Dispose();
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
||||
{
|
||||
// The visual tree goes with the window.
|
||||
}
|
||||
}
|
||||
|
||||
if (_controller is { } controller)
|
||||
{
|
||||
_controller = null;
|
||||
try
|
||||
{
|
||||
_composition?.Dispose();
|
||||
controller.Close();
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
||||
@@ -260,7 +403,6 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
// The browser process is already gone (it crashed): nothing left to close.
|
||||
}
|
||||
|
||||
_composition = null;
|
||||
if (exited is not null)
|
||||
{
|
||||
await Task.WhenAny(exited.Task, Task.Delay(ExitWait)).ConfigureAwait(true);
|
||||
@@ -276,24 +418,42 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
|
||||
private void OnBrowserProcessExited(object? sender, CoreWebView2BrowserProcessExitedEventArgs e) => _exited?.TrySetResult();
|
||||
|
||||
private void OnProcessFailed(object? sender, CoreWebView2ProcessFailedEventArgs e)
|
||||
private void OnProcessFailed(int generation, object? sender, CoreWebView2ProcessFailedEventArgs e)
|
||||
{
|
||||
_log.Warn("browser", $"WebView2: processo terminato ({e.ProcessFailedKind}).");
|
||||
if (_closing || _restarting)
|
||||
var kind = e.ProcessFailedKind;
|
||||
_log.Warn("browser", $"WebView2: processo terminato ({kind}).");
|
||||
|
||||
// A WebView that is closing, closed or replaced is not ours any more (a restart, «Scollega», a failed start).
|
||||
if (_closing || generation != _generation)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.ProcessFailedKind == CoreWebView2ProcessFailedKind.BrowserProcessExited)
|
||||
// During a start the failure is the start's own error: the start closes what it created and the caller retries.
|
||||
if (_starting)
|
||||
{
|
||||
// The whole browser is gone: the owner starts it again (same profile), as the supervisor does with Chromium.
|
||||
_session.Detach();
|
||||
BrowserProcessFailed?.Invoke(this, EventArgs.Empty);
|
||||
_crashedWhileStarting |= kind == CoreWebView2ProcessFailedKind.BrowserProcessExited;
|
||||
return;
|
||||
}
|
||||
else if (e.ProcessFailedKind is CoreWebView2ProcessFailedKind.RenderProcessExited or CoreWebView2ProcessFailedKind.RenderProcessUnresponsive)
|
||||
|
||||
if (kind == CoreWebView2ProcessFailedKind.BrowserProcessExited)
|
||||
{
|
||||
// The whole browser is gone: commands fail from now on, and the owner starts it again (same profile), as
|
||||
// the supervisor does with Chromium — once this handler has returned (threading model of WebView2).
|
||||
_session.Detach();
|
||||
_ = _ui.InvokeAsync(() => BrowserProcessFailed?.Invoke(this, EventArgs.Empty), DispatcherPriority.Background);
|
||||
}
|
||||
else if (kind is CoreWebView2ProcessFailedKind.RenderProcessExited or CoreWebView2ProcessFailedKind.RenderProcessUnresponsive)
|
||||
{
|
||||
// The page crashed: back to the rest page (spec §6.1); a running recipe ends on its own errors.
|
||||
(sender as CoreWebView2)?.Navigate(CdpPageExtensions.RestUrl);
|
||||
try
|
||||
{
|
||||
(sender as CoreWebView2)?.Navigate(CdpPageExtensions.RestUrl);
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
||||
{
|
||||
// The browser went with the page: its own ProcessFailed follows.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -331,19 +491,40 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
private void UserNavigation(Action<CoreWebView2> action, Func<CoreWebView2, bool> allowed)
|
||||
{
|
||||
// «Indietro» and «Ricarica» of the bar are Alberto's own navigation (rule 7): never an engine action.
|
||||
if (_controller?.CoreWebView2 is { } core && allowed(core))
|
||||
if (_core is not { } core)
|
||||
{
|
||||
TakeLease();
|
||||
action(core);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (allowed(core))
|
||||
{
|
||||
TakeLease();
|
||||
action(core);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
||||
{
|
||||
// The browser process is gone (it is starting again): the button does nothing.
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateBounds()
|
||||
{
|
||||
if (_controller is { } controller && _window is { } window)
|
||||
if (_controller is not { } controller || _window is not { } window)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
controller.Bounds = window.PageBounds;
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
||||
{
|
||||
// The browser process is gone: the next start sizes the new WebView.
|
||||
}
|
||||
}
|
||||
|
||||
private void TakeLease()
|
||||
@@ -368,5 +549,75 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
}
|
||||
}
|
||||
|
||||
private Task OnUiAsync(Func<Task> action) => _ui.CheckAccess() ? action() : _ui.InvokeAsync(action).Task.Unwrap();
|
||||
/// <summary>
|
||||
/// Runs one step of the life of the WebView (start, restart, stop) after the others. UI thread. With
|
||||
/// <paramref name="wait"/> the step runs anyway once that time has passed (stopping must not hang behind a start
|
||||
/// that WebView2 never completes).
|
||||
/// </summary>
|
||||
private async Task ExclusiveAsync(Func<Task> step, TimeSpan? wait = null)
|
||||
{
|
||||
var entered = true;
|
||||
if (wait is { } limit)
|
||||
{
|
||||
entered = await _lifecycle.WaitAsync(limit).ConfigureAwait(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
await _lifecycle.WaitAsync().ConfigureAwait(true);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await step().ConfigureAwait(true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (entered)
|
||||
{
|
||||
_lifecycle.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits for <paramref name="work"/> until <paramref name="ct"/> is cancelled. Then the caller goes on and the work
|
||||
/// is left to end by itself; its outcome is observed here, so a late error is never an unobserved task.
|
||||
/// </summary>
|
||||
private static async Task UntilCancelledAsync(Task work, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await work.WaitAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
_ = work.ContinueWith(
|
||||
static done => _ = done.Exception,
|
||||
CancellationToken.None,
|
||||
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
|
||||
TaskScheduler.Default);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs <paramref name="action"/> on the UI thread — at once when already there — and returns its task: an exception
|
||||
/// is always in the task, never thrown to the caller.
|
||||
/// </summary>
|
||||
private Task OnUiAsync(Func<Task> action)
|
||||
{
|
||||
if (!_ui.CheckAccess())
|
||||
{
|
||||
return _ui.InvokeAsync(action).Task.Unwrap();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return action();
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
return Task.FromException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,10 @@
|
||||
<ProjectReference Include="..\Febe.Desktop.Core\Febe.Desktop.Core.csproj" />
|
||||
<PackageReference Include="Microsoft.Web.WebView2" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- Le prove che girano solo su Windows (WebView2 vero sul thread dell'interfaccia). -->
|
||||
<InternalsVisibleTo Include="Febe.Tests.Windows" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- L'icona del marchio (appendice C), generata da BrandMark e IcoWriter: finestre e area di notifica la leggono da qui. -->
|
||||
<EmbeddedResource Include="Febe.ico" LogicalName="Febe.ico" />
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
L'eseguibile per Windows (WPF, `net10.0-windows`; specifica §5, §12). Si compila anche da Linux
|
||||
(`EnableWindowsTargeting`), ma gira solo su Windows: tutto ciò che si può provare altrove sta in
|
||||
`src/Febe.Desktop.Core` (`net10.0`, prove in `tests/Febe.Tests/Desktop`). Guida per l'uso: `docs/windows.md`.
|
||||
`src/Febe.Desktop.Core` (`net10.0`, prove in `tests/Febe.Tests/Desktop`); il resto si prova su Windows, con WebView2
|
||||
vero, in `tests/Febe.Tests.Windows` (`dotnet test tests/Febe.Tests.Windows`). Guida per l'uso: `docs/windows.md`.
|
||||
|
||||
## Come è fatto
|
||||
|
||||
@@ -23,9 +24,22 @@ L'eseguibile per Windows (WPF, `net10.0-windows`; specifica §5, §12). Si compi
|
||||
| `Native/Win32.cs` | Le poche chiamate Win32 e le interfacce di DirectComposition |
|
||||
| `Febe.ico` | Il marchio (appendice C) a 16–256 pixel, generato da `BrandMark`/`IcoWriter` (`FEBE_RIGENERA_ICONA=1 dotnet test --filter IconTests`) |
|
||||
|
||||
Regole che valgono anche qui: le chiamate a WebView2 solo sul thread dell'interfaccia; il browser di Febe non si nasconde
|
||||
e non si riduce mai a icona (S2); nel registro mai indirizzi con il gettone, cookie o tasti; nessun pacchetto oltre a
|
||||
`Microsoft.Web.WebView2` (WPF e Windows Forms vengono con il .NET per Windows).
|
||||
Regole che valgono anche qui:
|
||||
|
||||
- Ogni oggetto di WebView2 (ambiente, controllo, `CoreWebView2`, impostazioni, ricevitori DevTools) e ogni finestra si
|
||||
tocca solo sul thread dell'interfaccia, anche solo per leggere una proprietà: WebView2 lancia
|
||||
`InvalidOperationException` su ogni altro thread. Chi sta su un altro thread (composizione, motore) passa dal
|
||||
dispatcher o legge valori semplici presi durante l'avvio (`WebView2Host.Version`, `BrowserProcessId`). Attenzione a
|
||||
`ConfigureAwait(false)`: dopo, si è su un thread del pool. È l'errore del 14 ottobre 2026 (il browser non partiva mai).
|
||||
- Dentro un gestore di un evento di WebView2 niente chiusure, ricreazioni, cicli di messaggi o shell: si mette in coda
|
||||
sul dispatcher e si fa dopo (modello dei thread di WebView2).
|
||||
- Si riprova solo un avvio fallito: ciò che segue un avvio riuscito (registro, stato) non lo disfa mai.
|
||||
- Un solo WebView alla volta, chiunque lo avvii (primo avvio e suoi tentativi, «Scollega», ripartenza dopo un arresto
|
||||
del processo): l'avvio, dentro la sezione esclusiva di `WebView2Host`, trova quello in funzione e non fa nulla, chiude
|
||||
prima i resti di uno morto, e se fallisce chiude da sé ciò che ha creato. Un WebView orfano terrebbe vivo il processo
|
||||
del browser sul profilo, e «Scollega» non potrebbe più cancellarlo.
|
||||
- Il browser di Febe non si nasconde e non si riduce mai a icona (S2); nel registro mai indirizzi con il gettone, cookie
|
||||
o tasti; nessun pacchetto oltre a `Microsoft.Web.WebView2` (WPF e Windows Forms vengono con il .NET per Windows).
|
||||
|
||||
## Pubblicazione
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.ComponentModel;
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Threading;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
using Microsoft.Web.WebView2.Wpf;
|
||||
|
||||
@@ -120,7 +121,7 @@ internal sealed class MainWindow : Window
|
||||
e.Cancel = true;
|
||||
if (uri.Scheme is "http" or "https")
|
||||
{
|
||||
_ = _openOutside(uri);
|
||||
OpenOutsideLater(uri);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,7 +139,13 @@ internal sealed class MainWindow : Window
|
||||
}
|
||||
else if (uri.Scheme is "http" or "https")
|
||||
{
|
||||
_ = _openOutside(uri);
|
||||
OpenOutsideLater(uri);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens <paramref name="uri"/> in Alberto's browser once the handler of WebView2's event has returned: the shell
|
||||
/// may run a message loop of its own, and WebView2 does not support re-entering its handlers (threading model).
|
||||
/// </summary>
|
||||
private void OpenOutsideLater(Uri uri) => Dispatcher.InvokeAsync(() => _openOutside(uri), DispatcherPriority.Background);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"profiles": {
|
||||
"Sito di prova": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "--dati \"%USERPROFILE%\\FebeSviluppo\\comune\\dati\" --libreria \"%USERPROFILE%\\FebeSviluppo\\comune\\libreria\" --sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 30 --sviluppo"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,18 +17,40 @@ namespace Febe.Server;
|
||||
/// the older view is always ended — and its screencast stopped — before the newer one starts). Keys go to the browser
|
||||
/// and nowhere else.
|
||||
/// </summary>
|
||||
internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log) : IRemoteViewHost
|
||||
internal sealed class BrowserRemoteViewHost : IRemoteViewHost
|
||||
{
|
||||
private readonly IFebeBrowser _browser;
|
||||
private readonly BrowserUseTracker _tracker;
|
||||
private readonly IClock _clock;
|
||||
private readonly IClock _browserClock;
|
||||
private readonly FebeLog _log;
|
||||
private readonly Lock _gate = new();
|
||||
private readonly SemaphoreSlim _opening = new(1, 1);
|
||||
private BrowserRemoteViewConnection? _current;
|
||||
private bool _shuttingDown;
|
||||
|
||||
/// <param name="browser">The browser shown.</param>
|
||||
/// <param name="tracker">Notes when Alberto last used the browser.</param>
|
||||
/// <param name="clock">The composition's clock (the time of that note).</param>
|
||||
/// <param name="log">Febe's log.</param>
|
||||
/// <param name="browserClock">
|
||||
/// Time for the waits on the browser itself; null: the wall clock, because the browser commits a navigation in real
|
||||
/// time whatever clock the engine runs on (the tests compress it).
|
||||
/// </param>
|
||||
public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null)
|
||||
{
|
||||
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
|
||||
_tracker = tracker ?? throw new ArgumentNullException(nameof(tracker));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_log = log ?? throw new ArgumentNullException(nameof(log));
|
||||
_browserClock = browserClock ?? new SystemClock(clock.LocalZone);
|
||||
}
|
||||
|
||||
public async Task<IRemoteViewConnection> OpenAsync(CancellationToken ct)
|
||||
{
|
||||
if (!browser.IsAvailable)
|
||||
if (!_browser.IsAvailable)
|
||||
{
|
||||
throw new RemoteViewUnavailableException(browser.LastError is { } error
|
||||
throw new RemoteViewUnavailableException(_browser.LastError is { } error
|
||||
? "Il browser di Febe non è in funzione: " + error
|
||||
: "Il browser di Febe si sta avviando: riprova fra qualche secondo.");
|
||||
}
|
||||
@@ -37,6 +59,7 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
|
||||
// would both start and the later assignment would orphan the other (still holding its lease, and stopping the
|
||||
// shared screencast when it closes).
|
||||
await _opening.WaitAsync(ct).ConfigureAwait(false);
|
||||
IDisposable? handover = null;
|
||||
try
|
||||
{
|
||||
BrowserRemoteViewConnection? previous;
|
||||
@@ -53,13 +76,17 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
|
||||
|
||||
if (previous is not null)
|
||||
{
|
||||
// Alberto is still at the browser while one view takes the place of the other: without this lease the
|
||||
// engine would see nobody driving for a moment and put the page back to rest (a navigation under the new
|
||||
// view's start) or even begin a session.
|
||||
handover = _browser.UserDriving.Begin();
|
||||
await previous.EndAsync(RemoteViewEnd.Replaced).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var connection = new BrowserRemoteViewConnection(this, browser, tracker, clock);
|
||||
var connection = new BrowserRemoteViewConnection(this, _browser, _tracker, _clock, _browserClock);
|
||||
try
|
||||
{
|
||||
await connection.StartAsync(browser.BrowserOptions.WindowWidth, browser.BrowserOptions.WindowHeight, ct).ConfigureAwait(false);
|
||||
await connection.StartAsync(_browser.WindowWidth, _browser.WindowHeight, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -90,11 +117,13 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
|
||||
throw new RemoteViewUnavailableException("Febe si sta fermando.");
|
||||
}
|
||||
|
||||
log.Info("vista", "Vista remota aperta: il motore resta fermo finché è aperta.");
|
||||
_log.Info("vista", "Vista remota aperta: il motore resta fermo finché è aperta.");
|
||||
return connection;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// The new view holds its own lease by now; if it did not start, nobody is at the browser any more.
|
||||
handover?.Dispose();
|
||||
_opening.Release();
|
||||
}
|
||||
}
|
||||
@@ -126,7 +155,7 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
|
||||
}
|
||||
}
|
||||
|
||||
log.Info("vista", "Vista remota chiusa.");
|
||||
_log.Info("vista", "Vista remota chiusa.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,7 +163,7 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
|
||||
internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
|
||||
{
|
||||
private readonly BrowserRemoteViewHost _owner;
|
||||
private readonly ChromiumBrowser _browser;
|
||||
private readonly IFebeBrowser _browser;
|
||||
private readonly BrowserUseTracker _tracker;
|
||||
private readonly IClock _clock;
|
||||
private readonly RemoteViewSession _session;
|
||||
@@ -155,18 +184,18 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
|
||||
private int _disposed;
|
||||
private bool _used;
|
||||
|
||||
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, ChromiumBrowser browser, BrowserUseTracker tracker, IClock clock)
|
||||
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock)
|
||||
{
|
||||
_owner = owner;
|
||||
_browser = browser;
|
||||
_tracker = tracker;
|
||||
_clock = clock;
|
||||
_session = new RemoteViewSession(browser.Host.Cdp, browser.Host.UserDriving);
|
||||
_session = new RemoteViewSession(browser.Cdp, browser.UserDriving, clock: browserClock);
|
||||
}
|
||||
|
||||
public RemoteViewEnd? Ended { get; private set; }
|
||||
|
||||
private ICdpSession Cdp => _browser.Host.Cdp;
|
||||
private ICdpSession Cdp => _browser.Cdp;
|
||||
|
||||
public async Task StartAsync(int width, int height, CancellationToken ct)
|
||||
{
|
||||
|
||||
@@ -53,7 +53,7 @@ internal sealed class DockerPlatform(ServerOptions options) : IFebePlatform
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
ArgumentNullException.ThrowIfNull(app);
|
||||
RemoteView = new BrowserRemoteViewHost((ChromiumBrowser)app.Browser!, app.Tracker, app.Clock, app.Log);
|
||||
RemoteView = new BrowserRemoteViewHost(app.Browser!, app.Tracker, app.Clock, app.Log);
|
||||
services.AddSingleton<IRemoteViewHost>(RemoteView);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ using System.Threading.Channels;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Web.Connection;
|
||||
using Febe.Web.Engine;
|
||||
using Febe.Web.Library;
|
||||
using Febe.Web.Native;
|
||||
@@ -24,8 +25,8 @@ public static class EngineApi
|
||||
|
||||
public static void Map(IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
endpoints.MapGet("/api/engine", async (IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, CancellationToken ct) =>
|
||||
ApiHttp.Json(await SnapshotAsync(monitor, storage, tracker, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.EngineDto));
|
||||
endpoints.MapGet("/api/engine", async (IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, IConnectionService connection, CancellationToken ct) =>
|
||||
ApiHttp.Json(await SnapshotAsync(monitor, storage, tracker, clock, connection, ct).ConfigureAwait(false), FebeJsonContext.Default.EngineDto));
|
||||
|
||||
endpoints.MapPost("/api/engine/pause", async (IEngineControl control, CancellationToken ct) =>
|
||||
{
|
||||
@@ -78,13 +79,19 @@ public static class EngineApi
|
||||
endpoints.MapGet("/api/eventi", StreamAsync);
|
||||
}
|
||||
|
||||
/// <summary>The engine as the interface needs it.</summary>
|
||||
public static async Task<EngineDto> SnapshotAsync(IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, CancellationToken ct)
|
||||
/// <summary>
|
||||
/// The engine as the interface needs it. The link comes from the session cookie, never from whether «Tu» is known:
|
||||
/// the name of the connected account may come much later (H10), and meanwhile the sidebar says «Collegato» with
|
||||
/// «Nome non ancora noto». The engine looks at the cookie on every turn and its mode says so; when it does not run
|
||||
/// (or there is none in this process) the connection is asked.
|
||||
/// </summary>
|
||||
public static async Task<EngineDto> SnapshotAsync(IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, IConnectionService connection, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(monitor);
|
||||
ArgumentNullException.ThrowIfNull(storage);
|
||||
ArgumentNullException.ThrowIfNull(tracker);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
ArgumentNullException.ThrowIfNull(connection);
|
||||
var snapshot = await monitor.GetSnapshotAsync(ct).ConfigureAwait(false);
|
||||
var mine = await storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
|
||||
var state = snapshot.Mode switch
|
||||
@@ -92,9 +99,10 @@ public static class EngineApi
|
||||
EngineMode.NotConnected => "notConnected",
|
||||
EngineMode.StoppedForVerification => "verification",
|
||||
EngineMode.Disconnected => "disconnected",
|
||||
_ => mine is null ? "notConnected" : "connected",
|
||||
EngineMode.Off => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State == ConnectionState.Connected ? "connected" : "notConnected",
|
||||
_ => "connected",
|
||||
};
|
||||
var connection = state == "notConnected"
|
||||
var link = state == "notConnected"
|
||||
? new ConnectionDto(state, null, null, null)
|
||||
: new ConnectionDto(state, mine?.Username, mine?.DisplayName, null);
|
||||
|
||||
@@ -109,7 +117,7 @@ public static class EngineApi
|
||||
canResume = snapshot.Mode == EngineMode.Paused;
|
||||
}
|
||||
|
||||
return new EngineDto(clock.Now.ToUnixTimeMilliseconds(), snapshot, connection, canResume);
|
||||
return new EngineDto(clock.Now.ToUnixTimeMilliseconds(), snapshot, link, canResume);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -123,7 +131,8 @@ public static class EngineApi
|
||||
IFebeStorage storage,
|
||||
BrowserUseTracker tracker,
|
||||
LibraryChanges library,
|
||||
IClock clock)
|
||||
IClock clock,
|
||||
IConnectionService connection)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var response = context.Response;
|
||||
@@ -235,7 +244,7 @@ public static class EngineApi
|
||||
|
||||
async Task SendEngineAsync()
|
||||
{
|
||||
var dto = await SnapshotAsync(monitor, storage, tracker, clock, ct).ConfigureAwait(false);
|
||||
var dto = await SnapshotAsync(monitor, storage, tracker, clock, connection, ct).ConfigureAwait(false);
|
||||
await WriteAsync(response, "event: motore\ndata: " + JsonSerializer.Serialize(dto, FebeJsonContext.Default.EngineDto) + "\n\n", ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,9 +220,12 @@ export async function mountConnection(page) {
|
||||
function drawConnected() {
|
||||
waitingResume = false;
|
||||
closeView();
|
||||
// Before the first round the name of the account is not known yet: «Collegato» and «Nome non ancora noto», never «@».
|
||||
const nome = status.username || '';
|
||||
const sotto = nome ? status.displayName : t('stato.accountDaLeggere');
|
||||
fill(left, h('div.pannello.collegato',
|
||||
h('div.chi-collegato', avatar(status.username || '', 'g'),
|
||||
h('div', h('h2', t('impostazioni.collegamento.collegatoCome', { nome: status.username || '' })), status.displayName ? h('span.muto', status.displayName) : null)),
|
||||
h('div.chi-collegato', avatar(nome, 'g'),
|
||||
h('div', h('h2', nome ? t('impostazioni.collegamento.collegatoCome', { nome }) : t('stato.collegato')), sotto ? h('span.muto', sotto) : null)),
|
||||
h('p', t('impostazioni.collegamento.collegatoTesto')),
|
||||
h('div.azioni-collegato',
|
||||
h('button.btn', { type: 'button', onclick: useBrowser }, icon('app-window', 's'), t('impostazioni.collegamento.usaBrowser')),
|
||||
|
||||
@@ -323,6 +323,32 @@ export default {
|
||||
}
|
||||
}
|
||||
|
||||
// The empty state: no results of a filter, the first start (spec §10.3: not connected, the two ways to begin) or an
|
||||
// empty library. Whether Febe is connected comes with the engine, which may answer after the library: until then
|
||||
// the page stays blank, as the mosaic does while it loads, rather than guess. The empty state follows the engine
|
||||
// while it is on screen, and is drawn again only when it changes kind.
|
||||
let empty = null;
|
||||
function drawEmpty() {
|
||||
const kind = filtersActive() ? 'filtro' : !engineState() ? 'attesa' : notConnected() ? 'benvenuto' : 'vuota';
|
||||
if (empty && empty.kind === kind && empty.node.isConnected) return;
|
||||
let node;
|
||||
if (kind === 'attesa') {
|
||||
node = h('div', { 'aria-busy': 'true' });
|
||||
} else if (kind === 'filtro') {
|
||||
node = h('div.vuoto-pagina', icon('list-filter'), h('h2', t('libreria.nessuno')), h('p', t('libreria.nessunoTesto')),
|
||||
h('button.btn', { type: 'button', onclick: () => { Object.assign(state, readState(new URLSearchParams())); search.value = ''; apply(); } }, t('libreria.togliFiltri')));
|
||||
} else if (kind === 'benvenuto') {
|
||||
node = welcome();
|
||||
} else {
|
||||
node = h('div.vuoto-pagina', icon('image'), h('h2', t('libreria.vuota')), h('p', t('libreria.vuotaTesto')));
|
||||
}
|
||||
fill(host, node);
|
||||
empty = { kind, node };
|
||||
}
|
||||
page.onEngine(() => {
|
||||
if (empty && empty.node.isConnected) drawEmpty();
|
||||
});
|
||||
|
||||
// The mosaic.
|
||||
async function apply() {
|
||||
setQuery({
|
||||
@@ -347,12 +373,7 @@ export default {
|
||||
onOpen: (tile) => openViewer({ tile, source: mosaic, origin: t('libreria.titolo'), onDeleted: (ids) => mosaic.removeTiles(ids) }),
|
||||
onSelection: drawSelection,
|
||||
onTotals: ({ entries, accounts: n }) => page.count(t('libreria.quanti', { elementi: t('comune.elementi', { n: entries }), account: t('comune.account', { n }) })),
|
||||
onEmpty: () => fill(host, filtersActive()
|
||||
? h('div.vuoto-pagina', icon('list-filter'), h('h2', t('libreria.nessuno')), h('p', t('libreria.nessunoTesto')),
|
||||
h('button.btn', { type: 'button', onclick: () => { Object.assign(state, readState(new URLSearchParams())); search.value = ''; apply(); } }, t('libreria.togliFiltri')))
|
||||
: notConnected()
|
||||
? welcome()
|
||||
: h('div.vuoto-pagina', icon('image'), h('h2', t('libreria.vuota')), h('p', t('libreria.vuotaTesto')))),
|
||||
onEmpty: drawEmpty,
|
||||
});
|
||||
try {
|
||||
await mosaic.start();
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<!-- Prove che girano solo su Windows, con il WebView2 vero: il thread dell'interfaccia di WPF, il browser di Febe,
|
||||
il protocollo DevTools sul sito di prova locale e una sessione di raccolta della composizione condivisa.
|
||||
Si compila anche da Linux (EnableWindowsTargeting, come Febe.Desktop: la CI compila tutta la soluzione), ma si
|
||||
esegue solo su Windows (dotnet test tests/Febe.Tests.Windows); dove manca il runtime WebView2 le prove risultano
|
||||
inconcludenti. Mai Instagram: il browser vede solo 127.0.0.1. -->
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<EnableWindowsTargeting>true</EnableWindowsTargeting>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<!-- Con WPF l'SDK toglie System.IO dagli using impliciti (Path di System.Windows.Shapes): qui serve. -->
|
||||
<Using Include="System.IO" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MSTest" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Febe.Core\Febe.Core.csproj" />
|
||||
<ProjectReference Include="..\..\src\Febe.Data\Febe.Data.csproj" />
|
||||
<ProjectReference Include="..\..\src\Febe.Browser\Febe.Browser.csproj" />
|
||||
<ProjectReference Include="..\..\src\Febe.Web\Febe.Web.csproj" />
|
||||
<ProjectReference Include="..\..\src\Febe.App\Febe.App.csproj" />
|
||||
<ProjectReference Include="..\..\src\Febe.Desktop.Core\Febe.Desktop.Core.csproj" />
|
||||
<ProjectReference Include="..\..\src\Febe.Desktop\Febe.Desktop.csproj" />
|
||||
<ProjectReference Include="..\..\tools\Febe.SitoDiProva\Febe.SitoDiProva.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,2 @@
|
||||
// One WebView2 at a time: every test starts its own browser process, window and UI thread.
|
||||
[assembly: DoNotParallelize]
|
||||
@@ -0,0 +1,127 @@
|
||||
using Febe.App;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Data;
|
||||
using Febe.Desktop.Browser;
|
||||
using Febe.Desktop.Core;
|
||||
using Febe.Web.Engine;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>
|
||||
/// The browser of Febe for Windows on its own, as the composition builds it (<see cref="DesktopPlatform"/> through
|
||||
/// <c>DesktopShell</c>): a <see cref="WebView2Browser"/> with its window «Browser di Febe» and WebView2 on a real UI
|
||||
/// thread, a profile in a temporary Data folder, the switches of S2 and the log of Febe captured.
|
||||
/// </summary>
|
||||
internal sealed class BrowserBed : IAsyncDisposable
|
||||
{
|
||||
private BrowserBed(TestFolder folder, UiThread ui, LogLines lines, FebeLog log, FebeDatabase database, BrowserUseTracker tracker, WebView2Browser browser)
|
||||
{
|
||||
Folder = folder;
|
||||
Ui = ui;
|
||||
Lines = lines;
|
||||
Log = log;
|
||||
Database = database;
|
||||
Tracker = tracker;
|
||||
Browser = browser;
|
||||
}
|
||||
|
||||
public TestFolder Folder { get; }
|
||||
|
||||
public UiThread Ui { get; }
|
||||
|
||||
/// <summary>What Febe wrote in its log.</summary>
|
||||
public LogLines Lines { get; }
|
||||
|
||||
public FebeLog Log { get; }
|
||||
|
||||
public FebeDatabase Database { get; }
|
||||
|
||||
/// <summary>When Alberto last used the browser («Riprendi» after a verification).</summary>
|
||||
public BrowserUseTracker Tracker { get; }
|
||||
|
||||
public WebView2Browser Browser { get; }
|
||||
|
||||
public static async Task<BrowserBed> CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window)
|
||||
{
|
||||
var folder = new TestFolder(name);
|
||||
var ui = await UiThread.StartAsync();
|
||||
var lines = new LogLines();
|
||||
var clock = new SystemClock();
|
||||
var log = new FebeLog(null, lines, clock);
|
||||
var data = new DataFolderLayout(folder.Combine("dati"));
|
||||
var database = await FebeDatabase.OpenAsync(data.Root);
|
||||
var options = new FebeAppOptions { DataFolder = data.Root, LibraryFolder = folder.Combine("libreria") };
|
||||
var tracker = new BrowserUseTracker();
|
||||
var context = new FebePlatformContext(options, data, database, clock, log, tracker);
|
||||
var settings = new WebView2BrowserSettings(data.BrowserProfile, 1280, 900, hosting, BrowserArguments.ForWebView2());
|
||||
|
||||
// Built off the UI thread, as DesktopPlatform.CreateBrowserAsync does after its awaits.
|
||||
var browser = new WebView2Browser(ui.Dispatcher, settings, context, icon: null);
|
||||
return new BrowserBed(folder, ui, lines, log, database, tracker, browser);
|
||||
}
|
||||
|
||||
/// <summary>Waits (real time) until <paramref name="condition"/> holds; fails with <paramref name="what"/> and the log otherwise.</summary>
|
||||
public async Task WaitUntilAsync(Func<bool> condition, TimeSpan timeout, string what, CancellationToken ct)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (!condition())
|
||||
{
|
||||
if (DateTime.UtcNow > deadline)
|
||||
{
|
||||
Assert.Fail($"Tempo scaduto: {what}.\n{Lines.Text}");
|
||||
}
|
||||
|
||||
await Task.Delay(50, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads a value of the UI thread (the window, its position) through the dispatcher.</summary>
|
||||
public Task<T> OnUiAsync<T>(Func<T> read) => Ui.InvokeAsync(read);
|
||||
|
||||
/// <summary>The class names of the child windows of «Browser di Febe»: one per WebView hosted in it.</summary>
|
||||
public Task<IReadOnlyList<string>> ChildWindowsAsync() =>
|
||||
OnUiAsync(() => Browser.Host.Window is { } window ? ChildWindows.Of(window.Handle) : (IReadOnlyList<string>)[]);
|
||||
|
||||
/// <summary>
|
||||
/// Starts the browser from a thread-pool thread, like <c>FebeApp.BringUpBrowserAsync</c>, and waits until
|
||||
/// <see cref="WebView2Browser.RunAsync"/> returns. Fails at once when the log reports a failed start: the loop of
|
||||
/// retries would otherwise go on for ever.
|
||||
/// </summary>
|
||||
public async Task StartAsync(CancellationToken ct, TimeSpan? timeout = null)
|
||||
{
|
||||
var run = Task.Run(() => Browser.RunAsync(ct), ct);
|
||||
var deadline = DateTime.UtcNow + (timeout ?? TimeSpan.FromSeconds(60));
|
||||
while (!run.IsCompleted)
|
||||
{
|
||||
if (Lines.Any("non parte"))
|
||||
{
|
||||
Assert.Fail("Il browser di Febe non è partito al primo tentativo:\n" + Lines.Text);
|
||||
}
|
||||
|
||||
if (DateTime.UtcNow > deadline)
|
||||
{
|
||||
Assert.Fail("Il browser di Febe non è diventato disponibile in tempo:\n" + Lines.Text);
|
||||
}
|
||||
|
||||
await Task.Delay(50, ct);
|
||||
}
|
||||
|
||||
await run;
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await Browser.DisposeAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
await Ui.DisposeAsync();
|
||||
await Database.DisposeAsync();
|
||||
Log.Dispose();
|
||||
Folder.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>
|
||||
/// The direct child windows of a window, by class name. WebView2 hosted in a window («finestra») puts one child window
|
||||
/// per controller into its parent: two of them in «Browser di Febe» mean two WebViews, one of them orphaned.
|
||||
/// </summary>
|
||||
internal static class ChildWindows
|
||||
{
|
||||
/// <summary>The class names of the direct children of <paramref name="parent"/>, in Z order.</summary>
|
||||
public static IReadOnlyList<string> Of(IntPtr parent)
|
||||
{
|
||||
var names = new List<string>();
|
||||
var buffer = new char[256];
|
||||
var child = IntPtr.Zero;
|
||||
while ((child = FindWindowEx(parent, child, null, null)) != IntPtr.Zero)
|
||||
{
|
||||
var length = GetClassName(child, buffer, buffer.Length);
|
||||
names.Add(new string(buffer, 0, Math.Max(length, 0)));
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
[DllImport("user32.dll", EntryPoint = "FindWindowExW", CharSet = CharSet.Unicode)]
|
||||
private static extern IntPtr FindWindowEx(IntPtr parent, IntPtr childAfter, string? className, string? windowName);
|
||||
|
||||
[DllImport("user32.dll", EntryPoint = "GetClassNameW", CharSet = CharSet.Unicode)]
|
||||
private static extern int GetClassName(IntPtr window, [Out] char[] className, int maxCount);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Desktop.Core;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>
|
||||
/// A clock that compresses time, like the one of the Linux suite: <see cref="Delay"/> waits for real only a fraction
|
||||
/// of the requested time and <see cref="Now"/> moves on by the whole of it, so the engine keeps its order of events
|
||||
/// while a session lasts minutes instead of hours.
|
||||
/// </summary>
|
||||
internal sealed class CompressedClock(double factor, TimeZoneInfo zone) : IClock
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private TimeSpan _offset;
|
||||
|
||||
public TimeZoneInfo LocalZone { get; } = zone;
|
||||
|
||||
public DateTimeOffset Now
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return DateTimeOffset.UtcNow + _offset;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task Delay(TimeSpan time, CancellationToken ct)
|
||||
{
|
||||
if (time <= TimeSpan.Zero)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return;
|
||||
}
|
||||
|
||||
var real = TimeSpan.FromTicks((long)(time.Ticks / factor));
|
||||
if (real >= TimeSpan.FromMilliseconds(1))
|
||||
{
|
||||
await Task.Delay(real, ct).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
await Task.Yield();
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
_offset += time - real;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static class TestZones
|
||||
{
|
||||
/// <summary>
|
||||
/// A fixed-offset zone where it is between 12:00 and 13:00 now: inside the active window of every caution profile,
|
||||
/// whatever the hour of the test.
|
||||
/// </summary>
|
||||
public static TimeZoneInfo Noon()
|
||||
{
|
||||
var offset = 12 - DateTimeOffset.UtcNow.Hour;
|
||||
return TimeZoneInfo.CreateCustomTimeZone("Febe/Mezzogiorno", TimeSpan.FromHours(offset), "Mezzogiorno di prova", "Mezzogiorno di prova");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The registry values «CartellaDati» and «NuovaCartellaDati», in memory.</summary>
|
||||
internal sealed class MemoryLocations : IDataFolderLocationStore
|
||||
{
|
||||
public string? Current { get; private set; }
|
||||
|
||||
public string? Pending { get; private set; }
|
||||
|
||||
public void SetCurrent(string? folder) => Current = folder;
|
||||
|
||||
public void SetPending(string? folder) => Pending = folder;
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Febe.App;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Desktop;
|
||||
using Febe.Desktop.Browser;
|
||||
using Febe.Desktop.Core;
|
||||
using Febe.SitoDiProva;
|
||||
using Febe.Web.Native;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>
|
||||
/// The shared composition (<see cref="FebeApp"/>) as Febe.exe composes it — <see cref="DesktopPlatform"/>,
|
||||
/// <c>DesktopShell</c>, the window «Browser di Febe» on a WPF UI thread — against its own test site, in temporary
|
||||
/// folders, on a clock ten times faster and in a zone where it is noon. The interface is asked like the main window asks
|
||||
/// it: with the token of this start and the Origin of the interface.
|
||||
/// </summary>
|
||||
internal sealed class DesktopBed : IAsyncDisposable
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
|
||||
private DesktopBed(TestSite site, TestFolder folder, UiThread ui, LogLines lines, CompressedClock clock, DesktopPlatform platform, FebeApp app)
|
||||
{
|
||||
Site = site;
|
||||
Folder = folder;
|
||||
Ui = ui;
|
||||
Lines = lines;
|
||||
Clock = clock;
|
||||
Platform = platform;
|
||||
App = app;
|
||||
_client = new HttpClient(new HttpClientHandler { UseCookies = false, AllowAutoRedirect = false, UseProxy = false })
|
||||
{
|
||||
BaseAddress = app.Address,
|
||||
Timeout = TimeSpan.FromSeconds(30),
|
||||
};
|
||||
}
|
||||
|
||||
public TestSite Site { get; }
|
||||
|
||||
public TestFolder Folder { get; }
|
||||
|
||||
public UiThread Ui { get; }
|
||||
|
||||
/// <summary>What Febe wrote in its log.</summary>
|
||||
public LogLines Lines { get; }
|
||||
|
||||
public CompressedClock Clock { get; }
|
||||
|
||||
public DesktopPlatform Platform { get; }
|
||||
|
||||
public FebeApp App { get; }
|
||||
|
||||
/// <summary>The browser of Febe: WebView2 (Febe.exe never uses another one unless asked with <c>--browser edge</c>).</summary>
|
||||
public WebView2Browser Browser => App.Browser as WebView2Browser ?? throw new AssertFailedException("Il browser della composizione non è WebView2.");
|
||||
|
||||
/// <param name="name">Prefix of the temporary folder.</param>
|
||||
/// <param name="autoLogin"><c>--accesso-di-prova</c>: the composition opens the test site once at start-up.</param>
|
||||
public static async Task<DesktopBed> StartAsync(string name, bool autoLogin, CancellationToken ct)
|
||||
{
|
||||
var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
|
||||
var folder = new TestFolder(name);
|
||||
var ui = await UiThread.StartAsync();
|
||||
try
|
||||
{
|
||||
var lines = new LogLines();
|
||||
var data = folder.Combine("dati");
|
||||
List<string> arguments =
|
||||
[
|
||||
"--dati", data, "--libreria", folder.Combine("libreria"),
|
||||
"--sito-di-prova", site.SiteUrl, "--cdn-di-prova", site.CdnUrl, "--prima-sessione", "1",
|
||||
];
|
||||
if (autoLogin)
|
||||
{
|
||||
arguments.Add("--accesso-di-prova");
|
||||
}
|
||||
|
||||
if (!DesktopCommandLine.TryParse([.. arguments], out var options, out var problem))
|
||||
{
|
||||
throw new ArgumentException(problem);
|
||||
}
|
||||
|
||||
var zone = TestZones.Noon();
|
||||
var clock = new CompressedClock(10, zone);
|
||||
var shell = new DesktopShell(ui.Dispatcher, null, BrowserShell.Instance);
|
||||
var platform = new DesktopPlatform(options, shell, new MemoryLocations(), dataFolderFixed: true);
|
||||
var appOptions = options.AppOptions(data, new DesktopFolders(folder.Combine("AppData"), folder.Combine("Immagini"))) with { Zone = zone, ZoneId = zone.Id };
|
||||
var hooks = new FebeAppHooks { Clock = clock, Random = new SeededRandom(20261020), Console = lines, ShutdownTimeout = TimeSpan.FromSeconds(1) };
|
||||
var app = await FebeApp.StartAsync(appOptions, platform, hooks, ct);
|
||||
return new DesktopBed(site, folder, ui, lines, clock, platform, app);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await ui.DisposeAsync();
|
||||
folder.Dispose();
|
||||
await site.DisposeAsync();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A request as the main window sends it; the answer must be 200 with JSON.</summary>
|
||||
public async Task<JsonElement> JsonAsync(HttpMethod method, string path, string? json, CancellationToken ct)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, path);
|
||||
request.Headers.TryAddWithoutValidation(Febe.Web.Security.AccessToken.HeaderName, Platform.AccessToken);
|
||||
request.Headers.TryAddWithoutValidation("Origin", $"{App.Address.Scheme}://{App.Address.Authority}");
|
||||
if (json is not null)
|
||||
{
|
||||
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
}
|
||||
|
||||
using var response = await _client.SendAsync(request, ct);
|
||||
var text = await response.Content.ReadAsStringAsync(ct);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
|
||||
return JsonDocument.Parse(text).RootElement.Clone();
|
||||
}
|
||||
|
||||
/// <summary>Waits (real time) until <paramref name="condition"/> holds; fails with <paramref name="what"/> and the log otherwise.</summary>
|
||||
public async Task WaitUntilAsync(Func<Task<bool>> condition, TimeSpan timeout, string what, CancellationToken ct)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (!await condition())
|
||||
{
|
||||
if (DateTime.UtcNow > deadline)
|
||||
{
|
||||
Assert.Fail($"Tempo scaduto: {what}.\n{Lines.Text}");
|
||||
}
|
||||
|
||||
await Task.Delay(250, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stops the composition (the browser of Febe closes on its UI thread), then the UI thread, folders, site.</summary>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
_client.Dispose();
|
||||
try
|
||||
{
|
||||
await App.DisposeAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
await Ui.DisposeAsync();
|
||||
Folder.Dispose();
|
||||
await Site.DisposeAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>The «console» of <see cref="Febe.App.FebeLog"/> in a test: the lines Alberto would find in his log.</summary>
|
||||
internal sealed class LogLines : TextWriter
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<string> _lines = [];
|
||||
private readonly StringBuilder _current = new();
|
||||
|
||||
public override Encoding Encoding => Encoding.UTF8;
|
||||
|
||||
public IReadOnlyList<string> Lines
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return [.. _lines];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public string Text => string.Join('\n', Lines);
|
||||
|
||||
public bool Any(string fragment) => Lines.Any(l => l.Contains(fragment, StringComparison.Ordinal));
|
||||
|
||||
public override void Write(char value)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (value == '\n')
|
||||
{
|
||||
_lines.Add(_current.ToString().TrimEnd('\r'));
|
||||
_current.Clear();
|
||||
}
|
||||
else
|
||||
{
|
||||
_current.Append(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void WriteLine(string? value)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_current.Append(value);
|
||||
_lines.Add(_current.ToString());
|
||||
_current.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>
|
||||
/// A temporary folder under <see cref="Path.GetTempPath"/> (TEMP: on Alberto's PC a work folder outside drive C:),
|
||||
/// removed at the end of the test. WebView2 may hold a file of its profile for a moment after it closed: removal is
|
||||
/// retried and a leftover folder is not an error.
|
||||
/// </summary>
|
||||
internal sealed class TestFolder : IDisposable
|
||||
{
|
||||
public TestFolder(string prefix)
|
||||
{
|
||||
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "febe-prove-windows", prefix + "-" + Guid.NewGuid().ToString("N")[..10]);
|
||||
Directory.CreateDirectory(Path);
|
||||
}
|
||||
|
||||
public string Path { get; }
|
||||
|
||||
public string Combine(params string[] parts) => System.IO.Path.Combine([Path, .. parts]);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
for (var attempt = 0; attempt < 10; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(Path))
|
||||
{
|
||||
Directory.Delete(Path, recursive: true);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Thread.Sleep(300);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System.Windows.Threading;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>
|
||||
/// A UI thread like the one of Febe.exe: an STA thread running a WPF <see cref="System.Windows.Threading.Dispatcher"/>
|
||||
/// (its message pump and its <see cref="DispatcherSynchronizationContext"/>). The browser of Febe is created on it,
|
||||
/// while the test itself — like the engine of Febe — runs on thread-pool threads.
|
||||
/// </summary>
|
||||
internal sealed class UiThread : IAsyncDisposable
|
||||
{
|
||||
private readonly Thread _thread;
|
||||
|
||||
private UiThread(Thread thread, Dispatcher dispatcher)
|
||||
{
|
||||
_thread = thread;
|
||||
Dispatcher = dispatcher;
|
||||
}
|
||||
|
||||
public Dispatcher Dispatcher { get; }
|
||||
|
||||
/// <summary>The managed id of the UI thread (to tell where code ran).</summary>
|
||||
public int ThreadId => _thread.ManagedThreadId;
|
||||
|
||||
public static async Task<UiThread> StartAsync()
|
||||
{
|
||||
var ready = new TaskCompletionSource<Dispatcher>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
ready.SetResult(Dispatcher.CurrentDispatcher);
|
||||
Dispatcher.Run();
|
||||
})
|
||||
{
|
||||
IsBackground = true,
|
||||
Name = "Febe: thread dell'interfaccia (prove)",
|
||||
};
|
||||
thread.SetApartmentState(ApartmentState.STA);
|
||||
thread.Start();
|
||||
var dispatcher = await ready.Task.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
|
||||
return new UiThread(thread, dispatcher);
|
||||
}
|
||||
|
||||
/// <summary>Runs <paramref name="action"/> on the UI thread and waits for it.</summary>
|
||||
public Task<T> InvokeAsync<T>(Func<T> action) => Dispatcher.InvokeAsync(action).Task;
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (!Dispatcher.HasShutdownStarted)
|
||||
{
|
||||
Dispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
|
||||
}
|
||||
|
||||
await Task.Run(() => _thread.Join(TimeSpan.FromSeconds(15))).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
|
||||
namespace Febe.Tests.Windows.Support;
|
||||
|
||||
/// <summary>Whether these tests can run here: Windows with the WebView2 runtime (the tests are inconclusive otherwise).</summary>
|
||||
internal static class WebView2Runtime
|
||||
{
|
||||
/// <summary>Null when WebView2 can run; otherwise why not, in Italian (the text of the inconclusive result).</summary>
|
||||
public static string? UnavailableReason()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
return "Prova solo per Windows: qui non c'è WebView2.";
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return InstalledVersion() is null ? "Runtime WebView2 non installato su questo Windows." : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is WebView2RuntimeNotFoundException or DllNotFoundException or BadImageFormatException)
|
||||
{
|
||||
return $"Runtime WebView2 non disponibile ({ex.GetType().Name}).";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The version of the installed WebView2 runtime, e.g. «141.0.3537.71».</summary>
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
public static string? InstalledVersion() => CoreWebView2Environment.GetAvailableBrowserVersionString();
|
||||
|
||||
/// <summary>Marks the test inconclusive where WebView2 cannot run.</summary>
|
||||
public static void Require()
|
||||
{
|
||||
if (UnavailableReason() is { } reason)
|
||||
{
|
||||
Assert.Inconclusive(reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Tests.Windows.Support;
|
||||
|
||||
namespace Febe.Tests.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// The start of the browser of Febe on a real Windows (regression of 14 and 19 October 2026: «WebView2 non parte
|
||||
/// (InvalidOperationException: CoreWebView2Environment members can only be accessed from the UI thread.)» at every
|
||||
/// attempt, for ever). The composition starts the browser from a thread-pool thread; every WebView2 object lives on the
|
||||
/// UI thread of WPF.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed partial class WebView2BrowserStartTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestInitialize]
|
||||
public void RequireWebView2() => WebView2Runtime.Require();
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task StartedFromAThreadPoolThreadTheBrowserIsReadyAtTheFirstAttempt()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await BrowserBed.CreateAsync("avvio");
|
||||
|
||||
await bed.StartAsync(ct);
|
||||
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsTrue(bed.Browser.IsAvailable, "the browser is available once RunAsync returned");
|
||||
Assert.IsNull(bed.Browser.LastError);
|
||||
var ready = bed.Lines.Lines.Where(l => l.Contains("Browser di Febe pronto: WebView2 ", StringComparison.Ordinal)).ToList();
|
||||
Assert.HasCount(1, ready, "one «ready» line: " + bed.Lines.Text);
|
||||
Assert.MatchesRegex(ReadyLine(), ready[0]);
|
||||
Assert.IsFalse(bed.Lines.Any("non parte"), "no failed attempt: " + bed.Lines.Text);
|
||||
Assert.IsFalse(bed.Lines.Any("ERRORE"), "no error at all: " + bed.Lines.Text);
|
||||
|
||||
// The version is a plain value now: it can be read from any thread.
|
||||
var version = await Task.Run(() => bed.Browser.Host.Version, ct);
|
||||
Assert.IsNotNull(version);
|
||||
StringAssert.Contains(ready[0], version);
|
||||
|
||||
// The engine's threads use the page through the session: the command hops to the UI thread and back.
|
||||
Assert.AreEqual("about:blank", await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"\[browser\] Browser di Febe pronto: WebView2 \d+\.\d+\.\d+\.\d+, pagina 1280×900, finestra, fuori vista\.$")]
|
||||
private static partial Regex ReadyLine();
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.Browser.Capture;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Download;
|
||||
using Febe.Browser.Gestures;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Browser.RemoteView;
|
||||
using Febe.Browser.WebView2;
|
||||
using Febe.Browser.Recipes;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.SitoDiProva;
|
||||
using Febe.Tests.Windows.Support;
|
||||
|
||||
namespace Febe.Tests.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// S1 on a real Windows (docs/prove-dal-vivo.md, C3): the DevTools protocol of WebView2 through the real
|
||||
/// <see cref="WebView2CdpSession"/> and its allowlist, against the local test site (never Instagram), from thread-pool
|
||||
/// threads as the engine sends it, with the window «Browser di Febe» out of view as it always is.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class WebView2CdpTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestInitialize]
|
||||
public void RequireWebView2() => WebView2Runtime.Require();
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task S1TheProtocolWorksOnTheTestSiteWithTheWindowOutOfView()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
|
||||
await using var bed = await BrowserBed.CreateAsync("s1");
|
||||
await bed.StartAsync(ct);
|
||||
var cdp = bed.Browser.Cdp;
|
||||
Assert.IsInstanceOfType<WebView2CdpSession>(cdp, "the real session of WebView2, with its allowlist");
|
||||
var clock = new SystemClock();
|
||||
var testSite = CollectionSite.TestSite(site.SiteHost, site.CdnHost);
|
||||
|
||||
await Task.Run(
|
||||
async () =>
|
||||
{
|
||||
// Response bodies: Network.enable and the events are subscribed from this thread, the bodies come
|
||||
// through Network.getResponseBody.
|
||||
var bodies = new BodyCollector();
|
||||
await using var tap = new ResponseTap(cdp, testSite.Hosts, clock);
|
||||
tap.AddConsumer(bodies);
|
||||
await tap.StartAsync(ct);
|
||||
|
||||
// Navigation.
|
||||
var navigation = await cdp.NavigateAsync(site.Url("/profilo/luca.prova/"), ct);
|
||||
Assert.IsTrue(navigation.Succeeded, navigation.ErrorText);
|
||||
Assert.IsTrue(await cdp.WaitForLoadAsync(clock, TimeSpan.FromSeconds(20), ct), "the profile page loaded");
|
||||
await WaitUntilAsync(() => bodies.Paths.Contains("/dati/profilo/luca.prova"), TimeSpan.FromSeconds(20), "il corpo JSON del profilo", ct);
|
||||
var profile = bodies.Json("/dati/profilo/luca.prova");
|
||||
Assert.AreEqual("luca.prova", profile.GetProperty("profilo").GetProperty("nome").GetString());
|
||||
Assert.IsTrue(tap.Stats.JsonBodies >= 1);
|
||||
|
||||
// Read-only Runtime.evaluate: what the page sees, out of view (S2: visible, never «hidden»).
|
||||
var seen = await cdp.EvaluateAsync(
|
||||
"({ visibility: document.visibilityState, hidden: document.hidden, webdriver: navigator.webdriver, width: innerWidth, height: innerHeight, path: location.pathname, tiles: document.querySelectorAll('#griglia a').length })",
|
||||
ct);
|
||||
TestContext.WriteLine("La pagina vede: " + seen.GetRawText());
|
||||
Assert.AreEqual("/profilo/luca.prova/", seen.GetProperty("path").GetString());
|
||||
Assert.AreEqual("visible", seen.GetProperty("visibility").GetString(), "out of view the page stays visible (S2)");
|
||||
Assert.IsFalse(seen.GetProperty("hidden").GetBoolean());
|
||||
Assert.IsFalse(seen.GetProperty("webdriver").GetBoolean(), "an ordinary browser: navigator.webdriver is false");
|
||||
Assert.AreEqual(1280, seen.GetProperty("width").GetInt32(), "the page has its fixed width");
|
||||
Assert.IsGreaterThan(0, seen.GetProperty("tiles").GetInt32(), "the page drew the grid from the JSON");
|
||||
|
||||
// The session cookie of the site exists (only its name is looked at).
|
||||
Assert.IsTrue(await SessionCookieProbe.HasSessionCookieAsync(cdp, testSite.SessionCookie, ct));
|
||||
|
||||
// Scrolling with Input.dispatchMouseEvent (mouseWheel), as the recipes do.
|
||||
var height = (await cdp.EvaluateAsync("document.documentElement.scrollHeight", ct)).GetDouble();
|
||||
Assert.IsGreaterThan(seen.GetProperty("height").GetInt32() + 400.0, height, "a page long enough to scroll");
|
||||
Assert.AreEqual(0, (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble());
|
||||
var gestures = new HumanGestures(cdp, clock, new SeededRandom(20261020));
|
||||
await gestures.MoveToAsync(new PagePoint(640, 450), ct);
|
||||
var requested = await gestures.ScrollBurstAsync(ct: ct);
|
||||
await Task.Delay(800, ct);
|
||||
var scrolled = (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble();
|
||||
TestContext.WriteLine($"Scorrimento: chiesti {requested} pixel, pagina scesa di {scrolled}.");
|
||||
Assert.IsGreaterThan(100.0, scrolled, "the wheel really scrolled the page out of view");
|
||||
|
||||
// Page.captureScreenshot: a JPEG of the page, out of view (the preview of Attività).
|
||||
var jpeg = await PagePreview.CaptureAsync(cdp, 60, ct);
|
||||
TestContext.WriteLine($"Fotogramma: {jpeg.Length} byte.");
|
||||
Assert.IsGreaterThan(5_000, jpeg.Length, "a real frame, not an empty one");
|
||||
Assert.AreEqual(0xFF, jpeg[0]);
|
||||
Assert.AreEqual(0xD8, jpeg[1]);
|
||||
|
||||
// A file of the CDN through the browser (Network.loadNetworkResource, IO.read, IO.close).
|
||||
var media = FirstCdnAddress(profile, site.CdnUrl) ?? throw new AssertFailedException("nessun indirizzo del CDN nel JSON del profilo");
|
||||
var fetcher = new BrowserFileFetcher(cdp, testSite.Hosts);
|
||||
using var file = new MemoryStream();
|
||||
var fetched = await fetcher.FetchAsync(new Uri(media), file, null, ct);
|
||||
Assert.AreEqual(FetchOutcome.Completed, fetched.Outcome, fetched.Error);
|
||||
Assert.IsGreaterThan(1_000L, fetched.Bytes);
|
||||
Assert.AreEqual(0xFF, file.GetBuffer()[0], "a JPEG of the CDN");
|
||||
var refused = await fetcher.FetchAsync(new Uri(site.Url("/dati/inizio")), Stream.Null, null, ct);
|
||||
Assert.AreEqual(FetchOutcome.HostNotAllowed, refused.Outcome, "only the CDN is downloaded");
|
||||
|
||||
// Forbidden commands are refused before WebView2, and change nothing.
|
||||
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Emulation.setTimezoneOverride", new JsonObject { ["timezoneId"] = "America/New_York" }, ct));
|
||||
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Network.setUserAgentOverride", new JsonObject { ["userAgent"] = "Febe" }, ct));
|
||||
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Page.addScriptToEvaluateOnNewDocument", new JsonObject { ["source"] = "1" }, ct));
|
||||
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Fetch.enable", null, ct));
|
||||
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Target.createTarget", new JsonObject { ["url"] = "about:blank" }, ct));
|
||||
var before = (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble();
|
||||
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.EvaluateAsync("window.scrollBy(0, 500)", ct));
|
||||
await Task.Delay(300, ct);
|
||||
var after = (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble();
|
||||
Assert.IsLessThan(100.0, Math.Abs(after - before), "the refused script did not run (it would have scrolled 500 px)");
|
||||
var zone = (await cdp.EvaluateAsync("Intl.DateTimeFormat().resolvedOptions().timeZone", ct)).GetString();
|
||||
Assert.AreNotEqual("America/New_York", zone);
|
||||
|
||||
// Back to the rest page.
|
||||
await bed.Browser.RestAsync(ct);
|
||||
await cdp.WaitForLoadAsync(clock, TimeSpan.FromSeconds(10), ct);
|
||||
Assert.AreEqual(CdpPageExtensions.RestUrl, await cdp.GetMainFrameUrlAsync(ct));
|
||||
},
|
||||
ct);
|
||||
|
||||
// The log has actions and outcomes only: no signed address of the CDN, no error.
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsFalse(bed.Lines.Any("firma="), "no signed address in the log");
|
||||
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
|
||||
}
|
||||
|
||||
private static string? FirstCdnAddress(JsonElement element, string cdnUrl)
|
||||
{
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
if (property.Name == "indirizzo" && property.Value.ValueKind == JsonValueKind.String
|
||||
&& property.Value.GetString() is { } address && address.StartsWith(cdnUrl, StringComparison.Ordinal) && address.Contains(".jpg", StringComparison.Ordinal))
|
||||
{
|
||||
return address;
|
||||
}
|
||||
|
||||
if (FirstCdnAddress(property.Value, cdnUrl) is { } found)
|
||||
{
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
case JsonValueKind.Array:
|
||||
foreach (var item in element.EnumerateArray())
|
||||
{
|
||||
if (FirstCdnAddress(item, cdnUrl) is { } found)
|
||||
{
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task WaitUntilAsync(Func<bool> condition, TimeSpan timeout, string what, CancellationToken ct)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (!condition())
|
||||
{
|
||||
if (DateTime.UtcNow > deadline)
|
||||
{
|
||||
Assert.Fail($"Tempo scaduto: {what}.");
|
||||
}
|
||||
|
||||
await Task.Delay(50, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The JSON bodies the page received, by path.</summary>
|
||||
private sealed class BodyCollector : IResponseConsumer
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, string> _bodies = new(StringComparer.Ordinal);
|
||||
|
||||
public ICollection<string> Paths => _bodies.Keys;
|
||||
|
||||
public JsonElement Json(string path) => JsonDocument.Parse(_bodies[path]).RootElement.Clone();
|
||||
|
||||
public ValueTask ConsumeAsync(ResponseDescriptor response, JsonDocument body, CancellationToken ct)
|
||||
{
|
||||
_bodies.TryAdd(response.Path, body.RootElement.GetRawText());
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
using System.Net.Http;
|
||||
using Febe.App;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Desktop.Browser;
|
||||
using Febe.Tests.Windows.Support;
|
||||
|
||||
namespace Febe.Tests.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// One real collection session of the shared composition (<see cref="FebeApp"/>) running on WebView2, as Febe.exe
|
||||
/// composes it, against the local test site, with files arriving in a temporary library. The Linux suite has the
|
||||
/// equivalent with Chromium (ServerEndToEndTests). Never Instagram: the browser only sees 127.0.0.1.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class WebView2CollectionTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestInitialize]
|
||||
public void RequireWebView2() => WebView2Runtime.Require();
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(420_000, CooperativeCancellation = true)]
|
||||
public async Task ARealSessionOfTheCompositionRunsOnWebView2AndTheFilesArriveInTheLibrary()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await DesktopBed.StartAsync("raccolta", autoLogin: true, ct);
|
||||
var app = bed.App;
|
||||
Assert.IsEmpty(app.Problems, string.Join("; ", app.Problems.Select(p => p.Title)));
|
||||
|
||||
// The browser starts from a thread of the composition (the path that failed on Alberto's PC), the pipeline and
|
||||
// the engine follow.
|
||||
await app.Running.WaitAsync(TimeSpan.FromSeconds(120), ct);
|
||||
Assert.IsInstanceOfType<WebView2Browser>(app.Browser);
|
||||
Assert.IsTrue(bed.Lines.Any("Browser di Febe pronto: WebView2 "), bed.Lines.Text);
|
||||
Assert.IsFalse(bed.Lines.Any("non parte"), bed.Lines.Text);
|
||||
Assert.AreEqual(Febe.Web.Connection.ConnectionState.Connected, (await app.Connection!.GetStatusAsync(ct)).State, "the test site's automatic login");
|
||||
|
||||
// Accounts and «Controlla ora» through the interface, as from the main window.
|
||||
var added = await bed.JsonAsync(HttpMethod.Post, "/api/accounts", """{"usernames":["marta.prova","luca.prova"],"start":"everything"}""", ct);
|
||||
Assert.AreEqual(2, added.GetProperty("added").GetInt32());
|
||||
var marta = await app.Database.Accounts.FindByUsernameAsync("marta.prova", ct) ?? throw new AssertFailedException("marta.prova manca");
|
||||
var check = await bed.JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now", null, ct);
|
||||
if (check.GetProperty("status").GetString() == "needsConfirmation")
|
||||
{
|
||||
check = await bed.JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now", $$"""{"token":"{{check.GetProperty("token").GetString()}}"}""", ct);
|
||||
}
|
||||
|
||||
Assert.AreEqual("queued", check.GetProperty("status").GetString(), check.GetProperty("message").GetString());
|
||||
|
||||
// A session of the engine acts on the site through WebView2: every action has its Governor's permit.
|
||||
await bed.WaitUntilAsync(
|
||||
async () => (await app.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, bed.Clock.Now.AddDays(1), ct)).Any(a => a.AccountId == marta.Id),
|
||||
TimeSpan.FromSeconds(120),
|
||||
"un'azione del motore su marta.prova nel registro delle azioni",
|
||||
ct);
|
||||
|
||||
// Files arrive in the library, complete, downloaded through the browser from the test site's CDN.
|
||||
var library = app.Library ?? throw new AssertFailedException("nessuna libreria");
|
||||
List<Media> stored = [];
|
||||
await bed.WaitUntilAsync(
|
||||
async () =>
|
||||
{
|
||||
stored = await StoredAsync(app, marta.Id, ct);
|
||||
return stored.Count >= 3;
|
||||
},
|
||||
TimeSpan.FromSeconds(180),
|
||||
"tre file di marta.prova nella libreria",
|
||||
ct);
|
||||
foreach (var media in stored)
|
||||
{
|
||||
var path = library.FullPath(marta, media.RelativePath!);
|
||||
Assert.IsTrue(File.Exists(path), path);
|
||||
Assert.AreEqual(media.Bytes, new FileInfo(path).Length, path);
|
||||
StringAssert.StartsWith(path, bed.Folder.Path, "inside the temporary library");
|
||||
}
|
||||
|
||||
var actions = await app.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, bed.Clock.Now.AddDays(1), ct);
|
||||
Assert.IsTrue(actions.All(a => a.SessionId is not null), "every counted action belongs to a session");
|
||||
TestContext.WriteLine($"File di marta.prova: {stored.Count}; azioni: {actions.Count}; CDN: {bed.Site.Control.CdnFilesServed} file serviti.");
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsFalse(bed.Lines.Any("non parte"), "the browser never failed to start");
|
||||
Assert.IsFalse(bed.Lines.Any("firma="), "no signed address in the log");
|
||||
}
|
||||
|
||||
private static async Task<List<Media>> StoredAsync(FebeApp app, long accountId, CancellationToken ct)
|
||||
{
|
||||
var list = new List<Media>();
|
||||
foreach (var entry in await app.Database.Entries.ListByAccountAsync(accountId, null, ct))
|
||||
{
|
||||
foreach (var media in await app.Database.Media.ListByEntryAsync(entry.Id, ct))
|
||||
{
|
||||
if (media.State == MediaState.Downloaded && media.RelativePath is not null && media.Sha256 is not null && entry.Kind != EntryKind.ProfilePicture)
|
||||
{
|
||||
list.Add(media);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Tests.Windows.Support;
|
||||
using Febe.Web.Connection;
|
||||
|
||||
namespace Febe.Tests.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// The login on Windows through the real connection service of the composition (spec §4.1, docs/windows.md «Il primo
|
||||
/// collegamento a Instagram»), on WebView2 and the test site: «Accedi a Instagram» opens the login page in the window
|
||||
/// «Browser di Febe», which comes on screen while the engine is still; «Ho finito» checks the session (the cookie's name
|
||||
/// only) and puts the window back out of view; «Scollega» deletes the profile with the session and the browser comes
|
||||
/// back empty. The window comes on screen for a moment, as for Alberto.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class WebView2ConnectionTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestInitialize]
|
||||
public void RequireWebView2() => WebView2Runtime.Require();
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(240_000, CooperativeCancellation = true)]
|
||||
public async Task TheLoginBringsTheWindowAndScollegaEmptiesTheProfile()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await DesktopBed.StartAsync("collegamento", autoLogin: false, ct);
|
||||
var app = bed.App;
|
||||
await app.Running.WaitAsync(TimeSpan.FromSeconds(120), ct);
|
||||
var connection = app.Connection!;
|
||||
var browser = bed.Browser;
|
||||
Assert.AreEqual(ConnectionState.NotConnected, (await connection.GetStatusAsync(ct)).State, "a new profile is not connected");
|
||||
var window = await bed.Ui.InvokeAsync(() => browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
|
||||
Assert.IsFalse(await bed.Ui.InvokeAsync(() => window.IsOnScreen));
|
||||
|
||||
// «Accedi a Instagram» (here the test site's welcome page, whose first visit starts its session).
|
||||
await connection.BeginUserDrivingAsync(openLogin: true, ct);
|
||||
var driving = await connection.GetStatusAsync(ct);
|
||||
Assert.IsTrue(driving.UserIsDriving);
|
||||
Assert.IsTrue(browser.UserIsDriving, "the engine is still while Alberto is at the browser");
|
||||
Assert.IsTrue(await bed.Ui.InvokeAsync(() => window.IsOnScreen), "the window «Browser di Febe» came on screen");
|
||||
StringAssert.StartsWith(driving.CurrentUrl, bed.Site.SiteUrl, "the login page of the configured site, never Instagram in tests");
|
||||
|
||||
// «Ho finito».
|
||||
var finish = await connection.FinishAsync(ct);
|
||||
Assert.IsTrue(finish.Connected, finish.Message);
|
||||
Assert.IsFalse(browser.UserIsDriving, "«Ho finito» ends the driving");
|
||||
Assert.IsFalse(await bed.Ui.InvokeAsync(() => window.IsOnScreen), "and puts the window back out of view");
|
||||
Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State);
|
||||
Assert.IsNotNull(await app.Database.Settings.GetInt64Async(Febe.App.BrowserConnectionService.FirstConnectionKey, ct), "first connection recorded");
|
||||
|
||||
// «Scollega»: engine stopped, WebView2 closed, profile deleted, browser started again empty, engine started again.
|
||||
var marker = Path.Combine(browser.ProfileDirectory, "segno-della-prova");
|
||||
await File.WriteAllTextAsync(marker, "x", ct);
|
||||
await connection.DisconnectAsync(ct);
|
||||
Assert.IsFalse(File.Exists(marker), "the profile folder was deleted");
|
||||
Assert.IsTrue(browser.IsAvailable, "the browser runs again, with an empty profile");
|
||||
Assert.AreEqual(ConnectionState.NotConnected, (await connection.GetStatusAsync(ct)).State);
|
||||
Assert.IsFalse(browser.UserIsDriving);
|
||||
await bed.WaitUntilAsync(() => Task.FromResult(app.Engine!.Services.Runtime.IsRunning), TimeSpan.FromSeconds(10), "il motore di nuovo in funzione", ct);
|
||||
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsTrue(bed.Lines.Any("«Scollega»: motore fermo, profilo del browser cancellato, browser ripartito vuoto."), bed.Lines.Text);
|
||||
Assert.IsFalse(bed.Lines.Any("non parte"), bed.Lines.Text);
|
||||
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
using System.Diagnostics;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Browser.Recipes;
|
||||
using Febe.Browser.RemoteView;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Desktop.Core;
|
||||
using Febe.SitoDiProva;
|
||||
using Febe.Tests.Windows.Support;
|
||||
|
||||
namespace Febe.Tests.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// The life of the browser of Febe on a real Windows, driven from thread-pool threads as the composition and the
|
||||
/// connection service drive it: a start that really fails is retried (and only that), the window comes on screen and
|
||||
/// goes away with the «driving» lease (the login), «Scollega» empties the profile and the browser comes back, a browser
|
||||
/// process that dies is started again, and the second hosting of S2 (composition) starts and draws.
|
||||
/// </summary>
|
||||
/// <remarks>Two tests bring the window «Browser di Febe» on screen for a moment, as «Accedi a Instagram» does.</remarks>
|
||||
[TestClass]
|
||||
public sealed class WebView2LifecycleTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestInitialize]
|
||||
public void RequireWebView2() => WebView2Runtime.Require();
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task AStartThatReallyFailsIsRetriedAndThenTheBrowserIsReady()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await BrowserBed.CreateAsync("tentativi");
|
||||
|
||||
// A file where the profile folder must go: WebView2 cannot start.
|
||||
var profile = bed.Browser.ProfileDirectory;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(profile)!);
|
||||
await File.WriteAllTextAsync(profile, "occupa il posto della cartella del profilo", ct);
|
||||
|
||||
var run = Task.Run(() => bed.Browser.RunAsync(ct), ct);
|
||||
await bed.WaitUntilAsync(() => bed.Lines.Any("non parte"), TimeSpan.FromSeconds(30), "il primo avvio non riuscito", ct);
|
||||
Assert.IsFalse(bed.Browser.IsAvailable);
|
||||
StringAssert.StartsWith(bed.Browser.LastError, "WebView2 non parte (IOException:");
|
||||
StringAssert.EndsWith(bed.Lines.Lines.Single(l => l.Contains("non parte", StringComparison.Ordinal)), "Nuovo tentativo fra 5 s.");
|
||||
|
||||
// The obstacle goes away: the next attempt, 5 s later, works.
|
||||
File.Delete(profile);
|
||||
await run.WaitAsync(TimeSpan.FromSeconds(60), ct);
|
||||
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsTrue(bed.Browser.IsAvailable);
|
||||
Assert.IsNull(bed.Browser.LastError);
|
||||
Assert.HasCount(1, bed.Lines.Lines.Where(l => l.Contains("non parte", StringComparison.Ordinal)), "one failed attempt only");
|
||||
Assert.HasCount(1, bed.Lines.Lines.Where(l => l.Contains("Browser di Febe pronto: WebView2 ", StringComparison.Ordinal)));
|
||||
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task TheWindowComesOnScreenWithTheLeaseAndGoesAwayWithIt()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await BrowserBed.CreateAsync("finestra");
|
||||
await bed.StartAsync(ct);
|
||||
var window = await bed.OnUiAsync(() => bed.Browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
|
||||
Assert.IsTrue(await bed.OnUiAsync(() => window.IsVisible), "the window is open");
|
||||
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen), "after the start it is parked out of view");
|
||||
Assert.IsFalse(bed.Browser.UserIsDriving);
|
||||
|
||||
// «Accedi a Instagram» / «Portalo in primo piano», from the connection service's thread.
|
||||
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
|
||||
Assert.IsTrue(await bed.OnUiAsync(() => window.IsOnScreen), "the window came on screen");
|
||||
Assert.IsTrue(bed.Browser.UserIsDriving, "while it is in front the engine is still");
|
||||
Assert.IsNotNull(bed.Tracker.LastUsedAt, "using it counts for «Riprendi»");
|
||||
|
||||
// «Ho finito».
|
||||
await Task.Run(() => bed.Browser.HideFromUserAsync(ct), ct);
|
||||
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen));
|
||||
Assert.IsFalse(bed.Browser.UserIsDriving);
|
||||
|
||||
// Closing the window is «ho finito» too: out of view, still open, still painting.
|
||||
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
|
||||
Assert.IsTrue(bed.Browser.UserIsDriving);
|
||||
await bed.OnUiAsync(() =>
|
||||
{
|
||||
window.Close();
|
||||
return true;
|
||||
});
|
||||
Assert.IsFalse(bed.Browser.UserIsDriving);
|
||||
Assert.IsTrue(await bed.OnUiAsync(() => window.IsVisible), "closing it never closes it");
|
||||
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen));
|
||||
var jpeg = await Task.Run(() => PagePreview.CaptureAsync(bed.Browser.Cdp, 50, ct), ct);
|
||||
Assert.AreEqual(0xFF, jpeg[0], "the page still draws out of view");
|
||||
Assert.IsTrue(bed.Browser.IsAvailable);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task ScollegaDeletesTheProfileWithTheSessionAndTheBrowserComesBackEmpty()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
|
||||
await using var bed = await BrowserBed.CreateAsync("scollega");
|
||||
await bed.StartAsync(ct);
|
||||
var cdp = bed.Browser.Cdp;
|
||||
var cookie = CollectionSite.TestSite(site.SiteHost, site.CdnHost).SessionCookie;
|
||||
var clock = new SystemClock();
|
||||
|
||||
// «Collegato»: the site's session cookie is in the profile.
|
||||
await Task.Run(
|
||||
async () =>
|
||||
{
|
||||
await cdp.NavigateAsync(site.Url("/"), ct);
|
||||
await cdp.WaitForLoadAsync(clock, TimeSpan.FromSeconds(15), ct);
|
||||
},
|
||||
ct);
|
||||
Assert.IsTrue(await Task.Run(() => SessionCookieProbe.HasSessionCookieAsync(cdp, cookie, ct), ct), "connected to the test site");
|
||||
var marker = Path.Combine(bed.Browser.ProfileDirectory, "segno-della-prova");
|
||||
await File.WriteAllTextAsync(marker, "x", ct);
|
||||
var before = bed.Browser.Host.BrowserProcessId;
|
||||
|
||||
// «Scollega», from the connection service's thread.
|
||||
await Task.Run(() => bed.Browser.RestartWithEmptyProfileAsync(ct), ct);
|
||||
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsFalse(File.Exists(marker), "the profile folder was deleted");
|
||||
Assert.IsTrue(bed.Browser.IsAvailable, "the browser runs again");
|
||||
Assert.AreNotEqual(before, bed.Browser.Host.BrowserProcessId, "with a new browser process");
|
||||
Assert.IsFalse(await Task.Run(() => SessionCookieProbe.HasSessionCookieAsync(cdp, cookie, ct), ct), "the session went with the profile");
|
||||
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => cdp.GetMainFrameUrlAsync(ct), ct));
|
||||
Assert.IsTrue(bed.Lines.Any("Profilo del browser cancellato; il browser è ripartito vuoto."));
|
||||
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Regression (review of 20 October 2026): «Scollega» while the first start waits for its next attempt started the
|
||||
/// browser, then the waiting attempt started a second WebView in the same window without closing the first. The
|
||||
/// orphan kept its browser process alive on the profile: the next «Scollega» waited 15 s for nothing and could not
|
||||
/// delete the profile (the Instagram session stayed on disk), and exiting waited 15 s more.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task ScollegaWhileTheFirstStartWaitsToRetryLeavesOneWebViewAndTheNextScollegaWorks()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await BrowserBed.CreateAsync("scollega-nei-tentativi");
|
||||
|
||||
// A file where the profile folder must go: the first start fails, and fails again 5 s later.
|
||||
var profile = bed.Browser.ProfileDirectory;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(profile)!);
|
||||
await File.WriteAllTextAsync(profile, "occupa il posto della cartella del profilo", ct);
|
||||
var run = Task.Run(() => bed.Browser.RunAsync(ct), ct);
|
||||
await bed.WaitUntilAsync(() => bed.Lines.Any("Nuovo tentativo fra 15 s."), TimeSpan.FromSeconds(40), "il secondo avvio non riuscito", ct);
|
||||
File.Delete(profile);
|
||||
|
||||
// «Scollega» while RunAsync waits 15 s for its third attempt: the browser starts with it.
|
||||
await Task.Run(() => bed.Browser.RestartWithEmptyProfileAsync(ct), ct);
|
||||
Assert.IsTrue(bed.Browser.IsAvailable, bed.Lines.Text);
|
||||
var pid = bed.Browser.Host.BrowserProcessId;
|
||||
|
||||
// The waiting attempt finds the browser running: no second WebView, the one of «Scollega» untouched.
|
||||
await run.WaitAsync(TimeSpan.FromSeconds(40), ct);
|
||||
var children = await bed.ChildWindowsAsync();
|
||||
Assert.HasCount(1, children, "one WebView in the window: " + string.Join(", ", children));
|
||||
Assert.AreEqual(pid, bed.Browser.Host.BrowserProcessId, "the browser process of «Scollega» is still the one in use");
|
||||
Assert.IsTrue(bed.Lines.Any("Browser di Febe pronto: WebView2 "), bed.Lines.Text);
|
||||
Assert.IsTrue(bed.Browser.IsAvailable);
|
||||
|
||||
// The next «Scollega»: the only browser process exits at once, the profile goes, the browser comes back.
|
||||
var marker = Path.Combine(profile, "segno-della-prova");
|
||||
await File.WriteAllTextAsync(marker, "x", ct);
|
||||
var watch = Stopwatch.StartNew();
|
||||
await Task.Run(() => bed.Browser.RestartWithEmptyProfileAsync(ct), ct);
|
||||
TestContext.WriteLine($"Secondo «Scollega»: {watch.Elapsed.TotalSeconds:0.0} s.");
|
||||
Assert.IsLessThan(10, watch.Elapsed.TotalSeconds, "no wait for a browser process that never exits");
|
||||
Assert.IsFalse(File.Exists(marker), "the profile with the session was deleted");
|
||||
Assert.HasCount(1, await bed.ChildWindowsAsync());
|
||||
Assert.IsTrue(bed.Browser.IsAvailable);
|
||||
|
||||
// Exiting closes the only WebView and its process exits: no wait in vain.
|
||||
watch.Restart();
|
||||
await bed.Browser.DisposeAsync();
|
||||
TestContext.WriteLine($"Arresto: {watch.Elapsed.TotalSeconds:0.0} s.");
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsLessThan(10, watch.Elapsed.TotalSeconds, "exiting waits for nothing");
|
||||
Assert.HasCount(2, bed.Lines.Lines.Where(l => l.Contains("ERRORE", StringComparison.Ordinal)), "only the two failed starts: " + bed.Lines.Text);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Esci» while the start does not complete (review of 20 October 2026): the composition awaits
|
||||
/// <see cref="Febe.Desktop.Browser.WebView2Browser.RunAsync"/> before it closes the browser, so RunAsync must stop
|
||||
/// waiting as soon as it is cancelled. Here the UI thread is kept busy, as when WebView2 does not answer.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task OnExitTheStartStopsWaitingForAUiThreadThatDoesNotAnswer()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await BrowserBed.CreateAsync("uscita");
|
||||
var released = false;
|
||||
var busy = bed.Ui.Dispatcher.InvokeAsync(() =>
|
||||
{
|
||||
// Thread.Sleep does not pump: nothing else runs on the UI thread meanwhile.
|
||||
var until = DateTime.UtcNow.AddSeconds(60);
|
||||
while (!Volatile.Read(ref released) && DateTime.UtcNow < until)
|
||||
{
|
||||
Thread.Sleep(20);
|
||||
}
|
||||
});
|
||||
|
||||
using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
var run = Task.Run(() => bed.Browser.RunAsync(lifetime.Token), ct);
|
||||
await Task.Delay(500, ct);
|
||||
Assert.IsFalse(run.IsCompleted, "the start waits for the UI thread");
|
||||
|
||||
// «Esci»: FebeApp cancels its lifetime, then waits for RunAsync.
|
||||
var watch = Stopwatch.StartNew();
|
||||
await lifetime.CancelAsync();
|
||||
try
|
||||
{
|
||||
await run.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Volatile.Write(ref released, true);
|
||||
await busy.Task;
|
||||
}
|
||||
|
||||
TestContext.WriteLine($"RunAsync è tornato {watch.Elapsed.TotalSeconds:0.0} s dopo la cancellazione.");
|
||||
Assert.IsLessThan(3, watch.Elapsed.TotalSeconds, "RunAsync stops waiting at once");
|
||||
Assert.IsFalse(bed.Browser.IsAvailable);
|
||||
|
||||
// The start that was waiting for the UI thread does not begin after the exit, and stopping is quick.
|
||||
watch.Restart();
|
||||
await bed.Browser.DisposeAsync();
|
||||
Assert.IsLessThan(10, watch.Elapsed.TotalSeconds);
|
||||
Assert.IsNull(await bed.OnUiAsync(() => bed.Browser.Host.Window), "no window was created after the exit");
|
||||
Assert.AreEqual(0, bed.Browser.Host.BrowserProcessId, "no browser process was started after the exit");
|
||||
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
|
||||
Assert.IsFalse(bed.Lines.Any("Browser di Febe pronto"), bed.Lines.Text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task WhenItsBrowserProcessDiesTheBrowserStartsAgainByItself()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await BrowserBed.CreateAsync("arresto");
|
||||
await bed.StartAsync(ct);
|
||||
var reconnected = 0;
|
||||
bed.Browser.Host.Connection.Reconnected += (_, _) => Interlocked.Increment(ref reconnected);
|
||||
|
||||
// The browser process this test started — by its id, never by name.
|
||||
var pid = bed.Browser.Host.BrowserProcessId;
|
||||
Assert.AreNotEqual(0, pid);
|
||||
using (var process = Process.GetProcessById(pid))
|
||||
{
|
||||
Assert.AreEqual("msedgewebview2", process.ProcessName, "the browser process of WebView2");
|
||||
process.Kill();
|
||||
}
|
||||
|
||||
await bed.WaitUntilAsync(() => bed.Lines.Any("Browser di Febe ripartito: WebView2 "), TimeSpan.FromSeconds(90), "la ripartenza del browser", ct);
|
||||
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsTrue(bed.Lines.Any("WebView2: processo terminato (BrowserProcessExited)."));
|
||||
Assert.IsTrue(bed.Browser.IsAvailable);
|
||||
Assert.AreNotEqual(pid, bed.Browser.Host.BrowserProcessId, "a new browser process");
|
||||
Assert.AreEqual(1, Volatile.Read(ref reconnected), "the subscriptions of the session moved to the new WebView once");
|
||||
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
|
||||
Assert.IsFalse(bed.Lines.Any("non parte"), "the new start worked at once");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task TheCompositionHostingOfS2StartsAndDrawsThePage()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
|
||||
await using var bed = await BrowserBed.CreateAsync("composizione", BrowserHosting.Composition);
|
||||
await bed.StartAsync(ct);
|
||||
Assert.IsTrue(bed.Lines.Any(", composizione, fuori vista."), bed.Lines.Text);
|
||||
var cdp = bed.Browser.Cdp;
|
||||
var clock = new SystemClock();
|
||||
|
||||
var seen = await Task.Run(
|
||||
async () =>
|
||||
{
|
||||
await cdp.NavigateAsync(site.Url("/profilo/marta.prova/"), ct);
|
||||
await cdp.WaitForLoadAsync(clock, TimeSpan.FromSeconds(15), ct);
|
||||
return await cdp.EvaluateAsync("({ visibility: document.visibilityState, width: innerWidth, height: innerHeight })", ct);
|
||||
},
|
||||
ct);
|
||||
TestContext.WriteLine("La pagina vede: " + seen.GetRawText());
|
||||
Assert.AreEqual("visible", seen.GetProperty("visibility").GetString());
|
||||
Assert.AreEqual(1280, seen.GetProperty("width").GetInt32());
|
||||
var jpeg = await Task.Run(() => PagePreview.CaptureAsync(cdp, 60, ct), ct);
|
||||
Assert.IsGreaterThan(5_000, jpeg.Length, "a real frame");
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ using Febe.Browser.Download;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Browser.RemoteView;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
|
||||
namespace Febe.Tests.Browser;
|
||||
@@ -59,6 +61,174 @@ public sealed class CaptureUnitTests
|
||||
Assert.AreEqual(2, cdp.Sent.Count(c => c.Method == "Network.getResponseBody"), "Only JSON bodies are fetched.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task JavaScriptAnswersOfThePageAreDataButScriptFilesAreNot()
|
||||
{
|
||||
// Instagram serves its GraphQL data as «text/javascript» (HAR of 21/10/2026).
|
||||
var clock = new VirtualClock();
|
||||
var cdp = new FakeCdpSession(clock);
|
||||
cdp.Responder = (method, p) => method switch
|
||||
{
|
||||
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } },
|
||||
"Network.getResponseBody" when p!["requestId"]!.GetValue<string>() == "g1" => new JsonObject { ["body"] = """{"data":{"x":[1]}}""", ["base64Encoded"] = false },
|
||||
"Network.getResponseBody" when p!["requestId"]!.GetValue<string>() == "a1" => new JsonObject { ["body"] = """for (;;);{"payload":{}}""", ["base64Encoded"] = false },
|
||||
"Network.getResponseBody" => new JsonObject { ["body"] = "var x = 1;", ["base64Encoded"] = false },
|
||||
_ => null,
|
||||
};
|
||||
var consumer = new CollectingConsumer();
|
||||
var observer = new CollectingObserver();
|
||||
await using var tap = new ResponseTap(cdp, Hosts, clock);
|
||||
tap.AddConsumer(consumer);
|
||||
tap.AddObserver(observer);
|
||||
await tap.StartAsync();
|
||||
|
||||
cdp.Raise("Network.responseReceived", Received("g1", "http://127.0.0.1:5000/graphql/query", 200, "text/javascript; charset=utf-8", "XHR"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "g1", ["encodedDataLength"] = 20 });
|
||||
cdp.Raise("Network.responseReceived", Received("s1", "http://127.0.0.1:5001/bundle.js", 200, "text/javascript", "Script"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "s1", ["encodedDataLength"] = 10 });
|
||||
cdp.Raise("Network.responseReceived", Received("a1", "http://127.0.0.1:5000/ajax/navigation/", 200, "text/javascript", "XHR"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "a1", ["encodedDataLength"] = 24 });
|
||||
|
||||
await WaitUntilAsync(() => consumer.Items.Count == 1 && observer.Dropped.Contains("a1"));
|
||||
Assert.AreEqual("""{"data":{"x":[1]}}""", consumer.Items.Single().Json);
|
||||
Assert.AreEqual("XHR", consumer.Items.Single().Descriptor.ResourceType);
|
||||
Assert.IsFalse(cdp.Sent.Any(c => c.Method == "Network.getResponseBody" && c.Parameters?["requestId"]?.GetValue<string>() == "s1"), "A script file is never fetched.");
|
||||
Assert.AreEqual(1, tap.Stats.ParseErrors, "«for (;;);» is not JSON: skipped, and its waiters are told.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task EveryJsonBlockOfThePageDocumentIsAnAnswerOfItsOwn()
|
||||
{
|
||||
var clock = new VirtualClock();
|
||||
var cdp = new FakeCdpSession(clock);
|
||||
var tooDeep = new string('[', 300) + new string(']', 300);
|
||||
var html = $$"""
|
||||
<html><head><script type="application/json" data-sjs>{"a":1}</script><script>var b = 2;</script>
|
||||
<script type="application/json">{ non è json </script><script type="application/json">{{tooDeep}}</script>
|
||||
<script type="application/json"> </script></head>
|
||||
<body><script type="application/json">{"c":[3]}</script></body></html>
|
||||
""";
|
||||
cdp.Responder = (method, p) => method switch
|
||||
{
|
||||
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } },
|
||||
"Network.getResponseBody" when p!["requestId"]!.GetValue<string>() == "L7" => new JsonObject { ["body"] = html, ["base64Encoded"] = false },
|
||||
"Network.getResponseBody" when p!["requestId"]!.GetValue<string>() == "r10" => new JsonObject { ["body"] = """{"d":4}""", ["base64Encoded"] = false },
|
||||
"Network.getResponseBody" => new JsonObject { ["body"] = "<html><body>niente</body></html>", ["base64Encoded"] = false },
|
||||
_ => null,
|
||||
};
|
||||
var failing = new FailingConsumer();
|
||||
var consumer = new CollectingConsumer();
|
||||
var observer = new CollectingObserver();
|
||||
await using var tap = new ResponseTap(cdp, Hosts, clock);
|
||||
tap.AddConsumer(failing);
|
||||
tap.AddConsumer(consumer);
|
||||
tap.AddObserver(observer);
|
||||
await tap.StartAsync();
|
||||
|
||||
// The frame commits the new document before its body has finished loading: the body is still read.
|
||||
cdp.Raise("Network.responseReceived", Document("L7", "http://127.0.0.1:5000/marta.prova/"));
|
||||
cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["loaderId"] = "L7", ["url"] = "http://127.0.0.1:5000/marta.prova/" } });
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "L7", ["encodedDataLength"] = html.Length });
|
||||
|
||||
// A document without embedded JSON gives nothing; one of another host is not even fetched. A data answer after
|
||||
// them: the worker reads in order, so once it has arrived the documents have been dealt with.
|
||||
cdp.Raise("Network.responseReceived", Document("L8", "http://127.0.0.1:5000/vuota/"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "L8", ["encodedDataLength"] = 30 });
|
||||
cdp.Raise("Network.responseReceived", Document("L9", "https://esterno.example/"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "L9", ["encodedDataLength"] = 30 });
|
||||
cdp.Raise("Network.responseReceived", Received("r10", "http://127.0.0.1:5000/api/dopo", 200, "application/json"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "r10", ["encodedDataLength"] = 7 });
|
||||
await WaitUntilAsync(() => consumer.Items.Any(i => i.Descriptor.RequestId == "r10"));
|
||||
|
||||
// One answer per valid block, in the order of the document, each with the document's descriptor: a block that
|
||||
// is not JSON, is too deep or is blank is left out without being a parse error.
|
||||
var blocks = consumer.Items.Where(i => i.Descriptor.RequestId == "L7").ToList();
|
||||
CollectionAssert.AreEqual(new[] { """{"a":1}""", """{"c":[3]}""" }, blocks.Select(b => b.Json).ToArray());
|
||||
Assert.IsTrue(blocks.All(b => b.Descriptor.IsMainFrameDocument && b.Descriptor.MimeType == "text/html" && b.Descriptor.Path == "/marta.prova/"));
|
||||
Assert.AreEqual(0, tap.Stats.ParseErrors);
|
||||
Assert.AreEqual(3, tap.Stats.JsonBodies, "Two blocks and the answer after them.");
|
||||
|
||||
// A reader that fails on a block stops neither the other readers, nor the next block, nor the next answer.
|
||||
Assert.AreEqual(3, failing.Calls);
|
||||
|
||||
// Those who wait for a body are told once when nothing reached the readers, never when blocks did.
|
||||
Assert.IsFalse(observer.Dropped.Contains("L7"));
|
||||
Assert.AreEqual(1, observer.Dropped.Count(id => id == "L8"));
|
||||
Assert.IsFalse(cdp.Sent.Any(c => c.Method == "Network.getResponseBody" && c.Parameters?["requestId"]?.GetValue<string>() == "L9"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ThePaginationOfAnEmbeddedBlockStaysWithTheBlockThatCarriesIt()
|
||||
{
|
||||
// Two real answers (cleaned samples of the HAR of 21/10/2026) embedded in one page document: first the
|
||||
// collections, which say «has_next_page: true» of themselves, then a post, which says «more_available: false»
|
||||
// of itself. Read as one answer, the post took the first pagination of the document, the collections'.
|
||||
var clock = new VirtualClock();
|
||||
var cdp = new FakeCdpSession(clock);
|
||||
var html = $"""
|
||||
<!DOCTYPE html><html><head><script type="application/json">{SampleBody("raccolta-in-evidenza")}</script></head>
|
||||
<body><script type="application/json">{SampleBody("post-video")}</script></body></html>
|
||||
""";
|
||||
cdp.Responder = (method, p) => method switch
|
||||
{
|
||||
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } },
|
||||
"Network.getResponseBody" when p!["requestId"]!.GetValue<string>() == "L7" => new JsonObject { ["body"] = Convert.ToBase64String(Encoding.UTF8.GetBytes(html)), ["base64Encoded"] = true },
|
||||
"Network.getResponseBody" => new JsonObject { ["body"] = """{"segni":[1]}""", ["base64Encoded"] = false },
|
||||
_ => null,
|
||||
};
|
||||
var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadInstagram()), clock);
|
||||
var after = new CollectingConsumer();
|
||||
await using var tap = new ResponseTap(cdp, Hosts, clock);
|
||||
tap.AddConsumer(capture);
|
||||
tap.AddObserver(capture);
|
||||
tap.AddConsumer(after);
|
||||
await tap.StartAsync();
|
||||
|
||||
cdp.Raise("Network.responseReceived", Document("L7", "http://127.0.0.1:5000/marta.prova/"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "L7", ["encodedDataLength"] = html.Length });
|
||||
cdp.Raise("Network.responseReceived", Received("r2", "http://127.0.0.1:5000/api/dopo", 200, "application/json"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "r2", ["encodedDataLength"] = 7 });
|
||||
await WaitUntilAsync(() => after.Items.Any(i => i.Descriptor.RequestId == "r2"));
|
||||
|
||||
var reads = capture.Since(0);
|
||||
Assert.AreEqual(2, reads.Count, "One read per block (the answer after them is not about contents).");
|
||||
Assert.IsTrue(reads.All(r => r.Response.RequestId == "L7" && r.Response.IsMainFrameDocument));
|
||||
var collections = reads[0].Result;
|
||||
Assert.AreEqual(2, collections.Highlights.Count);
|
||||
Assert.AreEqual(true, collections.Page?.HasMore);
|
||||
Assert.IsFalse(string.IsNullOrEmpty(collections.Page?.Cursor));
|
||||
var post = reads[1].Result;
|
||||
Assert.AreEqual(0, post.Highlights.Count);
|
||||
Assert.AreEqual(1, post.Contents.Count);
|
||||
Assert.AreEqual(false, post.Page?.HasMore, "The post's own pagination, not the collections'.");
|
||||
Assert.IsNull(post.Page?.Cursor);
|
||||
Assert.AreEqual(0, capture.Pending, "Nothing is left on its way.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task BodiesThatWillNotComeAreReportedToObservers()
|
||||
{
|
||||
var clock = new VirtualClock();
|
||||
var cdp = new FakeCdpSession(clock);
|
||||
cdp.Responder = (method, _) => method == "Page.getFrameTree"
|
||||
? new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } }
|
||||
: null;
|
||||
var observer = new CollectingObserver();
|
||||
await using var tap = new ResponseTap(cdp, Hosts, clock, options: new ResponseTapOptions { MaxBodyBytes = 100 });
|
||||
tap.AddConsumer(new CollectingConsumer());
|
||||
tap.AddObserver(observer);
|
||||
await tap.StartAsync();
|
||||
|
||||
cdp.Raise("Network.responseReceived", Received("big", "http://127.0.0.1:5000/a", 200, "application/json"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "big", ["encodedDataLength"] = 1000 });
|
||||
cdp.Raise("Network.responseReceived", Received("fail", "http://127.0.0.1:5000/b", 200, "application/json"));
|
||||
cdp.Raise("Network.loadingFailed", new JsonObject { ["requestId"] = "fail" });
|
||||
cdp.Raise("Network.responseReceived", Received("old", "http://127.0.0.1:5000/c", 200, "application/json"));
|
||||
cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["loaderId"] = "L2", ["url"] = "http://127.0.0.1:5000/altra/" } });
|
||||
|
||||
CollectionAssert.AreEquivalent(new[] { "big", "fail", "old" }, observer.Dropped.ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task MainFrameNavigationsAreReported()
|
||||
{
|
||||
@@ -229,15 +399,25 @@ public sealed class CaptureUnitTests
|
||||
Assert.IsFalse(gate.IsDriving);
|
||||
}
|
||||
|
||||
private static JsonObject Received(string id, string url, int status, string mime) => new()
|
||||
private static JsonObject Received(string id, string url, int status, string mime, string type = "Fetch") => new()
|
||||
{
|
||||
["requestId"] = id,
|
||||
["loaderId"] = "L1",
|
||||
["frameId"] = "F1",
|
||||
["type"] = "Fetch",
|
||||
["type"] = type,
|
||||
["response"] = new JsonObject { ["url"] = url, ["status"] = status, ["mimeType"] = mime },
|
||||
};
|
||||
|
||||
/// <summary>The response of a main-frame navigation: its request id is the loader id.</summary>
|
||||
private static JsonObject Document(string loader, string url) => new()
|
||||
{
|
||||
["requestId"] = loader,
|
||||
["loaderId"] = loader,
|
||||
["frameId"] = "F1",
|
||||
["type"] = "Document",
|
||||
["response"] = new JsonObject { ["url"] = url, ["status"] = 200, ["mimeType"] = "text/html; charset=utf-8" },
|
||||
};
|
||||
|
||||
private static async Task WaitUntilAsync(Func<bool> condition)
|
||||
{
|
||||
for (var i = 0; i < 300 && !condition(); i++)
|
||||
@@ -248,17 +428,39 @@ public sealed class CaptureUnitTests
|
||||
Assert.IsTrue(condition(), "Condition not reached in time.");
|
||||
}
|
||||
|
||||
/// <summary>The body of a cleaned Instagram sample (<c>tests/campioni/instagram</c>), as JSON text.</summary>
|
||||
private static string SampleBody(string name)
|
||||
{
|
||||
var file = Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram"), $"*-{name}.json").Single();
|
||||
using var sample = JsonDocument.Parse(File.ReadAllText(file));
|
||||
return sample.RootElement.GetProperty("corpo").GetRawText();
|
||||
}
|
||||
|
||||
private sealed class CollectingConsumer : IResponseConsumer
|
||||
{
|
||||
public ConcurrentBag<(ResponseDescriptor Descriptor, string Json)> Items { get; } = [];
|
||||
/// <summary>In arrival order.</summary>
|
||||
public ConcurrentQueue<(ResponseDescriptor Descriptor, string Json)> Items { get; } = new();
|
||||
|
||||
public ValueTask ConsumeAsync(ResponseDescriptor response, JsonDocument body, CancellationToken ct)
|
||||
{
|
||||
Items.Add((response, body.RootElement.GetRawText()));
|
||||
Items.Enqueue((response, body.RootElement.GetRawText()));
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FailingConsumer : IResponseConsumer
|
||||
{
|
||||
private int _calls;
|
||||
|
||||
public int Calls => Volatile.Read(ref _calls);
|
||||
|
||||
public ValueTask ConsumeAsync(ResponseDescriptor response, JsonDocument body, CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref _calls);
|
||||
throw new InvalidOperationException("Lettore di prova che fallisce sempre.");
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class CollectingObserver : IResponseObserver
|
||||
{
|
||||
public ConcurrentQueue<ResponseDescriptor> Responses { get; } = new();
|
||||
@@ -267,7 +469,11 @@ public sealed class CaptureUnitTests
|
||||
|
||||
public void OnResponse(ResponseDescriptor response) => Responses.Enqueue(response);
|
||||
|
||||
public ConcurrentQueue<string> Dropped { get; } = new();
|
||||
|
||||
public void OnNavigation(NavigationDescriptor navigation) => Navigations.Enqueue(navigation);
|
||||
|
||||
public void OnBodyDropped(string requestId) => Dropped.Enqueue(requestId);
|
||||
}
|
||||
|
||||
private sealed class SyncProgress(List<long> values) : IProgress<long>
|
||||
|
||||
@@ -15,7 +15,9 @@ public sealed class HostingTests
|
||||
var args = ChromiumCommandLine.Build(Options, new ChromiumLaunchOptions());
|
||||
|
||||
CollectionAssert.Contains(args.ToList(), "--remote-debugging-port=9333");
|
||||
CollectionAssert.Contains(args.ToList(), "--user-data-dir=/tmp/febe-profilo");
|
||||
|
||||
// The profile reaches Chromium as a full path: «/tmp/febe-profilo» on Linux, rooted on the current drive on Windows.
|
||||
CollectionAssert.Contains(args.ToList(), $"--user-data-dir={Path.GetFullPath(Options.ProfileDirectory)}");
|
||||
CollectionAssert.Contains(args.ToList(), "--no-first-run");
|
||||
CollectionAssert.Contains(args.ToList(), "--no-default-browser-check");
|
||||
CollectionAssert.Contains(args.ToList(), "--window-size=1280,900");
|
||||
|
||||
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user