feat: déploiement Docker/Coolify — Dockerfile + docker-compose.yml + scalper serve (SCAL-15)
- serveur HTTP stdlib: GET /healthz, GET /check-source, POST /run (gate légal appliqué, 403 si bloqué) - image python:3.12-slim, user non-root, healthcheck, volumes data/out persistants - .env.example (.env ignoré), .dockerignore, docs/deploy-coolify.md - 39 tests OK + smoke loopback
This commit is contained in:
1 parent
876faf3ede
commit
67b165e913
9 files changed
+293
No files matched your search
@@ -0,0 +1,13 @@
|
||||
.git
|
||||
__pycache__
|
||||
*.pyc
|
||||
.venv
|
||||
venv
|
||||
.pytest_cache
|
||||
out
|
||||
data
|
||||
.env
|
||||
sources.toml
|
||||
tests
|
||||
docs
|
||||
skills
|
||||
@@ -0,0 +1,8 @@
|
||||
# Copie ce fichier en .env (déjà dans .gitignore) et renseigne tes valeurs.
|
||||
# Ne jamais committer de vraie clé API.
|
||||
|
||||
MISTRAL_API_KEY=
|
||||
MISTRAL_MODEL=mistral-small-latest
|
||||
|
||||
# Registre de sources personnalisées monté dans le conteneur (optionnel) :
|
||||
# SCALPER_CONFIG=/app/sources.toml
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY pyproject.toml README.md ./
|
||||
COPY src ./src
|
||||
|
||||
RUN pip install --no-cache-dir .
|
||||
|
||||
RUN useradd -m scalper && mkdir -p /app/data /app/out && chown -R scalper:scalper /app
|
||||
USER scalper
|
||||
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
EXPOSE 8000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
|
||||
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz')" || exit 1
|
||||
|
||||
CMD ["scalper", "serve", "--host", "0.0.0.0", "--port", "8000"]
|
||||
@@ -69,6 +69,16 @@ python -m pytest -q # ou python -m unittest discover -s tests
|
||||
|
||||
CI GitHub Actions (lint + tests) sur chaque PR — voir `.github/workflows/ci.yml`.
|
||||
|
||||
## Déploiement Docker / Coolify
|
||||
|
||||
```bash
|
||||
cp .env.example .env # MISTRAL_API_KEY (jamais committer)
|
||||
docker compose up -d # sert http://localhost:8000 (GET /healthz, GET /check-source, POST /run)
|
||||
```
|
||||
|
||||
Déploiement pas à pas sur Coolify : [docs/deploy-coolify.md](docs/deploy-coolify.md).
|
||||
Le conteneur applique le même gate légal que la CLI (sources non déclarées/bloquées refusées).
|
||||
|
||||
## Licence
|
||||
|
||||
MIT — voir [LICENSE](LICENSE).
|
||||
@@ -0,0 +1,31 @@
|
||||
# Déploiement Scalper — prêt pour Coolify (New Resource → Docker Compose depuis ce repo).
|
||||
#
|
||||
# 1) cp .env.example .env et renseigne MISTRAL_API_KEY (jamais committer .env)
|
||||
# 2) (optionnel) cp sources.example.toml sources.toml et déclare tes sources légales
|
||||
# 3) docker compose up -d (ou déploiement Coolify)
|
||||
#
|
||||
# Le conteneur applique le gate légal : sources non déclarées / bloquées
|
||||
# (mangas-origines, keiyoushi.github.io) -> jamais traitées.
|
||||
services:
|
||||
scalper:
|
||||
build: .
|
||||
container_name: scalper
|
||||
ports:
|
||||
- "8000:8000"
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
- PYTHONUNBUFFERED=1
|
||||
# Décommente si tu montes un registre de sources personnalisé :
|
||||
# - SCALPER_CONFIG=/app/sources.toml
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
- ./out:/app/out
|
||||
# Décommente si tu as un sources.toml personnalisé :
|
||||
# - ./sources.toml:/app/sources.toml:ro
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz')"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
@@ -0,0 +1,45 @@
|
||||
# Déployer Scalper sur Coolify (Docker Compose)
|
||||
|
||||
## 1. Préparer le dépôt
|
||||
```bash
|
||||
cp .env.example .env # renseigne MISTRAL_API_KEY (jamais committer .env)
|
||||
# optionnel : cp sources.example.toml sources.toml et déclare tes sources légales
|
||||
# (chaque domaine avec sa licence — obligatoire)
|
||||
```
|
||||
|
||||
## 2. Créer la ressource Coolify
|
||||
1. Coolify → **New Resource** → **Docker Compose** → sélectionne le repo `Orionis312050/Scalper`.
|
||||
2. Coolify détecte `docker-compose.yml` (service `scalper`, port **8000**).
|
||||
3. Dans l'onglet **Environment**, ajoute `MISTRAL_API_KEY` (secret) et éventuellement `SCALPER_CONFIG=/app/sources.toml`.
|
||||
4. (Optionnel) **Volumes** : monte `./sources.toml` en lecture seule si tu déclares des sources personnalisées.
|
||||
5. Déploie, puis attache un domaine. Coolify gère le reverse proxy HTTPS.
|
||||
|
||||
## 3. Vérifier
|
||||
```bash
|
||||
curl https://<ton-domaine>/healthz
|
||||
curl "https://<ton-domaine>/check-source?source=demo"
|
||||
```
|
||||
|
||||
## 4. Lancer un pipeline
|
||||
```bash
|
||||
curl -X POST https://<ton-domaine>/run \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"source":"mangadex","series":"<id>","lang":"fr","group":"Keiyoushi","max_chapters":3}'
|
||||
```
|
||||
Les résultats sont écrits dans le volume `./out` (monté dans le compose).
|
||||
|
||||
## Endpoints
|
||||
| Méthode | Chemin | Rôle |
|
||||
|---|---|---|
|
||||
| GET | `/healthz` | sonde de santé |
|
||||
| GET | `/check-source?source=...` | verdict légal (allowed/blocked) |
|
||||
| POST | `/run` | pipeline complet (check → scrape → clean → translate → QA → export) |
|
||||
|
||||
## Sécurité
|
||||
- Le serveur n'accepte que les sources **déclarées et légales** : domaine inconnu = bloqué,
|
||||
`mangas-origines` / `keiyoushi.github.io` = bloqués (liste inviolable), robots.txt vérifié.
|
||||
- Rate limiting ≥ 1 s entre requêtes vers les sources.
|
||||
- **Conseil** : restreins l'accès à `/run` (authentification Coolify / IP allowlist), car il déclenche
|
||||
du scraping et des appels LLM (coût API) sur ton instance.
|
||||
- Ne mets jamais `MISTRAL_API_KEY` dans le dépôt : `.env` est ignoré par git et exclu de l'image
|
||||
(`.dockerignore`).
|
||||
@@ -77,6 +77,10 @@ def main(argv: list[str] | None = None) -> int:
|
||||
c.add_argument("url")
|
||||
c.add_argument("--out", default="data")
|
||||
|
||||
c = sub.add_parser("serve", help="démarre le serveur HTTP (déploiement Docker/Coolify)")
|
||||
c.add_argument("--host", default="127.0.0.1")
|
||||
c.add_argument("--port", type=int, default=8000)
|
||||
|
||||
c = sub.add_parser("run", help="pipeline complet end-to-end")
|
||||
c.add_argument("--source", required=True)
|
||||
c.add_argument("--series", required=True)
|
||||
@@ -180,6 +184,11 @@ def main(argv: list[str] | None = None) -> int:
|
||||
(dest / "chapter.json").write_text(json.dumps(chapter.to_dict(), ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
_print({"status": "ok", "dest": str(dest), "blocks": len(chapter.blocks), "language": chapter.meta.get("language")})
|
||||
return 0
|
||||
if args.cmd == "serve":
|
||||
from .server import serve
|
||||
|
||||
serve(args.host, args.port)
|
||||
return 0
|
||||
if args.cmd == "run":
|
||||
summary = pipeline.run_pipeline(
|
||||
args.source, args.series, args.lang,
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Serveur HTTP léger (stdlib uniquement) pour déployer Scalper (ex. Coolify).
|
||||
|
||||
Endpoints :
|
||||
- GET /healthz
|
||||
- GET /check-source?source=<url|domaine>
|
||||
- POST /run {"source","series","lang","group"?,"max_chapters"?,"mock_llm"?,"out"?}
|
||||
|
||||
Toutes les requêtes passent par legal-source-check : une source bloquée
|
||||
(mangas-origines, keiyoushi.github.io, domaine non déclaré) n'est jamais traitée.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
from . import legal, pipeline
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args) -> None: # silence les logs par requête
|
||||
pass
|
||||
|
||||
def _json(self, code: int, payload: dict) -> None:
|
||||
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self) -> None:
|
||||
u = urlparse(self.path)
|
||||
if u.path == "/healthz":
|
||||
return self._json(200, {"status": "ok"})
|
||||
if u.path == "/check-source":
|
||||
source = parse_qs(u.query).get("source", [""])[0]
|
||||
if not source:
|
||||
return self._json(400, {"error": "paramètre 'source' requis"})
|
||||
return self._json(200, legal.check_source(source).to_dict())
|
||||
return self._json(404, {"error": "not found"})
|
||||
|
||||
def do_POST(self) -> None:
|
||||
u = urlparse(self.path)
|
||||
if u.path != "/run":
|
||||
return self._json(404, {"error": "not found"})
|
||||
try:
|
||||
length = int(self.headers.get("Content-Length", 0))
|
||||
body = json.loads(self.rfile.read(length) or b"{}")
|
||||
summary = pipeline.run_pipeline(
|
||||
body["source"],
|
||||
body["series"],
|
||||
body["lang"],
|
||||
out_root=body.get("out", "out"),
|
||||
mock_llm=bool(body.get("mock_llm", False)),
|
||||
max_chapters=body.get("max_chapters"),
|
||||
group=body.get("group"),
|
||||
)
|
||||
except KeyError as e:
|
||||
return self._json(400, {"error": f"champ requis manquant: {e}"})
|
||||
except Exception as e:
|
||||
return self._json(500, {"error": str(e)})
|
||||
code = 200 if summary.get("status") == "done" else 403
|
||||
return self._json(code, summary)
|
||||
|
||||
|
||||
def serve(host: str = "127.0.0.1", port: int = 8000) -> None:
|
||||
cfg = os.environ.get("SCALPER_CONFIG")
|
||||
if cfg:
|
||||
if Path(cfg).exists():
|
||||
legal.load_config(cfg)
|
||||
print(f"registre de sources chargé: {cfg}")
|
||||
else:
|
||||
print(f"attention: SCALPER_CONFIG={cfg} introuvable, ignoré")
|
||||
server = ThreadingHTTPServer((host, port), Handler)
|
||||
print(f"scalper serve sur http://{host}:{port} (GET /healthz, GET /check-source, POST /run)")
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
server.shutdown()
|
||||
@@ -0,0 +1,75 @@
|
||||
import json
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from http.server import ThreadingHTTPServer
|
||||
|
||||
from scalper.server import Handler
|
||||
|
||||
|
||||
class TestServer(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
cls.port = cls.server.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.server.shutdown()
|
||||
cls.server.server_close()
|
||||
|
||||
def _get(self, path: str):
|
||||
with urllib.request.urlopen(f"http://127.0.0.1:{self.port}{path}") as r:
|
||||
return r.status, json.loads(r.read())
|
||||
|
||||
def _post(self, path: str, payload: dict):
|
||||
req = urllib.request.Request(
|
||||
f"http://127.0.0.1:{self.port}{path}",
|
||||
data=json.dumps(payload).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req) as r:
|
||||
return r.status, json.loads(r.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.loads(e.read())
|
||||
|
||||
def test_healthz(self):
|
||||
status, body = self._get("/healthz")
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(body["status"], "ok")
|
||||
|
||||
def test_check_source_demo_allowed(self):
|
||||
status, body = self._get("/check-source?source=demo")
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(body["verdict"], "allowed")
|
||||
|
||||
def test_check_source_blocked(self):
|
||||
status, body = self._get("/check-source?source=https://mangas-origines.fr")
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(body["verdict"], "blocked")
|
||||
|
||||
def test_run_demo_mock_llm(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
status, body = self._post("/run", {"source": "demo", "series": "demo-1", "lang": "fr", "mock_llm": True, "out": tmp})
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(body["status"], "done")
|
||||
self.assertEqual(len(body["chapters"]), 2)
|
||||
|
||||
def test_run_blocked_source_returns_403(self):
|
||||
status, body = self._post("/run", {"source": "https://keiyoushi.github.io", "series": "x", "lang": "fr", "mock_llm": True})
|
||||
self.assertEqual(status, 403)
|
||||
self.assertEqual(body["status"], "blocked")
|
||||
|
||||
def test_run_missing_field_400(self):
|
||||
status, body = self._post("/run", {"source": "demo"})
|
||||
self.assertEqual(status, 400)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user