Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c34512da6b | ||
|
|
a8288d34cb | ||
|
|
b479ed8ccc | ||
|
|
8b1e6b721c | ||
|
|
3d428dba48 |
No files matched your search
+14
-4
@@ -1,18 +1,28 @@
|
|||||||
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS builder
|
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS builder
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
|
ENV UV_COMPILE_BYTECODE=1
|
||||||
|
|
||||||
|
# Copy workspace files
|
||||||
COPY pyproject.toml uv.lock ./
|
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
|
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
|
FROM python:3.12-slim-bookworm AS runner
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy virtual environment and code
|
||||||
COPY --from=builder /app/.venv /app/.venv
|
COPY --from=builder /app/.venv /app/.venv
|
||||||
|
COPY services/contracts/src ./services/contracts/src
|
||||||
COPY services/bff/src ./services/bff/src
|
COPY services/bff/src ./services/bff/src
|
||||||
|
|
||||||
ENV PATH="/app/.venv/bin:$PATH"
|
ENV PATH="/app/.venv/bin:$PATH"
|
||||||
ENV PYTHONPATH="/app/services/bff/src"
|
ENV PYTHONPATH="/app/services/bff/src:/app/services/contracts/src"
|
||||||
|
|
||||||
EXPOSE 8000
|
EXPOSE 8000
|
||||||
CMD ["uvicorn", "bff.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
CMD ["uvicorn", "bff.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||||
@@ -1,18 +1,30 @@
|
|||||||
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS builder
|
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS builder
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
|
ENV UV_COMPILE_BYTECODE=1
|
||||||
|
|
||||||
|
# Copy workspace files
|
||||||
COPY pyproject.toml uv.lock ./
|
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
|
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
|
FROM python:3.12-slim-bookworm AS runner
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy virtual environment and code
|
||||||
COPY --from=builder /app/.venv /app/.venv
|
COPY --from=builder /app/.venv /app/.venv
|
||||||
|
COPY services/contracts/src ./services/contracts/src
|
||||||
COPY services/worker/src ./services/worker/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 PATH="/app/.venv/bin:$PATH"
|
||||||
ENV PYTHONPATH="/app/services/worker/src"
|
ENV PYTHONPATH="/app/services/worker/src:/app/services/contracts/src"
|
||||||
|
|
||||||
EXPOSE 50051
|
EXPOSE 50051
|
||||||
CMD ["python", "-m", "worker.main"]
|
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")
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
@@ -9,7 +10,7 @@ from typing import Any
|
|||||||
|
|
||||||
from google.protobuf.timestamp_pb2 import Timestamp
|
from google.protobuf.timestamp_pb2 import Timestamp
|
||||||
from magnetflix.v1 import pipeline_pb2
|
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
|
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||||
|
|
||||||
|
|
||||||
@@ -81,10 +82,26 @@ def utc_now() -> datetime:
|
|||||||
return datetime.now(timezone.utc)
|
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):
|
class DownloadJob(Base):
|
||||||
"""ORM model representing an acquisition and relocation pipeline job."""
|
"""ORM model representing an acquisition and relocation pipeline job."""
|
||||||
|
|
||||||
__tablename__ = "download_jobs"
|
__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(
|
id: Mapped[str] = mapped_column(
|
||||||
String(36),
|
String(36),
|
||||||
@@ -113,6 +130,12 @@ class DownloadJob(Base):
|
|||||||
nullable=False,
|
nullable=False,
|
||||||
doc="BitTorrent magnet URI",
|
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(
|
requested_by: Mapped[str] = mapped_column(
|
||||||
String(128),
|
String(128),
|
||||||
nullable=False,
|
nullable=False,
|
||||||
@@ -179,6 +202,11 @@ class DownloadJob(Base):
|
|||||||
kwargs["created_at"] = utc_now()
|
kwargs["created_at"] = utc_now()
|
||||||
if "updated_at" not in kwargs:
|
if "updated_at" not in kwargs:
|
||||||
kwargs["updated_at"] = utc_now()
|
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)
|
super().__init__(**kwargs)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@@ -243,6 +271,7 @@ class DownloadJob(Base):
|
|||||||
"title": self.title,
|
"title": self.title,
|
||||||
"year": self.year,
|
"year": self.year,
|
||||||
"magnet_uri": self.magnet_uri,
|
"magnet_uri": self.magnet_uri,
|
||||||
|
"info_hash": self.info_hash,
|
||||||
"requested_by": self.requested_by,
|
"requested_by": self.requested_by,
|
||||||
"state": self.state,
|
"state": self.state,
|
||||||
"progress_pct": self.progress_pct,
|
"progress_pct": self.progress_pct,
|
||||||
|
|||||||
@@ -212,3 +212,103 @@ async def test_active_job_idempotency_query(temp_db):
|
|||||||
res_comp = await session.execute(stmt_comp)
|
res_comp = await session.execute(stmt_comp)
|
||||||
found_completed = res_comp.scalar_one_or_none()
|
found_completed = res_comp.scalar_one_or_none()
|
||||||
assert found_completed is 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
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
# Milestone 1: Contracts, Toolchain & Database Hardening (Prerequisites & Blockers)
|
# Milestone 1: Contracts, Toolchain & Database Hardening (Prerequisites & Blockers)
|
||||||
(A) Create services/contracts workspace package with pyproject.toml (module-name = 'magnetflix') +contracts @workspace
|
x 2026-10-31 (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
|
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
|
||||||
(A) Update services/worker and services/bff to depend on magnetflix-contracts via workspace dependency +deps @workspace
|
x 2026-10-31 (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
|
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
|
||||||
(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) 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
|
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
|
||||||
(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) 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
|
# 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
|
(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
|
||||||
|
|||||||
Reference in new issue
Block a user