"""This is one process per job, not a shared ProcessPoolExecutor. Killing a timed-out pool worker breaks the pool and fails the other job running in it.""" from __future__ import annotations import logging import multiprocessing import os import shutil import signal import subprocess import sys import tempfile import threading import time from collections.abc import Callable, Mapping from concurrent.futures import Future, ThreadPoolExecutor from contextlib import suppress from dataclasses import dataclass, field from datetime import datetime from functools import partial from multiprocessing.process import BaseProcess from pathlib import Path from typing import Annotated, Literal, Protocol from pydantic import BaseModel, Field, ValidationError from app.domain.errors import CodedError, ErrorCode, PasswordError, PasswordReason, ToolError from app.domain.job import Job, JobError, JobId from app.domain.mapping import MappingAsk, MappingError, SheetChoice from app.domain.tool import Progress, Reporter, Tool, ToolResult, ToolRun from app.logs import configure_logging, frames from app.services.jobs import JobExpiredError, JobNotFoundError, JobStore from app.settings import Settings log = logging.getLogger(__name__) _SPAWN = multiprocessing.get_context("spawn") _POLL_SECONDS = 0.2 _EXIT_GRACE_SECONDS = 5.0 _DISCARD_WAIT_SECONDS = 30.0 _TASKKILL = Path(os.environ.get("SYSTEMROOT", r"C:\Windows")) / "System32" / "taskkill.exe" class _ProgressMessage(BaseModel): kind: Literal["progress"] = "progress" progress: Progress class _ResultMessage(BaseModel): kind: Literal["result"] = "result" result: ToolResult class _PasswordMessage(BaseModel): kind: Literal["passwords"] = "passwords" files: dict[str, PasswordReason] class _MappingMessage(BaseModel): kind: Literal["mapping"] = "mapping" ask: MappingAsk class _ErrorMessage(BaseModel): kind: Literal["error"] = "error" error: JobError error_type: str | None = None frames: list[str] = Field(default_factory=list) type _Outcome = _ResultMessage | _PasswordMessage | _MappingMessage | _ErrorMessage class _Envelope(BaseModel): message: Annotated[ _ProgressMessage | _ResultMessage | _PasswordMessage | _MappingMessage | _ErrorMessage, Field(discriminator="kind"), ] class _Channel(Protocol): def send_bytes(self, buf: bytes) -> None: ... def recv_bytes(self) -> bytes: ... def poll(self, timeout: float) -> bool: ... def close(self) -> None: ... @dataclass class _Slot: cancelled: threading.Event = field(default_factory=threading.Event) finished: threading.Event = field(default_factory=threading.Event) future: Future[None] | None = None class JobRunner: def __init__(self, store: JobStore, tools: Mapping[str, Tool], settings: Settings) -> None: self._store = store self._tools = tools self._settings = settings self._threads = ThreadPoolExecutor(settings.max_workers, thread_name_prefix="job") self._slots: dict[JobId, _Slot] = {} self._closing = False self._lock = threading.Lock() def submit(self, job_id: JobId) -> Future[None]: with self._lock: if self._closing: raise CodedError(ErrorCode.SERVER_BUSY) if job_id in self._slots: raise CodedError(ErrorCode.JOB_STATE_CONFLICT) slot = self._slots[job_id] = _Slot() future = slot.future = self._threads.submit(self._run, job_id, slot) future.add_done_callback(partial(self._release, job_id, slot)) return future def resume(self, job_id: JobId, passwords: Mapping[str, str]) -> Future[None]: self._store.update(job_id, lambda job, now: job.supply_passwords(passwords, now)) return self.submit(job_id) def remap(self, job_id: JobId, sheets: list[SheetChoice]) -> Future[None]: self._store.update(job_id, lambda job, now: job.supply_mapping(sheets, now)) return self.submit(job_id) def discard(self, job_id: JobId) -> None: """Stop the job if it is queued or running, then delete it and its folder.""" with self._lock: slot = self._slots.get(job_id) if slot is not None: slot.cancelled.set() if slot is not None: if slot.future is not None: slot.future.cancel() slot.finished.wait(_DISCARD_WAIT_SECONDS) self._store.delete(job_id) def shutdown(self) -> None: with self._lock: self._closing = True for slot in self._slots.values(): slot.cancelled.set() self._threads.shutdown(wait=True, cancel_futures=True) def _release(self, job_id: JobId, slot: _Slot, _future: Future[None]) -> None: self._forget(job_id, slot) slot.finished.set() def _forget(self, job_id: JobId, slot: _Slot) -> None: with self._lock: if self._slots.get(job_id) is slot: del self._slots[job_id] def _run(self, job_id: JobId, slot: _Slot) -> None: try: self._run_once(job_id, slot) except Exception: log.exception("job runner failed", extra={"job_id": job_id}) failure = _ErrorMessage(error=JobError.of(ErrorCode.INTERNAL_ERROR)) with suppress(CodedError): self._store.update(job_id, partial(_settle, failure)) def _run_once(self, job_id: JobId, slot: _Slot) -> None: if slot.cancelled.is_set(): return try: job = self._store.update(job_id, lambda job, now: job.start(now)) except (JobNotFoundError, JobExpiredError): return tool = self._tools[job.tool] started = time.monotonic() outcome = self._supervise(job, tool, slot) if outcome is None: return _log_outcome(job, outcome, time.monotonic() - started) # The worker has stopped. Free the slot before the outcome is visible, so a resume that # follows the password prompt at once can submit the job again. self._forget(job_id, slot) with suppress(JobNotFoundError, JobExpiredError): self._store.update(job_id, partial(_settle, outcome)) def _supervise(self, job: Job, tool: Tool, slot: _Slot) -> _Outcome | None: request = ToolRun( files=tuple( sorted( (path for path in job.input_dir.iterdir() if path.is_file()), key=lambda path: path.name.casefold(), ) ), options=job.options, output_dir=job.output_dir, scratch_dir=job.scratch_dir, toolchain=self._settings.toolchain(), passwords={name: secret.get_secret_value() for name, secret in job.passwords.items()}, mappings=job.mappings, ) receiver, sender = _SPAWN.Pipe(duplex=False) process = _SPAWN.Process( target=_work, args=(tool.execute, request, sender), name=f"job-{job.id}", daemon=True ) outcome: _Outcome | None = None try: with self._lock: if slot.cancelled.is_set(): return None _empty(job.output_dir) _empty(job.scratch_dir) process.start() sender.close() deadline = time.monotonic() + self._settings.timeout_for(tool) outcome = self._collect(job, receiver, slot, deadline) return outcome finally: receiver.close() sender.close() if process.pid is not None: timed_out = isinstance(outcome, _ErrorMessage) and ( outcome.error.code is ErrorCode.TIMEOUT ) worker_done = outcome is not None and not timed_out _stop(process, _EXIT_GRACE_SECONDS if worker_done else 0) def _collect( self, job: Job, receiver: _Channel, slot: _Slot, deadline: float ) -> _Outcome | None: while not slot.cancelled.is_set(): remaining = deadline - time.monotonic() if remaining <= 0: return _ErrorMessage(error=JobError.of(ErrorCode.TIMEOUT)) try: if not receiver.poll(min(remaining, _POLL_SECONDS)): continue payload = receiver.recv_bytes() except (EOFError, OSError): return _internal_error("WorkerExited") try: message = _Envelope.model_validate_json(payload).message except ValidationError: return _internal_error("InvalidWorkerMessage") if not isinstance(message, _ProgressMessage): return message self._store.update(job.id, partial(_report, message.progress)) return None def _internal_error(error_type: str) -> _ErrorMessage: return _ErrorMessage(error=JobError.of(ErrorCode.INTERNAL_ERROR), error_type=error_type) def _report(progress: Progress, job: Job, _now: datetime) -> Job: return job.report(progress) def _settle(outcome: _Outcome, job: Job, now: datetime) -> Job: if isinstance(outcome, _ResultMessage): return job.succeed(outcome.result, now) if isinstance(outcome, _PasswordMessage): return job.ask_for_passwords(outcome.files, now) if isinstance(outcome, _MappingMessage): return job.ask_for_mapping(outcome.ask, now) return job.fail(outcome.error, now) def _log_outcome(job: Job, outcome: _Outcome, seconds: float) -> None: fields: dict[str, object] = {"job_id": job.id, "tool": job.tool, "seconds": round(seconds, 3)} if isinstance(outcome, _ResultMessage): log.info("job succeeded", extra=fields) elif isinstance(outcome, _PasswordMessage): log.info("job is waiting for passwords", extra={**fields, "count": len(outcome.files)}) elif isinstance(outcome, _MappingMessage): log.info( "job is waiting for the mapping", extra={**fields, "sheets": len(outcome.ask.sheets)} ) else: internal = outcome.error.code is ErrorCode.INTERNAL_ERROR log.log( logging.ERROR if internal else logging.WARNING, "job failed", extra={ **fields, "code": outcome.error.code, "error_type": outcome.error_type, "frames": outcome.frames, }, ) def _empty(folder: Path) -> None: for child in folder.iterdir(): if child.is_dir(): shutil.rmtree(child) else: child.unlink() def _stop(process: BaseProcess, grace_seconds: float) -> None: process.join(grace_seconds) if process.is_alive(): _kill_tree(process) process.join() process.close() def _kill_tree(process: BaseProcess) -> None: """Engines run tesseract and pdftoppm, so kill the worker's children with it.""" pid = process.pid if pid is None: return if sys.platform == "win32": subprocess.run( # noqa: S603 A fixed system binary and an integer pid. [str(_TASKKILL), "/T", "/F", "/PID", str(pid)], capture_output=True, check=False ) else: with suppress(ProcessLookupError): os.killpg(pid, signal.SIGKILL) process.kill() def _work( execute: Callable[[ToolRun[BaseModel], Reporter], ToolResult], request: ToolRun[BaseModel], channel: _Channel, ) -> None: configure_logging() _isolate(request.scratch_dir) lock = threading.Lock() def send(message: _ProgressMessage | _Outcome) -> None: payload = _Envelope(message=message).model_dump_json().encode() with lock: try: channel.send_bytes(payload) except OSError: # The runner closed the pipe because it is stopping this worker. Leave quietly, # so the dying worker prints no traceback. os._exit(0) def report(step: str, done: int, total: int) -> None: total = max(total, 1) progress = Progress( step=step.strip() or "Working", done=min(max(done, 0), total), total=total ) send(_ProgressMessage(progress=progress)) outcome: _Outcome try: result = execute(request, report) _check_downloads(result, request.output_dir) outcome = _ResultMessage(result=result) except PasswordError as error: outcome = _PasswordMessage(files=error.files) except MappingError as error: outcome = _MappingMessage(ask=error.ask) except ToolError as error: outcome = _ErrorMessage(error=JobError.from_error(error)) except Exception as error: # noqa: BLE001 The parent logs it from this message. outcome = _ErrorMessage( error=JobError.of(ErrorCode.INTERNAL_ERROR), error_type=type(error).__qualname__, frames=frames(error), ) send(outcome) channel.close() def _isolate(scratch_dir: Path) -> None: """Engines write temp files and logs under these folders. Point them into the job folder, so deleting the job deletes them too.""" for name in ("TMP", "TEMP", "TMPDIR", "LOCALAPPDATA"): os.environ[name] = str(scratch_dir) tempfile.tempdir = str(scratch_dir) if sys.platform != "win32": os.setsid() def _check_downloads(result: ToolResult, output_dir: Path) -> None: if not isinstance(result, ToolResult): raise TypeError(f"run returned {type(result).__name__}, not ToolResult") for name in (result.workbook, *(download.name for download in result.extra_downloads)): if not (output_dir / name).is_file(): raise FileNotFoundError("a download named in the result is not in output_dir")