refactor(api): put the job and worker process channels in job_channel

This commit is contained in:
imSp4rky
2026-11-29 14:33:21 -07:00
parent de2ffcb9bd
commit ccc327e2c3
12 changed files with 665 additions and 413 deletions
@@ -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(
+36 -59
View File
@@ -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)
+179
View File
@@ -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)
+2 -2
View File
@@ -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)
+3 -2
View File
@@ -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