Files
Athena-Deck/deploy/applio-web/backend/app/jobs/store.py
T
Mikei386 06cacafbad Add native Applio RVC and preserve the custom studio UI
Pin Applio 3.6.5 and verified basis assets, migrate private voice provenance, and coordinate conversion/live/training with Deck GPU leases. Prepare an inactive voice profile and a restricted studio container. Move CUDA and Torch caches out of the small temporary filesystem to prevent OmniVoice reference failures. Package app updates from the explicit allowlist in one Docker layer.
2026-10-05 10:02:07 +02:00

216 lines
7.9 KiB
Python

"""SQLite-backed job store with persistence across restarts."""
from __future__ import annotations
import json
import sqlite3
import threading
from datetime import datetime, timedelta
from pathlib import Path
from ..config import get_settings
from .enums import JobStatus
from .models import Job
class JobStore:
"""Thread-safe job store backed by SQLite."""
def __init__(self, db_path: Path | None = None) -> None:
settings = get_settings()
self._db_path = db_path or (settings.jobs_dir / "jobs.db")
try:
self._db_path.parent.mkdir(parents=True, exist_ok=True)
except (PermissionError, OSError):
# Fall back to a local temp dir if the configured path is not writable
import tempfile
self._db_path = Path(tempfile.gettempdir()) / "mikes_applio_jobs.db"
self._db_path.parent.mkdir(parents=True, exist_ok=True)
self._lock = threading.Lock()
self._init_db()
def _connect(self) -> sqlite3.Connection:
conn = sqlite3.connect(str(self._db_path), check_same_thread=False)
conn.row_factory = sqlite3.Row
return conn
def _init_db(self) -> None:
with self._lock, self._connect() as conn:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS jobs (
id TEXT PRIMARY KEY,
type TEXT NOT NULL,
status TEXT NOT NULL,
phase TEXT NOT NULL,
created_at TEXT NOT NULL,
started_at TEXT,
finished_at TEXT,
progress REAL DEFAULT 0,
progress_message TEXT DEFAULT '',
model_name TEXT,
parameters TEXT DEFAULT '{}',
input_files TEXT DEFAULT '[]',
output_files TEXT DEFAULT '[]',
log TEXT DEFAULT '[]',
error TEXT,
cancelled INTEGER DEFAULT 0,
duration_seconds REAL,
last_activity TEXT NOT NULL
)
"""
)
conn.commit()
def save(self, job: Job) -> None:
with self._lock, self._connect() as conn:
conn.execute(
"""
INSERT OR REPLACE INTO jobs (
id, type, status, phase, created_at, started_at, finished_at,
progress, progress_message, model_name, parameters,
input_files, output_files, log, error, cancelled,
duration_seconds, last_activity
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
job.id,
job.type.value,
job.status.value,
job.phase.value,
job.created_at.isoformat(),
job.started_at.isoformat() if job.started_at else None,
job.finished_at.isoformat() if job.finished_at else None,
job.progress,
job.progress_message,
job.model_name,
json.dumps(job.parameters),
json.dumps(job.input_files),
json.dumps(job.output_files),
json.dumps(job.log),
job.error,
1 if job.cancelled else 0,
job.duration_seconds,
job.last_activity.isoformat(),
),
)
conn.commit()
def get(self, job_id: str) -> Job | None:
with self._lock, self._connect() as conn:
row = conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
if row is None:
return None
return self._row_to_job(row)
def list(
self,
status: JobStatus | None = None,
limit: int = 100,
offset: int = 0,
) -> list[Job]:
with self._lock, self._connect() as conn:
if status:
rows = conn.execute(
"SELECT * FROM jobs WHERE status = ? ORDER BY created_at DESC LIMIT ? OFFSET ?",
(status.value, limit, offset),
).fetchall()
else:
rows = conn.execute(
"SELECT * FROM jobs ORDER BY created_at DESC LIMIT ? OFFSET ?",
(limit, offset),
).fetchall()
return [self._row_to_job(r) for r in rows]
def count(self, status: JobStatus | None = None) -> int:
with self._lock, self._connect() as conn:
if status:
row = conn.execute(
"SELECT COUNT(*) as c FROM jobs WHERE status = ?", (status.value,)
).fetchone()
else:
row = conn.execute("SELECT COUNT(*) as c FROM jobs").fetchone()
return row["c"]
def delete_terminal(self, job_id: str) -> bool:
"""Delete one completed job, never an active or queued job."""
with self._lock, self._connect() as conn:
cursor = conn.execute(
"""
DELETE FROM jobs
WHERE id = ?
AND status IN ('erfolgreich', 'fehlgeschlagen', 'abgebrochen')
""",
(job_id,),
)
conn.commit()
return cursor.rowcount == 1
def delete_all_terminal(self) -> list[str]:
"""Delete all completed jobs and return the deleted IDs."""
terminal = ("erfolgreich", "fehlgeschlagen", "abgebrochen")
with self._lock, self._connect() as conn:
rows = conn.execute(
"SELECT id FROM jobs WHERE status IN (?, ?, ?)", terminal
).fetchall()
ids = [row["id"] for row in rows]
conn.executemany(
"""
DELETE FROM jobs
WHERE id = ?
AND status IN ('erfolgreich', 'fehlgeschlagen', 'abgebrochen')
""",
[(job_id,) for job_id in ids],
)
conn.commit()
return ids
def cleanup_old(self, retention_days: int) -> int:
"""Remove jobs older than retention_days that are in terminal state."""
cutoff = datetime.now() - timedelta(days=retention_days)
with self._lock, self._connect() as conn:
cursor = conn.execute(
"""
DELETE FROM jobs
WHERE status IN ('erfolgreich', 'fehlgeschlagen', 'abgebrochen')
AND finished_at < ?
""",
(cutoff.isoformat(),),
)
conn.commit()
return cursor.rowcount
def _row_to_job(self, row: sqlite3.Row) -> Job:
from .enums import JobPhase, JobType
return Job(
id=row["id"],
type=JobType(row["type"]),
status=JobStatus(row["status"]),
phase=JobPhase(row["phase"]),
created_at=datetime.fromisoformat(row["created_at"]),
started_at=datetime.fromisoformat(row["started_at"]) if row["started_at"] else None,
finished_at=datetime.fromisoformat(row["finished_at"]) if row["finished_at"] else None,
progress=row["progress"],
progress_message=row["progress_message"],
model_name=row["model_name"],
parameters=json.loads(row["parameters"]),
input_files=json.loads(row["input_files"]),
output_files=json.loads(row["output_files"]),
log=json.loads(row["log"]),
error=row["error"],
cancelled=bool(row["cancelled"]),
duration_seconds=row["duration_seconds"],
last_activity=datetime.fromisoformat(row["last_activity"]),
)
_store: JobStore | None = None
def get_job_store() -> JobStore:
global _store
if _store is None:
_store = JobStore()
return _store