Compare commits
17
Commits
c3cc139216
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b32b4d09f1 | ||
|
|
b7aeee9fe8 | ||
|
|
e0d6cd7959 | ||
|
|
a3649c3ead | ||
|
|
c34512da6b | ||
|
|
a8288d34cb | ||
|
|
b479ed8ccc | ||
|
|
8b1e6b721c | ||
|
|
3d428dba48 | ||
|
|
083fe61549 | ||
|
|
f5e290fd96 | ||
|
|
9edc5e20cf | ||
|
|
9b16758eec | ||
|
|
a73fd2679d | ||
|
|
22d0952b3a | ||
|
|
4b4ba20ef8 | ||
|
|
38cd58a190 |
No files matched your search
+1
-4
@@ -15,9 +15,6 @@ dist/
|
||||
data/
|
||||
config/
|
||||
|
||||
# Generated docs and proto stubs in services (if re-generated on build)
|
||||
docs/api_spec.md
|
||||
# Local environment
|
||||
.envrc
|
||||
.direnv/
|
||||
services/bff/src/bff/magnetflix/v1/
|
||||
services/worker/src/worker/magnetflix/v1/
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## 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.
|
||||
- **Implementation autonomy ≠ Architectural autonomy.** Do not replace technologies, dependencies, or storage strategies without explicit approval.
|
||||
|
||||
@@ -15,14 +15,19 @@ 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.
|
||||
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.
|
||||
5. **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.
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## 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.
|
||||
- **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.
|
||||
- **No Speculative Robustness:** Do not add unrequested fallback layers, complex generic abstractions, or future-proofing bloat.
|
||||
|
||||
@@ -49,7 +54,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>`).
|
||||
- **File Whitelist Sanitization:**
|
||||
- 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.
|
||||
|
||||
---
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
- Read `docs/deployment.md` before changing Dockerfiles, Compose services, or Traefik/Authelia configs.
|
||||
|
||||
## Build & Tool Execution Commands
|
||||
- **Workspace Sync:** `uv sync` (Never use raw `pip`)
|
||||
- **Workspace Sync:** `uv sync --all-packages` (Never use raw `pip`)
|
||||
- **Workspace Lock:** `uv lock`
|
||||
- **Protobuf Generation:** `uv run buf generate` (or `make generate`)
|
||||
- **BFF Dev Server:** `uv run --package magnetflix-bff uvicorn bff.main:app --reload --port 8000`
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
.PHONY: generate test lint format check
|
||||
|
||||
generate:
|
||||
uv run buf generate
|
||||
@if command -v buf >/dev/null 2>&1; then \
|
||||
buf generate; \
|
||||
else \
|
||||
nix develop --command buf generate; \
|
||||
fi
|
||||
|
||||
test:
|
||||
uv run pytest
|
||||
|
||||
lint:
|
||||
uv run ruff check .
|
||||
|
||||
@@ -1,33 +1,40 @@
|
||||
# 🎬 MagNetFlix
|
||||
|
||||
> Automated, secure movie fetching and library organization pipeline via gRPC, Transmission, and Traefik/Authelia SSO.
|
||||
> Self-hosted, automated media acquisition and library organization pipeline built with **FastAPI (BFF)**, **gRPC**, **SQLite WAL**, **Transmission RPC**, and **pluggable SSO/OIDC authentication**.
|
||||
|
||||
---
|
||||
|
||||
## 📖 Table of Contents
|
||||
|
||||
- [Overview](docs/overview.md) - Project mission, key features, and user workflow.
|
||||
- [Architecture](docs/architecture.md) - System design, BFF pattern, gRPC contracts, and data flow.
|
||||
- [Development Rules & Agent Guidelines](AGENTS.md) - Coding standards, monorepo conventions, and toolchain rules.
|
||||
- [Roadmap](docs/roadmap.md) - Milestone-by-milestone development plan.
|
||||
- [Deployment Guide](docs/deployment.md) - Docker Compose, Traefik integration, and Authelia SSO setup.
|
||||
- [Overview](docs/overview.md) — Mission, user workflow, and features.
|
||||
- [Architecture](docs/architecture.md) — System design, state machine, security boundaries, and storage invariants.
|
||||
- [Reconciled Roadmap](docs/roadmap.md) — Dependency-ordered implementation milestones.
|
||||
- [Deployment Guide](docs/deployment.md) — Docker Compose topology, volume mounts, and SSO identity adapter.
|
||||
- [Architecture Decision Records](docs/adr/) — Canonical records of design choices, tradeoffs, and invariants:
|
||||
- [ADR 001: Pipeline Safety, Storage Boundaries, and BFF Dual-Client Architecture](docs/adr/001-pipeline-safety-and-bff-dual-client.md)
|
||||
- [ADR 002: Pipeline Invariants, Two-Stage Metadata, and Active Reconciliation](docs/adr/002-pipeline-invariants-and-active-reconciliation.md)
|
||||
- [Historical Audit Ledger](docs/history/phase-a-current-state-audit.md) — Phase A current-state audit and portfolio assessment.
|
||||
- [Development Rules & Agent Guidelines](AGENTS.md) — Code quality standards, safety rules, and workspace invariants.
|
||||
|
||||
---
|
||||
|
||||
## ⚡ Quick Start
|
||||
|
||||
```bash
|
||||
# Enter hermetic dev shell (Nix)
|
||||
# 1. Enter hermetic dev shell (Nix)
|
||||
nix develop
|
||||
|
||||
# Or install dependencies with uv workspace
|
||||
uv sync
|
||||
# 2. Or install dependencies for all workspace packages with uv
|
||||
uv sync --all-packages
|
||||
|
||||
# Generate protobuf stubs
|
||||
# 3. Generate protobuf stubs & documentation
|
||||
make generate
|
||||
|
||||
# Start full local stack with docker compose
|
||||
docker compose up -d
|
||||
# 4. Run test suite
|
||||
uv run pytest
|
||||
|
||||
# 5. Run static type checking and linters
|
||||
make check
|
||||
```
|
||||
|
||||
---
|
||||
@@ -36,28 +43,25 @@ docker compose up -d
|
||||
|
||||
```text
|
||||
.
|
||||
├── AGENTS.md # Development guidelines & rules for AI/human contributors
|
||||
├── Makefile # High-level build & generation commands
|
||||
├── AGENTS.md # Development guidelines & safety invariants
|
||||
├── CLAUDE.md # Developer CLI commands & tool directives
|
||||
├── Makefile # High-level build, codegen, lint, and test targets
|
||||
├── README.md # Project landing page
|
||||
├── buf.gen.yaml # Buf remote plugin generation config
|
||||
├── buf.yaml # Buf module definition
|
||||
├── docker-compose.yml # Local development & production compose stack
|
||||
├── docs/ # Detailed system documentation
|
||||
│ ├── architecture.md # Architecture & component interactions
|
||||
│ ├── deployment.md # Traefik & Authelia deployment guide
|
||||
├── buf.gen.yaml # Buf code generation configuration
|
||||
├── buf.yaml # Buf module configuration
|
||||
├── docs/ # Authoritative architecture and operations documentation
|
||||
│ ├── adr/ # Architecture Decision Records (ADRs)
|
||||
│ ├── history/ # Audit logs and review ledgers
|
||||
│ ├── architecture.md # System design, data flow, and invariants
|
||||
│ ├── deployment.md # Container topology and reverse proxy integration
|
||||
│ ├── overview.md # Feature overview & workflow
|
||||
│ └── roadmap.md # Development milestones
|
||||
│ └── roadmap.md # 5-Milestone implementation plan
|
||||
├── proto/ # Protocol Buffer definitions
|
||||
│ └── magnetflix/v1/
|
||||
│ └── pipeline.proto
|
||||
└── services/
|
||||
├── bff/ # FastAPI Web Gateway / HTML Form / Authelia SSO
|
||||
│ ├── Dockerfile
|
||||
│ ├── pyproject.toml
|
||||
│ └── src/bff/
|
||||
└── worker/ # gRPC Pipeline Worker & Transmission Coordinator
|
||||
├── Dockerfile
|
||||
├── alembic/
|
||||
├── pyproject.toml
|
||||
└── src/worker/
|
||||
├── services/
|
||||
│ ├── bff/ # FastAPI Web Gateway / HTML Form / Pluggable SSO
|
||||
│ ├── contracts/ # Shared Protobuf & gRPC contracts package
|
||||
│ └── worker/ # gRPC Pipeline Worker & Transmission Coordinator
|
||||
└── tests/ # Unit and integration test suites
|
||||
```
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts.
|
||||
# this is typically a path given in POSIX (e.g. forward slashes)
|
||||
# format, relative to the token %(here)s which refers to the location of this
|
||||
# ini file
|
||||
script_location = %(here)s/services/worker/alembic
|
||||
|
||||
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||
# Uncomment the line below if you want the files to be prepended with date and time
|
||||
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||
# for all available tokens
|
||||
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
|
||||
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
|
||||
|
||||
# sys.path path, will be prepended to sys.path if present.
|
||||
# defaults to the current working directory. for multiple paths, the path separator
|
||||
# is defined by "path_separator" below.
|
||||
prepend_sys_path = .
|
||||
|
||||
# timezone to use when rendering the date within the migration file
|
||||
# as well as the filename.
|
||||
# If specified, requires the tzdata library which can be installed by adding
|
||||
# `alembic[tz]` to the pip requirements.
|
||||
# string value is passed to ZoneInfo()
|
||||
# leave blank for localtime
|
||||
# timezone =
|
||||
|
||||
# max length of characters to apply to the "slug" field
|
||||
# truncate_slug_length = 40
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
# set to 'true' to allow .pyc and .pyo files without
|
||||
# a source .py file to be detected as revisions in the
|
||||
# versions/ directory
|
||||
# sourceless = false
|
||||
|
||||
# version location specification; This defaults
|
||||
# to <script_location>/versions. When using multiple version
|
||||
# directories, initial revisions must be specified with --version-path.
|
||||
# The path separator used here should be the separator specified by "path_separator"
|
||||
# below.
|
||||
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
|
||||
|
||||
# path_separator; This indicates what character is used to split lists of file
|
||||
# paths, including version_locations and prepend_sys_path within configparser
|
||||
# files such as alembic.ini.
|
||||
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
|
||||
# to provide os-dependent path splitting.
|
||||
#
|
||||
# Note that in order to support legacy alembic.ini files, this default does NOT
|
||||
# take place if path_separator is not present in alembic.ini. If this
|
||||
# option is omitted entirely, fallback logic is as follows:
|
||||
#
|
||||
# 1. Parsing of the version_locations option falls back to using the legacy
|
||||
# "version_path_separator" key, which if absent then falls back to the legacy
|
||||
# behavior of splitting on spaces and/or commas.
|
||||
# 2. Parsing of the prepend_sys_path option falls back to the legacy
|
||||
# behavior of splitting on spaces, commas, or colons.
|
||||
#
|
||||
# Valid values for path_separator are:
|
||||
#
|
||||
# path_separator = :
|
||||
# path_separator = ;
|
||||
# path_separator = space
|
||||
# path_separator = newline
|
||||
#
|
||||
# Use os.pathsep. Default configuration used for new projects.
|
||||
path_separator = os
|
||||
|
||||
|
||||
# set to 'true' to search source files recursively
|
||||
# in each "version_locations" directory
|
||||
# new in Alembic version 1.10
|
||||
# recursive_version_locations = false
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
# database URL. This is consumed by the user-maintained env.py script only.
|
||||
# other means of configuring database URLs may be customized within the env.py
|
||||
sqlalchemy.url = sqlite+aiosqlite:///data/magnetflix.sqlite3
|
||||
|
||||
|
||||
[post_write_hooks]
|
||||
# post_write_hooks defines scripts or Python functions that are run
|
||||
# on newly generated revision scripts. See the documentation for further
|
||||
# detail and examples
|
||||
|
||||
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||
# hooks = black
|
||||
# black.type = console_scripts
|
||||
# black.entrypoint = black
|
||||
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||
|
||||
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
|
||||
# hooks = ruff
|
||||
# ruff.type = module
|
||||
# ruff.module = ruff
|
||||
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Alternatively, use the exec runner to execute a binary found on your PATH
|
||||
# hooks = ruff
|
||||
# ruff.type = exec
|
||||
# ruff.executable = ruff
|
||||
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Logging configuration. This is also consumed by the user-maintained
|
||||
# env.py script only.
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARNING
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARNING
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
+4
-12
@@ -3,21 +3,13 @@ inputs:
|
||||
- directory: proto
|
||||
plugins:
|
||||
- remote: buf.build/protocolbuffers/python
|
||||
out: services/worker/src/worker
|
||||
out: services/contracts/src
|
||||
- remote: buf.build/grpc/python
|
||||
out: services/worker/src/worker
|
||||
out: services/contracts/src
|
||||
- remote: buf.build/community/nipunn1313-mypy
|
||||
out: services/worker/src/worker
|
||||
out: services/contracts/src
|
||||
- remote: buf.build/community/nipunn1313-mypy-grpc
|
||||
out: services/worker/src/worker
|
||||
- remote: buf.build/protocolbuffers/python
|
||||
out: services/bff/src/bff
|
||||
- remote: buf.build/grpc/python
|
||||
out: services/bff/src/bff
|
||||
- remote: buf.build/community/nipunn1313-mypy
|
||||
out: services/bff/src/bff
|
||||
- remote: buf.build/community/nipunn1313-mypy-grpc
|
||||
out: services/bff/src/bff
|
||||
out: services/contracts/src
|
||||
- remote: buf.build/community/pseudomuto-doc
|
||||
out: docs
|
||||
opt:
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
---
|
||||
type: decision
|
||||
status: accepted
|
||||
project: MagNetFlix
|
||||
date: 2026-10-13
|
||||
tags: [architecture, security, storage, bff, grpc, api, webextension]
|
||||
---
|
||||
|
||||
# ADR 001: Pipeline Safety, Storage Boundaries, and BFF Dual-Client Architecture
|
||||
|
||||
## Context and Problem Statement
|
||||
|
||||
MagNetFlix automates media acquisition from user submission to structured library organization for Jellyfin and Plex. During architectural audit and alignment with an existing browser extension proof-of-concept (`magnetflix-extension`), several critical design questions and operational hazards were identified:
|
||||
|
||||
1. **Client & API Alignment**: How should public users interact with the system? Should the web portal and browser extension require separate backends or conflicting API contracts?
|
||||
2. **Security & Ingress Boundary**: How can torrent downloading be offered to authenticated home users without exposing the underlying Transmission daemon or internal disk structures to the public network?
|
||||
3. **Cross-Volume Storage Integrity**: Downloads occur on fast scratch disks (`/data/staging`), while final libraries live on large storage pools (`/media/movies`). Moving files across filesystem boundaries cannot be done via atomic filesystem links (`EXDEV`). How do we prevent media servers from indexing 30GB media files while they are still being copied?
|
||||
4. **Metadata Authority**: Should metadata matching rely on web scraping (IMDb HTML scraping) or structured API integration (TMDB)?
|
||||
5. **Daemon Lifecycle & Path Alignment**: How do we prevent container volume path translation errors and eliminate ghost torrent sessions in Transmission daemon state?
|
||||
|
||||
## Decision Drivers
|
||||
|
||||
* **Minimal Attack Surface**: Zero public exposure of torrent engines, RPC ports, or staging filesystems.
|
||||
* **Ingestion Atomicity**: Guarantee that Jellyfin/Plex will never detect, lock, or play a partially transferred file.
|
||||
* **Deterministic Metadata Verification**: Authoritative title/year verification without fragility to HTML changes or IP rate-limiting.
|
||||
* **Client Versatility with Zero Divergence**: Unified support for both a self-hosted Web UI and a companion browser WebExtension without managing divergent APIs or CORS holes.
|
||||
* **Resource Hygiene**: Guaranteed reclamation of disk space and torrent session memory on terminal success or failure.
|
||||
|
||||
## Considered Options
|
||||
|
||||
* **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 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 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.
|
||||
* Filesystem operations enforce a two-stage copy-and-swap on the target volume.
|
||||
|
||||
## Decision Outcome
|
||||
|
||||
Chosen option: **Option 3**, because it provides complete physical separation between the public ingress tier and the torrent/filesystem execution tier while supporting both the browser extension and the web UI through a single API surface.
|
||||
|
||||
---
|
||||
|
||||
### Summary of Architectural Commitments
|
||||
|
||||
#### 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 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`), 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:
|
||||
* 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`.
|
||||
* 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)
|
||||
* Transmission daemon and gRPC Worker run strictly on a private, internal Docker bridge (`magnetflix_internal`).
|
||||
* Neither Transmission's web interface nor its RPC port (9091) is exposed to the host or internet.
|
||||
* Transmission is controllable exclusively through the Worker's `transmission-rpc` client wrapper.
|
||||
|
||||
#### 3. Storage Boundary: Two-Stage Atomic Relocation
|
||||
* Because scratch staging (`/data/staging`) and destination libraries (`/media/movies`) reside on separate storage mounts, file moves across devices require a copy-and-delete.
|
||||
* To prevent media servers from indexing in-flight transfers:
|
||||
1. **Transfer Stage**: Media and subtitle files are copied from `/data/staging/<job_id>/` to `/media/movies/.staging_<job_id>/` using Python's `shutil.copy2`.
|
||||
2. **Atomic Swap Stage**: Once copying is complete and size is verified, `os.replace` atomically renames `/media/movies/.staging_<job_id>/` to the canonical destination directory `/media/movies/<Title> (<Year>) [imdbid-<IMDbID>]/`.
|
||||
* Because the staging folder and final directory reside on the **same target filesystem**, `os.replace` is an instant, atomic metadata pointer update.
|
||||
|
||||
#### 4. Container Path Alignment
|
||||
* Transmission and Worker mount the staging directory to the identical absolute path (`/data/staging`). This eliminates container path translation logic when dispatching RPC download commands.
|
||||
|
||||
#### 5. Authoritative Metadata Verification via TMDB API
|
||||
* Media verification uses the official **The Movie Database (TMDB) API** (`/find/{imdb_id}?external_source=imdb_id`) via `httpx`.
|
||||
* Scraping libraries (Cinemagoer) are rejected to eliminate fragile HTML parsing and IP blocking.
|
||||
* Verified movie titles and release years must have positive normalized token overlap with the torrent payload name before organizing; zero overlap aborts the job to `FAILED`.
|
||||
|
||||
#### 6. Lifecycle Cleanup & Timeout Guarantees
|
||||
* When a job reaches a terminal state (`COMPLETED` or `FAILED`):
|
||||
* The scratch directory `/data/staging/<job_id>/` is purged immediately.
|
||||
* The torrent session is removed from Transmission daemon via RPC `remove_torrent(id, delete_data=True)` to prevent memory leaks and tracker retention.
|
||||
* If a torrent makes zero progress (0 bytes downloaded or unretrieved magnet metadata) for 15 consecutive minutes, the job transitions to `FAILED` with reason `"Download stalled: no seeds or metadata timeout"`.
|
||||
|
||||
---
|
||||
|
||||
## Pros and Cons of the Options
|
||||
|
||||
### Option 1: Direct Exposed Torrent Client with Script Hooks
|
||||
* Good, because minimal initial code is needed.
|
||||
* Bad, because exposes Transmission's attack surface to the internet; error handling in post-processing bash scripts is brittle and lacks transaction safety or audit logs.
|
||||
|
||||
### Option 2: Monolithic FastAPI Application
|
||||
* Good, because single process to deploy.
|
||||
* Bad, because CPU/disk I/O from torrent piece verification blocks Python async event loops; web vulnerabilities directly expose filesystem permissions; crashing the API kills ongoing torrent swarms.
|
||||
|
||||
### Option 3: Decoupled BFF + Private Worker + Two-Stage Relocation (Adopted)
|
||||
* Good, because complete isolation of untrusted network traffic from disk-writing engines; unified API serves both web UI and extension; atomic move eliminates race conditions with Jellyfin/Plex.
|
||||
* Bad, because cross-volume copying temporarily doubles disk usage during the `ORGANIZING` phase; requires an external TMDB API key.
|
||||
|
||||
---
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive Consequences
|
||||
* Media library scanners (Jellyfin/Plex) never lock or ingest corrupted, partially written files.
|
||||
* Single-origin web UI eliminates CORS configuration for standard users, while Pydantic aliases maintain 100% backward compatibility with the browser extension.
|
||||
* Transmission daemon is entirely insulated from public network access.
|
||||
* Staging directories and Transmission sessions are cleanly reclaimed on both success and failure.
|
||||
|
||||
### Negative Consequences & Accepted Trade-offs
|
||||
* Requires storage capacity on `/media/movies` to accommodate temporary copy staging (`.staging_<job_id>`) for the largest single feature film before atomic swap.
|
||||
* Worker requires outbound internet access to query TMDB API over HTTPS.
|
||||
|
||||
---
|
||||
|
||||
## More Information
|
||||
|
||||
* **Canonical Architecture**: [`docs/architecture.md`](../architecture.md)
|
||||
* **Deployment & Networking Spec**: [`docs/deployment.md`](../deployment.md)
|
||||
* **Browser Extension Reference**: Companion extension proof-of-concept located at `magnetflix-extension`.
|
||||
@@ -0,0 +1,88 @@
|
||||
---
|
||||
type: decision
|
||||
status: accepted
|
||||
project: MagNetFlix
|
||||
date: 2026-10-29
|
||||
tags: [architecture, security, storage, metadata, recovery, concurrency, sso, bff]
|
||||
---
|
||||
|
||||
# ADR 002: Pipeline Invariants, Two-Stage Metadata, and Active Reconciliation
|
||||
|
||||
## Context and Problem Statement
|
||||
|
||||
Following the initial architectural baseline established in [ADR 001](001-pipeline-safety-and-bff-dual-client.md) and the implementation of the SQLite WAL engine, an interactive architectural review identified critical engineering gaps across several core subsystems:
|
||||
|
||||
1. **Protobuf Packaging & Build Reproducibility (`GAP-1`)**: The stubs emitted by `buf` produced `ModuleNotFoundError: No module named 'magnetflix'` when imported due to nested package output paths, and generated stubs were excluded from git and static type checks.
|
||||
2. **Active-Job Concurrency (`GAP-2`)**: Concurrent submissions for the same movie could race past application-level checks and insert duplicate active downloads due to the absence of a database-level uniqueness constraint.
|
||||
3. **Sanitizer Boundary Policy (`GAP-3`)**: A documented contradiction existed between *purging* non-media files versus *aborting* the entire job if non-allowlisted files exist. Because ~95% of real-world torrents contain `.nfo` or `.txt` clutter, strict rejection causes widespread false-positive failures, while pure whitelisting ignores symlink/executable hazards.
|
||||
4. **Metadata Resolution Timing (`GAP-5`)**: Fetching TMDB metadata only after download completion leaves the UI live dashboard blank during 30–60 minute downloads and wastes tens of gigabytes of bandwidth on invalid IMDb IDs.
|
||||
5. **Subtitle Relocation Collisions (`GAP-4`)**: Hardcoding target subtitles to `<Title> (<Year>).en.srt` corrupts non-SRT formats (`.ass`, `.vtt`) and causes silent overwrite collisions when multiple tracks exist.
|
||||
6. **Crash Recovery & Daemon State (`GAP-6`)**: Simply marking SQLite rows as `FAILED` on worker restart leaves orphaned torrent sessions actively downloading in the Transmission container and abandons scratch disks.
|
||||
7. **Async Concurrency & Blocking I/O (`GAP-7`)**: Calling multi-gigabyte `shutil.copy2` transfers or synchronous `transmission-rpc` requests directly on Python's async event loop freezes gRPC RPCs and SSE streaming connections.
|
||||
8. **Pluggable SSO & Search Boundaries (`GAP-8`)**: Hardcoding Authelia headers tightly coupled MagNetFlix to specific homelab infrastructure, and client-side scraping of undocumented IMDb endpoints created browser CORS and fragility risks.
|
||||
|
||||
---
|
||||
|
||||
## Decision Outcome & Invariants
|
||||
|
||||
### 1. Dedicated Workspace Contracts Package (`DEC-1`)
|
||||
- Stubs are generated once into a shared workspace package `services/contracts` (`module-name = "magnetflix"`).
|
||||
- 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.
|
||||
|
||||
### 2. Database Partial Unique Indexes & Normalized Info-Hash (`DEC-2`)
|
||||
- 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 partial unique indexes in SQLite:
|
||||
```sql
|
||||
CREATE UNIQUE INDEX uq_download_jobs_active_imdb_id
|
||||
ON download_jobs (imdb_id)
|
||||
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 (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`)
|
||||
- **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 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`)
|
||||
- **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.
|
||||
|
||||
### 5. Multi-Track Subtitle Preservation, Path Sanitization & Two-Stage Atomic Swap (`DEC-5`)
|
||||
- Deterministically sanitize `<Title>` (stripping/replacing path-breaking characters such as `/`, `\`, `:`, `*`, `?`, `"`, `<`, `>`, `|`, and `..`) before constructing directory and file paths.
|
||||
- Retain native allowlisted subtitle extensions (`.srt`, `.vtt`, `.sub`, `.ass`).
|
||||
- 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`)
|
||||
- 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 zero progress delta (unchanged downloaded bytes/progress or unresolved metadata) for 15 consecutive minutes.
|
||||
|
||||
### 7. Thread Offloading & In-Memory SSE Fan-Out (`DEC-7`)
|
||||
- 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).
|
||||
- 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`)
|
||||
- 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, 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`).
|
||||
|
||||
---
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive Consequences
|
||||
- Guarantees 100% reproducible builds and eliminates `ModuleNotFoundError` across all environments.
|
||||
- Protects the host and media library from malicious torrent payloads, path traversal, and partial writes.
|
||||
- Eliminates zombie torrents and leaked staging disk space across container restarts.
|
||||
- Maintains responsive gRPC and SSE streaming performance during multi-gigabyte disk transfers.
|
||||
- Decouples MagNetFlix from specific reverse proxy or identity provider implementations.
|
||||
|
||||
### Accepted Tradeoffs & Operational Costs
|
||||
- Requires outbound TMDB API key access on both BFF (for movie search) and Worker (for metadata resolution).
|
||||
- Requires temporary disk space on `/media/movies` to hold `.staging_<job_id>/` during cross-volume copying.
|
||||
@@ -0,0 +1,243 @@
|
||||
# Protocol Documentation
|
||||
<a name="top"></a>
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [magnetflix/v1/pipeline.proto](#magnetflix_v1_pipeline-proto)
|
||||
- [GetJobRequest](#magnetflix-v1-GetJobRequest)
|
||||
- [GetJobResponse](#magnetflix-v1-GetJobResponse)
|
||||
- [JobStatus](#magnetflix-v1-JobStatus)
|
||||
- [ListJobsRequest](#magnetflix-v1-ListJobsRequest)
|
||||
- [ListJobsResponse](#magnetflix-v1-ListJobsResponse)
|
||||
- [StreamJobStatusRequest](#magnetflix-v1-StreamJobStatusRequest)
|
||||
- [StreamJobStatusResponse](#magnetflix-v1-StreamJobStatusResponse)
|
||||
- [SubmitDownloadRequest](#magnetflix-v1-SubmitDownloadRequest)
|
||||
- [SubmitDownloadResponse](#magnetflix-v1-SubmitDownloadResponse)
|
||||
|
||||
- [JobState](#magnetflix-v1-JobState)
|
||||
|
||||
- [PipelineService](#magnetflix-v1-PipelineService)
|
||||
|
||||
- [Scalar Value Types](#scalar-value-types)
|
||||
|
||||
|
||||
|
||||
<a name="magnetflix_v1_pipeline-proto"></a>
|
||||
<p align="right"><a href="#top">Top</a></p>
|
||||
|
||||
## magnetflix/v1/pipeline.proto
|
||||
|
||||
|
||||
|
||||
<a name="magnetflix-v1-GetJobRequest"></a>
|
||||
|
||||
### GetJobRequest
|
||||
Request to fetch a specific job by ID.
|
||||
|
||||
|
||||
| Field | Type | Label | Description |
|
||||
| ----- | ---- | ----- | ----------- |
|
||||
| job_id | [string](#string) | | Unique job identifier. |
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<a name="magnetflix-v1-GetJobResponse"></a>
|
||||
|
||||
### GetJobResponse
|
||||
Response containing the status of the requested job.
|
||||
|
||||
|
||||
| Field | Type | Label | Description |
|
||||
| ----- | ---- | ----- | ----------- |
|
||||
| job | [JobStatus](#magnetflix-v1-JobStatus) | | The retrieved job details. |
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<a name="magnetflix-v1-JobStatus"></a>
|
||||
|
||||
### JobStatus
|
||||
Full status information for a download job.
|
||||
|
||||
|
||||
| Field | Type | Label | Description |
|
||||
| ----- | ---- | ----- | ----------- |
|
||||
| job_id | [string](#string) | | Unique job ID. |
|
||||
| imdb_id | [string](#string) | | IMDb ID. |
|
||||
| title | [string](#string) | | Resolved movie title from TMDB (if available). |
|
||||
| year | [int32](#int32) | | Resolved release year from TMDB (if available). |
|
||||
| requested_by | [string](#string) | | User who requested the download. |
|
||||
| state | [JobState](#magnetflix-v1-JobState) | | Current state in the pipeline. |
|
||||
| progress_pct | [float](#float) | | Download progress percentage (0.0 to 100.0). |
|
||||
| download_rate_bytes | [int64](#int64) | | Download speed in bytes per second. |
|
||||
| error_message | [string](#string) | | Detailed error message if the job failed. |
|
||||
| created_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | Timestamp when the job was enqueued. |
|
||||
| updated_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | Timestamp when the job status or progress was last updated. |
|
||||
| completed_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | Timestamp when terminal processing finished (COMPLETED or FAILED). |
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<a name="magnetflix-v1-ListJobsRequest"></a>
|
||||
|
||||
### ListJobsRequest
|
||||
Request to list jobs with pagination and state filtering.
|
||||
|
||||
|
||||
| Field | Type | Label | Description |
|
||||
| ----- | ---- | ----- | ----------- |
|
||||
| page_size | [int32](#int32) | | Maximum number of jobs to return per page (default: 20, max: 100). |
|
||||
| page_token | [string](#string) | | Page token received from a previous ListJobsResponse next_page_token. |
|
||||
| state_filter | [JobState](#magnetflix-v1-JobState) | | Optional filter by job state. |
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<a name="magnetflix-v1-ListJobsResponse"></a>
|
||||
|
||||
### ListJobsResponse
|
||||
Paginated response containing a list of download jobs.
|
||||
|
||||
|
||||
| Field | Type | Label | Description |
|
||||
| ----- | ---- | ----- | ----------- |
|
||||
| jobs | [JobStatus](#magnetflix-v1-JobStatus) | repeated | List of matching jobs for the current page. |
|
||||
| next_page_token | [string](#string) | | Token to retrieve the next page of results, or empty if no more results. |
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<a name="magnetflix-v1-StreamJobStatusRequest"></a>
|
||||
|
||||
### StreamJobStatusRequest
|
||||
Request to stream job updates.
|
||||
|
||||
|
||||
| Field | Type | Label | Description |
|
||||
| ----- | ---- | ----- | ----------- |
|
||||
| job_id | [string](#string) | | Optional job ID to filter updates for a single job; if empty, streams all active jobs. |
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<a name="magnetflix-v1-StreamJobStatusResponse"></a>
|
||||
|
||||
### StreamJobStatusResponse
|
||||
Real-time job status event stream frame.
|
||||
|
||||
|
||||
| Field | Type | Label | Description |
|
||||
| ----- | ---- | ----- | ----------- |
|
||||
| job | [JobStatus](#magnetflix-v1-JobStatus) | | Current job status update. |
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<a name="magnetflix-v1-SubmitDownloadRequest"></a>
|
||||
|
||||
### SubmitDownloadRequest
|
||||
Request to submit a new movie download.
|
||||
|
||||
|
||||
| Field | Type | Label | Description |
|
||||
| ----- | ---- | ----- | ----------- |
|
||||
| magnet_uri | [string](#string) | | Magnet URI of the torrent to fetch. |
|
||||
| imdb_id | [string](#string) | | IMDb ID of the movie (e.g., "tt1375666"). |
|
||||
| requested_by | [string](#string) | | Username of the user requesting the download (from upstream SSO identity header). |
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<a name="magnetflix-v1-SubmitDownloadResponse"></a>
|
||||
|
||||
### SubmitDownloadResponse
|
||||
Response acknowledging the job submission.
|
||||
|
||||
|
||||
| Field | Type | Label | Description |
|
||||
| ----- | ---- | ----- | ----------- |
|
||||
| job_id | [string](#string) | | Unique identifier for the created job. |
|
||||
| message | [string](#string) | | Human-readable message. |
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<a name="magnetflix-v1-JobState"></a>
|
||||
|
||||
### JobState
|
||||
State enumeration of a download job lifecycle.
|
||||
|
||||
| Name | Number | Description |
|
||||
| ---- | ------ | ----------- |
|
||||
| JOB_STATE_UNSPECIFIED | 0 | |
|
||||
| JOB_STATE_QUEUED | 1 | |
|
||||
| JOB_STATE_DOWNLOADING | 2 | |
|
||||
| JOB_STATE_SCANNING | 3 | |
|
||||
| JOB_STATE_VERIFYING_METADATA | 4 | |
|
||||
| JOB_STATE_ORGANIZING | 5 | |
|
||||
| JOB_STATE_COMPLETED | 6 | |
|
||||
| JOB_STATE_FAILED | 7 | |
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<a name="magnetflix-v1-PipelineService"></a>
|
||||
|
||||
### PipelineService
|
||||
PipelineService coordinates movie download jobs, safety scans, and library relocation.
|
||||
|
||||
| Method Name | Request Type | Response Type | Description |
|
||||
| ----------- | ------------ | ------------- | ------------|
|
||||
| SubmitDownload | [SubmitDownloadRequest](#magnetflix-v1-SubmitDownloadRequest) | [SubmitDownloadResponse](#magnetflix-v1-SubmitDownloadResponse) | SubmitDownload enqueues a new movie download job. Rejects duplicate submissions if an active job for the same IMDb ID or info_hash exists, or if already in library. |
|
||||
| GetJob | [GetJobRequest](#magnetflix-v1-GetJobRequest) | [GetJobResponse](#magnetflix-v1-GetJobResponse) | GetJob retrieves the current status and metadata of a specific job. |
|
||||
| StreamJobStatus | [StreamJobStatusRequest](#magnetflix-v1-StreamJobStatusRequest) | [StreamJobStatusResponse](#magnetflix-v1-StreamJobStatusResponse) stream | StreamJobStatus streams real-time status updates. Semantics: Emits an immediate snapshot of matching active jobs upon connection, followed by subsequent state and progress change events. |
|
||||
| ListJobs | [ListJobsRequest](#magnetflix-v1-ListJobsRequest) | [ListJobsResponse](#magnetflix-v1-ListJobsResponse) | ListJobs returns a paginated list of download jobs. |
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## Scalar Value Types
|
||||
|
||||
| .proto Type | Notes | C++ | Java | Python | Go | C# | PHP | Ruby |
|
||||
| ----------- | ----- | --- | ---- | ------ | -- | -- | --- | ---- |
|
||||
| <a name="double" /> double | | double | double | float | float64 | double | float | Float |
|
||||
| <a name="float" /> float | | float | float | float | float32 | float | float | Float |
|
||||
| <a name="int32" /> int32 | Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead. | int32 | int | int | int32 | int | integer | Bignum or Fixnum (as required) |
|
||||
| <a name="int64" /> int64 | Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead. | int64 | long | int/long | int64 | long | integer/string | Bignum |
|
||||
| <a name="uint32" /> uint32 | Uses variable-length encoding. | uint32 | int | int/long | uint32 | uint | integer | Bignum or Fixnum (as required) |
|
||||
| <a name="uint64" /> uint64 | Uses variable-length encoding. | uint64 | long | int/long | uint64 | ulong | integer/string | Bignum or Fixnum (as required) |
|
||||
| <a name="sint32" /> sint32 | Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s. | int32 | int | int | int32 | int | integer | Bignum or Fixnum (as required) |
|
||||
| <a name="sint64" /> sint64 | Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s. | int64 | long | int/long | int64 | long | integer/string | Bignum |
|
||||
| <a name="fixed32" /> fixed32 | Always four bytes. More efficient than uint32 if values are often greater than 2^28. | uint32 | int | int | uint32 | uint | integer | Bignum or Fixnum (as required) |
|
||||
| <a name="fixed64" /> fixed64 | Always eight bytes. More efficient than uint64 if values are often greater than 2^56. | uint64 | long | int/long | uint64 | ulong | integer/string | Bignum |
|
||||
| <a name="sfixed32" /> sfixed32 | Always four bytes. | int32 | int | int | int32 | int | integer | Bignum or Fixnum (as required) |
|
||||
| <a name="sfixed64" /> sfixed64 | Always eight bytes. | int64 | long | int/long | int64 | long | integer/string | Bignum |
|
||||
| <a name="bool" /> bool | | bool | boolean | boolean | bool | bool | boolean | TrueClass/FalseClass |
|
||||
| <a name="string" /> string | A string must always contain UTF-8 encoded or 7-bit ASCII text. | string | String | str/unicode | string | string | string | String (UTF-8) |
|
||||
| <a name="bytes" /> bytes | May contain any arbitrary sequence of bytes. | string | ByteString | str | []byte | ByteString | string | String (ASCII-8BIT) |
|
||||
|
||||
+124
-70
@@ -1,123 +1,177 @@
|
||||
# 🏛️ MagNetFlix — Architecture & System Design
|
||||
# MagNetFlix — System Architecture & Component Design
|
||||
|
||||
MagNetFlix uses a **Backend-For-Frontend (BFF)** pattern paired with an internal **gRPC Worker** pipeline service to decouple public web endpoints from disk I/O 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
|
||||
flowchart TB
|
||||
subgraph Edge ["🌐 Public Edge (Protected)"]
|
||||
Browser["User Browser"] -->|HTTPS| Traefik["Traefik Reverse Proxy"]
|
||||
Traefik <-->|Forward Auth| Authelia["Authelia SSO"]
|
||||
subgraph Edge ["Public Edge (Protected Gateway)"]
|
||||
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
|
||||
Proxy <-->|Forward-Auth / OIDC Proxy| SSO["Identity Provider / SSO\n(OAuth2-Proxy / Authentik / Authelia)"]
|
||||
end
|
||||
|
||||
subgraph InternalServices ["🛡️ Internal Services (Docker Network)"]
|
||||
Traefik -->|HTTP + Remote-User| BFF["FastAPI BFF Gateway"]
|
||||
|
||||
subgraph WorkerApp ["Worker Service"]
|
||||
BFF -->|gRPC / Stream| Worker["gRPC Pipeline Server"]
|
||||
Worker --> DB[("SQLite 3 (WAL Mode)\nAudit & State Store")]
|
||||
Worker --> Sanitizer["Media Sanitizer & Allowlist"]
|
||||
Worker --> MetaService["TMDB Metadata Client"]
|
||||
Worker --> StorageMgr["Library Relocator & Renamer"]
|
||||
subgraph InternalServices ["Internal Service Tier (Docker Bridge)"]
|
||||
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"]
|
||||
BFF -->|gRPC / Status Stream| Worker["gRPC Pipeline Worker"]
|
||||
Worker --> DB[("SQLite 3 (WAL Mode)\n/data/magnetflix.sqlite3")]
|
||||
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 --> StorageMgr["Library Relocator & Renamer\n(Two-Stage Atomic Relocation)"]
|
||||
end
|
||||
|
||||
Worker --> Torrent["Transmission Daemon"]
|
||||
Worker -->|Transmission RPC| Torrent["Transmission Daemon"]
|
||||
end
|
||||
|
||||
subgraph Volumes ["💾 Storage Mounts"]
|
||||
subgraph Volumes ["Storage Mounts"]
|
||||
Torrent --> StagingDir[("/data/staging/<job_id> (Scratch Disk)")]
|
||||
StorageMgr --> FinalMedia[("/media/movies (Jellyfin/Plex Library)")]
|
||||
end
|
||||
```
|
||||
|
||||
### Canonical References
|
||||
- **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)
|
||||
- **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 Rules
|
||||
## 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
|
||||
stateDiagram-v2
|
||||
[*] --> QUEUED: SubmitDownload()
|
||||
QUEUED --> DOWNLOADING: Transmission starts torrent
|
||||
QUEUED --> FAILED: Startup crash recovery / pre-download abort
|
||||
DOWNLOADING --> SCANNING: Torrent reaches 100%
|
||||
DOWNLOADING --> FAILED: Torrent error / stalled timeout
|
||||
|
||||
SCANNING --> VERIFYING_METADATA: Sanitizer validates payload
|
||||
SCANNING --> FAILED: Disallowed files / no valid video
|
||||
|
||||
VERIFYING_METADATA --> ORGANIZING: TMDB match verified
|
||||
VERIFYING_METADATA --> FAILED: Title/year mismatch or lookup failed
|
||||
|
||||
ORGANIZING --> COMPLETED: Files relocated & renamed
|
||||
ORGANIZING --> FAILED: Disk full / permission error
|
||||
|
||||
DOWNLOADING --> FAILED: Torrent error / 15-min zero-delta stall
|
||||
|
||||
SCANNING --> VERIFYING_METADATA: Two-Tier Sanitizer validates payload
|
||||
SCANNING --> FAILED: Security threat or no valid video
|
||||
|
||||
VERIFYING_METADATA --> ORGANIZING: Token overlap matches TMDB cache
|
||||
VERIFYING_METADATA --> FAILED: Title/year token mismatch
|
||||
|
||||
ORGANIZING --> COMPLETED: Files relocated & atomic swap complete
|
||||
ORGANIZING --> FAILED: Target collision / disk full / permission error
|
||||
|
||||
COMPLETED --> [*]
|
||||
FAILED --> [*]
|
||||
```
|
||||
|
||||
### Transition & Failure Invariants
|
||||
1. **Linear 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`.
|
||||
3. **Stalled Download Timeout**: 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. **Crash & Restart Recovery**: Upon worker startup, any orphaned non-terminal jobs (`QUEUED`, `DOWNLOADING`, `SCANNING`, `VERIFYING_METADATA`, `ORGANIZING`) in the SQLite database are automatically transitioned to `FAILED` with reason `"Worker restarted during execution"`. Retrying requires a new submission.
|
||||
5. **Duplicate Rejection (Idempotency)**:
|
||||
- A submission is rejected if a non-terminal job for the same `imdb_id` is currently active in the database.
|
||||
- A submission is rejected if `/media/movies/*[imdbid-{imdb_id}]` already exists in the destination library.
|
||||
### Transition & Concurrency Invariants
|
||||
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.
|
||||
3. **Active-Job Idempotency (`DEC-2`)**:
|
||||
- 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.
|
||||
- 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 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 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 non-terminal jobs:
|
||||
- Transitions their SQLite state to `FAILED` with reason `"Worker restarted during execution"`.
|
||||
- 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>/`.
|
||||
|
||||
---
|
||||
|
||||
## 🛡️ Security & Media Sanitizer Specification
|
||||
## Security & Media Sanitizer Specification (`DEC-3`)
|
||||
|
||||
The sanitizer enforces a strict file-system boundary before files are touched or moved:
|
||||
The sanitizer enforces a two-tier security boundary on untrusted torrent payloads before files are processed (all extension checks are case-insensitive):
|
||||
|
||||
1. **Path Traversal & Symlink Check**: Rejects any archive or torrent payload containing symbolic links, hard links, or paths escaping the staging root (`..`).
|
||||
2. **File Allowlist**:
|
||||
- **Allowed Video**: `.mkv`, `.mp4`, `.avi`, `.webm`
|
||||
- **Allowed Subtitles**: `.srt`, `.vtt`, `.sub`, `.ass`
|
||||
- **Forbidden / Quarantine**: `.exe`, `.bat`, `.cmd`, `.sh`, `.scr`, `.vbs`, `.lnk`, `.iso`, `.zip`, `.rar`, etc.
|
||||
3. **Multiple Video Selection (Largest File Rule)**:
|
||||
- Files containing `sample` in the filename or with size `< 100MB` are discarded.
|
||||
- If multiple video files remain, the **single largest video file** is selected as the primary feature film. A warning is logged listing ignored video files.
|
||||
- If 0 eligible video files remain, the job transitions 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 parent-directory traversal segments (`..`).
|
||||
- **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 archives/disk images:
|
||||
`.exe`, `.bat`, `.cmd`, `.sh`, `.scr`, `.vbs`, `.ps1`, `.lnk`, `.iso`, `.zip`, `.rar`, `.7z`.
|
||||
|
||||
### Tier 2: Allowlist Extraction & Safe Discard
|
||||
- **Allowed Video**: `.mkv`, `.mp4`, `.avi`, `.webm`
|
||||
- **Allowed Subtitles**: `.srt`, `.vtt`, `.sub`, `.ass`
|
||||
- **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 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`.
|
||||
|
||||
---
|
||||
|
||||
## 🎬 Metadata Authority & Verification Criteria
|
||||
## Metadata Authority & Two-Stage Lifecycle (`DEC-4`)
|
||||
|
||||
- **Authority**: **The Movie Database (TMDB) API** using the `/find/{imdb_id}?external_source=imdb_id` endpoint.
|
||||
- **Verification Criteria**:
|
||||
- The canonical title and release year are fetched from TMDB.
|
||||
- A normalized token comparison is performed between the TMDB movie title/year and the torrent folder name / primary video filename.
|
||||
- If there is zero token overlap between the metadata title/year and the torrent name, the job transitions to `FAILED` (`"Torrent payload does not appear to match TMDB metadata"`).
|
||||
- **Authority**: **The Movie Database (TMDB) API** (`/find/{imdb_id}?external_source=imdb_id`) with bounded HTTP timeouts and retries.
|
||||
- **Stage 1 (Early Ingestion Resolution)**:
|
||||
- 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).
|
||||
- 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)**:
|
||||
- Once the torrent completes, the worker compares cached `(title, year)` tokens against the primary video filename and torrent folder name.
|
||||
- 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"`).
|
||||
|
||||
---
|
||||
|
||||
## 📂 Storage Paths & Two-Stage Atomic Relocation
|
||||
## Storage Architecture & Two-Stage Atomic Relocation (`DEC-5`)
|
||||
|
||||
- **Canonical Staging Path**: `/data/staging/<job_id>/`
|
||||
- **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**:
|
||||
```text
|
||||
/media/movies/<Title> (<Year>) [imdbid-<IMDbID>]/<Title> (<Year>).<ext>
|
||||
/media/movies/<Title> (<Year>) [imdbid-<IMDbID>]/<Title> (<Year>).en.srt
|
||||
/media/movies/<SanitizedTitle> (<Year>) [imdbid-<IMDbID>]/<SanitizedTitle> (<Year>).<ext>
|
||||
/media/movies/<SanitizedTitle> (<Year>) [imdbid-<IMDbID>]/<SanitizedTitle> (<Year>).en.srt
|
||||
/media/movies/<SanitizedTitle> (<Year>) [imdbid-<IMDbID>]/<SanitizedTitle> (<Year>).en.forced.srt
|
||||
/media/movies/<SanitizedTitle> (<Year>) [imdbid-<IMDbID>]/<SanitizedTitle> (<Year>).ja.ass
|
||||
```
|
||||
- **Two-Stage Atomic Relocation (Cross-Volume Safe)**:
|
||||
1. *Stage 1 (Transfer)*: Validated files are copied from `/data/staging/<job_id>/` to a temporary directory on the library mount: `/media/movies/.staging_<job_id>/` using `shutil.copy2`.
|
||||
2. *Stage 2 (Atomic Swap)*: Once copying completes and file integrity is verified, `os.replace` atomically renames `/media/movies/.staging_<job_id>/` to the final `/media/movies/<Title> (<Year>) [imdbid-<IMDbID>]/` directory. This prevents Jellyfin/Plex from indexing partially-copied media.
|
||||
- **Cleanup**:
|
||||
- The scratch directory `/data/staging/<job_id>/` is purged immediately upon successful completion or terminal failure.
|
||||
- The torrent session is removed from Transmission daemon via RPC `remove_torrent(id, delete_data=True)` to prevent lingering memory/network leaks.
|
||||
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. *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.
|
||||
- **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`.
|
||||
- The Transmission session is removed via RPC with `delete_data=True` to reclaim session memory and stop active swarm announcements.
|
||||
|
||||
---
|
||||
|
||||
## 🔐 Security Boundaries & Health Endpoints
|
||||
## Async Concurrency & Event Streaming (`DEC-7`)
|
||||
|
||||
### Authentication Trust Boundary
|
||||
- The FastAPI BFF trusts `Remote-User` and `Remote-Email` headers **strictly because it is reachable exclusively through the authenticated Traefik reverse proxy**. Direct ingress from outside the Docker network is prohibited.
|
||||
- **Non-Blocking Worker Event Loop & Pool Isolation**:
|
||||
- The worker coordinates jobs asynchronously (`grpc.aio`, `aiosqlite`, `httpx`).
|
||||
- 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 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**:
|
||||
- An internal in-memory pub/sub broker broadcasts progress and state change events to connected `StreamJobStatus` gRPC streams, avoiding SQLite polling loops.
|
||||
- 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.
|
||||
|
||||
### Health & Readiness Probes
|
||||
- **BFF**: `GET /healthz` (Verifies FastAPI liveness + gRPC worker channel connectivity).
|
||||
- **Worker**: gRPC standard health checking protocol (`grpc.health.v1.Health`) + Transmission RPC ping.
|
||||
---
|
||||
|
||||
## Pluggable Identity Adapter & Dual-Client BFF (`DEC-8`)
|
||||
|
||||
- **Provider-Agnostic Identity Adapter (Fail-Closed)**:
|
||||
- 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`). When `true`, missing or empty identity headers **fail closed with `401 Unauthorized`**.
|
||||
- `AUTH_HEADER_USER`: header name (default: `"Remote-User"`, configurable for any proxy/IdP such as `X-authentik-username` or `X-Forwarded-User`).
|
||||
- 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**:
|
||||
- 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.
|
||||
- **Dual Client Routes, Health Probes & Schemas**:
|
||||
- Supports both the hosted Web UI dashboard and the companion browser extension (`magnetflix-extension`):
|
||||
- `POST /api/v1/downloads` (canonical) and `POST /download` (legacy extension compatibility alias).
|
||||
- Inbound validation aliases accept `magnet` / `magnet_uri` and `imdbid` / `imdb_id`.
|
||||
- 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.
|
||||
+61
-35
@@ -1,16 +1,16 @@
|
||||
# 🚀 MagNetFlix — Deployment & Traefik Integration
|
||||
# 🚀 MagNetFlix — Deployment & Runtime Topology
|
||||
|
||||
This guide details how **MagNetFlix** integrates into the home server stack at `/home/kiskaadee/Deployments/` with **Traefik Reverse Proxy** and **Authelia SSO**.
|
||||
This guide details the container deployment architecture, storage boundaries, and reverse proxy / SSO integration for **MagNetFlix**.
|
||||
|
||||
---
|
||||
|
||||
## 🐳 Docker Compose Architecture
|
||||
|
||||
MagNetFlix runs as a multi-container stack attached to the shared `traefik_network`:
|
||||
MagNetFlix runs as an isolated multi-container stack connected to an internal service bridge, with public ingress routed through a reverse proxy (e.g. Traefik, Nginx, or Caddy) supporting forward-auth or OIDC proxy headers.
|
||||
|
||||
```yaml
|
||||
services:
|
||||
# 1. FastAPI Web Gateway & Form UI
|
||||
# 1. FastAPI Web Gateway & BFF Dashboard
|
||||
bff:
|
||||
build:
|
||||
context: .
|
||||
@@ -19,15 +19,19 @@ services:
|
||||
environment:
|
||||
- GRPC_WORKER_HOST=worker:50051
|
||||
- APP_ENV=production
|
||||
- AUTH_ENABLED=${AUTH_ENABLED:-true}
|
||||
- AUTH_HEADER_USER=${AUTH_HEADER_USER:-Remote-User}
|
||||
- CORS_ALLOWED_ORIGINS=${CORS_ALLOWED_ORIGINS:-}
|
||||
- TMDB_API_KEY=${TMDB_API_KEY}
|
||||
networks:
|
||||
- traefik_network
|
||||
- proxy_network
|
||||
- magnetflix_internal
|
||||
labels:
|
||||
- "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.tls.certresolver=letsencrypt"
|
||||
- "traefik.http.routers.magnetflix.middlewares=authelia@docker"
|
||||
- "traefik.http.routers.magnetflix.tls.certresolver=${TRAEFIK_CERTRESOLVER:-letsencrypt}"
|
||||
- "traefik.http.routers.magnetflix.middlewares=${TRAEFIK_AUTH_MIDDLEWARE}"
|
||||
- "traefik.http.services.magnetflix.loadbalancer.server.port=8000"
|
||||
|
||||
# 2. gRPC Pipeline Worker & Mover
|
||||
@@ -36,59 +40,81 @@ services:
|
||||
context: .
|
||||
dockerfile: services/worker/Dockerfile
|
||||
restart: unless-stopped
|
||||
user: "${PUID:-1000}:${PGID:-1000}"
|
||||
depends_on:
|
||||
transmission:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
- TRANSMISSION_HOST=transmission
|
||||
- TRANSMISSION_PORT=9091
|
||||
- DATABASE_URL=sqlite:////data/magnetflix.sqlite3
|
||||
- DATABASE_URL=sqlite+aiosqlite:////data/magnetflix.sqlite3
|
||||
- STAGING_DIR=/data/staging
|
||||
- MEDIA_DIR=/media/movies
|
||||
- TMDB_API_KEY=${TMDB_API_KEY}
|
||||
volumes:
|
||||
- ./data:/data
|
||||
- /mnt/storage/media/movies:/media/movies
|
||||
- ${MAGNETFLIX_DATA_DIR:-./data}:/data
|
||||
- ${MAGNETFLIX_MEDIA_DIR:-./media/movies}:/media/movies
|
||||
networks:
|
||||
- magnetflix_internal
|
||||
|
||||
# 3. Transmission Torrent Daemon
|
||||
# 3. Isolated Transmission Torrent Daemon
|
||||
transmission:
|
||||
image: lscr.io/linuxserver/transmission:latest
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- PUID=1000
|
||||
- PGID=1000
|
||||
- TZ=America/Chicago
|
||||
- PUID=${PUID:-1000}
|
||||
- PGID=${PGID:-1000}
|
||||
- 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:
|
||||
- ./config/transmission:/config
|
||||
- ./data/staging:/data/staging
|
||||
- ${TRANSMISSION_CONFIG_DIR:-./config/transmission}:/config
|
||||
- ${MAGNETFLIX_DATA_DIR:-./data}/staging:/data/staging
|
||||
networks:
|
||||
- magnetflix_internal
|
||||
|
||||
networks:
|
||||
traefik_network:
|
||||
proxy_network:
|
||||
external: true
|
||||
magnetflix_internal:
|
||||
driver: bridge
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔐 Authelia SSO Integration
|
||||
|
||||
When a user visits `addmovie.roadtotech.me`:
|
||||
1. Traefik triggers the `authelia@docker` forward-auth middleware.
|
||||
2. If unauthenticated, Authelia redirects the user to the login portal.
|
||||
3. Upon authentication, Authelia injects headers into the forwarded request:
|
||||
- `Remote-User`: Username of the logged-in user.
|
||||
- `Remote-Email`: Email address.
|
||||
- `Remote-Groups`: Group memberships (e.g. `admins`, `family`).
|
||||
4. FastAPI extracts `request.headers.get("Remote-User")` and passes it to the gRPC worker for audit logging.
|
||||
> **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`.
|
||||
|
||||
---
|
||||
|
||||
## 📂 Storage Volumes Configuration
|
||||
## 🔐 Pluggable SSO / Reverse Proxy Identity Adapter (`DEC-8`)
|
||||
|
||||
| Mount Path | Type | Purpose |
|
||||
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 |
|
||||
| :--- | :--- | :--- |
|
||||
| `/data/magnetflix.sqlite3` | Persistent Volume | SQLite DB with WAL mode for jobs and audit log. |
|
||||
| `/data/staging` | Fast Scratch Disk | Staging folder where Transmission downloads files. |
|
||||
| `/media/movies` | Media Storage | Final target destination mounted to Jellyfin/Plex. |
|
||||
| `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., `Remote-User` for Authelia/Caddy, `X-authentik-username` for Authentik, or `X-Forwarded-User` for OAuth2-Proxy). |
|
||||
| `CORS_ALLOWED_ORIGINS` | `""` | Optional comma-separated origins permitted for browser extension requests across custom domains. |
|
||||
|
||||
### Upstream Authentication Workflow
|
||||
1. Client (Web UI or browser extension) sends a request to the configured `${MAGNETFLIX_HOST}` endpoint.
|
||||
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 (`AUTH_HEADER_USER`) and forwards the request to the BFF on `proxy_network`.
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## 📂 Storage Volume Invariants
|
||||
|
||||
| Container Mount | Host Target | Filesystem Type | Purpose |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `/data/magnetflix.sqlite3` | Local persistent disk (`./data`) | Local SQLite (WAL Mode) | Job audit logs and pipeline state machine records. **Never place on NFS/SMB network shares.** |
|
||||
| `/data/staging` | Fast scratch disk (`./data/staging`) | Fast local storage | Transmission scratch directory where torrent pieces land. Shared strictly between `worker` and `transmission`. |
|
||||
| `/media/movies` | Media storage pool (`/mnt/storage/...`) | Media pool (ZFS/ext4) | Final Jellyfin/Plex target directory and temporary cross-volume staging (`.staging_<job_id>`). |
|
||||
|
||||
### Cross-Volume Publication & Atomic Swap (`DEC-5`)
|
||||
Because `/data/staging` and `/media/movies` reside on distinct filesystems, cross-volume transfers cannot use filesystem hard-links (`EXDEV` error):
|
||||
1. Files are copied across volumes to `/media/movies/.staging_<job_id>/` using `shutil.copy2`.
|
||||
2. Once transfer and file sizes are verified, `os.replace` executes an instant atomic directory rename on the **same target filesystem** from `.staging_<job_id>/` to `/media/movies/<Title> (<Year>) [imdbid-<IMDbID>]/`.
|
||||
3. Jellyfin and Plex library watchers will never detect, lock, or index partially transferred media files.
|
||||
@@ -0,0 +1,61 @@
|
||||
# 📜 Phase A Current-State Architectural Audit & Review Ledger
|
||||
|
||||
This historical record captures the findings, gap analysis, and architectural reconciliation conducted during the Phase A and Phase B review of **MagNetFlix** on 2026-10-30.
|
||||
|
||||
---
|
||||
|
||||
## 1. Initial State Inventory
|
||||
|
||||
- **Toolchain**: `uv` workspace with `services/worker` and `services/bff`, packaged via `uv_build`. Nix hermetic devShell in `flake.nix`.
|
||||
- **Database**: SQLite WAL engine in `services/worker/src/worker/db/engine.py` with strict pragmas (`journal_mode=WAL; foreign_keys=ON; synchronous=NORMAL; busy_timeout=5000`). Initial Alembic migration `234da461ab5b_create_download_jobs_table.py` created the `download_jobs` table.
|
||||
- **Protobuf**: Contract defined in `proto/magnetflix/v1/pipeline.proto`.
|
||||
- **Tests**: 5 unit tests in `tests/test_db.py` verifying SQLite pragmas, CRUD operations, state transitions, and idempotency queries.
|
||||
|
||||
---
|
||||
|
||||
## 2. Identified Discrepancies & Defect Register
|
||||
|
||||
During read-only inspection of the repository and its runtime behavior, 8 concrete architectural gaps were validated:
|
||||
|
||||
1. **`GAP-1` (Protobuf Package Layout & Broken Imports)**:
|
||||
- Generated stubs in `services/worker/src/worker/magnetflix/v1/pipeline_pb2_grpc.py` emitted `from magnetflix.v1 import pipeline_pb2`.
|
||||
- Importing failed with `ModuleNotFoundError: No module named 'magnetflix'`.
|
||||
- Masked because `pyproject.toml` excluded `services/**/magnetflix/` from `pyright` and `ruff`.
|
||||
- Generated stubs were gitignored, and Dockerfiles omitted `buf generate` and Alembic migration scripts.
|
||||
2. **`GAP-2` (Active Job Concurrency & Idempotency)**:
|
||||
- `imdb_id` had only a non-unique index; application-level check-then-insert was vulnerable to TOCTOU races under concurrent submissions.
|
||||
- `DownloadJob` had no `info_hash` column to track BitTorrent hashes.
|
||||
3. **`GAP-3` (Sanitizer Policy Contradiction)**:
|
||||
- Documentation contradicted whether to purge non-media clutter (`.nfo`, `.txt`, `.jpg`) or fail the entire job. Strict rejection failed ~95% of real torrents, while pure whitelisting allowed malicious symlinks and traversal payloads.
|
||||
4. **`GAP-4` (Subtitle Selection & Relocation Collisions)**:
|
||||
- Sanitizer accepted `.srt`, `.vtt`, `.sub`, `.ass`, but relocator spec forced `<Title> (<Year>).en.srt`, corrupting non-SRT formats and overwriting multi-track subtitles.
|
||||
5. **`GAP-5` (Metadata Resolution Timing)**:
|
||||
- Querying TMDB only after download left UI live dashboard titles blank during downloads and wasted gigabytes on invalid IDs.
|
||||
6. **`GAP-6` (Crash Recovery & Daemon State)**:
|
||||
- Marking DB rows `FAILED` on restart left Transmission actively downloading torrents and abandoned staging disks.
|
||||
7. **`GAP-7` (Async Concurrency & Blocking Disk I/O)**:
|
||||
- Synchronous `shutil.copy2` on 30GB files and synchronous `transmission-rpc` blocked Python's single async event loop, freezing gRPC and SSE streams.
|
||||
8. **`GAP-8` (SSO Decoupling & Movie Search)**:
|
||||
- Hardcoded Authelia headers tightly coupled the app to specific homelab infrastructure. Prototype extension queried undocumented IMDb APIs directly from the browser.
|
||||
|
||||
---
|
||||
|
||||
## 3. Accepted Architectural Decisions Summary
|
||||
|
||||
| Decision ID | Area | Accepted Resolution |
|
||||
| :--- | :--- | :--- |
|
||||
| **`DEC-1`** | Protobuf Packaging | Dedicated `services/contracts` workspace package (`magnetflix` module); commit stubs and docs to Git; update Dockerfiles. |
|
||||
| **`DEC-2`** | Database Hardening | Add SQLite partial unique index `uq_download_jobs_active_imdb_id` (`WHERE state NOT IN ('COMPLETED', 'FAILED')`) and indexed `info_hash` column. |
|
||||
| **`DEC-3`** | Sanitizer Boundary | Two-tier sanitizer: hard-fail on symlinks, hard links, traversal, special files, executables/archives; ignore benign clutter; extract allowlisted media; select largest primary video. |
|
||||
| **`DEC-4`** | TMDB Metadata | Two-stage lifecycle: resolve TMDB `(title, year)` early on ingestion to validate ID and populate UI; verify token overlap post-download offline from SQLite cache. |
|
||||
| **`DEC-5`** | Subtitle Relocation | Multi-track format preservation: retain `.srt`/`.vtt`/`.ass` extensions, parse language/forced tags with disambiguation indices (`.en.1.srt`), safe two-stage atomic directory swap. |
|
||||
| **`DEC-6`** | Crash Recovery | Active startup reconciliation sweep: auto-fail orphaned DB jobs, purge staging directories, remove torrents from Transmission via `info_hash`; enforce 15-min stall timeout. |
|
||||
| **`DEC-7`** | Async Concurrency | Bounded `ThreadPoolExecutor(max_workers=4)` for blocking disk I/O and RPCs; short-lived DB sessions; in-memory `asyncio.Queue` pub/sub broadcaster for SSE. |
|
||||
| **`DEC-8`** | Pluggable Auth & Search | Configurable SSO identity adapter middleware (`AUTH_HEADER_USER`); server-side TMDB search proxy (`GET /api/v1/movies/search`); dual route bindings (`POST /api/v1/downloads` & `POST /download`). |
|
||||
|
||||
---
|
||||
|
||||
## 4. Portfolio Engineering Assessment
|
||||
|
||||
- **Key Competencies**: Clean separation of concerns (BFF + gRPC Worker + Transmission daemon); defense-in-depth security boundary; cross-volume filesystem atomicity (`EXDEV` safe); SQLite WAL concurrency; non-blocking async architecture.
|
||||
- **Scope Discipline**: Explicitly designed as a robust single-node self-hosted pipeline; BitTorrent daemon boundary respected; no speculative microservice bloat.
|
||||
+12
-11
@@ -11,10 +11,10 @@ When self-hosting a media server (Jellyfin/Plex):
|
||||
2. In multi-user setups, tracking who requested what and keeping track of download failures is difficult without a dedicated audit log.
|
||||
|
||||
**MagNetFlix** solves this with an end-to-end automated workflow:
|
||||
- **Input**: A simple web form protected by **Authelia SSO** accepting an **IMDb ID** and a **Magnet URI**.
|
||||
- **Input**: A simple web form protected by **pluggable reverse-proxy / OIDC SSO** accepting an **IMDb ID** and a **Magnet URI**.
|
||||
- **Processing**: A background **gRPC worker** handles downloading via Transmission into a sandboxed staging directory.
|
||||
- **Safety**: Recursively scans and purges all non-media/dangerous executable files.
|
||||
- **Organization**: Fetches official metadata for the IMDb ID, verifies movie details, and places renamed media files into your library structure.
|
||||
- **Safety**: Recursively scans staging payloads, ignoring benign clutter while hard-failing jobs containing dangerous executables, archives, symlinks, or path traversal.
|
||||
- **Organization**: Resolves official TMDB metadata for the IMDb ID at ingestion, verifies movie tokens post-download, and atomically places renamed media files into your library structure.
|
||||
- **Observability**: Live status tracking and persistent audit logs.
|
||||
|
||||
---
|
||||
@@ -25,24 +25,25 @@ When self-hosting a media server (Jellyfin/Plex):
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
actor User as Authenticated User
|
||||
participant Traefik as Traefik (SSO Protected)
|
||||
participant Proxy as Reverse Proxy (SSO Protected)
|
||||
participant BFF as FastAPI (BFF Gateway)
|
||||
participant Worker as gRPC Pipeline Worker
|
||||
participant Engine as Transmission Daemon
|
||||
participant Media as Jellyfin / Plex Library
|
||||
|
||||
User->>Traefik: GET addmovie.roadtotech.me
|
||||
Traefik->>User: Renders MagNetFlix Web Form
|
||||
User->>Traefik: Submit form (magnet URI + IMDb ID: tt1375666)
|
||||
Traefik->>BFF: POST /api/v1/downloads (includes Remote-User header)
|
||||
User->>Proxy: GET https://<MAGNETFLIX_HOST>
|
||||
Proxy->>User: Renders MagNetFlix Web Form
|
||||
User->>Proxy: Submit form (magnet URI + IMDb ID: tt1375666)
|
||||
Proxy->>BFF: POST /api/v1/downloads (includes AUTH_HEADER_USER header)
|
||||
BFF->>Worker: gRPC SubmitDownload(magnet, imdb_id, user)
|
||||
Worker->>Worker: Resolve TMDB title/year (Stage 1)
|
||||
Worker-->>BFF: Acknowledged (Job ID: job-42)
|
||||
BFF-->>User: Enqueued! Showing live progress
|
||||
Worker->>Engine: Start torrent download in /data/staging/job-42
|
||||
Engine-->>Worker: Download Completed
|
||||
Worker->>Worker: Run Security Whitelist Scan (Purge .exe/.bat)
|
||||
Worker->>Worker: Verify IMDb metadata & rename files
|
||||
Worker->>Media: Move to /media/movies/Inception (2010) [imdbid-tt1375666]/
|
||||
Worker->>Worker: Run Two-Tier Security Scan (Hard-fail .exe/.bat)
|
||||
Worker->>Worker: Verify cached TMDB title/year tokens & rename files
|
||||
Worker->>Media: Atomic swap to /media/movies/Inception (2010) [imdbid-tt1375666]/
|
||||
Worker-->>BFF: Status: COMPLETED
|
||||
BFF-->>User: Notification: Movie ready in library!
|
||||
```
|
||||
+94
-54
@@ -1,73 +1,113 @@
|
||||
# 🗺️ MagNetFlix — Development Roadmap
|
||||
# 🗺️ MagNetFlix — MVP-First Implementation Roadmap
|
||||
|
||||
This roadmap breaks down the construction of **MagNetFlix** into clear, incremental milestones with testing embedded in each stage.
|
||||
This roadmap organizes **MagNetFlix** using an **MVP-first vertical slice strategy**: deliver a safe, usable local movie downloader as early as Milestone 2 (**Safe Walking Skeleton MVP**), then layer reliability hardening, SSO/SSE/autocomplete polish, and production reverse-proxy deployment in Milestones 3–5 without losing any architectural requirements (`DEC-1`–`DEC-8`).
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Milestones Overview
|
||||
## 🎯 Milestones Dependency Graph
|
||||
|
||||
```mermaid
|
||||
gantt
|
||||
title MagNetFlix Implementation Phases
|
||||
dateFormat YYYY-MM-DD
|
||||
section Phase 1
|
||||
Workspace & Protobuf Contract :p1, 2026-09-01, 2d
|
||||
section Phase 2
|
||||
Worker Engine & Pipeline Modules :p2, after p1, 4d
|
||||
Worker Unit & Component Tests :p2_test, after p2, 2d
|
||||
section Phase 3
|
||||
FastAPI BFF & Web UI (SSE) :p3, after p2_test, 3d
|
||||
BFF & gRPC Integration Tests :p3_test, after p3, 2d
|
||||
section Phase 4
|
||||
Traefik SSO & Docker Compose :p4, after p3_test, 2d
|
||||
End-to-End Verification :p4_test, after p4, 1d
|
||||
flowchart TD
|
||||
M1["Milestone 1: Contracts, Toolchain & DB Foundation (Done)"]
|
||||
M2["Milestone 2: Safe Walking Skeleton MVP\n(Sanitizer + Stage 1 TMDB + Core Relocator + Worker + Minimal BFF + Dev Compose)"]
|
||||
M3["Milestone 3: Reliability, Metadata Hardening & Crash Recovery\n(M1.8 Base32/Index + Stage 2 Verify + Multi-Track Subs + Recovery + Pools)"]
|
||||
M4["Milestone 4: SSO Security, Real-Time SSE & TMDB Autocomplete UX\n(Fail-Closed Auth + Legacy Alias + Search Proxy + SSE Pub/Sub)"]
|
||||
M5["Milestone 5: Production Reverse-Proxy Deployment & Hardened Verification\n(Traefik Labels + Healthchecks + Locked-Down E2E)"]
|
||||
|
||||
M1 --> M2
|
||||
M2 --> M3
|
||||
M3 --> M4
|
||||
M4 --> M5
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📌 Phase 1: Repository Foundation & Protobuf Contracts
|
||||
- [x] Initialize `uv` workspace with `services/bff` and `services/worker`.
|
||||
- [x] Configure `buf.yaml` and `buf.gen.yaml` with Python & gRPC stubs generation.
|
||||
- [x] Define `proto/magnetflix/v1/pipeline.proto` with pagination, `updated_at`, and streaming snapshot semantics.
|
||||
- [x] Create developer guidelines (`AGENTS.md` and `CLAUDE.md`).
|
||||
## 📌 Milestone 1: Contracts, Toolchain & Database Hardening (`Complete`)
|
||||
- **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.
|
||||
- **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:**
|
||||
- [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.3`: Update dependencies in `services/worker` and `services/bff` to include `magnetflix-contracts = { workspace = true }`.
|
||||
- [x] `M1.4`: Update `pyproject.toml` to include `tests/` in `pyright`, remove exclusions that masked broken imports, and add `test:` target to `Makefile`.
|
||||
- [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.7`: Update `DownloadJob` model and add unit tests in `tests/test_db.py` verifying duplicate active insertion rejection.
|
||||
- **Verifiable Exit Criteria:**
|
||||
- `uv run python -c "from magnetflix.v1 import pipeline_pb2, pipeline_pb2_grpc"` succeeds with 0 errors.
|
||||
- `uv run ruff check .` and `uv run pyright` pass cleanly across the entire workspace including contracts and tests.
|
||||
- `uv run pytest` passes all contract and database tests.
|
||||
|
||||
---
|
||||
|
||||
## 📌 Phase 2: Pipeline Worker & Security Engine
|
||||
- [ ] Set up SQLite with WAL mode via SQLAlchemy 2.0 and Alembic migrations.
|
||||
- [ ] Implement Transmission daemon RPC client wrapper.
|
||||
- [ ] Implement isolated scratch staging (`/data/staging/<job_id>`).
|
||||
- [ ] Build **Media Sanitizer & Allowlist**:
|
||||
- Symlink & path traversal blocker.
|
||||
- Video & subtitle extension whitelist.
|
||||
- Sample file discard (<100MB / "sample") & largest video file selector.
|
||||
- [ ] Build **TMDB Metadata Verifier**: Fetch title/year from TMDB via IMDb ID and perform token overlap verification.
|
||||
- [ ] Build **Library Relocator**: Move verified video and `.srt` files into final Jellyfin/Plex structure.
|
||||
- [ ] **Phase 2 Tests**:
|
||||
- `tests/test_sanitizer.py`: Unit tests for allowlist, traversal, and largest video file selection.
|
||||
- `tests/test_metadata.py`: Unit tests for TMDB client and token matching logic.
|
||||
- `tests/test_state_machine.py`: Unit tests for linear transitions, failure transitions, and restart recovery.
|
||||
- `tests/test_transmission.py`: Mocked Transmission RPC client tests.
|
||||
## 📌 Milestone 2: Safe Walking Skeleton MVP (Local End-to-End Pipeline)
|
||||
- **Objective:** Deliver a working, torrent-safe local vertical slice: submit a magnet URI + IMDb ID in a browser UI, download via Transmission, enforce Two-Tier Sanitizer security checks, resolve TMDB movie metadata, atomically publish into `/media/movies/<Title> (<Year>) [imdbid-<IMDbID>]/`, and poll live job progress.
|
||||
- **Dependencies:** Milestone 1.
|
||||
- **Requirements Satisfied:** `REQ-3`, `REQ-4` (Stage 1), `REQ-5` (Core), `REQ-6`, `REQ-7` (Core), `REQ-8`, `REQ-9` (Core API/UI), `REQ-11` (Local Dev Slice).
|
||||
- **Explicit Deferrals to Post-MVP:** Stage 2 filename token-overlap verification (`M3.2`), 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:**
|
||||
- [ ] `M2.1`: **Two-Tier Media Sanitizer** (`services/worker/src/worker/sanitizer.py` & `tests/test_sanitizer.py`) adhering to `DEC-3`:
|
||||
- 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).
|
||||
- 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`).
|
||||
- Safely ignore unlisted clutter (`.nfo`, `.txt`, `.jpg`, `.sfv`).
|
||||
- Discard sample files (`sample`/`samples` directory components or case-insensitive `\bsample\b` filename stem) and video files `< min_video_bytes`; **never** size-filter subtitles.
|
||||
- Select largest qualifying video (`.mkv`, `.mp4`, `.avi`, `.webm`) and deterministically sorted allowlisted subtitles (`.srt`, `.vtt`, `.sub`, `.ass`), or raise an explicit domain error if no qualifying video remains.
|
||||
- [ ] `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):
|
||||
- `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.
|
||||
- `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.3`: **Transmission Client, Minimal Pipeline Coordinator & Worker gRPC Server** (`transmission.py`, `pipeline.py`, `service.py`, `main.py`, `tests/test_transmission.py`, `tests/test_pipeline.py`, `tests/test_grpc_service.py`):
|
||||
- `TransmissionClient`: 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).
|
||||
- `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:`.
|
||||
- `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.
|
||||
- [ ] `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`):
|
||||
- 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:**
|
||||
- `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`.
|
||||
- `docker compose build && docker compose up -d` starts cleanly and delivers a real public-domain movie into `./media/movies/<Title> (<Year>) [imdbid-<IMDbID>]/`.
|
||||
|
||||
---
|
||||
|
||||
## 📌 Phase 3: BFF Gateway & Live Dashboard
|
||||
- [ ] Build FastAPI application with Pydantic v2 schemas.
|
||||
- [ ] Add Authelia SSO header middleware (`Remote-User`, `Remote-Email`).
|
||||
- [ ] Implement gRPC client wrapper in BFF.
|
||||
- [ ] Build clean HTML form (PicoCSS / Tailwind) for adding movies.
|
||||
- [ ] Implement Server-Sent Events (SSE) route `/api/v1/movies/events` connected to gRPC streaming updates.
|
||||
- [ ] Build live progress dashboard showing active and completed downloads.
|
||||
- [ ] **Phase 3 Tests**:
|
||||
- `tests/test_bff_routes.py`: FastAPI route and header extraction tests.
|
||||
- `tests/test_grpc_integration.py`: End-to-end gRPC communication between BFF and Worker.
|
||||
- `tests/test_sse_stream.py`: SSE stream snapshot and event emission tests.
|
||||
## 📌 Milestone 3: Reliability, Metadata Hardening & Crash Recovery
|
||||
- **Objective:** Close remaining `DEC-2`–`DEC-7` safety and operational resilience gaps deferred from the MVP slice.
|
||||
- **Dependencies:** Milestone 2.
|
||||
- **Requirements Satisfied:** `REQ-2` (`M1.8`), `REQ-4` (Stage 2), `REQ-5` (Multi-track subtitles), `REQ-7` (Stall timeout, Crash recovery, Executor isolation).
|
||||
- **Work Items:**
|
||||
- [ ] `M3.1`: *(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`).
|
||||
- [ ] `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`).
|
||||
- [ ] `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`).
|
||||
- [ ] `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.5`: Enable standard gRPC health checking (`grpcio-health-checking`) on the Worker server and add failure-injection tests for stall timeouts, crash recovery, and metadata mismatch rejection.
|
||||
- **Verifiable Exit Criteria:**
|
||||
- Crash recovery + failure-injection suites pass; orphaned staging directories and stalled torrents are deterministically cleaned up.
|
||||
|
||||
---
|
||||
|
||||
## 📌 Phase 4: Containerization & Traefik Integration
|
||||
- [ ] Create multi-stage `Dockerfile` for `bff` and `worker`.
|
||||
- [ ] Create production-ready `docker-compose.yml` including Transmission daemon and shared volumes.
|
||||
- [ ] Configure Traefik labels for `addmovie.arch-services.mywire.org` with Authelia middleware.
|
||||
- [ ] Configure health and readiness probes (`/healthz`, gRPC health service).
|
||||
- [ ] **Phase 4 Tests**: Full end-to-end dry-run with a public domain torrent.
|
||||
## 📌 Milestone 4: SSO Security, Real-Time SSE & TMDB Autocomplete UX
|
||||
- **Objective:** Replace MVP polling and dev-only submission with fail-closed SSO enforcement, legacy extension compatibility, TMDB autocomplete search, and live Server-Sent Events streaming.
|
||||
- **Dependencies:** Milestone 3.
|
||||
- **Requirements Satisfied:** `REQ-8` (`StreamJobStatus`), `REQ-9`, `REQ-10`.
|
||||
- **Work Items:**
|
||||
- [ ] `M4.1`: Harden **Pluggable Identity Adapter & CORS** in FastAPI BFF (`DEC-8`): enforce fail-closed `401` when `AUTH_ENABLED=true` and `AUTH_HEADER_USER` header is missing/empty (`/healthz` exempt), enforce `CORS_ALLOWED_ORIGINS` allowlist.
|
||||
- [ ] `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.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.
|
||||
- [ ] `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.
|
||||
- **Verifiable Exit Criteria:**
|
||||
- `uv run pytest tests/test_bff_routes.py` validates fail-closed `401`, legacy dual routes, search proxy, and live SSE streaming without CORS errors.
|
||||
|
||||
---
|
||||
|
||||
## 📌 Milestone 5: Production Reverse-Proxy Deployment & Hardened Verification
|
||||
- **Objective:** Finalize production Traefik reverse-proxy configuration, container health probes, and hardened end-to-end verification (`docs/deployment.md`).
|
||||
- **Dependencies:** Milestone 4.
|
||||
- **Requirements Satisfied:** `REQ-11` (Production Deployment).
|
||||
- **Work Items:**
|
||||
- [ ] `M5.1`: Reconcile 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`: Add Docker `HEALTHCHECK` directives (`/healthz` on BFF, gRPC health probe on Worker) and audit multi-stage image builds.
|
||||
- [ ] `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.
|
||||
- **Verifiable Exit Criteria:**
|
||||
- Fresh `docker compose build` succeeds with zero errors, container health checks stay `healthy`, and full hardened E2E lifecycle passes under `AUTH_ENABLED=true`.
|
||||
@@ -51,7 +51,7 @@
|
||||
# Automatically sync uv workspace if .venv is missing
|
||||
if [ ! -d ".venv" ]; then
|
||||
echo "Creating virtual environment and syncing workspace..."
|
||||
uv sync
|
||||
uv sync --all-packages
|
||||
fi
|
||||
'';
|
||||
};
|
||||
|
||||
@@ -7,7 +7,7 @@ import "google/protobuf/timestamp.proto";
|
||||
// PipelineService coordinates movie download jobs, safety scans, and library relocation.
|
||||
service PipelineService {
|
||||
// SubmitDownload enqueues a new movie download job.
|
||||
// Rejects duplicate submissions if an active job for the same IMDb ID exists or if already in library.
|
||||
// Rejects duplicate submissions if an active job for the same IMDb ID or info_hash exists, or if already in library.
|
||||
rpc SubmitDownload (SubmitDownloadRequest) returns (SubmitDownloadResponse);
|
||||
|
||||
// GetJob retrieves the current status and metadata of a specific job.
|
||||
@@ -40,7 +40,7 @@ message SubmitDownloadRequest {
|
||||
string magnet_uri = 1;
|
||||
// IMDb ID of the movie (e.g., "tt1375666").
|
||||
string imdb_id = 2;
|
||||
// Username of the user requesting the download (from Authelia Remote-User).
|
||||
// Username of the user requesting the download (from upstream SSO identity header).
|
||||
string requested_by = 3;
|
||||
}
|
||||
|
||||
|
||||
+13
-4
@@ -16,20 +16,29 @@ dev = [
|
||||
"mypy-protobuf>=5.1.0",
|
||||
"pyright>=1.1.411",
|
||||
"pytest>=8.0.0",
|
||||
"pytest-asyncio>=0.24.0",
|
||||
"ruff>=0.16.5",
|
||||
]
|
||||
|
||||
[tool.pyright]
|
||||
venvPath = "."
|
||||
venv = ".venv"
|
||||
extraPaths = ["services/bff/src", "services/worker/src"]
|
||||
include = ["services"]
|
||||
exclude = ["**/__pycache__", "services/**/magnetflix/"]
|
||||
extraPaths = ["services/bff/src", "services/worker/src", "services/contracts/src"]
|
||||
include = ["services/bff", "services/worker", "tests"]
|
||||
exclude = ["**/__pycache__"]
|
||||
reportIncompatibleVariableOverride = "none"
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 88
|
||||
target-version = "py312"
|
||||
extend-exclude = ["services/**/magnetflix/"]
|
||||
extend-exclude = ["services/contracts/src/magnetflix/v1/"]
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
asyncio_mode = "auto"
|
||||
asyncio_default_fixture_loop_scope = "function"
|
||||
testpaths = ["tests"]
|
||||
pythonpath = ["services/bff/src", "services/worker/src", "services/contracts/src"]
|
||||
|
||||
+15
-4
@@ -1,18 +1,29 @@
|
||||
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ENV UV_COMPILE_BYTECODE=1
|
||||
|
||||
# Copy workspace manifests and required packages so frozen lockfile resolution succeeds
|
||||
COPY pyproject.toml uv.lock ./
|
||||
COPY services/bff/pyproject.toml ./services/bff/
|
||||
COPY services/worker/pyproject.toml services/worker/README.md ./services/worker/
|
||||
COPY services/contracts ./services/contracts
|
||||
COPY services/bff ./services/bff
|
||||
|
||||
# Synchronize dependencies for bff package
|
||||
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
|
||||
WORKDIR /app
|
||||
|
||||
# Copy virtual environment and code
|
||||
COPY --from=builder /app/.venv /app/.venv
|
||||
COPY services/contracts/src ./services/contracts/src
|
||||
COPY services/bff/src ./services/bff/src
|
||||
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
ENV PYTHONPATH="/app/services/bff/src"
|
||||
ENV PYTHONPATH="/app/services/bff/src:/app/services/contracts/src"
|
||||
|
||||
EXPOSE 8000
|
||||
CMD ["uvicorn", "bff.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
@@ -0,0 +1,3 @@
|
||||
# MagNetFlix BFF
|
||||
|
||||
FastAPI Backend-for-Frontend and Web Gateway for MagNetFlix.
|
||||
@@ -7,12 +7,22 @@ requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"fastapi>=0.115.0",
|
||||
"grpcio>=1.83.1",
|
||||
"httpx>=0.28.0",
|
||||
"jinja2>=3.1.4",
|
||||
"protobuf>=7.36.1",
|
||||
"pydantic>=2.10.0",
|
||||
"uvicorn[standard]>=0.32.0",
|
||||
"magnetflix-contracts",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
requires = ["uv_build>=0.12.5,<0.13.0"]
|
||||
build-backend = "uv_build"
|
||||
|
||||
[tool.uv.build-backend]
|
||||
module-name = "bff"
|
||||
module-root = "src"
|
||||
|
||||
[tool.uv.sources]
|
||||
magnetflix-contracts = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# MagNetFlix Contracts
|
||||
|
||||
Shared Protobuf and gRPC stubs generated from `proto/` definitions for the MagNetFlix workspace.
|
||||
@@ -0,0 +1,18 @@
|
||||
[project]
|
||||
name = "magnetflix-contracts"
|
||||
version = "0.1.0"
|
||||
description = "Protobuf and gRPC schemas and stubs for MagNetFlix"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"grpcio>=1.83.1",
|
||||
"protobuf>=7.36.2",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
requires = ["uv_build>=0.12.5,<0.13.0"]
|
||||
build-backend = "uv_build"
|
||||
|
||||
[tool.uv.build-backend]
|
||||
module-name = "magnetflix"
|
||||
module-root = "src"
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Shared Protobuf and gRPC schemas and stubs for MagNetFlix."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,57 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
||||
# NO CHECKED-IN PROTOBUF GENCODE
|
||||
# source: magnetflix/v1/pipeline.proto
|
||||
# Protobuf Python Version: 7.36.2
|
||||
"""Generated protocol buffer code."""
|
||||
from google.protobuf import descriptor as _descriptor
|
||||
from google.protobuf import descriptor_pool as _descriptor_pool
|
||||
from google.protobuf import runtime_version as _runtime_version
|
||||
from google.protobuf import symbol_database as _symbol_database
|
||||
from google.protobuf.internal import builder as _builder
|
||||
_runtime_version.ValidateProtobufRuntimeVersion(
|
||||
_runtime_version.Domain.PUBLIC,
|
||||
7,
|
||||
36,
|
||||
2,
|
||||
'',
|
||||
'magnetflix/v1/pipeline.proto'
|
||||
)
|
||||
# @@protoc_insertion_point(imports)
|
||||
|
||||
_sym_db = _symbol_database.Default()
|
||||
|
||||
|
||||
from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
|
||||
|
||||
|
||||
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1cmagnetflix/v1/pipeline.proto\x12\rmagnetflix.v1\x1a\x1fgoogle/protobuf/timestamp.proto\"r\n\x15SubmitDownloadRequest\x12\x1d\n\nmagnet_uri\x18\x01 \x01(\tR\tmagnetUri\x12\x17\n\x07imdb_id\x18\x02 \x01(\tR\x06imdbId\x12!\n\x0crequested_by\x18\x03 \x01(\tR\x0brequestedBy\"I\n\x16SubmitDownloadResponse\x12\x15\n\x06job_id\x18\x01 \x01(\tR\x05jobId\x12\x18\n\x07message\x18\x02 \x01(\tR\x07message\"&\n\rGetJobRequest\x12\x15\n\x06job_id\x18\x01 \x01(\tR\x05jobId\"<\n\x0eGetJobResponse\x12*\n\x03job\x18\x01 \x01(\x0b\x32\x18.magnetflix.v1.JobStatusR\x03job\"/\n\x16StreamJobStatusRequest\x12\x15\n\x06job_id\x18\x01 \x01(\tR\x05jobId\"E\n\x17StreamJobStatusResponse\x12*\n\x03job\x18\x01 \x01(\x0b\x32\x18.magnetflix.v1.JobStatusR\x03job\"\x89\x01\n\x0fListJobsRequest\x12\x1b\n\tpage_size\x18\x01 \x01(\x05R\x08pageSize\x12\x1d\n\npage_token\x18\x02 \x01(\tR\tpageToken\x12:\n\x0cstate_filter\x18\x03 \x01(\x0e\x32\x17.magnetflix.v1.JobStateR\x0bstateFilter\"\xe4\x03\n\tJobStatus\x12\x15\n\x06job_id\x18\x01 \x01(\tR\x05jobId\x12\x17\n\x07imdb_id\x18\x02 \x01(\tR\x06imdbId\x12\x14\n\x05title\x18\x03 \x01(\tR\x05title\x12\x12\n\x04year\x18\x04 \x01(\x05R\x04year\x12!\n\x0crequested_by\x18\x05 \x01(\tR\x0brequestedBy\x12-\n\x05state\x18\x06 \x01(\x0e\x32\x17.magnetflix.v1.JobStateR\x05state\x12!\n\x0cprogress_pct\x18\x07 \x01(\x02R\x0bprogressPct\x12.\n\x13\x64ownload_rate_bytes\x18\x08 \x01(\x03R\x11\x64ownloadRateBytes\x12#\n\rerror_message\x18\t \x01(\tR\x0c\x65rrorMessage\x12\x39\n\ncreated_at\x18\n \x01(\x0b\x32\x1a.google.protobuf.TimestampR\tcreatedAt\x12\x39\n\nupdated_at\x18\x0b \x01(\x0b\x32\x1a.google.protobuf.TimestampR\tupdatedAt\x12=\n\x0c\x63ompleted_at\x18\x0c \x01(\x0b\x32\x1a.google.protobuf.TimestampR\x0b\x63ompletedAt\"h\n\x10ListJobsResponse\x12,\n\x04jobs\x18\x01 \x03(\x0b\x32\x18.magnetflix.v1.JobStatusR\x04jobs\x12&\n\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken*\xd9\x01\n\x08JobState\x12\x19\n\x15JOB_STATE_UNSPECIFIED\x10\x00\x12\x14\n\x10JOB_STATE_QUEUED\x10\x01\x12\x19\n\x15JOB_STATE_DOWNLOADING\x10\x02\x12\x16\n\x12JOB_STATE_SCANNING\x10\x03\x12 \n\x1cJOB_STATE_VERIFYING_METADATA\x10\x04\x12\x18\n\x14JOB_STATE_ORGANIZING\x10\x05\x12\x17\n\x13JOB_STATE_COMPLETED\x10\x06\x12\x14\n\x10JOB_STATE_FAILED\x10\x07\x32\xe8\x02\n\x0fPipelineService\x12]\n\x0eSubmitDownload\x12$.magnetflix.v1.SubmitDownloadRequest\x1a%.magnetflix.v1.SubmitDownloadResponse\x12\x45\n\x06GetJob\x12\x1c.magnetflix.v1.GetJobRequest\x1a\x1d.magnetflix.v1.GetJobResponse\x12\x62\n\x0fStreamJobStatus\x12%.magnetflix.v1.StreamJobStatusRequest\x1a&.magnetflix.v1.StreamJobStatusResponse0\x01\x12K\n\x08ListJobs\x12\x1e.magnetflix.v1.ListJobsRequest\x1a\x1f.magnetflix.v1.ListJobsResponseb\x06proto3')
|
||||
|
||||
_globals = globals()
|
||||
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
|
||||
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'magnetflix.v1.pipeline_pb2', _globals)
|
||||
if not _descriptor._USE_C_DESCRIPTORS:
|
||||
DESCRIPTOR._loaded_options = None
|
||||
_globals['_JOBSTATE']._serialized_start=1227
|
||||
_globals['_JOBSTATE']._serialized_end=1444
|
||||
_globals['_SUBMITDOWNLOADREQUEST']._serialized_start=80
|
||||
_globals['_SUBMITDOWNLOADREQUEST']._serialized_end=194
|
||||
_globals['_SUBMITDOWNLOADRESPONSE']._serialized_start=196
|
||||
_globals['_SUBMITDOWNLOADRESPONSE']._serialized_end=269
|
||||
_globals['_GETJOBREQUEST']._serialized_start=271
|
||||
_globals['_GETJOBREQUEST']._serialized_end=309
|
||||
_globals['_GETJOBRESPONSE']._serialized_start=311
|
||||
_globals['_GETJOBRESPONSE']._serialized_end=371
|
||||
_globals['_STREAMJOBSTATUSREQUEST']._serialized_start=373
|
||||
_globals['_STREAMJOBSTATUSREQUEST']._serialized_end=420
|
||||
_globals['_STREAMJOBSTATUSRESPONSE']._serialized_start=422
|
||||
_globals['_STREAMJOBSTATUSRESPONSE']._serialized_end=491
|
||||
_globals['_LISTJOBSREQUEST']._serialized_start=494
|
||||
_globals['_LISTJOBSREQUEST']._serialized_end=631
|
||||
_globals['_JOBSTATUS']._serialized_start=634
|
||||
_globals['_JOBSTATUS']._serialized_end=1118
|
||||
_globals['_LISTJOBSRESPONSE']._serialized_start=1120
|
||||
_globals['_LISTJOBSRESPONSE']._serialized_end=1224
|
||||
_globals['_PIPELINESERVICE']._serialized_start=1447
|
||||
_globals['_PIPELINESERVICE']._serialized_end=1807
|
||||
# @@protoc_insertion_point(module_scope)
|
||||
@@ -0,0 +1,327 @@
|
||||
"""
|
||||
@generated by mypy-protobuf. Do not edit manually!
|
||||
isort:skip_file
|
||||
"""
|
||||
|
||||
from collections import abc as _abc
|
||||
from google.protobuf import descriptor as _descriptor
|
||||
from google.protobuf import message as _message
|
||||
from google.protobuf import timestamp_pb2 as _timestamp_pb2
|
||||
from google.protobuf.internal import containers as _containers
|
||||
from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper
|
||||
import builtins as _builtins
|
||||
import sys
|
||||
import typing as _typing
|
||||
|
||||
if sys.version_info >= (3, 11):
|
||||
from typing import TypeAlias as _TypeAlias, Never as _Never
|
||||
else:
|
||||
from typing_extensions import TypeAlias as _TypeAlias, Never as _Never
|
||||
|
||||
DESCRIPTOR: _descriptor.FileDescriptor
|
||||
|
||||
class _JobState:
|
||||
ValueType = _typing.NewType("ValueType", _builtins.int)
|
||||
V: _TypeAlias = ValueType # noqa: Y015
|
||||
|
||||
class _JobStateEnumTypeWrapper(_enum_type_wrapper._EnumTypeWrapper[_JobState.ValueType], _builtins.type):
|
||||
DESCRIPTOR: _descriptor.EnumDescriptor
|
||||
JOB_STATE_UNSPECIFIED: _JobState.ValueType # 0
|
||||
JOB_STATE_QUEUED: _JobState.ValueType # 1
|
||||
JOB_STATE_DOWNLOADING: _JobState.ValueType # 2
|
||||
JOB_STATE_SCANNING: _JobState.ValueType # 3
|
||||
JOB_STATE_VERIFYING_METADATA: _JobState.ValueType # 4
|
||||
JOB_STATE_ORGANIZING: _JobState.ValueType # 5
|
||||
JOB_STATE_COMPLETED: _JobState.ValueType # 6
|
||||
JOB_STATE_FAILED: _JobState.ValueType # 7
|
||||
|
||||
class JobState(_JobState, metaclass=_JobStateEnumTypeWrapper):
|
||||
"""State enumeration of a download job lifecycle."""
|
||||
|
||||
JOB_STATE_UNSPECIFIED: JobState.ValueType # 0
|
||||
JOB_STATE_QUEUED: JobState.ValueType # 1
|
||||
JOB_STATE_DOWNLOADING: JobState.ValueType # 2
|
||||
JOB_STATE_SCANNING: JobState.ValueType # 3
|
||||
JOB_STATE_VERIFYING_METADATA: JobState.ValueType # 4
|
||||
JOB_STATE_ORGANIZING: JobState.ValueType # 5
|
||||
JOB_STATE_COMPLETED: JobState.ValueType # 6
|
||||
JOB_STATE_FAILED: JobState.ValueType # 7
|
||||
Global___JobState: _TypeAlias = JobState # noqa: Y015
|
||||
|
||||
@_typing.final
|
||||
class SubmitDownloadRequest(_message.Message):
|
||||
"""Request to submit a new movie download."""
|
||||
|
||||
DESCRIPTOR: _descriptor.Descriptor
|
||||
|
||||
MAGNET_URI_FIELD_NUMBER: _builtins.int
|
||||
IMDB_ID_FIELD_NUMBER: _builtins.int
|
||||
REQUESTED_BY_FIELD_NUMBER: _builtins.int
|
||||
magnet_uri: _builtins.str
|
||||
"""Magnet URI of the torrent to fetch."""
|
||||
imdb_id: _builtins.str
|
||||
"""IMDb ID of the movie (e.g., "tt1375666")."""
|
||||
requested_by: _builtins.str
|
||||
"""Username of the user requesting the download (from upstream SSO identity header)."""
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
magnet_uri: _builtins.str = ...,
|
||||
imdb_id: _builtins.str = ...,
|
||||
requested_by: _builtins.str = ...,
|
||||
) -> None: ...
|
||||
_HasFieldArgType: _TypeAlias = _Never # noqa: Y015
|
||||
def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
|
||||
_ClearFieldArgType: _TypeAlias = _typing.Literal["imdb_id", b"imdb_id", "magnet_uri", b"magnet_uri", "requested_by", b"requested_by"] # noqa: Y015
|
||||
def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
|
||||
def WhichOneof(self, oneof_group: _Never) -> None: ...
|
||||
|
||||
Global___SubmitDownloadRequest: _TypeAlias = SubmitDownloadRequest # noqa: Y015
|
||||
|
||||
@_typing.final
|
||||
class SubmitDownloadResponse(_message.Message):
|
||||
"""Response acknowledging the job submission."""
|
||||
|
||||
DESCRIPTOR: _descriptor.Descriptor
|
||||
|
||||
JOB_ID_FIELD_NUMBER: _builtins.int
|
||||
MESSAGE_FIELD_NUMBER: _builtins.int
|
||||
job_id: _builtins.str
|
||||
"""Unique identifier for the created job."""
|
||||
message: _builtins.str
|
||||
"""Human-readable message."""
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
job_id: _builtins.str = ...,
|
||||
message: _builtins.str = ...,
|
||||
) -> None: ...
|
||||
_HasFieldArgType: _TypeAlias = _Never # noqa: Y015
|
||||
def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
|
||||
_ClearFieldArgType: _TypeAlias = _typing.Literal["job_id", b"job_id", "message", b"message"] # noqa: Y015
|
||||
def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
|
||||
def WhichOneof(self, oneof_group: _Never) -> None: ...
|
||||
|
||||
Global___SubmitDownloadResponse: _TypeAlias = SubmitDownloadResponse # noqa: Y015
|
||||
|
||||
@_typing.final
|
||||
class GetJobRequest(_message.Message):
|
||||
"""Request to fetch a specific job by ID."""
|
||||
|
||||
DESCRIPTOR: _descriptor.Descriptor
|
||||
|
||||
JOB_ID_FIELD_NUMBER: _builtins.int
|
||||
job_id: _builtins.str
|
||||
"""Unique job identifier."""
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
job_id: _builtins.str = ...,
|
||||
) -> None: ...
|
||||
_HasFieldArgType: _TypeAlias = _Never # noqa: Y015
|
||||
def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
|
||||
_ClearFieldArgType: _TypeAlias = _typing.Literal["job_id", b"job_id"] # noqa: Y015
|
||||
def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
|
||||
def WhichOneof(self, oneof_group: _Never) -> None: ...
|
||||
|
||||
Global___GetJobRequest: _TypeAlias = GetJobRequest # noqa: Y015
|
||||
|
||||
@_typing.final
|
||||
class GetJobResponse(_message.Message):
|
||||
"""Response containing the status of the requested job."""
|
||||
|
||||
DESCRIPTOR: _descriptor.Descriptor
|
||||
|
||||
JOB_FIELD_NUMBER: _builtins.int
|
||||
@_builtins.property
|
||||
def job(self) -> Global___JobStatus:
|
||||
"""The retrieved job details."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
job: Global___JobStatus | None = ...,
|
||||
) -> None: ...
|
||||
_HasFieldArgType: _TypeAlias = _typing.Literal["job", b"job"] # noqa: Y015
|
||||
def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
|
||||
_ClearFieldArgType: _TypeAlias = _typing.Literal["job", b"job"] # noqa: Y015
|
||||
def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
|
||||
def WhichOneof(self, oneof_group: _Never) -> None: ...
|
||||
|
||||
Global___GetJobResponse: _TypeAlias = GetJobResponse # noqa: Y015
|
||||
|
||||
@_typing.final
|
||||
class StreamJobStatusRequest(_message.Message):
|
||||
"""Request to stream job updates."""
|
||||
|
||||
DESCRIPTOR: _descriptor.Descriptor
|
||||
|
||||
JOB_ID_FIELD_NUMBER: _builtins.int
|
||||
job_id: _builtins.str
|
||||
"""Optional job ID to filter updates for a single job; if empty, streams all active jobs."""
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
job_id: _builtins.str = ...,
|
||||
) -> None: ...
|
||||
_HasFieldArgType: _TypeAlias = _Never # noqa: Y015
|
||||
def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
|
||||
_ClearFieldArgType: _TypeAlias = _typing.Literal["job_id", b"job_id"] # noqa: Y015
|
||||
def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
|
||||
def WhichOneof(self, oneof_group: _Never) -> None: ...
|
||||
|
||||
Global___StreamJobStatusRequest: _TypeAlias = StreamJobStatusRequest # noqa: Y015
|
||||
|
||||
@_typing.final
|
||||
class StreamJobStatusResponse(_message.Message):
|
||||
"""Real-time job status event stream frame."""
|
||||
|
||||
DESCRIPTOR: _descriptor.Descriptor
|
||||
|
||||
JOB_FIELD_NUMBER: _builtins.int
|
||||
@_builtins.property
|
||||
def job(self) -> Global___JobStatus:
|
||||
"""Current job status update."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
job: Global___JobStatus | None = ...,
|
||||
) -> None: ...
|
||||
_HasFieldArgType: _TypeAlias = _typing.Literal["job", b"job"] # noqa: Y015
|
||||
def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
|
||||
_ClearFieldArgType: _TypeAlias = _typing.Literal["job", b"job"] # noqa: Y015
|
||||
def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
|
||||
def WhichOneof(self, oneof_group: _Never) -> None: ...
|
||||
|
||||
Global___StreamJobStatusResponse: _TypeAlias = StreamJobStatusResponse # noqa: Y015
|
||||
|
||||
@_typing.final
|
||||
class ListJobsRequest(_message.Message):
|
||||
"""Request to list jobs with pagination and state filtering."""
|
||||
|
||||
DESCRIPTOR: _descriptor.Descriptor
|
||||
|
||||
PAGE_SIZE_FIELD_NUMBER: _builtins.int
|
||||
PAGE_TOKEN_FIELD_NUMBER: _builtins.int
|
||||
STATE_FILTER_FIELD_NUMBER: _builtins.int
|
||||
page_size: _builtins.int
|
||||
"""Maximum number of jobs to return per page (default: 20, max: 100)."""
|
||||
page_token: _builtins.str
|
||||
"""Page token received from a previous ListJobsResponse next_page_token."""
|
||||
state_filter: Global___JobState.ValueType
|
||||
"""Optional filter by job state."""
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
page_size: _builtins.int = ...,
|
||||
page_token: _builtins.str = ...,
|
||||
state_filter: Global___JobState.ValueType = ...,
|
||||
) -> None: ...
|
||||
_HasFieldArgType: _TypeAlias = _Never # noqa: Y015
|
||||
def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
|
||||
_ClearFieldArgType: _TypeAlias = _typing.Literal["page_size", b"page_size", "page_token", b"page_token", "state_filter", b"state_filter"] # noqa: Y015
|
||||
def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
|
||||
def WhichOneof(self, oneof_group: _Never) -> None: ...
|
||||
|
||||
Global___ListJobsRequest: _TypeAlias = ListJobsRequest # noqa: Y015
|
||||
|
||||
@_typing.final
|
||||
class JobStatus(_message.Message):
|
||||
"""Full status information for a download job."""
|
||||
|
||||
DESCRIPTOR: _descriptor.Descriptor
|
||||
|
||||
JOB_ID_FIELD_NUMBER: _builtins.int
|
||||
IMDB_ID_FIELD_NUMBER: _builtins.int
|
||||
TITLE_FIELD_NUMBER: _builtins.int
|
||||
YEAR_FIELD_NUMBER: _builtins.int
|
||||
REQUESTED_BY_FIELD_NUMBER: _builtins.int
|
||||
STATE_FIELD_NUMBER: _builtins.int
|
||||
PROGRESS_PCT_FIELD_NUMBER: _builtins.int
|
||||
DOWNLOAD_RATE_BYTES_FIELD_NUMBER: _builtins.int
|
||||
ERROR_MESSAGE_FIELD_NUMBER: _builtins.int
|
||||
CREATED_AT_FIELD_NUMBER: _builtins.int
|
||||
UPDATED_AT_FIELD_NUMBER: _builtins.int
|
||||
COMPLETED_AT_FIELD_NUMBER: _builtins.int
|
||||
job_id: _builtins.str
|
||||
"""Unique job ID."""
|
||||
imdb_id: _builtins.str
|
||||
"""IMDb ID."""
|
||||
title: _builtins.str
|
||||
"""Resolved movie title from TMDB (if available)."""
|
||||
year: _builtins.int
|
||||
"""Resolved release year from TMDB (if available)."""
|
||||
requested_by: _builtins.str
|
||||
"""User who requested the download."""
|
||||
state: Global___JobState.ValueType
|
||||
"""Current state in the pipeline."""
|
||||
progress_pct: _builtins.float
|
||||
"""Download progress percentage (0.0 to 100.0)."""
|
||||
download_rate_bytes: _builtins.int
|
||||
"""Download speed in bytes per second."""
|
||||
error_message: _builtins.str
|
||||
"""Detailed error message if the job failed."""
|
||||
@_builtins.property
|
||||
def created_at(self) -> _timestamp_pb2.Timestamp:
|
||||
"""Timestamp when the job was enqueued."""
|
||||
|
||||
@_builtins.property
|
||||
def updated_at(self) -> _timestamp_pb2.Timestamp:
|
||||
"""Timestamp when the job status or progress was last updated."""
|
||||
|
||||
@_builtins.property
|
||||
def completed_at(self) -> _timestamp_pb2.Timestamp:
|
||||
"""Timestamp when terminal processing finished (COMPLETED or FAILED)."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
job_id: _builtins.str = ...,
|
||||
imdb_id: _builtins.str = ...,
|
||||
title: _builtins.str = ...,
|
||||
year: _builtins.int = ...,
|
||||
requested_by: _builtins.str = ...,
|
||||
state: Global___JobState.ValueType = ...,
|
||||
progress_pct: _builtins.float = ...,
|
||||
download_rate_bytes: _builtins.int = ...,
|
||||
error_message: _builtins.str = ...,
|
||||
created_at: _timestamp_pb2.Timestamp | None = ...,
|
||||
updated_at: _timestamp_pb2.Timestamp | None = ...,
|
||||
completed_at: _timestamp_pb2.Timestamp | None = ...,
|
||||
) -> None: ...
|
||||
_HasFieldArgType: _TypeAlias = _typing.Literal["completed_at", b"completed_at", "created_at", b"created_at", "updated_at", b"updated_at"] # noqa: Y015
|
||||
def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
|
||||
_ClearFieldArgType: _TypeAlias = _typing.Literal["completed_at", b"completed_at", "created_at", b"created_at", "download_rate_bytes", b"download_rate_bytes", "error_message", b"error_message", "imdb_id", b"imdb_id", "job_id", b"job_id", "progress_pct", b"progress_pct", "requested_by", b"requested_by", "state", b"state", "title", b"title", "updated_at", b"updated_at", "year", b"year"] # noqa: Y015
|
||||
def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
|
||||
def WhichOneof(self, oneof_group: _Never) -> None: ...
|
||||
|
||||
Global___JobStatus: _TypeAlias = JobStatus # noqa: Y015
|
||||
|
||||
@_typing.final
|
||||
class ListJobsResponse(_message.Message):
|
||||
"""Paginated response containing a list of download jobs."""
|
||||
|
||||
DESCRIPTOR: _descriptor.Descriptor
|
||||
|
||||
JOBS_FIELD_NUMBER: _builtins.int
|
||||
NEXT_PAGE_TOKEN_FIELD_NUMBER: _builtins.int
|
||||
next_page_token: _builtins.str
|
||||
"""Token to retrieve the next page of results, or empty if no more results."""
|
||||
@_builtins.property
|
||||
def jobs(self) -> _containers.RepeatedCompositeFieldContainer[Global___JobStatus]:
|
||||
"""List of matching jobs for the current page."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
jobs: _abc.Iterable[Global___JobStatus] | None = ...,
|
||||
next_page_token: _builtins.str = ...,
|
||||
) -> None: ...
|
||||
_HasFieldArgType: _TypeAlias = _Never # noqa: Y015
|
||||
def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ...
|
||||
_ClearFieldArgType: _TypeAlias = _typing.Literal["jobs", b"jobs", "next_page_token", b"next_page_token"] # noqa: Y015
|
||||
def ClearField(self, field_name: _ClearFieldArgType) -> None: ...
|
||||
def WhichOneof(self, oneof_group: _Never) -> None: ...
|
||||
|
||||
Global___ListJobsResponse: _TypeAlias = ListJobsResponse # noqa: Y015
|
||||
@@ -0,0 +1,216 @@
|
||||
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
|
||||
"""Client and server classes corresponding to protobuf-defined services."""
|
||||
import grpc
|
||||
|
||||
from magnetflix.v1 import pipeline_pb2 as magnetflix_dot_v1_dot_pipeline__pb2
|
||||
|
||||
|
||||
class PipelineServiceStub:
|
||||
"""PipelineService coordinates movie download jobs, safety scans, and library relocation.
|
||||
"""
|
||||
|
||||
def __init__(self, channel):
|
||||
"""Constructor.
|
||||
|
||||
Args:
|
||||
channel: A grpc.Channel.
|
||||
"""
|
||||
self.SubmitDownload = channel.unary_unary(
|
||||
'/magnetflix.v1.PipelineService/SubmitDownload',
|
||||
request_serializer=magnetflix_dot_v1_dot_pipeline__pb2.SubmitDownloadRequest.SerializeToString,
|
||||
response_deserializer=magnetflix_dot_v1_dot_pipeline__pb2.SubmitDownloadResponse.FromString,
|
||||
_registered_method=True)
|
||||
self.GetJob = channel.unary_unary(
|
||||
'/magnetflix.v1.PipelineService/GetJob',
|
||||
request_serializer=magnetflix_dot_v1_dot_pipeline__pb2.GetJobRequest.SerializeToString,
|
||||
response_deserializer=magnetflix_dot_v1_dot_pipeline__pb2.GetJobResponse.FromString,
|
||||
_registered_method=True)
|
||||
self.StreamJobStatus = channel.unary_stream(
|
||||
'/magnetflix.v1.PipelineService/StreamJobStatus',
|
||||
request_serializer=magnetflix_dot_v1_dot_pipeline__pb2.StreamJobStatusRequest.SerializeToString,
|
||||
response_deserializer=magnetflix_dot_v1_dot_pipeline__pb2.StreamJobStatusResponse.FromString,
|
||||
_registered_method=True)
|
||||
self.ListJobs = channel.unary_unary(
|
||||
'/magnetflix.v1.PipelineService/ListJobs',
|
||||
request_serializer=magnetflix_dot_v1_dot_pipeline__pb2.ListJobsRequest.SerializeToString,
|
||||
response_deserializer=magnetflix_dot_v1_dot_pipeline__pb2.ListJobsResponse.FromString,
|
||||
_registered_method=True)
|
||||
|
||||
|
||||
class PipelineServiceServicer:
|
||||
"""PipelineService coordinates movie download jobs, safety scans, and library relocation.
|
||||
"""
|
||||
|
||||
def SubmitDownload(self, request, context):
|
||||
"""SubmitDownload enqueues a new movie download job.
|
||||
Rejects duplicate submissions if an active job for the same IMDb ID or info_hash exists, or if already in library.
|
||||
"""
|
||||
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
|
||||
context.set_details('Method not implemented!')
|
||||
raise NotImplementedError('Method not implemented!')
|
||||
|
||||
def GetJob(self, request, context):
|
||||
"""GetJob retrieves the current status and metadata of a specific job.
|
||||
"""
|
||||
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
|
||||
context.set_details('Method not implemented!')
|
||||
raise NotImplementedError('Method not implemented!')
|
||||
|
||||
def StreamJobStatus(self, request, context):
|
||||
"""StreamJobStatus streams real-time status updates.
|
||||
Semantics: Emits an immediate snapshot of matching active jobs upon connection,
|
||||
followed by subsequent state and progress change events.
|
||||
"""
|
||||
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
|
||||
context.set_details('Method not implemented!')
|
||||
raise NotImplementedError('Method not implemented!')
|
||||
|
||||
def ListJobs(self, request, context):
|
||||
"""ListJobs returns a paginated list of download jobs.
|
||||
"""
|
||||
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
|
||||
context.set_details('Method not implemented!')
|
||||
raise NotImplementedError('Method not implemented!')
|
||||
|
||||
|
||||
def add_PipelineServiceServicer_to_server(servicer, server):
|
||||
rpc_method_handlers = {
|
||||
'SubmitDownload': grpc.unary_unary_rpc_method_handler(
|
||||
servicer.SubmitDownload,
|
||||
request_deserializer=magnetflix_dot_v1_dot_pipeline__pb2.SubmitDownloadRequest.FromString,
|
||||
response_serializer=magnetflix_dot_v1_dot_pipeline__pb2.SubmitDownloadResponse.SerializeToString,
|
||||
),
|
||||
'GetJob': grpc.unary_unary_rpc_method_handler(
|
||||
servicer.GetJob,
|
||||
request_deserializer=magnetflix_dot_v1_dot_pipeline__pb2.GetJobRequest.FromString,
|
||||
response_serializer=magnetflix_dot_v1_dot_pipeline__pb2.GetJobResponse.SerializeToString,
|
||||
),
|
||||
'StreamJobStatus': grpc.unary_stream_rpc_method_handler(
|
||||
servicer.StreamJobStatus,
|
||||
request_deserializer=magnetflix_dot_v1_dot_pipeline__pb2.StreamJobStatusRequest.FromString,
|
||||
response_serializer=magnetflix_dot_v1_dot_pipeline__pb2.StreamJobStatusResponse.SerializeToString,
|
||||
),
|
||||
'ListJobs': grpc.unary_unary_rpc_method_handler(
|
||||
servicer.ListJobs,
|
||||
request_deserializer=magnetflix_dot_v1_dot_pipeline__pb2.ListJobsRequest.FromString,
|
||||
response_serializer=magnetflix_dot_v1_dot_pipeline__pb2.ListJobsResponse.SerializeToString,
|
||||
),
|
||||
}
|
||||
generic_handler = grpc.method_handlers_generic_handler(
|
||||
'magnetflix.v1.PipelineService', rpc_method_handlers)
|
||||
server.add_generic_rpc_handlers((generic_handler,))
|
||||
server.add_registered_method_handlers('magnetflix.v1.PipelineService', rpc_method_handlers)
|
||||
|
||||
|
||||
# This class is part of an EXPERIMENTAL API.
|
||||
class PipelineService:
|
||||
"""PipelineService coordinates movie download jobs, safety scans, and library relocation.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def SubmitDownload(request,
|
||||
target,
|
||||
options=(),
|
||||
channel_credentials=None,
|
||||
call_credentials=None,
|
||||
insecure=False,
|
||||
compression=None,
|
||||
wait_for_ready=None,
|
||||
timeout=None,
|
||||
metadata=None):
|
||||
return grpc.experimental.unary_unary(
|
||||
request,
|
||||
target,
|
||||
'/magnetflix.v1.PipelineService/SubmitDownload',
|
||||
magnetflix_dot_v1_dot_pipeline__pb2.SubmitDownloadRequest.SerializeToString,
|
||||
magnetflix_dot_v1_dot_pipeline__pb2.SubmitDownloadResponse.FromString,
|
||||
options,
|
||||
channel_credentials,
|
||||
insecure,
|
||||
call_credentials,
|
||||
compression,
|
||||
wait_for_ready,
|
||||
timeout,
|
||||
metadata,
|
||||
_registered_method=True)
|
||||
|
||||
@staticmethod
|
||||
def GetJob(request,
|
||||
target,
|
||||
options=(),
|
||||
channel_credentials=None,
|
||||
call_credentials=None,
|
||||
insecure=False,
|
||||
compression=None,
|
||||
wait_for_ready=None,
|
||||
timeout=None,
|
||||
metadata=None):
|
||||
return grpc.experimental.unary_unary(
|
||||
request,
|
||||
target,
|
||||
'/magnetflix.v1.PipelineService/GetJob',
|
||||
magnetflix_dot_v1_dot_pipeline__pb2.GetJobRequest.SerializeToString,
|
||||
magnetflix_dot_v1_dot_pipeline__pb2.GetJobResponse.FromString,
|
||||
options,
|
||||
channel_credentials,
|
||||
insecure,
|
||||
call_credentials,
|
||||
compression,
|
||||
wait_for_ready,
|
||||
timeout,
|
||||
metadata,
|
||||
_registered_method=True)
|
||||
|
||||
@staticmethod
|
||||
def StreamJobStatus(request,
|
||||
target,
|
||||
options=(),
|
||||
channel_credentials=None,
|
||||
call_credentials=None,
|
||||
insecure=False,
|
||||
compression=None,
|
||||
wait_for_ready=None,
|
||||
timeout=None,
|
||||
metadata=None):
|
||||
return grpc.experimental.unary_stream(
|
||||
request,
|
||||
target,
|
||||
'/magnetflix.v1.PipelineService/StreamJobStatus',
|
||||
magnetflix_dot_v1_dot_pipeline__pb2.StreamJobStatusRequest.SerializeToString,
|
||||
magnetflix_dot_v1_dot_pipeline__pb2.StreamJobStatusResponse.FromString,
|
||||
options,
|
||||
channel_credentials,
|
||||
insecure,
|
||||
call_credentials,
|
||||
compression,
|
||||
wait_for_ready,
|
||||
timeout,
|
||||
metadata,
|
||||
_registered_method=True)
|
||||
|
||||
@staticmethod
|
||||
def ListJobs(request,
|
||||
target,
|
||||
options=(),
|
||||
channel_credentials=None,
|
||||
call_credentials=None,
|
||||
insecure=False,
|
||||
compression=None,
|
||||
wait_for_ready=None,
|
||||
timeout=None,
|
||||
metadata=None):
|
||||
return grpc.experimental.unary_unary(
|
||||
request,
|
||||
target,
|
||||
'/magnetflix.v1.PipelineService/ListJobs',
|
||||
magnetflix_dot_v1_dot_pipeline__pb2.ListJobsRequest.SerializeToString,
|
||||
magnetflix_dot_v1_dot_pipeline__pb2.ListJobsResponse.FromString,
|
||||
options,
|
||||
channel_credentials,
|
||||
insecure,
|
||||
call_credentials,
|
||||
compression,
|
||||
wait_for_ready,
|
||||
timeout,
|
||||
metadata,
|
||||
_registered_method=True)
|
||||
@@ -0,0 +1,109 @@
|
||||
"""
|
||||
@generated by mypy-protobuf. Do not edit manually!
|
||||
isort:skip_file
|
||||
"""
|
||||
|
||||
from collections import abc as _abc
|
||||
from grpc import aio as _aio
|
||||
from magnetflix.v1 import pipeline_pb2 as _pipeline_pb2
|
||||
import abc as _abc_1
|
||||
import grpc as _grpc
|
||||
import sys
|
||||
import typing as _typing
|
||||
|
||||
if sys.version_info >= (3, 11):
|
||||
from typing import Self as _Self
|
||||
else:
|
||||
from typing_extensions import Self as _Self
|
||||
|
||||
_T = _typing.TypeVar("_T")
|
||||
|
||||
class _MaybeAsyncIterator(_abc.AsyncIterator[_T], _abc.Iterator[_T], metaclass=_abc_1.ABCMeta): ...
|
||||
|
||||
class _ServicerContext(_grpc.ServicerContext, _aio.ServicerContext): # type: ignore[misc, type-arg]
|
||||
...
|
||||
|
||||
GRPC_GENERATED_VERSION: str
|
||||
GRPC_VERSION: str
|
||||
|
||||
class PipelineServiceStub:
|
||||
"""PipelineService coordinates movie download jobs, safety scans, and library relocation."""
|
||||
|
||||
@_typing.overload
|
||||
def __new__(cls, channel: _grpc.Channel) -> _Self: ...
|
||||
@_typing.overload
|
||||
def __new__(cls, channel: _aio.Channel) -> PipelineServiceAsyncStub: ...
|
||||
SubmitDownload: _grpc.UnaryUnaryMultiCallable[_pipeline_pb2.SubmitDownloadRequest, _pipeline_pb2.SubmitDownloadResponse]
|
||||
"""SubmitDownload enqueues a new movie download job.
|
||||
Rejects duplicate submissions if an active job for the same IMDb ID or info_hash exists, or if already in library.
|
||||
"""
|
||||
GetJob: _grpc.UnaryUnaryMultiCallable[_pipeline_pb2.GetJobRequest, _pipeline_pb2.GetJobResponse]
|
||||
"""GetJob retrieves the current status and metadata of a specific job."""
|
||||
StreamJobStatus: _grpc.UnaryStreamMultiCallable[_pipeline_pb2.StreamJobStatusRequest, _pipeline_pb2.StreamJobStatusResponse]
|
||||
"""StreamJobStatus streams real-time status updates.
|
||||
Semantics: Emits an immediate snapshot of matching active jobs upon connection,
|
||||
followed by subsequent state and progress change events.
|
||||
"""
|
||||
ListJobs: _grpc.UnaryUnaryMultiCallable[_pipeline_pb2.ListJobsRequest, _pipeline_pb2.ListJobsResponse]
|
||||
"""ListJobs returns a paginated list of download jobs."""
|
||||
|
||||
@_typing.type_check_only
|
||||
class PipelineServiceAsyncStub(PipelineServiceStub):
|
||||
"""PipelineService coordinates movie download jobs, safety scans, and library relocation."""
|
||||
|
||||
def __init__(self, channel: _aio.Channel) -> None: ...
|
||||
SubmitDownload: _aio.UnaryUnaryMultiCallable[_pipeline_pb2.SubmitDownloadRequest, _pipeline_pb2.SubmitDownloadResponse] # type: ignore[assignment]
|
||||
"""SubmitDownload enqueues a new movie download job.
|
||||
Rejects duplicate submissions if an active job for the same IMDb ID or info_hash exists, or if already in library.
|
||||
"""
|
||||
GetJob: _aio.UnaryUnaryMultiCallable[_pipeline_pb2.GetJobRequest, _pipeline_pb2.GetJobResponse] # type: ignore[assignment]
|
||||
"""GetJob retrieves the current status and metadata of a specific job."""
|
||||
StreamJobStatus: _aio.UnaryStreamMultiCallable[_pipeline_pb2.StreamJobStatusRequest, _pipeline_pb2.StreamJobStatusResponse] # type: ignore[assignment]
|
||||
"""StreamJobStatus streams real-time status updates.
|
||||
Semantics: Emits an immediate snapshot of matching active jobs upon connection,
|
||||
followed by subsequent state and progress change events.
|
||||
"""
|
||||
ListJobs: _aio.UnaryUnaryMultiCallable[_pipeline_pb2.ListJobsRequest, _pipeline_pb2.ListJobsResponse] # type: ignore[assignment]
|
||||
"""ListJobs returns a paginated list of download jobs."""
|
||||
|
||||
class PipelineServiceServicer(metaclass=_abc_1.ABCMeta):
|
||||
"""PipelineService coordinates movie download jobs, safety scans, and library relocation."""
|
||||
|
||||
@_abc_1.abstractmethod
|
||||
def SubmitDownload(
|
||||
self,
|
||||
request: _pipeline_pb2.SubmitDownloadRequest,
|
||||
context: _ServicerContext,
|
||||
) -> _typing.Union[_pipeline_pb2.SubmitDownloadResponse, _abc.Awaitable[_pipeline_pb2.SubmitDownloadResponse]]:
|
||||
"""SubmitDownload enqueues a new movie download job.
|
||||
Rejects duplicate submissions if an active job for the same IMDb ID or info_hash exists, or if already in library.
|
||||
"""
|
||||
|
||||
@_abc_1.abstractmethod
|
||||
def GetJob(
|
||||
self,
|
||||
request: _pipeline_pb2.GetJobRequest,
|
||||
context: _ServicerContext,
|
||||
) -> _typing.Union[_pipeline_pb2.GetJobResponse, _abc.Awaitable[_pipeline_pb2.GetJobResponse]]:
|
||||
"""GetJob retrieves the current status and metadata of a specific job."""
|
||||
|
||||
@_abc_1.abstractmethod
|
||||
def StreamJobStatus(
|
||||
self,
|
||||
request: _pipeline_pb2.StreamJobStatusRequest,
|
||||
context: _ServicerContext,
|
||||
) -> _typing.Union[_abc.Iterator[_pipeline_pb2.StreamJobStatusResponse], _abc.AsyncIterator[_pipeline_pb2.StreamJobStatusResponse]]:
|
||||
"""StreamJobStatus streams real-time status updates.
|
||||
Semantics: Emits an immediate snapshot of matching active jobs upon connection,
|
||||
followed by subsequent state and progress change events.
|
||||
"""
|
||||
|
||||
@_abc_1.abstractmethod
|
||||
def ListJobs(
|
||||
self,
|
||||
request: _pipeline_pb2.ListJobsRequest,
|
||||
context: _ServicerContext,
|
||||
) -> _typing.Union[_pipeline_pb2.ListJobsResponse, _abc.Awaitable[_pipeline_pb2.ListJobsResponse]]:
|
||||
"""ListJobs returns a paginated list of download jobs."""
|
||||
|
||||
def add_PipelineServiceServicer_to_server(servicer: PipelineServiceServicer, server: _typing.Union[_grpc.Server, _aio.Server]) -> None: ...
|
||||
@@ -1,18 +1,32 @@
|
||||
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ENV UV_COMPILE_BYTECODE=1
|
||||
|
||||
# Copy workspace manifests and required packages so frozen lockfile resolution succeeds
|
||||
COPY pyproject.toml uv.lock ./
|
||||
COPY services/worker/pyproject.toml ./services/worker/
|
||||
COPY services/bff/pyproject.toml services/bff/README.md ./services/bff/
|
||||
COPY services/contracts ./services/contracts
|
||||
COPY services/worker ./services/worker
|
||||
|
||||
# Synchronize dependencies for worker package
|
||||
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
|
||||
WORKDIR /app
|
||||
|
||||
# Copy virtual environment and code
|
||||
COPY --from=builder /app/.venv /app/.venv
|
||||
COPY services/contracts/src ./services/contracts/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 PYTHONPATH="/app/services/worker/src"
|
||||
ENV PYTHONPATH="/app/services/worker/src:/app/services/contracts/src"
|
||||
ENV DATABASE_URL="sqlite+aiosqlite:////data/magnetflix.sqlite3"
|
||||
|
||||
EXPOSE 50051
|
||||
CMD ["python", "-m", "worker.main"]
|
||||
@@ -0,0 +1,3 @@
|
||||
# MagNetFlix Worker
|
||||
|
||||
gRPC Pipeline Worker and Transmission coordinator for MagNetFlix.
|
||||
@@ -0,0 +1,41 @@
|
||||
# A generic, single database configuration for worker container/package.
|
||||
|
||||
[alembic]
|
||||
script_location = %(here)s/alembic
|
||||
prepend_sys_path = src
|
||||
path_separator = os
|
||||
sqlalchemy.url = sqlite+aiosqlite:///data/magnetflix.sqlite3
|
||||
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
@@ -0,0 +1 @@
|
||||
Generic single-database configuration with an async dbapi.
|
||||
@@ -0,0 +1,84 @@
|
||||
import asyncio
|
||||
import os
|
||||
from logging.config import fileConfig
|
||||
from pathlib import Path
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import pool
|
||||
from sqlalchemy.engine import Connection
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
from worker.db.engine import normalize_database_url
|
||||
from worker.db.models import Base
|
||||
|
||||
config = context.config
|
||||
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def get_url() -> str:
|
||||
"""Retrieve normalized async database URL."""
|
||||
env_url = os.getenv("DATABASE_URL")
|
||||
ini_url = config.get_main_option("sqlalchemy.url")
|
||||
chosen = env_url or ini_url or "sqlite+aiosqlite:///data/magnetflix.sqlite3"
|
||||
url = normalize_database_url(chosen)
|
||||
|
||||
prefix = "sqlite+aiosqlite:///"
|
||||
if url.startswith(prefix):
|
||||
raw_path = url[len(prefix) :]
|
||||
if raw_path and raw_path != ":memory:":
|
||||
Path(raw_path).resolve().parent.mkdir(parents=True, exist_ok=True)
|
||||
return url
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""Run migrations in 'offline' mode."""
|
||||
url = get_url()
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
render_as_batch=True,
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def do_run_migrations(connection: Connection) -> None:
|
||||
"""Configure migration context on active connection."""
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=target_metadata,
|
||||
render_as_batch=True,
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
async def run_async_migrations() -> None:
|
||||
"""Run migrations asynchronously using an AsyncEngine."""
|
||||
connectable = create_async_engine(
|
||||
get_url(),
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
async with connectable.connect() as connection:
|
||||
await connection.run_sync(do_run_migrations)
|
||||
|
||||
await connectable.dispose()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""Run migrations in 'online' mode."""
|
||||
asyncio.run(run_async_migrations())
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,28 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -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")
|
||||
@@ -0,0 +1,64 @@
|
||||
"""create download_jobs table
|
||||
|
||||
Revision ID: 234da461ab5b
|
||||
Revises:
|
||||
Create Date: 2026-10-13 07:11:05.259836
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '234da461ab5b'
|
||||
down_revision: Union[str, Sequence[str], None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('download_jobs',
|
||||
sa.Column('id', sa.String(length=36), nullable=False),
|
||||
sa.Column('imdb_id', sa.String(length=32), nullable=False),
|
||||
sa.Column('title', sa.String(length=255), nullable=True),
|
||||
sa.Column('year', sa.Integer(), nullable=True),
|
||||
sa.Column('magnet_uri', sa.Text(), nullable=False),
|
||||
sa.Column('requested_by', sa.String(length=128), nullable=False),
|
||||
sa.Column('state', sa.String(length=32), nullable=False),
|
||||
sa.Column('progress_pct', sa.Float(), nullable=False),
|
||||
sa.Column('download_rate_bytes', sa.BigInteger(), nullable=False),
|
||||
sa.Column('error_message', sa.Text(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column('completed_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('download_jobs', schema=None) as batch_op:
|
||||
batch_op.create_index(
|
||||
batch_op.f('ix_download_jobs_imdb_id'), ['imdb_id'], unique=False
|
||||
)
|
||||
batch_op.create_index(
|
||||
batch_op.f('ix_download_jobs_requested_by'),
|
||||
['requested_by'],
|
||||
unique=False,
|
||||
)
|
||||
batch_op.create_index(
|
||||
batch_op.f('ix_download_jobs_state'), ['state'], unique=False
|
||||
)
|
||||
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('download_jobs', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_download_jobs_state'))
|
||||
batch_op.drop_index(batch_op.f('ix_download_jobs_requested_by'))
|
||||
batch_op.drop_index(batch_op.f('ix_download_jobs_imdb_id'))
|
||||
|
||||
op.drop_table('download_jobs')
|
||||
# ### end Alembic commands ###
|
||||
@@ -9,12 +9,22 @@ dependencies = [
|
||||
"alembic>=1.14.0",
|
||||
"httpx>=0.28.0",
|
||||
"grpcio>=1.83.1",
|
||||
"grpcio-health-checking>=1.83.1",
|
||||
"protobuf>=7.36.1",
|
||||
"pydantic>=2.10.0",
|
||||
"sqlalchemy>=2.0.36",
|
||||
"transmission-rpc>=7.0.11",
|
||||
"magnetflix-contracts",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
requires = ["uv_build>=0.12.5,<0.13.0"]
|
||||
build-backend = "uv_build"
|
||||
|
||||
[tool.uv.build-backend]
|
||||
module-name = "worker"
|
||||
module-root = "src"
|
||||
|
||||
[tool.uv.sources]
|
||||
magnetflix-contracts = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Database module for MagNetFlix worker service."""
|
||||
|
||||
from worker.db.engine import (
|
||||
DEFAULT_DATABASE_URL,
|
||||
configure_sqlite_pragmas,
|
||||
create_engine,
|
||||
get_db_session,
|
||||
get_engine,
|
||||
get_session_factory,
|
||||
normalize_database_url,
|
||||
verify_wal_mode,
|
||||
)
|
||||
from worker.db.models import (
|
||||
ALLOWED_TRANSITIONS,
|
||||
Base,
|
||||
DownloadJob,
|
||||
JobStateEnum,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"ALLOWED_TRANSITIONS",
|
||||
"Base",
|
||||
"DEFAULT_DATABASE_URL",
|
||||
"DownloadJob",
|
||||
"JobStateEnum",
|
||||
"configure_sqlite_pragmas",
|
||||
"create_engine",
|
||||
"get_db_session",
|
||||
"get_engine",
|
||||
"get_session_factory",
|
||||
"normalize_database_url",
|
||||
"verify_wal_mode",
|
||||
]
|
||||
@@ -0,0 +1,134 @@
|
||||
"""SQLAlchemy async database engine and session management with SQLite WAL mode."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections.abc import AsyncGenerator
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import event, text
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
AsyncEngine,
|
||||
AsyncSession,
|
||||
async_sessionmaker,
|
||||
create_async_engine,
|
||||
)
|
||||
|
||||
DEFAULT_DATABASE_URL = "sqlite+aiosqlite:///data/magnetflix.sqlite3"
|
||||
|
||||
|
||||
def normalize_database_url(url: str | None = None) -> str:
|
||||
"""Normalize database URL to use async aiosqlite driver for SQLite.
|
||||
|
||||
If given 'sqlite:////path', converts to 'sqlite+aiosqlite:////path'.
|
||||
"""
|
||||
raw_url = url or os.getenv("DATABASE_URL") or DEFAULT_DATABASE_URL
|
||||
if raw_url.startswith("sqlite://") and not raw_url.startswith("sqlite+aiosqlite://"):
|
||||
return raw_url.replace("sqlite://", "sqlite+aiosqlite://", 1)
|
||||
return raw_url
|
||||
|
||||
|
||||
def _ensure_sqlite_parent_dir(db_url: str) -> None:
|
||||
"""Ensure parent directory exists for file-based SQLite database."""
|
||||
if not db_url.startswith("sqlite"):
|
||||
return
|
||||
prefix = "sqlite+aiosqlite:///"
|
||||
if db_url.startswith(prefix):
|
||||
raw_path = db_url[len(prefix) :]
|
||||
if raw_path and raw_path != ":memory:":
|
||||
db_file = Path(raw_path).resolve()
|
||||
db_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
def configure_sqlite_pragmas(engine: AsyncEngine) -> None:
|
||||
"""Register SQLite PRAGMAs for WAL mode, foreign keys, and synchronous=NORMAL."""
|
||||
|
||||
@event.listens_for(engine.sync_engine, "connect")
|
||||
def set_sqlite_pragma(dbapi_connection: Any, connection_record: Any) -> None:
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA journal_mode=WAL;")
|
||||
cursor.execute("PRAGMA foreign_keys=ON;")
|
||||
cursor.execute("PRAGMA synchronous=NORMAL;")
|
||||
cursor.execute("PRAGMA busy_timeout=5000;")
|
||||
cursor.close()
|
||||
|
||||
|
||||
def create_engine(
|
||||
url: str | None = None, echo: bool = False
|
||||
) -> tuple[AsyncEngine, async_sessionmaker[AsyncSession]]:
|
||||
"""Create an AsyncEngine and async sessionmaker configured with WAL pragmas."""
|
||||
normalized_url = normalize_database_url(url)
|
||||
_ensure_sqlite_parent_dir(normalized_url)
|
||||
|
||||
engine = create_async_engine(
|
||||
normalized_url,
|
||||
echo=echo,
|
||||
future=True,
|
||||
)
|
||||
|
||||
if normalized_url.startswith("sqlite"):
|
||||
configure_sqlite_pragmas(engine)
|
||||
|
||||
session_factory = async_sessionmaker(
|
||||
bind=engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False,
|
||||
autocommit=False,
|
||||
autoflush=False,
|
||||
)
|
||||
|
||||
return engine, session_factory
|
||||
|
||||
|
||||
# Module-level default singleton engine and sessionmaker
|
||||
_engine: AsyncEngine | None = None
|
||||
_session_factory: async_sessionmaker[AsyncSession] | None = None
|
||||
|
||||
|
||||
def get_engine() -> AsyncEngine:
|
||||
"""Retrieve or initialize the global AsyncEngine instance."""
|
||||
global _engine, _session_factory
|
||||
if _engine is None:
|
||||
_engine, _session_factory = create_engine()
|
||||
return _engine
|
||||
|
||||
|
||||
def get_session_factory() -> async_sessionmaker[AsyncSession]:
|
||||
"""Retrieve or initialize the global async_sessionmaker instance."""
|
||||
global _engine, _session_factory
|
||||
if _session_factory is None:
|
||||
_engine, _session_factory = create_engine()
|
||||
return _session_factory
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
"""Provide a transactional async database session context."""
|
||||
factory = get_session_factory()
|
||||
async with factory() as session:
|
||||
try:
|
||||
yield session
|
||||
await session.commit()
|
||||
except Exception:
|
||||
await session.rollback()
|
||||
raise
|
||||
|
||||
|
||||
async def verify_wal_mode(session: AsyncSession) -> dict[str, Any]:
|
||||
"""Inspect and return active SQLite pragmas.
|
||||
|
||||
Queries journal_mode, foreign_keys, synchronous, and busy_timeout.
|
||||
"""
|
||||
jm_res = await session.execute(text("PRAGMA journal_mode;"))
|
||||
fk_res = await session.execute(text("PRAGMA foreign_keys;"))
|
||||
sync_res = await session.execute(text("PRAGMA synchronous;"))
|
||||
busy_res = await session.execute(text("PRAGMA busy_timeout;"))
|
||||
|
||||
return {
|
||||
"journal_mode": jm_res.scalar(),
|
||||
"foreign_keys": fk_res.scalar(),
|
||||
"synchronous": sync_res.scalar(),
|
||||
"busy_timeout": busy_res.scalar(),
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
"""SQLAlchemy ORM models for MagNetFlix download jobs and audit trail."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from enum import Enum
|
||||
from typing import Any
|
||||
|
||||
from google.protobuf.timestamp_pb2 import Timestamp
|
||||
from magnetflix.v1 import pipeline_pb2
|
||||
from sqlalchemy import BigInteger, DateTime, Float, Index, Integer, String, Text, text
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
"""Base declarative class for SQLAlchemy ORM models."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class JobStateEnum(str, Enum):
|
||||
"""Enumeration of valid lifecycle states for a download job."""
|
||||
|
||||
QUEUED = "QUEUED"
|
||||
DOWNLOADING = "DOWNLOADING"
|
||||
SCANNING = "SCANNING"
|
||||
VERIFYING_METADATA = "VERIFYING_METADATA"
|
||||
ORGANIZING = "ORGANIZING"
|
||||
COMPLETED = "COMPLETED"
|
||||
FAILED = "FAILED"
|
||||
|
||||
|
||||
# Valid forward state transitions in the pipeline
|
||||
ALLOWED_TRANSITIONS: dict[str, set[str]] = {
|
||||
JobStateEnum.QUEUED.value: {
|
||||
JobStateEnum.DOWNLOADING.value,
|
||||
JobStateEnum.FAILED.value,
|
||||
},
|
||||
JobStateEnum.DOWNLOADING.value: {
|
||||
JobStateEnum.SCANNING.value,
|
||||
JobStateEnum.FAILED.value,
|
||||
},
|
||||
JobStateEnum.SCANNING.value: {
|
||||
JobStateEnum.VERIFYING_METADATA.value,
|
||||
JobStateEnum.FAILED.value,
|
||||
},
|
||||
JobStateEnum.VERIFYING_METADATA.value: {
|
||||
JobStateEnum.ORGANIZING.value,
|
||||
JobStateEnum.FAILED.value,
|
||||
},
|
||||
JobStateEnum.ORGANIZING.value: {
|
||||
JobStateEnum.COMPLETED.value,
|
||||
JobStateEnum.FAILED.value,
|
||||
},
|
||||
JobStateEnum.COMPLETED.value: set(),
|
||||
JobStateEnum.FAILED.value: set(),
|
||||
}
|
||||
|
||||
PROTO_STATE_MAP = {
|
||||
JobStateEnum.QUEUED.value: pipeline_pb2.JOB_STATE_QUEUED,
|
||||
JobStateEnum.DOWNLOADING.value: pipeline_pb2.JOB_STATE_DOWNLOADING,
|
||||
JobStateEnum.SCANNING.value: pipeline_pb2.JOB_STATE_SCANNING,
|
||||
JobStateEnum.VERIFYING_METADATA.value: pipeline_pb2.JOB_STATE_VERIFYING_METADATA,
|
||||
JobStateEnum.ORGANIZING.value: pipeline_pb2.JOB_STATE_ORGANIZING,
|
||||
JobStateEnum.COMPLETED.value: pipeline_pb2.JOB_STATE_COMPLETED,
|
||||
JobStateEnum.FAILED.value: pipeline_pb2.JOB_STATE_FAILED,
|
||||
}
|
||||
|
||||
|
||||
def _datetime_to_timestamp(dt: datetime | None) -> Timestamp:
|
||||
"""Convert Python datetime to Google Protobuf Timestamp."""
|
||||
ts = Timestamp()
|
||||
if dt is not None:
|
||||
ts.FromDatetime(dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc))
|
||||
return ts
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
"""Return timezone-aware current UTC datetime."""
|
||||
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):
|
||||
"""ORM model representing an acquisition and relocation pipeline job."""
|
||||
|
||||
__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(
|
||||
String(36),
|
||||
primary_key=True,
|
||||
default=lambda: str(uuid.uuid4()),
|
||||
doc="Unique UUID primary key",
|
||||
)
|
||||
imdb_id: Mapped[str] = mapped_column(
|
||||
String(32),
|
||||
nullable=False,
|
||||
index=True,
|
||||
doc="IMDb identifier (e.g. tt1375666)",
|
||||
)
|
||||
title: Mapped[str | None] = mapped_column(
|
||||
String(255),
|
||||
nullable=True,
|
||||
doc="Canonical movie title resolved from TMDB",
|
||||
)
|
||||
year: Mapped[int | None] = mapped_column(
|
||||
Integer,
|
||||
nullable=True,
|
||||
doc="Release year resolved from TMDB",
|
||||
)
|
||||
magnet_uri: Mapped[str] = mapped_column(
|
||||
Text,
|
||||
nullable=False,
|
||||
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(
|
||||
String(128),
|
||||
nullable=False,
|
||||
index=True,
|
||||
doc="Authenticated user from upstream SSO identity header",
|
||||
)
|
||||
state: Mapped[str] = mapped_column(
|
||||
String(32),
|
||||
nullable=False,
|
||||
default=JobStateEnum.QUEUED.value,
|
||||
index=True,
|
||||
doc="Current pipeline lifecycle state",
|
||||
)
|
||||
progress_pct: Mapped[float] = mapped_column(
|
||||
Float,
|
||||
nullable=False,
|
||||
default=0.0,
|
||||
doc="Download progress percentage (0.0 to 100.0)",
|
||||
)
|
||||
download_rate_bytes: Mapped[int] = mapped_column(
|
||||
BigInteger,
|
||||
nullable=False,
|
||||
default=0,
|
||||
doc="Download rate in bytes/sec",
|
||||
)
|
||||
error_message: Mapped[str] = mapped_column(
|
||||
Text,
|
||||
nullable=False,
|
||||
default="",
|
||||
doc="Terminal error description if state is FAILED",
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
nullable=False,
|
||||
default=utc_now,
|
||||
doc="UTC timestamp when job was enqueued",
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
nullable=False,
|
||||
default=utc_now,
|
||||
onupdate=utc_now,
|
||||
doc="UTC timestamp when job status was last updated",
|
||||
)
|
||||
completed_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
nullable=True,
|
||||
doc="UTC timestamp when job transitioned to terminal COMPLETED or FAILED",
|
||||
)
|
||||
|
||||
def __init__(self, **kwargs: Any) -> None:
|
||||
"""Initialize DownloadJob with default field values."""
|
||||
if "id" not in kwargs:
|
||||
kwargs["id"] = str(uuid.uuid4())
|
||||
if "state" not in kwargs:
|
||||
kwargs["state"] = JobStateEnum.QUEUED.value
|
||||
if "progress_pct" not in kwargs:
|
||||
kwargs["progress_pct"] = 0.0
|
||||
if "download_rate_bytes" not in kwargs:
|
||||
kwargs["download_rate_bytes"] = 0
|
||||
if "error_message" not in kwargs:
|
||||
kwargs["error_message"] = ""
|
||||
if "created_at" not in kwargs:
|
||||
kwargs["created_at"] = utc_now()
|
||||
if "updated_at" not in kwargs:
|
||||
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)
|
||||
|
||||
@property
|
||||
def is_terminal(self) -> bool:
|
||||
"""Return True if the job is in a terminal state (COMPLETED or FAILED)."""
|
||||
return self.state in (JobStateEnum.COMPLETED.value, JobStateEnum.FAILED.value)
|
||||
|
||||
def transition_to(
|
||||
self,
|
||||
new_state: JobStateEnum | str,
|
||||
error_message: str | None = None,
|
||||
) -> None:
|
||||
"""Safely transition job state following the state machine invariants.
|
||||
|
||||
Raises:
|
||||
ValueError: If the requested state transition is invalid.
|
||||
"""
|
||||
target = new_state.value if isinstance(new_state, JobStateEnum) else new_state
|
||||
allowed = ALLOWED_TRANSITIONS.get(self.state, set())
|
||||
|
||||
if target not in allowed:
|
||||
raise ValueError(
|
||||
f"Invalid state transition from '{self.state}' to '{target}'. "
|
||||
f"Allowed transitions: {allowed}"
|
||||
)
|
||||
|
||||
self.state = target
|
||||
self.updated_at = utc_now()
|
||||
|
||||
if error_message is not None:
|
||||
self.error_message = error_message
|
||||
|
||||
if self.is_terminal and self.completed_at is None:
|
||||
self.completed_at = utc_now()
|
||||
|
||||
def to_proto(self) -> pipeline_pb2.JobStatus:
|
||||
"""Convert ORM model instance into a Protobuf JobStatus message."""
|
||||
proto_state = PROTO_STATE_MAP.get(
|
||||
self.state, pipeline_pb2.JOB_STATE_UNSPECIFIED
|
||||
)
|
||||
|
||||
return pipeline_pb2.JobStatus(
|
||||
job_id=self.id,
|
||||
imdb_id=self.imdb_id,
|
||||
title=self.title or "",
|
||||
year=self.year or 0,
|
||||
requested_by=self.requested_by,
|
||||
state=proto_state,
|
||||
progress_pct=self.progress_pct,
|
||||
download_rate_bytes=self.download_rate_bytes,
|
||||
error_message=self.error_message,
|
||||
created_at=_datetime_to_timestamp(self.created_at),
|
||||
updated_at=_datetime_to_timestamp(self.updated_at),
|
||||
completed_at=_datetime_to_timestamp(self.completed_at),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Convert ORM model to dictionary."""
|
||||
return {
|
||||
"id": self.id,
|
||||
"imdb_id": self.imdb_id,
|
||||
"title": self.title,
|
||||
"year": self.year,
|
||||
"magnet_uri": self.magnet_uri,
|
||||
"info_hash": self.info_hash,
|
||||
"requested_by": self.requested_by,
|
||||
"state": self.state,
|
||||
"progress_pct": self.progress_pct,
|
||||
"download_rate_bytes": self.download_rate_bytes,
|
||||
"error_message": self.error_message,
|
||||
"created_at": (self.created_at.isoformat() if self.created_at else None),
|
||||
"updated_at": (self.updated_at.isoformat() if self.updated_at else None),
|
||||
"completed_at": (
|
||||
self.completed_at.isoformat() if self.completed_at else None
|
||||
),
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Unit and contract seam tests for generated Protobuf and gRPC stubs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def test_protobuf_and_grpc_stubs_importable():
|
||||
"""Verify that both pipeline_pb2 and pipeline_pb2_grpc import cleanly."""
|
||||
from magnetflix.v1 import pipeline_pb2, pipeline_pb2_grpc
|
||||
|
||||
assert pipeline_pb2.JOB_STATE_QUEUED == 1
|
||||
assert pipeline_pb2.JOB_STATE_DOWNLOADING == 2
|
||||
assert hasattr(pipeline_pb2_grpc, "PipelineServiceServicer")
|
||||
assert hasattr(pipeline_pb2_grpc, "PipelineServiceStub")
|
||||
|
||||
|
||||
def test_proto_job_status_creation():
|
||||
"""Verify that JobStatus protobuf message instantiates and serializes."""
|
||||
from google.protobuf.timestamp_pb2 import Timestamp
|
||||
from magnetflix.v1 import pipeline_pb2
|
||||
|
||||
ts = Timestamp()
|
||||
ts.GetCurrentTime()
|
||||
|
||||
status = pipeline_pb2.JobStatus(
|
||||
job_id="test-job-123",
|
||||
imdb_id="tt1375666",
|
||||
title="Inception",
|
||||
year=2010,
|
||||
requested_by="alice",
|
||||
state=pipeline_pb2.JOB_STATE_QUEUED,
|
||||
progress_pct=0.0,
|
||||
download_rate_bytes=0,
|
||||
error_message="",
|
||||
created_at=ts,
|
||||
)
|
||||
|
||||
assert status.job_id == "test-job-123"
|
||||
assert status.title == "Inception"
|
||||
serialized = status.SerializeToString()
|
||||
assert len(serialized) > 0
|
||||
|
||||
deserialized = pipeline_pb2.JobStatus()
|
||||
deserialized.ParseFromString(serialized)
|
||||
assert deserialized.imdb_id == "tt1375666"
|
||||
@@ -0,0 +1,314 @@
|
||||
"""Unit tests for SQLite WAL engine, ORM models, and CRUD operations."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from magnetflix.v1 import pipeline_pb2
|
||||
from sqlalchemy import select
|
||||
from worker.db import (
|
||||
Base,
|
||||
DownloadJob,
|
||||
JobStateEnum,
|
||||
create_engine,
|
||||
verify_wal_mode,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def temp_db():
|
||||
"""Create a temporary SQLite database file with WAL pragmas."""
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
db_path = Path(tmpdir) / "test_magnetflix.sqlite3"
|
||||
db_url = f"sqlite+aiosqlite:///{db_path}"
|
||||
engine, session_factory = create_engine(db_url)
|
||||
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
|
||||
yield session_factory, engine
|
||||
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sqlite_wal_pragmas(temp_db):
|
||||
"""Verify that SQLite engine automatically configures WAL mode and pragmas."""
|
||||
session_factory, _ = temp_db
|
||||
|
||||
async with session_factory() as session:
|
||||
pragmas = await verify_wal_mode(session)
|
||||
|
||||
assert pragmas["journal_mode"].lower() == "wal"
|
||||
assert pragmas["foreign_keys"] == 1
|
||||
assert pragmas["synchronous"] == 1 # 1 = NORMAL
|
||||
assert pragmas["busy_timeout"] == 5000
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_job_crud(temp_db):
|
||||
"""Test creating, reading, and updating a DownloadJob in SQLite."""
|
||||
session_factory, _ = temp_db
|
||||
|
||||
# 1. Create Job
|
||||
job = DownloadJob(
|
||||
imdb_id="tt1375666",
|
||||
magnet_uri="magnet:?xt=urn:btih:dummy123",
|
||||
requested_by="alice",
|
||||
)
|
||||
|
||||
async with session_factory() as session:
|
||||
session.add(job)
|
||||
await session.commit()
|
||||
job_id = job.id
|
||||
|
||||
assert job_id is not None
|
||||
|
||||
# 2. Read Job
|
||||
async with session_factory() as session:
|
||||
result = await session.execute(
|
||||
select(DownloadJob).where(DownloadJob.id == job_id)
|
||||
)
|
||||
saved = result.scalar_one()
|
||||
|
||||
assert saved.imdb_id == "tt1375666"
|
||||
assert saved.magnet_uri == "magnet:?xt=urn:btih:dummy123"
|
||||
assert saved.requested_by == "alice"
|
||||
assert saved.state == JobStateEnum.QUEUED.value
|
||||
assert saved.progress_pct == 0.0
|
||||
assert saved.download_rate_bytes == 0
|
||||
assert saved.error_message == ""
|
||||
assert saved.title is None
|
||||
assert saved.year is None
|
||||
assert saved.created_at is not None
|
||||
assert saved.updated_at is not None
|
||||
assert saved.completed_at is None
|
||||
assert saved.is_terminal is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_job_to_proto(temp_db):
|
||||
"""Test converting a DownloadJob ORM model to a Protobuf JobStatus message."""
|
||||
session_factory, _ = temp_db
|
||||
|
||||
job = DownloadJob(
|
||||
imdb_id="tt1375666",
|
||||
title="Inception",
|
||||
year=2010,
|
||||
magnet_uri="magnet:?xt=urn:btih:dummy123",
|
||||
requested_by="alice",
|
||||
progress_pct=42.5,
|
||||
download_rate_bytes=5242880,
|
||||
)
|
||||
|
||||
async with session_factory() as session:
|
||||
session.add(job)
|
||||
await session.commit()
|
||||
|
||||
proto = job.to_proto()
|
||||
assert isinstance(proto, pipeline_pb2.JobStatus)
|
||||
assert proto.job_id == job.id
|
||||
assert proto.imdb_id == "tt1375666"
|
||||
assert proto.title == "Inception"
|
||||
assert proto.year == 2010
|
||||
assert proto.requested_by == "alice"
|
||||
assert proto.state == pipeline_pb2.JOB_STATE_QUEUED
|
||||
assert abs(proto.progress_pct - 42.5) < 0.01
|
||||
assert proto.download_rate_bytes == 5242880
|
||||
assert proto.error_message == ""
|
||||
assert proto.created_at.seconds > 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_job_state_transitions(temp_db):
|
||||
"""Test state machine progression and terminal state invariants."""
|
||||
session_factory, _ = temp_db
|
||||
|
||||
job = DownloadJob(
|
||||
imdb_id="tt0111161",
|
||||
magnet_uri="magnet:?xt=urn:btih:shawshank",
|
||||
requested_by="bob",
|
||||
)
|
||||
|
||||
# 1. Valid Linear Progression:
|
||||
# QUEUED -> DOWNLOADING -> SCANNING -> VERIFYING_METADATA -> ORGANIZING -> COMPLETED
|
||||
job.transition_to(JobStateEnum.DOWNLOADING)
|
||||
assert job.state == JobStateEnum.DOWNLOADING.value
|
||||
assert job.completed_at is None
|
||||
|
||||
job.transition_to(JobStateEnum.SCANNING)
|
||||
assert job.state == JobStateEnum.SCANNING.value
|
||||
|
||||
job.transition_to(JobStateEnum.VERIFYING_METADATA)
|
||||
assert job.state == JobStateEnum.VERIFYING_METADATA.value
|
||||
|
||||
job.transition_to(JobStateEnum.ORGANIZING)
|
||||
assert job.state == JobStateEnum.ORGANIZING.value
|
||||
|
||||
job.transition_to(JobStateEnum.COMPLETED)
|
||||
assert job.state == JobStateEnum.COMPLETED.value
|
||||
assert job.is_terminal is True
|
||||
assert job.completed_at is not None
|
||||
|
||||
# 2. Cannot transition out of terminal COMPLETED
|
||||
with pytest.raises(ValueError, match="Invalid state transition"):
|
||||
job.transition_to(JobStateEnum.DOWNLOADING)
|
||||
|
||||
# 3. Direct failure transition from non-terminal state
|
||||
job_failing = DownloadJob(
|
||||
imdb_id="tt0068646",
|
||||
magnet_uri="magnet:?xt=urn:btih:godfather",
|
||||
requested_by="charlie",
|
||||
)
|
||||
job_failing.transition_to(JobStateEnum.FAILED, error_message="Tracker timed out")
|
||||
assert job_failing.state == JobStateEnum.FAILED.value
|
||||
assert job_failing.error_message == "Tracker timed out"
|
||||
assert job_failing.is_terminal is True
|
||||
assert job_failing.completed_at is not None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_active_job_idempotency_query(temp_db):
|
||||
"""Test querying active non-terminal jobs for duplicate rejection."""
|
||||
session_factory, _ = temp_db
|
||||
|
||||
active_job = DownloadJob(
|
||||
imdb_id="tt1375666",
|
||||
magnet_uri="magnet:?xt=urn:btih:inception",
|
||||
requested_by="alice",
|
||||
state=JobStateEnum.DOWNLOADING.value,
|
||||
)
|
||||
completed_job = DownloadJob(
|
||||
imdb_id="tt0111161",
|
||||
magnet_uri="magnet:?xt=urn:btih:shawshank",
|
||||
requested_by="bob",
|
||||
state=JobStateEnum.COMPLETED.value,
|
||||
)
|
||||
|
||||
async with session_factory() as session:
|
||||
session.add_all([active_job, completed_job])
|
||||
await session.commit()
|
||||
|
||||
# Query for active job with tt1375666
|
||||
terminal_states = [JobStateEnum.COMPLETED.value, JobStateEnum.FAILED.value]
|
||||
stmt = (
|
||||
select(DownloadJob)
|
||||
.where(DownloadJob.imdb_id == "tt1375666")
|
||||
.where(DownloadJob.state.not_in(terminal_states))
|
||||
)
|
||||
res = await session.execute(stmt)
|
||||
found_active = res.scalar_one_or_none()
|
||||
assert found_active is not None
|
||||
assert found_active.id == active_job.id
|
||||
|
||||
# Query for active job with tt0111161 (should be None because it's COMPLETED)
|
||||
stmt_comp = (
|
||||
select(DownloadJob)
|
||||
.where(DownloadJob.imdb_id == "tt0111161")
|
||||
.where(DownloadJob.state.not_in(terminal_states))
|
||||
)
|
||||
res_comp = await session.execute(stmt_comp)
|
||||
found_completed = res_comp.scalar_one_or_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,20 +1,22 @@
|
||||
(A) Create SQLAlchemy async engine with SQLite WAL mode pragmas in services/worker/src/worker/db/engine.py +db @worker
|
||||
(A) Define DownloadJob ORM model in services/worker/src/worker/db/models.py (id, imdb_id, title, year, magnet_uri, requested_by, status, progress_pct, download_rate_bytes, error_message, created_at, updated_at, completed_at) +db @worker
|
||||
(A) Initialize Alembic in services/worker/ and create initial migration for download_jobs table +db @worker
|
||||
(A) Write unit tests for DB connection, WAL pragma verification, and CRUD operations in tests/test_db.py +test @worker
|
||||
(B) Implement symlink & path-traversal blocker in services/worker/src/worker/sanitizer.py +sanitizer @worker
|
||||
(B) Implement file allowlist filtering (video: .mkv, .mp4, .avi, .webm; subtitles: .srt, .vtt, .sub, .ass) +sanitizer @worker
|
||||
(B) Implement sample discard (<100MB / 'sample' keyword) and largest primary video selector in sanitizer.py +sanitizer @worker
|
||||
(B) Write comprehensive unit tests in tests/test_sanitizer.py covering allowlist, symlinks, sample filtering, and largest video selection +test @worker
|
||||
(B) Implement async TMDB client querying /find/{imdb_id}?external_source=imdb_id in services/worker/src/worker/metadata.py +metadata @worker
|
||||
(B) Implement normalized token overlap verification between TMDB title/year and torrent/file names in metadata.py +metadata @worker
|
||||
(B) Write unit tests with mocked TMDB responses in tests/test_metadata.py verifying successful match and mismatch rejection +test @worker
|
||||
(C) Implement Transmission client wrapper in services/worker/src/worker/transmission.py (add_torrent to /data/staging/<job_id>, poll progress, remove_torrent) +transmission @worker
|
||||
(C) Write unit tests with mocked transmission-rpc client in tests/test_transmission.py +test @worker
|
||||
(C) Implement directory creator and atomic file mover in services/worker/src/worker/relocator.py (/media/movies/<Title> (<Year>) [imdbid-<IMDbID>]/) +relocator @worker
|
||||
(C) Implement subtitle renaming and staging cleanup in relocator.py +relocator @worker
|
||||
(C) Write unit tests in tests/test_relocator.py testing destination directory formatting, subtitle moving, and scratch cleanup +test @worker
|
||||
(D) Implement pipeline state machine coordinator (QUEUED -> DOWNLOADING -> SCANNING -> VERIFYING_METADATA -> ORGANIZING -> COMPLETED/FAILED) in services/worker/src/worker/pipeline.py +pipeline @worker
|
||||
(D) Implement startup crash recovery to auto-fail orphaned non-terminal jobs on worker start in pipeline.py +pipeline @worker
|
||||
(D) Implement gRPC PipelineServiceServicer in services/worker/src/worker/service.py (SubmitDownload, GetJob, StreamJobStatus, ListJobs) +grpc @worker
|
||||
(D) Write integration tests in tests/test_grpc_service.py verifying duplicate rejection, job submission, status querying, and pagination +test @worker
|
||||
# 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) 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 pyproject.toml to include tests/ in pyright, remove exclusions masking broken imports, and add test rule to Makefile +ci @workspace
|
||||
x 2026-10-31 (A) Update services/worker/Dockerfile and services/bff/Dockerfile to copy services/contracts, and copy alembic/ into worker image +docker @deploy
|
||||
x 2026-10-31 (A) 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
|
||||
|
||||
# Next Immediate Deliverable — Milestone 2: Safe Walking Skeleton MVP (See docs/roadmap.md for M3-M5)
|
||||
(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
|
||||
(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) [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) [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) [M2.2] Write unit tests in tests/test_metadata.py and tests/test_relocator.py +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
|
||||
(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
|
||||
(B) [M2.3] Write tests in tests/test_transmission.py, tests/test_pipeline.py, and tests/test_grpc_service.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
|
||||
(B) [M2.4] Write API tests in tests/test_bff_routes.py +test @bff
|
||||
(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
|
||||
@@ -5,6 +5,7 @@ requires-python = ">=3.12"
|
||||
[manifest]
|
||||
members = [
|
||||
"magnetflix-bff",
|
||||
"magnetflix-contracts",
|
||||
"magnetflix-worker",
|
||||
"magnetflix-workspace",
|
||||
]
|
||||
@@ -65,11 +66,11 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "certifi"
|
||||
version = "2026.7.22"
|
||||
version = "2026.10.23"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -306,43 +307,66 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "grpcio"
|
||||
version = "1.83.1"
|
||||
version = "1.85.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/e2/b1/46539f5050d7c316a13396d185451f95084a74ddc68b12d818595bef0377/grpcio-1.83.1.tar.gz", hash = "sha256:9cee6fcbf2eb57c4b49451787bfa87be8efc1ca02a0b327dd4b54d44502e362b", size = 13445033, upload-time = "2026-08-28T07:09:11.464Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/f0/03/f9e805772d4d01da2a1754a5f63c58601eacaf8f1e878729217188de7d16/grpcio-1.85.1.tar.gz", hash = "sha256:5f530287d5de5f7f66089ead81de44f6787162944dab3922efa65dfdff108a1d", size = 14091456, upload-time = "2026-10-30T16:01:16.909Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/85/9e/a3ba13e08bbee5bf6e57597dfe4823961fd7e94c0b8afe3a4bb7dca639f3/grpcio-1.83.1-cp312-cp312-linux_armv7l.whl", hash = "sha256:5acd14c6ddf047de62cbf8745b11103ea91abbf57d1b8edd5395ccd9fcd13abb", size = 6303170, upload-time = "2026-08-28T07:08:08.188Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1c/ae/65ce56a2527faa17d02cba4c2231c74047ad898be339486ba87f093bfb66/grpcio-1.83.1-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:16138031a47b771860a16a975b53087f4fd5bbdbb2c03a188c5d90ad65d2bdae", size = 12165806, upload-time = "2026-08-28T07:08:10.309Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4e/91/40432480088a2243d360864de072ed5b78c4ebbaabd29c28918f1e1b1454/grpcio-1.83.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5ccc26715fd4defca5e129e280dd883b1737b65045ec50ffe22ce42104089519", size = 6872490, upload-time = "2026-08-28T07:08:12.355Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c8/62/3da2300c8c79fd20a78a8a4bb6251e5068d9af33bc8fd389b98fec35e8a3/grpcio-1.83.1-cp312-cp312-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:b74f2a1d9ab1dfa3e263ef33d581613679b78d0884babf11671af26e45570ead", size = 7618367, upload-time = "2026-08-28T07:08:14.025Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bc/19/9fc702e31a631262d7a752fa699f6022821e707fefc8bff49b1550a57729/grpcio-1.83.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:72578aa07a4008f17521ef52debcc3acfd1e2c5426243bc3ffb56a38bfe610b7", size = 7040936, upload-time = "2026-08-28T07:08:15.963Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ec/56/95933cc44cba2429765fa065c951dd529e5771b119d9d2481b4646f1d6a5/grpcio-1.83.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c12e1fc59c6dc26d10d9144453ddc6cbfe4cd4c31e874ed2d0132f88e685eb8b", size = 7573096, upload-time = "2026-08-28T07:08:17.729Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ac/80/af63359da06b016de48cb111f144703a10043850dafa43ae0a038907b9e8/grpcio-1.83.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:4910b62f7d12197160bfb7de06d876d64dd12d43483e8292f98f49ca09b628d9", size = 8609442, upload-time = "2026-08-28T07:08:19.777Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3d/fa/f0586c56bdfb8a7a2adda01e0ac2413447cde3141ab09411a5d5afdcffd3/grpcio-1.83.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:9e703effe3ae779925c82ac24fdb82cf4105e1096810151ed9501c5f34546b9c", size = 7984321, upload-time = "2026-08-28T07:08:22.114Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/25/8a/14ec05669f9eb295801e26c2ea8c561a1b786b0e3557c2c22131165ab010/grpcio-1.83.1-cp312-cp312-win32.whl", hash = "sha256:a2aea8bd6e0a34f12cbaddb7bb70bec836818789fa5c7ab7572c6b745396a2d4", size = 4395604, upload-time = "2026-08-28T07:08:24.08Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e9/37/8c2f7cc16089e36a3fbacaacc7a3d043912aa0d2dfae5556f6450414ea6e/grpcio-1.83.1-cp312-cp312-win_amd64.whl", hash = "sha256:583bf2e8255040a4a312f9572dfe62a05271437b149550e1a536d5c47d2d1e8a", size = 5161512, upload-time = "2026-08-28T07:08:25.81Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7c/fd/d1fc58933bf88c9209f89dc570c810f1aa57cb04b3459cf2b26f61e32112/grpcio-1.83.1-cp313-cp313-linux_armv7l.whl", hash = "sha256:8d228e253b77865efcbdd7b5894ca882c9e0ea98c02b7d20582e61ded8dfd4b5", size = 6305628, upload-time = "2026-08-28T07:08:27.872Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c4/49/0b40bae059c619505c9b751cee6caa208e4904e290aaefa1728c4c2c67a5/grpcio-1.83.1-cp313-cp313-macosx_11_0_universal2.whl", hash = "sha256:0468b627f2987c9a77f7580030207cbd85457ffe52998beff4f0b5c38c58a72c", size = 12156839, upload-time = "2026-08-28T07:08:30.191Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/61/4b/e8c0d635da0ee5ddd9950c8d540f5dcdd0ef1854a382cc55496a487a8d31/grpcio-1.83.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:a6a282e81530cead60bbd752cc04950a57f224379e9821495d6a35bd5ce9b1f4", size = 6877036, upload-time = "2026-08-28T07:08:32.285Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c5/d4/760a33f339a7dd3d5f4b3e0e9bec5472d95592a80f887b2e9dab4e41cfbc/grpcio-1.83.1-cp313-cp313-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:947d945f52e8ecf3cafd2bb7113502a16ccfda3e12c854443094de32d83ad432", size = 7624404, upload-time = "2026-08-28T07:08:34.194Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/54/ec/bd798654b06fb42a92b57d1dc1b530084fa89ed442806fcd0a833a36f9b3/grpcio-1.83.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:55656318d5dd387077396dffb929171ca3966e24bfead9a6c5dba9f889062cb4", size = 7042942, upload-time = "2026-08-28T07:08:36.208Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/08/b0/c00f86614566dd0961825cf0f43d4f96a74371d9d95f952bcbc4b86d9a27/grpcio-1.83.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:9daf5acf4fc9d5f5627229969c2580a91e511779d76e4ccdeb9f4770f05d8bc2", size = 7576937, upload-time = "2026-08-28T07:08:38.041Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b1/38/85eff43a5c89dc666a252b5c9f8e9ab03f89e11c95b6263d2933f08fdbe7/grpcio-1.83.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:7b94174cbca93316888f805efbeb08f1c020f7b7493d2d50cc4f6b64ebb7e8bd", size = 8608391, upload-time = "2026-08-28T07:08:40.092Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/35/4e/82835483e2f812494be865e7965c0d626cb9e71ab0d83a420d75aea4ad67/grpcio-1.83.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:65c5a7210911ffe0f67b1cdc5308f9854b6d1f1b345e3e49ab7cac1ba50fa346", size = 7980060, upload-time = "2026-08-28T07:08:42.434Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b2/b7/68a98bef733fef704fbcfb3957c8dba67e3e38ca7a7fea851195bc97c648/grpcio-1.83.1-cp313-cp313-win32.whl", hash = "sha256:179368d9361854616ce6f397d4716e07480129652752fcbcfc5a7260455ad6f2", size = 4395226, upload-time = "2026-08-28T07:08:44.463Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/85/a0/df4de3b51d37ac8fb0320bb9668381ce2bd3b7aa990880bfc56a8a26f665/grpcio-1.83.1-cp313-cp313-win_amd64.whl", hash = "sha256:2e57af456385491a76e13c4aada8c8f43a8e47051e06ea97a9dbe2a49654e6db", size = 5160273, upload-time = "2026-08-28T07:08:46.216Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/42/9c/484d981d8b90c4e6abf3030bd2ed747e84d1eb192b3ec9cbb41e0b73e4bf/grpcio-1.83.1-cp314-cp314-linux_armv7l.whl", hash = "sha256:8b3c87ca908296bf125f841d3e1a2225a2b39aaa8ed7a57e7ccde465ee519bab", size = 6306089, upload-time = "2026-08-28T07:08:48.379Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/84/01/0afec1c92e4f292f74a44ecf75eabbf40903125b8c4df103c9868d6338da/grpcio-1.83.1-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:c0f3f20c90e72a171917ae65706500b096a1c3eb5f162c3ce702a2e25635f132", size = 12170381, upload-time = "2026-08-28T07:08:50.653Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c7/5a/e9a2383804433a0a61d6d93777ad321c7f36ac1cfdaa4c6d1a7c9ac846b7/grpcio-1.83.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:81bbf35a46bf8cad2dfbb2eccc19c711befb58b288acb534bbcd0d74283202a6", size = 6883286, upload-time = "2026-08-28T07:08:53.654Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/63/e7/f8ca8f76994e14c70b9a0052e82f10de497a23db450c36379c9716ebfc4d/grpcio-1.83.1-cp314-cp314-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:215cec07d11176507387bda4bf2751816e880f9bff8dc1ca524bfbb8ed8f2fad", size = 7624293, upload-time = "2026-08-28T07:08:55.709Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bb/7a/4b672814b0cd0fe63bdd735379d88b165759f3144ab023ad8ec5fc4d53ac/grpcio-1.83.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:abce7d43ec29cd39230fa8339de1a07643b55adc412a454850fbd875349950ff", size = 7044346, upload-time = "2026-08-28T07:08:57.802Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/50/b8/d89fe60e4239ad51be333dd9cc703741d449a35064e51f8a0b5bfa755432/grpcio-1.83.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:e256f95a40e3b0183a98556fb7164d24b97eeb353123ccabfcba94712b35ee2a", size = 7584187, upload-time = "2026-08-28T07:08:59.867Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/dc/b2/b290d7402633d9166e4dd47e6f5f74a24ce10a8340b84455896ebc349f85/grpcio-1.83.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:2110059146fb0ea216e1ffddb29377b5cc2fd412a5b0a92e102616bd5edf18c2", size = 8608730, upload-time = "2026-08-28T07:09:02.592Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f5/44/fa89e44d1b5cf5b9fa71b2fd7abf506f182fd43917231a92fbf1ea326b02/grpcio-1.83.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:20d944d967843f8183f9f23d5916388362e5f8eeeae855bbe4354d906dc9f31b", size = 7983283, upload-time = "2026-08-28T07:09:05.087Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ce/b8/9db73ed1f35ffa76124ac574bf296d06a359798dfd6b50d382f2b8a060a1/grpcio-1.83.1-cp314-cp314-win32.whl", hash = "sha256:623c87c6d4a1cb30d82c4e896f95477050f2e01b4a1f8cf91ff2b1abdf89c457", size = 4474327, upload-time = "2026-08-28T07:09:07.179Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/65/22/fc9a622d885a7a37ff972a12faaef443d74e47407181da70d0ab62ab41f0/grpcio-1.83.1-cp314-cp314-win_amd64.whl", hash = "sha256:47e6934ad38779271e2e7cc5f78a63a407cf3d98114c65c1fdbcd3f5a716f29b", size = 5302032, upload-time = "2026-08-28T07:09:09.285Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/31/8c/b6d9ea0bf02a6b47ba34c5f936da2921d76f5e40cbb411e9abb246b70d2d/grpcio-1.85.1-cp312-cp312-linux_armv7l.whl", hash = "sha256:1a10d337967ec2be049c6a2345320f6a59f71bf9f54febfd80e5a966cffaa945", size = 6797195, upload-time = "2026-10-30T15:59:35.364Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c6/ee/f60cfacd679fe811944be391c899955c3d9c7e07db922b47e535ddda550c/grpcio-1.85.1-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:658a9d89c5736bf4aa3ef4ecbc79528e26d8e23c5e1c83417d2870a1a06063e5", size = 12633025, upload-time = "2026-10-30T15:59:37.66Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f1/0d/5dbe225f0ceb208538dc8c16c5f52b0c402b91611f981604b5e280439dfb/grpcio-1.85.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:843aa281a48188621f50880496d35defed51298bcb66d5345d5f282fd3f87354", size = 7170616, upload-time = "2026-10-30T15:59:40.138Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/54/35/ce972a4e5bb721ba85f5c9e20a0029253ae0b2deb5276dafa3383e025133/grpcio-1.85.1-cp312-cp312-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:e768556a2346d1d2921f511f3145e2462e4fe68095c31e4db407558bcd3f1d4f", size = 8180786, upload-time = "2026-10-30T15:59:42.7Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/00/8d/74a8649d2787dae0a661855cdf09a8e2238fa741689bb368ca1b4f6d5b6f/grpcio-1.85.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a1a72d19c0ab84b4b73b6c47eeaade76d84b1973a51593ff1160a73df33d03d9", size = 7362744, upload-time = "2026-10-30T15:59:45.076Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/03/72/87ef13aba6bd2c5c6d4c5117238b17b1e3c1c1efa26c66cb377053124eb7/grpcio-1.85.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:0e07f477e1d1a05bdbe71d63add964c5457e7ab2e3f5fd32859639ed8ecb976e", size = 7929643, upload-time = "2026-10-30T15:59:47.294Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/09/f1/2e75b2906c9643e0be81a74bf23ae10c29661e0199c8f3a6e2c23707e882/grpcio-1.85.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:b2846c70ed58c8e149e8e5d867af40805a13b151d84157d8272952d711a77c5c", size = 9181161, upload-time = "2026-10-30T15:59:49.399Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c1/d9/6b9127e8fa3ef14a3ec199436bec6c1a54a0bb429ca261b1a2fb518938d1/grpcio-1.85.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:9998f03ac0dfed226eead6e93cee1b547d7a32e47e1915dee94eff0e113b167e", size = 8318829, upload-time = "2026-10-30T15:59:52.09Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/21/46/ff3374d33efee490a0e50e3c3fc59280b7f7fc2ed3ab1ee8c4e9873dc83d/grpcio-1.85.1-cp312-cp312-win32.whl", hash = "sha256:2670c03d154f6bec66a0fef97c607116761b032183187dfdfe229b5975820a4f", size = 4768056, upload-time = "2026-10-30T15:59:54.132Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/dd/48/4030a63540089d00a36cea15282623bcf084a5ea4c0ffc4685a42ef0f342/grpcio-1.85.1-cp312-cp312-win_amd64.whl", hash = "sha256:eaad7e6aa9ac3aded4f6bc86a18bf2cff3de356f972bf32a5558df9788085b85", size = 5607218, upload-time = "2026-10-30T15:59:56.721Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c1/05/2d40be7dbfd8e66e8e5675ec695fafacc69823dcd2ef5d387ad7431c7af7/grpcio-1.85.1-cp313-cp313-linux_armv7l.whl", hash = "sha256:e117b074d707d418ff411e0ad6fc86e97e83047b742488b41d7a5b7a62953cd3", size = 6801759, upload-time = "2026-10-30T15:59:58.834Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b0/98/530af74d704dc8e79c79b26888af44ccbdd1827bfabc9cb405b3d4cc184e/grpcio-1.85.1-cp313-cp313-macosx_11_0_universal2.whl", hash = "sha256:6bb4bbb5cb46010687db552fd88852c405595814fb7d435b072124bd6b93f827", size = 12629341, upload-time = "2026-10-30T16:00:01.159Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/21/cb/bac12e6c7ab3b1c6b50816fdcbf7f97aec1bd0992cc0d193e332aff716a5/grpcio-1.85.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0bde4264ca71aaf3bc56c587380c426b1c959d1db0ab0a3f632bc66515f9726f", size = 7174387, upload-time = "2026-10-30T16:00:04.847Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/90/0a/7770a652508a3a6c7d16fbb81db0f0b2be8a73a469af88a6cdfdc3d29cf2/grpcio-1.85.1-cp313-cp313-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:7b931335c163510fb054c30007fe3556ef3bf354a1c37b5da403f2e52c6bbd95", size = 8185778, upload-time = "2026-10-30T16:00:07.009Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bf/cb/52417fb272b7603d13ec8688e843dfd8df64584da1951ad954b9120d7c80/grpcio-1.85.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:de520b1555ae445cdc4f8f1cc7ccba12a19992bfafa7c292ebe7fe1fe5da6c53", size = 7364062, upload-time = "2026-10-30T16:00:09.777Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ba/86/9329799fa9defe9327084b9ca7b9a9745e83e7174bb90f2bfb2f37063967/grpcio-1.85.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:2b20ba567ca818b8393fd4668878b5688cab32a46e8e7a4d1a58641fc0072df9", size = 7932775, upload-time = "2026-10-30T16:00:11.956Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/48/e4/826e0ae8f89a3d2ab3a15b91ee4ef486bdd7a09fd1ff72e12d01505341dc/grpcio-1.85.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:f0ebfbd8ba42497e0ff7229c8c5e166e07c2b348462c1481dbd90faa978ad8af", size = 9173461, upload-time = "2026-10-30T16:00:15.696Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/88/2d/d4baf37bf1a9ba8222dcb133c6aeb09119b183bd7b471061762a1198461c/grpcio-1.85.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:000999ea9bba80217b1625782d638e7a688790f6154e845e18826f7da859bfc7", size = 8311104, upload-time = "2026-10-30T16:00:18.533Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e4/02/b07af232a583727fa84665d11165bbd7be6ddd31d84c2b8cb62a7b69062f/grpcio-1.85.1-cp313-cp313-win32.whl", hash = "sha256:b3722f4e01820f4d2422679a567fe33f31b6f14eba4352657a1078f4b4ed323e", size = 4769351, upload-time = "2026-10-30T16:00:21.165Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f9/f0/d2448e860d884e8c89dd9135cd9373df064c10227d90973d822c2125428d/grpcio-1.85.1-cp313-cp313-win_amd64.whl", hash = "sha256:c17d61af28b322c48ab3881c685e5f6e7e367c56844cf589ee7707be9477b969", size = 5606831, upload-time = "2026-10-30T16:00:23.621Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/39/cc/da49c22b9c571b5315acc507e2ff6568e5ff9d4c99895285910283bf87e3/grpcio-1.85.1-cp314-cp314-linux_armv7l.whl", hash = "sha256:2a378eb60ea42996be5a8c7167302fb30d968fcfcf9edd7b3fa6c985906c4500", size = 6803626, upload-time = "2026-10-30T16:00:26.587Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/12/92/35bcee92bcfc2b0f66290a5dd6dd23ced7b9423fe269cf4495136e73d55b/grpcio-1.85.1-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:90a7e0f26de39d15f5c741b8848bb2065c9ab7351c57d4fc973ff5cbda0cb9c7", size = 12640307, upload-time = "2026-10-30T16:00:28.969Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f2/b5/469b69dadb2c413706f16e0c3e7a2749cc70abaab10d718873603bec29b2/grpcio-1.85.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:421925365f9a665830eded01b8053033abbc2fbabc9bb4e9c59c3b5b12acbab9", size = 7187308, upload-time = "2026-10-30T16:00:31.652Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c4/df/2fcb1567d37e91ce26bddfca30f39fe6c39cbc5a2f4a210cfb1246ced1b2/grpcio-1.85.1-cp314-cp314-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:8a921a98ed6142a29651b4a6f4c7b8e051d115f1e78c31655a9642dcf6356dd9", size = 8188002, upload-time = "2026-10-30T16:00:33.893Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7b/b2/c67c1d8c7b70a094d404b28233458887bc1ca1319daa95d8952621216717/grpcio-1.85.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e0e6d5829b50a2ffcfcd2dbf08d02ac0d6919051a2e97c2ee27c99bc9916a245", size = 7368045, upload-time = "2026-10-30T16:00:36.675Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/80/48/5cf6c704be4b059d508e8f6c981154223533595ba7a3ee531211ef8be62e/grpcio-1.85.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:58b5ebe509da292bec5a1913c1e4c14d842a33f6cb330a87d3713c5089dd0f55", size = 7941330, upload-time = "2026-10-30T16:00:39.173Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/67/96/5ef14edb784ea2053610753993601e98a76a18b541a8a74103dc390540ab/grpcio-1.85.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:016982ebd21d2b48e955aa808e9db8d628708a35c6eba852cd0e70765826ab06", size = 9176909, upload-time = "2026-10-30T16:00:41.335Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/50/01/4264ae95364bdeede4c8a5f0d83df83a21b477935f9ab8c829ae5606e1d4/grpcio-1.85.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:0fa3d7b8b95e8a609967991c3b0a302b2f9d510fe417efadfa7c7d2d044a99ba", size = 8316226, upload-time = "2026-10-30T16:00:44.199Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/75/b8/79dace38eb4bb904751b804cfdc71609a3840f34084af7475169059dce20/grpcio-1.85.1-cp314-cp314-win32.whl", hash = "sha256:39b1965266b579f3758db20d74f9075b130d1b1edcf0464cda316e403a15da9b", size = 4853260, upload-time = "2026-10-30T16:00:47.098Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/48/c9/68a6bbd2450f08942c3056acd8995ac28af2b4eeb0574c0a8e59fa59b140/grpcio-1.85.1-cp314-cp314-win_amd64.whl", hash = "sha256:5f015600190124813032da0560ec950c13c257f77c1307abd77c393c0994f76f", size = 5758958, upload-time = "2026-10-30T16:00:49.145Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1b/bd/1a2481b354ab4528eb8b3462937904c9206e2a54748f3f74a2576205ef3e/grpcio-1.85.1-cp315-cp315-linux_armv7l.whl", hash = "sha256:07bfef5df75875d8481d3403f864785e30096594162e8041c53a84fb11ee4f8e", size = 6803392, upload-time = "2026-10-30T16:00:51.782Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/40/45/1868c12c18058d778fcecee0e04c867891a82d983d2dd0de2639158aa960/grpcio-1.85.1-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:e909e0f9145a555d3968dd2a448616b0d3cb58748b9e2053de3e7974b3e429bc", size = 12657793, upload-time = "2026-10-30T16:00:55.335Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ed/af/c283032a42df5217913b98bd0113738b68dd94b91cea16b2209565fefe67/grpcio-1.85.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:1f3064e209167e5fcb75a72cbc18918c06027b92b29fa06eaff0126f9a2aab5a", size = 7209146, upload-time = "2026-10-30T16:00:58.279Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/45/64/8a72fd6c20c206cff07eaa49b2ca63bb15d7ed9b6bf7c653ea10ec578e4b/grpcio-1.85.1-cp315-cp315-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:07675c635a2da0c772e58ac736a7fb10c7c7c1613157766441e6866ad97d25b4", size = 7511067, upload-time = "2026-10-30T16:01:00.806Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5d/b8/32afa404288c7eea4c6034d031f1a07eff772a8cdbfc7751314382e7b724/grpcio-1.85.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:759f7df78954e3ac0ed4c87612eff9125021b9271be37be8c88167aa533e29ee", size = 7410227, upload-time = "2026-10-30T16:01:02.966Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/89/a4/1c51e2c2d0d9e4d37e8e8a7be412c5dfb3fd5c80ab100dd531fd81b44d43/grpcio-1.85.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:7cd08bd5ad063ad9639dbebf95d3a6b8c8aa2c9d49049bc0e8f47e73ecf1c1a2", size = 7964886, upload-time = "2026-10-30T16:01:05.208Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/07/f3/e26f570129c162d8f15a02af6edb49e592ac1c88a63490cd3ec9142d8c67/grpcio-1.85.1-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:2198269c8b69cb1e9d5d20628029245e40b7227d5f6fc6f298a420701d8fb652", size = 8504060, upload-time = "2026-10-30T16:01:07.82Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/16/e1/e334cf7442c01892ed813563b21b2a8ab5b042e34f33ad76cf64526d1de8/grpcio-1.85.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:7bc5de50374416223bc35332aa8185567ec065f86190ff0ca6e13176ed39a3b4", size = 8346563, upload-time = "2026-10-30T16:01:10.394Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/66/bb/cf72913ce0baae1fed95445f1ba8ac309184ac16b4f20fb5f88219eff72c/grpcio-1.85.1-cp315-cp315-win32.whl", hash = "sha256:5740aedf1e6acde538d7b80a2507eb6ee0b8983c577a36890d27a0e2b62cc1eb", size = 4853404, upload-time = "2026-10-30T16:01:12.239Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ea/b8/b7cff7b9e1ff7b6a8d36a19ce8b9c575963e71fcbb3878b276cff6748b05/grpcio-1.85.1-cp315-cp315-win_amd64.whl", hash = "sha256:b32f39c56d22d2e8722eececd4376074d94e01595a29f4f944ae0b6cea1caa70", size = 5758584, upload-time = "2026-10-30T16:01:14.325Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "grpcio-health-checking"
|
||||
version = "1.85.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "grpcio" },
|
||||
{ name = "protobuf" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/9a/2c/ca51c42fbebecffa7129b347b95a2753b7c1a37db80803abef72e46390f8/grpcio_health_checking-1.85.1.tar.gz", hash = "sha256:93a5eeb29262165949b32fdaa86505f11018d1b8161382ee373a85530b11d281", size = 17986, upload-time = "2026-10-30T16:05:20.323Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/0e/87/9be2c7b713907545cb88f5cd318107a58c77cdc146198f6175122d0aa931/grpcio_health_checking-1.85.1-py3-none-any.whl", hash = "sha256:05e1cb0cc69706f89e884d219c9b2b9da4f561c1c610e9987ee4492b9c826ad1", size = 20011, upload-time = "2026-10-30T16:03:53.049Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -498,7 +522,9 @@ source = { editable = "services/bff" }
|
||||
dependencies = [
|
||||
{ name = "fastapi" },
|
||||
{ name = "grpcio" },
|
||||
{ name = "httpx" },
|
||||
{ name = "jinja2" },
|
||||
{ name = "magnetflix-contracts" },
|
||||
{ name = "protobuf" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "uvicorn", extra = ["standard"] },
|
||||
@@ -508,12 +534,29 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "fastapi", specifier = ">=0.115.0" },
|
||||
{ name = "grpcio", specifier = ">=1.83.1" },
|
||||
{ name = "httpx", specifier = ">=0.28.0" },
|
||||
{ name = "jinja2", specifier = ">=3.1.4" },
|
||||
{ name = "magnetflix-contracts", editable = "services/contracts" },
|
||||
{ name = "protobuf", specifier = ">=7.36.1" },
|
||||
{ name = "pydantic", specifier = ">=2.10.0" },
|
||||
{ name = "uvicorn", extras = ["standard"], specifier = ">=0.32.0" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "magnetflix-contracts"
|
||||
version = "0.1.0"
|
||||
source = { editable = "services/contracts" }
|
||||
dependencies = [
|
||||
{ name = "grpcio" },
|
||||
{ name = "protobuf" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "grpcio", specifier = ">=1.83.1" },
|
||||
{ name = "protobuf", specifier = ">=7.36.2" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "magnetflix-worker"
|
||||
version = "0.1.0"
|
||||
@@ -522,7 +565,9 @@ dependencies = [
|
||||
{ name = "aiosqlite" },
|
||||
{ name = "alembic" },
|
||||
{ name = "grpcio" },
|
||||
{ name = "grpcio-health-checking" },
|
||||
{ name = "httpx" },
|
||||
{ name = "magnetflix-contracts" },
|
||||
{ name = "protobuf" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "sqlalchemy" },
|
||||
@@ -534,7 +579,9 @@ requires-dist = [
|
||||
{ name = "aiosqlite", specifier = ">=0.20.0" },
|
||||
{ name = "alembic", specifier = ">=1.14.0" },
|
||||
{ name = "grpcio", specifier = ">=1.83.1" },
|
||||
{ name = "grpcio-health-checking", specifier = ">=1.83.1" },
|
||||
{ name = "httpx", specifier = ">=0.28.0" },
|
||||
{ name = "magnetflix-contracts", editable = "services/contracts" },
|
||||
{ name = "protobuf", specifier = ">=7.36.1" },
|
||||
{ name = "pydantic", specifier = ">=2.10.0" },
|
||||
{ name = "sqlalchemy", specifier = ">=2.0.36" },
|
||||
@@ -553,6 +600,7 @@ dev = [
|
||||
{ name = "mypy-protobuf" },
|
||||
{ name = "pyright" },
|
||||
{ name = "pytest" },
|
||||
{ name = "pytest-asyncio" },
|
||||
{ name = "ruff" },
|
||||
]
|
||||
|
||||
@@ -565,6 +613,7 @@ dev = [
|
||||
{ name = "mypy-protobuf", specifier = ">=5.1.0" },
|
||||
{ name = "pyright", specifier = ">=1.1.411" },
|
||||
{ name = "pytest", specifier = ">=8.0.0" },
|
||||
{ name = "pytest-asyncio", specifier = ">=0.24.0" },
|
||||
{ name = "ruff", specifier = ">=0.16.5" },
|
||||
]
|
||||
|
||||
@@ -685,17 +734,17 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "protobuf"
|
||||
version = "7.36.1"
|
||||
version = "7.36.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/86/73/f66c748df06e7fe24e658eddd600d19c4b40bad836c97ce2d0ad9851fb6b/protobuf-7.36.1.tar.gz", hash = "sha256:d0f6470f0ce2b84e3feaea2d4b816378b37ba4d4aa08a274305373de93e2d524", size = 512499, upload-time = "2026-08-31T22:40:04.667Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/d9/89/5b8517baa72f84a67b8a307ba953c91057af618bf40bf676f3c03551f8f0/protobuf-7.36.2.tar.gz", hash = "sha256:497d0463ff3316681da6c0b9e8d06cb465d61abce00b613ab42226175644d1bb", size = 512737, upload-time = "2026-09-17T20:07:59.326Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/f7/6c/3a54a58f2948b0f485df9ecdd06590f15d0a7abf46a89d50c3de709ff4ff/protobuf-7.36.1-cp310-abi3-macosx_10_9_universal2.whl", hash = "sha256:3cf2ee25d006cee57294a1196ea43b37feb78e0dcd1e8af5c1aeddb777655aca", size = 456046, upload-time = "2026-08-31T22:39:56.865Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6e/08/9f9548793c771095245c0eeaf0c84b76b16a5ef26158043d456f551344a0/protobuf-7.36.1-cp310-abi3-manylinux2014_aarch64.whl", hash = "sha256:43d3d37b1eb24c113b9b7d02008cac44e423f00b611b7781ae998d7623972969", size = 344226, upload-time = "2026-08-31T22:39:58.263Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fe/51/1bdbd612fa3c51e42ea6f45d05e84dc748ddcd2663e1aa1e89a00a33facd/protobuf-7.36.1-cp310-abi3-manylinux2014_s390x.whl", hash = "sha256:39c518c05586c016d7874ff6079ee115bcec1ea5fbb1d177fbf7867ef4c67e44", size = 357229, upload-time = "2026-08-31T22:39:59.198Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/22/df/c799fe7a05ef16ba853a59db01f3a2c5f7d0676469589ccc4874f76a2a88/protobuf-7.36.1-cp310-abi3-manylinux2014_x86_64.whl", hash = "sha256:97198b77e369a0abd8e262b8f6c7266c55ddb796a3a12c76d7b8881188ed83aa", size = 343228, upload-time = "2026-08-31T22:40:00.179Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3d/33/d4724ec5d86d496fe4108e220618aa0837ad3423a7af7ccdd9684ccc77c8/protobuf-7.36.1-cp310-abi3-win32.whl", hash = "sha256:0b53ce95272aad50ad25d7ff03373743209822e8ba42ea7fad27d2bee1547d00", size = 443002, upload-time = "2026-08-31T22:40:01.32Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/db/37/155788a0d8daded960375af604202805308169f9b859419ea0aa370946e2/protobuf-7.36.1-cp310-abi3-win_amd64.whl", hash = "sha256:51139351435d9b43d88a55eaa49fb6f737fbb478fb0cbf2cf694d1a04a9d3363", size = 456518, upload-time = "2026-08-31T22:40:02.494Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/39/ca/c47f91d3cab175b01fd8c4f0d80fdf8613be876cc616e66ad281a59c5ddf/protobuf-7.36.1-py3-none-any.whl", hash = "sha256:7d951e46b3f963d6c264c367c437921de9d5aedd9c3f9612b9077736b4e3ad5c", size = 179813, upload-time = "2026-08-31T22:40:03.54Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/32/72/98342feb672507c8f3a69e34b4fa8961f608edba5c1a48a6f47156d92cb5/protobuf-7.36.2-cp310-abi3-macosx_10_9_universal2.whl", hash = "sha256:cbc70b17ee27e28894c7fee8bb04be1abead49e936bc70eb60052531eee2079e", size = 456039, upload-time = "2026-09-17T20:07:51.542Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b6/ea/91fdf7c2b8bbd49cde056f00a9df6773532987e1c00fe2830b895af95c7e/protobuf-7.36.2-cp310-abi3-manylinux2014_aarch64.whl", hash = "sha256:e11e1f0180583a2af89db6a2ecd9e8dc40aa6d2988ca175bfd0e6d12ea72d74e", size = 344219, upload-time = "2026-09-17T20:07:52.914Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/17/ab/5fd5f8ece73fad885c5a09aa849b32d70472f954ba3a92d3bb5974ea953b/protobuf-7.36.2-cp310-abi3-manylinux2014_s390x.whl", hash = "sha256:f4fee11ec330d238b34a05c9b675f693c20415d1c5bd7d5320cc2f8a798eb9cf", size = 357223, upload-time = "2026-09-17T20:07:53.985Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/db/f3/3996583dd2906297a637af12114deddf7658af6e683fedb83be061983fb5/protobuf-7.36.2-cp310-abi3-manylinux2014_x86_64.whl", hash = "sha256:89f23aa53c24553a2416fd4fd1ec06f74fa42b14b546d8883128813f775bbfd2", size = 343223, upload-time = "2026-09-17T20:07:54.931Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fc/1b/dcc64f358fcb51811b58ae40b3d28f820725f116d86487cc20bd4b130701/protobuf-7.36.2-cp310-abi3-win32.whl", hash = "sha256:912c1221170e16c08d1f086762f563dd61ff83c18b5fa6652952dfaded66f728", size = 442998, upload-time = "2026-09-17T20:07:55.826Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8a/55/b77bda4e5e5f5971fb51b07663694690e9afdb9402136c16a522bd621cad/protobuf-7.36.2-cp310-abi3-win_amd64.whl", hash = "sha256:a300819d441e078a5608c0d3c709796bb548136058fda017ae51d425b44fd353", size = 456514, upload-time = "2026-09-17T20:07:57.188Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e4/04/d52c7016b04b6c5108f26691f9d33ec82a9b65d041f1a9c771137693d618/protobuf-7.36.2-py3-none-any.whl", hash = "sha256:bdb3a345d48db958e6ce1f18e508beb0cc981d64f24088427549c866cd039f1e", size = 179806, upload-time = "2026-09-17T20:07:58.211Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -826,6 +875,19 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pytest-asyncio"
|
||||
version = "1.4.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "pytest" },
|
||||
{ name = "typing-extensions", marker = "python_full_version < '3.13'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/43/7c/d36d04db312ecf4298932ef77e6e4a9e8ad017906e24e34f0b0c361a2473/pytest_asyncio-1.4.0.tar.gz", hash = "sha256:c6c0d2259945122819f171a32ecea2c349ead889ee28176caaf492143424be42", size = 58514, upload-time = "2026-05-26T09:56:04.083Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/03/e2/08a497ef684b88559c9cc5f4ad53a37e7b99e727094a86d6ea32536d5d3c/pytest_asyncio-1.4.0-py3-none-any.whl", hash = "sha256:933ca923a23075a87fb7070c0ec272a6848489824d887c85c812670932835aa1", size = 16930, upload-time = "2026-05-26T09:56:02.576Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "python-dotenv"
|
||||
version = "1.2.3"
|
||||
|
||||
Reference in new issue
Block a user