Compare commits
1
Commits
b7aeee9fe8
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b32b4d09f1 |
No files matched your search
@@ -15,7 +15,11 @@ The working tree represents the user's active work.
|
|||||||
2. **Check for Existing Files:** Before creating any new file, verify whether the file (or a user equivalent) already exists on disk. Never overwrite or re-scaffold user work.
|
2. **Check for Existing Files:** Before creating any new file, verify whether the file (or a user equivalent) already exists on disk. Never overwrite or re-scaffold user work.
|
||||||
3. **Never Overwrite Blindly:** Use available file-reading tools. Preserve user comments, links, and conventions. Prefer surgical edits over wholesale overwrites.
|
3. **Never Overwrite Blindly:** Use available file-reading tools. Preserve user comments, links, and conventions. Prefer surgical edits over wholesale overwrites.
|
||||||
4. **No Destructive Git Commands:** Never run `reset --hard`, `clean -fd`, `restore`, `checkout`, `stash`, `rebase`, or `amend` without explicit permission.
|
4. **No Destructive Git Commands:** Never run `reset --hard`, `clean -fd`, `restore`, `checkout`, `stash`, `rebase`, or `amend` without explicit permission.
|
||||||
5. **Live Task Tracking (`todo.txt`):** Keep `todo.txt` synchronized with code reality. When a task or milestone is implemented and verified, mark it as completed (`x YYYY-MM-DD ...`) immediately. Never leave completed work marked as pending.
|
5. **Live Planning & Task Synchronization:** Keep planning artifacts synchronized with code reality whenever a task completes or scope shifts across all four places:
|
||||||
|
- **Repository roadmap** (`docs/roadmap.md`) — authoritative milestone sequencing and exit criteria.
|
||||||
|
- **Immediate checklist** (`todo.txt`) — focused strictly on a granular breakdown of the **next immediate deliverable** milestone; mark completed items (`x YYYY-MM-DD ...`) immediately upon verification.
|
||||||
|
- **Gitea issues & milestones** (`kiskaadee/MagNetFlix`) — open/update/close issues and milestones so Gitea remains the authoritative backlog.
|
||||||
|
- **Gitea Kanban board** (`MagNetFlix Pipeline`, Project `#2`) — attach active deliverable issues and milestone epics to keep board status aligned.
|
||||||
6. **Final Diff Verification:** Before completing work, run `git status` and `git diff` to verify that no unrelated user changes were modified or discarded. Distinguish user changes from agent changes in completion reports.
|
6. **Final Diff Verification:** Before completing work, run `git status` and `git diff` to verify that no unrelated user changes were modified or discarded. Distinguish user changes from agent changes in completion reports.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
+59
-78
@@ -1,6 +1,6 @@
|
|||||||
# 🗺️ MagNetFlix — Reconciled Implementation Roadmap
|
# 🗺️ MagNetFlix — MVP-First Implementation Roadmap
|
||||||
|
|
||||||
This roadmap breaks down the completion of **MagNetFlix** into clear, dependency-ordered milestones. Each milestone includes explicit prerequisites, work items, and verifiable exit criteria.
|
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`).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -8,11 +8,11 @@ This roadmap breaks down the completion of **MagNetFlix** into clear, dependency
|
|||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
flowchart TD
|
flowchart TD
|
||||||
M1["Milestone 1: Contracts, Toolchain & DB Hardening\n(GAP-1, GAP-2, TD-1, TD-2, TD-3)"]
|
M1["Milestone 1: Contracts, Toolchain & DB Foundation (Done)"]
|
||||||
M2["Milestone 2: Pipeline Domain Engine & Filesystem Safety\n(GAP-3, GAP-4, GAP-5)"]
|
M2["Milestone 2: Safe Walking Skeleton MVP\n(Sanitizer + Stage 1 TMDB + Core Relocator + Worker + Minimal BFF + Dev Compose)"]
|
||||||
M3["Milestone 3: Transmission Integration & Worker Coordinator\n(GAP-6, GAP-7)"]
|
M3["Milestone 3: Reliability, Metadata Hardening & Crash Recovery\n(M1.8 Base32/Index + Stage 2 Verify + Multi-Track Subs + Recovery + Pools)"]
|
||||||
M4["Milestone 4: FastAPI BFF Gateway, SSE & Web UI\n(GAP-8)"]
|
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: Multi-Container Stack & Deployment Verification\n(Traefik, SSO, Compose)"]
|
M5["Milestone 5: Production Reverse-Proxy Deployment & Hardened Verification\n(Traefik Labels + Healthchecks + Locked-Down E2E)"]
|
||||||
|
|
||||||
M1 --> M2
|
M1 --> M2
|
||||||
M2 --> M3
|
M2 --> M3
|
||||||
@@ -22,10 +22,11 @@ flowchart TD
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📌 Milestone 1: Contracts, Toolchain & Database Hardening
|
## 📌 Milestone 1: Contracts, Toolchain & Database Hardening (`Complete`)
|
||||||
- **Objective:** Fix broken gRPC stub imports, ensure 100% reproducible offline container builds, eliminate the active-job deduplication race, and establish database schema invariants.
|
- **Objective:** Fix broken gRPC stub imports, ensure 100% reproducible offline container builds, eliminate the active `imdb_id` deduplication race, and establish database schema invariants.
|
||||||
- **Dependencies:** None.
|
- **Dependencies:** None.
|
||||||
- **Requirements Satisfied:** `REQ-1`, `REQ-2`.
|
- **Requirements Satisfied:** `REQ-1`, `REQ-2`.
|
||||||
|
- **Status:** Complete (`6/6` Gitea issues closed in Milestone `#13`). Former `M1.8` (`Base32 btih info_hash` normalization + Alembic migration `003` + `uq_download_jobs_active_info_hash`) is resequenced to `M3.1` so Milestone 1 closes cleanly and M2 enforces `urn:btih:<40-hex>` validation in `SubmitDownload` until `M3.1` lands.
|
||||||
- **Work Items:**
|
- **Work Items:**
|
||||||
- [x] `M1.1`: Create `services/contracts` workspace package (`pyproject.toml`, `module-name = "magnetflix"`).
|
- [x] `M1.1`: Create `services/contracts` workspace package (`pyproject.toml`, `module-name = "magnetflix"`).
|
||||||
- [x] `M1.2`: Reconfigure `buf.gen.yaml` to output stubs into `services/contracts/src`; generate and track stubs + `docs/api_spec.md` in Git (`DEC-1`).
|
- [x] `M1.2`: Reconfigure `buf.gen.yaml` to output stubs into `services/contracts/src`; generate and track stubs + `docs/api_spec.md` in Git (`DEC-1`).
|
||||||
@@ -34,99 +35,79 @@ flowchart TD
|
|||||||
- [x] `M1.5`: Update `services/worker/Dockerfile` and `services/bff/Dockerfile` to copy `services/contracts`, and include `alembic.ini` and `alembic/` in the Worker image.
|
- [x] `M1.5`: Update `services/worker/Dockerfile` and `services/bff/Dockerfile` to copy `services/contracts`, and include `alembic.ini` and `alembic/` in the Worker image.
|
||||||
- [x] `M1.6`: Create Alembic migration `002_add_info_hash_and_partial_unique_index.py` adding `info_hash` column and `uq_download_jobs_active_imdb_id` index (`DEC-2`).
|
- [x] `M1.6`: Create Alembic migration `002_add_info_hash_and_partial_unique_index.py` adding `info_hash` column and `uq_download_jobs_active_imdb_id` index (`DEC-2`).
|
||||||
- [x] `M1.7`: Update `DownloadJob` model and add unit tests in `tests/test_db.py` verifying duplicate active insertion rejection.
|
- [x] `M1.7`: Update `DownloadJob` model and add unit tests in `tests/test_db.py` verifying duplicate active insertion rejection.
|
||||||
- [ ] `M1.8` *(Architecture Review Follow-up)*: Normalize Base32 `btih` `info_hash` to 40-char lowercase hex in `DownloadJob` and add partial unique index `uq_download_jobs_active_info_hash` via Alembic migration `003`.
|
|
||||||
- **Verifiable Exit Criteria:**
|
- **Verifiable Exit Criteria:**
|
||||||
- `uv run python -c "from magnetflix.v1 import pipeline_pb2, pipeline_pb2_grpc"` succeeds with 0 errors.
|
- `uv run python -c "from magnetflix.v1 import pipeline_pb2, pipeline_pb2_grpc"` succeeds with 0 errors.
|
||||||
- `uv run ruff check .` and `uv run pyright` pass cleanly across the entire workspace including contracts and tests.
|
- `uv run ruff check .` and `uv run pyright` pass cleanly across the entire workspace including contracts and tests.
|
||||||
- `uv run pytest tests/test_db.py` passes all tests including partial unique index verification.
|
- `uv run pytest` passes all contract and database tests.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📌 Milestone 2: Pipeline Domain Engine & Filesystem Safety
|
## 📌 Milestone 2: Safe Walking Skeleton MVP (Local End-to-End Pipeline)
|
||||||
- **Objective:** Implement core business logic and security boundary modules: untrusted payload sanitization, metadata verification, and cross-volume publication.
|
- **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.
|
- **Dependencies:** Milestone 1.
|
||||||
- **Requirements Satisfied:** `REQ-3`, `REQ-4`, `REQ-5`.
|
- **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`), Base32 `btih` normalization + `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 + legacy `POST /download` + TMDB search autocomplete + SSE pub/sub (`M4`), and Traefik production Compose (`M5`).
|
||||||
- **Work Items:**
|
- **Work Items:**
|
||||||
- [ ] `M2.1`: Implement Media Sanitizer (`services/worker/src/worker/sanitizer.py`) adhering to `DEC-3`:
|
- [ ] `M2.1`: **Two-Tier Media Sanitizer** (`services/worker/src/worker/sanitizer.py` & `tests/test_sanitizer.py`) adhering to `DEC-3`:
|
||||||
- Hard-fail on symlinks, hard links, `..` traversal, special files, and dangerous extensions (case-insensitive: `.exe`, `.bat`, `.cmd`, `.sh`, `.scr`, `.vbs`, `.ps1`, `.lnk`, `.iso`, `.zip`, `.rar`, `.7z`).
|
- Export `scan_staging_dir(staging_dir: Path, min_video_bytes: int | None = None) -> SanitizedPayload` (default threshold from `MIN_VIDEO_BYTES`, fallback `100_000_000` bytes).
|
||||||
- Safely ignore unlisted non-dangerous files (such as `.nfo`, `.txt`, `.jpg`, `.sfv`).
|
- Traverse with `os.walk(staging_dir, followlinks=False)` and run security checks across the **entire tree before** sample discard (including inside `Sample/` folders): reject path escape (`..`), reject *all* symlinks and special nodes (FIFO/socket/device), reject hard links (`st_nlink > 1` on regular files `S_ISREG` only), and hard-fail on dangerous extensions case-insensitively (`.exe`, `.bat`, `.cmd`, `.sh`, `.scr`, `.vbs`, `.ps1`, `.lnk`, `.iso`, `.zip`, `.rar`, `.7z`).
|
||||||
- Discard samples (`< 100 MB` or case-insensitive word-boundary `"sample"` token / `Sample` directory); select largest primary video and allowlisted subtitles (`.srt`, `.vtt`, `.sub`, `.ass`).
|
- Safely ignore unlisted clutter (`.nfo`, `.txt`, `.jpg`, `.sfv`).
|
||||||
- [ ] `M2.2`: Write unit tests in `tests/test_sanitizer.py` verifying all security, allowlist, and sample discard rules.
|
- Discard sample files (`sample`/`samples` directory components or case-insensitive `\bsample\b` filename stem) and video files `< min_video_bytes`; **never** size-filter subtitles.
|
||||||
- [ ] `M2.3`: Implement TMDB Client & Token Verifier (`services/worker/src/worker/metadata.py`) adhering to `DEC-4`:
|
- 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.
|
||||||
- Early resolution via `GET /find/{imdb_id}?external_source=imdb_id` using `httpx.AsyncClient` with bounded timeouts/retries.
|
- [ ] `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 to `DEC-4` (Stage 1) & `DEC-5` (Core):
|
||||||
- Validates IMDb ID format, validates movie entity type, extracts `(title, year)`.
|
- `TmdbClient`: validate `TMDB_API_KEY` lazily at call time (raising explicit config error if missing, keeping module imports test-safe), validate `^tt\d{7,10}$`, call TMDB v3 `GET /find/{imdb_id}?external_source=imdb_id&api_key=...` via `httpx.AsyncClient` (`TMDB_BASE_URL` default `https://api.themoviedb.org/3`, `10s` timeout, max 2 retries on `5xx`/network errors), require non-empty `movie_results` (rejecting TV/missing), and extract `MovieMetadata(title, year, imdb_id, tmdb_id)` requiring a valid 4-digit `release_date` year.
|
||||||
- Post-download normalized token comparison between cached `(title, year)` and primary video filename.
|
- `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); ensure `MEDIA_DIR` exists, scan `MEDIA_DIR` for existing `*[imdbid-<IMDbID>]*` or exact canonical target `<SanitizedTitle> (<Year>) [imdbid-<IMDbID>]` (`DEC-2`), verify `shutil.disk_usage(MEDIA_DIR).free >= total_bytes * 1.05`, stage into `<MEDIA_DIR>/.staging_<job_id>/` (cleanup in `finally:`), name `<SanitizedTitle> (<Year>).<ext>` (deterministic `.1`, `.2` suffixes on same-extension subtitle collisions), and atomically commit via `os.replace`.
|
||||||
- [ ] `M2.4`: Write unit tests in `tests/test_metadata.py` with mocked TMDB HTTP responses (match, 404, non-movie, mismatch).
|
- [ ] `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`):
|
||||||
- [ ] `M2.5`: Implement Library Relocator (`services/worker/src/worker/relocator.py`) adhering to `DEC-5`:
|
- `TransmissionClient`: instantiate `transmission_rpc.Client` lazily per operation inside `asyncio.to_thread` (`TRANSMISSION_HOST`, `TRANSMISSION_PORT`, optional `TRANSMISSION_USER`/`TRANSMISSION_PASS`); provide `add_torrent(magnet_uri, download_dir) -> str`, `get_progress(info_hash) -> TorrentProgress(progress_pct, download_rate_bytes, is_finished, status, error_message)`, and `remove_torrent(info_hash, delete_data=True)` (failing fast if `torrent.error != 0` or missing).
|
||||||
- Deterministic `<Title>` path sanitization (stripping/replacing `/`, `\`, `:`, `*`, `?`, `"`, `<`, `>`, `|`, `..`).
|
- `PipelineCoordinator`: `SubmitDownload` validates `urn:btih:<40-hex>` (rejecting Base32/non-btih magnets with `INVALID_ARGUMENT` until `M3.1`), checks active `imdb_id`/`info_hash` duplicates and existing library `[imdbid-...]` directory (`ALREADY_EXISTS`), resolves Stage 1 TMDB metadata (`NOT_FOUND`/`INVALID_ARGUMENT`/`UNAVAILABLE`), persists `QUEUED` job, and spawns a tracked `asyncio.Task` to run `QUEUED -> DOWNLOADING -> SCANNING -> VERIFYING_METADATA` (MVP pass-through) `-> ORGANIZING -> COMPLETED` (or `FAILED`), polling every `POLL_INTERVAL_SECONDS` (default `2.0`), offloading scan/relocate via `asyncio.to_thread`, updating SQLite via short-lived sessions, and cleaning up Transmission torrent + `<STAGING_DIR>/<job_id>` in `finally:`.
|
||||||
- Multi-track subtitle format preservation (`.srt`, `.vtt`, `.sub`, `.ass`) with language/forced tags, untagged fallback (`<SanitizedTitle> (<Year>).<ext>`), and disambiguation indices.
|
- `PipelineServiceServicer` & `worker/main.py`: implement `SubmitDownload`, `GetJob` (omitting empty `completed_at` timestamps for unfinished jobs), `ListJobs` (integer offset `page_token` default `"0"`, `page_size` default `20` clamped `1..100`, ordered by `created_at DESC, id DESC`, optional `state_filter`), and return `UNIMPLEMENTED` for `StreamJobStatus`; serve on `WORKER_GRPC_PORT` (default `50051`) with graceful `SIGTERM`/`SIGINT` shutdown.
|
||||||
- Free-space pre-check + two-stage copy-and-swap: copy to `/media/movies/.staging_<job_id>/`, pre-check destination directory existence, and atomically swap via `os.replace`.
|
- [ ] `M2.4`: **Minimal FastAPI BFF, Polling Web UI, Local `docker-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`):
|
||||||
- [ ] `M2.6`: Write unit tests in `tests/test_relocator.py` asserting destination file layout and atomic swap error handling.
|
- BFF app keeps `AUTH_ENABLED` defaulting to `true` (`DEC-8`, returning `401` on `/api/*` when enabled without `AUTH_HEADER_USER`), using `local_user` only when `AUTH_ENABLED=false` is explicitly configured in local Compose; resolves templates via `Path(__file__).resolve().parent / "templates"` to match `services/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}`, and `GET /` polling HTML form every `3s`; explicit gRPC $\rightarrow$ HTTP error mapping (`ALREADY_EXISTS` $\rightarrow$ `409`, `NOT_FOUND` $\rightarrow$ `404`, `INVALID_ARGUMENT` $\rightarrow$ `422`, `UNAVAILABLE` $\rightarrow$ `503`).
|
||||||
|
- Local `docker-compose.yml`: `transmission` (`healthcheck`, `PUID`/`PGID`, `./data/staging:/data/staging`, `./config/transmission:/config`, `incomplete-dir-enabled` verified `false`), `worker` (`user: "${PUID:-1000}:${PGID:-1000}"`, `depends_on: transmission: condition: service_healthy`, runs `alembic upgrade head && exec python -m worker.main`, canonical env vars `DATABASE_URL=sqlite+aiosqlite:////data/magnetflix.sqlite3`, `STAGING_DIR=/data/staging`, `MEDIA_DIR=/media/movies`, `TMDB_API_KEY`), and `bff` (`8000:8000`, `GRPC_WORKER_HOST=worker:50051`, `AUTH_ENABLED=false`).
|
||||||
|
- Document/prepare pre-created `./data/staging`, `./media/movies`, `./config/transmission` owned by `PUID:PGID`, and verify a live `>= 100 MB` legal public-domain torrent completes end-to-end.
|
||||||
- **Verifiable Exit Criteria:**
|
- **Verifiable Exit Criteria:**
|
||||||
- `uv run pytest tests/test_sanitizer.py tests/test_metadata.py tests/test_relocator.py` passes 100%.
|
- `uv run ruff check .`, `uv run pyright`, and `uv run pytest` pass 100% across `tests/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`, and `tests/test_bff_routes.py`.
|
||||||
- Zero filesystem breakout vulnerabilities possible under synthetic traversal fixtures.
|
- `docker compose build && docker compose up -d` starts cleanly and delivers a real public-domain movie into `./media/movies/<Title> (<Year>) [imdbid-<IMDbID>]/`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📌 Milestone 3: Transmission Integration & Worker Coordinator
|
## 📌 Milestone 3: Reliability, Metadata Hardening & Crash Recovery
|
||||||
- **Objective:** Wrap Transmission RPC, coordinate the pipeline finite state machine, implement startup crash recovery, and expose the gRPC service.
|
- **Objective:** Close remaining `DEC-2`–`DEC-7` safety and operational resilience gaps deferred from the MVP slice.
|
||||||
- **Dependencies:** Milestone 2.
|
- **Dependencies:** Milestone 2.
|
||||||
- **Requirements Satisfied:** `REQ-6`, `REQ-7`, `REQ-8`.
|
- **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:**
|
- **Work Items:**
|
||||||
- [ ] `M3.1`: Implement Transmission RPC Client Wrapper (`services/worker/src/worker/transmission.py`) adhering to `DEC-6`:
|
- [ ] `M3.1`: *(Relocated `M1.8`)* Normalize Base32 `btih` `info_hash` to 40-char lowercase hex (accepting both 32-char Base32 and 40-char hex magnets in `SubmitDownload`) and add partial unique index `uq_download_jobs_active_info_hash` via Alembic migration `003` (`DEC-2`).
|
||||||
- `add_torrent(magnet_uri, download_dir=/data/staging/<job_id>)`.
|
- [ ] `M3.2`: Implement **Stage 2 Offline Token-Overlap Verifier** in `metadata.py` and wire `VERIFYING_METADATA` in `pipeline.py` to fail jobs whose sanitized primary video filename mismatches cached `(title, year)` (`DEC-4`).
|
||||||
- `get_progress(info_hash)` returning progress percentage and download speed.
|
- [ ] `M3.3`: Implement **Multi-Track Subtitle Format & Tag Parser** in `relocator.py` preserving `.srt`, `.vtt`, `.sub`, `.ass` with normalized ISO-639 language + `.forced` tags and deterministic disambiguation indices (`DEC-5`).
|
||||||
- `remove_torrent(info_hash, delete_data=True)` for terminal cleanup.
|
- [ ] `M3.4`: Harden `pipeline.py` with 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 bounded `ThreadPoolExecutor` isolating heavy relocation copies from RPC/scan offloading (`DEC-6`, `DEC-7`).
|
||||||
- [ ] `M3.2`: Write unit tests in `tests/test_transmission.py` with mocked RPC client.
|
- [ ] `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.
|
||||||
- [ ] `M3.3`: Implement Pipeline Coordinator & State Machine (`services/worker/src/worker/pipeline.py`) adhering to `DEC-6` & `DEC-7`:
|
|
||||||
- State progression: `QUEUED` $\rightarrow$ `DOWNLOADING` $\rightarrow$ `SCANNING` $\rightarrow$ `VERIFYING_METADATA` $\rightarrow$ `ORGANIZING` $\rightarrow$ `COMPLETED` (with `FAILED` reachable from any active state).
|
|
||||||
- 15-minute zero-progress-delta stalled torrent timeout.
|
|
||||||
- Startup crash recovery: query non-terminal jobs, fail DB rows, purge staging directories, remove torrents from Transmission (with bounded startup retry/backoff).
|
|
||||||
- Dedicated bounded relocation executor isolated from lightweight `transmission-rpc` and scan offloading.
|
|
||||||
- In-memory `asyncio.Queue` broadcaster (subscribe-before-snapshot + bounded per-subscriber coalescing) for real-time status streaming.
|
|
||||||
- [ ] `M3.4`: Implement gRPC Server Servicer (`services/worker/src/worker/service.py` & `main.py`) adhering to `pipeline.proto`:
|
|
||||||
- Implements `SubmitDownload`, `GetJob`, `ListJobs`, and `StreamJobStatus` plus gRPC health check.
|
|
||||||
- Maps application errors to proper gRPC status codes (`ALREADY_EXISTS`, `NOT_FOUND`, `INVALID_ARGUMENT`).
|
|
||||||
- [ ] `M3.5`: Write integration tests in `tests/test_pipeline.py` and `tests/test_grpc_service.py`.
|
|
||||||
- **Verifiable Exit Criteria:**
|
- **Verifiable Exit Criteria:**
|
||||||
- `uv run pytest tests/test_pipeline.py tests/test_grpc_service.py` passes 100%.
|
- Crash recovery + failure-injection suites pass; orphaned staging directories and stalled torrents are deterministically cleaned up.
|
||||||
- Worker process cleanly starts, handles startup reconciliation, and shuts down gracefully with `SIGTERM`.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📌 Milestone 4: FastAPI BFF Gateway, SSE & Web UI
|
## 📌 Milestone 4: SSO Security, Real-Time SSE & TMDB Autocomplete UX
|
||||||
- **Objective:** Implement the user-facing web gateway, pluggable SSO identity adapter, server-side TMDB search proxy, real-time SSE stream, and single-origin UI.
|
- **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.
|
- **Dependencies:** Milestone 3.
|
||||||
- **Requirements Satisfied:** `REQ-9`, `REQ-10`.
|
- **Requirements Satisfied:** `REQ-8` (`StreamJobStatus`), `REQ-9`, `REQ-10`.
|
||||||
- **Work Items:**
|
- **Work Items:**
|
||||||
- [ ] `M4.1`: Implement Pluggable Identity Adapter Middleware in FastAPI (`DEC-8`):
|
- [ ] `M4.1`: Harden **Pluggable Identity Adapter & CORS** in FastAPI BFF (`DEC-8`): enforce fail-closed `401` when `AUTH_ENABLED=true` and `AUTH_HEADER_USER` header is missing/empty (`/healthz` exempt), enforce `CORS_ALLOWED_ORIGINS` allowlist.
|
||||||
- Configurable via `AUTH_ENABLED`, `AUTH_HEADER_USER`, and `CORS_ALLOWED_ORIGINS`; fails closed with `401` when `AUTH_ENABLED=true` and falls back to `local_user` only when `AUTH_ENABLED=false`.
|
- [ ] `M4.2`: Add legacy extension route compatibility (`POST /download` alongside `POST /api/v1/downloads` with Pydantic `AliasChoices` for `magnet`/`magnet_uri` and `imdbid`/`imdb_id`).
|
||||||
- [ ] `M4.2`: Implement BFF gRPC Client Wrapper (`services/bff/src/bff/grpc_client.py`):
|
- [ ] `M4.3`: Implement server-side **TMDB Search Proxy** (`GET /api/v1/movies/search?q=...` with IMDb ID enrichment) and upgrade `services/bff/src/bff/templates/` + `static/` to autocomplete search with poster previews and live progress cards.
|
||||||
- Channels calls to Worker (`SubmitDownload`, `GetJob`, `ListJobs`, `StreamJobStatus`).
|
- [ ] `M4.4`: Implement Worker in-memory `asyncio.Queue` **subscribe-before-snapshot coalescing broadcaster** (`StreamJobStatus` RPC, `DEC-7`) and BFF **SSE endpoint** (`GET /api/v1/movies/events`) replacing frontend polling, with full SSE/auth route tests.
|
||||||
- [ ] `M4.3`: Implement REST Endpoints & Schemas (`services/bff/src/bff/main.py`):
|
|
||||||
- Dual route bindings: `POST /api/v1/downloads` and `POST /download` with Pydantic aliases (`magnet`/`magnet_uri`, `imdbid`/`imdb_id`).
|
|
||||||
- Server-side TMDB movie search proxy: `GET /api/v1/movies/search?q=...`.
|
|
||||||
- Server-Sent Events stream: `GET /api/v1/movies/events`.
|
|
||||||
- [ ] `M4.4`: Embed Hosted Web UI (`services/bff/src/bff/templates/` & `static/`):
|
|
||||||
- Clean, responsive dashboard (adapted from extension prototype `app.html`/`app.css`).
|
|
||||||
- Movie search autocomplete with poster previews, magnet input, and live progress bars.
|
|
||||||
- [ ] `M4.5`: Write API tests in `tests/test_bff_routes.py` covering auth extraction, dual routes, search proxy, and SSE streams.
|
|
||||||
- **Verifiable Exit Criteria:**
|
- **Verifiable Exit Criteria:**
|
||||||
- `uv run pytest tests/test_bff_routes.py` passes 100%.
|
- `uv run pytest tests/test_bff_routes.py` validates fail-closed `401`, legacy dual routes, search proxy, and live SSE streaming without CORS errors.
|
||||||
- BFF connects to gRPC worker, serves Web UI, and streams live download progress without browser CORS errors.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📌 Milestone 5: Multi-Container Stack & Deployment Verification
|
## 📌 Milestone 5: Production Reverse-Proxy Deployment & Hardened Verification
|
||||||
- **Objective:** Deliver production-ready containerization, Docker Compose stack, Traefik integration, and end-to-end slice verification.
|
- **Objective:** Finalize production Traefik reverse-proxy configuration, container health probes, and hardened end-to-end verification (`docs/deployment.md`).
|
||||||
- **Dependencies:** Milestone 4.
|
- **Dependencies:** Milestone 4.
|
||||||
- **Requirements Satisfied:** `REQ-11`.
|
- **Requirements Satisfied:** `REQ-11` (Production Deployment).
|
||||||
- **Work Items:**
|
- **Work Items:**
|
||||||
- [ ] `M5.1`: Finalize `services/worker/Dockerfile` and `services/bff/Dockerfile`.
|
- [ ] `M5.1`: Reconcile production `docker-compose.yml` (or production overlay) matching `docs/deployment.md`: Traefik labels, `proxy_network` external bridge + internal `backend` network isolating Worker, `AUTH_ENABLED=true`, and verified non-root `PUID`/`PGID` bind-mount permissions.
|
||||||
- [ ] `M5.2`: Author canonical `docker-compose.yml` defining `bff`, `worker`, and `transmission` services, volume mounts (`./data`, `/media/movies`), and internal/external networks.
|
- [ ] `M5.2`: Add Docker `HEALTHCHECK` directives (`/healthz` on BFF, gRPC health probe on Worker) and audit multi-stage image builds.
|
||||||
- [ ] `M5.3`: Configure health probes: BFF `GET /healthz`, Worker gRPC standard health check.
|
- [ ] `M5.3`: Execute full production E2E verification: SSO header auth $\rightarrow$ TMDB autocomplete $\rightarrow$ Transmission download $\rightarrow$ Two-Tier Sanitizer $\rightarrow$ Stage 2 token check $\rightarrow$ Multi-track atomic relocation $\rightarrow$ Live SSE completion + restart crash-recovery drill.
|
||||||
- [ ] `M5.4`: Execute end-to-end integration test with a small public domain/legal torrent:
|
|
||||||
- Verify full lifecycle: Form submission $\rightarrow$ Transmission download $\rightarrow$ Sanitizer scan $\rightarrow$ Metadata token check $\rightarrow$ Two-stage atomic relocation into Jellyfin/Plex format $\rightarrow$ Live SSE completion update.
|
|
||||||
- **Verifiable Exit Criteria:**
|
- **Verifiable Exit Criteria:**
|
||||||
- `docker compose build` succeeds with zero errors from a fresh checkout.
|
- Fresh `docker compose build` succeeds with zero errors, container health checks stay `healthy`, and full hardened E2E lifecycle passes under `AUTH_ENABLED=true`.
|
||||||
- Full end-to-end vertical slice runs to completion with media appearing in `/media/movies/<Title> (<Year>) [imdbid-<IMDbID>]/`.
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# Milestone 1: Contracts, Toolchain & Database Hardening (Prerequisites & Blockers)
|
# Milestone 1: Contracts, Toolchain & Database Hardening (Complete — M1.8 moved to M3.1)
|
||||||
x 2026-10-31 (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
|
||||||
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) 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 services/worker and services/bff to depend on magnetflix-contracts via workspace dependency +deps @workspace
|
||||||
@@ -6,34 +6,17 @@ x 2026-10-31 (A) Update pyproject.toml to include tests/ in pyright, remove excl
|
|||||||
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
|
||||||
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) 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
|
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
|
||||||
(A) Normalize Base32 btih info_hash to 40-char lowercase hex in DownloadJob and add partial unique index uq_download_jobs_active_info_hash via Alembic migration 003 +db @worker
|
|
||||||
|
|
||||||
# Milestone 2: Pipeline Domain Engine & Filesystem Safety
|
# Next Immediate Deliverable — Milestone 2: Safe Walking Skeleton MVP (See docs/roadmap.md for M3-M5)
|
||||||
(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
|
(A) [M2.1] Implement Two-Tier Media Sanitizer in services/worker/src/worker/sanitizer.py (os.walk followlinks=False, reject symlinks/special/S_ISREG hardlinks/traversal/dangerous exts even inside Sample/, ignore clutter, discard samples & < MIN_VIDEO_BYTES video only, select largest video + subtitles) +sanitizer @worker
|
||||||
(B) Write comprehensive unit tests in tests/test_sanitizer.py covering allowlist, traversal, sample filtering, and largest video selection +test @worker
|
(A) [M2.1] Write unit tests in tests/test_sanitizer.py covering traversal, symlinks, hardlinks, dangerous ext inside Sample/, clutter ignore, subtitle size preservation, and largest video selection +test @worker
|
||||||
(B) Implement TMDB Client & Token Verifier in services/worker/src/worker/metadata.py (early ingestion resolution via /find/{imdb_id} and post-download token overlap check) +metadata @worker
|
(B) [M2.2] Implement Stage 1 TmdbClient in services/worker/src/worker/metadata.py (lazy TMDB_API_KEY, ^tt\d{7,10}$ validation, /find/{imdb_id} v3 query, movie_results & release_date checks) +metadata @worker
|
||||||
(B) Write unit tests with mocked TMDB responses in tests/test_metadata.py verifying match, 404, non-movie rejection, and token overlap +test @worker
|
(B) [M2.2] Implement core atomic relocator in services/worker/src/worker/relocator.py (sanitize_title, [imdbid-...] dup scan in MEDIA_DIR, disk_usage 1.05x check, .staging_<job_id> copy + os.replace swap, deterministic subtitle collision suffix) +relocator @worker
|
||||||
(B) Implement Multi-Track Library Relocator in services/worker/src/worker/relocator.py (title path sanitization, format preservation for .srt/.vtt/.sub/.ass, language/disambiguation tagging, two-stage atomic directory swap) +relocator @worker
|
(B) [M2.2] Write unit tests in tests/test_metadata.py and tests/test_relocator.py +test @worker
|
||||||
(B) Write unit tests in tests/test_relocator.py testing destination directory formatting, subtitle moving, and atomic swap cleanup +test @worker
|
(B) [M2.3] Implement lazy TransmissionClient wrapper in services/worker/src/worker/transmission.py via asyncio.to_thread +transmission @worker
|
||||||
|
(B) [M2.3] Implement minimal PipelineCoordinator in services/worker/src/worker/pipeline.py (urn:btih:<40-hex> + active dup/library checks, tracked asyncio.Task, 2s polling, short-lived sessions, finally cleanup) +pipeline @worker
|
||||||
# Milestone 3: Transmission Integration & Worker Coordinator
|
(B) [M2.3] Implement gRPC PipelineServiceServicer in services/worker/src/worker/service.py & worker/main.py (SubmitDownload, GetJob omitting null completed_at, ListJobs offset/created_at DESC, UNIMPLEMENTED StreamJobStatus, SIGTERM shutdown) +grpc @worker
|
||||||
(C) Implement Transmission client wrapper in services/worker/src/worker/transmission.py (add_torrent to /data/staging/<job_id>, poll progress, remove_torrent with delete_data) +transmission @worker
|
(B) [M2.3] Write tests in tests/test_transmission.py, tests/test_pipeline.py, and tests/test_grpc_service.py +test @worker
|
||||||
(C) Write unit tests with mocked transmission-rpc client in tests/test_transmission.py +test @worker
|
(B) [M2.4] Implement minimal FastAPI BFF in services/bff/src/bff/grpc_client.py, main.py, and services/bff/src/bff/templates/index.html (AUTH_ENABLED app default true, /healthz, POST/GET /api/v1/downloads, 3s polling form, gRPC->HTTP mapping) +api @bff
|
||||||
(C) Implement pipeline state machine coordinator in services/worker/src/worker/pipeline.py (linear transitions + QUEUED->FAILED, 15-min zero-delta stall timeout, separate relocation pool, in-memory pub/sub queues) +pipeline @worker
|
(B) [M2.4] Write API tests in tests/test_bff_routes.py +test @bff
|
||||||
(C) Implement startup active reconciliation sweep in pipeline.py (auto-fail non-terminal jobs, remove Transmission torrents with bounded startup retry, purge staging disks) +pipeline @worker
|
(B) [M2.4] Author local docker-compose.yml (transmission healthcheck + incomplete-dir disabled, worker PUID:PGID + alembic upgrade head, bff AUTH_ENABLED=false, pre-created dirs) and run >= 100 MB public-domain torrent E2E verification +compose @deploy
|
||||||
(C) Implement gRPC PipelineServiceServicer in services/worker/src/worker/service.py and entrypoint worker/main.py (SubmitDownload, GetJob, StreamJobStatus, ListJobs) +grpc @worker
|
|
||||||
(C) Write integration tests in tests/test_grpc_service.py verifying duplicate rejection, job submission, status querying, and pagination +test @worker
|
|
||||||
|
|
||||||
# Milestone 4: FastAPI BFF Gateway, SSE & Web UI
|
|
||||||
(D) Implement Pluggable Identity Adapter Middleware in FastAPI BFF (fail-closed 401 when AUTH_ENABLED=true, configurable AUTH_HEADER_USER/CORS, local_user only when AUTH_ENABLED=false) +auth @bff
|
|
||||||
(D) Implement BFF gRPC client wrapper in services/bff/src/bff/grpc_client.py connecting to Worker service +grpc @bff
|
|
||||||
(D) Implement REST endpoints in services/bff/src/bff/main.py (dual routes POST /api/v1/downloads and POST /download with Pydantic aliases, GET /api/v1/movies/search TMDB proxy) +api @bff
|
|
||||||
(D) Implement Server-Sent Events stream GET /api/v1/movies/events connected to gRPC StreamJobStatus +sse @bff
|
|
||||||
(D) Embed single-origin HTML Web UI dashboard in services/bff/src/bff/templates/ and static/ with movie search autocomplete, poster previews, and live progress bars +ui @bff
|
|
||||||
(D) Write API tests in tests/test_bff_routes.py covering auth extraction, dual routes, search proxy, and SSE streams +test @bff
|
|
||||||
|
|
||||||
# Milestone 5: Multi-Container Stack & Deployment Verification
|
|
||||||
(E) Finalize services/worker/Dockerfile and services/bff/Dockerfile multi-stage production builds +docker @deploy
|
|
||||||
(E) Author canonical production-ready docker-compose.yml including bff, worker, transmission, volume mounts, and network bridges +compose @deploy
|
|
||||||
(E) Configure Traefik routing labels, health probes (/healthz and gRPC health), and verify container communication +traefik @deploy
|
|
||||||
(E) Execute end-to-end integration test with public domain torrent verifying full acquisition, organization, and SSE reporting lifecycle +e2e @test
|
|
||||||
Reference in new issue
Block a user