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
+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)