- Reorder docs/roadmap.md into an MVP-first vertical slice strategy (M2 Safe Walking Skeleton MVP followed by M3 hardening, M4 SSO/SSE/autocomplete UX, and M5 production Traefik deploy) while preserving all DEC-1 through DEC-8 invariants. - Move former M1.8 (Base32 info_hash normalization and Alembic migration 003) into M3.1 so Milestone 1 closes cleanly in sync with Gitea Milestone #13 (6/6 issues), and enforce urn:btih:<40-hex> + [imdbid-...] checks in M2. - Capture clean-room reproducibility constraints in M2 specs: fail-closed BFF AUTH_ENABLED=true default overridden in local Compose, canonical deployment env vars, relative template resolution inside services/bff/src, PUID:PGID bind-mount ownership, lazy Transmission client initialization, regular-file-only st_nlink checks, and incomplete-dir-enabled disabled. - Update AGENTS.md section 2.5 to enforce four-way planning sync across docs/roadmap.md, todo.txt, Gitea issues/milestones, and Project Board #2. - Narrow todo.txt active items strictly to the next immediate deliverable (Milestone 2: M2.1-M2.4).
16 KiB
16 KiB
🗺️ MagNetFlix — MVP-First Implementation Roadmap
This roadmap organizes MagNetFlix using an MVP-first vertical slice strategy: deliver a safe, usable local movie downloader as early as Milestone 2 (Safe Walking Skeleton MVP), then layer reliability hardening, SSO/SSE/autocomplete polish, and production reverse-proxy deployment in Milestones 3–5 without losing any architectural requirements (DEC-1–DEC-8).
🎯 Milestones Dependency Graph
flowchart TD
M1["Milestone 1: Contracts, Toolchain & DB Foundation (Done)"]
M2["Milestone 2: Safe Walking Skeleton MVP\n(Sanitizer + Stage 1 TMDB + Core Relocator + Worker + Minimal BFF + Dev Compose)"]
M3["Milestone 3: Reliability, Metadata Hardening & Crash Recovery\n(M1.8 Base32/Index + Stage 2 Verify + Multi-Track Subs + Recovery + Pools)"]
M4["Milestone 4: SSO Security, Real-Time SSE & TMDB Autocomplete UX\n(Fail-Closed Auth + Legacy Alias + Search Proxy + SSE Pub/Sub)"]
M5["Milestone 5: Production Reverse-Proxy Deployment & Hardened Verification\n(Traefik Labels + Healthchecks + Locked-Down E2E)"]
M1 --> M2
M2 --> M3
M3 --> M4
M4 --> M5
📌 Milestone 1: Contracts, Toolchain & Database Hardening (Complete)
- Objective: Fix broken gRPC stub imports, ensure 100% reproducible offline container builds, eliminate the active
imdb_iddeduplication race, and establish database schema invariants. - Dependencies: None.
- Requirements Satisfied:
REQ-1,REQ-2. - Status: Complete (
6/6Gitea issues closed in Milestone#13). FormerM1.8(Base32 btih info_hashnormalization + Alembic migration003+uq_download_jobs_active_info_hash) is resequenced toM3.1so Milestone 1 closes cleanly and M2 enforcesurn:btih:<40-hex>validation inSubmitDownloaduntilM3.1lands. - Work Items:
M1.1: Createservices/contractsworkspace package (pyproject.toml,module-name = "magnetflix").M1.2: Reconfigurebuf.gen.yamlto output stubs intoservices/contracts/src; generate and track stubs +docs/api_spec.mdin Git (DEC-1).M1.3: Update dependencies inservices/workerandservices/bffto includemagnetflix-contracts = { workspace = true }.M1.4: Updatepyproject.tomlto includetests/inpyright, remove exclusions that masked broken imports, and addtest:target toMakefile.M1.5: Updateservices/worker/Dockerfileandservices/bff/Dockerfileto copyservices/contracts, and includealembic.iniandalembic/in the Worker image.M1.6: Create Alembic migration002_add_info_hash_and_partial_unique_index.pyaddinginfo_hashcolumn anduq_download_jobs_active_imdb_idindex (DEC-2).M1.7: UpdateDownloadJobmodel and add unit tests intests/test_db.pyverifying duplicate active insertion rejection.
- Verifiable Exit Criteria:
uv run python -c "from magnetflix.v1 import pipeline_pb2, pipeline_pb2_grpc"succeeds with 0 errors.uv run ruff check .anduv run pyrightpass cleanly across the entire workspace including contracts and tests.uv run pytestpasses all contract and database tests.
📌 Milestone 2: Safe Walking Skeleton MVP (Local End-to-End Pipeline)
- Objective: Deliver a working, torrent-safe local vertical slice: submit a magnet URI + IMDb ID in a browser UI, download via Transmission, enforce Two-Tier Sanitizer security checks, resolve TMDB movie metadata, atomically publish into
/media/movies/<Title> (<Year>) [imdbid-<IMDbID>]/, and poll live job progress. - Dependencies: Milestone 1.
- Requirements Satisfied:
REQ-3,REQ-4(Stage 1),REQ-5(Core),REQ-6,REQ-7(Core),REQ-8,REQ-9(Core API/UI),REQ-11(Local Dev Slice). - Explicit Deferrals to Post-MVP: Stage 2 filename token-overlap verification (
M3.2), Base32btihnormalization +uq_download_jobs_active_info_hash(M3.1), multi-track subtitle language/forced tag parsing (M3.3), 15-min stall timeout + startup active reconciliation + dedicated relocation pool (M3.4), standard gRPC health check (M3.5), SSO middleware enforcement + legacyPOST /download+ TMDB search autocomplete + SSE pub/sub (M4), and Traefik production Compose (M5). - Work Items:
M2.1: Two-Tier Media Sanitizer (services/worker/src/worker/sanitizer.py&tests/test_sanitizer.py) adhering toDEC-3:- Export
scan_staging_dir(staging_dir: Path, min_video_bytes: int | None = None) -> SanitizedPayload(default threshold fromMIN_VIDEO_BYTES, fallback100_000_000bytes). - Traverse with
os.walk(staging_dir, followlinks=False)and run security checks across the entire tree before sample discard (including insideSample/folders): reject path escape (..), reject all symlinks and special nodes (FIFO/socket/device), reject hard links (st_nlink > 1on regular filesS_ISREGonly), and hard-fail on dangerous extensions case-insensitively (.exe,.bat,.cmd,.sh,.scr,.vbs,.ps1,.lnk,.iso,.zip,.rar,.7z). - Safely ignore unlisted clutter (
.nfo,.txt,.jpg,.sfv). - Discard sample files (
sample/samplesdirectory components or case-insensitive\bsample\bfilename stem) and video files< min_video_bytes; never size-filter subtitles. - Select largest qualifying video (
.mkv,.mp4,.avi,.webm) and deterministically sorted allowlisted subtitles (.srt,.vtt,.sub,.ass), or raise an explicit domain error if no qualifying video remains.
- Export
M2.2: Stage 1 TMDB Metadata Client & Core Atomic Relocator (services/worker/src/worker/metadata.py,services/worker/src/worker/relocator.py,tests/test_metadata.py,tests/test_relocator.py) adhering toDEC-4(Stage 1) &DEC-5(Core):TmdbClient: validateTMDB_API_KEYlazily at call time (raising explicit config error if missing, keeping module imports test-safe), validate^tt\d{7,10}$, call TMDB v3GET /find/{imdb_id}?external_source=imdb_id&api_key=...viahttpx.AsyncClient(TMDB_BASE_URLdefaulthttps://api.themoviedb.org/3,10stimeout, max 2 retries on5xx/network errors), require non-emptymovie_results(rejecting TV/missing), and extractMovieMetadata(title, year, imdb_id, tmdb_id)requiring a valid 4-digitrelease_dateyear.relocator.py:sanitize_title(title)replacing forbidden/control chars (/ \ : * ? " < > | \x00-\x1f \x7f) and..with spaces, collapsing whitespace, and stripping leading/trailing dots/spaces (failing if empty); ensureMEDIA_DIRexists, scanMEDIA_DIRfor existing*[imdbid-<IMDbID>]*or exact canonical target<SanitizedTitle> (<Year>) [imdbid-<IMDbID>](DEC-2), verifyshutil.disk_usage(MEDIA_DIR).free >= total_bytes * 1.05, stage into<MEDIA_DIR>/.staging_<job_id>/(cleanup infinally:), name<SanitizedTitle> (<Year>).<ext>(deterministic.1,.2suffixes on same-extension subtitle collisions), and atomically commit viaos.replace.
M2.3: Transmission Client, Minimal Pipeline Coordinator & Worker gRPC Server (transmission.py,pipeline.py,service.py,main.py,tests/test_transmission.py,tests/test_pipeline.py,tests/test_grpc_service.py):TransmissionClient: instantiatetransmission_rpc.Clientlazily per operation insideasyncio.to_thread(TRANSMISSION_HOST,TRANSMISSION_PORT, optionalTRANSMISSION_USER/TRANSMISSION_PASS); provideadd_torrent(magnet_uri, download_dir) -> str,get_progress(info_hash) -> TorrentProgress(progress_pct, download_rate_bytes, is_finished, status, error_message), andremove_torrent(info_hash, delete_data=True)(failing fast iftorrent.error != 0or missing).PipelineCoordinator:SubmitDownloadvalidatesurn:btih:<40-hex>(rejecting Base32/non-btih magnets withINVALID_ARGUMENTuntilM3.1), checks activeimdb_id/info_hashduplicates and existing library[imdbid-...]directory (ALREADY_EXISTS), resolves Stage 1 TMDB metadata (NOT_FOUND/INVALID_ARGUMENT/UNAVAILABLE), persistsQUEUEDjob, and spawns a trackedasyncio.Taskto runQUEUED -> DOWNLOADING -> SCANNING -> VERIFYING_METADATA(MVP pass-through)-> ORGANIZING -> COMPLETED(orFAILED), polling everyPOLL_INTERVAL_SECONDS(default2.0), offloading scan/relocate viaasyncio.to_thread, updating SQLite via short-lived sessions, and cleaning up Transmission torrent +<STAGING_DIR>/<job_id>infinally:.PipelineServiceServicer&worker/main.py: implementSubmitDownload,GetJob(omitting emptycompleted_attimestamps for unfinished jobs),ListJobs(integer offsetpage_tokendefault"0",page_sizedefault20clamped1..100, ordered bycreated_at DESC, id DESC, optionalstate_filter), and returnUNIMPLEMENTEDforStreamJobStatus; serve onWORKER_GRPC_PORT(default50051) with gracefulSIGTERM/SIGINTshutdown.
M2.4: Minimal FastAPI BFF, Polling Web UI, Localdocker-compose.yml& Live Torrent E2E (services/bff/src/bff/grpc_client.py,main.py,services/bff/src/bff/templates/index.html,docker-compose.yml,tests/test_bff_routes.py):- BFF app keeps
AUTH_ENABLEDdefaulting totrue(DEC-8, returning401on/api/*when enabled withoutAUTH_HEADER_USER), usinglocal_useronly whenAUTH_ENABLED=falseis explicitly configured in local Compose; resolves templates viaPath(__file__).resolve().parent / "templates"to matchservices/bff/Dockerfile. - Routes:
GET /healthz({"status": "ok"}),POST /api/v1/downloads(201 Created,{imdb_id, magnet_uri}\rightarrow{job_id, message}),GET /api/v1/downloads({"jobs": [...], "next_page_token": "..."}),GET /api/v1/downloads/{job_id}, andGET /polling HTML form every3s; explicit gRPC\rightarrowHTTP error mapping (ALREADY_EXISTS\rightarrow409,NOT_FOUND\rightarrow404,INVALID_ARGUMENT\rightarrow422,UNAVAILABLE\rightarrow503). - Local
docker-compose.yml:transmission(healthcheck,PUID/PGID,./data/staging:/data/staging,./config/transmission:/config,incomplete-dir-enabledverifiedfalse),worker(user: "${PUID:-1000}:${PGID:-1000}",depends_on: transmission: condition: service_healthy, runsalembic upgrade head && exec python -m worker.main, canonical env varsDATABASE_URL=sqlite+aiosqlite:////data/magnetflix.sqlite3,STAGING_DIR=/data/staging,MEDIA_DIR=/media/movies,TMDB_API_KEY), andbff(8000:8000,GRPC_WORKER_HOST=worker:50051,AUTH_ENABLED=false). - Document/prepare pre-created
./data/staging,./media/movies,./config/transmissionowned byPUID:PGID, and verify a live>= 100 MBlegal public-domain torrent completes end-to-end.
- BFF app keeps
- Verifiable Exit Criteria:
uv run ruff check .,uv run pyright, anduv run pytestpass 100% acrosstests/test_contracts.py,tests/test_db.py,tests/test_sanitizer.py,tests/test_metadata.py,tests/test_relocator.py,tests/test_transmission.py,tests/test_pipeline.py,tests/test_grpc_service.py, andtests/test_bff_routes.py.docker compose build && docker compose up -dstarts cleanly and delivers a real public-domain movie into./media/movies/<Title> (<Year>) [imdbid-<IMDbID>]/.
📌 Milestone 3: Reliability, Metadata Hardening & Crash Recovery
- Objective: Close remaining
DEC-2–DEC-7safety and operational resilience gaps deferred from the MVP slice. - Dependencies: Milestone 2.
- Requirements Satisfied:
REQ-2(M1.8),REQ-4(Stage 2),REQ-5(Multi-track subtitles),REQ-7(Stall timeout, Crash recovery, Executor isolation). - Work Items:
M3.1: (RelocatedM1.8) Normalize Base32btihinfo_hashto 40-char lowercase hex (accepting both 32-char Base32 and 40-char hex magnets inSubmitDownload) and add partial unique indexuq_download_jobs_active_info_hashvia Alembic migration003(DEC-2).M3.2: Implement Stage 2 Offline Token-Overlap Verifier inmetadata.pyand wireVERIFYING_METADATAinpipeline.pyto fail jobs whose sanitized primary video filename mismatches cached(title, year)(DEC-4).M3.3: Implement Multi-Track Subtitle Format & Tag Parser inrelocator.pypreserving.srt,.vtt,.sub,.asswith normalized ISO-639 language +.forcedtags and deterministic disambiguation indices (DEC-5).M3.4: Hardenpipeline.pywith a 15-minute zero-progress-delta stall timeout, startup active reconciliation sweep (failing orphaned non-terminal jobs, removing Transmission torrents with bounded startup retry, purging staging dirs), and a dedicated boundedThreadPoolExecutorisolating heavy relocation copies from RPC/scan offloading (DEC-6,DEC-7).M3.5: Enable standard gRPC health checking (grpcio-health-checking) on the Worker server and add failure-injection tests for stall timeouts, crash recovery, and metadata mismatch rejection.
- Verifiable Exit Criteria:
- Crash recovery + failure-injection suites pass; orphaned staging directories and stalled torrents are deterministically cleaned up.
📌 Milestone 4: SSO Security, Real-Time SSE & TMDB Autocomplete UX
- Objective: Replace MVP polling and dev-only submission with fail-closed SSO enforcement, legacy extension compatibility, TMDB autocomplete search, and live Server-Sent Events streaming.
- Dependencies: Milestone 3.
- Requirements Satisfied:
REQ-8(StreamJobStatus),REQ-9,REQ-10. - Work Items:
M4.1: Harden Pluggable Identity Adapter & CORS in FastAPI BFF (DEC-8): enforce fail-closed401whenAUTH_ENABLED=trueandAUTH_HEADER_USERheader is missing/empty (/healthzexempt), enforceCORS_ALLOWED_ORIGINSallowlist.M4.2: Add legacy extension route compatibility (POST /downloadalongsidePOST /api/v1/downloadswith PydanticAliasChoicesformagnet/magnet_uriandimdbid/imdb_id).M4.3: Implement server-side TMDB Search Proxy (GET /api/v1/movies/search?q=...with IMDb ID enrichment) and upgradeservices/bff/src/bff/templates/+static/to autocomplete search with poster previews and live progress cards.M4.4: Implement Worker in-memoryasyncio.Queuesubscribe-before-snapshot coalescing broadcaster (StreamJobStatusRPC,DEC-7) and BFF SSE endpoint (GET /api/v1/movies/events) replacing frontend polling, with full SSE/auth route tests.
- Verifiable Exit Criteria:
uv run pytest tests/test_bff_routes.pyvalidates fail-closed401, legacy dual routes, search proxy, and live SSE streaming without CORS errors.
📌 Milestone 5: Production Reverse-Proxy Deployment & Hardened Verification
- Objective: Finalize production Traefik reverse-proxy configuration, container health probes, and hardened end-to-end verification (
docs/deployment.md). - Dependencies: Milestone 4.
- Requirements Satisfied:
REQ-11(Production Deployment). - Work Items:
M5.1: Reconcile productiondocker-compose.yml(or production overlay) matchingdocs/deployment.md: Traefik labels,proxy_networkexternal bridge + internalbackendnetwork isolating Worker,AUTH_ENABLED=true, and verified non-rootPUID/PGIDbind-mount permissions.M5.2: Add DockerHEALTHCHECKdirectives (/healthzon BFF, gRPC health probe on Worker) and audit multi-stage image builds.M5.3: Execute full production E2E verification: SSO header auth\rightarrowTMDB autocomplete\rightarrowTransmission download\rightarrowTwo-Tier Sanitizer\rightarrowStage 2 token check\rightarrowMulti-track atomic relocation\rightarrowLive SSE completion + restart crash-recovery drill.
- Verifiable Exit Criteria:
- Fresh
docker compose buildsucceeds with zero errors, container health checks stayhealthy, and full hardened E2E lifecycle passes underAUTH_ENABLED=true.
- Fresh