diff --git a/docs/dev/rest-api/job-lifecycle.md b/docs/dev/rest-api/job-lifecycle.md index 8bf6e3111..8db34c758 100644 --- a/docs/dev/rest-api/job-lifecycle.md +++ b/docs/dev/rest-api/job-lifecycle.md @@ -160,7 +160,7 @@ full detail: | `track_progress` | list | Per-active-track `{label, progress, speed}` entries. | | `segments_done` | number | Segments downloaded for the track in progress. | | `segments_total` | number | Total segments for the track in progress. | -| `speed` | string | Transfer speed of the track in progress, e.g. `4.20 MB/s`. | +| `speed` | string or `null` | Transfer speed of the track in progress, e.g. `4.20 MB/s`. `null` when no track downloads. | | `skipped_subtitles` | list | Subtitles that were skipped as non-fatal failures (when `skip_subtitle_errors` is set). | | `skipped_titles` | list | Titles that the run skipped because a requested track or language is missing, each `{title, reason}`. | | `input_prompt` | string or `null` | The prompt the service waits on. Answer it with `POST /api/download/jobs/{job_id}/input`. | @@ -365,7 +365,8 @@ server process. For each job it spawns a separate Python subprocess: python -m unshackle.core.api.download_worker ``` -Three temporary files bridge the parent and the job worker: +Three temporary files bridge the parent and the job worker. `unshackle/core/api/job_channel.py` defines each file +and the stdin answer line: - **`payload.json`**: the manager writes it before launch. It contains the job ID, service, title ID, and merged parameters. @@ -384,8 +385,8 @@ and blocking work inside the download engine, and makes hard cancellation (killi process) reliable. The job worker's exit codes are `0` for success, `1` for a download error, and `2` for bad -arguments. Its `result.json` is either `{"status": "success", "output_files": [...]}` -or `{"status": "error", "message", "error_details", "error_code", "traceback"}`. If the +arguments. Its `result.json` holds `status`, `output_files`, `message`, `error_details`, `error_code` and +`traceback`. The `status` is `success` or `error`, and a success leaves the error fields `null`. If the process exits non-zero, or the result is missing or not a success, the parent marks the job `failed` and adopts the job worker's `error_code` (or derives one by categorising the exception). @@ -393,7 +394,9 @@ exception). ### How progress reaches the API While the job worker operates, the manager polls `progress.json` every **0.5 s** and copies the -fields it finds onto the live `DownloadJob`. That is what the `GET` endpoints return. +fields it finds onto the live `DownloadJob`. That is what the `GET` endpoints return. The file +holds the whole progress record each time, so each field in it replaces the job's value, `0` and +`null` too. The job worker aggregates progress across all selected tracks. It weights each track's completion fraction by its bitrate, so video and audio dominate the bar and subtitles diff --git a/tests/lang_selection/test_kind_only_selection.py b/tests/lang_selection/test_kind_only_selection.py index e3d8139a6..161fc38eb 100644 --- a/tests/lang_selection/test_kind_only_selection.py +++ b/tests/lang_selection/test_kind_only_selection.py @@ -17,6 +17,7 @@ import pytest from unshackle.commands.dl import dl from unshackle.core import binaries +from unshackle.core.api.job_channel import JobProgress, apply_progress from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS from unshackle.core.title_source import TitleSource @@ -195,6 +196,10 @@ def test_skip_missing_skips_the_title_and_reports_it( assert ids == {"video": ["v"], "audio": ["a"], "subs": ["s"]} assert "Skipping Show S01E01: Required audio language(s) not found: ko" in caplog.text assert {"skipped_titles": [{"title": "Show S01E01", "reason": "Required audio language(s) not found: ko"}]} in sink + state = JobProgress() + for event in sink: + apply_progress(state, event) + assert state.title == "Show" def test_skip_missing_skips_a_filter_miss_and_continues( diff --git a/tests/remote/unit/test_download_manager.py b/tests/remote/unit/test_download_manager.py index 5391fcb08..6653a7725 100644 --- a/tests/remote/unit/test_download_manager.py +++ b/tests/remote/unit/test_download_manager.py @@ -26,6 +26,25 @@ def manager() -> DownloadQueueManager: return DownloadQueueManager(max_concurrent_downloads=2, job_retention_hours=24) +@pytest.fixture +def fake_worker(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Callable[[str], None]: + """Make the manager spawn a worker script with this source; it imports the unshackle under test.""" + import os + + def use(source: str) -> None: + worker = tmp_path / "worker.py" + worker.write_text(source, encoding="utf-8") + spawn = asyncio.create_subprocess_exec + env = {**os.environ, "PYTHONPATH": str(Path(__file__).resolve().parents[3])} + + async def spawn_fake_worker(executable: str, *args: str, **kwargs: Any) -> Any: + return await spawn(executable, str(worker), *args[2:], env=env, **kwargs) + + monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn_fake_worker) + + return use + + def test_create_job_returns_queued_job(manager: DownloadQueueManager) -> None: job = manager.create_job("EXAMPLE", "movie-123", profile="default") assert isinstance(job, DownloadJob) @@ -157,7 +176,7 @@ def test_worker_write_result_retries_denied_replace(tmp_path: Path, monkeypatch: import json import os - from unshackle.core.api import download_worker + from unshackle.core.api import job_channel target = tmp_path / "progress.json" real_replace = os.replace @@ -169,8 +188,8 @@ def test_worker_write_result_retries_denied_replace(tmp_path: Path, monkeypatch: raise PermissionError(13, "Permission denied", str(dst)) real_replace(src, dst) - monkeypatch.setattr(download_worker.os, "replace", flaky_replace) - download_worker.write_result(target, {"progress": 42.0}) + monkeypatch.setattr(job_channel.os, "replace", flaky_replace) + job_channel.write_json(target, {"progress": 42.0}) assert json.loads(target.read_text(encoding="utf-8")) == {"progress": 42.0} assert len(attempts) == 2 @@ -459,9 +478,11 @@ def test_submit_input_writes_one_json_line_to_the_worker(manager: DownloadQueueM import io from types import SimpleNamespace + from unshackle.core.api.job_channel import WorkerProcess + job = manager.create_job("EXAMPLE", "t") stdin = io.BytesIO() - manager._download_processes[job.job_id] = SimpleNamespace(stdin=stdin) # type: ignore[assignment] + manager._workers[job.job_id] = WorkerProcess(job.job_id, SimpleNamespace(stdin=stdin), {}) # type: ignore[arg-type] assert manager.submit_input(job, "1234") is False job.input_prompt = "Enter PIN" @@ -476,40 +497,23 @@ import sys from pathlib import Path from typing import Any -from unshackle.core.api import download_worker +from unshackle.core.api import download_worker, job_channel from unshackle.core.console import prompt_user result_path, progress_path = Path(sys.argv[-2]), Path(sys.argv[-1]) -state = {} - - -def progress(update): - state.update(update) - download_worker.write_result(progress_path, state) - - -download_worker.relay_prompts(progress) +download_worker.relay_prompts(job_channel.ProgressFile(progress_path)) answers = [prompt_user("Enter OTP"), prompt_user("Enter OTP")] -download_worker.write_result(result_path, {"status": "success", "output_files": answers}) +job_channel.write_result(result_path, job_channel.WorkerResult("success", answers)) """ async def test_a_repeated_prompt_reaches_an_event_listener( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, manager: DownloadQueueManager + fake_worker: Callable[[str], None], manager: DownloadQueueManager ) -> None: """A re-prompt with the same text right after an answer must still publish an event.""" import asyncio - from unshackle.core.api import download_manager - - worker = tmp_path / "worker.py" - worker.write_text(FAKE_PROMPT_WORKER, encoding="utf-8") - spawn = asyncio.create_subprocess_exec - - async def spawn_fake_worker(executable: str, *args: str, **kwargs: Any) -> Any: - return await spawn(executable, str(worker), *args[2:], **kwargs) - - monkeypatch.setattr(download_manager.asyncio, "create_subprocess_exec", spawn_fake_worker) + fake_worker(FAKE_PROMPT_WORKER) job = manager.create_job("EXAMPLE", "t") events = manager.subscribe(job.job_id) run = asyncio.create_task(manager.run_download_async(job)) @@ -528,14 +532,11 @@ async def test_a_repeated_prompt_reaches_an_event_listener( async def test_a_notice_reaches_the_job_and_an_event_listener( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, manager: DownloadQueueManager + fake_worker: Callable[[str], None], manager: DownloadQueueManager ) -> None: """The job carries the worker's notice while the worker waits, and drops it at the end.""" import asyncio - from unshackle.core.api import download_manager - - worker = tmp_path / "worker.py" # The prompt holds the worker open until the test has seen the notice. source = FAKE_PROMPT_WORKER.replace("import prompt_user", "import prompt_user, show_notice").replace( 'answers = [prompt_user("Enter OTP"), prompt_user("Enter OTP")]', @@ -543,13 +544,7 @@ async def test_a_notice_reaches_the_job_and_an_event_listener( 'answers = [prompt_user("Continue", "https://login.example/pair")]', ) assert source.count("show_notice") == 2, "FAKE_PROMPT_WORKER changed; update the replacements" - worker.write_text(source, encoding="utf-8") - spawn = asyncio.create_subprocess_exec - - async def spawn_fake_worker(executable: str, *args: str, **kwargs: Any) -> Any: - return await spawn(executable, str(worker), *args[2:], **kwargs) - - monkeypatch.setattr(download_manager.asyncio, "create_subprocess_exec", spawn_fake_worker) + fake_worker(source) job = manager.create_job("EXAMPLE", "t") events = manager.subscribe(job.job_id) run = asyncio.create_task(manager.run_download_async(job)) @@ -607,21 +602,12 @@ sys.exit(download_worker.main(["worker"] + sys.argv[1:])) async def test_a_failed_job_keeps_the_worker_error( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, manager: DownloadQueueManager + fake_worker: Callable[[str], None], manager: DownloadQueueManager ) -> None: """The job records the worker's traceback and error, not the parent's "Worker exited" wrapper.""" import asyncio - from unshackle.core.api import download_manager - - worker = tmp_path / "worker.py" - worker.write_text(FAKE_FAILING_WORKER, encoding="utf-8") - spawn = asyncio.create_subprocess_exec - - async def spawn_fake_worker(executable: str, *args: str, **kwargs: Any) -> Any: - return await spawn(executable, str(worker), *args[2:], **kwargs) - - monkeypatch.setattr(download_manager.asyncio, "create_subprocess_exec", spawn_fake_worker) + fake_worker(FAKE_FAILING_WORKER) job = manager.create_job("EXAMPLE", "t") with pytest.raises(Exception, match="Worker exited"): await asyncio.wait_for(manager.execute_download(job), timeout=60) @@ -660,20 +646,11 @@ sys.exit(download_worker.main(["worker"] + sys.argv[1:])) async def test_a_skip_written_just_before_the_worker_exits_reaches_the_job( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, manager: DownloadQueueManager + fake_worker: Callable[[str], None], manager: DownloadQueueManager ) -> None: import asyncio - from unshackle.core.api import download_manager - - worker = tmp_path / "worker.py" - worker.write_text(FAKE_SKIPPING_WORKER, encoding="utf-8") - spawn = asyncio.create_subprocess_exec - - async def spawn_fake_worker(executable: str, *args: str, **kwargs: Any) -> Any: - return await spawn(executable, str(worker), *args[2:], **kwargs) - - monkeypatch.setattr(download_manager.asyncio, "create_subprocess_exec", spawn_fake_worker) + fake_worker(FAKE_SKIPPING_WORKER) job = manager.create_job("EXAMPLE", "t") with pytest.raises(Exception, match="Skipped all 2 titles"): await asyncio.wait_for(manager.run_download_async(job), timeout=20) diff --git a/tests/remote/unit/test_job_channel.py b/tests/remote/unit/test_job_channel.py new file mode 100644 index 000000000..e38198eb5 --- /dev/null +++ b/tests/remote/unit/test_job_channel.py @@ -0,0 +1,179 @@ +"""Tests of the job-worker channel: the progress record and its presence rule, the progress sink, answers and results.""" + +from __future__ import annotations + +import asyncio +import json +from dataclasses import asdict, fields +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest + +from unshackle.core.api.download_manager import HISTORY_FIELDS, DownloadQueueManager, JobStatus, record_job_history +from unshackle.core.api.job_channel import ( + PROGRESS_FIELDS, + JobProgress, + ProgressFile, + WorkerProcess, + WorkerResult, + apply_progress, + decode_answer, + encode_answer, + write_result, +) + +pytestmark = pytest.mark.unit + + +def test_a_key_in_the_update_replaces_the_field_none_and_zero_too() -> None: + state = JobProgress(total_tracks=3, speed="1 MB/s", title="Show") + assert apply_progress(state, {"total_tracks": 0, "speed": None}) is True + assert state.total_tracks == 0 and state.speed is None + assert state.title == "Show" + + +def test_an_update_that_changes_nothing_reports_no_change() -> None: + state = JobProgress(phase="muxing") + assert apply_progress(state, {"phase": "muxing"}) is False + assert apply_progress(state, {}) is False + + +def test_number_fields_are_cast() -> None: + state = JobProgress() + apply_progress(state, {"progress": 5, "segments_done": 2, "completed_tracks": 1.0}) + assert state.progress == 5.0 and isinstance(state.progress, float) + assert isinstance(state.segments_done, float) + assert state.completed_tracks == 1 and isinstance(state.completed_tracks, int) + + +@pytest.mark.parametrize( + ("update", "names"), + [ + ({"status": "downloading"}, "status"), + ({"phase": "x", "progress": None}, "progress"), + ({"progress": "x"}, "progress"), + ({"total_tracks": float("inf")}, "total_tracks"), + (None, "NoneType"), + ([], "list"), + ], +) +def test_a_bad_update_raises_and_changes_nothing(update: Any, names: str) -> None: + state = JobProgress() + with pytest.raises(ValueError, match=names): + apply_progress(state, update) + assert state == JobProgress() + + +def test_the_progress_file_holds_the_whole_merged_record(tmp_path: Path) -> None: + path = tmp_path / "progress.json" + sink = ProgressFile(path) + sink({"title": "Show", "current_title": "S01E01"}) + sink({"phase": "muxing"}) + written = json.loads(path.read_text(encoding="utf-8")) + assert set(written) == set(PROGRESS_FIELDS) + assert (written["title"], written["current_title"], written["phase"]) == ("Show", "S01E01", "muxing") + + +@pytest.mark.parametrize("bad", [{"phase": "x", "typo": 1}, {"phase": "x", "title": object()}], ids=["key", "value"]) +def test_the_progress_file_drops_a_bad_update_and_keeps_writing( + tmp_path: Path, caplog: pytest.LogCaptureFixture, bad: dict[str, Any] +) -> None: + """A value JSON cannot hold must not stay in the record, or each later write fails too.""" + path = tmp_path / "progress.json" + sink = ProgressFile(path) + sink({"phase": "muxing"}) + sink(bad) + assert json.loads(path.read_text(encoding="utf-8"))["phase"] == "muxing" + assert "Failed to write progress update" in caplog.text + sink({"phase": "done"}) + assert json.loads(path.read_text(encoding="utf-8"))["phase"] == "done" + + +def test_the_aggregate_track_progress_fits_the_record() -> None: + from unshackle.core.api.progress import build_job_progress_callables + + class Video: + height, width, range, bitrate = 1080, 1920, None, 4_000_000 + + state = JobProgress() + + def sink(update: dict[str, Any]) -> None: + apply_progress(state, update) + + callables = build_job_progress_callables([Video()], [lambda **kw: None], sink) # type: ignore[list-item] + callables[0](total=10, completed=5, downloaded="1.0 MB/s") + callables[0](downloaded="Downloaded") + assert (state.completed_tracks, state.total_tracks, state.progress) == (1, 1, 90.0) + + +def test_an_answer_survives_the_pipe_with_a_newline() -> None: + line = encode_answer("12\n34") + assert line.count(b"\n") == 1 and line.endswith(b"\n") + assert decode_answer(line) == "12\n34" + + +def test_the_parent_reads_the_progress_file_once_per_change(tmp_path: Path) -> None: + path = tmp_path / "progress.json" + worker = WorkerProcess("j", SimpleNamespace(), {"progress": str(path)}) # type: ignore[arg-type] + ProgressFile(path)({"phase": "muxing"}) + update = worker.read_progress() + assert update is not None and update["phase"] == "muxing" + assert worker.read_progress() is None + + +@pytest.mark.parametrize( + ("content", "expected"), + [ + (json.dumps(asdict(WorkerResult("success", ["a.mkv"]))), WorkerResult("success", ["a.mkv"])), + (json.dumps({"status": "error", "message": "boom"}), WorkerResult("error", message="boom")), + ("", None), + ("{}", None), + ], + ids=["success", "error", "empty", "no-status"], +) +def test_the_parent_reads_the_worker_result( + tmp_path: Path, caplog: pytest.LogCaptureFixture, content: str, expected: WorkerResult | None +) -> None: + path = tmp_path / "result.json" + path.write_text(content, encoding="utf-8") + worker = WorkerProcess("j", SimpleNamespace(), {"result": str(path)}) # type: ignore[arg-type] + assert asyncio.run(worker.result()) == expected + assert "Failed to parse" not in caplog.text + + +def test_write_result_round_trips(tmp_path: Path) -> None: + path = tmp_path / "result.json" + result = WorkerResult("error", message="m", error_details="d", error_code="WORKER_ERROR", traceback="tb") + write_result(path, result) + worker = WorkerProcess("j", SimpleNamespace(), {"result": str(path)}) # type: ignore[arg-type] + assert asyncio.run(worker.result()) == result + + +def test_a_job_shows_every_progress_field_and_the_full_view_adds_output_files() -> None: + job = DownloadQueueManager().create_job("EXAMPLE", "t") + apply_progress(job, {"phase": "muxing", "output_files": ["a.mkv"]}) + short, full = job.to_dict(), job.to_dict(include_full_details=True) + assert set(PROGRESS_FIELDS) - set(short) == {"output_files"} + assert short["phase"] == "muxing" and full["output_files"] == ["a.mkv"] + assert {f.name for f in fields(JobProgress)} <= set(full) + + +def test_the_history_entry_takes_its_fields_from_the_full_job_view( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from unshackle.core.api import download_manager + + history = tmp_path / "api_history.jsonl" + monkeypatch.setattr(download_manager, "history_path", lambda: history) + job = DownloadQueueManager().create_job("EXAMPLE", "t", credential="user:secretpass") + job.status = JobStatus.FAILED + job.error_message = "login failed for user:secretpass" + job.skipped_titles = [{"title": "Show S01E02", "reason": "missing ko"}] + record_job_history(job) + entry = json.loads(history.read_text(encoding="utf-8")) + full = job.to_dict(include_full_details=True) + assert set(entry) == {"owner", *HISTORY_FIELDS} + assert {name: entry[name] for name in HISTORY_FIELDS} == {name: full[name] for name in HISTORY_FIELDS} + assert "secretpass" not in json.dumps(entry) diff --git a/tests/remote/unit/test_progress_throttle.py b/tests/remote/unit/test_progress_throttle.py index 3629ecbae..10d70f109 100644 --- a/tests/remote/unit/test_progress_throttle.py +++ b/tests/remote/unit/test_progress_throttle.py @@ -14,7 +14,7 @@ from pathlib import Path import pytest from unshackle.core.api import progress as progress_module -from unshackle.core.api.download_worker import write_result +from unshackle.core.api.job_channel import write_json from unshackle.core.api.progress import build_job_progress_callables pytestmark = pytest.mark.unit @@ -110,7 +110,7 @@ def test_concurrent_writers_do_not_clobber_each_other(tmp_path: Path): start.wait() try: for tick in range(40): - write_result(target, {"writer": index, "tick": tick}) + write_json(target, {"writer": index, "tick": tick}) except BaseException as exc: # noqa: BLE001 - reported to the test thread errors.append(exc) diff --git a/tests/remote/unit/test_worker_speed_limit.py b/tests/remote/unit/test_worker_speed_limit.py index 7c81ddbad..19e52adf2 100644 --- a/tests/remote/unit/test_worker_speed_limit.py +++ b/tests/remote/unit/test_worker_speed_limit.py @@ -9,6 +9,7 @@ import pytest from unshackle.core.api import download_worker from unshackle.core.api.download_manager import DownloadQueueManager from unshackle.core.api.download_worker import apply_payload_speed_limit +from unshackle.core.api.job_channel import JobPayload requests_downloader = importlib.import_module("unshackle.core.downloaders.requests") @@ -22,14 +23,14 @@ def test_worker_share_of_limit(lock, expected): def test_worker_locks_payload_limit_against_job_reset(): - apply_payload_speed_limit({"speed_limit": 1_000_000}) + apply_payload_speed_limit(JobPayload("j1", "SVC", "t", speed_limit=1_000_000)) requests_downloader.set_speed_limit(None) limiter = requests_downloader.speed_limiter assert limiter is not None and limiter.rate == 1_000_000 def test_worker_without_payload_limit_stays_unlimited(): - apply_payload_speed_limit({"speed_limit": None}) + apply_payload_speed_limit(JobPayload("j1", "SVC", "t")) assert requests_downloader.speed_limiter is None diff --git a/unshackle/commands/dl.py b/unshackle/commands/dl.py index baa90596c..56db4dc87 100644 --- a/unshackle/commands/dl.py +++ b/unshackle/commands/dl.py @@ -129,6 +129,7 @@ from unshackle.core.vaults import Vaults, load_config_vaults if TYPE_CHECKING: import pysubs2 + from unshackle.core.api.job_channel import ProgressSink from unshackle.core.title_source import ServerKeySource @@ -1552,7 +1553,7 @@ class dl: merge_video: bool | None = None, real_video_bitrate: bool = False, real_audio_bitrate: bool = False, - progress_sink: Callable[[dict[str, Any]], None] | None = None, + progress_sink: ProgressSink | None = None, postscript: Sequence[str] = (), no_postscript: bool = False, all_drm: bool = False, @@ -2503,9 +2504,7 @@ class dl: # Now repack the decrypted tracks if progress_sink and any(getattr(t, "needs_repack", False) for t in title.tracks): - progress_sink( - {"phase": "repackaging", "progress": 92.0, "status": "downloading", "active_tracks": []} - ) + progress_sink({"phase": "repackaging", "progress": 92.0, "active_tracks": []}) with console.status("Repackaging tracks with FFMPEG..."): has_repacked = False # Video tracks whose VUI was folded into the repack pass; skipped in the VUI loop below. diff --git a/unshackle/core/api/download_manager.py b/unshackle/core/api/download_manager.py index 59d6e7fbc..f3b0bd1ed 100644 --- a/unshackle/core/api/download_manager.py +++ b/unshackle/core/api/download_manager.py @@ -3,13 +3,9 @@ import hashlib import importlib import json import logging -import os -import sys -import tempfile import threading import uuid from collections import deque -from collections.abc import Callable from contextlib import suppress from dataclasses import dataclass, field from datetime import datetime, timedelta @@ -18,6 +14,14 @@ from pathlib import Path from typing import TYPE_CHECKING, Any from unshackle.core.api.events import bus, publish_service_event, put_latest +from unshackle.core.api.job_channel import ( + PROGRESS_FIELDS, + JobPayload, + JobProgress, + ProgressSink, + WorkerProcess, + apply_progress, +) from unshackle.core.api.sanitize import sanitize_log from unshackle.core.credential import Credential from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_path, redact_text @@ -120,8 +124,8 @@ TERMINAL_STATUSES = (JobStatus.COMPLETED, JobStatus.FAILED, JobStatus.CANCELLED) @dataclass -class DownloadJob: - """Represents a download job with all its parameters and status.""" +class DownloadJob(JobProgress): + """Represents a download job with all its parameters and status; its progress fields come from the worker.""" job_id: str status: JobStatus @@ -132,39 +136,13 @@ class DownloadJob: started_time: datetime | None = None completed_time: datetime | None = None - progress: float = 0.0 - output_files: list[str] = field(default_factory=list) error_message: str | None = None error_details: str | None = None error_code: str | None = None error_traceback: str | None = None worker_stderr: str | None = None - phase: str | None = None - title: str | None = None - current_title: str | None = None - completed_tracks: int = 0 - total_tracks: int = 0 - active_tracks: list[str] = field(default_factory=list) - track_progress: list[dict[str, Any]] = field(default_factory=list) - segments_done: float = 0.0 - segments_total: float = 0.0 - speed: str | None = None - - # Prompt a service raised through prompt_user() and waits on; answered by submit_input(). - input_prompt: str | None = None - # Message a service shows through show_notice() while it waits for an approval; needs no answer. - notice: str | None = None - # Text of the QR code that goes with input_prompt or notice. - qr: str | None = None - - # Subtitles skipped under skip_subtitle_errors (non-fatal). Each entry is a dl.SkippedSubtitle - # dict (id / language / title) so a client can report which weren't available. - skipped_subtitles: list[dict[str, Any]] = field(default_factory=list) - # Titles skipped because a requested track or language is missing; each a dl.SkippedTitle (title / reason). - skipped_titles: list[dict[str, Any]] = field(default_factory=list) - cancel_event: threading.Event = field(default_factory=threading.Event) # Guards against writing the same job to the persistent history file twice. @@ -183,22 +161,7 @@ class DownloadJob: "created_time": self.created_time.isoformat(), "service": self.service, "title_id": self.title_id, - "title": self.title, - "progress": self.progress, - "phase": self.phase, - "current_title": self.current_title, - "completed_tracks": self.completed_tracks, - "total_tracks": self.total_tracks, - "active_tracks": self.active_tracks, - "track_progress": self.track_progress, - "segments_done": self.segments_done, - "segments_total": self.segments_total, - "speed": self.speed, - "skipped_subtitles": self.skipped_subtitles, - "skipped_titles": self.skipped_titles, - "input_prompt": self.input_prompt, - "notice": self.notice, - "qr": self.qr, + **{name: getattr(self, name) for name in PROGRESS_FIELDS if name != "output_files"}, } if include_full_details: @@ -245,6 +208,19 @@ def history_limit() -> int: return 100 +HISTORY_FIELDS = ( + "job_id", + "service", + "title_id", + "title", + "status", + "created_time", + "completed_time", + "output_files", + "skipped_titles", + "parameters", + "error_message", +) _history_appends_since_trim = 0 # module-level; record_job_history runs serialized on the event loop @@ -254,20 +230,8 @@ def record_job_history(job: DownloadJob) -> None: if job.history_recorded or job.status not in TERMINAL_STATUSES: return job.history_recorded = True - entry = { - "job_id": job.job_id, - "owner": owner_id(job.owner_key), - "service": job.service, - "title_id": job.title_id, - "title": job.title, - "status": job.status.value, - "created_time": job.created_time.isoformat(), - "completed_time": job.completed_time.isoformat() if job.completed_time else None, - "output_files": job.output_files, - "skipped_titles": job.skipped_titles, - "parameters": redact_parameters(job.parameters), - "error_message": _redact_text(job.error_message, job.parameters, job.service), - } + details = job.to_dict(include_full_details=True) + entry = {"owner": owner_id(job.owner_key), **{name: details[name] for name in HISTORY_FIELDS}} try: path = history_path() path.parent.mkdir(parents=True, exist_ok=True) @@ -389,7 +353,7 @@ def perform_download( service: str, title_id: str, params: dict[str, Any], - progress_callback: Callable[[dict[str, Any]], None] | None = None, + progress_callback: ProgressSink | None = None, ) -> list[str]: """Do the synchronous download work for a job. @@ -519,8 +483,7 @@ class DownloadQueueManager: self._priority_jobs: deque = deque() self._promoted_ids: set = set() # their stale FIFO-queue copies get skipped via this set self._active_downloads: dict[str, asyncio.Task] = {} - self._download_processes: dict[str, asyncio.subprocess.Process] = {} - self._job_temp_files: dict[str, dict[str, str]] = {} + self._workers: dict[str, WorkerProcess] = {} self._workers_started = False self._shutdown_event = asyncio.Event() self._subscribers: dict[str, list[asyncio.Queue]] = {} @@ -632,12 +595,11 @@ class DownloadQueueManager: task.cancel() log.info(f"Cancelled download task for job {sanitize_log(job_id)}") - process = self._download_processes.get(job_id) - if process: - try: - process.terminate() + worker = self._workers.get(job_id) + if worker: + if worker.terminate(): log.info(f"Terminated worker process for job {sanitize_log(job_id)}") - except ProcessLookupError: + else: log.debug(f"Worker process for job {sanitize_log(job_id)} already exited") return True @@ -646,10 +608,9 @@ class DownloadQueueManager: def submit_input(self, job: DownloadJob, response: str) -> bool: """Send *response* to the job's worker when it waits on a prompt; ``False`` when no prompt is pending.""" - process = self._download_processes.get(job.job_id) - if not job.input_prompt or process is None or process.stdin is None: + worker = self._workers.get(job.job_id) + if not job.input_prompt or worker is None or not worker.answer(response): return False - process.stdin.write((json.dumps(response) + "\n").encode("utf-8")) # Cleared here, not on the worker's next progress write, so a second submit cannot queue a stale answer. job.input_prompt = None self.publish(job, "progress") @@ -736,25 +697,8 @@ class DownloadQueueManager: for job_id in list(self._jobs): self.cancel_job(job_id) - for job_id, process in list(self._download_processes.items()): - try: - await asyncio.wait_for(process.wait(), timeout=5) - except TimeoutError: - log.warning(f"Worker process for job {job_id} did not exit, killing") - with suppress(ProcessLookupError): - process.kill() - await process.wait() - finally: - self._download_processes.pop(job_id, None) - - # Clean up any remaining temp files - for paths in self._job_temp_files.values(): - for path in paths.values(): - try: - os.remove(path) - except OSError: - pass - self._job_temp_files.clear() + for worker in list(self._workers.values()): + await worker.stop() # Wait for workers to finish if self._active_downloads: @@ -865,131 +809,33 @@ class DownloadQueueManager: async def run_download_async(self, job: DownloadJob) -> list[str]: """Invoke a job worker subprocess to do the download.""" - - payload = { - "job_id": job.job_id, - "service": job.service, - "title_id": job.title_id, - "parameters": job.parameters, - "speed_limit": self.worker_speed_limit(), - } - - payload_fd, payload_path = tempfile.mkstemp(prefix=f"unshackle_job_{job.job_id}_", suffix="_payload.json") - os.close(payload_fd) - result_fd, result_path = tempfile.mkstemp(prefix=f"unshackle_job_{job.job_id}_", suffix="_result.json") - os.close(result_fd) - progress_fd, progress_path = tempfile.mkstemp(prefix=f"unshackle_job_{job.job_id}_", suffix="_progress.json") - os.close(progress_fd) - - with open(payload_path, "w", encoding="utf-8") as handle: - json.dump(payload, handle) - - process = await asyncio.create_subprocess_exec( - sys.executable, - "-m", - "unshackle.core.api.download_worker", - payload_path, - result_path, - progress_path, - stdin=asyncio.subprocess.PIPE, - stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.PIPE, + worker = await WorkerProcess.spawn( + JobPayload(job.job_id, job.service, job.title_id, job.parameters, self.worker_speed_limit()) ) - - self._download_processes[job.job_id] = process - self._job_temp_files[job.job_id] = {"payload": payload_path, "result": result_path, "progress": progress_path} - - async def drain() -> tuple[bytes, bytes]: - """Collect the worker's output; unlike communicate(), leave stdin open for prompt answers.""" - assert process.stdout is not None and process.stderr is not None - out, err, _ = await asyncio.gather(process.stdout.read(), process.stderr.read(), process.wait()) - return out, err - - communicate_task = asyncio.create_task(drain()) - - stdout_bytes = b"" - stderr_bytes = b"" - last_progress_stat: tuple[int, int] | None = None # (st_mtime_ns, st_size) of last parse - last_published: dict[str, Any] | None = None + self._workers[job.job_id] = worker try: while True: - done, _ = await asyncio.wait({communicate_task}, timeout=0.5) + exited = await worker.wait(0.5) - # Read progress before the exit check so the worker's last write lands (skip an unchanged file) + # Read progress before the exit check so the worker's last write lands. try: - stat = os.stat(progress_path) - stat_key = (stat.st_mtime_ns, stat.st_size) - if stat_key != last_progress_stat: - with open(progress_path, encoding="utf-8") as handle: - progress_data = json.load(handle) - prompt_before = job.input_prompt - if progress_data.get("phase") and progress_data["phase"] != job.phase: - job.phase = progress_data["phase"] - if progress_data.get("current_title"): - job.current_title = str(progress_data["current_title"]) - if progress_data.get("title"): - job.title = str(progress_data["title"]) - if progress_data.get("output_files"): - job.output_files = [str(f) for f in progress_data["output_files"]] - if progress_data.get("total_tracks"): - job.total_tracks = int(progress_data["total_tracks"]) - if progress_data.get("completed_tracks") is not None: - job.completed_tracks = int(progress_data["completed_tracks"]) - if "active_tracks" in progress_data: - job.active_tracks = list(progress_data["active_tracks"]) - if "track_progress" in progress_data: - job.track_progress = list(progress_data["track_progress"]) - for _sk in ("segments_done", "segments_total"): - if _sk in progress_data: - try: - setattr(job, _sk, float(progress_data[_sk])) - except (TypeError, ValueError): - pass - if progress_data.get("speed"): - job.speed = str(progress_data["speed"]) - if "input_prompt" in progress_data: - job.input_prompt = progress_data["input_prompt"] - if "notice" in progress_data: - job.notice = progress_data["notice"] - if "qr" in progress_data: - job.qr = progress_data["qr"] - if progress_data.get("skipped_subtitles"): - job.skipped_subtitles = progress_data["skipped_subtitles"] - if progress_data.get("skipped_titles"): - job.skipped_titles = progress_data["skipped_titles"] - if "progress" in progress_data: - new_progress = float(progress_data["progress"]) - if new_progress != job.progress: - job.progress = new_progress - log.debug(f"Job {job.job_id} progress updated: {job.progress}%") - # submit_input() clears the prompt out of band, so a re-prompt with the same text - # leaves the file equal to last_published; publish the prompt change anyway. - if progress_data != last_published or job.input_prompt != prompt_before: - last_published = progress_data - self.publish(job, "progress") - last_progress_stat = stat_key - except (OSError, json.JSONDecodeError, ValueError) as e: + update = worker.read_progress() + if update is not None and apply_progress(job, update): + self.publish(job, "progress") + except (OSError, ValueError) as e: log.debug(f"Could not read progress for job {job.job_id}: {e}") - if communicate_task in done: - stdout_bytes, stderr_bytes = communicate_task.result() + if exited: break if job.cancel_event.is_set() or job.status == JobStatus.CANCELLED: log.info(f"Cancellation detected for job {job.job_id}, terminating worker process") - process.terminate() - try: - await asyncio.wait_for(communicate_task, timeout=5) - except TimeoutError: - log.warning(f"Worker process for job {job.job_id} did not terminate, killing") - process.kill() - await asyncio.wait_for(communicate_task, timeout=5) + await worker.stop() raise asyncio.CancelledError("Job was cancelled") - returncode = process.returncode - stdout = stdout_bytes.decode("utf-8", errors="ignore") - stderr = stderr_bytes.decode("utf-8", errors="ignore") + returncode = worker.returncode + stdout, stderr = worker.output() # A service can echo a credential or a proxy URL into its output, so scrub it before # it reaches the log as well, not only the API response. @@ -1004,58 +850,27 @@ class DownloadQueueManager: else: log.debug(f"Worker stderr for job {job.job_id}: {safe_stderr}") - result_data: dict[str, Any] | None = None - for attempt in range(5): - try: - with open(result_path, encoding="utf-8") as handle: - result_data = json.load(handle) - except FileNotFoundError: - log.error(f"Result file missing for job {job.job_id}") - except PermissionError as exc: - log.debug(f"Result file for job {job.job_id} denied, retrying: {exc}") - await asyncio.sleep(0.02 * (attempt + 1)) - continue - except json.JSONDecodeError as exc: - log.error(f"Failed to parse worker result for job {job.job_id}: {exc}") - break + result = await worker.result() + if result and returncode == 0 and result.status == "success": + job.error_traceback = result.traceback + return result.output_files - if result_data: - job.error_traceback = result_data.get("traceback") - - if returncode != 0: - message = result_data.get("message") if result_data else "unknown error" - if result_data: - job.error_details = result_data.get("error_details", message) - job.error_code = result_data.get("error_code") + message = result.message if result else ("unknown error" if returncode else "worker did not report success") + if result: + job.error_traceback = result.traceback + job.error_details = result.error_details if result.error_details is not None else message + job.error_code = result.error_code + if returncode: raise Exception(f"Worker exited with code {returncode}: {message}") - - if not result_data or result_data.get("status") != "success": - message = result_data.get("message") if result_data else "worker did not report success" - if result_data: - job.error_details = result_data.get("error_details", message) - job.error_code = result_data.get("error_code") - raise Exception(f"Worker failure: {message}") - - return result_data.get("output_files", []) + raise Exception(f"Worker failure: {message}") finally: - if not communicate_task.done(): - communicate_task.cancel() - with suppress(asyncio.CancelledError): - await communicate_task - - self._download_processes.pop(job.job_id, None) + await worker.close() + self._workers.pop(job.job_id, None) job.input_prompt = None job.notice = None job.qr = None - temp_paths = self._job_temp_files.pop(job.job_id, {}) - for path in temp_paths.values(): - try: - os.remove(path) - except OSError: - pass - async def cleanup_worker(self) -> None: """Job worker that periodically cleans up old jobs.""" while not self._shutdown_event.is_set(): diff --git a/unshackle/core/api/download_worker.py b/unshackle/core/api/download_worker.py index f55daefa3..379ae1450 100644 --- a/unshackle/core/api/download_worker.py +++ b/unshackle/core/api/download_worker.py @@ -3,21 +3,23 @@ from __future__ import annotations import io -import json import logging -import os import queue import sys import threading -import time import traceback -from collections.abc import Callable from pathlib import Path -from typing import Any -from uuid import uuid4 from unshackle.core import session as http_session from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT +from unshackle.core.api.job_channel import ( + JobPayload, + ProgressFile, + ProgressSink, + WorkerResult, + decode_answer, + write_result, +) from unshackle.core.console import set_notice_handler, set_prompt_handler from unshackle.core.downloaders import format_speed, set_speed_limit from unshackle.core.remote_protocol import APIErrorCode, coded @@ -27,47 +29,11 @@ from .download_manager import perform_download log = logging.getLogger("download_worker") -def read_payload(path: Path) -> dict[str, Any]: - with path.open("r", encoding="utf-8") as handle: - return json.load(handle) - - -_replace_lock = threading.Lock() - - -def write_result(path: Path, payload: dict[str, Any]) -> None: - """Write the payload with an atomic replace, because the parent polls this file during the write. - - Each call gets its own temp name, so two threads writing this destination cannot replace away - the temp file the other is about to move. - - Windows denies the replace while another thread or the parent holds the destination open. The - lock removes the in-process contention; the retry covers the parent process. - """ - path.parent.mkdir(parents=True, exist_ok=True) - tmp = path.with_name(f"{path.name}.{uuid4().hex}.tmp") - try: - tmp.write_text(json.dumps(payload), encoding="utf-8") - with _replace_lock: - for attempt in range(10): - try: - os.replace(tmp, path) - return - except PermissionError: - if attempt == 9: - raise - time.sleep(0.02 * (attempt + 1)) - except OSError: - tmp.unlink(missing_ok=True) - raise - - -def relay_prompts(progress_callback: Callable[[dict[str, Any]], None]) -> None: +def relay_prompts(progress_callback: ProgressSink) -> None: """Send each prompt_user() prompt to the parent as ``input_prompt`` progress, and read the answer from stdin. - The parent writes each answer as one JSON string per line, so an answer can hold a newline. The reader - uses unbuffered stdin: a daemon thread blocked in ``sys.stdin.buffer`` aborts the interpreter at shutdown. - Prompts go out one at a time, and a prompt discards answers that arrived before it, such as a late + The reader uses unbuffered stdin: a daemon thread blocked in ``sys.stdin.buffer`` aborts the interpreter at + shutdown. Prompts go out one at a time, and a prompt discards answers that arrived before it, such as a late answer to a prompt that timed out. A show_notice() message goes out as ``notice`` progress and needs no answer. The QR code text of a prompt or notice goes out with it as ``qr``. """ @@ -76,7 +42,7 @@ def relay_prompts(progress_callback: Callable[[dict[str, Any]], None]) -> None: def read_answers() -> None: for line in io.FileIO(sys.stdin.fileno(), "rb", closefd=False): - answers.put(json.loads(line.decode("utf-8", errors="replace"))) + answers.put(decode_answer(line)) threading.Thread(target=read_answers, name="prompt-answers", daemon=True).start() @@ -100,13 +66,12 @@ def relay_prompts(progress_callback: Callable[[dict[str, Any]], None]) -> None: set_notice_handler(lambda message, qr: progress_callback({"notice": message, "qr": qr})) -def apply_payload_speed_limit(payload: dict[str, Any]) -> None: +def apply_payload_speed_limit(payload: JobPayload) -> None: """Lock this worker's share of the server speed limit so the job cannot clear it.""" - limit = payload.get("speed_limit") - if not limit: + if not payload.speed_limit: return - set_speed_limit(limit, lock=True) - log.info(f"Job speed limit: {format_speed(limit)} (share of the global speed limit)") + set_speed_limit(payload.speed_limit, lock=True) + log.info(f"Job speed limit: {format_speed(payload.speed_limit)} (share of the global speed limit)") def main(argv: list[str]) -> int: @@ -118,41 +83,25 @@ def main(argv: list[str]) -> int: return 2 http_session.record_bodies = False - payload_path = Path(argv[1]) result_path = Path(argv[2]) - progress_path = Path(argv[3]) if len(argv) > 3 else None + progress: ProgressSink = ProgressFile(Path(argv[3])) if len(argv) > 3 else (lambda update: None) - result: dict[str, Any] = {} + payload: JobPayload | None = None + result: WorkerResult | None = None exit_code = 0 try: - payload = read_payload(payload_path) - job_id = payload["job_id"] - service = payload["service"] - title_id = payload["title_id"] - params = payload.get("parameters", {}) + payload = JobPayload.read(Path(argv[1])) apply_payload_speed_limit(payload) - log.info(f"Worker starting job {job_id} ({service}:{title_id})") + log.info(f"Worker starting job {payload.job_id} ({payload.service}:{payload.title_id})") - # Merged so sparse keys (current_title, output_files) survive later writes. - progress_state: dict[str, Any] = {} - progress_lock = threading.Lock() + relay_prompts(progress) + output_files = perform_download( + payload.job_id, payload.service, payload.title_id, payload.parameters, progress_callback=progress + ) - def progress_callback(progress_data: dict[str, Any]) -> None: - """Write progress updates to file for main process to read.""" - if progress_path: - try: - with progress_lock: - progress_state.update(progress_data) - write_result(progress_path, progress_state) - except Exception as e: - log.error(f"Failed to write progress update: {e}") - - relay_prompts(progress_callback) - output_files = perform_download(job_id, service, title_id, params, progress_callback=progress_callback) - - result = {"status": "success", "output_files": output_files} + result = WorkerResult(status="success", output_files=output_files) except Exception as exc: # noqa: BLE001 - capture for parent process from unshackle.core.api.errors import categorize_exception @@ -164,23 +113,24 @@ def main(argv: list[str]) -> int: api_error = categorize_exception( exc, context={ - "service": payload.get("service") if "payload" in locals() else None, - "title_id": payload.get("title_id") if "payload" in locals() else None, - "job_id": payload.get("job_id") if "payload" in locals() else None, + "service": payload.service if payload else None, + "title_id": payload.title_id if payload else None, + "job_id": payload.job_id if payload else None, }, ) - result = { - "status": "error", - "message": str(exc), - "error_details": api_error.message, - "error_code": api_error.error_code.value, - "traceback": tb, - } + result = WorkerResult( + status="error", + message=str(exc), + error_details=api_error.message, + error_code=api_error.error_code.value, + traceback=tb, + ) finally: try: - write_result(result_path, result) + if result is not None: + write_result(result_path, result) except Exception as exc: # noqa: BLE001 - last resort logging log.error(f"Failed to write worker result file: {exc}") diff --git a/unshackle/core/api/job_channel.py b/unshackle/core/api/job_channel.py new file mode 100644 index 000000000..e6ae774ca --- /dev/null +++ b/unshackle/core/api/job_channel.py @@ -0,0 +1,318 @@ +"""The edge between a REST download job and its worker process: payload, progress, prompt answers and result. + +The parent spawns the worker with a payload file, a result file and a progress file, and writes prompt +answers to the worker's stdin. Both sides read and write these channels only through this module. +""" + +from __future__ import annotations + +import asyncio +import json +import logging +import os +import sys +import tempfile +import threading +import time +from collections.abc import Callable, Iterable +from contextlib import suppress +from dataclasses import asdict, dataclass, field, fields, replace +from pathlib import Path +from typing import Any, TypeVar +from uuid import uuid4 + +log = logging.getLogger("job_channel") + +ProgressSink = Callable[[dict[str, Any]], None] + + +@dataclass(kw_only=True) +class JobProgress: + """The progress a worker reports and a job shows; ``DownloadJob`` holds the same fields. + + One presence rule for each field: a field in an update replaces the value, ``0`` too, so a ``total_tracks`` + of 0 lands, and ``None`` too for a field that is not a number. A field not in the update keeps its value. + """ + + progress: float = 0.0 + phase: str | None = None + title: str | None = None + current_title: str | None = None + completed_tracks: int = 0 + total_tracks: int = 0 + active_tracks: list[str] = field(default_factory=list) + track_progress: list[dict[str, Any]] = field(default_factory=list) + segments_done: float = 0.0 + segments_total: float = 0.0 + speed: str | None = None + input_prompt: str | None = None + notice: str | None = None + qr: str | None = None + skipped_subtitles: list[dict[str, Any]] = field(default_factory=list) + skipped_titles: list[dict[str, Any]] = field(default_factory=list) + output_files: list[str] = field(default_factory=list) + + +PROGRESS_FIELDS = tuple(f.name for f in fields(JobProgress)) +_FIELD_SET = frozenset(PROGRESS_FIELDS) +_NUMBER_FIELDS: dict[str, Callable[[Any], Any]] = { + f.name: type(f.default) for f in fields(JobProgress) if type(f.default) in (int, float) +} + + +def apply_progress(target: JobProgress, update: dict[str, Any]) -> bool: + """Apply ``update`` to ``target`` and tell whether a field changed. + + A name that is not a ``JobProgress`` field or a number field with a bad value raises ``ValueError`` and + changes nothing. + """ + if not isinstance(update, dict): + raise ValueError(f"Job progress update is a {type(update).__name__}, not an object") + unknown = update.keys() - _FIELD_SET + if unknown: + raise ValueError(f"Unknown job progress key(s): {', '.join(sorted(unknown))}") + values = dict(update) + for name, cast in _NUMBER_FIELDS.items(): + if name in values: + try: + values[name] = cast(values[name]) + except (TypeError, ValueError, OverflowError): + raise ValueError(f"Bad job progress value for {name}: {values[name]!r}") from None + changed = False + for name, value in values.items(): + if value != getattr(target, name): + setattr(target, name, value) + changed = True + return changed + + +_replace_lock = threading.Lock() + + +def write_json(path: Path, payload: dict[str, Any]) -> None: + """Write the payload with an atomic replace, because the other process reads this file during the write. + + Each call gets its own temp name, so two threads writing this destination cannot replace away + the temp file the other is about to move. + + Windows denies the replace while another thread or the parent holds the destination open. The + lock removes the in-process contention; the retry covers the parent process. + """ + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(f"{path.name}.{uuid4().hex}.tmp") + try: + tmp.write_text(json.dumps(payload), encoding="utf-8") + with _replace_lock: + for attempt in range(10): + try: + os.replace(tmp, path) + return + except PermissionError: + if attempt == 9: + raise + time.sleep(0.02 * (attempt + 1)) + except OSError: + tmp.unlink(missing_ok=True) + raise + + +class ProgressFile: + """The worker's progress sink: it merges each update into one ``JobProgress`` and writes the whole record.""" + + def __init__(self, path: Path) -> None: + self.path = path + self.state = JobProgress() + self._lock = threading.Lock() + + def __call__(self, update: dict[str, Any]) -> None: + """Write the record with ``update`` applied; it logs and drops a bad update and never raises.""" + try: + with self._lock: + state = replace(self.state) + if apply_progress(state, update): + write_json(self.path, vars(state)) + self.state = state + except Exception as e: # noqa: BLE001 - a progress write must never fail the download + log.error(f"Failed to write progress update: {e}") + + +@dataclass +class JobPayload: + """What the parent gives a worker to start a job.""" + + job_id: str + service: str + title_id: str + parameters: dict[str, Any] = field(default_factory=dict) + speed_limit: float | None = None + + @classmethod + def read(cls, path: Path) -> JobPayload: + return _load(cls, json.loads(path.read_text(encoding="utf-8"))) + + +@dataclass +class WorkerResult: + """What a worker reports when it ends; ``status`` is ``success`` or ``error``.""" + + status: str + output_files: list[str] = field(default_factory=list) + message: str | None = None + error_details: str | None = None + error_code: str | None = None + traceback: str | None = None + + +_Record = TypeVar("_Record", "JobPayload", "WorkerResult") + + +def _load(cls: type[_Record], data: dict[str, Any]) -> _Record: + """A record from its JSON object; it ignores the keys that are not fields.""" + return cls(**{f.name: data[f.name] for f in fields(cls) if f.name in data}) + + +def write_result(path: Path, result: WorkerResult) -> None: + write_json(path, asdict(result)) + + +def encode_answer(text: str) -> bytes: + """One prompt answer as one JSON line, so an answer can hold a newline.""" + return (json.dumps(text) + "\n").encode("utf-8") + + +def decode_answer(line: bytes) -> str: + return json.loads(line.decode("utf-8", errors="replace")) + + +class WorkerProcess: + """One job's worker subprocess: its files, its answer pipe and its exit.""" + + def __init__(self, job_id: str, process: asyncio.subprocess.Process, paths: dict[str, str]) -> None: + self.job_id = job_id + self.process = process + self.paths = paths + self._output: asyncio.Task[tuple[bytes, bytes]] | None = None + self._progress_stat: tuple[int, int] | None = None + + @classmethod + async def spawn(cls, payload: JobPayload) -> WorkerProcess: + """Write the payload and start ``python -m unshackle.core.api.download_worker`` on it.""" + paths: dict[str, str] = {} + try: + for name in ("payload", "result", "progress"): + fd, paths[name] = tempfile.mkstemp(prefix=f"unshackle_job_{payload.job_id}_", suffix=f"_{name}.json") + os.close(fd) + Path(paths["payload"]).write_text(json.dumps(asdict(payload)), encoding="utf-8") + process = await asyncio.create_subprocess_exec( + sys.executable, + "-m", + "unshackle.core.api.download_worker", + paths["payload"], + paths["result"], + paths["progress"], + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + except BaseException: + remove_files(paths.values()) + raise + worker = cls(payload.job_id, process, paths) + worker._output = asyncio.create_task(worker._collect()) + return worker + + async def _collect(self) -> tuple[bytes, bytes]: + """Collect the worker's output; unlike communicate(), leave stdin open for prompt answers.""" + assert self.process.stdout is not None and self.process.stderr is not None + out, err, _ = await asyncio.gather(self.process.stdout.read(), self.process.stderr.read(), self.process.wait()) + return out, err + + async def wait(self, timeout: float) -> bool: + """Wait up to ``timeout`` seconds for the worker to exit; True when it has exited.""" + assert self._output is not None + done, _ = await asyncio.wait({self._output}, timeout=timeout) + return bool(done) + + @property + def returncode(self) -> int | None: + return self.process.returncode + + def output(self) -> tuple[str, str]: + """The stdout and stderr of a worker that has exited.""" + assert self._output is not None + out, err = self._output.result() + return out.decode("utf-8", errors="ignore"), err.decode("utf-8", errors="ignore") + + def read_progress(self) -> dict[str, Any] | None: + """The progress record the worker wrote since the last read; None when the file did not change.""" + path = self.paths["progress"] + stat = os.stat(path) + key = (stat.st_mtime_ns, stat.st_size) + if key == self._progress_stat: + return None + with open(path, encoding="utf-8") as handle: + data = json.load(handle) + self._progress_stat = key + return data + + def answer(self, text: str) -> bool: + """Write one prompt answer to the worker's stdin; False when the worker has no stdin.""" + if self.process.stdin is None: + return False + self.process.stdin.write(encode_answer(text)) + return True + + def terminate(self) -> bool: + """Ask the worker to stop; False when it had already exited.""" + try: + self.process.terminate() + except ProcessLookupError: + return False + return True + + async def stop(self, grace: float = 5) -> None: + """Terminate the worker, and kill it when it is still running after ``grace`` seconds.""" + self.terminate() + try: + await asyncio.wait_for(self.process.wait(), timeout=grace) + except TimeoutError: + log.warning(f"Worker process for job {self.job_id} did not exit, killing") + with suppress(ProcessLookupError): + self.process.kill() + await self.process.wait() + + async def result(self) -> WorkerResult | None: + """The result the worker wrote; None when the file is missing, empty or not a result.""" + for attempt in range(5): + try: + with open(self.paths["result"], encoding="utf-8") as handle: + text = handle.read() + # mkstemp makes the file empty; a worker that dies before its result leaves it so. + data = json.loads(text) if text.strip() else None + except FileNotFoundError: + log.error(f"Result file missing for job {self.job_id}") + except PermissionError as exc: + log.debug(f"Result file for job {self.job_id} denied, retrying: {exc}") + await asyncio.sleep(0.02 * (attempt + 1)) + continue + except json.JSONDecodeError as exc: + log.error(f"Failed to parse worker result for job {self.job_id}: {exc}") + else: + if isinstance(data, dict) and "status" in data: + return _load(WorkerResult, data) + return None + return None + + async def close(self) -> None: + """Stop collecting the worker's output and remove its files.""" + if self._output is not None and not self._output.done(): + self._output.cancel() + with suppress(asyncio.CancelledError): + await self._output + remove_files(self.paths.values()) + + +def remove_files(paths: Iterable[str]) -> None: + for path in paths: + with suppress(OSError): + os.remove(path) diff --git a/unshackle/core/api/progress.py b/unshackle/core/api/progress.py index 968ac6859..81af32374 100644 --- a/unshackle/core/api/progress.py +++ b/unshackle/core/api/progress.py @@ -8,12 +8,15 @@ from __future__ import annotations import time from collections.abc import Callable -from typing import Any +from typing import TYPE_CHECKING, Any from unshackle.core.api.sanitize import sanitize_log from unshackle.core.constants import AnyTrack from unshackle.core.utilities import standard_resolution +if TYPE_CHECKING: + from unshackle.core.api.job_channel import ProgressSink + JOB_PROGRESS_TERMINAL_STATES = {"Downloaded", "Decrypted", "[yellow]SKIPPED"} PROGRESS_EMIT_INTERVAL = 0.5 @@ -65,7 +68,7 @@ def track_progress_weight(track: AnyTrack) -> float: def build_job_progress_callables( tracks: list[AnyTrack], inner_callables: list[Callable[..., None]], - sink: Callable[[dict[str, Any]], None], + sink: ProgressSink, ) -> list[Callable[..., None]]: """Wrap each track's progress callable so ``sink`` receives aggregate job progress. @@ -126,7 +129,6 @@ def build_job_progress_callables( "segments_done": seg_done[active_i] if active_i is not None else 0.0, "segments_total": seg_total[active_i] if active_i is not None else 0.0, "speed": speeds[active_i] if active_i is not None else None, - "status": "downloading", } ) diff --git a/unshackle/core/mux_step.py b/unshackle/core/mux_step.py index 86dcbd789..3f1d56326 100644 --- a/unshackle/core/mux_step.py +++ b/unshackle/core/mux_step.py @@ -10,7 +10,7 @@ from concurrent.futures import ThreadPoolExecutor from copy import deepcopy from functools import partial from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any import click from pymediainfo import MediaInfo @@ -30,6 +30,9 @@ from unshackle.core.tracks.selection import select_hybrid_bases from unshackle.core.utilities import standard_resolution from unshackle.core.utils.subprocess import tool_reason +if TYPE_CHECKING: + from unshackle.core.api.job_channel import ProgressSink + MuxOutput = tuple[Path, Audio.Codec | None] @@ -108,7 +111,7 @@ def mux_title( range_: Sequence[Video.Range], vcodec: Sequence[Any], generate_dv: bool, - progress_sink: Callable[[dict[str, Any]], None] | None, + progress_sink: ProgressSink | None, write_sidecars: Callable[[str, Path], list[Path]] | None, ) -> tuple[list[MuxOutput], dict[Path | None, list[Path]]]: """Mux the tracks of a title, then delete them; the muxed files and the sidecar files of each. @@ -229,7 +232,7 @@ def mux_title( return sum(v.path.stat().st_size for v in video_tracks if v and v.path and v.path.exists()) if progress_sink: - progress_sink({"phase": "muxing", "progress": 96.0, "status": "downloading", "active_tracks": []}) + progress_sink({"phase": "muxing", "progress": 96.0, "active_tracks": []}) try: with SyncLive(Padding(progress, (0, 5, 1, 5)), console=console, refresh_per_second=20):