Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c34512da6b | ||
|
|
a8288d34cb |
No files matched your search
@@ -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
|
||||||
@@ -4,8 +4,8 @@ x 2026-10-31 (A) Reconfigure buf.gen.yaml to output stubs into services/contract
|
|||||||
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 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 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) 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