Open-source AI podcast clipper. Generate vertical clips with face tracking and burned-in captions. CLI, MCP server, web app.
Python ai-toolsauto-captionscaptionscliffmpegmcpmcp-serveropusclip-alternativepodcast-clipspodcastsshortform-videovertical-videowhisper
backend: add hardened subprocess wrapper (proc.run)
Nika Siradze3696577a28b0
diff --git a/backend/utils/proc.py b/backend/utils/proc.pynew file mode 100644index 0000000..d118dd9--- /dev/null+++ b/backend/utils/proc.py@@ -0,0 +1,79 @@+"""Hardened subprocess helpers.++Wraps subprocess.run() with mandatory timeouts, structured logging, and a+typed error surface so hot paths (ffmpeg/ffprobe/whisper/etc.) can't hang+the server or swallow failures silently.+"""++from __future__ import annotations++import logging+import subprocess+import time+from typing import Sequence++log = logging.getLogger("podcli.proc")+++class ProcError(RuntimeError):+ """Raised when a wrapped subprocess fails or times out."""++ def __init__(self, cmd: Sequence[str], returncode: int, stderr: str, duration: float):+ self.cmd = list(cmd)+ self.returncode = returncode+ self.stderr = stderr+ self.duration = duration+ tool = cmd[0] if cmd else "?"+ super().__init__(+ f"{tool} failed (rc={returncode}, {duration:.2f}s): {stderr.strip()[:400]}"+ )+++def run(+ cmd: Sequence[str],+ *,+ timeout: float,+ check: bool = True,+ input_text: str | None = None,+ cwd: str | None = None,+) -> subprocess.CompletedProcess[str]:+ """Run a command with a mandatory timeout and structured logging.++ - Captures stdout/stderr as text.+ - Logs start, duration, and failure with the tool name + return code.+ - Raises ProcError on non-zero exit (when check=True) or timeout.+ """+ if not cmd:+ raise ValueError("proc.run: cmd must be non-empty")+ tool = cmd[0]+ t0 = time.monotonic()+ log.debug("proc.start tool=%s argc=%d timeout=%.0fs", tool, len(cmd), timeout)+ try:+ result = subprocess.run(+ list(cmd),+ capture_output=True,+ text=True,+ timeout=timeout,+ input=input_text,+ cwd=cwd,+ )+ except subprocess.TimeoutExpired as exc:+ duration = time.monotonic() - t0+ stderr = (exc.stderr or b"").decode("utf-8", "replace") if isinstance(exc.stderr, bytes) else (exc.stderr or "")+ log.error("proc.timeout tool=%s duration=%.2fs", tool, duration)+ raise ProcError(cmd, -1, f"timeout after {timeout:.0f}s: {stderr}", duration) from exc++ duration = time.monotonic() - t0+ if result.returncode != 0:+ log.warning(+ "proc.fail tool=%s rc=%d duration=%.2fs stderr=%s",+ tool,+ result.returncode,+ duration,+ (result.stderr or "")[-400:].strip(),+ )+ if check:+ raise ProcError(cmd, result.returncode, result.stderr or "", duration)+ else:+ log.debug("proc.ok tool=%s duration=%.2fs", tool, duration)+ return resultdiff --git a/tests/test_proc.py b/tests/test_proc.pynew file mode 100644index 0000000..a556691--- /dev/null+++ b/tests/test_proc.py@@ -0,0 +1,40 @@+import os+import sys+import unittest++ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))+if ROOT not in sys.path:+ sys.path.insert(0, ROOT)++from backend.utils.proc import ProcError, run+++class ProcTests(unittest.TestCase):+ def test_run_captures_stdout(self):+ result = run(["echo", "hello"], timeout=5)+ self.assertEqual(result.returncode, 0)+ self.assertIn("hello", result.stdout)++ def test_run_raises_on_nonzero_exit(self):+ with self.assertRaises(ProcError) as ctx:+ run(["sh", "-c", "echo bad 1>&2; exit 7"], timeout=5)+ self.assertEqual(ctx.exception.returncode, 7)+ self.assertIn("bad", ctx.exception.stderr)++ def test_run_check_false_returns_result(self):+ result = run(["sh", "-c", "exit 3"], timeout=5, check=False)+ self.assertEqual(result.returncode, 3)++ def test_run_timeout_raises_proc_error(self):+ with self.assertRaises(ProcError) as ctx:+ run(["sh", "-c", "sleep 2"], timeout=0.2)+ self.assertEqual(ctx.exception.returncode, -1)+ self.assertIn("timeout", str(ctx.exception).lower())++ def test_empty_cmd_rejected(self):+ with self.assertRaises(ValueError):+ run([], timeout=1)+++if __name__ == "__main__":+ unittest.main()