diff --git a/service/src/main/inse/background_jobs/__init__.py b/service/src/main/inse/background_jobs/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/service/src/main/inse/background_jobs/model.py b/service/src/main/inse/background_jobs/model.py new file mode 100644 index 00000000..ffaaa066 --- /dev/null +++ b/service/src/main/inse/background_jobs/model.py @@ -0,0 +1,81 @@ +""" +Database tables for the background job runner. +""" + +from datetime import datetime, timezone +from enum import StrEnum +from typing import Optional + +from sqlmodel import Field, SQLModel + + +class BackgroundJobName(StrEnum): + """Jobs known to the background-jobs image's entrypoint.sh dispatcher.""" + + NEWS = "news" + NEWS_STATS = "news-stats" + + +class JobRunStatus(StrEnum): + RUNNING = "running" + SUCCEEDED = "succeeded" + FAILED = "failed" + STOPPED = "stopped" + + +class JobTriggeredBy(StrEnum): + SCHEDULE = "schedule" + MANUAL = "manual" + + +def utcnow() -> datetime: + return datetime.now(timezone.utc).replace(tzinfo=None) + + +class JobDefinition(SQLModel, table=True): + __tablename__ = "background_job_definition" + + id: Optional[int] = Field(default=None, primary_key=True) + name: str = Field( + index=True, unique=True, description="Human-readable job name shown in the UI." + ) + description: str = Field(default="", description="What this job does.") + target_index: str = Field( + default="", description="Elasticsearch index the job writes to (UI info)." + ) + job: BackgroundJobName = Field( + description="Job argument passed to the background-jobs image's entrypoint." + ) + schedule: Optional[str] = Field( + default=None, + description="Cron expression in UTC (e.g. '0 3 * * *'). Null = manual only.", + ) + enabled: bool = Field( + default=True, description="Disabled definitions are never scheduled." + ) + next_run_at: Optional[datetime] = Field( + default=None, description="Computed by the scheduler from the cron expression." + ) + created_at: datetime = Field(default_factory=utcnow) + + +class JobRun(SQLModel, table=True): + __tablename__ = "background_job_run" + + id: Optional[int] = Field(default=None, primary_key=True) + definition_id: int = Field( + foreign_key="background_job_definition.id", index=True + ) + container_id: Optional[str] = Field(default=None) + status: JobRunStatus = Field(default=JobRunStatus.RUNNING) + triggered_by: JobTriggeredBy = Field( + description="Whether the scheduler or a superadmin started this run." + ) + started_at: datetime = Field(default_factory=utcnow) + finished_at: Optional[datetime] = Field(default=None) + exit_code: Optional[int] = Field(default=None) + logs: Optional[str] = Field( + default=None, + description="Captured stdout/stderr, filled in when the run finishes " + "(the container itself is removed afterwards).", + ) diff --git a/service/src/main/inse/background_jobs/seed.py b/service/src/main/inse/background_jobs/seed.py new file mode 100644 index 00000000..73a5ac1b --- /dev/null +++ b/service/src/main/inse/background_jobs/seed.py @@ -0,0 +1,49 @@ +""" +Seeding of the whitelisted background job definitions. +""" + +import logging + +from sqlmodel import Session, select + +from .model import BackgroundJobName, JobDefinition + +logger = logging.getLogger(__name__) + +PREDEFINED_JOB_DEFINITIONS: list[dict] = [ + { + "name": "News-Aufbereitung", + "description": ( + "Übernimmt neue Artikel aus dem „aktuell“-Index und fügt Relevanz, " + "Personenzuordnungen und Schlagwörter hinzu (Delta-Sync per LLM)." + ), + "target_index": "aktuell_postproc", + "job": BackgroundJobName.NEWS, + "schedule": None, + "enabled": True, + }, + { + "name": "News-Statistik", + "description": ( + "Zählt die Einträge in „aktuell“ und „aktuell_postproc“ (read-only, " + "verändert nichts) — nützlich als Verbindungstest." + ), + "target_index": "aktuell_postproc", + "job": BackgroundJobName.NEWS_STATS, + "schedule": None, + "enabled": True, + }, +] + + +def create_predefined_job_definitions(session: Session) -> None: + """Seed the whitelisted job definitions once (idempotent, keyed by job).""" + for entry in PREDEFINED_JOB_DEFINITIONS: + existing = session.exec( + select(JobDefinition).where(JobDefinition.job == entry["job"]) + ).first() + if existing: + continue + session.add(JobDefinition(**entry)) + logger.info("Seeded background job definition '%s'.", entry["name"]) + session.commit() diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index b8fa3d17..b4d12eec 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -43,6 +43,7 @@ from inse.bookmarks.router import router as bookmarks_router from inse.institutions.router import router as institutions_router from inse.database import create_db_and_tables, get_session from inse.auth.service import create_predefined_accounts +from inse.background_jobs.seed import create_predefined_job_definitions from . import config from .service import router as service_router @@ -69,6 +70,7 @@ async def lifespan(app: FastAPI): create_db_and_tables() with contextmanager(get_session)() as session: create_predefined_accounts(session, "../data/predefined_accounts.json") + create_predefined_job_definitions(session) yield logger.info("Shutting down the application...")