✨ 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
+24
-7
@@ -53,6 +53,10 @@ def build_base_url(url: str | None, port: int | None = None) -> str | None:
|
||||
|
||||
|
||||
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)
|
||||
sonarr: 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()
|
||||
|
||||
|
||||
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()
|
||||
if not path.exists():
|
||||
return AppConfig()
|
||||
return None
|
||||
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.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.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.
|
||||
tmp_dir = str(path.parent)
|
||||
with tempfile.NamedTemporaryFile(
|
||||
@@ -134,9 +147,13 @@ def write_config(config: AppConfig) -> None:
|
||||
suffix=".tmp",
|
||||
delete=False,
|
||||
) as handle:
|
||||
json.dump(serialized, handle, indent=2, ensure_ascii=False)
|
||||
json.dump(data, handle, indent=2, ensure_ascii=False)
|
||||
handle.write("\n")
|
||||
tmp_name = handle.name
|
||||
|
||||
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.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy import inspect, select, text, update
|
||||
from sqlalchemy import select, update
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
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.database import Base, engine, get_db
|
||||
from app.migrations import migrate_conf_file, run_db_migrations
|
||||
from app.models import IsoMovie
|
||||
from app.qbittorrent import QbittorrentClient, match_torrent
|
||||
from app.radarr import RadarrClient, movie_file_path
|
||||
@@ -53,26 +54,14 @@ from app.worker import conversion_worker
|
||||
async def lifespan(_: FastAPI):
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
# Very small "migration" helper for dev: add new columns if the SQLite DB already exists.
|
||||
# (SQLAlchemy create_all doesn't alter existing tables.)
|
||||
try:
|
||||
inspector = inspect(engine)
|
||||
columns = {col["name"] for col in inspector.get_columns("iso_movies")}
|
||||
migrations = {
|
||||
"processed_at": "DATETIME",
|
||||
"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
|
||||
# Migrations versionnees (base + conf.json), tracees au demarrage.
|
||||
db_applied = run_db_migrations(engine)
|
||||
if db_applied:
|
||||
print(f"migrations de base appliquees: {', '.join(db_applied)}", flush=True)
|
||||
conf_applied = migrate_conf_file()
|
||||
if conf_applied:
|
||||
print(f"migrations conf.json: {', '.join(conf_applied)}", flush=True)
|
||||
|
||||
auth.bootstrap_setup()
|
||||
_log_config_summary()
|
||||
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
|
||||
Reference in new issue
Block a user