Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a3649c3ead | ||
|
|
c34512da6b | ||
|
|
a8288d34cb | ||
|
|
b479ed8ccc | ||
|
|
8b1e6b721c | ||
|
|
3d428dba48 |
No files matched your search
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
## 1. Mission & Authority
|
## 1. Mission & Authority
|
||||||
|
|
||||||
**MagNetFlix** is a self-hosted, automated media acquisition pipeline built around **FastAPI (BFF) + gRPC (Worker) + UV Workspaces + SQLite3 WAL + Transmission + Traefik/Authelia SSO**.
|
**MagNetFlix** is a self-hosted, automated media acquisition pipeline built around **FastAPI (BFF) + gRPC (Worker) + UV Workspaces + SQLite3 WAL + Transmission + Reverse Proxy / OIDC SSO**.
|
||||||
- **Architecture Documentation** (`docs/architecture.md`), **Roadmap** (`docs/roadmap.md`), and **Deployment Specifications** (`docs/deployment.md`) define the authoritative design.
|
- **Architecture Documentation** (`docs/architecture.md`), **Roadmap** (`docs/roadmap.md`), and **Deployment Specifications** (`docs/deployment.md`) define the authoritative design.
|
||||||
- **Implementation autonomy ≠ Architectural autonomy.** Do not replace technologies, dependencies, or storage strategies without explicit approval.
|
- **Implementation autonomy ≠ Architectural autonomy.** Do not replace technologies, dependencies, or storage strategies without explicit approval.
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ The working tree represents the user's active work.
|
|||||||
## 3. Architecture & Component Contracts (Progressive Triggers)
|
## 3. Architecture & Component Contracts (Progressive Triggers)
|
||||||
|
|
||||||
- **Mandatory Architecture Review:** Always read `docs/architecture.md` before making any changes affecting API routes, gRPC definitions, database models, directory layouts, or component boundaries.
|
- **Mandatory Architecture Review:** Always read `docs/architecture.md` before making any changes affecting API routes, gRPC definitions, database models, directory layouts, or component boundaries.
|
||||||
- **Read `docs/deployment.md`** before altering networking, Traefik routing, Authelia SSO middleware, or Docker volume bindings.
|
- **Read `docs/deployment.md`** before altering networking, reverse proxy routing, SSO middleware, or Docker volume bindings.
|
||||||
- **Stop and Ask:** If an implementation conflicts with documentation or an ambiguous requirement materially affects architecture, stop and ask the user rather than guessing or silently changing the design.
|
- **Stop and Ask:** If an implementation conflicts with documentation or an ambiguous requirement materially affects architecture, stop and ask the user rather than guessing or silently changing the design.
|
||||||
- **No Speculative Robustness:** Do not add unrequested fallback layers, complex generic abstractions, or future-proofing bloat.
|
- **No Speculative Robustness:** Do not add unrequested fallback layers, complex generic abstractions, or future-proofing bloat.
|
||||||
|
|
||||||
@@ -50,7 +50,7 @@ The working tree represents the user's active work.
|
|||||||
- **Isolated Staging:** Downloads must be confined to an isolated temporary scratch path (e.g., `/data/staging/<job_id>`).
|
- **Isolated Staging:** Downloads must be confined to an isolated temporary scratch path (e.g., `/data/staging/<job_id>`).
|
||||||
- **File Whitelist Sanitization:**
|
- **File Whitelist Sanitization:**
|
||||||
- Whitelist: Video (`.mkv`, `.mp4`, `.avi`, `.webm`) and Subtitles (`.srt`, `.vtt`, `.sub`, `.ass`).
|
- Whitelist: Video (`.mkv`, `.mp4`, `.avi`, `.webm`) and Subtitles (`.srt`, `.vtt`, `.sub`, `.ass`).
|
||||||
- Quarantine / Reject: Executables, binaries, scripts, or archives (`.exe`, `.bat`, `.cmd`, `.sh`, `.scr`, `.vbs`, `.lnk`, `.iso`, `.zip`, `.rar`).
|
- Quarantine / Reject: Executables, binaries, scripts, or archives (case-insensitive: `.exe`, `.bat`, `.cmd`, `.sh`, `.scr`, `.vbs`, `.ps1`, `.lnk`, `.iso`, `.zip`, `.rar`, `.7z`).
|
||||||
- Clean up staging directories immediately after successful file relocation or upon terminal failure.
|
- Clean up staging directories immediately after successful file relocation or upon terminal failure.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ MagNetFlix automates media acquisition from user submission to structured librar
|
|||||||
* **Option 1: Direct Exposed Torrent Client with Script Hooks**: Expose Transmission's Web UI directly via reverse proxy and rely on `torrent-done-script.sh` bash scripts for post-processing.
|
* **Option 1: Direct Exposed Torrent Client with Script Hooks**: Expose Transmission's Web UI directly via reverse proxy and rely on `torrent-done-script.sh` bash scripts for post-processing.
|
||||||
* **Option 2: Monolithic FastAPI Application**: Run HTTP endpoints, in-process BitTorrent client (`libtorrent`), and media processing inside a single Python process.
|
* **Option 2: Monolithic FastAPI Application**: Run HTTP endpoints, in-process BitTorrent client (`libtorrent`), and media processing inside a single Python process.
|
||||||
* **Option 3: Decoupled FastAPI BFF + Private gRPC Pipeline Worker + Isolated Transmission Daemon (Dual-Client Compatible)**:
|
* **Option 3: Decoupled FastAPI BFF + Private gRPC Pipeline Worker + Isolated Transmission Daemon (Dual-Client Compatible)**:
|
||||||
* FastAPI acts as a Backend-for-Frontend (BFF), serving the web UI directly on `addmovie.roadtotech.me` behind Traefik/Authelia SSO, and providing dual API route bindings.
|
* FastAPI acts as a Backend-for-Frontend (BFF), serving the web UI directly behind an upstream reverse proxy / OIDC SSO gateway, and providing dual API route bindings.
|
||||||
* Worker runs as a private gRPC service coordinating an isolated Transmission daemon over an internal Docker bridge.
|
* Worker runs as a private gRPC service coordinating an isolated Transmission daemon over an internal Docker bridge.
|
||||||
* Filesystem operations enforce a two-stage copy-and-swap on the target volume.
|
* Filesystem operations enforce a two-stage copy-and-swap on the target volume.
|
||||||
|
|
||||||
@@ -44,12 +44,12 @@ Chosen option: **Option 3**, because it provides complete physical separation be
|
|||||||
### Summary of Architectural Commitments
|
### Summary of Architectural Commitments
|
||||||
|
|
||||||
#### 1. Dual-Client BFF Gateway & Web UI Hosting
|
#### 1. Dual-Client BFF Gateway & Web UI Hosting
|
||||||
* The FastAPI BFF directly serves the public web UI (adapted from the standalone `app.html` design) as a single-origin application behind Traefik and Authelia forward-auth.
|
* The FastAPI BFF directly serves the public web UI (adapted from the standalone `app.html` design) as a single-origin application behind a configurable reverse proxy and SSO/OIDC forward-auth gateway.
|
||||||
* The BFF simultaneously acts as the API backend for the companion browser extension (`magnetflix-extension`).
|
* The BFF simultaneously acts as the API backend for the companion browser extension (`magnetflix-extension`), with configurable `CORS_ALLOWED_ORIGINS` and target host settings so deployments are portable across any homelab or VPS domain.
|
||||||
* To support both clients without friction:
|
* To support both clients without friction:
|
||||||
* Dual route bindings are established: `POST /api/v1/downloads` (canonical) and `POST /download` (extension alias).
|
* Dual route bindings are established: `POST /api/v1/downloads` (canonical) and `POST /download` (legacy extension compatibility alias).
|
||||||
* Inbound Pydantic schemas accept both naming conventions via validation aliases: `magnet` / `magnet_uri` and `imdbid` / `imdb_id`.
|
* Inbound Pydantic schemas accept both naming conventions via validation aliases: `magnet` / `magnet_uri` and `imdbid` / `imdb_id`.
|
||||||
* The BFF extracts authenticated user identity strictly from the Traefik `Remote-User` header. In local development or extension contexts lacking SSO headers, a deterministic fallback (`local_user`) is applied.
|
* The BFF extracts authenticated user identity from the configurable upstream proxy header (`AUTH_HEADER_USER`, defaulting to `Remote-User`). When `AUTH_ENABLED=true`, missing or empty identity headers fail closed (`401 Unauthorized`). The `local_user` fallback is restricted strictly to `AUTH_ENABLED=false` for offline local development.
|
||||||
|
|
||||||
#### 2. Engine & Network Isolation (Defense-in-Depth)
|
#### 2. Engine & Network Isolation (Defense-in-Depth)
|
||||||
* Transmission daemon and gRPC Worker run strictly on a private, internal Docker bridge (`magnetflix_internal`).
|
* Transmission daemon and gRPC Worker run strictly on a private, internal Docker bridge (`magnetflix_internal`).
|
||||||
|
|||||||
@@ -30,41 +30,46 @@ Following the initial architectural baseline established in [ADR 001](001-pipeli
|
|||||||
- Both `worker` and `bff` depend on `magnetflix-contracts` via `{ workspace = true }`, allowing native `from magnetflix.v1 import pipeline_pb2, pipeline_pb2_grpc` imports.
|
- Both `worker` and `bff` depend on `magnetflix-contracts` via `{ workspace = true }`, allowing native `from magnetflix.v1 import pipeline_pb2, pipeline_pb2_grpc` imports.
|
||||||
- Generated stubs and `docs/api_spec.md` are committed to Git, enabling reproducible offline test and Docker builds.
|
- Generated stubs and `docs/api_spec.md` are committed to Git, enabling reproducible offline test and Docker builds.
|
||||||
|
|
||||||
### 2. Database Partial Unique Index & Info-Hash Column (`DEC-2`)
|
### 2. Database Partial Unique Indexes & Normalized Info-Hash (`DEC-2`)
|
||||||
- Add an indexed column `info_hash` to `download_jobs`.
|
- Add an indexed column `info_hash` to `download_jobs`, normalized to 40-character lowercase hex at ingestion (converting 32-character Base32 `urn:btih:` hashes).
|
||||||
- Add a partial unique index in SQLite:
|
- Add partial unique indexes in SQLite:
|
||||||
```sql
|
```sql
|
||||||
CREATE UNIQUE INDEX uq_download_jobs_active_imdb_id
|
CREATE UNIQUE INDEX uq_download_jobs_active_imdb_id
|
||||||
ON download_jobs (imdb_id)
|
ON download_jobs (imdb_id)
|
||||||
WHERE state NOT IN ('COMPLETED', 'FAILED');
|
WHERE state NOT IN ('COMPLETED', 'FAILED');
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX uq_download_jobs_active_info_hash
|
||||||
|
ON download_jobs (info_hash)
|
||||||
|
WHERE info_hash IS NOT NULL AND state NOT IN ('COMPLETED', 'FAILED');
|
||||||
```
|
```
|
||||||
- Guaranteed engine-level deduplication: concurrent duplicate submissions fail with `IntegrityError`, mapped cleanly to `grpc.StatusCode.ALREADY_EXISTS`.
|
- Guaranteed engine-level deduplication: concurrent duplicate submissions (same active `imdb_id` or same active `info_hash`) fail with `IntegrityError`, mapped cleanly to `grpc.StatusCode.ALREADY_EXISTS`.
|
||||||
|
|
||||||
### 3. Two-Tier Sanitization Policy (`DEC-3`)
|
### 3. Two-Tier Sanitization Policy (`DEC-3`)
|
||||||
- **Tier 1 (Hard Security Rejection)**: Immediate job abort to `FAILED` if the payload contains symbolic links (`os.path.islink`), hard links (`st_nlink > 1`), path traversal (`..`), special device nodes, or dangerous extensions (`.exe`, `.bat`, `.cmd`, `.sh`, `.scr`, `.vbs`, `.ps1`, `.lnk`, `.iso`, `.zip`, `.rar`, `.7z`).
|
- **Tier 1 (Hard Security Rejection)**: Immediate job abort to `FAILED` if the payload contains symbolic links (`os.path.islink`), hard links (`st_nlink > 1`), path traversal (`..`), special device nodes, or dangerous extensions (case-insensitive: `.exe`, `.bat`, `.cmd`, `.sh`, `.scr`, `.vbs`, `.ps1`, `.lnk`, `.iso`, `.zip`, `.rar`, `.7z`).
|
||||||
- **Tier 2 (Allowlist Extraction & Safe Discard)**: Extract allowlisted video (`.mkv`, `.mp4`, `.avi`, `.webm`) and subtitles (`.srt`, `.vtt`, `.sub`, `.ass`). Safely ignore benign clutter (`.nfo`, `.txt`, `.jpg`, `.sfv`). Discard samples (`< 100MB` or `"sample"`). Select the single largest remaining video file as the feature film.
|
- **Tier 2 (Allowlist Extraction & Safe Discard)**: Extract allowlisted video (`.mkv`, `.mp4`, `.avi`, `.webm`) and subtitles (`.srt`, `.vtt`, `.sub`, `.ass`). Safely ignore unlisted non-dangerous files (such as `.nfo`, `.txt`, `.jpg`, `.sfv`). Discard samples (`< 100 MB` or case-insensitive word-boundary `"sample"` token / `Sample` directory). Select the single largest remaining video file as the feature film.
|
||||||
|
|
||||||
### 4. Two-Stage Metadata Lifecycle (`DEC-4`)
|
### 4. Two-Stage Metadata Lifecycle (`DEC-4`)
|
||||||
- **Stage 1 (Early Ingestion)**: Query TMDB API `/find/{imdb_id}?external_source=imdb_id` at job submission/queueing time. Verify valid movie entity type; persist `title` and `year` to SQLite immediately. Live UI and SSE streams display movie metadata from second 1.
|
- **Stage 1 (Early Ingestion)**: Query TMDB API `/find/{imdb_id}?external_source=imdb_id` at job submission/queueing time. Verify valid movie entity type; persist `title` and `year` to SQLite immediately. Live UI and SSE streams display movie metadata from second 1.
|
||||||
- **Stage 2 (Post-Download Token Check)**: Compare cached `(title, year)` tokens against primary video filename completely offline from SQLite without external network dependencies.
|
- **Stage 2 (Post-Download Token Check)**: Compare cached `(title, year)` tokens against primary video filename completely offline from SQLite without external network dependencies.
|
||||||
|
|
||||||
### 5. Multi-Track Subtitle Preservation & Two-Stage Atomic Swap (`DEC-5`)
|
### 5. Multi-Track Subtitle Preservation, Path Sanitization & Two-Stage Atomic Swap (`DEC-5`)
|
||||||
- Retain native subtitle extensions (`.srt`, `.vtt`, `.ass`).
|
- Deterministically sanitize `<Title>` (stripping/replacing path-breaking characters such as `/`, `\`, `:`, `*`, `?`, `"`, `<`, `>`, `|`, and `..`) before constructing directory and file paths.
|
||||||
- Parse language and forced tags from filenames; append disambiguation indices (`<Title> (<Year>).en.1.srt`) when multiple subtitles share tags to prevent overwrites.
|
- Retain native allowlisted subtitle extensions (`.srt`, `.vtt`, `.sub`, `.ass`).
|
||||||
- Copy verified files across storage boundaries to `/media/movies/.staging_<job_id>/`. Pre-check destination existence, then atomically swap via `os.replace`.
|
- Parse language and forced tags from filenames; omit the language tag if none is detected (`<SanitizedTitle> (<Year>).<ext>`) and append disambiguation indices (`<SanitizedTitle> (<Year>).en.1.srt`) when multiple subtitles share tags to prevent overwrites.
|
||||||
|
- Copy verified files across storage boundaries to `/media/movies/.staging_<job_id>/` after checking free disk space. Pre-check destination existence, then atomically swap via `os.replace`.
|
||||||
|
|
||||||
### 6. Active Reconciliation & Stalled Timeout (`DEC-6`)
|
### 6. Active Reconciliation & Stalled Timeout (`DEC-6`)
|
||||||
- On worker startup, query all non-terminal SQLite jobs: transition state to `FAILED`, actively call Transmission RPC `remove_torrent(info_hash, delete_data=True)`, and purge scratch directories `/data/staging/<job_id>/` and `/media/movies/.staging_<job_id>/`.
|
- On worker startup, query all non-terminal SQLite jobs: transition state to `FAILED`, actively call Transmission RPC `remove_torrent(info_hash, delete_data=True)` (with bounded startup retry/backoff while Transmission initializes), and purge scratch directories `/data/staging/<job_id>/` and `/media/movies/.staging_<job_id>/`.
|
||||||
- Monitor swarm progress during `DOWNLOADING`: auto-fail jobs with 0 progress for 15 consecutive minutes.
|
- Monitor swarm progress during `DOWNLOADING`: auto-fail jobs with zero progress delta (unchanged downloaded bytes/progress or unresolved metadata) for 15 consecutive minutes.
|
||||||
|
|
||||||
### 7. Thread Offloading & In-Memory SSE Fan-Out (`DEC-7`)
|
### 7. Thread Offloading & In-Memory SSE Fan-Out (`DEC-7`)
|
||||||
- Dispatch all blocking disk copies (`shutil.copy2`), synchronous RPC calls (`transmission-rpc`), and directory scans to a bounded `ThreadPoolExecutor(max_workers=4)`.
|
- Dispatch blocking disk copies (`shutil.copy2`) to a dedicated bounded relocation executor isolated from lightweight `transmission-rpc` calls and directory scans so multi-GB transfers never starve swarm polling.
|
||||||
- Database sessions are strictly short-lived (committed and closed before long I/O).
|
- Database sessions are strictly short-lived (committed and closed before long I/O).
|
||||||
- Broadcast progress and state change events via an internal `asyncio.Queue` pub/sub broker to connected gRPC/SSE streams.
|
- Subscribe to the `asyncio.Queue` pub/sub broker *before* reading the initial SQLite snapshot, using bounded per-subscriber queues with latest-state coalescing for connected gRPC/SSE streams.
|
||||||
|
|
||||||
### 8. Pluggable Identity Adapter & Server-Side Search (`DEC-8`)
|
### 8. Pluggable Identity Adapter & Server-Side Search (`DEC-8`)
|
||||||
- FastAPI BFF middleware reads identity headers via configurable environment variables (`AUTH_ENABLED`, `AUTH_HEADER_USER`, `AUTH_HEADER_EMAIL`) with a safe dev fallback (`local_user`).
|
- FastAPI BFF middleware reads identity headers via configurable environment variables (`AUTH_ENABLED`, `AUTH_HEADER_USER`), failing closed with `401 Unauthorized` when `AUTH_ENABLED=true` and falling back to `local_user` only when `AUTH_ENABLED=false`.
|
||||||
- Expose `GET /api/v1/movies/search?q=...` proxying TMDB movie search server-side to eliminate CORS issues and undocumented third-party scraping.
|
- Expose `GET /api/v1/movies/search?q=...` proxying TMDB movie search server-side to eliminate CORS issues and undocumented third-party scraping, and support configurable `CORS_ALLOWED_ORIGINS` for browser extension deployments.
|
||||||
- Mount dual route bindings (`POST /api/v1/downloads` and `POST /download`) with Pydantic aliases (`magnet`/`magnet_uri`, `imdbid`/`imdb_id`).
|
- Mount dual route bindings (`POST /api/v1/downloads` and `POST /download`) with Pydantic aliases (`magnet`/`magnet_uri`, `imdbid`/`imdb_id`).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
+81
-64
@@ -1,58 +1,70 @@
|
|||||||
# 🏛️ MagNetFlix — System Architecture & Component Design
|
# MagNetFlix — System Architecture & Component Design
|
||||||
|
|
||||||
MagNetFlix uses a **Backend-For-Frontend (BFF)** pattern paired with an internal **gRPC Pipeline Worker** service to decouple public web endpoints from disk I/O, BitTorrent network activity, and media processing.
|
MagNetFlix uses a **Backend-For-Frontend (BFF)** pattern paired with an internal **gRPC Pipeline Worker** service to decouple public web endpoints from disk I/O, BitTorrent network activity, and media processing.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📐 High-Level Architecture
|
## High-Level Architecture
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
flowchart TB
|
flowchart TB
|
||||||
subgraph Edge ["🌐 Public Edge (Protected Gateway)"]
|
subgraph Edge ["Public Edge (Protected Gateway)"]
|
||||||
Browser["User Browser\n(Web UI Dashboard)"] -->|HTTPS| Proxy["Reverse Proxy\n(Traefik / Nginx / Caddy)"]
|
Browser["User Browser\n(Web UI Dashboard)"] -->|HTTPS| Proxy["Reverse Proxy\n(Traefik / Nginx / Caddy)"]
|
||||||
Extension["Browser Extension\n(One-Click Magnet Interceptor)"] -->|HTTPS| Proxy
|
Extension["Browser Extension\n(One-Click Magnet Interceptor)"] -->|HTTPS| Proxy
|
||||||
Proxy <-->|Auth Forward / Bearer| SSO["Identity Provider / SSO\n(Authelia / Authentik / OAuth2-Proxy)"]
|
Proxy <-->|Forward-Auth / OIDC Proxy| SSO["Identity Provider / SSO\n(OAuth2-Proxy / Authentik / Authelia)"]
|
||||||
end
|
end
|
||||||
|
|
||||||
subgraph InternalServices ["🛡️ Internal Service Tier (Docker Bridge)"]
|
subgraph InternalServices ["Internal Service Tier (Docker Bridge)"]
|
||||||
Proxy -->|HTTP + Identity Headers| BFF["FastAPI BFF Gateway\n(Pluggable Auth Adapter & SSE Stream)"]
|
Proxy -->|HTTP + Identity Header| BFF["FastAPI BFF Gateway\n(Pluggable Auth Adapter & SSE Stream)"]
|
||||||
|
BFF -->|Movie Search| TMDB["TMDB API"]
|
||||||
|
|
||||||
subgraph WorkerApp ["Worker Service Tier"]
|
subgraph WorkerApp ["Worker Service Tier"]
|
||||||
BFF -->|gRPC / Status Stream| Worker["gRPC Pipeline Worker"]
|
BFF -->|gRPC / Status Stream| Worker["gRPC Pipeline Worker"]
|
||||||
Worker --> DB[("SQLite 3 (WAL Mode)\nJobs & Audit Store")]
|
Worker --> DB[("SQLite 3 (WAL Mode)\n/data/magnetflix.sqlite3")]
|
||||||
Worker --> MetaService["TMDB Metadata Client\n(Early Resolution & Token Check)"]
|
Worker --> MetaService["TMDB Metadata Client\n(Early Resolution & Token Check)"]
|
||||||
|
MetaService -->|Title/Year Lookup| TMDB
|
||||||
Worker --> Sanitizer["Media Sanitizer & Allowlist\n(Two-Tier Security Boundary)"]
|
Worker --> Sanitizer["Media Sanitizer & Allowlist\n(Two-Tier Security Boundary)"]
|
||||||
Worker --> StorageMgr["Library Relocator & Renamer\n(Two-Stage Atomic Relocation)"]
|
Worker --> StorageMgr["Library Relocator & Renamer\n(Two-Stage Atomic Relocation)"]
|
||||||
end
|
end
|
||||||
|
|
||||||
Worker -->|Offloaded RPC| Torrent["Transmission Daemon"]
|
Worker -->|Transmission RPC| Torrent["Transmission Daemon"]
|
||||||
end
|
end
|
||||||
|
|
||||||
subgraph Volumes ["💾 Storage Mounts"]
|
subgraph Volumes ["Storage Mounts"]
|
||||||
Torrent --> StagingDir[("/data/staging/<job_id> (Scratch Disk)")]
|
Torrent --> StagingDir[("/data/staging/<job_id> (Scratch Disk)")]
|
||||||
StorageMgr --> FinalMedia[("/media/movies (Jellyfin/Plex Library)")]
|
StorageMgr --> FinalMedia[("/media/movies (Jellyfin/Plex Library)")]
|
||||||
end
|
end
|
||||||
```
|
```
|
||||||
|
|
||||||
> **Design Decisions & Tradeoffs:**
|
### Canonical References
|
||||||
> - [ADR 001: Pipeline Safety, Storage Boundaries, and BFF Dual-Client Architecture](adr/001-pipeline-safety-and-bff-dual-client.md)
|
- **Design Decisions (`DEC-1`–`DEC-8`):** [ADR 001: Pipeline Safety & BFF Dual-Client](adr/001-pipeline-safety-and-bff-dual-client.md) · [ADR 002: Pipeline Invariants & Active Reconciliation](adr/002-pipeline-invariants-and-active-reconciliation.md)
|
||||||
> - [ADR 002: Pipeline Invariants, Two-Stage Metadata, and Active Reconciliation](adr/002-pipeline-invariants-and-active-reconciliation.md)
|
- **gRPC & Persistence Contracts:** [`proto/magnetflix/v1/pipeline.proto`](../proto/magnetflix/v1/pipeline.proto) (`SubmitDownload`, `GetJob`, `StreamJobStatus`, `ListJobs`) · [`services/worker/src/worker/db/models.py`](../services/worker/src/worker/db/models.py)
|
||||||
|
- **Deployment & Roadmap:** [Deployment Topology](deployment.md) · [Implementation Roadmap](roadmap.md)
|
||||||
|
|
||||||
|
### Scope, Non-Goals & Operational Limits
|
||||||
|
- **Scope:** Single-movie acquisition via IMDb ID and BitTorrent `btih` magnet URIs, organized into Jellyfin/Plex naming conventions.
|
||||||
|
- **v1 Non-Goals:** TV series/multi-episode packs, BitTorrent v2 (`btmh`) magnets, in-flight job cancellation (`CancelDownload`), and direct JWT/JWKS validation inside the BFF.
|
||||||
|
- **Operational Limits:**
|
||||||
|
- Cross-volume relocation requires temporary free space on `/media/movies` equal to the feature film and subtitles being copied (`ORGANIZING`).
|
||||||
|
- `/data/staging` and `/data/magnetflix.sqlite3` share `/data` unless mounted separately; pre-check available disk space before accepting or relocating payloads.
|
||||||
|
- SQLite WAL supports concurrent readers and a single writer; keep database transactions short-lived and outside long I/O.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🔄 Job State Machine & Lifecycle Invariants
|
## Job State Machine & Lifecycle Invariants
|
||||||
|
|
||||||
The pipeline worker operates strictly as a finite state machine with terminal failure handling.
|
The pipeline worker operates as a finite state machine with terminal failure handling.
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
stateDiagram-v2
|
stateDiagram-v2
|
||||||
[*] --> QUEUED: SubmitDownload()
|
[*] --> QUEUED: SubmitDownload()
|
||||||
QUEUED --> DOWNLOADING: Transmission starts torrent
|
QUEUED --> DOWNLOADING: Transmission starts torrent
|
||||||
|
QUEUED --> FAILED: Startup crash recovery / pre-download abort
|
||||||
DOWNLOADING --> SCANNING: Torrent reaches 100%
|
DOWNLOADING --> SCANNING: Torrent reaches 100%
|
||||||
DOWNLOADING --> FAILED: Torrent error / 15-min stall timeout
|
DOWNLOADING --> FAILED: Torrent error / 15-min zero-delta stall
|
||||||
|
|
||||||
SCANNING --> VERIFYING_METADATA: Two-Tier Sanitizer validates payload
|
SCANNING --> VERIFYING_METADATA: Two-Tier Sanitizer validates payload
|
||||||
SCANNING --> FAILED: Security threat (symlink/traversal/exe) / no valid video
|
SCANNING --> FAILED: Security threat or no valid video
|
||||||
|
|
||||||
VERIFYING_METADATA --> ORGANIZING: Token overlap matches TMDB cache
|
VERIFYING_METADATA --> ORGANIZING: Token overlap matches TMDB cache
|
||||||
VERIFYING_METADATA --> FAILED: Title/year token mismatch
|
VERIFYING_METADATA --> FAILED: Title/year token mismatch
|
||||||
@@ -65,96 +77,101 @@ stateDiagram-v2
|
|||||||
```
|
```
|
||||||
|
|
||||||
### Transition & Concurrency Invariants
|
### Transition & Concurrency Invariants
|
||||||
1. **Linear Progression**: `QUEUED` ➔ `DOWNLOADING` ➔ `SCANNING` ➔ `VERIFYING_METADATA` ➔ `ORGANIZING` ➔ `COMPLETED`.
|
1. **Nominal Progression**: `QUEUED` -> `DOWNLOADING` -> `SCANNING` -> `VERIFYING_METADATA` -> `ORGANIZING` -> `COMPLETED`.
|
||||||
2. **Terminal Failure**: Any failure at any phase transitions the job directly to `FAILED` with a populated `error_message`. Terminal states (`COMPLETED`, `FAILED`) are immutable.
|
2. **Terminal Failure**: Any failure at any phase transitions the job directly to `FAILED` with a populated `error_message`. Terminal states (`COMPLETED`, `FAILED`) are immutable.
|
||||||
3. **Active-Job Idempotency (`DEC-2`)**:
|
3. **Active-Job Idempotency (`DEC-2`)**:
|
||||||
- Submissions are rejected if a non-terminal job for the same `imdb_id` is currently active in SQLite.
|
- Magnet `urn:btih:` hashes are normalized to 40-character lowercase hex at ingestion (converting 32-character Base32 hashes); non-`btih` or malformed magnets are rejected.
|
||||||
- Enforced by a partial unique index: `uq_download_jobs_active_imdb_id ON download_jobs (imdb_id) WHERE state NOT IN ('COMPLETED', 'FAILED')`.
|
- Submissions are rejected (`ALREADY_EXISTS`) if a non-terminal job (`state NOT IN ('COMPLETED', 'FAILED')`) exists in SQLite for the same `imdb_id` **or** the same normalized `info_hash` (preventing two jobs from sharing one Transmission swarm and deleting each other's files).
|
||||||
- Submissions are rejected if `/media/movies/*[imdbid-{imdb_id}]` already exists in the destination library.
|
- Submissions are rejected if the destination library already contains a matching `[imdbid-{imdb_id}]` directory or the canonical target path.
|
||||||
4. **Stalled Download Timeout (`DEC-6`)**: If a torrent achieves zero progress (0 bytes downloaded or unresolved magnet metadata) for 15 consecutive minutes, the job transitions to `FAILED` with reason `"Download stalled: no seeds or metadata timeout"`.
|
4. **Stalled Download Timeout (`DEC-6`)**: If a torrent makes **zero progress delta** (unchanged downloaded bytes/progress percentage, or unresolved magnet metadata) for 15 consecutive minutes, the job transitions to `FAILED` with reason `"Download stalled: no seeds or metadata timeout"`.
|
||||||
5. **Active Startup Crash Recovery (`DEC-6`)**: Upon worker startup, an active reconciliation sweep queries all orphaned non-terminal jobs:
|
5. **Active Startup Crash Recovery (`DEC-6`)**: Upon worker startup, an active reconciliation sweep queries all non-terminal jobs:
|
||||||
- Transitions their SQLite state to `FAILED` with reason `"Worker restarted during execution"`.
|
- Transitions their SQLite state to `FAILED` with reason `"Worker restarted during execution"`.
|
||||||
- Actively signals Transmission via RPC to remove the torrent session via `info_hash` (`delete_data=True`).
|
- Connects to Transmission RPC (with bounded startup retry/backoff if Transmission is still initializing) to remove the torrent session via `info_hash` and delete its data.
|
||||||
- Purges scratch directories `/data/staging/<job_id>/` and `/media/movies/.staging_<job_id>/`.
|
- Purges scratch directories `/data/staging/<job_id>/` and `/media/movies/.staging_<job_id>/`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🛡️ Security & Media Sanitizer Specification (`DEC-3`)
|
## Security & Media Sanitizer Specification (`DEC-3`)
|
||||||
|
|
||||||
The sanitizer enforces a strict two-tier security boundary on untrusted torrent payloads before files are processed:
|
The sanitizer enforces a two-tier security boundary on untrusted torrent payloads before files are processed (all extension checks are case-insensitive):
|
||||||
|
|
||||||
### Tier 1: Hard-Fail Security Threats (Immediate Abort to `FAILED`)
|
### Tier 1: Hard-Fail Security Threats (Immediate Abort to `FAILED`)
|
||||||
- **Filesystem Traversal**: Rejects any file or directory path that resolves outside `/data/staging/<job_id>/` or contains relative escaping elements (`..`).
|
- **Filesystem Traversal**: Rejects any file or directory path that resolves outside `/data/staging/<job_id>/` or contains parent-directory traversal segments (`..`).
|
||||||
- **Links & Special Nodes**: Rejects any symbolic links (`os.path.islink`), hard links (`st_nlink > 1`), FIFOs, sockets, or device nodes.
|
- **Links & Special Nodes**: Rejects any symbolic links, hard links (`st_nlink > 1`), FIFOs, sockets, or device nodes.
|
||||||
- **Dangerous Extensions**: Rejects any payload containing executable binaries, scripts, or disk images:
|
- **Dangerous Extensions**: Rejects any payload containing executable binaries, scripts, or archives/disk images:
|
||||||
`.exe`, `.bat`, `.cmd`, `.sh`, `.scr`, `.vbs`, `.ps1`, `.lnk`, `.iso`, `.zip`, `.rar`, `.7z`.
|
`.exe`, `.bat`, `.cmd`, `.sh`, `.scr`, `.vbs`, `.ps1`, `.lnk`, `.iso`, `.zip`, `.rar`, `.7z`.
|
||||||
|
|
||||||
### Tier 2: Allowlist Extraction & Safe Discard
|
### Tier 2: Allowlist Extraction & Safe Discard
|
||||||
- **Allowed Video**: `.mkv`, `.mp4`, `.avi`, `.webm`
|
- **Allowed Video**: `.mkv`, `.mp4`, `.avi`, `.webm`
|
||||||
- **Allowed Subtitles**: `.srt`, `.vtt`, `.sub`, `.ass`
|
- **Allowed Subtitles**: `.srt`, `.vtt`, `.sub`, `.ass`
|
||||||
- **Harmless Clutter**: Benign non-media clutter (`.nfo`, `.txt`, `.jpg`, `.sfv`) is safely ignored during extraction and cleaned up when the scratch directory is purged.
|
- **Ignored Non-Media Files**: Non-allowlisted, non-dangerous files (such as `.nfo`, `.txt`, `.jpg`, `.sfv`, or other unrecognized clutter) are ignored during extraction and deleted when the scratch directory is purged.
|
||||||
- **Sample Discard**: Files containing `sample` in the filename or with size `< 100MB` are discarded.
|
- **Sample Discard**: Files under `100 MB` or matching `"sample"` as a case-insensitive standalone token / parent `Sample` directory are discarded (avoiding false positives on movie titles containing `"sample"` as a substring).
|
||||||
- **Primary Video Selection**: The single largest remaining video file is selected as the feature film. If 0 eligible video files remain, the job transitions to `FAILED`.
|
- **Primary Video Selection**: The single largest remaining video file is selected as the feature film. If 0 eligible video files remain, the job transitions to `FAILED`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🎬 Metadata Authority & Two-Stage Lifecycle (`DEC-4`)
|
## Metadata Authority & Two-Stage Lifecycle (`DEC-4`)
|
||||||
|
|
||||||
- **Authority**: **The Movie Database (TMDB) API** using `/find/{imdb_id}?external_source=imdb_id`.
|
- **Authority**: **The Movie Database (TMDB) API** (`/find/{imdb_id}?external_source=imdb_id`) with bounded HTTP timeouts and retries.
|
||||||
- **Stage 1 (Early Ingestion Resolution)**:
|
- **Stage 1 (Early Ingestion Resolution)**:
|
||||||
- Validates `imdb_id` format (`^tt\d{7,10}$`) and queries TMDB at submission/queueing time.
|
- Validates standard IMDb ID format (`tt` followed by 7–10 digits) and queries TMDB at submission/queueing time.
|
||||||
- Verifies the entity is a valid movie (rejects non-existent IDs and TV shows before downloading).
|
- Verifies the entity is a valid movie (rejects non-existent IDs and TV shows before downloading).
|
||||||
- Persists canonical `title` and `year` to `DownloadJob`, immediately populating live UI dashboards and SSE status frames.
|
- Persists canonical `title` and `year` to `DownloadJob`, making them available to live UI dashboards and SSE streams from the start of the job.
|
||||||
- **Stage 2 (Post-Download Token Verification)**:
|
- **Stage 2 (Post-Download Token Verification)**:
|
||||||
- Once the torrent completes, the worker compares cached `(title, year)` tokens against the primary video filename and torrent folder name.
|
- Once the torrent completes, the worker compares cached `(title, year)` tokens against the primary video filename and torrent folder name.
|
||||||
- Executed entirely offline from the SQLite database cache without outbound network dependencies.
|
- Executed against the SQLite database cache with no outbound network calls.
|
||||||
- Zero token overlap aborts the job to `FAILED` (`"Torrent payload does not appear to match TMDB metadata"`).
|
- Zero token overlap aborts the job to `FAILED` (`"Torrent payload does not appear to match TMDB metadata"`).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📂 Storage Architecture & Two-Stage Atomic Relocation (`DEC-5`)
|
## Storage Architecture & Two-Stage Atomic Relocation (`DEC-5`)
|
||||||
|
|
||||||
- **Canonical Staging Path**: `/data/staging/<job_id>/` (fast local scratch storage).
|
- **Canonical Staging Path**: `/data/staging/<job_id>/` (local scratch storage).
|
||||||
|
- **Path & Filename Sanitization**: Before building destination paths, `<Title>` is deterministically sanitized to strip or replace filesystem-illegal and path-breaking characters (`/`, `\`, `:`, `*`, `?`, `"`, `<`, `>`, `|`, control characters, and `..`) and collapse excess whitespace.
|
||||||
- **Canonical Library Destination**:
|
- **Canonical Library Destination**:
|
||||||
```text
|
```text
|
||||||
/media/movies/<Title> (<Year>) [imdbid-<IMDbID>]/<Title> (<Year>).<ext>
|
/media/movies/<SanitizedTitle> (<Year>) [imdbid-<IMDbID>]/<SanitizedTitle> (<Year>).<ext>
|
||||||
/media/movies/<Title> (<Year>) [imdbid-<IMDbID>]/<Title> (<Year>).en.srt
|
/media/movies/<SanitizedTitle> (<Year>) [imdbid-<IMDbID>]/<SanitizedTitle> (<Year>).en.srt
|
||||||
/media/movies/<Title> (<Year>) [imdbid-<IMDbID>]/<Title> (<Year>).en.forced.srt
|
/media/movies/<SanitizedTitle> (<Year>) [imdbid-<IMDbID>]/<SanitizedTitle> (<Year>).en.forced.srt
|
||||||
/media/movies/<Title> (<Year>) [imdbid-<IMDbID>]/<Title> (<Year>).ja.ass
|
/media/movies/<SanitizedTitle> (<Year>) [imdbid-<IMDbID>]/<SanitizedTitle> (<Year>).ja.ass
|
||||||
```
|
```
|
||||||
- **Two-Stage Atomic Relocation (Cross-Volume Safe)**:
|
- **Two-Stage Atomic Relocation (Cross-Volume Safe)**:
|
||||||
1. *Transfer Stage*: Validated video and subtitles are copied from `/data/staging/<job_id>/` to temporary staging on the destination mount: `/media/movies/.staging_<job_id>/` using `shutil.copy2`. Subtitles preserve native formats (`.srt`, `.vtt`, `.ass`) and parse language/forced tags with disambiguation indices (`.en.1.srt`) to prevent overwrites.
|
1. *Pre-check & Transfer Stage*: Verify sufficient free space on `/media/movies` and verify the destination directory does not already exist. Copy validated video and subtitles across volumes from `/data/staging/<job_id>/` to temporary staging on the destination mount (`/media/movies/.staging_<job_id>/`). The relocator preserves native allowlisted subtitle formats (`.srt`, `.vtt`, `.sub`, `.ass`), parses language/forced tags from filenames, omits the language tag when none is detected (`<SanitizedTitle> (<Year>).<ext>`), and appends disambiguation indices (`.en.1.srt` or `.1.srt`) to prevent overwrites.
|
||||||
2. *Pre-check & Atomic Swap*: The worker verifies that `/media/movies/<Title> (<Year>) [imdbid-<IMDbID>]/` does not already exist. It then uses `os.replace` to atomically rename `.staging_<job_id>/` to the final path. This prevents media servers (Jellyfin/Plex) from indexing partially-copied media files.
|
2. *Atomic Swap*: Atomically rename `.staging_<job_id>/` to the final destination directory on the same target filesystem so media servers (Jellyfin/Plex) never index partially copied media files.
|
||||||
- **Cleanup Invariant**:
|
- **Permissions & Cleanup Invariant**:
|
||||||
|
- `worker` and `transmission` share aligned non-root `PUID`/`PGID` ownership (`1000:1000` by default) so staging and final library files remain readable by media servers.
|
||||||
- Scratch `/data/staging/<job_id>/` and any temporary `.staging_<job_id>/` are purged immediately upon `COMPLETED` or `FAILED`.
|
- Scratch `/data/staging/<job_id>/` and any temporary `.staging_<job_id>/` are purged immediately upon `COMPLETED` or `FAILED`.
|
||||||
- Transmission session is removed via RPC `remove_torrent(info_hash, delete_data=True)` to prevent memory or tracker leaks.
|
- The Transmission session is removed via RPC with `delete_data=True` to reclaim session memory and stop active swarm announcements.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## ⚡ Async Concurrency & Thread Offloading (`DEC-7`)
|
## Async Concurrency & Event Streaming (`DEC-7`)
|
||||||
|
|
||||||
- **Non-Blocking Worker Event Loop**:
|
- **Non-Blocking Worker Event Loop & Pool Isolation**:
|
||||||
- The worker coordinates jobs using Python `asyncio` (`grpc.aio`, `aiosqlite`, `httpx`).
|
- The worker coordinates jobs asynchronously (`grpc.aio`, `aiosqlite`, `httpx`).
|
||||||
- All blocking operations (multi-gigabyte `shutil.copy2` transfers, synchronous `transmission-rpc` HTTP calls, and recursive filesystem scans) are dispatched to a dedicated bounded `ThreadPoolExecutor(max_workers=4)`.
|
- Blocking operations are offloaded to **separate bounded worker pools** so multi-gigabyte cross-volume file copies cannot starve lightweight `transmission-rpc` progress polling or filesystem scans.
|
||||||
- Database sessions are strictly short-lived; transactions are committed before long I/O operations and closed immediately.
|
- Database sessions are short-lived: transactions are committed before long I/O operations and closed immediately.
|
||||||
|
- Graceful shutdown handles `SIGINT`/`SIGTERM` by stopping the gRPC server cleanly and draining active workers.
|
||||||
- **In-Memory Pub/Sub Event Streaming**:
|
- **In-Memory Pub/Sub Event Streaming**:
|
||||||
- An internal `asyncio.Queue` pub/sub broker broadcasts progress and state change events to connected `StreamJobStatus` gRPC streams without polling SQLite in tight loops.
|
- An internal in-memory pub/sub broker broadcasts progress and state change events to connected `StreamJobStatus` gRPC streams, avoiding SQLite polling loops.
|
||||||
- Graceful shutdown handles `SIGINT`/`SIGTERM` via `server.stop(grace=5)`.
|
- Streams subscribe to the broker *before* reading the initial SQLite snapshot (deduplicating by update timestamp/state) and use bounded per-subscriber queues with latest-state coalescing so slow SSE clients never exhaust memory or block healthy streams.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🌐 Pluggable Identity Adapter & Dual-Client BFF (`DEC-8`)
|
## Pluggable Identity Adapter & Dual-Client BFF (`DEC-8`)
|
||||||
|
|
||||||
- **Pluggable Identity Adapter**:
|
- **Provider-Agnostic Identity Adapter (Fail-Closed)**:
|
||||||
- FastAPI middleware reads authenticated identity from upstream reverse proxies via configurable environment variables:
|
- FastAPI middleware reads the authenticated username from an upstream reverse proxy or OIDC proxy (such as OAuth2-Proxy, Authentik, Authelia, Caddy, or Nginx) via configurable environment variables:
|
||||||
- `AUTH_ENABLED`: boolean (default: `true`; if `false`, defaults to `local_user` for offline/local development).
|
- `AUTH_ENABLED`: boolean (default: `true`). When `true`, missing or empty identity headers **fail closed with `401 Unauthorized`**.
|
||||||
- `AUTH_HEADER_USER`: header name (default: `"Remote-User"`, configurable for Authentik, OAuth2-Proxy, etc.).
|
- `AUTH_HEADER_USER`: header name (default: `"Remote-User"`, configurable for any proxy/IdP such as `X-authentik-username` or `X-Forwarded-User`).
|
||||||
- `AUTH_HEADER_EMAIL`: header name (default: `"Remote-Email"`).
|
- When `AUTH_ENABLED=false` (local development/testing only), identity falls back to `local_user`.
|
||||||
|
- **Portable Configuration & CORS**:
|
||||||
|
- Deployment domains, proxy middlewares, and `CORS_ALLOWED_ORIGINS` (for custom browser extension origins) are environment-driven—zero homelab domains or specific SSO vendors are hardcoded in application logic.
|
||||||
- **Server-Side Movie Search Proxy**:
|
- **Server-Side Movie Search Proxy**:
|
||||||
- BFF exposes `GET /api/v1/movies/search?q=...` proxying official TMDB movie search queries server-side using `TMDB_API_KEY`.
|
- BFF exposes `GET /api/v1/movies/search?q=...`, proxying official TMDB movie search queries server-side using `TMDB_API_KEY` to avoid client-side scraping and browser CORS issues.
|
||||||
- Eliminates client-side scraping of undocumented APIs and prevents browser CORS issues.
|
- **Dual Client Routes, Health Probes & Schemas**:
|
||||||
- **Dual Client Routes & Schemas**:
|
|
||||||
- Supports both the hosted Web UI dashboard and the companion browser extension (`magnetflix-extension`):
|
- Supports both the hosted Web UI dashboard and the companion browser extension (`magnetflix-extension`):
|
||||||
- `POST /api/v1/downloads` (canonical) and `POST /download` (extension alias).
|
- `POST /api/v1/downloads` (canonical) and `POST /download` (legacy extension compatibility alias).
|
||||||
- Pydantic validation aliases accept `magnet` / `magnet_uri` and `imdbid` / `imdb_id`.
|
- Inbound validation aliases accept `magnet` / `magnet_uri` and `imdbid` / `imdb_id`.
|
||||||
- Real-time Server-Sent Events (SSE) route at `GET /api/v1/movies/events`.
|
- Real-time Server-Sent Events (SSE) stream at `GET /api/v1/movies/events` backed by gRPC `StreamJobStatus`.
|
||||||
|
- Health probes: BFF `GET /healthz` and Worker standard gRPC health check.
|
||||||
+34
-23
@@ -19,19 +19,19 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
- GRPC_WORKER_HOST=worker:50051
|
- GRPC_WORKER_HOST=worker:50051
|
||||||
- APP_ENV=production
|
- APP_ENV=production
|
||||||
- AUTH_ENABLED=true
|
- AUTH_ENABLED=${AUTH_ENABLED:-true}
|
||||||
- AUTH_HEADER_USER=Remote-User
|
- AUTH_HEADER_USER=${AUTH_HEADER_USER:-Remote-User}
|
||||||
- AUTH_HEADER_EMAIL=Remote-Email
|
- CORS_ALLOWED_ORIGINS=${CORS_ALLOWED_ORIGINS:-}
|
||||||
- TMDB_API_KEY=${TMDB_API_KEY}
|
- TMDB_API_KEY=${TMDB_API_KEY}
|
||||||
networks:
|
networks:
|
||||||
- traefik_network
|
- proxy_network
|
||||||
- magnetflix_internal
|
- magnetflix_internal
|
||||||
labels:
|
labels:
|
||||||
- "traefik.enable=true"
|
- "traefik.enable=true"
|
||||||
- "traefik.http.routers.magnetflix.rule=Host(`addmovie.roadtotech.me`)"
|
- "traefik.http.routers.magnetflix.rule=Host(`${MAGNETFLIX_HOST}`)"
|
||||||
- "traefik.http.routers.magnetflix.entrypoints=websecure"
|
- "traefik.http.routers.magnetflix.entrypoints=websecure"
|
||||||
- "traefik.http.routers.magnetflix.tls.certresolver=letsencrypt"
|
- "traefik.http.routers.magnetflix.tls.certresolver=${TRAEFIK_CERTRESOLVER:-letsencrypt}"
|
||||||
- "traefik.http.routers.magnetflix.middlewares=authelia@docker"
|
- "traefik.http.routers.magnetflix.middlewares=${TRAEFIK_AUTH_MIDDLEWARE}"
|
||||||
- "traefik.http.services.magnetflix.loadbalancer.server.port=8000"
|
- "traefik.http.services.magnetflix.loadbalancer.server.port=8000"
|
||||||
|
|
||||||
# 2. gRPC Pipeline Worker & Mover
|
# 2. gRPC Pipeline Worker & Mover
|
||||||
@@ -40,6 +40,10 @@ services:
|
|||||||
context: .
|
context: .
|
||||||
dockerfile: services/worker/Dockerfile
|
dockerfile: services/worker/Dockerfile
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
user: "${PUID:-1000}:${PGID:-1000}"
|
||||||
|
depends_on:
|
||||||
|
transmission:
|
||||||
|
condition: service_healthy
|
||||||
environment:
|
environment:
|
||||||
- TRANSMISSION_HOST=transmission
|
- TRANSMISSION_HOST=transmission
|
||||||
- TRANSMISSION_PORT=9091
|
- TRANSMISSION_PORT=9091
|
||||||
@@ -48,8 +52,8 @@ services:
|
|||||||
- MEDIA_DIR=/media/movies
|
- MEDIA_DIR=/media/movies
|
||||||
- TMDB_API_KEY=${TMDB_API_KEY}
|
- TMDB_API_KEY=${TMDB_API_KEY}
|
||||||
volumes:
|
volumes:
|
||||||
- ./data:/data
|
- ${MAGNETFLIX_DATA_DIR:-./data}:/data
|
||||||
- /mnt/storage/media/movies:/media/movies
|
- ${MAGNETFLIX_MEDIA_DIR:-./media/movies}:/media/movies
|
||||||
networks:
|
networks:
|
||||||
- magnetflix_internal
|
- magnetflix_internal
|
||||||
|
|
||||||
@@ -58,39 +62,46 @@ services:
|
|||||||
image: lscr.io/linuxserver/transmission:latest
|
image: lscr.io/linuxserver/transmission:latest
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
- PUID=1000
|
- PUID=${PUID:-1000}
|
||||||
- PGID=1000
|
- PGID=${PGID:-1000}
|
||||||
- TZ=America/Chicago
|
- TZ=${TZ:-UTC}
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "curl -sf http://localhost:9091/transmission/rpc >/dev/null || [ $$? -eq 22 ]"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
volumes:
|
volumes:
|
||||||
- ./config/transmission:/config
|
- ${TRANSMISSION_CONFIG_DIR:-./config/transmission}:/config
|
||||||
- ./data/staging:/data/staging
|
- ${MAGNETFLIX_DATA_DIR:-./data}/staging:/data/staging
|
||||||
networks:
|
networks:
|
||||||
- magnetflix_internal
|
- magnetflix_internal
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
traefik_network:
|
proxy_network:
|
||||||
external: true
|
external: true
|
||||||
magnetflix_internal:
|
magnetflix_internal:
|
||||||
driver: bridge
|
driver: bridge
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> **Reverse Proxy Portability:** The Traefik labels above use environment variables (`MAGNETFLIX_HOST`, `TRAEFIK_AUTH_MIDDLEWARE`) so any deployment (homelab or VPS) can configure its own domain and SSO middleware without patching compose files. Users running Nginx or Caddy forward-auth can omit the `traefik.*` labels and expose `bff:8000` on `proxy_network`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🔐 Pluggable SSO / Reverse Proxy Identity Adapter (`DEC-8`)
|
## 🔐 Pluggable SSO / Reverse Proxy Identity Adapter (`DEC-8`)
|
||||||
|
|
||||||
MagNetFlix does not couple its internal application logic to any specific identity provider. Instead, the FastAPI BFF operates an **Identity Adapter** extracting authenticated identity from upstream gateway headers:
|
MagNetFlix does not couple its internal application logic to any specific identity provider or domain. Instead, the FastAPI BFF operates a fail-closed **Identity Adapter** extracting authenticated identity from upstream gateway headers:
|
||||||
|
|
||||||
| Environment Variable | Default | Purpose |
|
| Environment Variable | Default | Purpose |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| `AUTH_ENABLED` | `true` | If `false`, identity falls back to `local_user` for offline testing or standalone development. |
|
| `AUTH_ENABLED` | `true` | When `true`, requests missing a non-empty `AUTH_HEADER_USER` fail closed with `401 Unauthorized`. Set to `false` only for offline/local development (`local_user`). |
|
||||||
| `AUTH_HEADER_USER` | `Remote-User` | Name of the incoming HTTP header containing the verified username (e.g. Authelia, Authentik `X-authentik-username`, or OAuth2-Proxy `X-Forwarded-User`). |
|
| `AUTH_HEADER_USER` | `Remote-User` | Name of the incoming HTTP header containing the verified username (e.g., `Remote-User` for Authelia/Caddy, `X-authentik-username` for Authentik, or `X-Forwarded-User` for OAuth2-Proxy). |
|
||||||
| `AUTH_HEADER_EMAIL` | `Remote-Email` | Name of the HTTP header containing the user's verified email address. |
|
| `CORS_ALLOWED_ORIGINS` | `""` | Optional comma-separated origins permitted for browser extension requests across custom domains. |
|
||||||
|
|
||||||
### Upstream Authentication Workflow
|
### Upstream Authentication Workflow
|
||||||
1. Client sends request to `addmovie.roadtotech.me`.
|
1. Client (Web UI or browser extension) sends a request to the configured `${MAGNETFLIX_HOST}` endpoint.
|
||||||
2. Reverse proxy executes forward-auth against the identity provider (Authelia, Authentik, etc.).
|
2. Reverse proxy executes forward-auth or OIDC session validation against the chosen identity provider (OAuth2-Proxy, Authentik, Authelia, etc.).
|
||||||
3. If valid, the proxy injects the configured identity header (`Remote-User`) and forwards the request to the BFF on `traefik_network`.
|
3. If valid, the proxy injects the configured identity header (`AUTH_HEADER_USER`) and forwards the request to the BFF on `proxy_network`.
|
||||||
4. BFF extracts the verified identity and forwards it across the private gRPC boundary to the Worker for persistent audit logging.
|
4. BFF enforces `AUTH_ENABLED` (returning `401` if enabled and header is absent) and forwards the verified username across the private gRPC boundary to the Worker for persistent audit logging.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
+22
-20
@@ -27,13 +27,14 @@ flowchart TD
|
|||||||
- **Dependencies:** None.
|
- **Dependencies:** None.
|
||||||
- **Requirements Satisfied:** `REQ-1`, `REQ-2`.
|
- **Requirements Satisfied:** `REQ-1`, `REQ-2`.
|
||||||
- **Work Items:**
|
- **Work Items:**
|
||||||
- [ ] `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"`).
|
||||||
- [ ] `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`).
|
||||||
- [ ] `M1.3`: Update dependencies in `services/worker` and `services/bff` to include `magnetflix-contracts = { workspace = true }`.
|
- [x] `M1.3`: Update dependencies in `services/worker` and `services/bff` to include `magnetflix-contracts = { workspace = true }`.
|
||||||
- [ ] `M1.4`: Update `pyproject.toml` to include `tests/` in `pyright`, remove exclusions that masked broken imports, and add `test:` target to `Makefile`.
|
- [x] `M1.4`: Update `pyproject.toml` to include `tests/` in `pyright`, remove exclusions that masked broken imports, and add `test:` target to `Makefile`.
|
||||||
- [ ] `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.
|
||||||
- [ ] `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`).
|
||||||
- [ ] `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.
|
||||||
@@ -47,18 +48,19 @@ flowchart TD
|
|||||||
- **Requirements Satisfied:** `REQ-3`, `REQ-4`, `REQ-5`.
|
- **Requirements Satisfied:** `REQ-3`, `REQ-4`, `REQ-5`.
|
||||||
- **Work Items:**
|
- **Work Items:**
|
||||||
- [ ] `M2.1`: Implement Media Sanitizer (`services/worker/src/worker/sanitizer.py`) adhering to `DEC-3`:
|
- [ ] `M2.1`: Implement Media Sanitizer (`services/worker/src/worker/sanitizer.py`) adhering to `DEC-3`:
|
||||||
- Hard-fail on symlinks, hard links, `..` traversal, special files, and dangerous extensions (`.exe`, `.bat`, `.sh`, `.iso`, `.zip`).
|
- 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`).
|
||||||
- Safely ignore benign clutter (`.nfo`, `.txt`, `.jpg`, `.sfv`).
|
- Safely ignore unlisted non-dangerous files (such as `.nfo`, `.txt`, `.jpg`, `.sfv`).
|
||||||
- Discard samples (`< 100MB` or containing `sample`); select largest primary video and allowlisted subtitles (`.srt`, `.vtt`, `.ass`).
|
- Discard samples (`< 100 MB` or case-insensitive word-boundary `"sample"` token / `Sample` directory); select largest primary video and allowlisted subtitles (`.srt`, `.vtt`, `.sub`, `.ass`).
|
||||||
- [ ] `M2.2`: Write unit tests in `tests/test_sanitizer.py` verifying all security, allowlist, and sample discard rules.
|
- [ ] `M2.2`: Write unit tests in `tests/test_sanitizer.py` verifying all security, allowlist, and sample discard rules.
|
||||||
- [ ] `M2.3`: Implement TMDB Client & Token Verifier (`services/worker/src/worker/metadata.py`) adhering to `DEC-4`:
|
- [ ] `M2.3`: Implement TMDB Client & Token Verifier (`services/worker/src/worker/metadata.py`) adhering to `DEC-4`:
|
||||||
- Early resolution via `GET /find/{imdb_id}?external_source=imdb_id` using `httpx.AsyncClient`.
|
- Early resolution via `GET /find/{imdb_id}?external_source=imdb_id` using `httpx.AsyncClient` with bounded timeouts/retries.
|
||||||
- Validates IMDb ID format, validates movie entity type, extracts `(title, year)`.
|
- Validates IMDb ID format, validates movie entity type, extracts `(title, year)`.
|
||||||
- Post-download normalized token comparison between cached `(title, year)` and primary video filename.
|
- Post-download normalized token comparison between cached `(title, year)` and primary video filename.
|
||||||
- [ ] `M2.4`: Write unit tests in `tests/test_metadata.py` with mocked TMDB HTTP responses (match, 404, non-movie, mismatch).
|
- [ ] `M2.4`: Write unit tests in `tests/test_metadata.py` with mocked TMDB HTTP responses (match, 404, non-movie, mismatch).
|
||||||
- [ ] `M2.5`: Implement Library Relocator (`services/worker/src/worker/relocator.py`) adhering to `DEC-5`:
|
- [ ] `M2.5`: Implement Library Relocator (`services/worker/src/worker/relocator.py`) adhering to `DEC-5`:
|
||||||
- Multi-track subtitle format preservation (`.srt`, `.vtt`, `.ass`) with language and disambiguation tags.
|
- Deterministic `<Title>` path sanitization (stripping/replacing `/`, `\`, `:`, `*`, `?`, `"`, `<`, `>`, `|`, `..`).
|
||||||
- Two-stage copy-and-swap: copy to `/media/movies/.staging_<job_id>/`, pre-check destination directory existence, and atomically swap via `os.replace`.
|
- Multi-track subtitle format preservation (`.srt`, `.vtt`, `.sub`, `.ass`) with language/forced tags, untagged fallback (`<SanitizedTitle> (<Year>).<ext>`), and disambiguation indices.
|
||||||
|
- 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.6`: Write unit tests in `tests/test_relocator.py` asserting destination file layout and atomic swap error handling.
|
- [ ] `M2.6`: Write unit tests in `tests/test_relocator.py` asserting destination file layout and atomic swap error handling.
|
||||||
- **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 pytest tests/test_sanitizer.py tests/test_metadata.py tests/test_relocator.py` passes 100%.
|
||||||
@@ -77,13 +79,13 @@ flowchart TD
|
|||||||
- `remove_torrent(info_hash, delete_data=True)` for terminal cleanup.
|
- `remove_torrent(info_hash, delete_data=True)` for terminal cleanup.
|
||||||
- [ ] `M3.2`: Write unit tests in `tests/test_transmission.py` with mocked RPC client.
|
- [ ] `M3.2`: Write unit tests in `tests/test_transmission.py` with mocked RPC client.
|
||||||
- [ ] `M3.3`: Implement Pipeline Coordinator & State Machine (`services/worker/src/worker/pipeline.py`) adhering to `DEC-6` & `DEC-7`:
|
- [ ] `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`.
|
- State progression: `QUEUED` $\rightarrow$ `DOWNLOADING` $\rightarrow$ `SCANNING` $\rightarrow$ `VERIFYING_METADATA` $\rightarrow$ `ORGANIZING` $\rightarrow$ `COMPLETED` (with `FAILED` reachable from any active state).
|
||||||
- 15-minute stalled torrent timeout.
|
- 15-minute zero-progress-delta stalled torrent timeout.
|
||||||
- Startup crash recovery: query orphaned jobs, fail DB rows, purge staging directories, remove torrents from Transmission.
|
- Startup crash recovery: query non-terminal jobs, fail DB rows, purge staging directories, remove torrents from Transmission (with bounded startup retry/backoff).
|
||||||
- Dedicated bounded `ThreadPoolExecutor(max_workers=4)` for offloading disk I/O and synchronous Transmission calls.
|
- Dedicated bounded relocation executor isolated from lightweight `transmission-rpc` and scan offloading.
|
||||||
- In-memory `asyncio.Queue` broadcaster for real-time status streaming.
|
- 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`:
|
- [ ] `M3.4`: Implement gRPC Server Servicer (`services/worker/src/worker/service.py` & `main.py`) adhering to `pipeline.proto`:
|
||||||
- Implements `SubmitDownload`, `GetJob`, `ListJobs`, and `StreamJobStatus`.
|
- Implements `SubmitDownload`, `GetJob`, `ListJobs`, and `StreamJobStatus` plus gRPC health check.
|
||||||
- Maps application errors to proper gRPC status codes (`ALREADY_EXISTS`, `NOT_FOUND`, `INVALID_ARGUMENT`).
|
- 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`.
|
- [ ] `M3.5`: Write integration tests in `tests/test_pipeline.py` and `tests/test_grpc_service.py`.
|
||||||
- **Verifiable Exit Criteria:**
|
- **Verifiable Exit Criteria:**
|
||||||
@@ -98,7 +100,7 @@ flowchart TD
|
|||||||
- **Requirements Satisfied:** `REQ-9`, `REQ-10`.
|
- **Requirements Satisfied:** `REQ-9`, `REQ-10`.
|
||||||
- **Work Items:**
|
- **Work Items:**
|
||||||
- [ ] `M4.1`: Implement Pluggable Identity Adapter Middleware in FastAPI (`DEC-8`):
|
- [ ] `M4.1`: Implement Pluggable Identity Adapter Middleware in FastAPI (`DEC-8`):
|
||||||
- Configurable via `AUTH_ENABLED`, `AUTH_HEADER_USER`, `AUTH_HEADER_EMAIL`, with safe dev fallback (`local_user`).
|
- 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`: Implement BFF gRPC Client Wrapper (`services/bff/src/bff/grpc_client.py`):
|
- [ ] `M4.2`: Implement BFF gRPC Client Wrapper (`services/bff/src/bff/grpc_client.py`):
|
||||||
- Channels calls to Worker (`SubmitDownload`, `GetJob`, `ListJobs`, `StreamJobStatus`).
|
- Channels calls to Worker (`SubmitDownload`, `GetJob`, `ListJobs`, `StreamJobStatus`).
|
||||||
- [ ] `M4.3`: Implement REST Endpoints & Schemas (`services/bff/src/bff/main.py`):
|
- [ ] `M4.3`: Implement REST Endpoints & Schemas (`services/bff/src/bff/main.py`):
|
||||||
|
|||||||
+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,30 +1,31 @@
|
|||||||
# 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
|
||||||
|
(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
|
# 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
|
||||||
(B) Write comprehensive unit tests in tests/test_sanitizer.py covering allowlist, traversal, sample filtering, and largest video selection +test @worker
|
(B) Write comprehensive unit tests in tests/test_sanitizer.py covering allowlist, traversal, sample filtering, 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) 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) Write unit tests with mocked TMDB responses in tests/test_metadata.py verifying match, 404, non-movie rejection, and token overlap +test @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) Implement Multi-Track Library Relocator in services/worker/src/worker/relocator.py (format preservation for .srt/.vtt/.ass, language/disambiguation tagging, two-stage atomic directory swap) +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) Write unit tests in tests/test_relocator.py testing destination directory formatting, subtitle moving, and atomic swap cleanup +test @worker
|
(B) Write unit tests in tests/test_relocator.py testing destination directory formatting, subtitle moving, and atomic swap cleanup +test @worker
|
||||||
|
|
||||||
# Milestone 3: Transmission Integration & Worker Coordinator
|
# Milestone 3: Transmission Integration & Worker Coordinator
|
||||||
(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
|
(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
|
||||||
(C) Write unit tests with mocked transmission-rpc client in tests/test_transmission.py +test @worker
|
(C) Write unit tests with mocked transmission-rpc client in tests/test_transmission.py +test @worker
|
||||||
(C) Implement pipeline state machine coordinator in services/worker/src/worker/pipeline.py (linear transitions, 15-min stall timeout, bounded ThreadPoolExecutor offloading, in-memory pub/sub queues) +pipeline @worker
|
(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
|
||||||
(C) Implement startup active reconciliation sweep in pipeline.py (auto-fail orphaned jobs, remove Transmission torrents, purge staging disks) +pipeline @worker
|
(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
|
||||||
(C) Implement gRPC PipelineServiceServicer in services/worker/src/worker/service.py and entrypoint worker/main.py (SubmitDownload, GetJob, StreamJobStatus, ListJobs) +grpc @worker
|
(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
|
(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
|
# Milestone 4: FastAPI BFF Gateway, SSE & Web UI
|
||||||
(D) Implement Pluggable Identity Adapter Middleware in FastAPI BFF (env-driven header extraction with local_user dev fallback) +auth @bff
|
(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 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 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) Implement Server-Sent Events stream GET /api/v1/movies/events connected to gRPC StreamJobStatus +sse @bff
|
||||||
|
|||||||
Reference in new issue
Block a user