forked from kenzuya/unshackle
328 lines
12 KiB
Python
328 lines
12 KiB
Python
"""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
|
|
|
|
from unshackle.core import process_exit
|
|
|
|
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)
|
|
already_present: 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.
|
|
|
|
A worker that stops writes nothing: the parent has removed the file of a cancelled job.
|
|
"""
|
|
if process_exit.stopping():
|
|
return
|
|
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
|
|
archive_scope: str = "api-unowned"
|
|
|
|
@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)
|