forked from kenzuya/unshackle
refactor(api): put the job and worker process channels in job_channel
This commit is contained in:
@@ -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():
|
||||
|
||||
@@ -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}")
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -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",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
Reference in New Issue
Block a user