feat(logging): expand debug-logging coverage, add primitives, redaction & tests

Instrument the full download pipeline in the structured JSONL debug logger and make adding logging to new features a one-liner.

Coverage:
- DRM license request/response, content keys (incl. remote-CDM seam) and decrypt timing across Widevine/PlayReady/ClearKey
- DASH/HLS/ISM manifest fetch + parse milestones (HLS.to_tracks also covers the m3u8_parser path used by iTunes/ATV-style services)
- Per-backend vault get/add via the Vaults manager, track selection, subtitle conversion, repackage, normalize_vui, and full mkvmerge mux (command, duration, output size, warnings)
- All external tooling (ffmpeg, ffprobe, mkvmerge, mkvpropedit, dovi_tool, SubtitleEdit, ccextractor) via a unified `tool_run` op, centralised in run_step/ffprobe + log_tool_run

DX:
- Add log_event() / timed_operation() primitives (no-op when disabled); retrofit ~91 guard/timing blocks onto them
- Fix message= collision in log_drm_operation/log_vault_query/log_service_call that raised TypeError on the live decrypt path

Redaction (redact_all = redact_text -> redact_url -> redact_path):
- Collapse content/CDN/api URLs to `redacted[.ext]`
- Strip local path prefixes (install root -> <unshackle>, venv -> <venv>, home -> ~)
- Apply to every logged string so shared logs leak no URLs, paths or usernames
- Drop per-request service_call logging (manifest parse is the request seam)
This commit is contained in:
imSp4rky
2026-06-09 22:12:05 -06:00
parent 7064d261c2
commit 394ed67e28
24 changed files with 1763 additions and 793 deletions
+9
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import json
import logging
import subprocess
import time
from collections import OrderedDict, defaultdict
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
@@ -13,6 +14,7 @@ from requests import Session
from unshackle.core.binaries import FFProbe
from unshackle.core.session import RnetSession
from unshackle.core.utils.subprocess import log_tool_run
if TYPE_CHECKING:
from unshackle.core.tracks import Track
@@ -421,6 +423,7 @@ def probe_bytes_duration(data: Optional[bytes], log: logging.Logger) -> Optional
return None
ffprobe_bin = str(FFProbe) if FFProbe else "ffprobe"
try:
probe_start = time.monotonic()
result = subprocess.run(
[ffprobe_bin, "-v", "error", "-show_entries", "format=duration:stream=duration", "-of", "json", "pipe:"],
input=data,
@@ -428,6 +431,12 @@ def probe_bytes_duration(data: Optional[bytes], log: logging.Logger) -> Optional
stderr=subprocess.PIPE,
timeout=60,
)
log_tool_run(
"ffprobe duration probe",
"ffprobe",
result.returncode,
duration_ms=round((time.monotonic() - probe_start) * 1000, 1),
)
info = json.loads(result.stdout or b"{}")
candidates = [info.get("format", {}).get("duration")]
candidates += [s.get("duration") for s in info.get("streams", [])]
+9 -1
View File
@@ -13,11 +13,12 @@ re-implement subprocess plumbing per call site. Each wrapper:
from __future__ import annotations
import subprocess
import time
from pathlib import Path
from typing import Optional
from unshackle.core import binaries
from unshackle.core.utils.subprocess import run_step
from unshackle.core.utils.subprocess import log_tool_run, run_step
def _require_dovi_tool() -> str:
@@ -82,7 +83,14 @@ def editor(
def info_summary(rpu: Path) -> str:
"""Return the textual summary (`dovi_tool info -i ... -s`) for an RPU file."""
tool = _require_dovi_tool()
info_start = time.monotonic()
p = subprocess.run([tool, "info", "-i", str(rpu), "-s"], capture_output=True, text=True)
log_tool_run(
"dovi_tool info",
"dovi_tool",
p.returncode,
duration_ms=round((time.monotonic() - info_start) * 1000, 1),
)
if p.returncode != 0:
raise RuntimeError(f"dovi_tool info failed: {(p.stderr or '')[-400:]}")
return p.stdout
+86
View File
@@ -3,6 +3,8 @@
from __future__ import annotations
import re
import sys
from pathlib import Path
from typing import Iterable, Optional
from urllib.parse import urlsplit, urlunsplit
@@ -37,3 +39,87 @@ def safe_display_url(url: str) -> str:
if parts.port:
netloc += f":{parts.port}"
return urlunsplit((parts.scheme, netloc, parts.path, "", ""))
def _path_bases() -> list[tuple[str, str]]:
"""Local base directories to strip from logged paths, longest-first.
Anchors everything left of the unshackle install/root (and the venv / home dir) so an
absolute path like ``/home/me/Projects/unshackle-live/temp`` logs as ``<unshackle>/temp``,
hiding the username and machine layout on both Linux and Windows.
"""
candidates: list[tuple[str, str]] = []
try:
# redact.py lives at <root>/unshackle/core/utils/redact.py -> parents[3] == project/install root
candidates.append((str(Path(__file__).resolve().parents[3]), "<unshackle>"))
except Exception:
pass
for raw in (getattr(sys, "prefix", ""), getattr(sys, "base_prefix", "")):
if raw:
candidates.append((str(Path(raw)), "<venv>"))
try:
candidates.append((str(Path.home()), "~"))
except Exception:
pass
bases: list[tuple[str, str]] = []
seen: set[str] = set()
for base, token in candidates:
# cover both separator conventions (a path may be logged with / even on Windows)
for variant in (base, base.replace("\\", "/"), base.replace("/", "\\")):
if variant and variant not in seen:
seen.add(variant)
bases.append((variant, token))
bases.sort(key=lambda item: len(item[0]), reverse=True)
return bases
_PATH_BASES = _path_bases()
def redact_path(text: Optional[str]) -> Optional[str]:
"""Replace local base-directory prefixes (install root, venv, home) in ``text`` with tokens.
Idempotent and cheap; only touches strings that actually contain a known base dir, so URLs
and relative paths pass through unchanged.
"""
if not isinstance(text, str) or not text:
return text
for base, token in _PATH_BASES:
if base in text:
text = text.replace(base, token)
return text
# any http(s) URL embedded in free text (content/manifest/segment/api locations)
URL_RE = re.compile(r"https?://[^\s\"'<>\\]+", re.IGNORECASE)
# a plausible file extension to preserve (e.g. .mpd, .m3u8, .mp4, .m4s, .vtt)
_EXT_RE = re.compile(r"^\.[A-Za-z0-9]{1,5}$")
def _collapse_url(match: "re.Match[str]") -> str:
url = match.group(0)
try:
suffix = Path(urlsplit(url).path).suffix
except Exception:
suffix = ""
if not _EXT_RE.match(suffix):
suffix = ""
return f"redacted{suffix}"
def redact_url(text: Optional[str]) -> Optional[str]:
"""Collapse every http(s) URL in ``text`` to ``redacted[.ext]``.
Hides content/CDN/manifest/segment/api locations (host + path + query) from shareable debug
logs while keeping the file extension so the manifest/segment type stays visible
(e.g. ``redacted.mpd``). Non-URL strings pass through unchanged.
"""
if not isinstance(text, str) or not text:
return text
return URL_RE.sub(_collapse_url, text)
def redact_all(text: Optional[str]) -> Optional[str]:
"""Full redaction for logged strings: secrets, then URLs, then local path prefixes."""
return redact_path(redact_url(redact_text(text)))
+77 -2
View File
@@ -1,10 +1,43 @@
import json
import subprocess
import time
from pathlib import Path
from typing import Optional, Sequence, Union
from unshackle.core import binaries
from unshackle.core.console import console
from unshackle.core.utilities import get_debug_logger
def log_tool_run(
label: str,
tool: Optional[str],
returncode: Optional[int],
*,
duration_ms: Optional[float] = None,
**context: object,
) -> None:
"""Emit a structured ``tool_run`` debug-log entry for an external tool invocation.
Central helper so every binary call (ffmpeg, mkvpropedit, dovi_tool, etc.) logs the
same shape. No-op when debug logging is disabled.
"""
dl = get_debug_logger()
if not dl:
return
failed = bool(returncode)
dl.log(
level="ERROR" if failed else "DEBUG",
operation="tool_run",
message=f"{label} {'failed' if failed else 'ok'}",
context={
"label": label,
"tool": tool,
"returncode": returncode,
"duration_ms": duration_ms,
**context,
},
)
def ffprobe(uri: Union[bytes, Path]) -> dict:
@@ -19,11 +52,33 @@ def ffprobe(uri: Union[bytes, Path]) -> dict:
)
elif isinstance(uri, bytes):
args.append("pipe:")
dl = get_debug_logger()
start = time.monotonic()
try:
ff = subprocess.run(args, input=uri if isinstance(uri, bytes) else None, check=True, capture_output=True)
except subprocess.CalledProcessError:
if dl:
dl.log(
level="DEBUG",
operation="tool_run",
message="ffprobe failed",
context={"tool": "ffprobe", "duration_ms": round((time.monotonic() - start) * 1000, 1)},
)
return {}
return json.loads(ff.stdout.decode("utf8"))
result = json.loads(ff.stdout.decode("utf8"))
if dl:
dl.log(
level="DEBUG",
operation="tool_run",
message=f"ffprobe found {len(result.get('streams', []))} stream(s)",
context={
"tool": "ffprobe",
"streams": len(result.get("streams", [])),
"duration_ms": round((time.monotonic() - start) * 1000, 1),
},
)
return result
def run_step(
@@ -42,6 +97,7 @@ def run_step(
output.unlink(missing_ok=True)
str_args = [str(a) for a in args]
start = time.monotonic()
if status:
with console.status(status, spinner="dots"):
p = subprocess.run(str_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
@@ -50,7 +106,26 @@ def run_step(
stderr = p.stderr or b""
bad_output = output is not None and (not output.exists() or output.stat().st_size == 0)
if p.returncode or bad_output:
failed = bool(p.returncode or bad_output)
if dl := get_debug_logger():
dl.log(
level="ERROR" if failed else "DEBUG",
operation="tool_run",
message=f"{label} {'failed' if failed else 'ok'}",
context={
"label": label,
"tool": Path(str_args[0]).name if str_args else None,
"arg_count": len(str_args),
"returncode": p.returncode,
"duration_ms": round((time.monotonic() - start) * 1000, 1),
"output": str(output) if output else None,
"output_size": output.stat().st_size if output and output.exists() else 0,
"bad_output": bad_output,
},
)
if failed:
if output is not None:
output.unlink(missing_ok=True)
raise RuntimeError(f"{label} failed: {stderr.decode(errors='replace')[-400:]}")
+11
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import logging
import subprocess
import tempfile
import time
from pathlib import Path
from typing import Optional
from xml.sax.saxutils import escape
@@ -14,6 +15,7 @@ from unshackle.core.providers import (ExternalIds, MetadataResult, enrich_ids, f
from unshackle.core.titles.episode import Episode
from unshackle.core.titles.movie import Movie
from unshackle.core.titles.title import Title
from unshackle.core.utils.subprocess import log_tool_run
log = logging.getLogger("TAGS")
@@ -33,12 +35,21 @@ def apply_tags(path: Path, tags: dict[str, str]) -> None:
f.write("\n".join(xml_lines))
tmp_path = Path(f.name)
try:
tag_start = time.monotonic()
result = subprocess.run(
[str(binaries.Mkvpropedit), str(path), "--tags", f"global:{tmp_path}"],
check=False,
capture_output=True,
text=True,
)
log_tool_run(
"mkvpropedit tags",
"mkvpropedit",
result.returncode,
duration_ms=round((time.monotonic() - tag_start) * 1000, 1),
file=Path(path).name,
tag_count=len(tags),
)
if result.returncode != 0:
log.warning("mkvpropedit failed (exit %d): %s", result.returncode, result.stderr.strip())
else: