GastinelGarde : signalement des detections au Hub (desactive par defaut)
Nouveau paquet hub (Java pur) : envoi asynchrone des franchissements de palier (alerte, setback, expulsion) vers POST /internal/detections du Hub, selon la conception du bloc 2 (section 2) et les contraintes de la revue de securite du Hub. - fil d'envoi a part, file bornee sans verrou, copie sur disque, nouvelles tentatives exponentielles (1 s a 5 min), Retry-After, identifiant d'idempotence conserve ; - le tick serveur n'ajoute qu'un objet en file : aucune entree-sortie, aucune attente ; - cle de la source lue dans un fichier, jamais en dur, jamais journalisee ; - champs conformes au Hub (controle, dimension, version_mod, exemptions), aucune IP ; - reglages [hub] (envoi = false par defaut), commande /garde hub, ANNEXE-HUB.md ; - 55 tests unitaires hors ligne (faux serveur HTTP local). Non compile avec NeoForge ici (Garde, GardeSpec, GardeCommands) : a verifier au build. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Cette révision appartient à :
1 Parent
b2e5189d8a
révision
fb0643f0a3
23 fichiers modifiés
+2903
-1
Aucun fichier ne correspond à votre recherche
@@ -0,0 +1,57 @@
|
|||||||
|
# Annexe : contrat d'envoi des détections au Hub (GastinelGarde, branche feat/signalement-hub)
|
||||||
|
|
||||||
|
Source du contrat : `conception-hub-bloc2-20261019.md` §2, plus la revue de sécurité du Hub (branche `feat/sanctions-bloc2`,
|
||||||
|
fichier `stacks/accounts/internal/sanctions/ingest.go`). Aucune valeur secrète dans ce fichier.
|
||||||
|
|
||||||
|
## Ce que fait GastinelGarde
|
||||||
|
|
||||||
|
- **Désactivé par défaut** : `[hub] envoi = false`. Sans cela, `Signalement.surVerdict` ne fait qu'une lecture de variable.
|
||||||
|
- **Quoi** : un franchissement de palier (ALERTE, SETBACK ou EXPULSION) par joueur et par contrôle, pas chaque infraction, et jamais un bannissement. Un même palier n'est pas répété pendant `episodeMinutes` (10) ; seul un palier plus haut repart.
|
||||||
|
- **ENFORCE seulement** par défaut. OBSERVE seulement si `envoyerObserve = true` ; ces détections portent `mode = observe` (le Hub ne doit jamais les compter).
|
||||||
|
- **Gravité** : ALERTE = 1, SETBACK = 2, EXPULSION = 3. En ENFORCE, c'est la sanction réellement appliquée ; en OBSERVE, le palier mérité.
|
||||||
|
- **Quand** : dans un fil à part (`GastinelGarde-Hub`, priorité basse). Le tick ajoute un objet dans une file sans verrou.
|
||||||
|
- **Où** : `POST <url>/internal/detections`, `Content-Type: application/json`, en-tête `X-Source-Cle: <clé>`. Pas de redirection suivie.
|
||||||
|
- **Clé** : lue dans `fichierCle` (une ligne, 32 à 256 caractères ASCII visibles, droits 600 conseillés). Jamais dans la configuration, jamais journalisée, jamais écrite dans la file sur disque.
|
||||||
|
- **Reprise sur panne** : file bornée (`fileMax` = 10 000, les plus anciennes sont abandonnées), copie sur disque à l'arrêt et en panne, relue au démarrage ; attente 1 s, 2 s, 4 s … 5 min (+ 25 % au hasard) ; `Retry-After` respecté (5 min au plus) ; 401 / 403 : nouvel essai toutes les 5 min ; 400 : lot abandonné ; 413 : lot divisé par deux ; détections de plus de 23 h abandonnées (le Hub refuse au-delà de 24 h).
|
||||||
|
- **Débit** : `debitMaxParMinute` = 50 (le Hub accepte 60 par défaut) ; lots de 50 au plus et 15 000 octets (le Hub refuse 16 Kio).
|
||||||
|
|
||||||
|
## Corps envoyé
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"detections":[{
|
||||||
|
"id_externe":"<uuid joueur>:<contrôle>:<palier>:<ms>",
|
||||||
|
"sujet":{"type":"uuid_minecraft","valeur":"<uuid joueur>"},
|
||||||
|
"type":"<contrôle>", "gravite":1, "mode":"enforce", "points":9.5,
|
||||||
|
"survenue_le":"2026-10-19T10:00:00Z",
|
||||||
|
"details":{"controle":"…","palier":3,"exemptions":["…"],"version_mod":"0.3.2","x":0,"y":0,"z":0,"dimension":"minecraft:overworld"}
|
||||||
|
}]}
|
||||||
|
```
|
||||||
|
|
||||||
|
Aucun champ `service` ni `source` (le Hub les déduit de la clé). `id_externe` est fixé à la création : toutes les tentatives
|
||||||
|
d'une même détection portent le même identifiant (idempotence côté Hub).
|
||||||
|
|
||||||
|
## Conformité aux contraintes du Hub
|
||||||
|
|
||||||
|
| Champ | Motif Hub | Côté mod |
|
||||||
|
|---|---|---|
|
||||||
|
| `type` | `^[a-z0-9_-]{1,48}$`, dans `types_autorises` de la source | identifiants des contrôles (`killaura-angle`, `no-fall`…) |
|
||||||
|
| `id_externe` | `^[A-Za-z0-9:._-]{8,128}$` | vérifié à la création |
|
||||||
|
| `details.controle`, `details.dimension` | `^[a-z0-9_.:-]{1,64}$` | minuscules, autre caractère remplacé par `_`, 64 au plus |
|
||||||
|
| `details.version_mod` | `^[0-9A-Za-z.+-]{1,32}$` | autre caractère remplacé par `-`, « inconnue » si impossible |
|
||||||
|
| `details.exemptions` | 10 au plus, chacune `^[a-z0-9_.-]{1,32}$` | nettoyées, doublons retirés |
|
||||||
|
| `details.palier` | entier 0 à 100 | rang de la sanction (ALERTE 2, SETBACK 3, EXPULSION 4) |
|
||||||
|
| `details.x/y/z` | entiers ±30 000 000 | position arrondie au bloc, seulement si `coordonnees = true` |
|
||||||
|
| texte | aucune adresse IPv4 / IPv6 / préfixe | mêmes motifs que le Hub ; une valeur qui en ressemble est omise |
|
||||||
|
| `points` | 0 à 99 999 | borné |
|
||||||
|
| `survenue_le` | RFC 3339, de −24 h à +5 min | heure serveur, secondes |
|
||||||
|
| autre clé de `details` | retirée par le Hub | liste blanche appliquée aussi à la création et à la relecture du disque |
|
||||||
|
|
||||||
|
Le texte libre du moteur (`Verdict.details()`, qui peut contenir un pseudo) n'est **jamais** envoyé.
|
||||||
|
|
||||||
|
## À aligner avec le Hub (hypothèses du mod, à confirmer quand la route HTTP du Hub sera écrite)
|
||||||
|
|
||||||
|
1. **Enveloppe** : `{"detections":[…]}`. Le Hub (`Service.Ingerer`) prend un tableau de détections mais la route HTTP n'était pas encore écrite à la lecture ; si elle attend un tableau nu, changer `EnvoiHub.envoyer` (une ligne).
|
||||||
|
2. **Réponse 200** : tableau d'objets `{id_externe, statut: cree|doublon|refuse, code}` ; le mod accepte un tableau à la racine ou sous `resultats` / `results` / `detections` / `items`. Une réponse 200 illisible est tenue pour acceptée.
|
||||||
|
3. **`details.palier`** : le Hub veut un entier ; le mod envoie le rang de l'énumération `Sanction`. À confirmer.
|
||||||
|
4. **`types_autorises`** de la source `gastinelgarde` : doit contenir les 15 contrôles (`Signalement.typesAttendus()` donne la liste). `gravite_max` ≥ 3.
|
||||||
|
5. **Restriction réseau (D5-B)** : côté Hub, par réseau Docker du conteneur Minecraft ; rien à faire dans le mod.
|
||||||
@@ -1,5 +1,20 @@
|
|||||||
# Journal des versions
|
# Journal des versions
|
||||||
|
|
||||||
|
## Non publié (branche feat/signalement-hub, dérivée de fix/0.3.2-d1-d3)
|
||||||
|
|
||||||
|
Signalement des détections au Hub (bloc 2 de l'architecture des sanctions, GastinelGarde = première source).
|
||||||
|
**Désactivé par défaut** (`[hub] envoi = false`) : sans changement de configuration, aucun comportement ne change.
|
||||||
|
Testé hors jeu seulement (tests unitaires, faux serveur HTTP local) ; rien n'a été essayé sur un serveur Minecraft.
|
||||||
|
|
||||||
|
- Nouveau paquet `hub` (Java pur, sans Minecraft) : à chaque franchissement de palier (alerte, setback, expulsion) d'un
|
||||||
|
contrôle en ENFORCE, une détection est mise en file ; un fil à part l'envoie par lots à `POST /internal/detections`.
|
||||||
|
- Le tick du serveur ne fait qu'ajouter un objet dans une file sans verrou : jamais d'entrée-sortie, d'attente ni d'exception.
|
||||||
|
- File bornée (10 000), copie sur disque (`gastinelgarde-hub/file-attente.jsonl`) à l'arrêt et pendant une panne,
|
||||||
|
attente exponentielle de 1 s à 5 min, `Retry-After` respecté, identifiant d'idempotence conservé à chaque tentative.
|
||||||
|
- Clé de la source lue dans un fichier (`config/gastinelgarde-hub.key`), jamais dans la configuration, jamais journalisée.
|
||||||
|
- Champs texte conformes au Hub (`controle`, `dimension`, `version_mod`, exemptions), aucune adresse IP.
|
||||||
|
- Commande `/garde hub` : état de l'envoi. Contrat et points à aligner avec le Hub : `ANNEXE-HUB.md`.
|
||||||
|
|
||||||
## 0.3.2 (19/10/2026)
|
## 0.3.2 (19/10/2026)
|
||||||
|
|
||||||
Correctifs des défauts D1 à D3 trouvés aux essais en jeu du 19/10 (rapport-garde-test-1019). Modes et options
|
Correctifs des défauts D1 à D3 trouvés aux essais en jeu du 19/10 (rapport-garde-test-1019). Modes et options
|
||||||
|
|||||||
@@ -222,6 +222,14 @@ mais n'élargit plus rien (la clé `pingLagMs` est ignorée).
|
|||||||
Plafond configurable (`sanctionMax`). Les points décroissent de 0,5 par seconde. `rotation` ne peut que
|
Plafond configurable (`sanctionMax`). Les points décroissent de 0,5 par seconde. `rotation` ne peut que
|
||||||
journaliser et alerter (le coup a déjà eu lieu quand l'aller-retour est vu).
|
journaliser et alerter (le coup a déjà eu lieu quand l'aller-retour est vu).
|
||||||
|
|
||||||
|
## Signalement au Hub (désactivé par défaut)
|
||||||
|
|
||||||
|
Voir `ANNEXE-HUB.md` pour le contrat. Résumé : si `[hub] envoi = true`, que `url` pointe vers le Hub (réseau Docker interne)
|
||||||
|
et que le fichier `fichierCle` contient la clé de la source, chaque franchissement de palier (alerte, setback, expulsion)
|
||||||
|
d'un contrôle en ENFORCE est envoyé au Hub, dans un fil à part, par lots, avec nouvelles tentatives. Le Hub ne reçoit ni
|
||||||
|
pseudo, ni adresse IP, ni texte libre. Une panne du Hub ne ralentit jamais le serveur et ne perd rien tant que la file
|
||||||
|
(10 000, 23 h au plus) n'est pas pleine. Le bannissement reste une décision humaine.
|
||||||
|
|
||||||
## Commandes (ops, niveau 2)
|
## Commandes (ops, niveau 2)
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -231,6 +239,7 @@ journaliser et alerter (le coup a déjà eu lieu quand l'aller-retour est vu).
|
|||||||
/garde mode <contrôle> off|observe|enforce (écrit dans la configuration)
|
/garde mode <contrôle> off|observe|enforce (écrit dans la configuration)
|
||||||
/garde exempter <joueur> <minutes>
|
/garde exempter <joueur> <minutes>
|
||||||
/garde traces on|off enregistreur (jusqu'au redémarrage)
|
/garde traces on|off enregistreur (jusqu'au redémarrage)
|
||||||
|
/garde hub état du signalement au Hub (désactivé par défaut)
|
||||||
/garde reload
|
/garde reload
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -173,3 +173,42 @@
|
|||||||
# Default: 1024
|
# Default: 1024
|
||||||
# Range: 16 ~ 102400
|
# Range: 16 ~ 102400
|
||||||
tailleMaxMo = 1024
|
tailleMaxMo = 1024
|
||||||
|
|
||||||
|
#Signalement des détections au Hub (API d'ingestion). DÉSACTIVÉ PAR DÉFAUT : rien n'est lu ni envoyé tant que envoi = false.
|
||||||
|
#Seul un franchissement de palier (alerte, setback, expulsion) est signalé, jamais chaque infraction, jamais un bannissement.
|
||||||
|
#La clé de la source n'est PAS dans ce fichier : elle est lue dans fichierCle (une ligne, 32 caractères au moins, droits 600).
|
||||||
|
[hub]
|
||||||
|
#Interrupteur général. false = rien n'est lu, rien n'est envoyé.
|
||||||
|
envoi = false
|
||||||
|
#Adresse de base du Hub sur le réseau Docker interne, sans le chemin (http ou https, sans identifiants). Vide = pas d'envoi.
|
||||||
|
url = ""
|
||||||
|
#Fichier de la clé de la source (chemin relatif au dossier du serveur, ou absolu). Ne jamais le commiter ni le copier.
|
||||||
|
fichierCle = "config/gastinelgarde-hub.key"
|
||||||
|
#Envoyer aussi les contrôles en OBSERVE (marqués observe : le Hub ne les compte jamais pour une sanction). Conseillé false.
|
||||||
|
envoyerObserve = false
|
||||||
|
#Plus petit palier signalé : ALERTE, SETBACK ou EXPULSION.
|
||||||
|
palierMin = "ALERTE"
|
||||||
|
#Détections par requête (le Hub accepte 1 à 50 et 16 Kio).
|
||||||
|
# Range: 1 ~ 50
|
||||||
|
lotMax = 50
|
||||||
|
#Attente entre deux envois quand tout va bien (ms).
|
||||||
|
# Range: 200 ~ 60000
|
||||||
|
intervalleMs = 2000
|
||||||
|
#Détections gardées au plus en attente (les plus anciennes sont abandonnées au-delà).
|
||||||
|
# Range: 10 ~ 100000
|
||||||
|
fileMax = 10000
|
||||||
|
#Âge au-delà duquel une détection n'est plus envoyée (le Hub refuse plus de 24 h).
|
||||||
|
# Range: 1 ~ 23
|
||||||
|
ageMaxHeures = 23
|
||||||
|
#Détections envoyées au plus par minute (le Hub limite à 60 par défaut).
|
||||||
|
# Range: 1 ~ 600
|
||||||
|
debitMaxParMinute = 50
|
||||||
|
#Minutes pendant lesquelles un même palier d'un même contrôle et d'un même joueur n'est signalé qu'une fois.
|
||||||
|
# Range: 1 ~ 1440
|
||||||
|
episodeMinutes = 10
|
||||||
|
# Range: 200 ~ 30000
|
||||||
|
delaiConnexionMs = 3000
|
||||||
|
# Range: 500 ~ 60000
|
||||||
|
delaiRequeteMs = 5000
|
||||||
|
#Joindre la position (arrondie au bloc) et la dimension à chaque signalement.
|
||||||
|
coordonnees = true
|
||||||
@@ -16,6 +16,7 @@ import com.gastinelgarde.core.RiptideSuivi;
|
|||||||
import com.gastinelgarde.core.Sanction;
|
import com.gastinelgarde.core.Sanction;
|
||||||
import com.gastinelgarde.core.Suivi;
|
import com.gastinelgarde.core.Suivi;
|
||||||
import com.gastinelgarde.core.TraceFichier;
|
import com.gastinelgarde.core.TraceFichier;
|
||||||
|
import com.gastinelgarde.hub.Signalement;
|
||||||
import com.gastinelgarde.core.TraceLigne;
|
import com.gastinelgarde.core.TraceLigne;
|
||||||
import com.gastinelgarde.core.Verdict;
|
import com.gastinelgarde.core.Verdict;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -115,6 +116,7 @@ public final class Garde {
|
|||||||
|
|
||||||
private static TraceFichier traces;
|
private static TraceFichier traces;
|
||||||
private static Path journal;
|
private static Path journal;
|
||||||
|
private static volatile boolean serveurDemarre;
|
||||||
private static boolean tracesEnCours;
|
private static boolean tracesEnCours;
|
||||||
private static int gelTick = Integer.MIN_VALUE;
|
private static int gelTick = Integer.MIN_VALUE;
|
||||||
private static double tpsEstime = 20.0;
|
private static double tpsEstime = 20.0;
|
||||||
@@ -133,6 +135,37 @@ public final class Garde {
|
|||||||
|
|
||||||
public static void surConfigChargee() {
|
public static void surConfigChargee() {
|
||||||
GastinelGarde.LOGGER.info("[GastinelGarde] Configuration appliquée.");
|
GastinelGarde.LOGGER.info("[GastinelGarde] Configuration appliquée.");
|
||||||
|
if (serveurDemarre) redemarrerHub(); // /garde reload ou fichier modifié : le Hub relit ses réglages
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* (Re)lance le signalement au Hub selon la configuration. Coupé par défaut ; ne lève jamais d'exception.
|
||||||
|
* Fait dans un fil à part : l'arrêt de l'ancienne instance attend jusqu'à 2 s et écrit sur disque, ce qui ne doit
|
||||||
|
* jamais arriver dans le tick (ex. {@code /garde reload}, exécuté par le fil du serveur).
|
||||||
|
*/
|
||||||
|
private static void redemarrerHub() {
|
||||||
|
Thread t = new Thread(() -> {
|
||||||
|
try {
|
||||||
|
if (!serveurDemarre) return; // le serveur s'est arrêté entre-temps
|
||||||
|
Path jeu = FMLPaths.GAMEDIR.get();
|
||||||
|
com.gastinelgarde.hub.HubConfig h = GardeSpec.hub(jeu.resolve("gastinelgarde-hub"));
|
||||||
|
Signalement.demarrer(h, jeu.resolve(h.fichierCle()),
|
||||||
|
ligne -> GastinelGarde.LOGGER.info("[GastinelGarde] {}", ligne), versionMod());
|
||||||
|
} catch (Throwable e) {
|
||||||
|
GastinelGarde.LOGGER.warn("[GastinelGarde] Hub : démarrage impossible ({})", e.getClass().getSimpleName());
|
||||||
|
}
|
||||||
|
}, "GastinelGarde-Hub-config");
|
||||||
|
t.setDaemon(true);
|
||||||
|
t.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String versionMod() {
|
||||||
|
try {
|
||||||
|
return net.neoforged.fml.ModList.get().getModContainerById(GastinelGarde.MOD_ID)
|
||||||
|
.map(c -> c.getModInfo().getVersion().toString()).orElse("inconnue");
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
return "inconnue";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static synchronized void demarrer() {
|
public static synchronized void demarrer() {
|
||||||
@@ -148,9 +181,13 @@ public final class Garde {
|
|||||||
traces = null;
|
traces = null;
|
||||||
tracesEnCours = false;
|
tracesEnCours = false;
|
||||||
}
|
}
|
||||||
|
serveurDemarre = true;
|
||||||
|
redemarrerHub();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static synchronized void arreter() {
|
public static synchronized void arreter() {
|
||||||
|
serveurDemarre = false;
|
||||||
|
Signalement.arreter(); // écrit sur disque ce qui n'est pas parti (2 s d'attente au plus)
|
||||||
if (traces != null) {
|
if (traces != null) {
|
||||||
try {
|
try {
|
||||||
traces.close();
|
traces.close();
|
||||||
@@ -181,6 +218,7 @@ public final class Garde {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static void joueurParti(UUID id) {
|
public static void joueurParti(UUID id) {
|
||||||
|
Signalement.joueurParti(id);
|
||||||
MOTEUR.retirer(id);
|
MOTEUR.retirer(id);
|
||||||
MARQUES.remove(id);
|
MARQUES.remove(id);
|
||||||
ALERTES_COUPEES.remove(id);
|
ALERTES_COUPEES.remove(id);
|
||||||
@@ -538,9 +576,17 @@ public final class Garde {
|
|||||||
}
|
}
|
||||||
if (v.notifier()) alerterOps(p, v);
|
if (v.notifier()) alerterOps(p, v);
|
||||||
}
|
}
|
||||||
|
if (Signalement.actif()) { // coupé par défaut : une simple lecture de variable
|
||||||
|
for (Verdict v : verdicts) Signalement.surVerdict(p.getUUID(), v, () -> positionPour(p));
|
||||||
|
}
|
||||||
return Verdict.pire(verdicts);
|
return Verdict.pire(verdicts);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static Signalement.Position positionPour(ServerPlayer p) {
|
||||||
|
return new Signalement.Position(p.getBlockX(), p.getBlockY(), p.getBlockZ(),
|
||||||
|
p.level().dimension().location().toString());
|
||||||
|
}
|
||||||
|
|
||||||
private static void alerterOps(ServerPlayer cible, Verdict v) {
|
private static void alerterOps(ServerPlayer cible, Verdict v) {
|
||||||
Component msg = Component.literal(String.format("[Garde] %s : %s VL=%.1f (%s, %s)",
|
Component msg = Component.literal(String.format("[Garde] %s : %s VL=%.1f (%s, %s)",
|
||||||
cible.getGameProfile().getName(), v.controle().id(), v.vl(), v.mode(), v.applicable()))
|
cible.getGameProfile().getName(), v.controle().id(), v.vl(), v.mode(), v.applicable()))
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import net.neoforged.neoforge.event.RegisterCommandsEvent;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* /garde status [joueur] | alertes on|off | mode <contrôle> off|observe|enforce | exempter <joueur> <minutes>
|
* /garde status [joueur] | alertes on|off | mode <contrôle> off|observe|enforce | exempter <joueur> <minutes>
|
||||||
* | traces on|off | reload (réservé aux ops, niveau 2)
|
* | traces on|off | hub | reload (réservé aux ops, niveau 2)
|
||||||
*/
|
*/
|
||||||
public final class GardeCommands {
|
public final class GardeCommands {
|
||||||
|
|
||||||
@@ -64,6 +64,11 @@ public final class GardeCommands {
|
|||||||
.then(Commands.argument("minutes", IntegerArgumentType.integer(1, 1440))
|
.then(Commands.argument("minutes", IntegerArgumentType.integer(1, 1440))
|
||||||
.executes(GardeCommands::exempter))));
|
.executes(GardeCommands::exempter))));
|
||||||
|
|
||||||
|
racine.then(Commands.literal("hub").executes(ctx -> {
|
||||||
|
ok(ctx, com.gastinelgarde.hub.Signalement.resume());
|
||||||
|
return 1;
|
||||||
|
}));
|
||||||
|
|
||||||
racine.then(Commands.literal("reload").executes(GardeCommands::recharger));
|
racine.then(Commands.literal("reload").executes(GardeCommands::recharger));
|
||||||
|
|
||||||
d.register(racine);
|
d.register(racine);
|
||||||
|
|||||||
@@ -78,6 +78,21 @@ public final class GardeSpec {
|
|||||||
private static final ModConfigSpec.DoubleValue AC_VITESSE_MINECART;
|
private static final ModConfigSpec.DoubleValue AC_VITESSE_MINECART;
|
||||||
private static final ModConfigSpec.IntValue AC_EMPILEMENT_MAX;
|
private static final ModConfigSpec.IntValue AC_EMPILEMENT_MAX;
|
||||||
|
|
||||||
|
private static final ModConfigSpec.BooleanValue HUB_ENVOI;
|
||||||
|
private static final ModConfigSpec.ConfigValue<String> HUB_URL;
|
||||||
|
private static final ModConfigSpec.ConfigValue<String> HUB_FICHIER_CLE;
|
||||||
|
private static final ModConfigSpec.BooleanValue HUB_OBSERVE;
|
||||||
|
private static final ModConfigSpec.EnumValue<Sanction> HUB_PALIER_MIN;
|
||||||
|
private static final ModConfigSpec.IntValue HUB_LOT_MAX;
|
||||||
|
private static final ModConfigSpec.IntValue HUB_INTERVALLE_MS;
|
||||||
|
private static final ModConfigSpec.IntValue HUB_FILE_MAX;
|
||||||
|
private static final ModConfigSpec.IntValue HUB_AGE_MAX_HEURES;
|
||||||
|
private static final ModConfigSpec.IntValue HUB_DEBIT_MAX;
|
||||||
|
private static final ModConfigSpec.IntValue HUB_EPISODE_MIN;
|
||||||
|
private static final ModConfigSpec.IntValue HUB_DELAI_CONNEXION_MS;
|
||||||
|
private static final ModConfigSpec.IntValue HUB_DELAI_REQUETE_MS;
|
||||||
|
private static final ModConfigSpec.BooleanValue HUB_COORDONNEES;
|
||||||
|
|
||||||
private static final ModConfigSpec.BooleanValue TRACES_ACTIVES;
|
private static final ModConfigSpec.BooleanValue TRACES_ACTIVES;
|
||||||
private static final ModConfigSpec.IntValue TRACES_JOURS;
|
private static final ModConfigSpec.IntValue TRACES_JOURS;
|
||||||
private static final ModConfigSpec.IntValue TRACES_TAILLE_MO;
|
private static final ModConfigSpec.IntValue TRACES_TAILLE_MO;
|
||||||
@@ -237,6 +252,35 @@ public final class GardeSpec {
|
|||||||
TRACES_TAILLE_MO = b.defineInRange("tailleMaxMo", 1024, 16, 102400);
|
TRACES_TAILLE_MO = b.defineInRange("tailleMaxMo", 1024, 16, 102400);
|
||||||
b.pop();
|
b.pop();
|
||||||
|
|
||||||
|
b.comment("Signalement des détections au Hub (API d'ingestion, conception-hub-bloc2 §2). DÉSACTIVÉ PAR DÉFAUT.",
|
||||||
|
"Seul un franchissement de palier (alerte, setback, expulsion) est signalé, jamais chaque infraction, et jamais",
|
||||||
|
"un bannissement. L'envoi se fait dans un fil à part : une panne du Hub ne ralentit jamais le serveur.",
|
||||||
|
"La clé de la source n'est PAS dans ce fichier : elle est lue dans le fichier « fichierCle » (une ligne,",
|
||||||
|
"32 caractères au moins, droits 600), qui ne doit jamais être commité ni copié.").push("hub");
|
||||||
|
HUB_ENVOI = b.comment("Interrupteur général. false = rien n'est lu, rien n'est envoyé.").define("envoi", false);
|
||||||
|
HUB_URL = b.comment("Adresse de base du Hub sur le réseau Docker interne, sans le chemin (http ou https, sans identifiants).",
|
||||||
|
"Forme : http://<service>:<port>. Vide = pas d'envoi.").define("url", "");
|
||||||
|
HUB_FICHIER_CLE = b.comment("Fichier de la clé de la source (chemin relatif au dossier du serveur, ou absolu).")
|
||||||
|
.define("fichierCle", "config/gastinelgarde-hub.key");
|
||||||
|
HUB_OBSERVE = b.comment("Envoyer aussi les contrôles en OBSERVE (marqués « observe » : le Hub ne les compte jamais pour une sanction).",
|
||||||
|
"Conseillé false : ces contrôles ne sont pas validés en jeu.").define("envoyerObserve", false);
|
||||||
|
HUB_PALIER_MIN = b.comment("Plus petit palier signalé : ALERTE, SETBACK ou EXPULSION.").defineEnum("palierMin", Sanction.ALERTE);
|
||||||
|
HUB_LOT_MAX = b.comment("Détections par requête (le Hub accepte 1 à 50 et 16 Kio).").defineInRange("lotMax", 50, 1, 50);
|
||||||
|
HUB_INTERVALLE_MS = b.comment("Attente entre deux envois quand tout va bien (ms).").defineInRange("intervalleMs", 2000, 200, 60000);
|
||||||
|
HUB_FILE_MAX = b.comment("Détections gardées au plus en attente (les plus anciennes sont abandonnées au-delà).")
|
||||||
|
.defineInRange("fileMax", 10000, 10, 100000);
|
||||||
|
HUB_AGE_MAX_HEURES = b.comment("Âge au-delà duquel une détection n'est plus envoyée. Le Hub refuse plus de 24 h : 23 au plus.")
|
||||||
|
.defineInRange("ageMaxHeures", 23, 1, 23);
|
||||||
|
HUB_DEBIT_MAX = b.comment("Détections envoyées au plus par minute (le Hub limite à 60 par défaut).")
|
||||||
|
.defineInRange("debitMaxParMinute", 50, 1, 600);
|
||||||
|
HUB_EPISODE_MIN = b.comment("Durée (minutes) pendant laquelle un même palier d'un même contrôle et d'un même joueur n'est signalé qu'une fois.")
|
||||||
|
.defineInRange("episodeMinutes", 10, 1, 1440);
|
||||||
|
HUB_DELAI_CONNEXION_MS = b.defineInRange("delaiConnexionMs", 3000, 200, 30000);
|
||||||
|
HUB_DELAI_REQUETE_MS = b.defineInRange("delaiRequeteMs", 5000, 500, 60000);
|
||||||
|
HUB_COORDONNEES = b.comment("Joindre la position (arrondie au bloc) et la dimension à chaque signalement.")
|
||||||
|
.define("coordonnees", true);
|
||||||
|
b.pop();
|
||||||
|
|
||||||
SPEC = b.build();
|
SPEC = b.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -380,6 +424,27 @@ public final class GardeSpec {
|
|||||||
return mo * 1024L * 1024L;
|
return mo * 1024L * 1024L;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Réglages du signalement au Hub (valeurs par défaut, donc envoi coupé, si le fichier n'est pas chargé). */
|
||||||
|
public static com.gastinelgarde.hub.HubConfig hub(java.nio.file.Path dossierEtat) {
|
||||||
|
boolean l = SPEC.isLoaded();
|
||||||
|
return new com.gastinelgarde.hub.HubConfig(
|
||||||
|
l ? HUB_ENVOI.get() : HUB_ENVOI.getDefault(),
|
||||||
|
l ? HUB_URL.get() : HUB_URL.getDefault(),
|
||||||
|
java.nio.file.Path.of(l ? HUB_FICHIER_CLE.get() : HUB_FICHIER_CLE.getDefault()),
|
||||||
|
l ? HUB_OBSERVE.get() : HUB_OBSERVE.getDefault(),
|
||||||
|
l ? HUB_PALIER_MIN.get() : HUB_PALIER_MIN.getDefault(),
|
||||||
|
l ? HUB_LOT_MAX.get() : HUB_LOT_MAX.getDefault(),
|
||||||
|
l ? HUB_INTERVALLE_MS.get() : HUB_INTERVALLE_MS.getDefault(),
|
||||||
|
l ? HUB_FILE_MAX.get() : HUB_FILE_MAX.getDefault(),
|
||||||
|
(l ? HUB_AGE_MAX_HEURES.get() : HUB_AGE_MAX_HEURES.getDefault()) * 3600_000L,
|
||||||
|
l ? HUB_DEBIT_MAX.get() : HUB_DEBIT_MAX.getDefault(),
|
||||||
|
(l ? HUB_EPISODE_MIN.get() : HUB_EPISODE_MIN.getDefault()) * 60_000L,
|
||||||
|
l ? HUB_DELAI_CONNEXION_MS.get() : HUB_DELAI_CONNEXION_MS.getDefault(),
|
||||||
|
l ? HUB_DELAI_REQUETE_MS.get() : HUB_DELAI_REQUETE_MS.getDefault(),
|
||||||
|
l ? HUB_COORDONNEES.get() : HUB_COORDONNEES.getDefault(),
|
||||||
|
dossierEtat);
|
||||||
|
}
|
||||||
|
|
||||||
/** Modifie un mode dans le fichier de configuration (conservé au prochain démarrage). */
|
/** Modifie un mode dans le fichier de configuration (conservé au prochain démarrage). */
|
||||||
public static void definirMode(Controle c, Mode m) {
|
public static void definirMode(Controle c, Mode m) {
|
||||||
ModConfigSpec.EnumValue<Mode> v = MODES.get(c);
|
ModConfigSpec.EnumValue<Mode> v = MODES.get(c);
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
package com.gastinelgarde.hub;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mise en conformité des champs texte avec ce que le Hub accepte (revue de sécurité du Hub, 19/10/2026) :
|
||||||
|
* <ul>
|
||||||
|
* <li>{@code controle} et {@code dimension} : {@code ^[a-z0-9_.:-]{1,64}$} ;</li>
|
||||||
|
* <li>{@code version_mod} : {@code ^[0-9A-Za-z.+-]{1,32}$} ;</li>
|
||||||
|
* <li>exemptions : 10 au plus, chacune {@code ^[a-z0-9_.-]{1,32}$} (une seule invalide fait rejeter toute la liste
|
||||||
|
* côté Hub, d'où le nettoyage ici) ;</li>
|
||||||
|
* <li>aucune valeur qui ressemble à une adresse IP (v4, v6, ou préfixe) dans un champ texte.</li>
|
||||||
|
* </ul>
|
||||||
|
* Une valeur qui ne peut pas devenir conforme est omise : un détail en moins vaut mieux qu'une détection refusée.
|
||||||
|
*/
|
||||||
|
public final class Assainir {
|
||||||
|
|
||||||
|
public static final Pattern CONTROLE = Pattern.compile("^[a-z0-9_.:-]{1,64}$");
|
||||||
|
public static final Pattern VERSION_MOD = Pattern.compile("^[0-9A-Za-z.+-]{1,32}$");
|
||||||
|
public static final Pattern EXEMPTION = Pattern.compile("^[a-z0-9_.-]{1,32}$");
|
||||||
|
public static final Pattern TYPE_DETECTION = Pattern.compile("^[a-z0-9_-]{1,48}$");
|
||||||
|
public static final Pattern ID_EXTERNE = Pattern.compile("^[A-Za-z0-9:._-]{8,128}$");
|
||||||
|
public static final int EXEMPTIONS_MAX = 10;
|
||||||
|
|
||||||
|
// Mêmes motifs que le Hub : IPv4 isolée dans la chaîne, ou suite « hex:hex:hex » (IPv6 et préfixes).
|
||||||
|
private static final Pattern IPV4_DANS = Pattern.compile("(^|[^0-9])[0-9]{1,3}(\\.[0-9]{1,3}){3}($|[^0-9])");
|
||||||
|
private static final Pattern IPV6_DANS = Pattern.compile("[0-9A-Fa-f]{0,4}(:[0-9A-Fa-f]{0,4}){2,}");
|
||||||
|
private static final Pattern CARACTERE_NON_ADMIS = Pattern.compile("[^a-z0-9_.:-]");
|
||||||
|
private static final Pattern CARACTERE_NON_ADMIS_EXEMPTION = Pattern.compile("[^a-z0-9_.-]");
|
||||||
|
private static final Pattern CARACTERE_NON_ADMIS_VERSION = Pattern.compile("[^0-9A-Za-z.+-]");
|
||||||
|
|
||||||
|
private Assainir() { }
|
||||||
|
|
||||||
|
/** Vrai si la chaîne est, ou contient, une adresse IPv4 / IPv6 / un préfixe CIDR. */
|
||||||
|
public static boolean ressembleAdresseIp(String s) {
|
||||||
|
if (s == null) return false;
|
||||||
|
return IPV4_DANS.matcher(s).find() || IPV6_DANS.matcher(s).find();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Identifiant de contrôle conforme, ou {@code null}. */
|
||||||
|
public static String controle(String brut) {
|
||||||
|
return conforme(brut, CARACTERE_NON_ADMIS, CONTROLE, 64);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dimension (« minecraft:overworld ») conforme : les « / » d'un chemin de dimension deviennent « _ ». */
|
||||||
|
public static String dimension(String brut) {
|
||||||
|
return conforme(brut, CARACTERE_NON_ADMIS, CONTROLE, 64);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Version du mod conforme ; « inconnue » si elle ne peut pas l'être. */
|
||||||
|
public static String versionMod(String brut) {
|
||||||
|
String v = brut == null ? "" : CARACTERE_NON_ADMIS_VERSION.matcher(brut.strip()).replaceAll("-");
|
||||||
|
if (v.length() > 32) v = v.substring(0, 32);
|
||||||
|
if (!VERSION_MOD.matcher(v).matches() || ressembleAdresseIp(v)) return "inconnue";
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Liste d'exemptions conforme : 10 au plus, chacune valide, sans doublon ; les valeurs inexploitables sont ignorées. */
|
||||||
|
public static List<String> exemptions(Iterable<String> brutes) {
|
||||||
|
List<String> sortie = new ArrayList<>();
|
||||||
|
if (brutes == null) return sortie;
|
||||||
|
for (String b : brutes) {
|
||||||
|
if (sortie.size() >= EXEMPTIONS_MAX) break;
|
||||||
|
String e = conforme(b, CARACTERE_NON_ADMIS_EXEMPTION, EXEMPTION, 32);
|
||||||
|
if (e != null && !sortie.contains(e)) sortie.add(e);
|
||||||
|
}
|
||||||
|
return sortie;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Liste blanche des clés de {@code details} (celles que le Hub conserve), avec leur type et leurs bornes ; toute
|
||||||
|
* autre clé, ou valeur mal formée, est retirée. Sert de dernier garde-fou à la création d'une {@link Detection}
|
||||||
|
* et à la relecture de la file d'attente sur disque.
|
||||||
|
*/
|
||||||
|
public static java.util.Map<String, Object> details(java.util.Map<String, Object> brut) {
|
||||||
|
java.util.Map<String, Object> sortie = new java.util.LinkedHashMap<>();
|
||||||
|
if (brut == null) return sortie;
|
||||||
|
String c = brut.get("controle") instanceof String t ? controle(t) : null;
|
||||||
|
if (c != null) sortie.put("controle", c);
|
||||||
|
Long palier = entier(brut.get("palier"), 0, 100);
|
||||||
|
if (palier != null) sortie.put("palier", palier);
|
||||||
|
if (brut.get("exemptions") instanceof Iterable<?> it) {
|
||||||
|
List<String> l = new ArrayList<>();
|
||||||
|
for (Object o : it) if (o instanceof String t) l.add(t);
|
||||||
|
List<String> ex = exemptions(l);
|
||||||
|
if (!ex.isEmpty()) sortie.put("exemptions", ex);
|
||||||
|
}
|
||||||
|
if (brut.get("version_mod") instanceof String t && VERSION_MOD.matcher(t).matches() && !ressembleAdresseIp(t)) {
|
||||||
|
sortie.put("version_mod", t);
|
||||||
|
}
|
||||||
|
for (String k : new String[] {"x", "y", "z"}) {
|
||||||
|
Long v = entier(brut.get(k), -30_000_000L, 30_000_000L);
|
||||||
|
if (v != null) sortie.put(k, v);
|
||||||
|
}
|
||||||
|
if (brut.get("dimension") instanceof String t) {
|
||||||
|
String d = dimension(t);
|
||||||
|
if (d != null) sortie.put("dimension", d);
|
||||||
|
}
|
||||||
|
return sortie;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Long entier(Object o, long min, long max) {
|
||||||
|
if (!(o instanceof Number n)) return null;
|
||||||
|
double d = n.doubleValue();
|
||||||
|
if (Double.isNaN(d) || Double.isInfinite(d) || d != Math.rint(d)) return null;
|
||||||
|
long v = n.longValue();
|
||||||
|
return v >= min && v <= max ? v : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String conforme(String brut, Pattern interdits, Pattern attendu, int max) {
|
||||||
|
if (brut == null) return null;
|
||||||
|
String s = interdits.matcher(brut.strip().toLowerCase(Locale.ROOT)).replaceAll("_");
|
||||||
|
if (s.length() > max) s = s.substring(0, max);
|
||||||
|
if (s.isEmpty() || !attendu.matcher(s).matches() || ressembleAdresseIp(s)) return null;
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package com.gastinelgarde.hub;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Une détection prête à être envoyée au Hub (contrat : conception-hub-bloc2 §2.1). Immuable.
|
||||||
|
* Pas de champ « service » ni « source » : le Hub les déduit de la clé.
|
||||||
|
*
|
||||||
|
* @param idExterne clé d'idempotence côté Hub, 8 à 128 caractères, fixée une fois pour toutes à la création
|
||||||
|
* (une nouvelle tentative renvoie exactement le même identifiant)
|
||||||
|
* @param sujetUuid UUID Minecraft du joueur
|
||||||
|
* @param type identifiant du contrôle (liste blanche côté Hub, voir ANNEXE-HUB.md)
|
||||||
|
* @param gravite 1 à 3
|
||||||
|
* @param mode {@code observe} ou {@code enforce} (mode du contrôle au moment des faits)
|
||||||
|
* @param points points d'infraction du contrôle au franchissement du palier
|
||||||
|
* @param survenueMs instant des faits (epoch ms)
|
||||||
|
* @param details clés de la liste blanche seulement ; valeurs String, Number, Boolean ou liste de String
|
||||||
|
*/
|
||||||
|
public record Detection(String idExterne, String sujetUuid, String type, int gravite, String mode,
|
||||||
|
double points, long survenueMs, Map<String, Object> details) {
|
||||||
|
|
||||||
|
public static final int ID_MIN = 8;
|
||||||
|
public static final int ID_MAX = 128;
|
||||||
|
private static final Pattern UUID_TEXTE =
|
||||||
|
Pattern.compile("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}");
|
||||||
|
|
||||||
|
public Detection {
|
||||||
|
if (idExterne == null || idExterne.length() < ID_MIN || idExterne.length() > ID_MAX
|
||||||
|
|| !Assainir.ID_EXTERNE.matcher(idExterne).matches()) {
|
||||||
|
throw new IllegalArgumentException("id_externe : " + ID_MIN + " à " + ID_MAX + " caractères parmi A-Z a-z 0-9 : . _ -");
|
||||||
|
}
|
||||||
|
if (sujetUuid == null || !UUID_TEXTE.matcher(sujetUuid).matches()) {
|
||||||
|
throw new IllegalArgumentException("sujet : UUID attendu");
|
||||||
|
}
|
||||||
|
if (type == null || !Assainir.TYPE_DETECTION.matcher(type).matches()) throw new IllegalArgumentException("type : [a-z0-9_-], 1 à 48");
|
||||||
|
if (gravite < 1 || gravite > 3) throw new IllegalArgumentException("gravité : 1 à 3");
|
||||||
|
if (!"observe".equals(mode) && !"enforce".equals(mode)) throw new IllegalArgumentException("mode : observe ou enforce");
|
||||||
|
if (Double.isNaN(points) || Double.isInfinite(points)) points = 0;
|
||||||
|
points = Math.max(0, Math.min(99_999, points)); // le Hub refuse hors de 0 à 99 999
|
||||||
|
details = java.util.Collections.unmodifiableMap(Assainir.details(details)); // liste blanche de clés, valeurs conformes
|
||||||
|
}
|
||||||
|
|
||||||
|
/** L'objet JSON de la détection, tel qu'envoyé dans le lot. */
|
||||||
|
public String json() {
|
||||||
|
Map<String, Object> sujet = new LinkedHashMap<>();
|
||||||
|
sujet.put("type", "uuid_minecraft");
|
||||||
|
sujet.put("valeur", sujetUuid);
|
||||||
|
Map<String, Object> m = new LinkedHashMap<>();
|
||||||
|
m.put("id_externe", idExterne);
|
||||||
|
m.put("sujet", sujet);
|
||||||
|
m.put("type", type);
|
||||||
|
m.put("gravite", gravite);
|
||||||
|
m.put("mode", mode);
|
||||||
|
m.put("points", Math.round(points * 100.0) / 100.0);
|
||||||
|
m.put("survenue_le", Instant.ofEpochSecond(Math.floorDiv(survenueMs, 1000L)).toString()); // RFC 3339, UTC
|
||||||
|
m.put("details", details);
|
||||||
|
return MiniJson.ecrire(m);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Relit une détection écrite par {@link #json()} (file d'attente sur disque). */
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public static Detection depuisJson(Object racine) {
|
||||||
|
if (!(racine instanceof Map<?, ?> m)) throw new IllegalArgumentException("objet attendu");
|
||||||
|
Map<String, Object> sujet = (Map<String, Object>) m.get("sujet");
|
||||||
|
Object d = m.get("details");
|
||||||
|
return new Detection(
|
||||||
|
(String) m.get("id_externe"),
|
||||||
|
(String) sujet.get("valeur"),
|
||||||
|
(String) m.get("type"),
|
||||||
|
((Number) m.get("gravite")).intValue(),
|
||||||
|
(String) m.get("mode"),
|
||||||
|
((Number) m.get("points")).doubleValue(),
|
||||||
|
Instant.parse((String) m.get("survenue_le")).toEpochMilli(),
|
||||||
|
d instanceof Map<?, ?> dm ? (Map<String, Object>) dm : Map.of());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,341 @@
|
|||||||
|
package com.gastinelgarde.hub;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.util.ArrayDeque;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
import java.util.function.LongSupplier;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fil d'envoi vers le Hub. Tout ce qui est lent (réseau, disque, attente) se passe ici, jamais dans le tick du
|
||||||
|
* serveur : le tick ne fait qu'ajouter une détection dans {@link FileEnvoi} (sans verrou).
|
||||||
|
*
|
||||||
|
* <p>Comportement (conception-hub-bloc2 §2) :
|
||||||
|
* <ul>
|
||||||
|
* <li>lots de 1 à 50 détections et 15 000 octets au plus (le Hub refuse plus de 16 Kio) ;</li>
|
||||||
|
* <li>au plus {@code debitMaxParMinute} détections par minute (le Hub répond 429 au-delà de sa limite) ;</li>
|
||||||
|
* <li>panne réseau, 5xx, 404 : attente exponentielle de 1 s à 5 min (+ jusqu'à 25 % au hasard), le lot est
|
||||||
|
* remis en tête, l'identifiant de chaque détection ne change pas (le Hub ignore les doublons) ;</li>
|
||||||
|
* <li>429 : on attend {@code Retry-After} (au plus 5 min) ; 401 / 403 : clé refusée ou source inactive,
|
||||||
|
* on réessaie toutes les 5 min sans rien jeter (la file reste bornée) ;</li>
|
||||||
|
* <li>400 : le lot est invalide, il est abandonné (le renvoyer ne servirait à rien) ; 413 : lot divisé par deux ;</li>
|
||||||
|
* <li>réponse 200 : {@code cree} et {@code doublon} sont acquittés, {@code refuse} est abandonné.</li>
|
||||||
|
* </ul>
|
||||||
|
* La clé n'est jamais écrite dans un message. Les messages au journal sont limités (un par type et par 5 minutes).
|
||||||
|
*/
|
||||||
|
public final class EnvoiHub {
|
||||||
|
|
||||||
|
/** Limite du Hub : 16 Kio par requête ; on garde de la marge pour l'enveloppe. */
|
||||||
|
public static final int OCTETS_CORPS_MAX = 15_000;
|
||||||
|
public static final long ATTENTE_MIN_MS = 1_000;
|
||||||
|
public static final long ATTENTE_MAX_MS = 300_000;
|
||||||
|
private static final long INTERVALLE_SPOOL_MS = 30_000;
|
||||||
|
private static final long INTERVALLE_MESSAGE_MS = 300_000;
|
||||||
|
|
||||||
|
private final HubConfig cfg;
|
||||||
|
private final URI adresse;
|
||||||
|
private final String cle;
|
||||||
|
private final Transport transport;
|
||||||
|
private final FileEnvoi file;
|
||||||
|
private final Spool spool;
|
||||||
|
private final LongSupplier horloge;
|
||||||
|
private final Consumer<String> journal;
|
||||||
|
|
||||||
|
// État du fil d'envoi (modifié par ce fil seulement).
|
||||||
|
private int echecs;
|
||||||
|
private long prochainEssaiMs;
|
||||||
|
private int lotCourant;
|
||||||
|
private final ArrayDeque<Long> envoyesRecents = new ArrayDeque<>();
|
||||||
|
private long dernierSpoolMs = Long.MIN_VALUE / 2;
|
||||||
|
private final Map<String, Long> derniersMessages = new java.util.concurrent.ConcurrentHashMap<>();
|
||||||
|
private boolean enPanne;
|
||||||
|
|
||||||
|
private volatile List<Detection> enVol = List.of();
|
||||||
|
private volatile boolean arret;
|
||||||
|
private Thread fil;
|
||||||
|
|
||||||
|
// Compteurs lisibles de n'importe où.
|
||||||
|
private final AtomicLong envoyees = new AtomicLong();
|
||||||
|
private final AtomicLong doublons = new AtomicLong();
|
||||||
|
private final AtomicLong refusees = new AtomicLong();
|
||||||
|
private final AtomicLong perimees = new AtomicLong();
|
||||||
|
private final AtomicLong lotsRejetes = new AtomicLong();
|
||||||
|
private final AtomicLong echecsTotal = new AtomicLong();
|
||||||
|
|
||||||
|
public EnvoiHub(HubConfig cfg, String cle, Transport transport, FileEnvoi file, LongSupplier horloge,
|
||||||
|
Consumer<String> journal) {
|
||||||
|
this.cfg = cfg;
|
||||||
|
this.adresse = cfg.adresseApi();
|
||||||
|
if (this.adresse == null) throw new IllegalArgumentException("adresse du Hub invalide");
|
||||||
|
this.cle = cle;
|
||||||
|
this.transport = transport;
|
||||||
|
this.file = file;
|
||||||
|
this.spool = new Spool(cfg.dossierEtat().resolve("file-attente.jsonl"));
|
||||||
|
this.horloge = horloge;
|
||||||
|
this.journal = journal;
|
||||||
|
this.lotCourant = cfg.lotMax();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Cycle de vie ---
|
||||||
|
|
||||||
|
/** Reprend la file écrite sur disque, puis lance le fil d'envoi (daemon, priorité basse). */
|
||||||
|
public synchronized void demarrer() {
|
||||||
|
if (fil != null) return;
|
||||||
|
List<Detection> reprises = spool.lire(horloge.getAsLong() - cfg.ageMaxMs());
|
||||||
|
if (!reprises.isEmpty()) {
|
||||||
|
file.ajouterTout(reprises);
|
||||||
|
journal.accept("Hub : " + reprises.size() + " détection(s) reprise(s) de la file d'attente du disque.");
|
||||||
|
}
|
||||||
|
arret = false;
|
||||||
|
fil = new Thread(this::boucle, "GastinelGarde-Hub");
|
||||||
|
fil.setDaemon(true);
|
||||||
|
fil.setPriority(Thread.MIN_PRIORITY);
|
||||||
|
fil.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Arrête le fil (au plus 2 s d'attente) et écrit ce qui n'est pas parti sur le disque. */
|
||||||
|
public synchronized void arreter() {
|
||||||
|
arret = true;
|
||||||
|
Thread t = fil;
|
||||||
|
fil = null;
|
||||||
|
if (t != null) {
|
||||||
|
t.interrupt();
|
||||||
|
try {
|
||||||
|
t.join(2000);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sauverSpool(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void boucle() {
|
||||||
|
while (!arret) {
|
||||||
|
long attente;
|
||||||
|
try {
|
||||||
|
attente = cycle();
|
||||||
|
} catch (Throwable t) { // le fil ne doit jamais mourir ni rien lâcher vers le serveur
|
||||||
|
limite("bug", "Hub : erreur interne du client (" + t.getClass().getSimpleName() + "), nouvel essai dans 5 s.");
|
||||||
|
attente = 5000;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Thread.sleep(Math.max(50, attente));
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Un tour de boucle (public pour les tests : horloge et transport injectés) ---
|
||||||
|
|
||||||
|
/** Fait ce qu'il y a à faire maintenant et renvoie le temps à attendre avant le prochain tour (ms). */
|
||||||
|
public long cycle() {
|
||||||
|
long now = horloge.getAsLong();
|
||||||
|
int vieilles = file.purgerAvant(now - cfg.ageMaxMs());
|
||||||
|
if (vieilles > 0) {
|
||||||
|
perimees.addAndGet(vieilles);
|
||||||
|
limite("age", "Hub : " + vieilles + " détection(s) trop ancienne(s) abandonnée(s) (le Hub refuse au-delà de 24 h).");
|
||||||
|
}
|
||||||
|
if (file.vide()) {
|
||||||
|
if (spool.existe()) sauverSpool(false);
|
||||||
|
return cfg.intervalleMs();
|
||||||
|
}
|
||||||
|
if (now < prochainEssaiMs) return prochainEssaiMs - now;
|
||||||
|
|
||||||
|
while (!envoyesRecents.isEmpty() && now - envoyesRecents.peekFirst() >= 60_000) envoyesRecents.pollFirst();
|
||||||
|
int dispo = cfg.debitMaxParMinute() - envoyesRecents.size();
|
||||||
|
if (dispo <= 0) return Math.max(200, 60_000 - (now - envoyesRecents.peekFirst()));
|
||||||
|
|
||||||
|
List<Detection> lot = file.prendre(Math.min(lotCourant, dispo), OCTETS_CORPS_MAX - 64);
|
||||||
|
if (lot.isEmpty()) return cfg.intervalleMs();
|
||||||
|
enVol = lot;
|
||||||
|
try {
|
||||||
|
return envoyer(lot, now);
|
||||||
|
} finally {
|
||||||
|
enVol = List.of();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private long envoyer(List<Detection> lot, long now) {
|
||||||
|
StringBuilder corps = new StringBuilder(64 + lot.size() * 400).append("{\"detections\":[");
|
||||||
|
for (int i = 0; i < lot.size(); i++) {
|
||||||
|
if (i > 0) corps.append(',');
|
||||||
|
corps.append(lot.get(i).json());
|
||||||
|
}
|
||||||
|
corps.append("]}");
|
||||||
|
|
||||||
|
Transport.Reponse r;
|
||||||
|
try {
|
||||||
|
r = transport.envoyer(adresse, cle, corps.toString());
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
file.remettre(lot);
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
return cfg.intervalleMs();
|
||||||
|
} catch (IOException | RuntimeException e) {
|
||||||
|
return echec(lot, now, "Hub injoignable (" + e.getClass().getSimpleName() + ")");
|
||||||
|
}
|
||||||
|
|
||||||
|
int s = r.statut();
|
||||||
|
if (s == 200) return succes(lot, r, now);
|
||||||
|
if (s == 429) {
|
||||||
|
file.remettre(lot);
|
||||||
|
long ra = r.retryAfterSec().isPresent() ? r.retryAfterSec().getAsLong() * 1000 : delaiExponentiel(++echecs);
|
||||||
|
long attente = Math.max(ATTENTE_MIN_MS, Math.min(ATTENTE_MAX_MS, ra));
|
||||||
|
prochainEssaiMs = now + attente;
|
||||||
|
echecsTotal.incrementAndGet();
|
||||||
|
limite("429", "Hub : débit limité (429), reprise dans " + attente / 1000 + " s.");
|
||||||
|
return attente;
|
||||||
|
}
|
||||||
|
if (s == 401 || s == 403) {
|
||||||
|
file.remettre(lot);
|
||||||
|
echecs++;
|
||||||
|
echecsTotal.incrementAndGet();
|
||||||
|
prochainEssaiMs = now + ATTENTE_MAX_MS;
|
||||||
|
limite("auth" + s, s == 401
|
||||||
|
? "Hub : clé refusée (401). Vérifier le fichier de clé ; on réessaie dans 5 min."
|
||||||
|
: "Hub : source désactivée côté Hub (403). Elle doit être activée dans le Portail ; on réessaie dans 5 min.");
|
||||||
|
sauverSpoolSiBesoin(now);
|
||||||
|
return ATTENTE_MAX_MS;
|
||||||
|
}
|
||||||
|
if (s == 400) {
|
||||||
|
lotsRejetes.incrementAndGet();
|
||||||
|
perimees.addAndGet(lot.size());
|
||||||
|
limite("400", "Hub : lot de " + lot.size() + " détection(s) refusé comme invalide (400), abandonné.");
|
||||||
|
return 200;
|
||||||
|
}
|
||||||
|
if (s == 413) {
|
||||||
|
if (lot.size() > 1) {
|
||||||
|
lotCourant = Math.max(1, lot.size() / 2);
|
||||||
|
file.remettre(lot);
|
||||||
|
limite("413", "Hub : lot trop gros (413), lots réduits à " + lotCourant + ".");
|
||||||
|
} else {
|
||||||
|
lotsRejetes.incrementAndGet();
|
||||||
|
perimees.addAndGet(1);
|
||||||
|
limite("413", "Hub : une détection est trop grosse (413), abandonnée.");
|
||||||
|
}
|
||||||
|
return 200;
|
||||||
|
}
|
||||||
|
return echec(lot, now, "Hub : réponse inattendue (HTTP " + s + ")");
|
||||||
|
}
|
||||||
|
|
||||||
|
private long succes(List<Detection> lot, Transport.Reponse r, long now) {
|
||||||
|
ReponseHub rh = ReponseHub.analyser(r.corps());
|
||||||
|
envoyees.addAndGet(lot.size());
|
||||||
|
if (rh.lue()) {
|
||||||
|
doublons.addAndGet(rh.doublons());
|
||||||
|
refusees.addAndGet(rh.refusees());
|
||||||
|
if (rh.refusees() > 0) {
|
||||||
|
limite("refus", "Hub : " + rh.refusees() + " détection(s) refusée(s) par le Hub : " + rh.codesRefus()
|
||||||
|
+ " (abandonnées, à corriger côté réglages du Hub).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (int i = 0; i < lot.size(); i++) envoyesRecents.addLast(now);
|
||||||
|
if (enPanne) {
|
||||||
|
journal.accept("Hub : liaison rétablie, " + lot.size() + " détection(s) envoyée(s).");
|
||||||
|
enPanne = false;
|
||||||
|
}
|
||||||
|
echecs = 0;
|
||||||
|
prochainEssaiMs = 0;
|
||||||
|
lotCourant = cfg.lotMax();
|
||||||
|
derniersMessages.clear(); // un futur incident sera de nouveau signalé tout de suite
|
||||||
|
if (file.vide()) sauverSpool(false);
|
||||||
|
return file.vide() ? cfg.intervalleMs() : 200;
|
||||||
|
}
|
||||||
|
|
||||||
|
private long echec(List<Detection> lot, long now, String raison) {
|
||||||
|
file.remettre(lot);
|
||||||
|
echecs++;
|
||||||
|
echecsTotal.incrementAndGet();
|
||||||
|
long base = delaiExponentiel(echecs);
|
||||||
|
long attente = base + ThreadLocalRandom.current().nextLong(base / 4 + 1);
|
||||||
|
prochainEssaiMs = now + attente;
|
||||||
|
enPanne = true;
|
||||||
|
limite("reseau", raison + ", nouvel essai dans " + attente / 1000 + " s, " + (file.taille()) + " en attente.");
|
||||||
|
sauverSpoolSiBesoin(now);
|
||||||
|
return attente;
|
||||||
|
}
|
||||||
|
|
||||||
|
static long delaiExponentiel(int echecs) {
|
||||||
|
int puissance = Math.min(Math.max(echecs - 1, 0), 20);
|
||||||
|
return Math.min(ATTENTE_MAX_MS, ATTENTE_MIN_MS << puissance);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Disque ---
|
||||||
|
|
||||||
|
private void sauverSpoolSiBesoin(long now) {
|
||||||
|
if (now - dernierSpoolMs >= INTERVALLE_SPOOL_MS) {
|
||||||
|
dernierSpoolMs = now;
|
||||||
|
sauverSpool(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Écrit (ou efface, si plus rien) la copie sur disque. {@code arret} : inclut le lot en vol. */
|
||||||
|
private void sauverSpool(boolean arret) {
|
||||||
|
try {
|
||||||
|
List<Detection> l = file.instantane();
|
||||||
|
if (arret) {
|
||||||
|
List<Detection> v = enVol;
|
||||||
|
if (!v.isEmpty()) {
|
||||||
|
java.util.ArrayList<Detection> tout = new java.util.ArrayList<>(v);
|
||||||
|
tout.addAll(l);
|
||||||
|
l = tout;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
spool.ecrire(l);
|
||||||
|
} catch (IOException | RuntimeException e) {
|
||||||
|
limite("disque", "Hub : écriture de la file d'attente impossible (" + e.getClass().getSimpleName() + ").");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Journal limité ---
|
||||||
|
|
||||||
|
private void limite(String type, String message) {
|
||||||
|
long now = horloge.getAsLong();
|
||||||
|
Long dernier = derniersMessages.get(type);
|
||||||
|
if (dernier != null && now - dernier < INTERVALLE_MESSAGE_MS) return;
|
||||||
|
derniersMessages.put(type, now);
|
||||||
|
journal.accept(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- État ---
|
||||||
|
|
||||||
|
public String resume() {
|
||||||
|
long attente = Math.max(0, prochainEssaiMs - horloge.getAsLong());
|
||||||
|
return "Hub : " + file.taille() + " en attente, " + envoyees.get() + " envoyée(s) (" + doublons.get() + " doublons, "
|
||||||
|
+ refusees.get() + " refusées), " + perimees.get() + " périmées, " + file.abandonnees() + " perdues (file pleine), "
|
||||||
|
+ echecs + " échec(s) de suite"
|
||||||
|
+ (attente > 0 ? ", prochain essai dans " + attente / 1000 + " s" : "");
|
||||||
|
}
|
||||||
|
|
||||||
|
public long envoyees() {
|
||||||
|
return envoyees.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public long refusees() {
|
||||||
|
return refusees.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public long doublons() {
|
||||||
|
return doublons.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public long perimees() {
|
||||||
|
return perimees.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public long lotsRejetes() {
|
||||||
|
return lotsRejetes.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public int echecsDeSuite() {
|
||||||
|
return echecs;
|
||||||
|
}
|
||||||
|
|
||||||
|
public FileEnvoi file() {
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
package com.gastinelgarde.hub;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.ConcurrentLinkedDeque;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* File d'attente bornée des détections à envoyer. Sans verrou : {@link #ajouter} ne bloque jamais, même si le fil
|
||||||
|
* d'envoi est occupé ou bloqué sur le réseau (le tick serveur n'attend rien ici). Pleine, elle abandonne les plus
|
||||||
|
* anciennes (les récentes comptent le plus) et le compte.
|
||||||
|
*/
|
||||||
|
public final class FileEnvoi {
|
||||||
|
|
||||||
|
private final ConcurrentLinkedDeque<Detection> file = new ConcurrentLinkedDeque<>();
|
||||||
|
private final AtomicInteger taille = new AtomicInteger();
|
||||||
|
private final AtomicLong abandonnees = new AtomicLong();
|
||||||
|
private volatile int max;
|
||||||
|
|
||||||
|
public FileEnvoi(int max) {
|
||||||
|
this.max = Math.max(10, max);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void definirMax(int max) {
|
||||||
|
this.max = Math.max(10, max);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ajoute une détection (ne bloque jamais). Renvoie vrai si une plus ancienne a dû être abandonnée. */
|
||||||
|
public boolean ajouter(Detection d) {
|
||||||
|
file.addLast(d);
|
||||||
|
boolean abandon = false;
|
||||||
|
if (taille.incrementAndGet() > max) {
|
||||||
|
if (file.pollFirst() != null) {
|
||||||
|
taille.decrementAndGet();
|
||||||
|
abandonnees.incrementAndGet();
|
||||||
|
abandon = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return abandon;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retire au plus {@code n} détections, et au plus {@code octetsMax} octets de JSON (une détection au moins).
|
||||||
|
* Fil d'envoi seulement.
|
||||||
|
*/
|
||||||
|
public List<Detection> prendre(int n, int octetsMax) {
|
||||||
|
List<Detection> lot = new ArrayList<>(Math.min(n, 64));
|
||||||
|
int octets = 0;
|
||||||
|
while (lot.size() < n) {
|
||||||
|
Detection d = file.pollFirst();
|
||||||
|
if (d == null) break;
|
||||||
|
taille.decrementAndGet();
|
||||||
|
int t = d.json().getBytes(StandardCharsets.UTF_8).length + 1;
|
||||||
|
if (!lot.isEmpty() && octets + t > octetsMax) {
|
||||||
|
file.addFirst(d);
|
||||||
|
taille.incrementAndGet();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
lot.add(d);
|
||||||
|
octets += t;
|
||||||
|
}
|
||||||
|
return lot;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remet un lot non envoyé en tête, dans son ordre d'origine. */
|
||||||
|
public void remettre(List<Detection> lot) {
|
||||||
|
for (int i = lot.size() - 1; i >= 0; i--) {
|
||||||
|
file.addFirst(lot.get(i));
|
||||||
|
taille.incrementAndGet();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Retire les détections survenues avant {@code limiteMs}. Renvoie leur nombre. */
|
||||||
|
public int purgerAvant(long limiteMs) {
|
||||||
|
int n = 0;
|
||||||
|
for (Iterator<Detection> it = file.iterator(); it.hasNext();) {
|
||||||
|
Detection d = it.next();
|
||||||
|
if (d.survenueMs() < limiteMs) {
|
||||||
|
it.remove();
|
||||||
|
taille.decrementAndGet();
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ajouterTout(Collection<Detection> l) {
|
||||||
|
for (Detection d : l) ajouter(d);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Detection> instantane() {
|
||||||
|
return new ArrayList<>(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int taille() {
|
||||||
|
return Math.max(0, taille.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean vide() {
|
||||||
|
return file.isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public long abandonnees() {
|
||||||
|
return abandonnees.get();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package com.gastinelgarde.hub;
|
||||||
|
|
||||||
|
import com.gastinelgarde.core.Sanction;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Réglages du signalement au Hub. Valeurs par défaut : tout est coupé ({@code envoi = false}) ; rien ne part tant
|
||||||
|
* que Théo n'a pas activé, renseigné l'adresse et posé le fichier de clé.
|
||||||
|
*
|
||||||
|
* @param envoi interrupteur général (défaut : false)
|
||||||
|
* @param url adresse de base du Hub (réseau Docker interne), sans le chemin ; vide = pas d'envoi
|
||||||
|
* @param fichierCle fichier qui contient la clé de la source (jamais dans le fichier de réglages)
|
||||||
|
* @param envoyerObserve envoyer aussi les contrôles en OBSERVE (marqués {@code observe}, jamais comptés par le Hub)
|
||||||
|
* @param palierMin plus petit palier envoyé : ALERTE, SETBACK ou EXPULSION
|
||||||
|
* @param lotMax détections par requête (le Hub accepte 1 à 50)
|
||||||
|
* @param intervalleMs attente entre deux envois quand tout va bien
|
||||||
|
* @param fileMax détections gardées au plus ; au-delà, les plus anciennes sont abandonnées
|
||||||
|
* @param ageMaxMs âge au-delà duquel une détection n'est plus envoyée (le Hub refuse plus de 24 h)
|
||||||
|
* @param debitMaxParMinute détections envoyées au plus par minute (le Hub limite à 60 par défaut)
|
||||||
|
* @param episodeMs durée pendant laquelle un même palier d'un même contrôle n'est signalé qu'une fois
|
||||||
|
* @param delaiConnexionMs délai de connexion
|
||||||
|
* @param delaiRequeteMs délai total d'une requête
|
||||||
|
* @param coordonnees joindre la position arrondie au bloc et la dimension
|
||||||
|
* @param dossierEtat dossier de la file d'attente sur disque
|
||||||
|
*/
|
||||||
|
public record HubConfig(boolean envoi, String url, Path fichierCle, boolean envoyerObserve, Sanction palierMin,
|
||||||
|
int lotMax, long intervalleMs, int fileMax, long ageMaxMs, int debitMaxParMinute,
|
||||||
|
long episodeMs, int delaiConnexionMs, int delaiRequeteMs, boolean coordonnees,
|
||||||
|
Path dossierEtat) {
|
||||||
|
|
||||||
|
public static final String CHEMIN_API = "/internal/detections";
|
||||||
|
public static final long AGE_MAX_API_MS = 24L * 3600_000L;
|
||||||
|
|
||||||
|
public HubConfig {
|
||||||
|
if (palierMin == null || palierMin.ordinal() < Sanction.ALERTE.ordinal()) palierMin = Sanction.ALERTE;
|
||||||
|
lotMax = Math.max(1, Math.min(50, lotMax));
|
||||||
|
intervalleMs = Math.max(200, intervalleMs);
|
||||||
|
fileMax = Math.max(10, fileMax);
|
||||||
|
// le Hub refuse toute détection de plus de 24 h : inutile d'en garder (ni d'en renvoyer) plus longtemps
|
||||||
|
ageMaxMs = Math.max(60_000L, Math.min(ageMaxMs, AGE_MAX_API_MS - 3600_000L));
|
||||||
|
debitMaxParMinute = Math.max(1, debitMaxParMinute);
|
||||||
|
episodeMs = Math.max(1000, episodeMs);
|
||||||
|
delaiConnexionMs = Math.max(200, delaiConnexionMs);
|
||||||
|
delaiRequeteMs = Math.max(500, delaiRequeteMs);
|
||||||
|
url = url == null ? "" : url.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Tout coupé. */
|
||||||
|
public static HubConfig defaut(Path dossierEtat) {
|
||||||
|
return new HubConfig(false, "", Path.of("config", "gastinelgarde-hub.key"), false, Sanction.ALERTE,
|
||||||
|
50, 2000, 10_000, 23L * 3600_000L, 50, 600_000L, 3000, 5000, true, dossierEtat);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adresse complète de l'API, ou {@code null} si l'adresse de base est absente ou refusée (http/https seulement,
|
||||||
|
* pas d'identifiants dans l'adresse, ni paramètre, ni fragment).
|
||||||
|
*/
|
||||||
|
public URI adresseApi() {
|
||||||
|
if (url.isEmpty()) return null;
|
||||||
|
try {
|
||||||
|
URI u = URI.create(url);
|
||||||
|
String s = u.getScheme();
|
||||||
|
if (s == null || !(s.equalsIgnoreCase("http") || s.equalsIgnoreCase("https"))) return null;
|
||||||
|
if (u.getHost() == null || u.getUserInfo() != null || u.getRawQuery() != null || u.getRawFragment() != null) return null;
|
||||||
|
String base = url.endsWith("/") ? url.substring(0, url.length() - 1) : url;
|
||||||
|
return URI.create(base + CHEMIN_API);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package com.gastinelgarde.hub;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.attribute.PosixFilePermission;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lit la clé de la source dans son fichier (une ligne ; les lignes vides et celles qui commencent par # sont
|
||||||
|
* ignorées). La clé n'est jamais dans le fichier de réglages, jamais dans le code, jamais dans un message :
|
||||||
|
* les erreurs ci-dessous ne contiennent que le CHEMIN du fichier et une raison générale.
|
||||||
|
*/
|
||||||
|
public final class LecteurCle {
|
||||||
|
|
||||||
|
/** Le Hub exige au moins 32 caractères (modèle de relaykey.go). */
|
||||||
|
public static final int LONGUEUR_MIN = 32;
|
||||||
|
public static final int LONGUEUR_MAX = 256;
|
||||||
|
|
||||||
|
public enum Raison { OK, ABSENTE, ILLISIBLE, VIDE, TROP_COURTE, TROP_LONGUE, CARACTERES_INVALIDES }
|
||||||
|
|
||||||
|
/** La clé n'apparaît pas dans {@link #toString()}. */
|
||||||
|
public static final class Resultat {
|
||||||
|
private final Raison raison;
|
||||||
|
private final String cle;
|
||||||
|
private final boolean droitsTropLarges;
|
||||||
|
|
||||||
|
Resultat(Raison raison, String cle, boolean droitsTropLarges) {
|
||||||
|
this.raison = raison;
|
||||||
|
this.cle = cle;
|
||||||
|
this.droitsTropLarges = droitsTropLarges;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Raison raison() {
|
||||||
|
return raison;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean ok() {
|
||||||
|
return raison == Raison.OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** La clé (seulement si {@link #ok()}), à passer au transport et nulle part ailleurs. */
|
||||||
|
public String cle() {
|
||||||
|
return cle;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Vrai si le fichier est lisible par le groupe ou les autres (système POSIX seulement). */
|
||||||
|
public boolean droitsTropLarges() {
|
||||||
|
return droitsTropLarges;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Resultat[" + raison + "]";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private LecteurCle() { }
|
||||||
|
|
||||||
|
public static Resultat lire(Path fichier) {
|
||||||
|
if (fichier == null || !Files.isRegularFile(fichier)) return new Resultat(Raison.ABSENTE, null, false);
|
||||||
|
boolean large = false;
|
||||||
|
try {
|
||||||
|
Set<PosixFilePermission> p = Files.getPosixFilePermissions(fichier);
|
||||||
|
large = p.contains(PosixFilePermission.GROUP_READ) || p.contains(PosixFilePermission.OTHERS_READ)
|
||||||
|
|| p.contains(PosixFilePermission.GROUP_WRITE) || p.contains(PosixFilePermission.OTHERS_WRITE);
|
||||||
|
} catch (UnsupportedOperationException | IOException e) {
|
||||||
|
// pas de droits POSIX (Windows) : rien à signaler
|
||||||
|
}
|
||||||
|
List<String> lignes;
|
||||||
|
try {
|
||||||
|
if (Files.size(fichier) > 4096) return new Resultat(Raison.TROP_LONGUE, null, large);
|
||||||
|
lignes = Files.readAllLines(fichier, StandardCharsets.UTF_8);
|
||||||
|
} catch (IOException | RuntimeException e) {
|
||||||
|
return new Resultat(Raison.ILLISIBLE, null, large);
|
||||||
|
}
|
||||||
|
for (String l : lignes) {
|
||||||
|
String t = l.strip();
|
||||||
|
if (t.isEmpty() || t.startsWith("#")) continue;
|
||||||
|
if (t.length() < LONGUEUR_MIN) return new Resultat(Raison.TROP_COURTE, null, large);
|
||||||
|
if (t.length() > LONGUEUR_MAX) return new Resultat(Raison.TROP_LONGUE, null, large);
|
||||||
|
for (int i = 0; i < t.length(); i++) {
|
||||||
|
char c = t.charAt(i);
|
||||||
|
if (c < 0x21 || c > 0x7e) return new Resultat(Raison.CARACTERES_INVALIDES, null, large); // pas d'espace ni d'en-tête piégé
|
||||||
|
}
|
||||||
|
return new Resultat(Raison.OK, t, large);
|
||||||
|
}
|
||||||
|
return new Resultat(Raison.VIDE, null, large);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Phrase à mettre dans le journal : le chemin et la raison, jamais le contenu. */
|
||||||
|
public static String message(Path fichier, Raison r) {
|
||||||
|
return switch (r) {
|
||||||
|
case OK -> "clé lue";
|
||||||
|
case ABSENTE -> "fichier de clé absent : " + fichier;
|
||||||
|
case ILLISIBLE -> "fichier de clé illisible : " + fichier;
|
||||||
|
case VIDE -> "fichier de clé vide : " + fichier;
|
||||||
|
case TROP_COURTE -> "clé trop courte dans " + fichier + " (au moins " + LONGUEUR_MIN + " caractères)";
|
||||||
|
case TROP_LONGUE -> "clé trop longue dans " + fichier;
|
||||||
|
case CARACTERES_INVALIDES -> "clé avec des caractères non admis dans " + fichier;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
package com.gastinelgarde.hub;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* JSON minimal, sans dépendance (le cœur du client Hub reste du Java pur, testable sans Minecraft).
|
||||||
|
* Écriture : Map, List, String, Number, Boolean, null. Lecture : tout JSON valide, borné en taille et en profondeur
|
||||||
|
* (la réponse du Hub vient du réseau : on ne la croit pas).
|
||||||
|
*/
|
||||||
|
public final class MiniJson {
|
||||||
|
|
||||||
|
private static final int PROFONDEUR_MAX = 32;
|
||||||
|
private static final int TAILLE_MAX = 1 << 20;
|
||||||
|
|
||||||
|
private MiniJson() { }
|
||||||
|
|
||||||
|
// --- Écriture ---
|
||||||
|
|
||||||
|
public static String ecrire(Object o) {
|
||||||
|
StringBuilder sb = new StringBuilder(128);
|
||||||
|
ecrire(sb, o);
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ecrire(StringBuilder sb, Object o) {
|
||||||
|
if (o == null) {
|
||||||
|
sb.append("null");
|
||||||
|
} else if (o instanceof String s) {
|
||||||
|
chaine(sb, s);
|
||||||
|
} else if (o instanceof Boolean b) {
|
||||||
|
sb.append(b ? "true" : "false");
|
||||||
|
} else if (o instanceof Double || o instanceof Float) {
|
||||||
|
double d = ((Number) o).doubleValue();
|
||||||
|
if (Double.isNaN(d) || Double.isInfinite(d)) sb.append("null");
|
||||||
|
else sb.append(java.math.BigDecimal.valueOf(d).stripTrailingZeros().toPlainString());
|
||||||
|
} else if (o instanceof Number n) {
|
||||||
|
sb.append(n.toString());
|
||||||
|
} else if (o instanceof Map<?, ?> m) {
|
||||||
|
sb.append('{');
|
||||||
|
boolean premier = true;
|
||||||
|
for (Map.Entry<?, ?> e : m.entrySet()) {
|
||||||
|
if (!premier) sb.append(',');
|
||||||
|
premier = false;
|
||||||
|
chaine(sb, String.valueOf(e.getKey()));
|
||||||
|
sb.append(':');
|
||||||
|
ecrire(sb, e.getValue());
|
||||||
|
}
|
||||||
|
sb.append('}');
|
||||||
|
} else if (o instanceof Iterable<?> it) {
|
||||||
|
sb.append('[');
|
||||||
|
boolean premier = true;
|
||||||
|
for (Object x : it) {
|
||||||
|
if (!premier) sb.append(',');
|
||||||
|
premier = false;
|
||||||
|
ecrire(sb, x);
|
||||||
|
}
|
||||||
|
sb.append(']');
|
||||||
|
} else {
|
||||||
|
chaine(sb, o.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void chaine(StringBuilder sb, String s) {
|
||||||
|
sb.append('"');
|
||||||
|
for (int i = 0; i < s.length(); i++) {
|
||||||
|
char c = s.charAt(i);
|
||||||
|
switch (c) {
|
||||||
|
case '"' -> sb.append("\\\"");
|
||||||
|
case '\\' -> sb.append("\\\\");
|
||||||
|
case '\n' -> sb.append("\\n");
|
||||||
|
case '\r' -> sb.append("\\r");
|
||||||
|
case '\t' -> sb.append("\\t");
|
||||||
|
case '\b' -> sb.append("\\b");
|
||||||
|
case '\f' -> sb.append("\\f");
|
||||||
|
default -> {
|
||||||
|
if (c < 0x20 || c == 0x2028 || c == 0x2029) sb.append(String.format("\\u%04x", (int) c));
|
||||||
|
else sb.append(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sb.append('"');
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Lecture ---
|
||||||
|
|
||||||
|
/** Analyse un JSON complet. Lève {@link IllegalArgumentException} si invalide, trop gros ou trop profond. */
|
||||||
|
public static Object lire(String texte) {
|
||||||
|
if (texte == null) throw new IllegalArgumentException("texte absent");
|
||||||
|
if (texte.length() > TAILLE_MAX) throw new IllegalArgumentException("JSON trop gros");
|
||||||
|
Lecteur l = new Lecteur(texte);
|
||||||
|
l.espaces();
|
||||||
|
Object v = l.valeur(0);
|
||||||
|
l.espaces();
|
||||||
|
if (l.i != texte.length()) throw new IllegalArgumentException("texte après la valeur JSON");
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class Lecteur {
|
||||||
|
final String t;
|
||||||
|
int i;
|
||||||
|
|
||||||
|
Lecteur(String t) {
|
||||||
|
this.t = t;
|
||||||
|
}
|
||||||
|
|
||||||
|
void espaces() {
|
||||||
|
while (i < t.length()) {
|
||||||
|
char c = t.charAt(i);
|
||||||
|
if (c == ' ' || c == '\n' || c == '\r' || c == '\t') i++;
|
||||||
|
else break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
IllegalArgumentException erreur(String m) {
|
||||||
|
return new IllegalArgumentException(m + " (position " + i + ")");
|
||||||
|
}
|
||||||
|
|
||||||
|
Object valeur(int prof) {
|
||||||
|
if (prof > PROFONDEUR_MAX) throw erreur("JSON trop profond");
|
||||||
|
if (i >= t.length()) throw erreur("fin inattendue");
|
||||||
|
char c = t.charAt(i);
|
||||||
|
switch (c) {
|
||||||
|
case '{': return objet(prof);
|
||||||
|
case '[': return tableau(prof);
|
||||||
|
case '"': return chaine();
|
||||||
|
case 't': mot("true"); return Boolean.TRUE;
|
||||||
|
case 'f': mot("false"); return Boolean.FALSE;
|
||||||
|
case 'n': mot("null"); return null;
|
||||||
|
default: return nombre();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void mot(String m) {
|
||||||
|
if (!t.startsWith(m, i)) throw erreur("valeur inconnue");
|
||||||
|
i += m.length();
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> objet(int prof) {
|
||||||
|
Map<String, Object> m = new LinkedHashMap<>();
|
||||||
|
i++;
|
||||||
|
espaces();
|
||||||
|
if (i < t.length() && t.charAt(i) == '}') {
|
||||||
|
i++;
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
while (true) {
|
||||||
|
espaces();
|
||||||
|
if (i >= t.length() || t.charAt(i) != '"') throw erreur("clé attendue");
|
||||||
|
String k = chaine();
|
||||||
|
espaces();
|
||||||
|
if (i >= t.length() || t.charAt(i) != ':') throw erreur("':' attendu");
|
||||||
|
i++;
|
||||||
|
espaces();
|
||||||
|
m.put(k, valeur(prof + 1));
|
||||||
|
espaces();
|
||||||
|
if (i >= t.length()) throw erreur("fin inattendue");
|
||||||
|
char c = t.charAt(i++);
|
||||||
|
if (c == '}') return m;
|
||||||
|
if (c != ',') throw erreur("',' ou '}' attendu");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Object> tableau(int prof) {
|
||||||
|
List<Object> l = new ArrayList<>();
|
||||||
|
i++;
|
||||||
|
espaces();
|
||||||
|
if (i < t.length() && t.charAt(i) == ']') {
|
||||||
|
i++;
|
||||||
|
return l;
|
||||||
|
}
|
||||||
|
while (true) {
|
||||||
|
espaces();
|
||||||
|
l.add(valeur(prof + 1));
|
||||||
|
espaces();
|
||||||
|
if (i >= t.length()) throw erreur("fin inattendue");
|
||||||
|
char c = t.charAt(i++);
|
||||||
|
if (c == ']') return l;
|
||||||
|
if (c != ',') throw erreur("',' ou ']' attendu");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String chaine() {
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
i++; // guillemet ouvrant
|
||||||
|
while (true) {
|
||||||
|
if (i >= t.length()) throw erreur("chaîne non terminée");
|
||||||
|
char c = t.charAt(i++);
|
||||||
|
if (c == '"') return sb.toString();
|
||||||
|
if (c < 0x20) throw erreur("caractère de contrôle dans une chaîne");
|
||||||
|
if (c != '\\') {
|
||||||
|
sb.append(c);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (i >= t.length()) throw erreur("échappement incomplet");
|
||||||
|
char e = t.charAt(i++);
|
||||||
|
switch (e) {
|
||||||
|
case '"' -> sb.append('"');
|
||||||
|
case '\\' -> sb.append('\\');
|
||||||
|
case '/' -> sb.append('/');
|
||||||
|
case 'b' -> sb.append('\b');
|
||||||
|
case 'f' -> sb.append('\f');
|
||||||
|
case 'n' -> sb.append('\n');
|
||||||
|
case 'r' -> sb.append('\r');
|
||||||
|
case 't' -> sb.append('\t');
|
||||||
|
case 'u' -> {
|
||||||
|
if (i + 4 > t.length()) throw erreur("\\u incomplet");
|
||||||
|
try {
|
||||||
|
sb.append((char) Integer.parseInt(t.substring(i, i + 4), 16));
|
||||||
|
} catch (NumberFormatException ex) {
|
||||||
|
throw erreur("\\u invalide");
|
||||||
|
}
|
||||||
|
i += 4;
|
||||||
|
}
|
||||||
|
default -> throw erreur("échappement inconnu");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Number nombre() {
|
||||||
|
int debut = i;
|
||||||
|
while (i < t.length() && "+-0123456789.eE".indexOf(t.charAt(i)) >= 0) i++;
|
||||||
|
if (debut == i) throw erreur("valeur inattendue");
|
||||||
|
String s = t.substring(debut, i);
|
||||||
|
try {
|
||||||
|
if (s.indexOf('.') < 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) return Long.parseLong(s);
|
||||||
|
return Double.parseDouble(s);
|
||||||
|
} catch (NumberFormatException ex) {
|
||||||
|
throw erreur("nombre invalide");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package com.gastinelgarde.hub;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.TreeMap;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lecture de la réponse 200 du Hub : un résultat par détection (conception §2.3 : {@code cree}, {@code doublon},
|
||||||
|
* {@code refuse} + code). Le format exact du tableau n'est pas figé dans la conception ; on accepte donc un tableau
|
||||||
|
* à la racine ou un objet qui contient un tableau, et le statut sous plusieurs noms de champ. Une réponse 200
|
||||||
|
* illisible est tenue pour acceptée (HTTP 200 = lot pris en compte), jamais pour une raison de renvoyer.
|
||||||
|
*/
|
||||||
|
public record ReponseHub(int creees, int doublons, int refusees, Map<String, Integer> codesRefus, boolean lue) {
|
||||||
|
|
||||||
|
private static final String[] CLES_TABLEAU = {"resultats", "resultat", "results", "detections", "items"};
|
||||||
|
private static final String[] CLES_STATUT = {"statut", "status", "resultat", "etat", "result"};
|
||||||
|
private static final String[] CLES_CODE = {"code", "raison", "motif", "reason"};
|
||||||
|
|
||||||
|
public static ReponseHub analyser(String corps) {
|
||||||
|
try {
|
||||||
|
Object racine = MiniJson.lire(corps);
|
||||||
|
List<?> liste = null;
|
||||||
|
if (racine instanceof List<?> l) {
|
||||||
|
liste = l;
|
||||||
|
} else if (racine instanceof Map<?, ?> m) {
|
||||||
|
for (String k : CLES_TABLEAU) {
|
||||||
|
if (m.get(k) instanceof List<?> l) {
|
||||||
|
liste = l;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (liste == null) return new ReponseHub(0, 0, 0, Map.of(), false);
|
||||||
|
int c = 0;
|
||||||
|
int d = 0;
|
||||||
|
int r = 0;
|
||||||
|
Map<String, Integer> codes = new TreeMap<>();
|
||||||
|
for (Object o : liste) {
|
||||||
|
if (!(o instanceof Map<?, ?> m)) continue;
|
||||||
|
String statut = premier(m, CLES_STATUT);
|
||||||
|
if (statut == null) continue;
|
||||||
|
switch (statut.toLowerCase(java.util.Locale.ROOT)) {
|
||||||
|
case "cree", "created" -> c++;
|
||||||
|
case "doublon", "duplicate" -> d++;
|
||||||
|
case "refuse", "rejected" -> {
|
||||||
|
r++;
|
||||||
|
String code = premier(m, CLES_CODE);
|
||||||
|
codes.merge(code == null ? "inconnu" : borner(code), 1, Integer::sum);
|
||||||
|
}
|
||||||
|
default -> { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new ReponseHub(c, d, r, codes, true);
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
return new ReponseHub(0, 0, 0, Map.of(), false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String premier(Map<?, ?> m, String[] cles) {
|
||||||
|
for (String k : cles) {
|
||||||
|
if (m.get(k) instanceof String s) return s;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Le code vient du réseau et finit dans un journal : court et sans retour à la ligne. */
|
||||||
|
private static String borner(String s) {
|
||||||
|
String t = s.length() > 40 ? s.substring(0, 40) : s;
|
||||||
|
return t.replaceAll("[^A-Za-z0-9_.-]", "?");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,214 @@
|
|||||||
|
package com.gastinelgarde.hub;
|
||||||
|
|
||||||
|
import com.gastinelgarde.core.Controle;
|
||||||
|
import com.gastinelgarde.core.Mode;
|
||||||
|
import com.gastinelgarde.core.Sanction;
|
||||||
|
import com.gastinelgarde.core.Verdict;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
import java.util.function.LongSupplier;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Point d'entrée du signalement au Hub, appelé par GastinelGarde. Désactivé par défaut : tant que
|
||||||
|
* {@link #demarrer} n'a pas créé d'instance, {@link #surVerdict} ne fait qu'une lecture de variable.
|
||||||
|
*
|
||||||
|
* <p>Ce que le tick serveur paie quand c'est actif : une comparaison de palier (verrou très court) et, seulement
|
||||||
|
* à un franchissement, la construction d'une petite détection et un ajout sans verrou dans {@link FileEnvoi}.
|
||||||
|
* Aucune entrée-sortie, aucune attente, aucune exception ne remonte.
|
||||||
|
*/
|
||||||
|
public final class Signalement {
|
||||||
|
|
||||||
|
/** Position du joueur au moment des faits (fournie à la demande, seulement à un franchissement). */
|
||||||
|
public record Position(int x, int y, int z, String dimension) { }
|
||||||
|
|
||||||
|
private static volatile Signalement instance;
|
||||||
|
|
||||||
|
private final HubConfig cfg;
|
||||||
|
private final SuiviPaliers suivi;
|
||||||
|
private final FileEnvoi file;
|
||||||
|
private final EnvoiHub envoi;
|
||||||
|
private final String versionMod;
|
||||||
|
private final LongSupplier horloge;
|
||||||
|
private final Consumer<String> journal;
|
||||||
|
private volatile long dernierMessageBugMs;
|
||||||
|
|
||||||
|
private Signalement(HubConfig cfg, SuiviPaliers suivi, FileEnvoi file, EnvoiHub envoi, String versionMod,
|
||||||
|
LongSupplier horloge, Consumer<String> journal) {
|
||||||
|
this.cfg = cfg;
|
||||||
|
this.suivi = suivi;
|
||||||
|
this.file = file;
|
||||||
|
this.envoi = envoi;
|
||||||
|
this.versionMod = versionMod;
|
||||||
|
this.horloge = horloge;
|
||||||
|
this.journal = journal;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Cycle de vie ---
|
||||||
|
|
||||||
|
public static boolean actif() {
|
||||||
|
return instance != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* (Re)démarre le signalement selon ces réglages. Ne démarre RIEN (et le dit au journal) si l'envoi est coupé, si
|
||||||
|
* l'adresse est absente ou refusée, ou si la clé est absente, illisible ou trop courte. Peut être rappelé à chaque
|
||||||
|
* rechargement de la configuration : l'instance précédente est arrêtée et sa file écrite sur disque d'abord.
|
||||||
|
*/
|
||||||
|
public static synchronized void demarrer(HubConfig cfg, Path fichierCle, Transport transport, LongSupplier horloge,
|
||||||
|
Consumer<String> journal, String versionMod) {
|
||||||
|
arreter();
|
||||||
|
if (!cfg.envoi()) {
|
||||||
|
journal.accept("Hub : envoi des détections désactivé (hub.envoi = false).");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
URI api = cfg.adresseApi();
|
||||||
|
if (api == null) {
|
||||||
|
journal.accept("Hub : adresse absente ou refusée (http/https sans identifiants), envoi désactivé.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
LecteurCle.Resultat k = LecteurCle.lire(fichierCle);
|
||||||
|
if (!k.ok()) {
|
||||||
|
journal.accept("Hub : " + LecteurCle.message(fichierCle, k.raison()) + ". Envoi désactivé.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (k.droitsTropLarges()) {
|
||||||
|
journal.accept("Hub : ATTENTION, le fichier de clé est lisible par d'autres comptes : " + fichierCle
|
||||||
|
+ " (le protéger, par exemple chmod 600).");
|
||||||
|
}
|
||||||
|
FileEnvoi file = new FileEnvoi(cfg.fileMax());
|
||||||
|
EnvoiHub envoi = new EnvoiHub(cfg, k.cle(), transport, file, horloge, journal);
|
||||||
|
Signalement s = new Signalement(cfg, new SuiviPaliers(cfg.episodeMs(), cfg.palierMin()), file, envoi,
|
||||||
|
Assainir.versionMod(versionMod),
|
||||||
|
horloge, journal);
|
||||||
|
envoi.demarrer();
|
||||||
|
instance = s;
|
||||||
|
journal.accept("Hub : envoi des détections actif vers " + api.getScheme() + "://" + api.getHost()
|
||||||
|
+ (api.getPort() > 0 ? ":" + api.getPort() : "") + " (palier minimum " + cfg.palierMin()
|
||||||
|
+ (cfg.envoyerObserve() ? ", contrôles en OBSERVE inclus" : ", contrôles en ENFORCE seulement") + ").");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Réglages de production : transport HTTP du JDK, horloge système. */
|
||||||
|
public static void demarrer(HubConfig cfg, Path fichierCle, Consumer<String> journal, String versionMod) {
|
||||||
|
String version = Assainir.versionMod(versionMod); // sert aussi d'en-tête User-Agent : jamais de caractère piégé
|
||||||
|
demarrer(cfg, fichierCle, new Transport.Http(cfg.delaiConnexionMs(), cfg.delaiRequeteMs(), version),
|
||||||
|
System::currentTimeMillis, journal, version);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static synchronized void arreter() {
|
||||||
|
Signalement s = instance;
|
||||||
|
instance = null;
|
||||||
|
if (s != null) s.envoi.arreter();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Appel depuis GastinelGarde ---
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Examine un verdict. Si c'est un franchissement de palier à signaler, met une détection en file. Ne bloque
|
||||||
|
* jamais, ne lève jamais d'exception.
|
||||||
|
*
|
||||||
|
* @param position fournie à la demande (appelée seulement si une détection est créée, et seulement si le
|
||||||
|
* réglage « coordonnées » est actif)
|
||||||
|
*/
|
||||||
|
public static void surVerdict(UUID joueur, Verdict v, Supplier<Position> position) {
|
||||||
|
Signalement s = instance;
|
||||||
|
if (s == null) return;
|
||||||
|
try {
|
||||||
|
s.examiner(joueur, v, position);
|
||||||
|
} catch (Throwable t) {
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
if (now - s.dernierMessageBugMs > 300_000) {
|
||||||
|
s.dernierMessageBugMs = now;
|
||||||
|
s.journal.accept("Hub : erreur lors du signalement (" + t.getClass().getSimpleName() + "), ignorée.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void joueurParti(UUID joueur) {
|
||||||
|
Signalement s = instance;
|
||||||
|
if (s != null) s.suivi.oublier(joueur);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String resume() {
|
||||||
|
Signalement s = instance;
|
||||||
|
return s == null ? "Hub : envoi désactivé." : s.envoi.resume();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Interne ---
|
||||||
|
|
||||||
|
private void examiner(UUID joueur, Verdict v, Supplier<Position> position) {
|
||||||
|
if (v.mode() == Mode.OFF) return;
|
||||||
|
boolean observe = v.mode() == Mode.OBSERVE;
|
||||||
|
if (observe && !cfg.envoyerObserve()) return;
|
||||||
|
// ENFORCE : la sanction réellement appliquée ; OBSERVE : le palier mérité (rien n'est appliqué, c'est une information)
|
||||||
|
Sanction palier = observe ? v.palier() : v.applicable();
|
||||||
|
int gravite = gravite(palier);
|
||||||
|
if (gravite == 0) return;
|
||||||
|
String controle = Assainir.controle(v.controle().id());
|
||||||
|
if (controle == null) return; // identifiant de contrôle inexploitable : pas de signalement plutôt qu'un refus du Hub
|
||||||
|
long now = horloge.getAsLong();
|
||||||
|
if (!suivi.franchit(joueur, v.controle(), palier, now)) return;
|
||||||
|
|
||||||
|
Map<String, Object> details = new LinkedHashMap<>();
|
||||||
|
details.put("controle", controle);
|
||||||
|
details.put("palier", numeroPalier(palier));
|
||||||
|
List<String> ex = Assainir.exemptions(v.exemptions());
|
||||||
|
if (!ex.isEmpty()) details.put("exemptions", ex);
|
||||||
|
details.put("version_mod", versionMod);
|
||||||
|
if (cfg.coordonnees() && position != null) {
|
||||||
|
Position p = position.get();
|
||||||
|
if (p != null) {
|
||||||
|
details.put("x", p.x());
|
||||||
|
details.put("y", p.y());
|
||||||
|
details.put("z", p.z());
|
||||||
|
String dim = Assainir.dimension(p.dimension());
|
||||||
|
if (dim != null) details.put("dimension", dim);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String id = joueur + ":" + controle + ":" + palier.name().toLowerCase(java.util.Locale.ROOT) + ":" + now;
|
||||||
|
file.ajouter(new Detection(id, joueur.toString(), controle, gravite,
|
||||||
|
observe ? "observe" : "enforce", v.vl(), now, details));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Numéro envoyé dans {@code details.palier} (entier, 0 à 100 côté Hub) : rang de la sanction, ALERTE = 2 … EXPULSION = 4. */
|
||||||
|
static int numeroPalier(Sanction palier) {
|
||||||
|
return palier == null ? 0 : palier.ordinal();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** ALERTE = 1, SETBACK = 2, EXPULSION = 3 ; les autres paliers ne sont pas signalés. */
|
||||||
|
static int gravite(Sanction palier) {
|
||||||
|
if (palier == null) return 0;
|
||||||
|
return switch (palier) {
|
||||||
|
case ALERTE -> 1;
|
||||||
|
case SETBACK -> 2;
|
||||||
|
case EXPULSION -> 3;
|
||||||
|
default -> 0;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pour les tests. */
|
||||||
|
static Signalement instanceCourante() {
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
EnvoiHub envoi() {
|
||||||
|
return envoi;
|
||||||
|
}
|
||||||
|
|
||||||
|
FileEnvoi file() {
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pour les tests : les 15 contrôles que le Hub doit accepter comme types. */
|
||||||
|
public static List<String> typesAttendus() {
|
||||||
|
List<String> l = new ArrayList<>();
|
||||||
|
for (Controle c : Controle.values()) l.add(c.id());
|
||||||
|
return l;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package com.gastinelgarde.hub;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.StandardCopyOption;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Copie sur disque de la file d'attente (une détection par ligne, au format de l'API). Écrite par le fil d'envoi
|
||||||
|
* seulement (jamais par le tick) quand le Hub ne répond pas et à l'arrêt du serveur ; relue au démarrage. Contient
|
||||||
|
* des UUID de joueurs et des positions : donnée personnelle, d'où l'âge maximal et l'effacement dès que tout est
|
||||||
|
* accusé. Ne contient jamais la clé.
|
||||||
|
*/
|
||||||
|
public final class Spool {
|
||||||
|
|
||||||
|
private final Path fichier;
|
||||||
|
|
||||||
|
public Spool(Path fichier) {
|
||||||
|
this.fichier = fichier;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Path fichier() {
|
||||||
|
return fichier;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remplace le contenu par ces détections (écriture atomique) ; liste vide = fichier supprimé. */
|
||||||
|
public void ecrire(List<Detection> l) throws IOException {
|
||||||
|
if (l.isEmpty()) {
|
||||||
|
supprimer();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Files.createDirectories(fichier.toAbsolutePath().getParent());
|
||||||
|
Path tmp = fichier.resolveSibling(fichier.getFileName() + ".tmp");
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
for (Detection d : l) sb.append(d.json()).append('\n');
|
||||||
|
Files.writeString(tmp, sb.toString(), StandardCharsets.UTF_8);
|
||||||
|
try {
|
||||||
|
Files.move(tmp, fichier, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
|
||||||
|
} catch (java.nio.file.AtomicMoveNotSupportedException e) {
|
||||||
|
Files.move(tmp, fichier, StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Relit les détections valides plus récentes que {@code limiteMs} ; les lignes illisibles sont ignorées. */
|
||||||
|
public List<Detection> lire(long limiteMs) {
|
||||||
|
List<Detection> sortie = new ArrayList<>();
|
||||||
|
if (!Files.isRegularFile(fichier)) return sortie;
|
||||||
|
try {
|
||||||
|
for (String ligne : Files.readAllLines(fichier, StandardCharsets.UTF_8)) {
|
||||||
|
if (ligne.isBlank()) continue;
|
||||||
|
try {
|
||||||
|
Detection d = Detection.depuisJson(MiniJson.lire(ligne));
|
||||||
|
if (d.survenueMs() >= limiteMs) sortie.add(d);
|
||||||
|
} catch (RuntimeException ignoree) {
|
||||||
|
// ligne abîmée (coupure pendant l'écriture) : on continue avec les suivantes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
// fichier illisible : on repart d'une file vide
|
||||||
|
}
|
||||||
|
return sortie;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void supprimer() throws IOException {
|
||||||
|
Files.deleteIfExists(fichier);
|
||||||
|
Files.deleteIfExists(fichier.resolveSibling(fichier.getFileName() + ".tmp"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean existe() {
|
||||||
|
return Files.exists(fichier);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package com.gastinelgarde.hub;
|
||||||
|
|
||||||
|
import com.gastinelgarde.core.Controle;
|
||||||
|
import com.gastinelgarde.core.Sanction;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Décide si un verdict est un « franchissement de palier » à signaler au Hub : le Hub ne reçoit pas chaque
|
||||||
|
* infraction (conception §0), seulement le moment où un joueur atteint, pour un contrôle donné, un palier plus
|
||||||
|
* élevé que celui déjà signalé pendant l'épisode en cours.
|
||||||
|
*
|
||||||
|
* Un épisode dure {@code episodeMs} depuis le premier signalement ; ensuite la mémoire s'efface. Ainsi un joueur
|
||||||
|
* qui enchaîne les setbacks produit au plus 3 signalements (alerte, setback, expulsion) par contrôle et par épisode,
|
||||||
|
* et non un par infraction.
|
||||||
|
*/
|
||||||
|
public final class SuiviPaliers {
|
||||||
|
|
||||||
|
private record Cle(UUID joueur, Controle controle) { }
|
||||||
|
|
||||||
|
private static final class Episode {
|
||||||
|
Sanction signale;
|
||||||
|
long debutMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final int ENTREES_MAX = 4096;
|
||||||
|
|
||||||
|
private final long episodeMs;
|
||||||
|
private final Sanction palierMin;
|
||||||
|
private final Map<Cle, Episode> episodes = new HashMap<>();
|
||||||
|
|
||||||
|
public SuiviPaliers(long episodeMs, Sanction palierMin) {
|
||||||
|
this.episodeMs = episodeMs;
|
||||||
|
this.palierMin = palierMin;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Vrai si ce verdict doit être signalé ; enregistre alors le palier signalé. Thread-safe. */
|
||||||
|
public synchronized boolean franchit(UUID joueur, Controle controle, Sanction palier, long nowMs) {
|
||||||
|
if (palier == null || palier.ordinal() < palierMin.ordinal()) return false;
|
||||||
|
Cle cle = new Cle(joueur, controle);
|
||||||
|
Episode e = episodes.get(cle);
|
||||||
|
if (e != null && nowMs - e.debutMs > episodeMs) {
|
||||||
|
episodes.remove(cle);
|
||||||
|
e = null;
|
||||||
|
}
|
||||||
|
if (e == null) {
|
||||||
|
if (episodes.size() >= ENTREES_MAX) nettoyer(nowMs);
|
||||||
|
e = new Episode();
|
||||||
|
e.signale = palier;
|
||||||
|
e.debutMs = nowMs;
|
||||||
|
episodes.put(cle, e);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (palier.ordinal() > e.signale.ordinal()) {
|
||||||
|
e.signale = palier;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Oublie un joueur (déconnexion). */
|
||||||
|
public synchronized void oublier(UUID joueur) {
|
||||||
|
episodes.keySet().removeIf(k -> k.joueur().equals(joueur));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void nettoyer(long nowMs) {
|
||||||
|
for (Iterator<Episode> it = episodes.values().iterator(); it.hasNext();) {
|
||||||
|
if (nowMs - it.next().debutMs > episodeMs) it.remove();
|
||||||
|
}
|
||||||
|
if (episodes.size() >= ENTREES_MAX) episodes.clear(); // garde-fou mémoire : mieux vaut un doublon qu'une fuite
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized int taille() {
|
||||||
|
return episodes.size();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package com.gastinelgarde.hub;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.OptionalLong;
|
||||||
|
|
||||||
|
/** Envoi d'un lot au Hub. Interface pour pouvoir la remplacer dans les tests. */
|
||||||
|
public interface Transport {
|
||||||
|
|
||||||
|
/** Réponse HTTP : statut, corps (borné) et {@code Retry-After} en secondes s'il est présent. */
|
||||||
|
record Reponse(int statut, String corps, OptionalLong retryAfterSec) { }
|
||||||
|
|
||||||
|
/** Envoie le corps JSON. Lève {@link IOException} pour toute panne réseau (connexion, délai, coupure). */
|
||||||
|
Reponse envoyer(URI adresse, String cle, String corpsJson) throws IOException, InterruptedException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Implémentation JDK ({@code java.net.http}). Aucune redirection n'est suivie (la clé ne doit pas partir
|
||||||
|
* ailleurs), délais courts, réponse lue sur 64 Kio au plus.
|
||||||
|
*/
|
||||||
|
final class Http implements Transport {
|
||||||
|
|
||||||
|
private static final int REPONSE_MAX = 64 * 1024;
|
||||||
|
|
||||||
|
private final HttpClient client;
|
||||||
|
private final Duration delaiRequete;
|
||||||
|
private final String agent;
|
||||||
|
|
||||||
|
public Http(int delaiConnexionMs, int delaiRequeteMs, String versionMod) {
|
||||||
|
this.client = HttpClient.newBuilder()
|
||||||
|
.connectTimeout(Duration.ofMillis(delaiConnexionMs))
|
||||||
|
.followRedirects(HttpClient.Redirect.NEVER)
|
||||||
|
.version(HttpClient.Version.HTTP_1_1)
|
||||||
|
.build();
|
||||||
|
this.delaiRequete = Duration.ofMillis(delaiRequeteMs);
|
||||||
|
this.agent = "GastinelGarde/" + versionMod;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Reponse envoyer(URI adresse, String cle, String corpsJson) throws IOException, InterruptedException {
|
||||||
|
HttpRequest rq = HttpRequest.newBuilder(adresse)
|
||||||
|
.timeout(delaiRequete)
|
||||||
|
.header("Content-Type", "application/json; charset=utf-8")
|
||||||
|
.header("Accept", "application/json")
|
||||||
|
.header("X-Source-Cle", cle)
|
||||||
|
.header("User-Agent", agent)
|
||||||
|
.POST(HttpRequest.BodyPublishers.ofString(corpsJson, StandardCharsets.UTF_8))
|
||||||
|
.build();
|
||||||
|
HttpResponse<InputStream> r = client.send(rq, HttpResponse.BodyHandlers.ofInputStream());
|
||||||
|
String corps;
|
||||||
|
try (InputStream in = r.body()) {
|
||||||
|
corps = new String(in.readNBytes(REPONSE_MAX), StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
OptionalLong ra = OptionalLong.empty();
|
||||||
|
String h = r.headers().firstValue("Retry-After").orElse(null);
|
||||||
|
if (h != null) {
|
||||||
|
try {
|
||||||
|
ra = OptionalLong.of(Math.max(0, Long.parseLong(h.trim())));
|
||||||
|
} catch (NumberFormatException ignoree) {
|
||||||
|
// date HTTP ou valeur illisible : on retombe sur l'attente exponentielle
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Reponse(r.statusCode(), corps, ra);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
package com.gastinelgarde.hub;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import com.gastinelgarde.core.Controle;
|
||||||
|
import com.gastinelgarde.core.Sanction;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** Conformité aux contraintes du Hub : motifs des champs texte, aucune adresse IP, clés de details en liste blanche. */
|
||||||
|
class ContratHubTest {
|
||||||
|
|
||||||
|
private static final String UUID_J = "123e4567-e89b-12d3-a456-426614174000";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void tousLesControlesDuModSontAcceptesTelsQuels() {
|
||||||
|
for (Controle c : Controle.values()) {
|
||||||
|
assertEquals(c.id(), Assainir.controle(c.id()), c.id());
|
||||||
|
assertTrue(Assainir.TYPE_DETECTION.matcher(c.id()).matches(), "type Hub : " + c.id());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void controleEtDimensionNonConformesSontCorriges() {
|
||||||
|
assertEquals("killaura_angle_", Assainir.controle("KillAura Angle!"));
|
||||||
|
assertEquals("minecraft:overworld", Assainir.dimension("minecraft:overworld"));
|
||||||
|
assertEquals("monmod:aether_ciel", Assainir.dimension("monmod:aether/ciel"));
|
||||||
|
assertEquals("monmod:aether_ciel", Assainir.dimension("MonMod:Aether/Ciel"));
|
||||||
|
assertEquals(64, Assainir.dimension("a".repeat(200)).length());
|
||||||
|
assertNull(Assainir.controle(""));
|
||||||
|
assertNull(Assainir.controle(null));
|
||||||
|
assertNull(Assainir.dimension(" "));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void uneDimensionOuUnControleQuiRessembleAUneAdresseEstOmis() {
|
||||||
|
assertNull(Assainir.controle("192.0.2.10"));
|
||||||
|
assertNull(Assainir.dimension("2001:db8::1"));
|
||||||
|
assertNull(Assainir.controle("x10.1.2.3x"));
|
||||||
|
assertTrue(Assainir.ressembleAdresseIp("2001:db8::/32"));
|
||||||
|
assertTrue(Assainir.ressembleAdresseIp("::1"));
|
||||||
|
assertTrue(Assainir.ressembleAdresseIp("a 198.51.100.7 b"));
|
||||||
|
assertFalse(Assainir.ressembleAdresseIp("minecraft:overworld"));
|
||||||
|
assertFalse(Assainir.ressembleAdresseIp("0.3.2"));
|
||||||
|
assertFalse(Assainir.ressembleAdresseIp("1.21.1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void versionDuMod() {
|
||||||
|
assertEquals("0.3.2", Assainir.versionMod("0.3.2"));
|
||||||
|
assertEquals("0.3.2-beta.1+abc", Assainir.versionMod("0.3.2-beta.1+abc"));
|
||||||
|
assertEquals("0.3.2-x", Assainir.versionMod("0.3.2 x"));
|
||||||
|
assertEquals("inconnue", Assainir.versionMod(null));
|
||||||
|
assertEquals("inconnue", Assainir.versionMod(""));
|
||||||
|
assertEquals("inconnue", Assainir.versionMod("192.0.2.1"));
|
||||||
|
assertEquals(32, Assainir.versionMod("1".repeat(100)).length());
|
||||||
|
// saut de ligne dans une version : jamais de caractère piégé (elle sert aussi d'en-tête User-Agent)
|
||||||
|
assertTrue(Assainir.VERSION_MOD.matcher(Assainir.versionMod("1.0\r\nX-Evil: 1")).matches());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void exemptionsConformesEtBornees() {
|
||||||
|
List<String> entree = new ArrayList<>(List.of("creatif", "peut-voler", "Chute Lente", "teleportation", "creatif",
|
||||||
|
"198.51.100.9", "", "x".repeat(50)));
|
||||||
|
for (int i = 0; i < 20; i++) entree.add("raison" + i);
|
||||||
|
List<String> sortie = Assainir.exemptions(entree);
|
||||||
|
assertEquals(Assainir.EXEMPTIONS_MAX, sortie.size());
|
||||||
|
assertEquals(List.of("creatif", "peut-voler", "chute_lente", "teleportation"), sortie.subList(0, 4));
|
||||||
|
assertFalse(sortie.contains("198.51.100.9"));
|
||||||
|
for (String e : sortie) assertTrue(Assainir.EXEMPTION.matcher(e).matches(), e);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void detailsGardeSeulementLaListeBlanche() {
|
||||||
|
Map<String, Object> d = new LinkedHashMap<>();
|
||||||
|
d.put("controle", "portee");
|
||||||
|
d.put("palier", 3);
|
||||||
|
d.put("x", 120);
|
||||||
|
d.put("y", 64);
|
||||||
|
d.put("z", -5000);
|
||||||
|
d.put("dimension", "minecraft:the_nether");
|
||||||
|
d.put("version_mod", "0.3.2");
|
||||||
|
d.put("exemptions", List.of("creatif"));
|
||||||
|
d.put("pseudo", "Steve");
|
||||||
|
d.put("ip", "198.51.100.7");
|
||||||
|
d.put("chat", "salut");
|
||||||
|
Map<String, Object> propre = Assainir.details(d);
|
||||||
|
assertEquals(List.of("controle", "palier", "exemptions", "version_mod", "x", "y", "z", "dimension"),
|
||||||
|
new ArrayList<>(propre.keySet()));
|
||||||
|
assertEquals(3L, propre.get("palier"));
|
||||||
|
assertEquals(-5000L, propre.get("z"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void detailsRetireLesValeursMalFormees() {
|
||||||
|
Map<String, Object> d = new LinkedHashMap<>();
|
||||||
|
d.put("controle", "portee");
|
||||||
|
d.put("palier", "alerte"); // le Hub veut un entier
|
||||||
|
d.put("x", 1.5); // pas un entier
|
||||||
|
d.put("y", 99_000_000L); // hors bornes
|
||||||
|
d.put("z", Double.NaN);
|
||||||
|
d.put("dimension", 12);
|
||||||
|
d.put("version_mod", "1.0 \n");
|
||||||
|
d.put("exemptions", "creatif"); // pas une liste
|
||||||
|
Map<String, Object> propre = Assainir.details(d);
|
||||||
|
assertEquals(List.of("controle"), new ArrayList<>(propre.keySet()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void uneAdresseDansUnChampTexteNePasseJamais() {
|
||||||
|
Map<String, Object> d = new LinkedHashMap<>();
|
||||||
|
d.put("controle", "portee");
|
||||||
|
d.put("version_mod", "10.1.2.3");
|
||||||
|
d.put("dimension", "2001:db8:0:1::5");
|
||||||
|
d.put("exemptions", List.of("192.0.2.1", "creatif"));
|
||||||
|
Map<String, Object> propre = Assainir.details(d);
|
||||||
|
String json = MiniJson.ecrire(propre);
|
||||||
|
assertFalse(Assainir.ressembleAdresseIp(json.replace("\"", " ")), json);
|
||||||
|
assertEquals(List.of("creatif"), propre.get("exemptions"));
|
||||||
|
assertFalse(propre.containsKey("version_mod"));
|
||||||
|
assertFalse(propre.containsKey("dimension"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void detectionRefuseUnIdentifiantOuUnTypeHorsContrat() {
|
||||||
|
Map<String, Object> d = Map.of();
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new Detection("court", UUID_J, "portee", 1, "enforce", 1, 0, d));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new Detection("a b c d e f g h", UUID_J, "portee", 1, "enforce", 1, 0, d));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new Detection("x".repeat(129), UUID_J, "portee", 1, "enforce", 1, 0, d));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new Detection("identifiant-ok", UUID_J, "Portee!", 1, "enforce", 1, 0, d));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new Detection("identifiant-ok", "pas-un-uuid", "portee", 1, "enforce", 1, 0, d));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new Detection("identifiant-ok", UUID_J, "portee", 4, "enforce", 1, 0, d));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new Detection("identifiant-ok", UUID_J, "portee", 1, "ban", 1, 0, d));
|
||||||
|
new Detection("identifiant-ok", UUID_J, "portee", 1, "enforce", 1, 0, d);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void detectionBorneLesPoints() {
|
||||||
|
assertEquals(0.0, new Detection("identifiant-ok", UUID_J, "portee", 1, "enforce", -5, 0, Map.of()).points());
|
||||||
|
assertEquals(99_999.0, new Detection("identifiant-ok", UUID_J, "portee", 1, "enforce", 1e9, 0, Map.of()).points());
|
||||||
|
assertEquals(0.0, new Detection("identifiant-ok", UUID_J, "portee", 1, "enforce", Double.NaN, 0, Map.of()).points());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void jsonEnvoyeSansChampServiceNiSourceEtAvecHorodatageRfc3339() {
|
||||||
|
Detection d = new Detection("identifiant-ok", UUID_J, "portee", 2, "enforce", 7.126, 1_760_000_000_123L,
|
||||||
|
Map.of("controle", "portee"));
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Map<String, Object> m = (Map<String, Object>) MiniJson.lire(d.json());
|
||||||
|
assertEquals(List.of("id_externe", "sujet", "type", "gravite", "mode", "points", "survenue_le", "details"),
|
||||||
|
new ArrayList<>(m.keySet()));
|
||||||
|
assertEquals("2025-10-09T08:53:20Z", m.get("survenue_le"));
|
||||||
|
assertEquals(7.13, ((Number) m.get("points")).doubleValue(), 1e-9);
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Map<String, Object> sujet = (Map<String, Object>) m.get("sujet");
|
||||||
|
assertEquals("uuid_minecraft", sujet.get("type"));
|
||||||
|
assertEquals(UUID_J, sujet.get("valeur"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void relectureDuDisqueRefiltreLesDetails() {
|
||||||
|
String json = "{\"id_externe\":\"identifiant-ok\",\"sujet\":{\"type\":\"uuid_minecraft\",\"valeur\":\"" + UUID_J
|
||||||
|
+ "\"},\"type\":\"portee\",\"gravite\":1,\"mode\":\"enforce\",\"points\":1.0,"
|
||||||
|
+ "\"survenue_le\":\"2026-10-19T10:00:00Z\",\"details\":{\"controle\":\"portee\",\"ip\":\"198.51.100.7\","
|
||||||
|
+ "\"pseudo\":\"Steve\"}}";
|
||||||
|
Detection d = Detection.depuisJson(MiniJson.lire(json));
|
||||||
|
assertEquals(List.of("controle"), new ArrayList<>(d.details().keySet()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void graviteEtPalierNumerotes() {
|
||||||
|
assertEquals(0, Signalement.gravite(Sanction.AUCUNE));
|
||||||
|
assertEquals(0, Signalement.gravite(Sanction.JOURNAL));
|
||||||
|
assertEquals(1, Signalement.gravite(Sanction.ALERTE));
|
||||||
|
assertEquals(2, Signalement.gravite(Sanction.SETBACK));
|
||||||
|
assertEquals(3, Signalement.gravite(Sanction.EXPULSION));
|
||||||
|
assertEquals(2, Signalement.numeroPalier(Sanction.ALERTE));
|
||||||
|
assertEquals(4, Signalement.numeroPalier(Sanction.EXPULSION));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,445 @@
|
|||||||
|
package com.gastinelgarde.hub;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import com.gastinelgarde.core.Sanction;
|
||||||
|
import com.sun.net.httpserver.HttpServer;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||||
|
import java.util.concurrent.CopyOnWriteArrayList;
|
||||||
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Envoi réel (java.net.http) vers un FAUX serveur HTTP local, hors ligne : aucune connexion hors de cette machine.
|
||||||
|
* Le fil d'envoi n'est pas lancé : on appelle {@link EnvoiHub#cycle()} avec une horloge simulée, pour des essais
|
||||||
|
* exacts et sans attente.
|
||||||
|
*/
|
||||||
|
class EnvoiHubServeurTest {
|
||||||
|
|
||||||
|
/** Clé factice des essais. Pas une vraie clé. */
|
||||||
|
static final String CLE = "cle-de-test-0123456789-0123456789-ABCDEF";
|
||||||
|
|
||||||
|
/** Une requête reçue par le faux Hub. */
|
||||||
|
record Recue(String methode, String chemin, String cle, String contentType, String corps) { }
|
||||||
|
|
||||||
|
/** Réponse programmée : statut, corps, en-tête Retry-After facultatif, délai facultatif. */
|
||||||
|
record Reponse(int statut, String corps, String retryAfter, long delaiMs) {
|
||||||
|
static Reponse ok(String corps) {
|
||||||
|
return new Reponse(200, corps, null, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static Reponse statut(int s) {
|
||||||
|
return new Reponse(s, "{}", null, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
HttpServer serveur;
|
||||||
|
final List<Recue> recues = new CopyOnWriteArrayList<>();
|
||||||
|
final ConcurrentLinkedQueue<Reponse> scenario = new ConcurrentLinkedQueue<>();
|
||||||
|
volatile Reponse parDefaut = Reponse.ok("{\"resultats\":[]}");
|
||||||
|
final AtomicLong horloge = new AtomicLong(1_760_000_000_000L);
|
||||||
|
final List<String> journal = new CopyOnWriteArrayList<>();
|
||||||
|
String url;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void demarrerFauxHub() throws IOException {
|
||||||
|
serveur = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
|
||||||
|
serveur.createContext("/", ex -> {
|
||||||
|
byte[] corps = ex.getRequestBody().readAllBytes();
|
||||||
|
recues.add(new Recue(ex.getRequestMethod(), ex.getRequestURI().getPath(),
|
||||||
|
ex.getRequestHeaders().getFirst("X-Source-Cle"), ex.getRequestHeaders().getFirst("Content-Type"),
|
||||||
|
new String(corps, StandardCharsets.UTF_8)));
|
||||||
|
Reponse r = scenario.poll();
|
||||||
|
if (r == null) r = parDefaut;
|
||||||
|
if (r.delaiMs() > 0) {
|
||||||
|
try {
|
||||||
|
Thread.sleep(r.delaiMs());
|
||||||
|
} catch (InterruptedException ignoree) {
|
||||||
|
// fin de l'essai
|
||||||
|
}
|
||||||
|
}
|
||||||
|
byte[] sortie = r.corps().getBytes(StandardCharsets.UTF_8);
|
||||||
|
if (r.retryAfter() != null) ex.getResponseHeaders().add("Retry-After", r.retryAfter());
|
||||||
|
ex.getResponseHeaders().add("Content-Type", "application/json");
|
||||||
|
try {
|
||||||
|
ex.sendResponseHeaders(r.statut(), sortie.length);
|
||||||
|
try (OutputStream os = ex.getResponseBody()) {
|
||||||
|
os.write(sortie);
|
||||||
|
}
|
||||||
|
} catch (IOException ignoree) {
|
||||||
|
// client parti (délai dépassé)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
serveur.setExecutor(java.util.concurrent.Executors.newCachedThreadPool(r -> {
|
||||||
|
Thread t = new Thread(r, "faux-hub");
|
||||||
|
t.setDaemon(true);
|
||||||
|
return t;
|
||||||
|
}));
|
||||||
|
serveur.start();
|
||||||
|
url = "http://127.0.0.1:" + serveur.getAddress().getPort();
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void arreterFauxHub() {
|
||||||
|
serveur.stop(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
HubConfig cfg(Path tmp) {
|
||||||
|
return new HubConfig(true, url, tmp.resolve("k"), false, Sanction.ALERTE, 50, 2000, 1000, 3600_000L, 50, 600_000L,
|
||||||
|
1000, 2000, true, tmp.resolve("etat"));
|
||||||
|
}
|
||||||
|
|
||||||
|
EnvoiHub envoi(HubConfig c, FileEnvoi f) {
|
||||||
|
return new EnvoiHub(c, CLE, new Transport.Http(c.delaiConnexionMs(), c.delaiRequeteMs(), "0.3.2"), f, horloge::get,
|
||||||
|
journal::add);
|
||||||
|
}
|
||||||
|
|
||||||
|
Detection det(int n) {
|
||||||
|
return FileEtCleTest.det(n, horloge.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
static String resultats(String... statuts) {
|
||||||
|
StringBuilder sb = new StringBuilder("{\"resultats\":[");
|
||||||
|
for (int i = 0; i < statuts.length; i++) {
|
||||||
|
if (i > 0) sb.append(',');
|
||||||
|
String[] p = statuts[i].split(":");
|
||||||
|
sb.append("{\"id_externe\":\"x").append(i).append("\",\"statut\":\"").append(p[0]).append('"');
|
||||||
|
if (p.length > 1) sb.append(",\"code\":\"").append(p[1]).append('"');
|
||||||
|
sb.append('}');
|
||||||
|
}
|
||||||
|
return sb.append("]}").toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
static List<Map<String, Object>> detectionsDe(Recue r) {
|
||||||
|
Map<String, Object> m = (Map<String, Object>) MiniJson.lire(r.corps());
|
||||||
|
return (List<Map<String, Object>>) m.get("detections");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void lotEnvoyeAuBonEndroitAvecLaCleEnEnTeteEtJamaisDansLeCorps(@TempDir Path tmp) {
|
||||||
|
FileEnvoi f = new FileEnvoi(1000);
|
||||||
|
EnvoiHub e = envoi(cfg(tmp), f);
|
||||||
|
for (int i = 0; i < 3; i++) f.ajouter(det(i));
|
||||||
|
parDefaut = Reponse.ok(resultats("cree", "cree", "cree"));
|
||||||
|
e.cycle();
|
||||||
|
assertEquals(1, recues.size());
|
||||||
|
Recue r = recues.get(0);
|
||||||
|
assertEquals("POST", r.methode());
|
||||||
|
assertEquals("/internal/detections", r.chemin());
|
||||||
|
assertEquals(CLE, r.cle());
|
||||||
|
assertTrue(r.contentType().startsWith("application/json"));
|
||||||
|
assertFalse(r.corps().contains(CLE), "la clé ne doit jamais être dans le corps");
|
||||||
|
assertEquals(3, detectionsDe(r).size());
|
||||||
|
assertEquals(3, e.envoyees());
|
||||||
|
assertTrue(f.vide());
|
||||||
|
for (String l : journal) assertFalse(l.contains(CLE), "la clé ne doit jamais être dans le journal : " + l);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void chaqueDetectionEnvoyeeRespecteLesMotifsDuHub(@TempDir Path tmp) {
|
||||||
|
FileEnvoi f = new FileEnvoi(1000);
|
||||||
|
EnvoiHub e = envoi(cfg(tmp), f);
|
||||||
|
f.ajouter(new Detection("123e4567-e89b-12d3-a456-426614174000:portee:setback:1", "123e4567-e89b-12d3-a456-426614174000",
|
||||||
|
"portee", 2, "enforce", 12.5, horloge.get(),
|
||||||
|
new java.util.LinkedHashMap<>(Map.of("controle", "portee", "palier", 3, "x", 10, "y", 70, "z", -20,
|
||||||
|
"dimension", "minecraft:overworld", "version_mod", "0.3.2", "exemptions", List.of("creatif"),
|
||||||
|
"ip", "198.51.100.4"))));
|
||||||
|
e.cycle();
|
||||||
|
Map<String, Object> d = detectionsDe(recues.get(0)).get(0);
|
||||||
|
assertEquals(List.of("id_externe", "sujet", "type", "gravite", "mode", "points", "survenue_le", "details"),
|
||||||
|
new ArrayList<>(d.keySet()));
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Map<String, Object> det = (Map<String, Object>) d.get("details");
|
||||||
|
assertFalse(det.containsKey("ip"));
|
||||||
|
assertTrue(Assainir.CONTROLE.matcher((String) det.get("controle")).matches());
|
||||||
|
assertTrue(Assainir.CONTROLE.matcher((String) det.get("dimension")).matches());
|
||||||
|
assertTrue(Assainir.VERSION_MOD.matcher((String) det.get("version_mod")).matches());
|
||||||
|
assertEquals(3L, ((Number) det.get("palier")).longValue());
|
||||||
|
for (Object valeur : det.values()) {
|
||||||
|
if (valeur instanceof String t) assertFalse(Assainir.ressembleAdresseIp(t), "adresse dans details : " + t);
|
||||||
|
if (valeur instanceof List<?> l) for (Object o : l) assertFalse(Assainir.ressembleAdresseIp(String.valueOf(o)), String.valueOf(o));
|
||||||
|
}
|
||||||
|
assertFalse(recues.get(0).corps().contains("198.51.100.4"), "l'adresse fournie dans details ne part pas");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void panneReseauNouvellesTentativesAvecLeMemeIdentifiantPuisSucces(@TempDir Path tmp) {
|
||||||
|
FileEnvoi f = new FileEnvoi(1000);
|
||||||
|
EnvoiHub e = envoi(cfg(tmp), f);
|
||||||
|
f.ajouter(det(1));
|
||||||
|
scenario.add(Reponse.statut(503));
|
||||||
|
scenario.add(Reponse.statut(500));
|
||||||
|
parDefaut = Reponse.ok(resultats("cree"));
|
||||||
|
|
||||||
|
long a1 = e.cycle();
|
||||||
|
assertEquals(1, f.taille(), "le lot est remis en file");
|
||||||
|
assertTrue(a1 >= 1000 && a1 <= 1250, "1re attente ~1 s : " + a1);
|
||||||
|
assertEquals(1, e.echecsDeSuite());
|
||||||
|
e.cycle(); // trop tôt : rien n'est envoyé
|
||||||
|
assertEquals(1, recues.size());
|
||||||
|
|
||||||
|
horloge.addAndGet(a1 + 1);
|
||||||
|
long a2 = e.cycle();
|
||||||
|
assertTrue(a2 >= 2000 && a2 <= 2500, "2e attente ~2 s (exponentielle) : " + a2);
|
||||||
|
|
||||||
|
horloge.addAndGet(a2 + 1);
|
||||||
|
e.cycle();
|
||||||
|
assertEquals(3, recues.size());
|
||||||
|
assertTrue(f.vide());
|
||||||
|
assertEquals(0, e.echecsDeSuite());
|
||||||
|
String id1 = (String) detectionsDe(recues.get(0)).get(0).get("id_externe");
|
||||||
|
assertEquals(id1, detectionsDe(recues.get(1)).get(0).get("id_externe"));
|
||||||
|
assertEquals(id1, detectionsDe(recues.get(2)).get(0).get("id_externe"), "même identifiant à chaque tentative (idempotence)");
|
||||||
|
assertTrue(journal.stream().anyMatch(l -> l.contains("liaison rétablie")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void hubArreteConnexionRefuseLaFileResteEtTientLeCoup(@TempDir Path tmp) {
|
||||||
|
serveur.stop(0); // plus personne n'écoute sur ce port
|
||||||
|
FileEnvoi f = new FileEnvoi(50);
|
||||||
|
EnvoiHub e = envoi(cfg(tmp), f);
|
||||||
|
for (int i = 0; i < 80; i++) f.ajouter(det(i));
|
||||||
|
assertEquals(50, f.taille());
|
||||||
|
long attente = 0;
|
||||||
|
long debutSimule = horloge.get();
|
||||||
|
for (int tour = 0; tour < 12; tour++) {
|
||||||
|
attente = e.cycle();
|
||||||
|
horloge.addAndGet(attente + 1);
|
||||||
|
}
|
||||||
|
assertEquals(50, f.taille(), "rien n'est perdu pendant la panne (file bornée à 50)");
|
||||||
|
assertEquals(30, f.abandonnees());
|
||||||
|
assertEquals(12, e.echecsDeSuite());
|
||||||
|
assertTrue(attente <= EnvoiHub.ATTENTE_MAX_MS * 5 / 4, "l'attente plafonne à 5 min (+25 % au hasard) : " + attente);
|
||||||
|
long dureeSimuleeMin = (horloge.get() - debutSimule) / 60_000;
|
||||||
|
assertTrue(journal.size() <= dureeSimuleeMin / 5 + 1,
|
||||||
|
"journal limité à un message par type et par 5 min (" + dureeSimuleeMin + " min simulées) : " + journal);
|
||||||
|
assertTrue(journal.size() < 12, "bien moins de messages que de tentatives");
|
||||||
|
assertTrue(Files.exists(tmp.resolve("etat/file-attente.jsonl")), "la file est écrite sur disque pendant la panne");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void attenteExponentielleDe1sA5min() {
|
||||||
|
assertEquals(1000, EnvoiHub.delaiExponentiel(1));
|
||||||
|
assertEquals(2000, EnvoiHub.delaiExponentiel(2));
|
||||||
|
assertEquals(4000, EnvoiHub.delaiExponentiel(3));
|
||||||
|
assertEquals(64_000, EnvoiHub.delaiExponentiel(7));
|
||||||
|
assertEquals(300_000, EnvoiHub.delaiExponentiel(10));
|
||||||
|
assertEquals(300_000, EnvoiHub.delaiExponentiel(500));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void erreur429RespecteRetryAfter(@TempDir Path tmp) {
|
||||||
|
FileEnvoi f = new FileEnvoi(1000);
|
||||||
|
EnvoiHub e = envoi(cfg(tmp), f);
|
||||||
|
f.ajouter(det(1));
|
||||||
|
scenario.add(new Reponse(429, "{}", "17", 0));
|
||||||
|
long a = e.cycle();
|
||||||
|
assertEquals(17_000, a);
|
||||||
|
assertEquals(1, f.taille());
|
||||||
|
horloge.addAndGet(16_000);
|
||||||
|
e.cycle();
|
||||||
|
assertEquals(1, recues.size(), "avant l'échéance, rien ne part");
|
||||||
|
horloge.addAndGet(1_001);
|
||||||
|
parDefaut = Reponse.ok(resultats("cree"));
|
||||||
|
e.cycle();
|
||||||
|
assertEquals(2, recues.size());
|
||||||
|
assertTrue(f.vide());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void retryAfterAbsentOuAbsurdeEstBorne(@TempDir Path tmp) {
|
||||||
|
FileEnvoi f = new FileEnvoi(1000);
|
||||||
|
EnvoiHub e = envoi(cfg(tmp), f);
|
||||||
|
f.ajouter(det(1));
|
||||||
|
scenario.add(new Reponse(429, "{}", "99999999", 0));
|
||||||
|
assertEquals(EnvoiHub.ATTENTE_MAX_MS, e.cycle());
|
||||||
|
horloge.addAndGet(EnvoiHub.ATTENTE_MAX_MS + 1);
|
||||||
|
scenario.add(new Reponse(429, "{}", "0", 0));
|
||||||
|
assertEquals(EnvoiHub.ATTENTE_MIN_MS, e.cycle());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void cleRefusee401EtSourceInactive403GardentLaFileEtReessaientToutesLes5Min(@TempDir Path tmp) {
|
||||||
|
FileEnvoi f = new FileEnvoi(1000);
|
||||||
|
EnvoiHub e = envoi(cfg(tmp), f);
|
||||||
|
f.ajouter(det(1));
|
||||||
|
scenario.add(Reponse.statut(401));
|
||||||
|
assertEquals(EnvoiHub.ATTENTE_MAX_MS, e.cycle());
|
||||||
|
assertEquals(1, f.taille());
|
||||||
|
assertTrue(journal.stream().anyMatch(l -> l.contains("401")));
|
||||||
|
horloge.addAndGet(EnvoiHub.ATTENTE_MAX_MS + 1);
|
||||||
|
scenario.add(Reponse.statut(403));
|
||||||
|
assertEquals(EnvoiHub.ATTENTE_MAX_MS, e.cycle());
|
||||||
|
assertEquals(1, f.taille());
|
||||||
|
assertTrue(journal.stream().anyMatch(l -> l.contains("403")));
|
||||||
|
for (String l : journal) assertFalse(l.contains(CLE));
|
||||||
|
horloge.addAndGet(EnvoiHub.ATTENTE_MAX_MS + 1);
|
||||||
|
parDefaut = Reponse.ok(resultats("cree"));
|
||||||
|
e.cycle();
|
||||||
|
assertTrue(f.vide(), "dès que la source est activée côté Hub, la file part");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void lotInvalide400EstAbandonneSansBoucler(@TempDir Path tmp) {
|
||||||
|
FileEnvoi f = new FileEnvoi(1000);
|
||||||
|
EnvoiHub e = envoi(cfg(tmp), f);
|
||||||
|
f.ajouter(det(1));
|
||||||
|
f.ajouter(det(2));
|
||||||
|
scenario.add(Reponse.statut(400));
|
||||||
|
e.cycle();
|
||||||
|
assertTrue(f.vide());
|
||||||
|
assertEquals(1, e.lotsRejetes());
|
||||||
|
assertEquals(2, e.perimees());
|
||||||
|
assertEquals(1, recues.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void lotTropGros413EstDivise(@TempDir Path tmp) {
|
||||||
|
FileEnvoi f = new FileEnvoi(1000);
|
||||||
|
EnvoiHub e = envoi(cfg(tmp), f);
|
||||||
|
for (int i = 0; i < 8; i++) f.ajouter(det(i));
|
||||||
|
scenario.add(Reponse.statut(413));
|
||||||
|
e.cycle();
|
||||||
|
assertEquals(8, f.taille());
|
||||||
|
parDefaut = Reponse.ok(resultats("cree", "cree", "cree", "cree"));
|
||||||
|
e.cycle();
|
||||||
|
assertEquals(4, detectionsDe(recues.get(1)).size(), "lot ramené à la moitié");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void doublonsEtRefusLusDansLaReponseSontAcquittesSansRenvoi(@TempDir Path tmp) {
|
||||||
|
FileEnvoi f = new FileEnvoi(1000);
|
||||||
|
EnvoiHub e = envoi(cfg(tmp), f);
|
||||||
|
for (int i = 0; i < 3; i++) f.ajouter(det(i));
|
||||||
|
parDefaut = Reponse.ok(resultats("cree", "doublon", "refuse:horodatage_hors_fenetre"));
|
||||||
|
e.cycle();
|
||||||
|
assertTrue(f.vide());
|
||||||
|
assertEquals(1, e.doublons());
|
||||||
|
assertEquals(1, e.refusees());
|
||||||
|
assertTrue(journal.stream().anyMatch(l -> l.contains("horodatage_hors_fenetre")));
|
||||||
|
assertEquals(1, recues.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void reponse200IllisibleEstTenueCommeAcceptee(@TempDir Path tmp) {
|
||||||
|
FileEnvoi f = new FileEnvoi(1000);
|
||||||
|
EnvoiHub e = envoi(cfg(tmp), f);
|
||||||
|
f.ajouter(det(1));
|
||||||
|
parDefaut = Reponse.ok("<html>pas du json</html>");
|
||||||
|
e.cycle();
|
||||||
|
assertTrue(f.vide());
|
||||||
|
assertEquals(1, e.envoyees());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void lotsDe50EtDebitParMinute(@TempDir Path tmp) {
|
||||||
|
HubConfig c = new HubConfig(true, url, tmp.resolve("k"), false, Sanction.ALERTE, 50, 2000, 1000, 3600_000L, 60, 600_000L,
|
||||||
|
1000, 2000, true, tmp.resolve("etat"));
|
||||||
|
FileEnvoi f = new FileEnvoi(1000);
|
||||||
|
EnvoiHub e = envoi(c, f);
|
||||||
|
for (int i = 0; i < 130; i++) f.ajouter(det(i));
|
||||||
|
parDefaut = Reponse.ok("{}");
|
||||||
|
e.cycle();
|
||||||
|
assertEquals(50, detectionsDe(recues.get(0)).size());
|
||||||
|
horloge.addAndGet(300);
|
||||||
|
e.cycle();
|
||||||
|
assertEquals(10, detectionsDe(recues.get(1)).size(), "60 par minute au plus : 10 seulement dans la même minute");
|
||||||
|
horloge.addAndGet(300);
|
||||||
|
long att = e.cycle();
|
||||||
|
assertEquals(2, recues.size(), "limite atteinte : rien ne part avant la fin de la minute");
|
||||||
|
assertTrue(att > 50_000 && att <= 60_000, "attente jusqu'à la fin de la minute : " + att);
|
||||||
|
horloge.addAndGet(60_001);
|
||||||
|
e.cycle();
|
||||||
|
assertEquals(3, recues.size());
|
||||||
|
assertEquals(50, detectionsDe(recues.get(2)).size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void detectionsTropVieillesAbandonneesAvantEnvoi(@TempDir Path tmp) {
|
||||||
|
FileEnvoi f = new FileEnvoi(1000);
|
||||||
|
EnvoiHub e = envoi(cfg(tmp), f);
|
||||||
|
f.ajouter(FileEtCleTest.det(1, horloge.get() - 2 * 3600_000L)); // plus vieille que ageMax (1 h ici)
|
||||||
|
f.ajouter(det(2));
|
||||||
|
e.cycle();
|
||||||
|
assertEquals(1, e.perimees());
|
||||||
|
assertEquals(1, detectionsDe(recues.get(0)).size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fileSurDisqueSurvitAUnRedemarrageHubArrete(@TempDir Path tmp) {
|
||||||
|
HubConfig c = cfg(tmp);
|
||||||
|
FileEnvoi f = new FileEnvoi(1000);
|
||||||
|
EnvoiHub e = envoi(c, f);
|
||||||
|
for (int i = 0; i < 4; i++) f.ajouter(det(i));
|
||||||
|
serveur.stop(0);
|
||||||
|
e.cycle(); // échec : copie sur disque
|
||||||
|
e.arreter(); // arrêt du serveur Minecraft : tout est écrit
|
||||||
|
assertTrue(Files.exists(tmp.resolve("etat/file-attente.jsonl")));
|
||||||
|
|
||||||
|
FileEnvoi f2 = new FileEnvoi(1000);
|
||||||
|
EnvoiHub e2 = envoi(c, f2);
|
||||||
|
e2.demarrer(); // relit le disque (lance le fil, arrêté tout de suite)
|
||||||
|
e2.arreter();
|
||||||
|
assertEquals(4, f2.taille());
|
||||||
|
List<Detection> l = f2.prendre(50, 1_000_000);
|
||||||
|
assertEquals(4, l.size());
|
||||||
|
assertEquals(det(0).idExterne(), l.get(0).idExterne(), "mêmes identifiants après redémarrage");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fileEffaceeDuDisqueUneFoisToutAccuse(@TempDir Path tmp) throws Exception {
|
||||||
|
HubConfig c = cfg(tmp);
|
||||||
|
FileEnvoi f = new FileEnvoi(1000);
|
||||||
|
EnvoiHub e = envoi(c, f);
|
||||||
|
f.ajouter(det(1));
|
||||||
|
scenario.add(Reponse.statut(500));
|
||||||
|
long a = e.cycle();
|
||||||
|
assertTrue(Files.exists(tmp.resolve("etat/file-attente.jsonl")));
|
||||||
|
horloge.addAndGet(a + 1);
|
||||||
|
parDefaut = Reponse.ok(resultats("cree"));
|
||||||
|
e.cycle();
|
||||||
|
assertFalse(Files.exists(tmp.resolve("etat/file-attente.jsonl")), "plus de donnée personnelle sur disque une fois accusé");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void jamaisDeRedirectionSuivie(@TempDir Path tmp) {
|
||||||
|
FileEnvoi f = new FileEnvoi(1000);
|
||||||
|
EnvoiHub e = envoi(cfg(tmp), f);
|
||||||
|
f.ajouter(det(1));
|
||||||
|
scenario.add(new Reponse(302, "{}", null, 0));
|
||||||
|
e.cycle();
|
||||||
|
assertEquals(1, recues.size());
|
||||||
|
assertEquals(1, f.taille(), "302 = réponse inattendue : on réessaie plus tard, sans suivre la redirection");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void hubLentLeCycleSArreteAuDelaiDeRequete(@TempDir Path tmp) {
|
||||||
|
FileEnvoi f = new FileEnvoi(1000);
|
||||||
|
EnvoiHub e = envoi(cfg(tmp), f);
|
||||||
|
f.ajouter(det(1));
|
||||||
|
scenario.add(new Reponse(200, resultats("cree"), null, 6000)); // délai de requête : 2 s
|
||||||
|
long t0 = System.nanoTime();
|
||||||
|
e.cycle();
|
||||||
|
long ms = (System.nanoTime() - t0) / 1_000_000;
|
||||||
|
assertTrue(ms < 4000, "coupé au délai de requête : " + ms + " ms");
|
||||||
|
assertEquals(1, f.taille());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
package com.gastinelgarde.hub;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import com.gastinelgarde.core.Controle;
|
||||||
|
import com.gastinelgarde.core.Sanction;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
/** File bornée, file sur disque, suivi des paliers, lecture de la clé. */
|
||||||
|
class FileEtCleTest {
|
||||||
|
|
||||||
|
static Detection det(int n, long survenueMs) {
|
||||||
|
return new Detection(String.format("00000000-0000-0000-0000-%012d:portee:alerte:%d", n, survenueMs),
|
||||||
|
"123e4567-e89b-12d3-a456-426614174000", "portee", 1, "enforce", 1.0, survenueMs, Map.of("controle", "portee"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- File bornée ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void laFileEstBorneeEtAbandonneLesPlusAnciennes() {
|
||||||
|
FileEnvoi f = new FileEnvoi(10);
|
||||||
|
for (int i = 0; i < 25; i++) f.ajouter(det(i, 1000 + i));
|
||||||
|
assertEquals(10, f.taille());
|
||||||
|
assertEquals(15, f.abandonnees());
|
||||||
|
List<Detection> lot = f.prendre(50, 1_000_000);
|
||||||
|
assertEquals(10, lot.size());
|
||||||
|
assertEquals(1015, lot.get(0).survenueMs()); // les plus récentes sont gardées
|
||||||
|
assertEquals(1024, lot.get(9).survenueMs());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void lotBorneEnNombreEtEnOctets() {
|
||||||
|
FileEnvoi f = new FileEnvoi(1000);
|
||||||
|
for (int i = 0; i < 100; i++) f.ajouter(det(i, 1000 + i));
|
||||||
|
assertEquals(50, f.prendre(50, 1_000_000).size());
|
||||||
|
int un = det(0, 1000).json().getBytes(StandardCharsets.UTF_8).length + 1;
|
||||||
|
List<Detection> petit = f.prendre(50, un * 3 + 1);
|
||||||
|
assertEquals(3, petit.size());
|
||||||
|
assertEquals(47, f.taille());
|
||||||
|
// une seule détection plus grosse que la limite part quand même (sinon la file serait bloquée)
|
||||||
|
assertEquals(1, f.prendre(50, 1).size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void remettreRetrouveLOrdreEtPurgerEnleveLesVieilles() {
|
||||||
|
FileEnvoi f = new FileEnvoi(100);
|
||||||
|
for (int i = 0; i < 6; i++) f.ajouter(det(i, 1000 + i));
|
||||||
|
List<Detection> lot = f.prendre(3, 1_000_000);
|
||||||
|
f.remettre(lot);
|
||||||
|
assertEquals(6, f.taille());
|
||||||
|
List<Detection> tout = f.prendre(6, 1_000_000);
|
||||||
|
for (int i = 0; i < 6; i++) assertEquals(1000 + i, tout.get(i).survenueMs());
|
||||||
|
f.remettre(tout);
|
||||||
|
assertEquals(3, f.purgerAvant(1003));
|
||||||
|
assertEquals(3, f.taille());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Disque ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fileSurDisqueEcritureAtomiqueEtRelecture(@TempDir Path tmp) throws IOException {
|
||||||
|
Spool s = new Spool(tmp.resolve("sous/dossier/file.jsonl"));
|
||||||
|
assertTrue(s.lire(0).isEmpty());
|
||||||
|
s.ecrire(List.of(det(1, 5000), det(2, 6000), det(3, 100)));
|
||||||
|
assertTrue(s.existe());
|
||||||
|
assertFalse(Files.exists(tmp.resolve("sous/dossier/file.jsonl.tmp")));
|
||||||
|
List<Detection> l = s.lire(1000); // la 3e est trop ancienne
|
||||||
|
assertEquals(2, l.size());
|
||||||
|
assertEquals(det(1, 5000), l.get(0)); // même identifiant, mêmes valeurs : la relecture ne change rien
|
||||||
|
s.ecrire(List.of());
|
||||||
|
assertFalse(s.existe());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void ligneAbimeeIgnoreeLesSuivantesRestent(@TempDir Path tmp) throws IOException {
|
||||||
|
Path p = tmp.resolve("file.jsonl");
|
||||||
|
Files.writeString(p, det(1, 5000).json() + "\n{pas du json\n" + det(2, 6000).json().substring(0, 40) + "\n"
|
||||||
|
+ det(3, 7000).json() + "\n", StandardCharsets.UTF_8);
|
||||||
|
List<Detection> l = new Spool(p).lire(0);
|
||||||
|
assertEquals(2, l.size());
|
||||||
|
assertEquals(5000, l.get(0).survenueMs());
|
||||||
|
assertEquals(7000, l.get(1).survenueMs());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Suivi des paliers ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void unPalierEstSignaleUneFoisParEpisodePuisSeulementSiPlusHaut() {
|
||||||
|
SuiviPaliers s = new SuiviPaliers(600_000, Sanction.ALERTE);
|
||||||
|
UUID j = UUID.randomUUID();
|
||||||
|
assertTrue(s.franchit(j, Controle.PORTEE, Sanction.ALERTE, 0));
|
||||||
|
assertFalse(s.franchit(j, Controle.PORTEE, Sanction.ALERTE, 1000));
|
||||||
|
assertTrue(s.franchit(j, Controle.PORTEE, Sanction.SETBACK, 2000));
|
||||||
|
assertFalse(s.franchit(j, Controle.PORTEE, Sanction.SETBACK, 3000));
|
||||||
|
assertFalse(s.franchit(j, Controle.PORTEE, Sanction.ALERTE, 4000)); // jamais de redescente
|
||||||
|
assertTrue(s.franchit(j, Controle.PORTEE, Sanction.EXPULSION, 5000));
|
||||||
|
assertTrue(s.franchit(j, Controle.VOL, Sanction.ALERTE, 5000)); // un autre contrôle : un autre épisode
|
||||||
|
assertTrue(s.franchit(j, Controle.PORTEE, Sanction.ALERTE, 700_000)); // l'épisode est fini
|
||||||
|
assertFalse(s.franchit(j, Controle.HITBOX, Sanction.JOURNAL, 0)); // sous le palier minimum
|
||||||
|
assertFalse(s.franchit(j, Controle.HITBOX, Sanction.AUCUNE, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void joueurPartiOublieEtMemoireBornee() {
|
||||||
|
SuiviPaliers s = new SuiviPaliers(600_000, Sanction.ALERTE);
|
||||||
|
UUID j = UUID.randomUUID();
|
||||||
|
s.franchit(j, Controle.PORTEE, Sanction.ALERTE, 0);
|
||||||
|
s.oublier(j);
|
||||||
|
assertEquals(0, s.taille());
|
||||||
|
for (int i = 0; i < 20_000; i++) s.franchit(UUID.randomUUID(), Controle.PORTEE, Sanction.ALERTE, 0);
|
||||||
|
assertTrue(s.taille() <= 4096, "taille " + s.taille());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Clé ---
|
||||||
|
|
||||||
|
private static final String CLE_TEST = "cle-de-test-0123456789-0123456789-ABCDEF"; // valeur factice, pas une vraie clé
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void cleLueSansEtatsDAme(@TempDir Path tmp) throws IOException {
|
||||||
|
Path f = tmp.resolve("k.key");
|
||||||
|
Files.writeString(f, "# commentaire\n\n " + CLE_TEST + " \n", StandardCharsets.UTF_8);
|
||||||
|
LecteurCle.Resultat r = LecteurCle.lire(f);
|
||||||
|
assertTrue(r.ok());
|
||||||
|
assertEquals(CLE_TEST, r.cle());
|
||||||
|
assertFalse(r.toString().contains(CLE_TEST));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void cleAbsenteVideCourteOuPiegee(@TempDir Path tmp) throws IOException {
|
||||||
|
assertEquals(LecteurCle.Raison.ABSENTE, LecteurCle.lire(tmp.resolve("rien")).raison());
|
||||||
|
assertEquals(LecteurCle.Raison.ABSENTE, LecteurCle.lire(null).raison());
|
||||||
|
Path f = tmp.resolve("k.key");
|
||||||
|
Files.writeString(f, "# rien\n");
|
||||||
|
assertEquals(LecteurCle.Raison.VIDE, LecteurCle.lire(f).raison());
|
||||||
|
Files.writeString(f, "trop-court\n");
|
||||||
|
assertEquals(LecteurCle.Raison.TROP_COURTE, LecteurCle.lire(f).raison());
|
||||||
|
Files.writeString(f, CLE_TEST + " avec espace\n");
|
||||||
|
assertEquals(LecteurCle.Raison.CARACTERES_INVALIDES, LecteurCle.lire(f).raison());
|
||||||
|
Files.writeString(f, "x".repeat(5000));
|
||||||
|
assertEquals(LecteurCle.Raison.TROP_LONGUE, LecteurCle.lire(f).raison());
|
||||||
|
assertNull(LecteurCle.lire(f).cle());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void messagesDErreurSansLeContenuDeLaCle(@TempDir Path tmp) throws IOException {
|
||||||
|
Path f = tmp.resolve("k.key");
|
||||||
|
Files.writeString(f, CLE_TEST + " espace\n");
|
||||||
|
LecteurCle.Resultat r = LecteurCle.lire(f);
|
||||||
|
for (LecteurCle.Raison raison : LecteurCle.Raison.values()) {
|
||||||
|
assertFalse(LecteurCle.message(f, raison).contains("cle-de-test"), raison.name());
|
||||||
|
}
|
||||||
|
assertNull(r.cle());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Réglages ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void adresseDeLApiAcceptSeulementHttpSansIdentifiants(@TempDir Path tmp) {
|
||||||
|
assertEquals("http://hub:8080/internal/detections", cfg("http://hub:8080", tmp).adresseApi().toString());
|
||||||
|
assertEquals("https://hub/internal/detections", cfg("https://hub/", tmp).adresseApi().toString());
|
||||||
|
assertNull(cfg("", tmp).adresseApi());
|
||||||
|
assertNull(cfg("ftp://hub", tmp).adresseApi());
|
||||||
|
assertNull(cfg("http://utilisateur:secret@hub", tmp).adresseApi());
|
||||||
|
assertNull(cfg("http://hub?x=1", tmp).adresseApi());
|
||||||
|
assertNull(cfg("pas une adresse", tmp).adresseApi());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void reglagesBornes(@TempDir Path tmp) {
|
||||||
|
HubConfig c = new HubConfig(true, "http://hub", Path.of("k"), false, Sanction.JOURNAL, 999, 1, 1, Long.MAX_VALUE,
|
||||||
|
0, 0, 0, 0, true, tmp);
|
||||||
|
assertEquals(Sanction.ALERTE, c.palierMin());
|
||||||
|
assertEquals(50, c.lotMax());
|
||||||
|
assertTrue(c.ageMaxMs() < HubConfig.AGE_MAX_API_MS);
|
||||||
|
assertTrue(c.fileMax() >= 10);
|
||||||
|
assertTrue(c.debitMaxParMinute() >= 1);
|
||||||
|
assertFalse(HubConfig.defaut(tmp).envoi());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static HubConfig cfg(String url, Path tmp) {
|
||||||
|
return new HubConfig(true, url, Path.of("k"), false, Sanction.ALERTE, 50, 2000, 100, 3600_000L, 50, 600_000L, 1000, 1000,
|
||||||
|
true, tmp);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,268 @@
|
|||||||
|
package com.gastinelgarde.hub;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import com.gastinelgarde.core.Controle;
|
||||||
|
import com.gastinelgarde.core.Mode;
|
||||||
|
import com.gastinelgarde.core.Sanction;
|
||||||
|
import com.gastinelgarde.core.Verdict;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.OptionalLong;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.CopyOnWriteArrayList;
|
||||||
|
import java.util.concurrent.CountDownLatch;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
/** Le point d'entrée appelé par le tick : coupé par défaut, rapide, jamais d'exception, contrat respecté. */
|
||||||
|
class SignalementTest {
|
||||||
|
|
||||||
|
static final String CLE = EnvoiHubServeurTest.CLE;
|
||||||
|
final List<String> journal = new CopyOnWriteArrayList<>();
|
||||||
|
final List<String> corpsRecus = new CopyOnWriteArrayList<>();
|
||||||
|
final AtomicLong horloge = new AtomicLong(1_760_000_000_000L);
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void nettoyer() {
|
||||||
|
Signalement.arreter();
|
||||||
|
}
|
||||||
|
|
||||||
|
Path cle(Path tmp) throws IOException {
|
||||||
|
Path k = tmp.resolve("hub.key");
|
||||||
|
Files.writeString(k, CLE + "\n", StandardCharsets.UTF_8);
|
||||||
|
return k;
|
||||||
|
}
|
||||||
|
|
||||||
|
HubConfig cfg(Path tmp, boolean envoi, boolean observe) {
|
||||||
|
return new HubConfig(envoi, "http://hub:8080", tmp.resolve("hub.key"), observe, Sanction.ALERTE, 50, 200, 1000,
|
||||||
|
3600_000L, 50, 600_000L, 1000, 2000, true, tmp.resolve("etat"));
|
||||||
|
}
|
||||||
|
|
||||||
|
static Verdict verdict(Controle c, Mode m, Sanction palier, Sanction applicable, List<String> ex) {
|
||||||
|
return new Verdict(c, m, 1.0, 9.0, palier, applicable, false, "détail interne avec pseudo Steve et 198.51.100.7", ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Transport qui note les corps reçus et répond 200. */
|
||||||
|
Transport enregistreur(CountDownLatch recu) {
|
||||||
|
return (URI adresse, String cle, String corps) -> {
|
||||||
|
assertEquals(CLE, cle);
|
||||||
|
corpsRecus.add(corps);
|
||||||
|
if (recu != null) recu.countDown();
|
||||||
|
return new Transport.Reponse(200, "{\"resultats\":[]}", OptionalLong.empty());
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void desactiveParDefautRienNeEstCree(@TempDir Path tmp) {
|
||||||
|
assertFalse(HubConfig.defaut(tmp).envoi());
|
||||||
|
assertFalse(Signalement.actif());
|
||||||
|
Signalement.surVerdict(UUID.randomUUID(), verdict(Controle.PORTEE, Mode.ENFORCE, Sanction.EXPULSION, Sanction.EXPULSION, List.of()),
|
||||||
|
() -> {
|
||||||
|
throw new AssertionError("la position ne doit pas être demandée quand c'est désactivé");
|
||||||
|
});
|
||||||
|
assertTrue(Signalement.resume().contains("désactivé"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void envoiFauxNeDemarreRienMemeAvecUneCle(@TempDir Path tmp) throws IOException {
|
||||||
|
Signalement.demarrer(cfg(tmp, false, false), cle(tmp), enregistreur(null), horloge::get, journal::add, "0.3.2");
|
||||||
|
assertFalse(Signalement.actif());
|
||||||
|
assertTrue(journal.get(0).contains("désactivé"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void sansCleOuAvecCleCourteOuMauvaiseAdresseOnNeDemarrePas(@TempDir Path tmp) throws IOException {
|
||||||
|
Signalement.demarrer(cfg(tmp, true, false), tmp.resolve("absent.key"), enregistreur(null), horloge::get, journal::add, "0.3.2");
|
||||||
|
assertFalse(Signalement.actif());
|
||||||
|
assertTrue(journal.get(0).contains("absent"));
|
||||||
|
Files.writeString(tmp.resolve("courte.key"), "courte\n");
|
||||||
|
Signalement.demarrer(cfg(tmp, true, false), tmp.resolve("courte.key"), enregistreur(null), horloge::get, journal::add, "0.3.2");
|
||||||
|
assertFalse(Signalement.actif());
|
||||||
|
HubConfig mauvaise = new HubConfig(true, "ftp://hub", tmp.resolve("hub.key"), false, Sanction.ALERTE, 50, 200, 1000,
|
||||||
|
3600_000L, 50, 600_000L, 1000, 2000, true, tmp.resolve("etat"));
|
||||||
|
Signalement.demarrer(mauvaise, cle(tmp), enregistreur(null), horloge::get, journal::add, "0.3.2");
|
||||||
|
assertFalse(Signalement.actif());
|
||||||
|
for (String l : journal) assertFalse(l.contains(CLE), l);
|
||||||
|
for (String l : journal) assertTrue(l.startsWith("Hub :"), l);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void franchissementEnEnforceEstEnvoyeAvecLeContrat(@TempDir Path tmp) throws Exception {
|
||||||
|
CountDownLatch recu = new CountDownLatch(1);
|
||||||
|
Signalement.demarrer(cfg(tmp, true, false), cle(tmp), enregistreur(recu), horloge::get, journal::add, "0.3.2");
|
||||||
|
assertTrue(Signalement.actif());
|
||||||
|
UUID j = UUID.fromString("123e4567-e89b-12d3-a456-426614174000");
|
||||||
|
Signalement.surVerdict(j, verdict(Controle.NO_FALL, Mode.ENFORCE, Sanction.SETBACK, Sanction.SETBACK,
|
||||||
|
List.of("elytres", "Chute Lente", "198.51.100.9")), () -> new Signalement.Position(10, 64, -3, "minecraft:overworld"));
|
||||||
|
assertTrue(recu.await(5, TimeUnit.SECONDS), "envoi attendu en moins de 5 s");
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Map<String, Object> m = (Map<String, Object>) MiniJson.lire(corpsRecus.get(0));
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Map<String, Object> d = (Map<String, Object>) ((List<?>) m.get("detections")).get(0);
|
||||||
|
assertEquals("no-fall", d.get("type"));
|
||||||
|
assertEquals(2L, ((Number) d.get("gravite")).longValue());
|
||||||
|
assertEquals("enforce", d.get("mode"));
|
||||||
|
assertTrue(((String) d.get("id_externe")).startsWith(j + ":no-fall:setback:"));
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Map<String, Object> det = (Map<String, Object>) d.get("details");
|
||||||
|
assertEquals("no-fall", det.get("controle"));
|
||||||
|
assertEquals(3L, ((Number) det.get("palier")).longValue());
|
||||||
|
assertEquals(List.of("elytres", "chute_lente"), det.get("exemptions"));
|
||||||
|
assertEquals("0.3.2", det.get("version_mod"));
|
||||||
|
assertEquals("minecraft:overworld", det.get("dimension"));
|
||||||
|
assertEquals(10L, ((Number) det.get("x")).longValue());
|
||||||
|
// aucun texte libre du moteur (pseudo, adresse) dans ce qui part
|
||||||
|
String corps = corpsRecus.get(0);
|
||||||
|
assertFalse(corps.contains("Steve"));
|
||||||
|
assertFalse(corps.contains("198.51.100"));
|
||||||
|
assertFalse(corps.contains("détail"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void observeNEstPasEnvoyeParDefautEtMarqueObserveSiOnLeDemande(@TempDir Path tmp) throws Exception {
|
||||||
|
Signalement.demarrer(cfg(tmp, true, false), cle(tmp), enregistreur(null), horloge::get, journal::add, "0.3.2");
|
||||||
|
UUID j = UUID.randomUUID();
|
||||||
|
Signalement.surVerdict(j, verdict(Controle.VOL, Mode.OBSERVE, Sanction.EXPULSION, Sanction.ALERTE, List.of()), null);
|
||||||
|
assertEquals(0, Signalement.instanceCourante().file().taille() + Signalement.instanceCourante().envoi().envoyees());
|
||||||
|
Signalement.arreter();
|
||||||
|
|
||||||
|
CountDownLatch recu = new CountDownLatch(1);
|
||||||
|
Signalement.demarrer(cfg(tmp, true, true), cle(tmp), enregistreur(recu), horloge::get, journal::add, "0.3.2");
|
||||||
|
Signalement.surVerdict(j, verdict(Controle.VOL, Mode.OBSERVE, Sanction.EXPULSION, Sanction.ALERTE, List.of()), null);
|
||||||
|
assertTrue(recu.await(5, TimeUnit.SECONDS));
|
||||||
|
assertTrue(corpsRecus.get(corpsRecus.size() - 1).contains("\"mode\":\"observe\""));
|
||||||
|
assertTrue(corpsRecus.get(corpsRecus.size() - 1).contains("\"gravite\":3"), "OBSERVE : palier mérité");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void enEnforceLaSanctionReellementAppliqueeFaitLaGravite(@TempDir Path tmp) throws Exception {
|
||||||
|
CountDownLatch recu = new CountDownLatch(1);
|
||||||
|
Signalement.demarrer(cfg(tmp, true, false), cle(tmp), enregistreur(recu), horloge::get, journal::add, "0.3.2");
|
||||||
|
Signalement.surVerdict(UUID.randomUUID(), verdict(Controle.PORTEE, Mode.ENFORCE, Sanction.EXPULSION, Sanction.SETBACK, List.of()), null);
|
||||||
|
assertTrue(recu.await(5, TimeUnit.SECONDS));
|
||||||
|
assertTrue(corpsRecus.get(0).contains("\"gravite\":2"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void modeOffJournalEtAucuneNeSontJamaisEnvoyes(@TempDir Path tmp) throws Exception {
|
||||||
|
Signalement.demarrer(cfg(tmp, true, true), cle(tmp), enregistreur(null), horloge::get, journal::add, "0.3.2");
|
||||||
|
UUID j = UUID.randomUUID();
|
||||||
|
Signalement.surVerdict(j, verdict(Controle.PORTEE, Mode.OFF, Sanction.EXPULSION, Sanction.EXPULSION, List.of()), null);
|
||||||
|
Signalement.surVerdict(j, verdict(Controle.PORTEE, Mode.ENFORCE, Sanction.JOURNAL, Sanction.JOURNAL, List.of()), null);
|
||||||
|
Signalement.surVerdict(j, verdict(Controle.PORTEE, Mode.ENFORCE, Sanction.AUCUNE, Sanction.AUCUNE, List.of()), null);
|
||||||
|
assertEquals(0, Signalement.instanceCourante().file().taille());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void uneRafaleDInfractionsDonneAuPlusTroisSignalementsParControle(@TempDir Path tmp) throws Exception {
|
||||||
|
Signalement.demarrer(cfg(tmp, true, false), cle(tmp), (a, c, b) -> {
|
||||||
|
throw new IOException("hub arrêté");
|
||||||
|
}, horloge::get, journal::add, "0.3.2");
|
||||||
|
UUID j = UUID.randomUUID();
|
||||||
|
for (int i = 0; i < 5000; i++) {
|
||||||
|
Sanction s = i < 1000 ? Sanction.ALERTE : i < 2000 ? Sanction.SETBACK : Sanction.EXPULSION;
|
||||||
|
Signalement.surVerdict(j, verdict(Controle.PORTEE, Mode.ENFORCE, s, s, List.of()), null);
|
||||||
|
}
|
||||||
|
// le fil d'envoi peut déjà avoir pris un lot ; ce qui compte : 3 identifiants distincts au total
|
||||||
|
Thread.sleep(100);
|
||||||
|
int total = Signalement.instanceCourante().file().taille();
|
||||||
|
assertTrue(total <= 3 && total >= 1, "signalements en file : " + total);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void leTickNEstJamaisRalentiMemeSiLeHubBloque(@TempDir Path tmp) throws Exception {
|
||||||
|
CountDownLatch bloque = new CountDownLatch(1);
|
||||||
|
CountDownLatch entre = new CountDownLatch(1);
|
||||||
|
Transport bloquant = (a, c, corps) -> {
|
||||||
|
entre.countDown();
|
||||||
|
bloque.await(30, TimeUnit.SECONDS); // simule un Hub qui ne répond jamais
|
||||||
|
throw new IOException("délai dépassé");
|
||||||
|
};
|
||||||
|
Signalement.demarrer(cfg(tmp, true, false), cle(tmp), bloquant, horloge::get, journal::add, "0.3.2");
|
||||||
|
// une première détection pour que le fil d'envoi se bloque dans le transport
|
||||||
|
Signalement.surVerdict(UUID.randomUUID(), verdict(Controle.PORTEE, Mode.ENFORCE, Sanction.ALERTE, Sanction.ALERTE, List.of()), null);
|
||||||
|
assertTrue(entre.await(5, TimeUnit.SECONDS));
|
||||||
|
|
||||||
|
int joueurs = 20_000;
|
||||||
|
UUID[] ids = new UUID[joueurs];
|
||||||
|
for (int i = 0; i < joueurs; i++) ids[i] = UUID.randomUUID();
|
||||||
|
Verdict v = verdict(Controle.VITESSE, Mode.ENFORCE, Sanction.SETBACK, Sanction.SETBACK, List.of("elytres"));
|
||||||
|
long t0 = System.nanoTime();
|
||||||
|
for (UUID id : ids) Signalement.surVerdict(id, v, () -> new Signalement.Position(1, 2, 3, "minecraft:overworld"));
|
||||||
|
long ms = (System.nanoTime() - t0) / 1_000_000;
|
||||||
|
double microsParAppel = ms * 1000.0 / joueurs;
|
||||||
|
System.out.println("MESURE tick : " + joueurs + " signalements pendant que le Hub est bloqué : " + ms + " ms ("
|
||||||
|
+ String.format("%.1f", microsParAppel) + " µs par appel)");
|
||||||
|
assertTrue(ms < 1500, "20 000 signalements en " + ms + " ms : le tick attendrait le Hub");
|
||||||
|
assertTrue(microsParAppel < 100, "coût par appel : " + microsParAppel + " µs");
|
||||||
|
bloque.countDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void desactiverPendantLeJeuNeLeveAucuneException(@TempDir Path tmp) throws Exception {
|
||||||
|
Signalement.demarrer(cfg(tmp, true, false), cle(tmp), enregistreur(null), horloge::get, journal::add, "0.3.2");
|
||||||
|
UUID j = UUID.randomUUID();
|
||||||
|
Signalement.surVerdict(j, verdict(Controle.PORTEE, Mode.ENFORCE, Sanction.ALERTE, Sanction.ALERTE, List.of()), () -> {
|
||||||
|
throw new IllegalStateException("position indisponible");
|
||||||
|
});
|
||||||
|
Signalement.joueurParti(j);
|
||||||
|
Signalement.arreter();
|
||||||
|
Signalement.arreter();
|
||||||
|
Signalement.surVerdict(j, verdict(Controle.PORTEE, Mode.ENFORCE, Sanction.ALERTE, Sanction.ALERTE, List.of()), null);
|
||||||
|
Signalement.joueurParti(j);
|
||||||
|
assertFalse(Signalement.actif());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void redemarrageEcritLaFileSurDisqueEtLaReprend(@TempDir Path tmp) throws Exception {
|
||||||
|
AtomicInteger appels = new AtomicInteger();
|
||||||
|
Transport panne = (a, c, b) -> {
|
||||||
|
appels.incrementAndGet();
|
||||||
|
throw new IOException("hub arrêté");
|
||||||
|
};
|
||||||
|
Signalement.demarrer(cfg(tmp, true, false), cle(tmp), panne, horloge::get, journal::add, "0.3.2");
|
||||||
|
UUID j = UUID.randomUUID();
|
||||||
|
Signalement.surVerdict(j, verdict(Controle.PORTEE, Mode.ENFORCE, Sanction.ALERTE, Sanction.ALERTE, List.of()), null);
|
||||||
|
Signalement.surVerdict(j, verdict(Controle.VOL, Mode.ENFORCE, Sanction.SETBACK, Sanction.SETBACK, List.of()), null);
|
||||||
|
Signalement.arreter(); // arrêt du serveur
|
||||||
|
assertTrue(Files.exists(tmp.resolve("etat/file-attente.jsonl")));
|
||||||
|
String contenu = Files.readString(tmp.resolve("etat/file-attente.jsonl"));
|
||||||
|
assertFalse(contenu.contains(CLE), "la clé ne doit jamais être écrite dans la file sur disque");
|
||||||
|
assertEquals(2, contenu.lines().count());
|
||||||
|
|
||||||
|
CountDownLatch recu = new CountDownLatch(1);
|
||||||
|
Signalement.demarrer(cfg(tmp, true, false), cle(tmp), enregistreur(recu), horloge::get, journal::add, "0.3.2");
|
||||||
|
assertTrue(recu.await(5, TimeUnit.SECONDS));
|
||||||
|
assertEquals(2, ((List<?>) ((Map<?, ?>) MiniJson.lire(corpsRecus.get(0))).get("detections")).size());
|
||||||
|
assertNotNull(journal.stream().filter(l -> l.contains("reprise")).findFirst().orElse(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void lesMessagesDuJournalNeContiennentJamaisLaCle(@TempDir Path tmp) throws Exception {
|
||||||
|
Transport panne = (a, c, b) -> {
|
||||||
|
throw new IOException("échec contenant " + c); // pire cas : la bibliothèque réseau met la clé dans son message
|
||||||
|
};
|
||||||
|
Signalement.demarrer(cfg(tmp, true, false), cle(tmp), panne, horloge::get, journal::add, "0.3.2");
|
||||||
|
Signalement.surVerdict(UUID.randomUUID(), verdict(Controle.PORTEE, Mode.ENFORCE, Sanction.ALERTE, Sanction.ALERTE, List.of()), null);
|
||||||
|
Thread.sleep(800);
|
||||||
|
Signalement.arreter();
|
||||||
|
assertFalse(journal.isEmpty());
|
||||||
|
List<String> tout = new ArrayList<>(journal);
|
||||||
|
tout.add(Signalement.resume());
|
||||||
|
for (String l : tout) assertFalse(l.contains(CLE), l);
|
||||||
|
}
|
||||||
|
}
|
||||||
Référencer dans un nouveau ticket
Bloquer un utilisateur