✨ Migrations versionnees de la base et de conf.json (schema_migrations + cle version)
This commit is contained in:
1 parent
3a75527135
commit
c7344f8988
5 files changed
+325
-28
No files matched your search
@@ -10,6 +10,15 @@ La configuration des services (Radarr, Sonarr, Prowlarr, Jellyfin, Overseerr/See
|
|||||||
- L'interface modifie ce fichier via l'API (écriture atomique côté backend).
|
- L'interface modifie ce fichier via l'API (écriture atomique côté backend).
|
||||||
- Chaque service expose un statut dans la page Configuration: `Non configuré` (URL ou clé API manquante), `Configuré · non testé`, `Testé` (dernier test de connexion réussi, version affichée) ou `Test échoué`. Le résultat du dernier test est conservé dans `conf.json` (bloc `test`) et invalidé dès que l'URL ou les identifiants changent.
|
- Chaque service expose un statut dans la page Configuration: `Non configuré` (URL ou clé API manquante), `Configuré · non testé`, `Testé` (dernier test de connexion réussi, version affichée) ou `Test échoué`. Le résultat du dernier test est conservé dans `conf.json` (bloc `test`) et invalidé dès que l'URL ou les identifiants changent.
|
||||||
|
|
||||||
|
## Migrations (base de données et conf.json)
|
||||||
|
|
||||||
|
Les évolutions de structure sont versionnées et appliquées automatiquement au démarrage (`app/migrations.py`):
|
||||||
|
|
||||||
|
- **Base de données**: chaque migration est un `DbMigration` numéroté, appliqué dans sa propre transaction et tracé dans la table `schema_migrations`. Une migration doit rester inoffensive sur un schéma déjà à jour (vérifier l'existence des tables/colonnes avant d'agir), car `create_all` crée déjà le schéma complet sur une base vierge.
|
||||||
|
- **conf.json**: le fichier porte une clé `version` en tête. `CONF_MIGRATIONS` contient des fonctions `(dict) -> dict` qui transforment le contenu brut de la version N vers N+1, appliquées en chaîne jusqu'à la version courante. La valeur par défaut de `AppConfig.version` (dans `app/conf_store.py`) doit être mise à jour en même temps; un test vérifie cet invariant.
|
||||||
|
|
||||||
|
Pour ajouter une migration: ajouter l'entrée en fin de `DB_MIGRATIONS` ou de `CONF_MIGRATIONS` avec le numéro de version suivant, puis un test qui couvre la transformation depuis un état ancien.
|
||||||
|
|
||||||
Radarr (rappel API):
|
Radarr (rappel API):
|
||||||
|
|
||||||
- Base: `/api/v3`
|
- Base: `/api/v3`
|
||||||
|
|||||||
+24
-7
@@ -53,6 +53,10 @@ def build_base_url(url: str | None, port: int | None = None) -> str | None:
|
|||||||
|
|
||||||
|
|
||||||
class AppConfig(BaseModel):
|
class AppConfig(BaseModel):
|
||||||
|
# Version de la structure du fichier, migree au demarrage
|
||||||
|
# (voir app/migrations.py). Doit rester synchrone avec
|
||||||
|
# current_conf_version(): un test verifie cet invariant.
|
||||||
|
version: int = 1
|
||||||
radarr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
radarr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
||||||
sonarr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
sonarr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
||||||
prowlarr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
prowlarr: ApiServiceConfig = Field(default_factory=ApiServiceConfig)
|
||||||
@@ -108,22 +112,31 @@ def reset_test(service: ApiServiceConfig | QbittorrentConfig) -> None:
|
|||||||
service.test = TestState()
|
service.test = TestState()
|
||||||
|
|
||||||
|
|
||||||
def read_config() -> AppConfig:
|
def read_raw_config() -> dict | None:
|
||||||
|
"""Contenu brut de conf.json (dict), ou None s'il est absent.
|
||||||
|
|
||||||
|
Sert aux migrations, qui transforment le fichier avant validation
|
||||||
|
pydantic. Un contenu invalide (non-dict) est traite comme absent.
|
||||||
|
"""
|
||||||
path = config_path()
|
path = config_path()
|
||||||
if not path.exists():
|
if not path.exists():
|
||||||
return AppConfig()
|
return None
|
||||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||||
if not isinstance(raw, dict):
|
return raw if isinstance(raw, dict) else None
|
||||||
|
|
||||||
|
|
||||||
|
def read_config() -> AppConfig:
|
||||||
|
raw = read_raw_config()
|
||||||
|
if raw is None:
|
||||||
return AppConfig()
|
return AppConfig()
|
||||||
return AppConfig.model_validate(raw)
|
return AppConfig.model_validate(raw)
|
||||||
|
|
||||||
|
|
||||||
def write_config(config: AppConfig) -> None:
|
def write_raw_config(data: dict) -> None:
|
||||||
|
"""Ecriture atomique du contenu brut de conf.json."""
|
||||||
path = config_path()
|
path = config_path()
|
||||||
path.parent.mkdir(parents=True, exist_ok=True)
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
serialized = config.model_dump(mode="json", exclude_none=True)
|
|
||||||
|
|
||||||
# Atomic write to avoid corrupting conf.json if the process is interrupted.
|
# Atomic write to avoid corrupting conf.json if the process is interrupted.
|
||||||
tmp_dir = str(path.parent)
|
tmp_dir = str(path.parent)
|
||||||
with tempfile.NamedTemporaryFile(
|
with tempfile.NamedTemporaryFile(
|
||||||
@@ -134,9 +147,13 @@ def write_config(config: AppConfig) -> None:
|
|||||||
suffix=".tmp",
|
suffix=".tmp",
|
||||||
delete=False,
|
delete=False,
|
||||||
) as handle:
|
) as handle:
|
||||||
json.dump(serialized, handle, indent=2, ensure_ascii=False)
|
json.dump(data, handle, indent=2, ensure_ascii=False)
|
||||||
handle.write("\n")
|
handle.write("\n")
|
||||||
tmp_name = handle.name
|
tmp_name = handle.name
|
||||||
|
|
||||||
os.replace(tmp_name, path)
|
os.replace(tmp_name, path)
|
||||||
|
|
||||||
|
|
||||||
|
def write_config(config: AppConfig) -> None:
|
||||||
|
write_raw_config(config.model_dump(mode="json", exclude_none=True))
|
||||||
|
|
||||||
+10
-21
@@ -10,7 +10,7 @@ import httpx
|
|||||||
from fastapi import Cookie, Depends, FastAPI, HTTPException, Response
|
from fastapi import Cookie, Depends, FastAPI, HTTPException, Response
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from fastapi.responses import FileResponse
|
from fastapi.responses import FileResponse
|
||||||
from sqlalchemy import inspect, select, text, update
|
from sqlalchemy import select, update
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from app import auth
|
from app import auth
|
||||||
@@ -27,6 +27,7 @@ from app.conf_store import (
|
|||||||
)
|
)
|
||||||
from app.converter import cancel_conversion, conversion_paths, finalize_validation
|
from app.converter import cancel_conversion, conversion_paths, finalize_validation
|
||||||
from app.database import Base, engine, get_db
|
from app.database import Base, engine, get_db
|
||||||
|
from app.migrations import migrate_conf_file, run_db_migrations
|
||||||
from app.models import IsoMovie
|
from app.models import IsoMovie
|
||||||
from app.qbittorrent import QbittorrentClient, match_torrent
|
from app.qbittorrent import QbittorrentClient, match_torrent
|
||||||
from app.radarr import RadarrClient, movie_file_path
|
from app.radarr import RadarrClient, movie_file_path
|
||||||
@@ -53,26 +54,14 @@ from app.worker import conversion_worker
|
|||||||
async def lifespan(_: FastAPI):
|
async def lifespan(_: FastAPI):
|
||||||
Base.metadata.create_all(bind=engine)
|
Base.metadata.create_all(bind=engine)
|
||||||
|
|
||||||
# Very small "migration" helper for dev: add new columns if the SQLite DB already exists.
|
# Migrations versionnees (base + conf.json), tracees au demarrage.
|
||||||
# (SQLAlchemy create_all doesn't alter existing tables.)
|
db_applied = run_db_migrations(engine)
|
||||||
try:
|
if db_applied:
|
||||||
inspector = inspect(engine)
|
print(f"migrations de base appliquees: {', '.join(db_applied)}", flush=True)
|
||||||
columns = {col["name"] for col in inspector.get_columns("iso_movies")}
|
conf_applied = migrate_conf_file()
|
||||||
migrations = {
|
if conf_applied:
|
||||||
"processed_at": "DATETIME",
|
print(f"migrations conf.json: {', '.join(conf_applied)}", flush=True)
|
||||||
"completed_at": "DATETIME",
|
|
||||||
"failed_step": "TEXT",
|
|
||||||
"last_error": "TEXT",
|
|
||||||
"poster_url": "TEXT",
|
|
||||||
"radarr_linked": "BOOLEAN DEFAULT 1",
|
|
||||||
}
|
|
||||||
with engine.begin() as conn:
|
|
||||||
for column, ddl in migrations.items():
|
|
||||||
if column not in columns:
|
|
||||||
conn.execute(text(f"ALTER TABLE iso_movies ADD COLUMN {column} {ddl}"))
|
|
||||||
except Exception:
|
|
||||||
# Don't fail app startup for a best-effort migration.
|
|
||||||
pass
|
|
||||||
auth.bootstrap_setup()
|
auth.bootstrap_setup()
|
||||||
_log_config_summary()
|
_log_config_summary()
|
||||||
worker_task = asyncio.create_task(conversion_worker())
|
worker_task = asyncio.create_task(conversion_worker())
|
||||||
|
|||||||
@@ -0,0 +1,156 @@
|
|||||||
|
"""Migrations versionnees de la base de donnees et de conf.json.
|
||||||
|
|
||||||
|
Chaque evolution de structure est une migration identifiee par un numero de
|
||||||
|
version. Au demarrage, les migrations non appliquees sont jouees une seule
|
||||||
|
fois et tracees :
|
||||||
|
|
||||||
|
- base de donnees : table ``schema_migrations`` (une ligne par version) ;
|
||||||
|
- conf.json : cle ``version`` en tete du fichier.
|
||||||
|
|
||||||
|
Conventions importantes :
|
||||||
|
|
||||||
|
- ``Base.metadata.create_all`` cree deja le schema le plus recent sur une
|
||||||
|
base vierge. Les migrations de base doivent donc etre inoffensives sur un
|
||||||
|
schema deja a jour (verifier l'existence des tables/colonnes avant d'agir).
|
||||||
|
- Les migrations sont appliquees dans l'ordre, chacune dans sa transaction,
|
||||||
|
et enregistrees dans la meme transaction : une migration echouee laisse la
|
||||||
|
base dans l'etat de la version precedente.
|
||||||
|
|
||||||
|
Pour ajouter une migration :
|
||||||
|
|
||||||
|
- base de donnees : ajouter un ``DbMigration`` en fin de ``DB_MIGRATIONS``
|
||||||
|
avec le numero de version suivant ;
|
||||||
|
- conf.json : ajouter une fonction ``(dict) -> dict`` en fin de
|
||||||
|
``CONF_MIGRATIONS`` (elle transforme la version N vers N+1), puis mettre a
|
||||||
|
jour la valeur par défaut de ``AppConfig.version`` dans conf_store.py.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Callable
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
|
||||||
|
from sqlalchemy import Connection, inspect, text
|
||||||
|
from sqlalchemy.engine import Engine
|
||||||
|
|
||||||
|
from app.conf_store import read_raw_config, write_raw_config
|
||||||
|
|
||||||
|
|
||||||
|
# --- Migrations de la base de donnees ---
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class DbMigration:
|
||||||
|
"""Une migration de base : version cible, description, corps."""
|
||||||
|
|
||||||
|
version: int
|
||||||
|
description: str
|
||||||
|
upgrade: Callable[[Connection], None]
|
||||||
|
|
||||||
|
|
||||||
|
def _upgrade_v1(conn: Connection) -> None:
|
||||||
|
"""Colonnes de suivi des conversions (bases creees avant le systeme)."""
|
||||||
|
inspector = inspect(conn)
|
||||||
|
if not inspector.has_table("iso_movies"):
|
||||||
|
return
|
||||||
|
columns = {col["name"] for col in inspector.get_columns("iso_movies")}
|
||||||
|
new_columns = {
|
||||||
|
"processed_at": "DATETIME",
|
||||||
|
"completed_at": "DATETIME",
|
||||||
|
"failed_step": "TEXT",
|
||||||
|
"last_error": "TEXT",
|
||||||
|
"poster_url": "TEXT",
|
||||||
|
"radarr_linked": "BOOLEAN DEFAULT 1",
|
||||||
|
}
|
||||||
|
for column, ddl in new_columns.items():
|
||||||
|
if column not in columns:
|
||||||
|
conn.execute(text(f"ALTER TABLE iso_movies ADD COLUMN {column} {ddl}"))
|
||||||
|
|
||||||
|
|
||||||
|
DB_MIGRATIONS: list[DbMigration] = [
|
||||||
|
DbMigration(
|
||||||
|
version=1,
|
||||||
|
description="iso_movies: colonnes de suivi des conversions",
|
||||||
|
upgrade=_upgrade_v1,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def run_db_migrations(engine: Engine) -> list[str]:
|
||||||
|
"""Applique les migrations non jouees; renvoie leurs descriptions."""
|
||||||
|
with engine.begin() as conn:
|
||||||
|
conn.execute(
|
||||||
|
text(
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
|
version INTEGER PRIMARY KEY,
|
||||||
|
description TEXT NOT NULL,
|
||||||
|
applied_at TEXT NOT NULL
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
with engine.connect() as conn:
|
||||||
|
applied = {
|
||||||
|
row[0] for row in conn.execute(text("SELECT version FROM schema_migrations"))
|
||||||
|
}
|
||||||
|
|
||||||
|
done: list[str] = []
|
||||||
|
for migration in DB_MIGRATIONS:
|
||||||
|
if migration.version in applied:
|
||||||
|
continue
|
||||||
|
with engine.begin() as conn:
|
||||||
|
migration.upgrade(conn)
|
||||||
|
conn.execute(
|
||||||
|
text(
|
||||||
|
"""
|
||||||
|
INSERT INTO schema_migrations (version, description, applied_at)
|
||||||
|
VALUES (:version, :description, :applied_at)
|
||||||
|
"""
|
||||||
|
),
|
||||||
|
{
|
||||||
|
"version": migration.version,
|
||||||
|
"description": migration.description,
|
||||||
|
"applied_at": datetime.now(UTC).isoformat(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
done.append(migration.description)
|
||||||
|
return done
|
||||||
|
|
||||||
|
|
||||||
|
# --- Migrations de conf.json ---
|
||||||
|
# CONF_MIGRATIONS[i] transforme le contenu brut du fichier de la version
|
||||||
|
# i+1 vers i+2. La version courante de la structure suit la longueur de
|
||||||
|
# cette liste; elle doit rester synchrone avec AppConfig.version par defaut.
|
||||||
|
CONF_MIGRATIONS: list[Callable[[dict], dict]] = []
|
||||||
|
|
||||||
|
|
||||||
|
def current_conf_version() -> int:
|
||||||
|
return 1 + len(CONF_MIGRATIONS)
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_conf_file() -> list[str]:
|
||||||
|
"""Migre conf.json vers la version courante de la structure.
|
||||||
|
|
||||||
|
Un fichier sans cle ``version`` est considere comme v1 (structure
|
||||||
|
d'avant la mise en place du systeme). Renvoie la liste des migrations
|
||||||
|
appliquees, pour trace au demarrage.
|
||||||
|
"""
|
||||||
|
raw = read_raw_config()
|
||||||
|
if raw is None:
|
||||||
|
return []
|
||||||
|
|
||||||
|
version = raw.get("version")
|
||||||
|
if not isinstance(version, int):
|
||||||
|
version = 1
|
||||||
|
|
||||||
|
applied: list[str] = []
|
||||||
|
for step, migrate in enumerate(CONF_MIGRATIONS, start=1):
|
||||||
|
if version > step:
|
||||||
|
continue
|
||||||
|
raw = migrate(raw)
|
||||||
|
applied.append(f"conf.json v{step} -> v{step + 1}")
|
||||||
|
|
||||||
|
target = current_conf_version()
|
||||||
|
if raw.get("version") != target:
|
||||||
|
raw["version"] = target
|
||||||
|
write_raw_config(raw)
|
||||||
|
return applied
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import json
|
||||||
|
|
||||||
|
from sqlalchemy import create_engine, inspect, text
|
||||||
|
|
||||||
|
from app import models # noqa: F401 - enregistre les modeles SQLAlchemy
|
||||||
|
from app.conf_store import AppConfig, config_path, write_raw_config
|
||||||
|
from app.database import Base
|
||||||
|
from app.migrations import (
|
||||||
|
CONF_MIGRATIONS,
|
||||||
|
current_conf_version,
|
||||||
|
migrate_conf_file,
|
||||||
|
run_db_migrations,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_db_migration_from_legacy_schema(tmp_path) -> None:
|
||||||
|
"""Une base 'legacy' (colonnes v1 absentes) est migree, sans perdre les
|
||||||
|
donnees, et la migration n'est jouee qu'une seule fois."""
|
||||||
|
engine = create_engine(f"sqlite:///{tmp_path / 'legacy.db'}")
|
||||||
|
with engine.begin() as conn:
|
||||||
|
conn.execute(
|
||||||
|
text(
|
||||||
|
"""
|
||||||
|
CREATE TABLE iso_movies (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
radarr_movie_id INTEGER,
|
||||||
|
radarr_movie_file_id INTEGER,
|
||||||
|
title TEXT,
|
||||||
|
path TEXT,
|
||||||
|
status TEXT,
|
||||||
|
last_seen_at DATETIME
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
text(
|
||||||
|
"INSERT INTO iso_movies (radarr_movie_id, radarr_movie_file_id,"
|
||||||
|
" title, path, status) VALUES (10, 20, 'ISO Movie', '/x.iso', 'detected')"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
applied = run_db_migrations(engine)
|
||||||
|
|
||||||
|
assert applied == ["iso_movies: colonnes de suivi des conversions"]
|
||||||
|
columns = {col["name"] for col in inspect(engine).get_columns("iso_movies")}
|
||||||
|
assert {
|
||||||
|
"processed_at",
|
||||||
|
"completed_at",
|
||||||
|
"failed_step",
|
||||||
|
"last_error",
|
||||||
|
"poster_url",
|
||||||
|
"radarr_linked",
|
||||||
|
} <= columns
|
||||||
|
|
||||||
|
# Les donnees existantes sont conservees.
|
||||||
|
with engine.connect() as conn:
|
||||||
|
rows = list(conn.execute(text("SELECT title, radarr_linked FROM iso_movies")))
|
||||||
|
assert rows == [("ISO Movie", 1)]
|
||||||
|
|
||||||
|
# La version est tracee et la migration n'est pas rejouee.
|
||||||
|
with engine.connect() as conn:
|
||||||
|
recorded = list(conn.execute(text("SELECT version FROM schema_migrations")))
|
||||||
|
assert [row[0] for row in recorded] == [1]
|
||||||
|
assert run_db_migrations(engine) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_db_migration_fresh_database(tmp_path) -> None:
|
||||||
|
"""Sur une base vierge, create_all cree deja le schema complet: la
|
||||||
|
migration v1 est inoffensive mais reste tracee."""
|
||||||
|
engine = create_engine(f"sqlite:///{tmp_path / 'fresh.db'}")
|
||||||
|
Base.metadata.create_all(bind=engine)
|
||||||
|
|
||||||
|
applied = run_db_migrations(engine)
|
||||||
|
|
||||||
|
assert applied == ["iso_movies: colonnes de suivi des conversions"]
|
||||||
|
assert run_db_migrations(engine) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_conf_file_stamped_with_version() -> None:
|
||||||
|
"""Un conf.json d'avant le systeme (sans cle version) est charge tel quel
|
||||||
|
et estampille avec la version courante."""
|
||||||
|
write_raw_config({"radarr": {"url": "http://radarr:7878", "api_key": "k"}})
|
||||||
|
|
||||||
|
applied = migrate_conf_file()
|
||||||
|
|
||||||
|
assert applied == []
|
||||||
|
raw = json.loads(config_path().read_text(encoding="utf-8"))
|
||||||
|
assert raw["version"] == current_conf_version()
|
||||||
|
assert raw["radarr"]["url"] == "http://radarr:7878"
|
||||||
|
assert raw["radarr"]["api_key"] == "k"
|
||||||
|
|
||||||
|
|
||||||
|
def test_conf_migration_transforms_content(monkeypatch) -> None:
|
||||||
|
"""Une migration conf.json transforme le contenu et incremente la version,
|
||||||
|
en chaine jusqu'a la version courante."""
|
||||||
|
def v1_to_v2(data: dict) -> dict:
|
||||||
|
data["jellyfin"] = data.pop("jellyfin_old", {})
|
||||||
|
return data
|
||||||
|
|
||||||
|
def v2_to_v3(data: dict) -> dict:
|
||||||
|
data["prowlarr"] = {"url": None}
|
||||||
|
return data
|
||||||
|
|
||||||
|
monkeypatch.setattr("app.migrations.CONF_MIGRATIONS", [v1_to_v2, v2_to_v3])
|
||||||
|
assert current_conf_version() == 3
|
||||||
|
write_raw_config({"version": 1, "jellyfin_old": {"url": "http://jf:8096"}})
|
||||||
|
|
||||||
|
applied = migrate_conf_file()
|
||||||
|
|
||||||
|
assert applied == ["conf.json v1 -> v2", "conf.json v2 -> v3"]
|
||||||
|
raw = json.loads(config_path().read_text(encoding="utf-8"))
|
||||||
|
assert raw["version"] == 3
|
||||||
|
assert raw["jellyfin"] == {"url": "http://jf:8096"}
|
||||||
|
assert "jellyfin_old" not in raw
|
||||||
|
assert raw["prowlarr"] == {"url": None}
|
||||||
|
|
||||||
|
# Deja a jour: plus aucune migration a appliquer.
|
||||||
|
assert migrate_conf_file() == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_appconfig_version_matches_registry(monkeypatch) -> None:
|
||||||
|
"""Invariant: la version par defaut d'AppConfig suit le registre de
|
||||||
|
migrations conf.json."""
|
||||||
|
monkeypatch.setattr("app.migrations.CONF_MIGRATIONS", CONF_MIGRATIONS)
|
||||||
|
assert AppConfig().version == current_conf_version()
|
||||||
Reference in new issue
Block a user