From 4b4ba20ef8ac0495220e73769e430b0757d82242 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Tue, 13 Oct 2026 07:26:27 -0500 Subject: [PATCH] feat(worker): implement async SQLite WAL engine, ORM model, and Alembic migrations - Build async SQLAlchemy engine with PRAGMA journal_mode=WAL, foreign_keys=ON, and synchronous=NORMAL - Implement DownloadJob ORM model with protobuf mapping and state transition guards - Initialize Alembic async migrations and create initial download_jobs table schema - Add unit test suite in tests/test_db.py covering WAL pragmas, CRUD, and state transitions - Update todo.txt marking Priority (A) tasks complete --- alembic.ini | 148 ++++++++++ services/worker/alembic.ini | 41 +++ services/worker/alembic/README | 1 + services/worker/alembic/env.py | 84 ++++++ services/worker/alembic/script.py.mako | 28 ++ ...234da461ab5b_create_download_jobs_table.py | 64 +++++ services/worker/src/worker/db/__init__.py | 33 +++ services/worker/src/worker/db/engine.py | 134 +++++++++ services/worker/src/worker/db/models.py | 261 ++++++++++++++++++ tests/test_db.py | 216 +++++++++++++++ todo.txt | 8 +- 11 files changed, 1014 insertions(+), 4 deletions(-) create mode 100644 alembic.ini create mode 100644 services/worker/alembic.ini create mode 100644 services/worker/alembic/README create mode 100644 services/worker/alembic/env.py create mode 100644 services/worker/alembic/script.py.mako create mode 100644 services/worker/alembic/versions/234da461ab5b_create_download_jobs_table.py create mode 100644 services/worker/src/worker/db/__init__.py create mode 100644 services/worker/src/worker/db/engine.py create mode 100644 services/worker/src/worker/db/models.py create mode 100644 tests/test_db.py diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..ce20d8e --- /dev/null +++ b/alembic.ini @@ -0,0 +1,148 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts. +# this is typically a path given in POSIX (e.g. forward slashes) +# format, relative to the token %(here)s which refers to the location of this +# ini file +script_location = %(here)s/services/worker/alembic + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s +# Or organize into date-based subdirectories (requires recursive_version_locations = true) +# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. for multiple paths, the path separator +# is defined by "path_separator" below. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the tzdata library which can be installed by adding +# `alembic[tz]` to the pip requirements. +# string value is passed to ZoneInfo() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to /versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "path_separator" +# below. +# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions + +# path_separator; This indicates what character is used to split lists of file +# paths, including version_locations and prepend_sys_path within configparser +# files such as alembic.ini. +# The default rendered in new alembic.ini files is "os", which uses os.pathsep +# to provide os-dependent path splitting. +# +# Note that in order to support legacy alembic.ini files, this default does NOT +# take place if path_separator is not present in alembic.ini. If this +# option is omitted entirely, fallback logic is as follows: +# +# 1. Parsing of the version_locations option falls back to using the legacy +# "version_path_separator" key, which if absent then falls back to the legacy +# behavior of splitting on spaces and/or commas. +# 2. Parsing of the prepend_sys_path option falls back to the legacy +# behavior of splitting on spaces, commas, or colons. +# +# Valid values for path_separator are: +# +# path_separator = : +# path_separator = ; +# path_separator = space +# path_separator = newline +# +# Use os.pathsep. Default configuration used for new projects. +path_separator = os + + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +# database URL. This is consumed by the user-maintained env.py script only. +# other means of configuring database URLs may be customized within the env.py +sqlalchemy.url = sqlite+aiosqlite:///data/magnetflix.sqlite3 + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module +# hooks = ruff +# ruff.type = module +# ruff.module = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Alternatively, use the exec runner to execute a binary found on your PATH +# hooks = ruff +# ruff.type = exec +# ruff.executable = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Logging configuration. This is also consumed by the user-maintained +# env.py script only. +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARNING +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARNING +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/services/worker/alembic.ini b/services/worker/alembic.ini new file mode 100644 index 0000000..80e9ee5 --- /dev/null +++ b/services/worker/alembic.ini @@ -0,0 +1,41 @@ +# A generic, single database configuration for worker container/package. + +[alembic] +script_location = %(here)s/alembic +prepend_sys_path = src +path_separator = os +sqlalchemy.url = sqlite+aiosqlite:///data/magnetflix.sqlite3 + +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/services/worker/alembic/README b/services/worker/alembic/README new file mode 100644 index 0000000..e0d0858 --- /dev/null +++ b/services/worker/alembic/README @@ -0,0 +1 @@ +Generic single-database configuration with an async dbapi. \ No newline at end of file diff --git a/services/worker/alembic/env.py b/services/worker/alembic/env.py new file mode 100644 index 0000000..6b1afd8 --- /dev/null +++ b/services/worker/alembic/env.py @@ -0,0 +1,84 @@ +import asyncio +import os +from logging.config import fileConfig +from pathlib import Path + +from alembic import context +from sqlalchemy import pool +from sqlalchemy.engine import Connection +from sqlalchemy.ext.asyncio import create_async_engine +from worker.db.engine import normalize_database_url +from worker.db.models import Base + +config = context.config + +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +target_metadata = Base.metadata + + +def get_url() -> str: + """Retrieve normalized async database URL.""" + env_url = os.getenv("DATABASE_URL") + ini_url = config.get_main_option("sqlalchemy.url") + chosen = env_url or ini_url or "sqlite+aiosqlite:///data/magnetflix.sqlite3" + url = normalize_database_url(chosen) + + prefix = "sqlite+aiosqlite:///" + if url.startswith(prefix): + raw_path = url[len(prefix) :] + if raw_path and raw_path != ":memory:": + Path(raw_path).resolve().parent.mkdir(parents=True, exist_ok=True) + return url + + +def run_migrations_offline() -> None: + """Run migrations in 'offline' mode.""" + url = get_url() + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + render_as_batch=True, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def do_run_migrations(connection: Connection) -> None: + """Configure migration context on active connection.""" + context.configure( + connection=connection, + target_metadata=target_metadata, + render_as_batch=True, + ) + + with context.begin_transaction(): + context.run_migrations() + + +async def run_async_migrations() -> None: + """Run migrations asynchronously using an AsyncEngine.""" + connectable = create_async_engine( + get_url(), + poolclass=pool.NullPool, + ) + + async with connectable.connect() as connection: + await connection.run_sync(do_run_migrations) + + await connectable.dispose() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode.""" + asyncio.run(run_async_migrations()) + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/services/worker/alembic/script.py.mako b/services/worker/alembic/script.py.mako new file mode 100644 index 0000000..1101630 --- /dev/null +++ b/services/worker/alembic/script.py.mako @@ -0,0 +1,28 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} + + +def upgrade() -> None: + """Upgrade schema.""" + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + """Downgrade schema.""" + ${downgrades if downgrades else "pass"} diff --git a/services/worker/alembic/versions/234da461ab5b_create_download_jobs_table.py b/services/worker/alembic/versions/234da461ab5b_create_download_jobs_table.py new file mode 100644 index 0000000..bcaeb0e --- /dev/null +++ b/services/worker/alembic/versions/234da461ab5b_create_download_jobs_table.py @@ -0,0 +1,64 @@ +"""create download_jobs table + +Revision ID: 234da461ab5b +Revises: +Create Date: 2026-10-13 07:11:05.259836 + +""" +from typing import Sequence, Union + +import sqlalchemy as sa +from alembic import op + +# revision identifiers, used by Alembic. +revision: str = '234da461ab5b' +down_revision: Union[str, Sequence[str], None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('download_jobs', + sa.Column('id', sa.String(length=36), nullable=False), + sa.Column('imdb_id', sa.String(length=32), nullable=False), + sa.Column('title', sa.String(length=255), nullable=True), + sa.Column('year', sa.Integer(), nullable=True), + sa.Column('magnet_uri', sa.Text(), nullable=False), + sa.Column('requested_by', sa.String(length=128), nullable=False), + sa.Column('state', sa.String(length=32), nullable=False), + sa.Column('progress_pct', sa.Float(), nullable=False), + sa.Column('download_rate_bytes', sa.BigInteger(), nullable=False), + sa.Column('error_message', sa.Text(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('completed_at', sa.DateTime(timezone=True), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('download_jobs', schema=None) as batch_op: + batch_op.create_index( + batch_op.f('ix_download_jobs_imdb_id'), ['imdb_id'], unique=False + ) + batch_op.create_index( + batch_op.f('ix_download_jobs_requested_by'), + ['requested_by'], + unique=False, + ) + batch_op.create_index( + batch_op.f('ix_download_jobs_state'), ['state'], unique=False + ) + + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('download_jobs', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_download_jobs_state')) + batch_op.drop_index(batch_op.f('ix_download_jobs_requested_by')) + batch_op.drop_index(batch_op.f('ix_download_jobs_imdb_id')) + + op.drop_table('download_jobs') + # ### end Alembic commands ### diff --git a/services/worker/src/worker/db/__init__.py b/services/worker/src/worker/db/__init__.py new file mode 100644 index 0000000..aa79c68 --- /dev/null +++ b/services/worker/src/worker/db/__init__.py @@ -0,0 +1,33 @@ +"""Database module for MagNetFlix worker service.""" + +from worker.db.engine import ( + DEFAULT_DATABASE_URL, + configure_sqlite_pragmas, + create_engine, + get_db_session, + get_engine, + get_session_factory, + normalize_database_url, + verify_wal_mode, +) +from worker.db.models import ( + ALLOWED_TRANSITIONS, + Base, + DownloadJob, + JobStateEnum, +) + +__all__ = [ + "ALLOWED_TRANSITIONS", + "Base", + "DEFAULT_DATABASE_URL", + "DownloadJob", + "JobStateEnum", + "configure_sqlite_pragmas", + "create_engine", + "get_db_session", + "get_engine", + "get_session_factory", + "normalize_database_url", + "verify_wal_mode", +] diff --git a/services/worker/src/worker/db/engine.py b/services/worker/src/worker/db/engine.py new file mode 100644 index 0000000..993dacb --- /dev/null +++ b/services/worker/src/worker/db/engine.py @@ -0,0 +1,134 @@ +"""SQLAlchemy async database engine and session management with SQLite WAL mode.""" + +from __future__ import annotations + +import os +from collections.abc import AsyncGenerator +from contextlib import asynccontextmanager +from pathlib import Path +from typing import Any + +from sqlalchemy import event, text +from sqlalchemy.ext.asyncio import ( + AsyncEngine, + AsyncSession, + async_sessionmaker, + create_async_engine, +) + +DEFAULT_DATABASE_URL = "sqlite+aiosqlite:///data/magnetflix.sqlite3" + + +def normalize_database_url(url: str | None = None) -> str: + """Normalize database URL to use async aiosqlite driver for SQLite. + + If given 'sqlite:////path', converts to 'sqlite+aiosqlite:////path'. + """ + raw_url = url or os.getenv("DATABASE_URL") or DEFAULT_DATABASE_URL + if raw_url.startswith("sqlite://") and not raw_url.startswith("sqlite+aiosqlite://"): + return raw_url.replace("sqlite://", "sqlite+aiosqlite://", 1) + return raw_url + + +def _ensure_sqlite_parent_dir(db_url: str) -> None: + """Ensure parent directory exists for file-based SQLite database.""" + if not db_url.startswith("sqlite"): + return + prefix = "sqlite+aiosqlite:///" + if db_url.startswith(prefix): + raw_path = db_url[len(prefix) :] + if raw_path and raw_path != ":memory:": + db_file = Path(raw_path).resolve() + db_file.parent.mkdir(parents=True, exist_ok=True) + + +def configure_sqlite_pragmas(engine: AsyncEngine) -> None: + """Register SQLite PRAGMAs for WAL mode, foreign keys, and synchronous=NORMAL.""" + + @event.listens_for(engine.sync_engine, "connect") + def set_sqlite_pragma(dbapi_connection: Any, connection_record: Any) -> None: + cursor = dbapi_connection.cursor() + cursor.execute("PRAGMA journal_mode=WAL;") + cursor.execute("PRAGMA foreign_keys=ON;") + cursor.execute("PRAGMA synchronous=NORMAL;") + cursor.execute("PRAGMA busy_timeout=5000;") + cursor.close() + + +def create_engine( + url: str | None = None, echo: bool = False +) -> tuple[AsyncEngine, async_sessionmaker[AsyncSession]]: + """Create an AsyncEngine and async sessionmaker configured with WAL pragmas.""" + normalized_url = normalize_database_url(url) + _ensure_sqlite_parent_dir(normalized_url) + + engine = create_async_engine( + normalized_url, + echo=echo, + future=True, + ) + + if normalized_url.startswith("sqlite"): + configure_sqlite_pragmas(engine) + + session_factory = async_sessionmaker( + bind=engine, + class_=AsyncSession, + expire_on_commit=False, + autocommit=False, + autoflush=False, + ) + + return engine, session_factory + + +# Module-level default singleton engine and sessionmaker +_engine: AsyncEngine | None = None +_session_factory: async_sessionmaker[AsyncSession] | None = None + + +def get_engine() -> AsyncEngine: + """Retrieve or initialize the global AsyncEngine instance.""" + global _engine, _session_factory + if _engine is None: + _engine, _session_factory = create_engine() + return _engine + + +def get_session_factory() -> async_sessionmaker[AsyncSession]: + """Retrieve or initialize the global async_sessionmaker instance.""" + global _engine, _session_factory + if _session_factory is None: + _engine, _session_factory = create_engine() + return _session_factory + + +@asynccontextmanager +async def get_db_session() -> AsyncGenerator[AsyncSession, None]: + """Provide a transactional async database session context.""" + factory = get_session_factory() + async with factory() as session: + try: + yield session + await session.commit() + except Exception: + await session.rollback() + raise + + +async def verify_wal_mode(session: AsyncSession) -> dict[str, Any]: + """Inspect and return active SQLite pragmas. + + Queries journal_mode, foreign_keys, synchronous, and busy_timeout. + """ + jm_res = await session.execute(text("PRAGMA journal_mode;")) + fk_res = await session.execute(text("PRAGMA foreign_keys;")) + sync_res = await session.execute(text("PRAGMA synchronous;")) + busy_res = await session.execute(text("PRAGMA busy_timeout;")) + + return { + "journal_mode": jm_res.scalar(), + "foreign_keys": fk_res.scalar(), + "synchronous": sync_res.scalar(), + "busy_timeout": busy_res.scalar(), + } diff --git a/services/worker/src/worker/db/models.py b/services/worker/src/worker/db/models.py new file mode 100644 index 0000000..0593466 --- /dev/null +++ b/services/worker/src/worker/db/models.py @@ -0,0 +1,261 @@ +"""SQLAlchemy ORM models for MagNetFlix download jobs and audit trail.""" + +from __future__ import annotations + +import uuid +from datetime import datetime, timezone +from enum import Enum +from typing import Any + +from google.protobuf.timestamp_pb2 import Timestamp +from sqlalchemy import BigInteger, DateTime, Float, Integer, String, Text +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column + +from worker.magnetflix.v1 import pipeline_pb2 + + +class Base(DeclarativeBase): + """Base declarative class for SQLAlchemy ORM models.""" + + pass + + +class JobStateEnum(str, Enum): + """Enumeration of valid lifecycle states for a download job.""" + + QUEUED = "QUEUED" + DOWNLOADING = "DOWNLOADING" + SCANNING = "SCANNING" + VERIFYING_METADATA = "VERIFYING_METADATA" + ORGANIZING = "ORGANIZING" + COMPLETED = "COMPLETED" + FAILED = "FAILED" + + +# Valid forward state transitions in the pipeline +ALLOWED_TRANSITIONS: dict[str, set[str]] = { + JobStateEnum.QUEUED.value: { + JobStateEnum.DOWNLOADING.value, + JobStateEnum.FAILED.value, + }, + JobStateEnum.DOWNLOADING.value: { + JobStateEnum.SCANNING.value, + JobStateEnum.FAILED.value, + }, + JobStateEnum.SCANNING.value: { + JobStateEnum.VERIFYING_METADATA.value, + JobStateEnum.FAILED.value, + }, + JobStateEnum.VERIFYING_METADATA.value: { + JobStateEnum.ORGANIZING.value, + JobStateEnum.FAILED.value, + }, + JobStateEnum.ORGANIZING.value: { + JobStateEnum.COMPLETED.value, + JobStateEnum.FAILED.value, + }, + JobStateEnum.COMPLETED.value: set(), + JobStateEnum.FAILED.value: set(), +} + +PROTO_STATE_MAP = { + JobStateEnum.QUEUED.value: pipeline_pb2.JOB_STATE_QUEUED, + JobStateEnum.DOWNLOADING.value: pipeline_pb2.JOB_STATE_DOWNLOADING, + JobStateEnum.SCANNING.value: pipeline_pb2.JOB_STATE_SCANNING, + JobStateEnum.VERIFYING_METADATA.value: pipeline_pb2.JOB_STATE_VERIFYING_METADATA, + JobStateEnum.ORGANIZING.value: pipeline_pb2.JOB_STATE_ORGANIZING, + JobStateEnum.COMPLETED.value: pipeline_pb2.JOB_STATE_COMPLETED, + JobStateEnum.FAILED.value: pipeline_pb2.JOB_STATE_FAILED, +} + + +def _datetime_to_timestamp(dt: datetime | None) -> Timestamp: + """Convert Python datetime to Google Protobuf Timestamp.""" + ts = Timestamp() + if dt is not None: + ts.FromDatetime(dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)) + return ts + + +def utc_now() -> datetime: + """Return timezone-aware current UTC datetime.""" + return datetime.now(timezone.utc) + + +class DownloadJob(Base): + """ORM model representing an acquisition and relocation pipeline job.""" + + __tablename__ = "download_jobs" + + id: Mapped[str] = mapped_column( + String(36), + primary_key=True, + default=lambda: str(uuid.uuid4()), + doc="Unique UUID primary key", + ) + imdb_id: Mapped[str] = mapped_column( + String(32), + nullable=False, + index=True, + doc="IMDb identifier (e.g. tt1375666)", + ) + title: Mapped[str | None] = mapped_column( + String(255), + nullable=True, + doc="Canonical movie title resolved from TMDB", + ) + year: Mapped[int | None] = mapped_column( + Integer, + nullable=True, + doc="Release year resolved from TMDB", + ) + magnet_uri: Mapped[str] = mapped_column( + Text, + nullable=False, + doc="BitTorrent magnet URI", + ) + requested_by: Mapped[str] = mapped_column( + String(128), + nullable=False, + index=True, + doc="Authenticated user from Remote-User SSO header", + ) + state: Mapped[str] = mapped_column( + String(32), + nullable=False, + default=JobStateEnum.QUEUED.value, + index=True, + doc="Current pipeline lifecycle state", + ) + progress_pct: Mapped[float] = mapped_column( + Float, + nullable=False, + default=0.0, + doc="Download progress percentage (0.0 to 100.0)", + ) + download_rate_bytes: Mapped[int] = mapped_column( + BigInteger, + nullable=False, + default=0, + doc="Download rate in bytes/sec", + ) + error_message: Mapped[str] = mapped_column( + Text, + nullable=False, + default="", + doc="Terminal error description if state is FAILED", + ) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), + nullable=False, + default=utc_now, + doc="UTC timestamp when job was enqueued", + ) + updated_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), + nullable=False, + default=utc_now, + onupdate=utc_now, + doc="UTC timestamp when job status was last updated", + ) + completed_at: Mapped[datetime | None] = mapped_column( + DateTime(timezone=True), + nullable=True, + doc="UTC timestamp when job transitioned to terminal COMPLETED or FAILED", + ) + + def __init__(self, **kwargs: Any) -> None: + """Initialize DownloadJob with default field values.""" + if "id" not in kwargs: + kwargs["id"] = str(uuid.uuid4()) + if "state" not in kwargs: + kwargs["state"] = JobStateEnum.QUEUED.value + if "progress_pct" not in kwargs: + kwargs["progress_pct"] = 0.0 + if "download_rate_bytes" not in kwargs: + kwargs["download_rate_bytes"] = 0 + if "error_message" not in kwargs: + kwargs["error_message"] = "" + if "created_at" not in kwargs: + kwargs["created_at"] = utc_now() + if "updated_at" not in kwargs: + kwargs["updated_at"] = utc_now() + super().__init__(**kwargs) + + @property + def is_terminal(self) -> bool: + """Return True if the job is in a terminal state (COMPLETED or FAILED).""" + return self.state in (JobStateEnum.COMPLETED.value, JobStateEnum.FAILED.value) + + def transition_to( + self, + new_state: JobStateEnum | str, + error_message: str | None = None, + ) -> None: + """Safely transition job state following the state machine invariants. + + Raises: + ValueError: If the requested state transition is invalid. + """ + target = new_state.value if isinstance(new_state, JobStateEnum) else new_state + allowed = ALLOWED_TRANSITIONS.get(self.state, set()) + + if target not in allowed: + raise ValueError( + f"Invalid state transition from '{self.state}' to '{target}'. " + f"Allowed transitions: {allowed}" + ) + + self.state = target + self.updated_at = utc_now() + + if error_message is not None: + self.error_message = error_message + + if self.is_terminal and self.completed_at is None: + self.completed_at = utc_now() + + def to_proto(self) -> pipeline_pb2.JobStatus: + """Convert ORM model instance into a Protobuf JobStatus message.""" + proto_state = PROTO_STATE_MAP.get( + self.state, pipeline_pb2.JOB_STATE_UNSPECIFIED + ) + + return pipeline_pb2.JobStatus( + job_id=self.id, + imdb_id=self.imdb_id, + title=self.title or "", + year=self.year or 0, + requested_by=self.requested_by, + state=proto_state, + progress_pct=self.progress_pct, + download_rate_bytes=self.download_rate_bytes, + error_message=self.error_message, + created_at=_datetime_to_timestamp(self.created_at), + updated_at=_datetime_to_timestamp(self.updated_at), + completed_at=_datetime_to_timestamp(self.completed_at), + ) + + def to_dict(self) -> dict[str, Any]: + """Convert ORM model to dictionary.""" + return { + "id": self.id, + "imdb_id": self.imdb_id, + "title": self.title, + "year": self.year, + "magnet_uri": self.magnet_uri, + "requested_by": self.requested_by, + "state": self.state, + "progress_pct": self.progress_pct, + "download_rate_bytes": self.download_rate_bytes, + "error_message": self.error_message, + "created_at": ( + self.created_at.isoformat() if self.created_at else None + ), + "updated_at": ( + self.updated_at.isoformat() if self.updated_at else None + ), + "completed_at": ( + self.completed_at.isoformat() if self.completed_at else None + ), + } diff --git a/tests/test_db.py b/tests/test_db.py new file mode 100644 index 0000000..4d982ef --- /dev/null +++ b/tests/test_db.py @@ -0,0 +1,216 @@ +"""Unit tests for SQLite WAL engine, ORM models, and CRUD operations.""" + +from __future__ import annotations + +import tempfile +from pathlib import Path + +import pytest +from sqlalchemy import select +from worker.db import ( + Base, + DownloadJob, + JobStateEnum, + create_engine, + verify_wal_mode, +) +from worker.magnetflix.v1 import pipeline_pb2 + + +@pytest.fixture +async def temp_db(): + """Create a temporary SQLite database file with WAL pragmas.""" + with tempfile.TemporaryDirectory() as tmpdir: + db_path = Path(tmpdir) / "test_magnetflix.sqlite3" + db_url = f"sqlite+aiosqlite:///{db_path}" + engine, session_factory = create_engine(db_url) + + async with engine.begin() as conn: + await conn.run_sync(Base.metadata.create_all) + + yield session_factory, engine + + await engine.dispose() + + +@pytest.mark.asyncio +async def test_sqlite_wal_pragmas(temp_db): + """Verify that SQLite engine automatically configures WAL mode and pragmas.""" + session_factory, _ = temp_db + + async with session_factory() as session: + pragmas = await verify_wal_mode(session) + + assert pragmas["journal_mode"].lower() == "wal" + assert pragmas["foreign_keys"] == 1 + assert pragmas["synchronous"] == 1 # 1 = NORMAL + assert pragmas["busy_timeout"] == 5000 + + +@pytest.mark.asyncio +async def test_download_job_crud(temp_db): + """Test creating, reading, and updating a DownloadJob in SQLite.""" + session_factory, _ = temp_db + + # 1. Create Job + job = DownloadJob( + imdb_id="tt1375666", + magnet_uri="magnet:?xt=urn:btih:dummy123", + requested_by="alice", + ) + + async with session_factory() as session: + session.add(job) + await session.commit() + job_id = job.id + + assert job_id is not None + + # 2. Read Job + async with session_factory() as session: + result = await session.execute( + select(DownloadJob).where(DownloadJob.id == job_id) + ) + saved = result.scalar_one() + + assert saved.imdb_id == "tt1375666" + assert saved.magnet_uri == "magnet:?xt=urn:btih:dummy123" + assert saved.requested_by == "alice" + assert saved.state == JobStateEnum.QUEUED.value + assert saved.progress_pct == 0.0 + assert saved.download_rate_bytes == 0 + assert saved.error_message == "" + assert saved.title is None + assert saved.year is None + assert saved.created_at is not None + assert saved.updated_at is not None + assert saved.completed_at is None + assert saved.is_terminal is False + + +@pytest.mark.asyncio +async def test_download_job_to_proto(temp_db): + """Test converting a DownloadJob ORM model to a Protobuf JobStatus message.""" + session_factory, _ = temp_db + + job = DownloadJob( + imdb_id="tt1375666", + title="Inception", + year=2010, + magnet_uri="magnet:?xt=urn:btih:dummy123", + requested_by="alice", + progress_pct=42.5, + download_rate_bytes=5242880, + ) + + async with session_factory() as session: + session.add(job) + await session.commit() + + proto = job.to_proto() + assert isinstance(proto, pipeline_pb2.JobStatus) + assert proto.job_id == job.id + assert proto.imdb_id == "tt1375666" + assert proto.title == "Inception" + assert proto.year == 2010 + assert proto.requested_by == "alice" + assert proto.state == pipeline_pb2.JOB_STATE_QUEUED + assert abs(proto.progress_pct - 42.5) < 0.01 + assert proto.download_rate_bytes == 5242880 + assert proto.error_message == "" + assert proto.created_at.seconds > 0 + + +@pytest.mark.asyncio +async def test_download_job_state_transitions(temp_db): + """Test state machine progression and terminal state invariants.""" + session_factory, _ = temp_db + + job = DownloadJob( + imdb_id="tt0111161", + magnet_uri="magnet:?xt=urn:btih:shawshank", + requested_by="bob", + ) + + # 1. Valid Linear Progression: + # QUEUED -> DOWNLOADING -> SCANNING -> VERIFYING_METADATA -> ORGANIZING -> COMPLETED + job.transition_to(JobStateEnum.DOWNLOADING) + assert job.state == JobStateEnum.DOWNLOADING.value + assert job.completed_at is None + + job.transition_to(JobStateEnum.SCANNING) + assert job.state == JobStateEnum.SCANNING.value + + job.transition_to(JobStateEnum.VERIFYING_METADATA) + assert job.state == JobStateEnum.VERIFYING_METADATA.value + + job.transition_to(JobStateEnum.ORGANIZING) + assert job.state == JobStateEnum.ORGANIZING.value + + job.transition_to(JobStateEnum.COMPLETED) + assert job.state == JobStateEnum.COMPLETED.value + assert job.is_terminal is True + assert job.completed_at is not None + + # 2. Cannot transition out of terminal COMPLETED + with pytest.raises(ValueError, match="Invalid state transition"): + job.transition_to(JobStateEnum.DOWNLOADING) + + # 3. Direct failure transition from non-terminal state + job_failing = DownloadJob( + imdb_id="tt0068646", + magnet_uri="magnet:?xt=urn:btih:godfather", + requested_by="charlie", + ) + job_failing.transition_to( + JobStateEnum.FAILED, error_message="Tracker timed out" + ) + assert job_failing.state == JobStateEnum.FAILED.value + assert job_failing.error_message == "Tracker timed out" + assert job_failing.is_terminal is True + assert job_failing.completed_at is not None + + +@pytest.mark.asyncio +async def test_active_job_idempotency_query(temp_db): + """Test querying active non-terminal jobs for duplicate rejection.""" + session_factory, _ = temp_db + + active_job = DownloadJob( + imdb_id="tt1375666", + magnet_uri="magnet:?xt=urn:btih:inception", + requested_by="alice", + state=JobStateEnum.DOWNLOADING.value, + ) + completed_job = DownloadJob( + imdb_id="tt0111161", + magnet_uri="magnet:?xt=urn:btih:shawshank", + requested_by="bob", + state=JobStateEnum.COMPLETED.value, + ) + + async with session_factory() as session: + session.add_all([active_job, completed_job]) + await session.commit() + + # Query for active job with tt1375666 + terminal_states = [JobStateEnum.COMPLETED.value, JobStateEnum.FAILED.value] + stmt = ( + select(DownloadJob) + .where(DownloadJob.imdb_id == "tt1375666") + .where(DownloadJob.state.not_in(terminal_states)) + ) + res = await session.execute(stmt) + found_active = res.scalar_one_or_none() + assert found_active is not None + assert found_active.id == active_job.id + + # Query for active job with tt0111161 (should be None because it's COMPLETED) + stmt_comp = ( + select(DownloadJob) + .where(DownloadJob.imdb_id == "tt0111161") + .where(DownloadJob.state.not_in(terminal_states)) + ) + res_comp = await session.execute(stmt_comp) + found_completed = res_comp.scalar_one_or_none() + assert found_completed is None diff --git a/todo.txt b/todo.txt index 253e41b..3ca0cfe 100644 --- a/todo.txt +++ b/todo.txt @@ -1,7 +1,7 @@ -(A) Create SQLAlchemy async engine with SQLite WAL mode pragmas in services/worker/src/worker/db/engine.py +db @worker -(A) Define DownloadJob ORM model in services/worker/src/worker/db/models.py (id, imdb_id, title, year, magnet_uri, requested_by, status, progress_pct, download_rate_bytes, error_message, created_at, updated_at, completed_at) +db @worker -(A) Initialize Alembic in services/worker/ and create initial migration for download_jobs table +db @worker -(A) Write unit tests for DB connection, WAL pragma verification, and CRUD operations in tests/test_db.py +test @worker +x 2026-10-13 (A) Create SQLAlchemy async engine with SQLite WAL mode pragmas in services/worker/src/worker/db/engine.py +db @worker +x 2026-10-13 (A) Define DownloadJob ORM model in services/worker/src/worker/db/models.py (id, imdb_id, title, year, magnet_uri, requested_by, status, progress_pct, download_rate_bytes, error_message, created_at, updated_at, completed_at) +db @worker +x 2026-10-13 (A) Initialize Alembic in services/worker/ and create initial migration for download_jobs table +db @worker +x 2026-10-13 (A) Write unit tests for DB connection, WAL pragma verification, and CRUD operations in tests/test_db.py +test @worker (B) Implement symlink & path-traversal blocker in services/worker/src/worker/sanitizer.py +sanitizer @worker (B) Implement file allowlist filtering (video: .mkv, .mp4, .avi, .webm; subtitles: .srt, .vtt, .sub, .ass) +sanitizer @worker (B) Implement sample discard (<100MB / 'sample' keyword) and largest primary video selector in sanitizer.py +sanitizer @worker