Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff22377619 |
@@ -33,20 +33,6 @@ ssh vps "cd /opt/aep-worker && npm install --omit=dev"
|
||||
`package.json` du worker peut être simplifié à cette occasion, ou laissé tel
|
||||
quel si `dotenv` sert encore pour un lancement manuel en local.)
|
||||
|
||||
## 1 bis. Écrire le témoin de version (obligatoire, lot « témoins » du 22/11)
|
||||
|
||||
Juste après la copie, depuis le poste de dev, à la racine du dépôt :
|
||||
|
||||
```bash
|
||||
ssh vps "/usr/local/bin/veille-temoins.sh --poser-version $(git log -1 --format=%h origin/main -- worker/)"
|
||||
```
|
||||
|
||||
Écrit `/opt/aep-worker/VERSION` (commit, empreinte des fichiers copiés, date). La
|
||||
veille quotidienne (`deploy/veille/`) le compare au dernier commit de `main` qui
|
||||
touche `worker/` : un worker resté en retard de plus de 48 h, ou recopié sans ce
|
||||
geste, produit une alerte ntfy. Si on déploie depuis une branche, mettre le commit
|
||||
de la branche : la veille dira l'écart avec `main` tant que la branche n'est pas mergée.
|
||||
|
||||
## 2. Poser les unités systemd
|
||||
|
||||
```bash
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
# Veille du VPS (lot « témoins », 22/11/2026)
|
||||
|
||||
Un script lancé une fois par jour (08:30) qui vérifie ce qui tourne seul et n'envoie
|
||||
un message ntfy que si quelque chose cloche ; le lundi, un message même quand tout va
|
||||
bien (versions et disque). Il ne garde aucun état : un défaut qui dure se redit chaque jour.
|
||||
|
||||
Ce qu'il vérifie : worker d'AEP (minuteur actif, dernier passage réussi de moins de
|
||||
24 h, pas trois échecs de suite, `VERSION` égal au dernier commit de `main` sur
|
||||
`worker/` à 48 h près) · `aep.`, `event.…/ruetz`, `maison.`, `quartier.` en 200 ·
|
||||
`/health` de REinNOVER à `statut: ok` et son alerte BDNB · `build.json` du Quartier ·
|
||||
`/health` du RAG 9623 depuis le VPS · moins de 4 G libres sur `/`.
|
||||
|
||||
Il ne remplace pas `healthcheck-sites.sh` (cron 10 min) ni `check-disk.sh` (paliers) :
|
||||
eux voient vite, lui voit large et prouve qu'il vit.
|
||||
|
||||
## Installer (root sur le VPS)
|
||||
|
||||
```bash
|
||||
scp deploy/veille/veille-temoins.sh vps:/usr/local/bin/
|
||||
scp deploy/veille/veille-temoins.service deploy/veille/veille-temoins.timer vps:/etc/systemd/system/
|
||||
ssh vps "chmod 755 /usr/local/bin/veille-temoins.sh && systemctl daemon-reload && systemctl enable --now veille-temoins.timer"
|
||||
ssh vps "/usr/local/bin/veille-temoins.sh --poser-version $(git log -1 --format=%h origin/main -- worker/)"
|
||||
```
|
||||
|
||||
## Essayer sans rien casser
|
||||
|
||||
```bash
|
||||
ssh vps "veille-temoins.sh --sec --hebdo" # affiche, n'envoie rien
|
||||
ssh vps "veille-temoins.sh --seuil-disque-go 100" # défaut provoqué, envoyé
|
||||
ssh vps "veille-temoins.sh --url-essai https://aep.trans-former.fr/n-existe-pas"
|
||||
ssh vps "veille-temoins.sh --hebdo" # message hebdomadaire
|
||||
```
|
||||
|
||||
Journal : `/var/log/veille-temoins.log` (une ligne par passage, mesures seulement).
|
||||
|
||||
## Retour arrière
|
||||
|
||||
```bash
|
||||
ssh vps "systemctl disable --now veille-temoins.timer"
|
||||
```
|
||||
@@ -1,9 +0,0 @@
|
||||
[Unit]
|
||||
Description=Veille du VPS — témoins de ce qui tourne seul (worker AEP, sites, RAG 9623, disque, BDNB)
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/local/bin/veille-temoins.sh
|
||||
TimeoutStartSec=300
|
||||
@@ -1,176 +0,0 @@
|
||||
#!/bin/bash
|
||||
# veille-temoins.sh — témoins de ce qui tourne seul sur le VPS (lot « témoins », 22/11/2026)
|
||||
#
|
||||
# Lancé une fois par jour par veille-temoins.timer (08:30). N'envoie rien quand tout va
|
||||
# bien, sauf le lundi : un message hebdomadaire dit les versions et le disque, pour que
|
||||
# le silence ne puisse pas vouloir dire « le veilleur est mort ».
|
||||
# Aucun état gardé : un défaut qui dure se redit chaque jour (un anti-spam à état binaire
|
||||
# éteint une alerte de seuil, cf. pieges-connus §10, check-disk du 08/08).
|
||||
# Le message ne porte que des mesures : jamais de texte de contributeur, jamais de nom.
|
||||
# Le worker est lu par les seules lignes de systemd (_PID=1), jamais par sa sortie.
|
||||
#
|
||||
# Usage :
|
||||
# veille-temoins.sh passage normal
|
||||
# veille-temoins.sh --hebdo force le message hebdomadaire
|
||||
# veille-temoins.sh --sec n'envoie rien, affiche le message
|
||||
# veille-temoins.sh --seuil-disque-go N seuil d'alerte disque en Go (défaut 4)
|
||||
# veille-temoins.sh --url-essai URL ajoute une adresse qui doit répondre 200
|
||||
# veille-temoins.sh --poser-version COMMIT écrit /opt/aep-worker/VERSION (au déploiement)
|
||||
#
|
||||
# Retour arrière : systemctl disable --now veille-temoins.timer
|
||||
|
||||
set -uo pipefail
|
||||
|
||||
ENV_FILE=/opt/aep/.env
|
||||
WORKER_DIR=/opt/aep-worker
|
||||
VERSION_FILE=$WORKER_DIR/VERSION
|
||||
AEP_NITRO=/opt/aep/.output/nitro.json
|
||||
LOG=/var/log/veille-temoins.log
|
||||
GITEA_API="https://git.trans-former.fr/api/v1/repos/jules/nav-carte/commits?sha=main&path=worker&limit=1&stat=false&verification=false&files=false"
|
||||
SITES=(
|
||||
https://aep.trans-former.fr
|
||||
https://event.trans-former.fr/ruetz
|
||||
https://maison.trans-former.fr
|
||||
https://quartier.trans-former.fr
|
||||
)
|
||||
REINNOVER_HEALTH=https://maison.trans-former.fr/health
|
||||
QUARTIER_BUILD=https://quartier.trans-former.fr/build.json
|
||||
RAG_HEALTH=http://127.0.0.1:9623/health
|
||||
SEUIL_GO=4
|
||||
DELAI_DEPLOIEMENT_H=48 # main peut précéder le déploiement du worker pendant ce délai
|
||||
|
||||
empreinte_worker() { (cd "$WORKER_DIR" && cat enrich.js lib/*.js 2>/dev/null | sha256sum | cut -c1-16); }
|
||||
|
||||
poser_version() {
|
||||
local c="${1:-}"
|
||||
[[ "$c" =~ ^[0-9a-f]{7,40}$ ]] || { echo "commit invalide : '$c'" >&2; exit 2; }
|
||||
printf 'commit=%s\nempreinte=%s\ndeploye=%s\n' "${c:0:7}" "$(empreinte_worker)" "$(date -Iseconds)" > "$VERSION_FILE"
|
||||
cat "$VERSION_FILE"
|
||||
}
|
||||
|
||||
jqv() { printf '%s' "$1" | jq -r "$2" 2>/dev/null; }
|
||||
code_http() { curl -s -o /dev/null -w '%{http_code}' --max-time 15 "$1"; }
|
||||
|
||||
HEBDO=0; SEC=0
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--hebdo) HEBDO=1 ;;
|
||||
--sec) SEC=1 ;;
|
||||
--seuil-disque-go) SEUIL_GO="${2:?valeur manquante}"; shift ;;
|
||||
--url-essai) SITES+=("${2:?adresse manquante}"); shift ;;
|
||||
--poser-version) poser_version "${2:-}"; exit 0 ;;
|
||||
*) echo "argument inconnu : $1" >&2; exit 2 ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
[ "$(date +%u)" = 1 ] && HEBDO=1
|
||||
|
||||
DEFAUTS=()
|
||||
MAINTENANT=$(date +%s)
|
||||
|
||||
# --- 1. Worker d'AEP -------------------------------------------------------------
|
||||
T=$(systemctl is-active aep-worker.timer 2>/dev/null)
|
||||
[ "$T" = active ] || DEFAUTS+=("worker : minuteur $T")
|
||||
|
||||
ISSUES=$(journalctl -u aep-worker.service _PID=1 --since -7d -o short-unix --no-pager 2>/dev/null \
|
||||
| awk '/Finished /{print $1, "ok"} /Failed with result/{print $1, "echec"}')
|
||||
DERNIER_OK=$(printf '%s\n' "$ISSUES" | awk '$2=="ok"{t=$1} END{print int(t)}')
|
||||
if [ "${DERNIER_OK:-0}" -eq 0 ]; then
|
||||
DEFAUTS+=("worker : aucun passage réussi depuis 7 jours")
|
||||
else
|
||||
AGE_H=$(( (MAINTENANT - DERNIER_OK) / 3600 ))
|
||||
[ "$AGE_H" -ge 24 ] && DEFAUTS+=("worker : dernier passage réussi il y a ${AGE_H} h")
|
||||
fi
|
||||
ECHECS=$(printf '%s\n' "$ISSUES" | tail -3 | grep -c ' echec$')
|
||||
[ "$ECHECS" -ge 3 ] && DEFAUTS+=("worker : trois échecs de suite")
|
||||
|
||||
W_VER="?"; W_ETAT=""
|
||||
if [ ! -f "$VERSION_FILE" ]; then
|
||||
DEFAUTS+=("worker : pas de fichier VERSION (déployé sans témoin)")
|
||||
else
|
||||
W_VER=$(sed -n 's/^commit=//p' "$VERSION_FILE")
|
||||
W_EMP=$(sed -n 's/^empreinte=//p' "$VERSION_FILE")
|
||||
[ "$W_EMP" = "$(empreinte_worker)" ] || DEFAUTS+=("worker : fichiers changés depuis le déploiement de $W_VER (VERSION périmé)")
|
||||
ATTENDU=$(curl -s --max-time 15 "$GITEA_API" | jq -r '.[0] | "\(.sha[0:7]) \(.created)"' 2>/dev/null)
|
||||
if [[ ! "$ATTENDU" =~ ^[0-9a-f]{7}\ .+ ]]; then
|
||||
DEFAUTS+=("worker : version attendue illisible (API Gitea)")
|
||||
else
|
||||
A_SHA=${ATTENDU%% *}; A_DATE=${ATTENDU#* }
|
||||
if [ "$A_SHA" = "$W_VER" ]; then
|
||||
W_ETAT="à jour"
|
||||
else
|
||||
A_AGE_H=$(( (MAINTENANT - $(date -d "$A_DATE" +%s)) / 3600 ))
|
||||
W_ETAT="main porte $A_SHA"
|
||||
[ "$A_AGE_H" -ge "$DELAI_DEPLOIEMENT_H" ] && DEFAUTS+=("worker : déployé $W_VER, main porte $A_SHA depuis ${A_AGE_H} h")
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# --- 2. Sites (une seconde chance à 20 s, pour ne pas alerter sur un hoquet) -----
|
||||
for u in "${SITES[@]}"; do
|
||||
c=$(code_http "$u")
|
||||
[ "$c" = 200 ] || { sleep 20; c=$(code_http "$u"); }
|
||||
[ "$c" = 200 ] || DEFAUTS+=("site : ${u#https://} répond $c")
|
||||
done
|
||||
|
||||
RH=$(curl -s --max-time 15 "$REINNOVER_HEALTH")
|
||||
R_STATUT=$(jqv "$RH" '.statut // empty'); R_BUILD=$(jqv "$RH" '.build // empty')
|
||||
[ "$R_STATUT" = ok ] || DEFAUTS+=("REinNOVER : /health statut ${R_STATUT:-illisible}")
|
||||
|
||||
QB=$(curl -s --max-time 15 "$QUARTIER_BUILD")
|
||||
Q_HASH=$(jqv "$QB" '.hash // empty')
|
||||
[ -n "$Q_HASH" ] || DEFAUTS+=("Quartier : build.json illisible")
|
||||
|
||||
# --- 3. RAG 9623 (chatbot public), depuis le VPS ----------------------------------
|
||||
c=$(code_http "$RAG_HEALTH")
|
||||
[ "$c" = 200 ] || DEFAUTS+=("RAG 9623 : /health répond $c")
|
||||
|
||||
# --- 4. Disque --------------------------------------------------------------------
|
||||
LIBRE_K=$(df --output=avail -k / | tail -1 | tr -dc '0-9')
|
||||
LIBRE_G=$(awk -v k="$LIBRE_K" 'BEGIN{printf "%.1f", k/1048576}' | tr . ,)
|
||||
awk -v k="$LIBRE_K" -v s="${SEUIL_GO/,/.}" 'BEGIN{exit !(k/1048576 < s)}' \
|
||||
&& DEFAUTS+=("disque : $LIBRE_G G libres (seuil $SEUIL_GO G)")
|
||||
|
||||
# --- 5. Quota BDNB (l'alerte que rend déjà /health de REinNOVER) ------------------
|
||||
if [ "$(jqv "$RH" '.bdnb.alerte // false')" = true ]; then
|
||||
DEFAUTS+=("BDNB : alerte de quota (restant $(jqv "$RH" '.bdnb.restant'), limite $(jqv "$RH" '.bdnb.limite'))")
|
||||
fi
|
||||
|
||||
# --- Message ----------------------------------------------------------------------
|
||||
AEP_DATE=$(jq -r '.date // empty' "$AEP_NITRO" 2>/dev/null)
|
||||
AEP_BUILD=$( [ -n "$AEP_DATE" ] && date -d "$AEP_DATE" '+%d/%m %H:%M' || echo '?')
|
||||
VERSIONS="worker $W_VER${W_ETAT:+ ($W_ETAT)} · AEP build du $AEP_BUILD · REinNOVER ${R_BUILD:-?} · Quartier ${Q_HASH:-?} · disque $LIBRE_G G libres"
|
||||
|
||||
N=${#DEFAUTS[@]}
|
||||
TS=$(date '+%Y-%m-%d %H:%M:%S')
|
||||
if [ "$N" -eq 0 ] && [ "$HEBDO" -eq 0 ]; then
|
||||
echo "$TS ok $VERSIONS" >> "$LOG"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "$N" -gt 0 ]; then
|
||||
TITRE="VPS : $N défaut(s)"; PRIO=4; TAGS='["warning"]'
|
||||
CORPS=$(printf '%s\n' "${DEFAUTS[@]}")
|
||||
[ "$HEBDO" -eq 1 ] && CORPS="$CORPS"$'\n'"$VERSIONS"
|
||||
else
|
||||
TITRE="VPS : veille hebdomadaire, tout va bien"; PRIO=3; TAGS='[]'
|
||||
CORPS="$VERSIONS"
|
||||
fi
|
||||
|
||||
if [ "$SEC" -eq 1 ]; then
|
||||
printf '[sec] %s (priorité %s)\n%s\n' "$TITRE" "$PRIO" "$CORPS"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Sujet ntfy lu dans l'environnement du VPS, jamais affiché ni écrit au journal.
|
||||
TOPIC=$(grep -E '^NTFY_TOPIC=' "$ENV_FILE" 2>/dev/null | tail -1 | cut -d= -f2- | tr -d "\"' \r")
|
||||
if [ -z "$TOPIC" ]; then
|
||||
echo "$TS ECHEC sujet ntfy absent de $ENV_FILE ($N défaut(s))" >> "$LOG"
|
||||
exit 1
|
||||
fi
|
||||
CODE=$(jq -n --arg t "$TOPIC" --arg ti "$TITRE" --arg m "$CORPS" --argjson p "$PRIO" --argjson g "$TAGS" \
|
||||
'{topic:$t, title:$ti, message:$m, priority:$p, tags:$g}' \
|
||||
| curl -s -o /dev/null -w '%{http_code}' --max-time 15 -H 'Content-Type: application/json' --data-binary @- https://ntfy.sh/)
|
||||
echo "$TS envoi=$CODE defauts=$N hebdo=$HEBDO ${DEFAUTS[*]:-}" >> "$LOG"
|
||||
tail -2000 "$LOG" > "$LOG.tmp" 2>/dev/null && mv "$LOG.tmp" "$LOG"
|
||||
[ "$CODE" = 200 ]
|
||||
@@ -1,9 +0,0 @@
|
||||
[Unit]
|
||||
Description=Veille du VPS une fois par jour (message hebdomadaire le lundi)
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 08:30:00
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -7,6 +7,7 @@
|
||||
"dev": "nuxt dev",
|
||||
"generate": "nuxt generate",
|
||||
"preview": "nuxt preview",
|
||||
"test:routes": "node scripts/test-routes.mjs",
|
||||
"test": "node scripts/test-echelles-nav.mjs && node scripts/test-figures.mjs && node scripts/test-vue-fiches.mjs && node scripts/test-submit-libre.mjs && node scripts/test-circuit-breaker.mjs && node scripts/test-bandeau.mjs && node scripts/test-outils-data.mjs && node scripts/test-citations.mjs && node scripts/test-seo.mjs && node scripts/test-y.mjs && node scripts/test-connaissances.mjs && node scripts/test-bibliotheque.mjs && node scripts/test-media-data.mjs && node scripts/test-taxonomie.mjs && node scripts/test-geocodage.mjs && node scripts/test-migrer-taxonomie.mjs && node scripts/test-fiche-publique.mjs && node --test \"worker/test/*.test.js\"",
|
||||
"postinstall": "nuxt prepare"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
/**
|
||||
* Banc de routes (lot SURFACE, étape A) : le serveur Nuxt BÂTI (`.output/server/index.mjs`)
|
||||
* démarré sur un port local, tous ses services externes remplacés par UN faux serveur local
|
||||
* qui enregistre ce qu'il reçoit et répond ce qu'on lui dit.
|
||||
*
|
||||
* Aucun appel réel : l'application démarre avec un environnement VIDE (pas celui du shell,
|
||||
* pas de .env), où chaque adresse de service pointe le faux serveur et chaque clé vaut « faux ».
|
||||
*
|
||||
* Usage (voir scripts/test-routes.mjs) :
|
||||
* import { demarrerBanc } from './banc-routes.mjs'
|
||||
* const banc = await demarrerBanc() // bâtit si besoin, démarre faux + appli
|
||||
* banc.faux.repondre.bifrost = (req) => ({ json: { … } })
|
||||
* const r = await banc.requete('/api/chatbot', { method: 'POST', json: { question: '…' }, ip: '10.0.0.1' })
|
||||
* banc.faux.recu('resend') // requêtes reçues par le faux Resend
|
||||
* await banc.arreter()
|
||||
*
|
||||
* Services simulés (préfixe d'URL sur le faux serveur → variable d'environnement de l'appli) :
|
||||
* /nocodb → NUXT_NOCODB_URL GET/POST /api/v2/tables/:table/records
|
||||
* /bifrost → NUXT_BIFROST_URL POST /v1/chat/completions
|
||||
* /mistral → MISTRAL_API_URL POST /v1/chat/completions (filtre des commentaires)
|
||||
* /resend → RESEND_API_URL POST /emails (signalements)
|
||||
* /rag → NUXT_RAG_PE_URL GET /health, POST /query (LightRAG Pensées)
|
||||
* /rag-emancipation → NUXT_RAG_EMANCIPATION_URL
|
||||
* Redis pointe un port fermé : la limite de débit Redis retombe sur son compteur en mémoire.
|
||||
*/
|
||||
|
||||
import { spawn, spawnSync } from 'node:child_process'
|
||||
import { createServer } from 'node:http'
|
||||
import { existsSync, mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join, dirname } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const RACINE = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
|
||||
const TABLES = { orgs: 'tbl_orgs', stats: 'tbl_stats', comments: 'tbl_comments', avis: 'tbl_avis' }
|
||||
|
||||
function lireCorps(req) {
|
||||
return new Promise((resolve) => {
|
||||
const morceaux = []
|
||||
req.on('data', (c) => morceaux.push(c))
|
||||
req.on('end', () => {
|
||||
const brut = Buffer.concat(morceaux).toString('utf-8')
|
||||
let json = null
|
||||
try { json = brut ? JSON.parse(brut) : null } catch { /* corps non JSON */ }
|
||||
resolve({ brut, json })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** Réponse Bifrost par défaut : un JSON valide, servi par un fournisseur gratuit. */
|
||||
export function reponseBifrost(contenu = { reponse_texte: 'Réponse du faux modèle.', fiches_recommandees: [] }, extra = {}) {
|
||||
return {
|
||||
json: {
|
||||
choices: [{ message: { content: typeof contenu === 'string' ? contenu : JSON.stringify(contenu) }, finish_reason: 'stop' }],
|
||||
usage: { prompt_tokens: 1000, completion_tokens: 200 },
|
||||
extra_fields: { provider: 'groq', resolved_model_used: 'groq/openai/gpt-oss-20b' },
|
||||
...extra,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** Réponse Mistral (filtre des commentaires) dont le `content` vaut `contenu` tel quel. */
|
||||
export function reponseMistral(contenu) {
|
||||
return { json: { choices: [{ message: { content: contenu } }] } }
|
||||
}
|
||||
|
||||
function fauxParDefaut() {
|
||||
return {
|
||||
nocodb: (req) => {
|
||||
const m = req.chemin.match(/^\/api\/v2\/tables\/([^/]+)\/records/)
|
||||
if (!m) return { status: 404, json: { msg: 'faux NocoDB : chemin inconnu' } }
|
||||
if (req.methode === 'GET') {
|
||||
const lignes = m[1] === TABLES.orgs ? [{ Id: 1, nom: 'Organisation témoin', description_enrichie: 'architecture paille', tags_fonction: 'Conseil', echelle: 'Locale', localisation_ville: 'Lyon' }] : []
|
||||
return { json: { list: lignes, pageInfo: { isLastPage: true } } }
|
||||
}
|
||||
return { json: { Id: 42 } }
|
||||
},
|
||||
bifrost: () => reponseBifrost(),
|
||||
mistral: () => reponseMistral('{"safe": true, "category": null, "reason": null}'),
|
||||
resend: () => ({ json: { id: 'faux-courriel' } }),
|
||||
rag: (req) => (req.chemin === '/health' ? { json: { status: 'healthy' } } : { json: { response: 'Réponse du faux RAG.', references: [] } }),
|
||||
'rag-emancipation': (req) => (req.chemin === '/health' ? { json: { status: 'healthy' } } : { json: { response: 'Réponse du faux RAG Émancipation.', references: [] } }),
|
||||
}
|
||||
}
|
||||
|
||||
/** Faux serveur unique : enregistre chaque requête reçue, répond par `repondre[service]`. */
|
||||
export async function demarrerFaux() {
|
||||
const journal = []
|
||||
const repondre = fauxParDefaut()
|
||||
const serveur = createServer(async (req, res) => {
|
||||
const url = new URL(req.url, 'http://faux')
|
||||
const [, service, ...reste] = url.pathname.split('/')
|
||||
const { brut, json } = await lireCorps(req)
|
||||
const entree = {
|
||||
service,
|
||||
methode: req.method,
|
||||
chemin: '/' + reste.join('/'),
|
||||
query: Object.fromEntries(url.searchParams),
|
||||
entetes: req.headers,
|
||||
brut,
|
||||
json,
|
||||
}
|
||||
journal.push(entree)
|
||||
const fn = repondre[service]
|
||||
let r = fn ? await fn(entree) : { status: 404, json: { msg: `faux serveur : service inconnu « ${service} »` } }
|
||||
if (r?.delaiMs) await new Promise((ok) => setTimeout(ok, r.delaiMs))
|
||||
if (res.destroyed) return
|
||||
res.writeHead(r?.status ?? 200, { 'Content-Type': 'application/json' })
|
||||
res.end(r?.json !== undefined ? JSON.stringify(r.json) : (r?.texte ?? ''))
|
||||
})
|
||||
await new Promise((ok) => serveur.listen(0, '127.0.0.1', ok))
|
||||
const url = `http://127.0.0.1:${serveur.address().port}`
|
||||
return {
|
||||
url,
|
||||
journal,
|
||||
repondre,
|
||||
/** Requêtes reçues par un service (toutes si `service` absent). */
|
||||
recu: (service) => (service ? journal.filter((e) => e.service === service) : journal.slice()),
|
||||
/** Vide le journal et remet les réponses par défaut. */
|
||||
reinitialiser() {
|
||||
journal.length = 0
|
||||
Object.assign(repondre, fauxParDefaut())
|
||||
},
|
||||
arreter: () => new Promise((ok) => { serveur.closeAllConnections?.(); serveur.close(() => ok()) }),
|
||||
}
|
||||
}
|
||||
|
||||
/** Bâtit l'application (`nuxt build`) sauf si BANC_SANS_BUILD=1 et qu'un `.output` existe. */
|
||||
export function batir() {
|
||||
const sortie = join(RACINE, '.output', 'server', 'index.mjs')
|
||||
if (process.env.BANC_SANS_BUILD === '1' && existsSync(sortie)) {
|
||||
console.log('[banc] BANC_SANS_BUILD=1 : build existant réutilisé')
|
||||
return
|
||||
}
|
||||
console.log('[banc] nuxt build… (environ une minute)')
|
||||
const t0 = Date.now()
|
||||
const r = spawnSync('npx', ['nuxt', 'build'], { cwd: RACINE, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' })
|
||||
if (r.status !== 0) {
|
||||
console.error(r.stdout?.slice(-4000), r.stderr?.slice(-4000))
|
||||
throw new Error('[banc] nuxt build a échoué')
|
||||
}
|
||||
console.log(`[banc] build fait en ${Math.round((Date.now() - t0) / 1000)} s`)
|
||||
}
|
||||
|
||||
function portLibre() {
|
||||
return new Promise((ok) => {
|
||||
const s = createServer()
|
||||
s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => ok(p)) })
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Démarre le faux serveur puis l'application bâtie. `envSup` ajoute ou remplace des variables
|
||||
* d'environnement de l'application.
|
||||
*/
|
||||
export async function demarrerBanc({ envSup = {}, build = true } = {}) {
|
||||
if (build) batir()
|
||||
const faux = await demarrerFaux()
|
||||
const port = await portLibre()
|
||||
const dossierLimites = mkdtempSync(join(tmpdir(), 'banc-limites-'))
|
||||
const env = {
|
||||
PATH: process.env.PATH,
|
||||
NODE_ENV: 'production',
|
||||
HOST: '127.0.0.1',
|
||||
PORT: String(port),
|
||||
NUXT_NOCODB_URL: `${faux.url}/nocodb`,
|
||||
NUXT_NOCODB_TOKEN: 'faux',
|
||||
NUXT_ORG_TABLE_ID: TABLES.orgs,
|
||||
NUXT_STATS_TABLE_ID: TABLES.stats,
|
||||
STATS_TABLE_ID: TABLES.stats,
|
||||
NUXT_COMMENT_TABLE_ID: TABLES.comments,
|
||||
NUXT_AVIS_TABLE_ID: TABLES.avis,
|
||||
NUXT_BIFROST_URL: `${faux.url}/bifrost`,
|
||||
NUXT_BIFROST_VK: 'faux',
|
||||
NUXT_MISTRAL_API_KEY: 'faux',
|
||||
MISTRAL_API_URL: `${faux.url}/mistral`,
|
||||
RESEND_API_KEY: 'faux',
|
||||
RESEND_API_URL: `${faux.url}/resend`,
|
||||
NUXT_RESEND_API_KEY: 'faux',
|
||||
EMAIL_JULES: 'jules@exemple.invalid',
|
||||
NUXT_EMAIL_JULES: 'jules@exemple.invalid',
|
||||
NUXT_RAG_PE_URL: `${faux.url}/rag`,
|
||||
NUXT_RAG_EMANCIPATION_URL: `${faux.url}/rag-emancipation`,
|
||||
NUXT_RAG_EMANCIPATION_KEY: 'faux',
|
||||
NUXT_REDIS_URL: 'redis://127.0.0.1:1',
|
||||
NAV_RATELIMIT_DIR: dossierLimites,
|
||||
...envSup,
|
||||
}
|
||||
const appli = spawn(process.execPath, [join(RACINE, '.output', 'server', 'index.mjs')], { cwd: RACINE, env, stdio: ['ignore', 'pipe', 'pipe'] })
|
||||
const journalAppli = []
|
||||
appli.stdout.on('data', (d) => journalAppli.push(String(d)))
|
||||
appli.stderr.on('data', (d) => journalAppli.push(String(d)))
|
||||
const base = `http://127.0.0.1:${port}`
|
||||
|
||||
let pret = false
|
||||
for (let i = 0; i < 100 && !pret; i++) {
|
||||
if (appli.exitCode !== null) break
|
||||
try { await fetch(`${base}/robots.txt`); pret = true } catch { await new Promise((ok) => setTimeout(ok, 100)) }
|
||||
}
|
||||
if (!pret) {
|
||||
appli.kill('SIGKILL')
|
||||
await faux.arreter()
|
||||
throw new Error(`[banc] l'application n'a pas démarré :\n${journalAppli.join('')}`)
|
||||
}
|
||||
|
||||
let ipSuivante = 1
|
||||
return {
|
||||
base,
|
||||
faux,
|
||||
tables: TABLES,
|
||||
/** Journal (stdout + stderr) de l'application. */
|
||||
journalAppli: () => journalAppli.join(''),
|
||||
/** Une adresse de visiteur neuve à chaque appel (les limites de débit sont par adresse). */
|
||||
ipNeuve: () => `10.${(ipSuivante >> 16) & 255}.${(ipSuivante >> 8) & 255}.${ipSuivante++ & 255}`,
|
||||
/**
|
||||
* Requête HTTP contre l'application. `json` : corps JSON ; `brut` : corps tel quel ;
|
||||
* `ip` : valeur de X-Forwarded-For (sinon une adresse neuve). Rend { status, json, texte }.
|
||||
*/
|
||||
async requete(chemin, { method = 'GET', json, brut, ip, entetes = {} } = {}) {
|
||||
const headers = { 'x-forwarded-for': ip ?? this.ipNeuve(), ...entetes }
|
||||
let body
|
||||
if (json !== undefined) { body = JSON.stringify(json); headers['content-type'] = 'application/json' }
|
||||
if (brut !== undefined) { body = brut; headers['content-type'] ??= 'application/json' }
|
||||
const res = await fetch(`${base}${chemin}`, { method, headers, body })
|
||||
const texte = await res.text()
|
||||
let j = null
|
||||
try { j = JSON.parse(texte) } catch { /* HTML ou vide */ }
|
||||
return { status: res.status, json: j, texte }
|
||||
},
|
||||
async arreter() {
|
||||
if (appli.exitCode === null) {
|
||||
appli.kill('SIGTERM')
|
||||
await new Promise((ok) => { const t = setTimeout(() => { appli.kill('SIGKILL'); ok() }, 3000); appli.once('exit', () => { clearTimeout(t); ok() }) })
|
||||
}
|
||||
await faux.arreter()
|
||||
rmSync(dossierLimites, { recursive: true, force: true })
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** Attend qu'une condition devienne vraie (écritures non attendues par la route, ex. stats_usage). */
|
||||
export async function attendre(cond, { delaiMs = 3000, pasMs = 50 } = {}) {
|
||||
const fin = Date.now() + delaiMs
|
||||
while (Date.now() < fin) {
|
||||
if (await cond()) return true
|
||||
await new Promise((ok) => setTimeout(ok, pasMs))
|
||||
}
|
||||
return Boolean(await cond())
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Banc de routes (lot SURFACE) : bâtit l'application une fois, la démarre sur un port local
|
||||
* et joue des requêtes HTTP contre elle. Les services externes sont remplacés par le faux
|
||||
* serveur de scripts/banc-routes.mjs, qui enregistre ce qu'il reçoit. Aucun appel réel.
|
||||
*
|
||||
* Usage : npm run test:routes (bâtit, ~1 min)
|
||||
* BANC_SANS_BUILD=1 npm run test:routes (réutilise .output)
|
||||
*/
|
||||
|
||||
import { demarrerBanc } from './banc-routes.mjs'
|
||||
|
||||
let ok = 0
|
||||
let ko = 0
|
||||
const echecs = []
|
||||
function check(nom, cond, detail = '') {
|
||||
if (cond) { ok++; console.log(` ✓ ${nom}`) }
|
||||
else { ko++; echecs.push(nom); console.log(` ✗ ${nom}${detail ? ` — ${detail}` : ''}`) }
|
||||
}
|
||||
|
||||
const banc = await demarrerBanc()
|
||||
const { faux } = banc
|
||||
|
||||
async function groupe(titre, fn) {
|
||||
console.log(`\n${titre}`)
|
||||
faux.reinitialiser()
|
||||
try { await fn() } catch (e) { ko++; echecs.push(`${titre} : exception`); console.log(` ✗ exception : ${e?.stack ?? e}`) }
|
||||
}
|
||||
|
||||
try {
|
||||
await groupe('A. Le banc joue les routes', async () => {
|
||||
const r = await banc.requete('/robots.txt')
|
||||
check('GET /robots.txt → 200', r.status === 200, `status ${r.status}`)
|
||||
|
||||
for (const chemin of ['/evenements/ruetz', '/evenements/ruetz/codev', '/evenements/ruetz/foret']) {
|
||||
const p = await banc.requete(chemin)
|
||||
check(`témoin Ruetz ${chemin} → 200`, p.status === 200, `status ${p.status}`)
|
||||
}
|
||||
|
||||
const c = await banc.requete('/api/chatbot', { method: 'POST', json: { question: 'Qui fait de la paille à Lyon ?' } })
|
||||
check('POST /api/chatbot nominal → 200', c.status === 200, `status ${c.status} ${c.texte.slice(0, 200)}`)
|
||||
check('… la réponse vient du faux Bifrost', c.json?.reponse_texte === 'Réponse du faux modèle.')
|
||||
check('… le faux Bifrost a reçu un appel', faux.recu('bifrost').length === 1)
|
||||
|
||||
const s = await banc.requete('/api/report', { method: 'POST', json: { fiche_id: 1, message: 'Le lien est mort.', email: 'a@b.fr' } })
|
||||
check('POST /api/report nominal → 200', s.status === 200, `status ${s.status} ${s.texte.slice(0, 200)}`)
|
||||
check('… le faux Resend a reçu le courriel', faux.recu('resend').length === 1)
|
||||
|
||||
const inconnus = faux.recu().filter((e) => !['nocodb', 'bifrost', 'mistral', 'resend', 'rag', 'rag-emancipation'].includes(e.service))
|
||||
check('aucun appel vers un service non simulé', inconnus.length === 0, inconnus.map((e) => e.service).join(', '))
|
||||
})
|
||||
} finally {
|
||||
await banc.arreter()
|
||||
}
|
||||
|
||||
console.log(`\ntest-routes : ${ok} sur ${ok + ko}${ko ? ` — échecs : ${echecs.join(' · ')}` : ''}`)
|
||||
process.exit(ko ? 1 : 0)
|
||||
@@ -15,6 +15,9 @@
|
||||
|
||||
import { checkRateLimit } from '~/server/utils/rateLimit'
|
||||
|
||||
// Adresse de l'API Mistral, réglable pour le banc de routes (scripts/banc-routes.mjs).
|
||||
const MISTRAL_API_URL = process.env.MISTRAL_API_URL || 'https://api.mistral.ai'
|
||||
|
||||
interface CommentBody {
|
||||
orga_id: number
|
||||
contenu: string
|
||||
@@ -36,7 +39,7 @@ async function filtreEthique(
|
||||
const timeout = setTimeout(() => controller.abort(), 2000)
|
||||
|
||||
try {
|
||||
const response: any = await $fetch('https://api.mistral.ai/v1/chat/completions', {
|
||||
const response: any = await $fetch(`${MISTRAL_API_URL}/v1/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${mistralKey}`,
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
import { checkRateLimitJson } from '~/server/utils/rateLimitJson'
|
||||
|
||||
const EMAIL_JULES = process.env.EMAIL_JULES || 'jules@trans-former.fr'
|
||||
// Adresse de l'API Resend, réglable pour le banc de routes (scripts/banc-routes.mjs).
|
||||
const RESEND_API_URL = process.env.RESEND_API_URL || 'https://api.resend.com'
|
||||
|
||||
const VALID_CATEGORIES = ['Une fiche', 'Le chatbot', 'La carte', 'Autre'] as const
|
||||
|
||||
@@ -60,7 +62,7 @@ export default defineEventHandler(async (event) => {
|
||||
const submittedAt = new Date().toLocaleString('fr-FR', { timeZone: 'Europe/Paris' })
|
||||
|
||||
try {
|
||||
await $fetch('https://api.resend.com/emails', {
|
||||
await $fetch(`${RESEND_API_URL}/emails`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${resendApiKey}`,
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
import { checkRateLimitJson } from '~/server/utils/rateLimitJson'
|
||||
|
||||
const EMAIL_JULES = process.env.EMAIL_JULES || 'jules@trans-former.fr'
|
||||
// Adresse de l'API Resend, réglable pour le banc de routes (scripts/banc-routes.mjs).
|
||||
const RESEND_API_URL = process.env.RESEND_API_URL || 'https://api.resend.com'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// 1. IP
|
||||
@@ -57,7 +59,7 @@ export default defineEventHandler(async (event) => {
|
||||
const submittedAt = new Date().toLocaleString('fr-FR', { timeZone: 'Europe/Paris' })
|
||||
|
||||
try {
|
||||
await $fetch('https://api.resend.com/emails', {
|
||||
await $fetch(`${RESEND_API_URL}/emails`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${resendApiKey}`,
|
||||
|
||||
@@ -15,7 +15,8 @@ import { createHash } from 'crypto'
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
|
||||
const RATELIMIT_DIR = '/tmp/nav-ratelimit'
|
||||
// Réglable pour le banc de routes (un dossier jetable par passage).
|
||||
const RATELIMIT_DIR = process.env.NAV_RATELIMIT_DIR || '/tmp/nav-ratelimit'
|
||||
|
||||
type RateLimitFile = {
|
||||
[action: string]: { count: number; date: string }
|
||||
|
||||
Reference in New Issue
Block a user