Compare commits

...
Author SHA1 Message Date
kiskaadee c34512da6b Merge pull request 'feat(db): add info_hash column and partial unique index on active imdb_id' (#13) from feat/db-concurrency-idempotency into main 2026-11-01 00:32:47 -05:00
kiskaadee a8288d34cb feat(db): add info_hash column and partial unique index on active imdb_id
- Add info_hash column to DownloadJob ORM and extract BTIH from magnet_uri
- Add uq_download_jobs_active_imdb_id partial unique index for active jobs
- Author Alembic migration 002_add_info_hash_and_partial_unique_index
- Add unit tests verifying duplicate active rejection and info_hash persistence

Closes #5, Closes #6
2026-10-31 22:37:24 -05:00
kiskaadee b479ed8ccc Merge pull request 'build(docker): update service Dockerfiles for workspace packaging and migrations' (#12) from feat/docker-build-packaging into main 2026-10-31 22:32:39 -05:00
kiskaadee 8b1e6b721c build(docker): update service Dockerfiles for workspace packaging and migrations
- Copy services/contracts into builder and runner stages for worker and bff
- Copy alembic.ini and services/worker/alembic into worker runner stage
- Enable bytecode compilation via UV_COMPILE_BYTECODE=1
- Update PYTHONPATH to include contracts stubs

Closes #4
2026-10-31 22:11:06 -05:00
kiskaadee 3d428dba48 Merge pull request 'feat(contracts): establish shared contracts package and toolchain alignment' (#11) from feat/contracts-workspace into main 2026-10-31 22:06:06 -05:00
6 changed files with 212 additions and 16 deletions

No files matched your search

+14 -4
View File
@@ -1,18 +1,28 @@
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS builder
WORKDIR /app
ENV UV_COMPILE_BYTECODE=1
# Copy workspace files
COPY pyproject.toml uv.lock ./
COPY services/bff/pyproject.toml ./services/bff/
COPY services/contracts ./services/contracts
COPY services/bff ./services/bff
# Synchronize dependencies for bff package
RUN uv sync --frozen --no-dev --package magnetflix-bff
COPY services/bff/src ./services/bff/src
# Final stage
FROM python:3.12-slim-bookworm AS runner
WORKDIR /app
# Copy virtual environment and code
COPY --from=builder /app/.venv /app/.venv
COPY services/contracts/src ./services/contracts/src
COPY services/bff/src ./services/bff/src
ENV PATH="/app/.venv/bin:$PATH"
ENV PYTHONPATH="/app/services/bff/src"
ENV PYTHONPATH="/app/services/bff/src:/app/services/contracts/src"
EXPOSE 8000
CMD ["uvicorn", "bff.main:app", "--host", "0.0.0.0", "--port", "8000"]
+16 -4
View File
@@ -1,18 +1,30 @@
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS builder
WORKDIR /app
ENV UV_COMPILE_BYTECODE=1
# Copy workspace files
COPY pyproject.toml uv.lock ./
COPY services/worker/pyproject.toml ./services/worker/
COPY services/contracts ./services/contracts
COPY services/worker ./services/worker
# Synchronize dependencies for worker package
RUN uv sync --frozen --no-dev --package magnetflix-worker
COPY services/worker/src ./services/worker/src
# Final stage
FROM python:3.12-slim-bookworm AS runner
WORKDIR /app
# Copy virtual environment and code
COPY --from=builder /app/.venv /app/.venv
COPY services/contracts/src ./services/contracts/src
COPY services/worker/src ./services/worker/src
COPY services/worker/alembic.ini ./alembic.ini
COPY services/worker/alembic ./alembic
ENV PATH="/app/.venv/bin:$PATH"
ENV PYTHONPATH="/app/services/worker/src"
ENV PYTHONPATH="/app/services/worker/src:/app/services/contracts/src"
EXPOSE 50051
CMD ["python", "-m", "worker.main"]
@@ -0,0 +1,45 @@
"""add info_hash and partial unique index on active imdb_id
Revision ID: 002_add_info_hash_and_partial_unique_index
Revises: 234da461ab5b
Create Date: 2026-10-31 22:36:00.000000
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "002_add_info_hash_and_partial_unique_index"
down_revision: Union[str, Sequence[str], None] = "234da461ab5b"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema to add info_hash and partial unique index on active imdb_id."""
with op.batch_alter_table("download_jobs", schema=None) as batch_op:
batch_op.add_column(
sa.Column("info_hash", sa.String(length=64), nullable=True)
)
batch_op.create_index(
batch_op.f("ix_download_jobs_info_hash"),
["info_hash"],
unique=False,
)
batch_op.create_index(
"uq_download_jobs_active_imdb_id",
["imdb_id"],
unique=True,
sqlite_where=sa.text("state NOT IN ('COMPLETED', 'FAILED')"),
)
def downgrade() -> None:
"""Downgrade schema."""
with op.batch_alter_table("download_jobs", schema=None) as batch_op:
batch_op.drop_index("uq_download_jobs_active_imdb_id")
batch_op.drop_index(batch_op.f("ix_download_jobs_info_hash"))
batch_op.drop_column("info_hash")
+30 -1
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import re
import uuid
from datetime import datetime, timezone
from enum import Enum
@@ -9,7 +10,7 @@ from typing import Any
from google.protobuf.timestamp_pb2 import Timestamp
from magnetflix.v1 import pipeline_pb2
from sqlalchemy import BigInteger, DateTime, Float, Integer, String, Text
from sqlalchemy import BigInteger, DateTime, Float, Index, Integer, String, Text, text
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
@@ -81,10 +82,26 @@ def utc_now() -> datetime:
return datetime.now(timezone.utc)
def extract_info_hash(magnet_uri: str) -> str | None:
"""Extract and lowercase the BTIH info-hash from a BitTorrent magnet URI."""
match = re.search(r"urn:btih:([a-zA-Z0-9]+)", magnet_uri, re.IGNORECASE)
if match:
return match.group(1).lower()
return None
class DownloadJob(Base):
"""ORM model representing an acquisition and relocation pipeline job."""
__tablename__ = "download_jobs"
__table_args__ = (
Index(
"uq_download_jobs_active_imdb_id",
"imdb_id",
unique=True,
sqlite_where=text("state NOT IN ('COMPLETED', 'FAILED')"),
),
)
id: Mapped[str] = mapped_column(
String(36),
@@ -113,6 +130,12 @@ class DownloadJob(Base):
nullable=False,
doc="BitTorrent magnet URI",
)
info_hash: Mapped[str | None] = mapped_column(
String(64),
nullable=True,
index=True,
doc="BitTorrent info-hash extracted from magnet URI",
)
requested_by: Mapped[str] = mapped_column(
String(128),
nullable=False,
@@ -179,6 +202,11 @@ class DownloadJob(Base):
kwargs["created_at"] = utc_now()
if "updated_at" not in kwargs:
kwargs["updated_at"] = utc_now()
if "info_hash" not in kwargs or kwargs["info_hash"] is None:
if "magnet_uri" in kwargs and kwargs["magnet_uri"]:
kwargs["info_hash"] = extract_info_hash(kwargs["magnet_uri"])
elif isinstance(kwargs.get("info_hash"), str):
kwargs["info_hash"] = kwargs["info_hash"].lower()
super().__init__(**kwargs)
@property
@@ -243,6 +271,7 @@ class DownloadJob(Base):
"title": self.title,
"year": self.year,
"magnet_uri": self.magnet_uri,
"info_hash": self.info_hash,
"requested_by": self.requested_by,
"state": self.state,
"progress_pct": self.progress_pct,
+100
View File
@@ -212,3 +212,103 @@ async def test_active_job_idempotency_query(temp_db):
res_comp = await session.execute(stmt_comp)
found_completed = res_comp.scalar_one_or_none()
assert found_completed is None
@pytest.mark.asyncio
async def test_download_job_info_hash_extraction_and_persistence(temp_db):
"""Test extraction and database persistence of info_hash from magnet URI."""
session_factory, _ = temp_db
# 1. Automatic BTIH extraction and lowercasing
magnet = "magnet:?xt=urn:btih:4A5B6C7D8E9F1234567890ABCDEF1234567890AB&dn=Inception"
job = DownloadJob(
imdb_id="tt1375666",
magnet_uri=magnet,
requested_by="alice",
)
assert job.info_hash == "4a5b6c7d8e9f1234567890abcdef1234567890ab"
# 2. Persistence and query by info_hash
async with session_factory() as session:
session.add(job)
await session.commit()
async with session_factory() as session:
result = await session.execute(
select(DownloadJob).where(
DownloadJob.info_hash == "4a5b6c7d8e9f1234567890abcdef1234567890ab"
)
)
saved = result.scalar_one()
assert saved.id == job.id
assert saved.info_hash == "4a5b6c7d8e9f1234567890abcdef1234567890ab"
@pytest.mark.asyncio
async def test_active_job_partial_unique_constraint(temp_db):
"""Verify that SQLite partial index rejects concurrent active jobs for same imdb."""
from sqlalchemy.exc import IntegrityError
session_factory, _ = temp_db
# 1. Insert first active job
job1 = DownloadJob(
imdb_id="tt9999999",
magnet_uri="magnet:?xt=urn:btih:hash111111111111111111111111111111111111",
requested_by="alice",
state=JobStateEnum.QUEUED.value,
)
async with session_factory() as session:
session.add(job1)
await session.commit()
# 2. Inserting a second active job for the same imdb_id must raise IntegrityError
job2 = DownloadJob(
imdb_id="tt9999999",
magnet_uri="magnet:?xt=urn:btih:hash222222222222222222222222222222222222",
requested_by="bob",
state=JobStateEnum.DOWNLOADING.value,
)
with pytest.raises(IntegrityError):
async with session_factory() as session:
session.add(job2)
await session.commit()
# 3. Mark job1 as COMPLETED; inserting a new active job for tt9999999 must succeed
async with session_factory() as session:
result = await session.execute(
select(DownloadJob).where(DownloadJob.id == job1.id)
)
loaded_job1 = result.scalar_one()
loaded_job1.state = JobStateEnum.COMPLETED.value
await session.commit()
job3 = DownloadJob(
imdb_id="tt9999999",
magnet_uri="magnet:?xt=urn:btih:hash333333333333333333333333333333333333",
requested_by="charlie",
state=JobStateEnum.QUEUED.value,
)
async with session_factory() as session:
session.add(job3)
await session.commit()
# 4. Mark job3 as FAILED; inserting another active job for tt9999999 must succeed
async with session_factory() as session:
result = await session.execute(
select(DownloadJob).where(DownloadJob.id == job3.id)
)
loaded_job3 = result.scalar_one()
loaded_job3.state = JobStateEnum.FAILED.value
await session.commit()
job4 = DownloadJob(
imdb_id="tt9999999",
magnet_uri="magnet:?xt=urn:btih:hash444444444444444444444444444444444444",
requested_by="dave",
state=JobStateEnum.QUEUED.value,
)
async with session_factory() as session:
session.add(job4)
await session.commit()
assert job4.id is not None
+7 -7
View File
@@ -1,11 +1,11 @@
# Milestone 1: Contracts, Toolchain & Database Hardening (Prerequisites & Blockers)
(A) Create services/contracts workspace package with pyproject.toml (module-name = 'magnetflix') +contracts @workspace
(A) Reconfigure buf.gen.yaml to output stubs into services/contracts/src, generate stubs + docs/api_spec.md, and track in Git +proto @contracts
(A) Update services/worker and services/bff to depend on magnetflix-contracts via workspace dependency +deps @workspace
(A) Update pyproject.toml to include tests/ in pyright, remove exclusions masking broken imports, and add test rule to Makefile +ci @workspace
(A) Update services/worker/Dockerfile and services/bff/Dockerfile to copy services/contracts, and copy alembic/ into worker image +docker @deploy
(A) Create Alembic migration 002_add_info_hash_and_partial_unique_index.py adding info_hash column and uq_download_jobs_active_imdb_id index +db @worker
(A) Update DownloadJob ORM model and write unit tests in tests/test_db.py verifying duplicate active insertion rejection +test @worker
x 2026-10-31 (A) Create services/contracts workspace package with pyproject.toml (module-name = 'magnetflix') +contracts @workspace
x 2026-10-31 (A) Reconfigure buf.gen.yaml to output stubs into services/contracts/src, generate stubs + docs/api_spec.md, and track in Git +proto @contracts
x 2026-10-31 (A) Update services/worker and services/bff to depend on magnetflix-contracts via workspace dependency +deps @workspace
x 2026-10-31 (A) Update pyproject.toml to include tests/ in pyright, remove exclusions masking broken imports, and add test rule to Makefile +ci @workspace
x 2026-10-31 (A) Update services/worker/Dockerfile and services/bff/Dockerfile to copy services/contracts, and copy alembic/ into worker image +docker @deploy
x 2026-10-31 (A) Create Alembic migration 002_add_info_hash_and_partial_unique_index.py adding info_hash column and uq_download_jobs_active_imdb_id index +db @worker
x 2026-10-31 (A) Update DownloadJob ORM model and write unit tests in tests/test_db.py verifying duplicate active insertion rejection +test @worker
# Milestone 2: Pipeline Domain Engine & Filesystem Safety
(B) Implement Two-Tier Media Sanitizer in services/worker/src/worker/sanitizer.py (hard-fail on symlinks/traversal/executables, ignore .txt/.nfo, sample discard, largest video selector) +sanitizer @worker