feat(log): record each HTTP attempt in the debug log with debug_requests

This commit is contained in:
imSp4rky
2026-11-27 18:05:00 -07:00
parent 0e2cedcdbe
commit 438419ab1b
24 changed files with 1132 additions and 107 deletions
+10 -1
View File
@@ -17,6 +17,7 @@ from aiohttp import web
import unshackle.core.config as config_module
from unshackle.core import binaries
from unshackle.core import session as http_session
from unshackle.core.api import cors_middleware, no_5xx_middleware, setup_routes
from unshackle.core.api.compression import compression_middleware
from unshackle.core.api.events import publish_refresh_events, publish_service_event
@@ -42,7 +43,7 @@ from unshackle.core.api.stats import (
)
from unshackle.core.config import Config, config
from unshackle.core.console import console
from unshackle.core.constants import context_settings
from unshackle.core.constants import HTTP_LOGGERS, context_settings
from unshackle.core.downloaders import format_speed, parse_speed_limit, set_speed_limit
from unshackle.core.remote_protocol import HEALTH_ROUTE
@@ -401,6 +402,8 @@ def serve(
from pyplayready.remote import serve as pyplayready_serve
from pywidevine import serve as pywidevine_serve
http_session.record_bodies = False
if quiet:
logging.basicConfig(
force=True,
@@ -429,6 +432,12 @@ def serve(
logging.getLogger("api").setLevel(logging.WARNING)
logging.getLogger("api.remote").setLevel(logging.WARNING)
ring.setFormatter(logging.Formatter("%(message)s"))
ring.addFilter(
lambda record: (
record.levelno > logging.DEBUG
or not (record.name == "RnetSession" or record.name.split(".")[0] in HTTP_LOGGERS)
)
)
if not debug:
ring.addFilter(lambda record: record.name != "aiohttp.access")
logging.getLogger().addHandler(ring)
+2 -2
View File
@@ -15,7 +15,7 @@ from unshackle.core import __code_hash__, __version__
from unshackle.core.commands import Commands
from unshackle.core.config import config
from unshackle.core.console import ComfyRichHandler, console
from unshackle.core.constants import context_settings
from unshackle.core.constants import HTTP_LOGGERS, context_settings
from unshackle.core.update_checker import UpdateChecker
from unshackle.core.utilities import close_debug_logger, init_debug_logger
@@ -77,7 +77,7 @@ def main(version: bool, debug: bool) -> None:
init_debug_logger(enabled=True)
if debug and not config.debug_requests:
for noisy in ("urllib3", "urllib3.connectionpool", "requests", "rnet", "httpx", "httpcore", "hpack", "h2"):
for noisy in HTTP_LOGGERS:
logging.getLogger(noisy).setLevel(logging.WARNING)
urllib3.disable_warnings(InsecureRequestWarning)
+2
View File
@@ -16,6 +16,7 @@ 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.console import set_notice_handler, set_prompt_handler
from unshackle.core.downloaders import format_speed, set_speed_limit
@@ -116,6 +117,7 @@ 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
+1
View File
@@ -237,6 +237,7 @@ class Config:
self.debug: bool = kwargs.get("debug", False)
self.debug_keys: bool = kwargs.get("debug_keys", False)
self.debug_requests: bool = kwargs.get("debug_requests", False)
self.debug_requests_body_limit: int = max(int(kwargs.get("debug_requests_body_limit") or 0), 0)
def validate_output_templates(self) -> None:
"""Validate output template configurations and warn about potential issues."""
+1
View File
@@ -8,6 +8,7 @@ DOWNLOAD_CANCELLED = Event()
DOWNLOAD_LICENCE_ONLY = Event()
DEFAULT_SAMPLE = (120, 180)
HTTP_LOGGERS = ("urllib3", "urllib3.connectionpool", "requests", "rnet", "httpx", "httpcore", "hpack", "h2")
DOWNLOAD_ALL_DRM = Event()
+7 -1
View File
@@ -415,12 +415,16 @@ def is_requests_session(session: Any) -> bool:
def no_retry_session(session: Session) -> Session:
"""A shallow copy of ``session`` whose adapters never retry, sharing its state and pools.
The view writes no debug_requests debug-log entry: segment and probe requests stay out of the record.
download() owns segment retries, so a mounted urllib3 ``Retry`` nests inside a single
attempt: one 429 carrying ``Retry-After: 60`` costs five one-minute sleeps before
download() even sees the failure. requests takes no per-call retry override, and track
threads share the caller's session, so remounting it is not an option.
"""
view = copy(session)
from unshackle.core.session import unrecorded_view
view = unrecorded_view(session)
view.adapters = OrderedDict()
for prefix, adapter in session.adapters.items():
twin = copy(adapter)
@@ -475,6 +479,7 @@ def probe_ranged(url: str, session: Any, **kwargs: Any) -> tuple[int, bool]:
rest.setdefault("read_timeout", rnet_read_timeout())
# let download() own segment retries, with no nested session-level retry loop
rest.setdefault("max_retries", 0)
rest.setdefault("record_request", False)
else:
rest.setdefault("timeout", (CONNECT_TIMEOUT, READ_TIMEOUT))
session = no_retry_session(session)
@@ -891,6 +896,7 @@ def download(
request_kwargs.setdefault("read_timeout", rnet_read_timeout())
# own segment retries here, suppressing RnetSession's nested retry loop
request_kwargs.setdefault("max_retries", 0)
request_kwargs.setdefault("record_request", False)
else:
request_kwargs.setdefault("timeout", (CONNECT_TIMEOUT, READ_TIMEOUT))
req_headers = dict(request_kwargs.get("headers", {}) or {})
+2 -1
View File
@@ -24,7 +24,7 @@ from unshackle.core.manifests import DASH, HLS, ISM, MissingLanguageError, snaps
from unshackle.core.proxies.resolve import REGION_QUERY
from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.remote_service import resolve_proxy_arg, segment_uri_filter
from unshackle.core.session import failure_response, utf8_text
from unshackle.core.session import failure_response, record_requests, utf8_text
from unshackle.core.title_source import KeyArrival, TitleSource
from unshackle.core.titles import Episode, Movies, Series, Title_T, Titles_T, remap_titles
from unshackle.core.tracks import Audio, Chapter, Chapters, Subtitle, Tracks, Video
@@ -269,6 +269,7 @@ class ImportService(TitleSource):
else next((r["headers"] for r in first.tracks if r.get("url") and r.get("headers")), {})
)
self.session = self.build_session(ctx, self.region, headers)
record_requests(self.session)
@staticmethod
def legacy_entry(entry: mediaexport.Entry) -> dict[str, Any]:
+8 -6
View File
@@ -41,7 +41,7 @@ from unshackle.core.manifests.segment_pipeline import (
license_drm,
)
from unshackle.core.manifests.trim import trim_overlaps
from unshackle.core.session import RnetSession
from unshackle.core.session import RnetSession, unrecorded
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video, resume
from unshackle.core.tracks.track import DRM_PREFERENCE_TYPES, Track, parse_sidx
from unshackle.core.utilities import is_close_match, log_event, try_ensure_utf8
@@ -1085,10 +1085,12 @@ class DASH:
init_url = segment_template.get("initialization")
if init_url and probe_kid:
res = session.get(
res = unrecorded(
session,
"get",
DASH.replace_fields(
init_url, Bandwidth=representation.get("bandwidth"), RepresentationID=representation.get("id")
)
),
)
res.raise_for_status()
init_data = res.content
@@ -1192,7 +1194,7 @@ class DASH:
else:
init_range_header = None
res = session.get(url=source_url, headers=init_range_header)
res = unrecorded(session, "get", source_url, headers=init_range_header)
res.raise_for_status()
init_data = res.content
track_kid = track.get_key_id(init_data)
@@ -1222,7 +1224,7 @@ class DASH:
init_range_header = {"Range": f"bytes={init_range}"} if init_range else None
slice_range = request_range(init_range_header) if init_range_header else None
if (same_file and init_range) or (not same_file and probe_kid):
res = session.get(url=init_url, headers=init_range_header, stream=True)
res = unrecorded(session, "get", init_url, headers=init_range_header, stream=True)
res.raise_for_status()
content_range = parse_content_range(res.headers.get("Content-Range"))
if init_range_header and not (
@@ -1243,7 +1245,7 @@ class DASH:
subsegments: list[tuple[int, int, int]] = []
index_range = segment_base.get("indexRange")
if window and index_range and not isinstance(track, Subtitle):
res = session.get(url=rep_base_url, headers={"Range": f"bytes={index_range}"})
res = unrecorded(session, "get", rep_base_url, headers={"Range": f"bytes={index_range}"})
res.raise_for_status()
segment_timescale, subsegments = parse_sidx(res.content, int(index_range.split("-")[0]))
+4 -7
View File
@@ -46,7 +46,7 @@ from unshackle.core.manifests.segment_pipeline import (
licensing,
remove_segment_dir,
)
from unshackle.core.session import RnetResponse, RnetSession, utf8_text
from unshackle.core.session import RnetResponse, RnetSession, unrecorded, utf8_text
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video, resume
from unshackle.core.tracks.track import DRM_PREFERENCE_TYPES, Track, assert_fragments_decrypted
from unshackle.core.utilities import get_extension, is_close_match, log_event, try_ensure_utf8
@@ -409,7 +409,7 @@ class HLS:
seg_uri = urljoin(variant_url, variant.segments[0].uri)
# Download only the first 8KB: SPS is always near the start of the first TS packet
res = session.get(seg_uri, headers={"Range": "bytes=0-8191"})
res = unrecorded(session, "get", seg_uri, headers={"Range": "bytes=0-8191"})
data = res.content
return HLS.parse_ts_video_info(data)
@@ -595,10 +595,7 @@ class HLS:
else:
init_range_header = {}
res = session.get(
url=urljoin(init_section.base_uri, init_section.uri),
headers=init_range_header,
)
res = unrecorded(session, "get", urljoin(init_section.base_uri, init_section.uri), headers=init_range_header)
if not isinstance(res, (requests.Response, RnetResponse)):
raise TypeError(f"Expected response to be requests.Response or rnet.Response, not {type(res)}")
@@ -1418,7 +1415,7 @@ class HLS:
headers = {"Range": f"bytes={byte_range}"}
else:
headers = {}
map_res = session.get(url=map_uri, headers=headers)
map_res = unrecorded(session, "get", map_uri, headers=headers)
if map_res.ok:
return track.get_key_id(map_res.content)
logging.getLogger("HLS").warning(
+3 -1
View File
@@ -85,7 +85,7 @@ from unshackle.core.remote_protocol import (
coded,
)
from unshackle.core.search_result import SearchResult
from unshackle.core.session import MAX_BACKOFF
from unshackle.core.session import MAX_BACKOFF, record_requests
from unshackle.core.title_source import KeyArrival, TitleSource
from unshackle.core.titles import Title_T, Titles_T, remap_titles
from unshackle.core.titles.episode import Episode, Series
@@ -247,6 +247,7 @@ class RemoteClient:
from unshackle.core import __version__
self._session = requests.Session()
record_requests(self._session)
self._session.headers["User-Agent"] = f"unshackle/{__version__}"
if self.api_key:
self._session.headers[self.auth_headers[self._auth_header_index]] = self.api_key
@@ -896,6 +897,7 @@ class RemoteService(TitleSource):
),
)
self.session.mount("http://", self.session.adapters["https://"])
record_requests(self.session)
svc_config = services_config.get(service_tag, {})
self._server_cdm: bool | None = services_config.get("_server_cdm")
+2
View File
@@ -32,6 +32,7 @@ from unshackle.core.session import (
READ_TIMEOUT,
RETRY_METHODS,
STATUS_FORCELIST,
record_requests,
)
from unshackle.core.title_cacher import TitleCacher
from unshackle.core.title_source import TitleSource
@@ -164,6 +165,7 @@ class Service(TitleSource):
self.log = logging.getLogger(self.__class__.__name__)
self.session = self.get_session()
record_requests(self.session)
self.cache = Cacher(self.__class__.__name__)
self.title_cache: TitleCacher = TitleCacher(self.__class__.__name__)
self.cache_dir = config.directories.cache / self.__class__.__name__
+278 -25
View File
@@ -2,7 +2,9 @@
from __future__ import annotations
import contextlib
import http
import json
import logging
import math
import random
@@ -15,14 +17,16 @@ from datetime import UTC, datetime
from email.utils import parsedate_to_datetime
from http.cookiejar import Cookie, CookieJar
from typing import Any
from urllib.parse import urlencode, urlparse, urlunparse
from urllib.parse import urlencode, urlparse, urlsplit, urlunparse
import rnet
from requests import HTTPError, Request, Response, Session
from requests import HTTPError, PreparedRequest, Request, Response, Session
from requests.adapters import BaseAdapter
from requests.cookies import create_cookie
from requests.structures import CaseInsensitiveDict
from unshackle.core.config import config
from unshackle.core.utilities import get_debug_logger, log_event
from unshackle.core.utils import run_proxy
# rnet's only distinguishing role is TLS fingerprinting; retry, backoff,
@@ -201,14 +205,13 @@ class RnetResponse:
)
def iter_content(self, chunk_size: int | None = None) -> Iterator[bytes]:
"""Re-chunk rnet's variable-size data into fixed-size pieces."""
self._streamed = True
"""Re-chunk rnet's variable-size data, or the body already read, into fixed-size pieces."""
if chunk_size is None or chunk_size <= 0:
yield from self._resp.stream()
yield from self.stream()
return
buf = bytearray()
for chunk in self._resp.stream():
for chunk in self.stream():
buf.extend(chunk)
while len(buf) >= chunk_size:
yield bytes(buf[:chunk_size])
@@ -217,8 +220,11 @@ class RnetResponse:
yield bytes(buf)
def stream(self) -> Iterator[bytes]:
"""Direct pass-through of rnet's native ``stream()`` iterator."""
"""Direct pass-through of rnet's native ``stream()`` iterator, or the body already read."""
self._streamed = True
if self._content is not None:
yield self._content
return
yield from self._resp.stream()
def close(self) -> None:
@@ -578,6 +584,216 @@ def failure_reason(exc: BaseException) -> str:
return f"{type(inner).__name__} ({texts[-1]})" if texts else type(inner).__name__
TEXT_TYPES = ("json", "xml", "text/")
MANIFEST_TYPES = ("dash+xml", "mpegurl", "vnd.ms-sstr")
MANIFEST_SUFFIXES = (".mpd", ".m3u8", ".m3u", "/manifest")
FORM_TYPE = "x-www-form-urlencoded"
record_bodies = True
"""False in a server process (``serve`` and its download job worker): its http_request entries carry no body."""
def text_fields(data: bytes, content_type: str) -> dict[str, Any]:
"""A text body as entry fields: JSON parsed, other text as a string, cut to the body limit."""
limit = config.debug_requests_body_limit
if limit and len(data) > limit:
return {"body": data[:limit].decode("utf-8", errors="replace"), "body_size": len(data), "body_cut": True}
if "json" in content_type:
with contextlib.suppress(ValueError):
return {"body": json.loads(data)}
return {"body": data.decode("utf-8", errors="replace")}
def request_body(content_type: str, data: Any) -> dict[str, Any]:
"""The body fields of a sent request: a JSON, form, XML or text body as sent. A binary body has none."""
content_type = content_type.lower()
if isinstance(data, str):
data = data.encode("utf-8")
if not data or not isinstance(data, bytes):
return {}
if FORM_TYPE not in content_type and not any(t in content_type for t in TEXT_TYPES):
return {}
return text_fields(data, content_type)
def rnet_sent(kwargs: dict[str, Any], headers: Any) -> tuple[str, Any] | None:
"""The content type and body of an rnet request, for its http_request entry."""
if kwargs.get("json") is not None:
return "application/json", json.dumps(kwargs["json"])
if kwargs.get("form") is not None:
return FORM_TYPE, urlencode(kwargs["form"])
if kwargs.get("body") is None:
return None
merged = {k.lower(): v for k, v in dict(headers).items()}
merged.update({k.lower(): v for k, v in (kwargs.get("headers") or {}).items()})
return merged.get("content-type", ""), kwargs["body"]
def response_body(response: Any, path: str) -> dict[str, Any]:
"""The body fields of a response for its http_request entry.
Only a text content-type has its body read. A manifest has none: a manifest content-type, or a manifest
path suffix on a response that is not JSON.
"""
content_type = (response.headers.get("content-type") or "").lower()
manifest = any(t in content_type for t in MANIFEST_TYPES) or (
"json" not in content_type and path.lower().endswith(MANIFEST_SUFFIXES)
)
if manifest or "event-stream" in content_type or not any(t in content_type for t in TEXT_TYPES):
return {}
data: bytes = response.content
if not data:
return {}
return text_fields(data, content_type)
def record_request(
method: str,
url: str,
attempt: int | None,
*,
duration: float | None = None,
response: Any = None,
status: int | None = None,
error: BaseException | None = None,
body: bool = False,
sent: tuple[str, Any] | None = None,
) -> None:
"""Write one ``http_request`` debug-log entry for an HTTP attempt, with its values as received.
With ``body`` set, a text response body goes in the entry too, and ``sent`` (content type, body) adds a
text request body, except in a server process. A body read
that fails writes ``body_error``, and the caller's own read raises the error. The duration stops at the
response headers.
"""
debug_logger = get_debug_logger()
if not debug_logger or not debug_logger.enabled:
return
parts = urlsplit(url)
size: Any = None
received: dict[str, Any] = {}
request_fields: dict[str, Any] = {}
if sent is not None and record_bodies:
try:
request_fields = request_body(*sent)
except Exception as e:
request_fields = {"body_error": failure_reason(e)}
if response is not None:
status = response.status_code
size = response.headers.get("content-length")
if body and record_bodies:
try:
received = response_body(response, parts.path)
except Exception as e:
received = {"body_error": failure_reason(e)}
if not str(size).isdigit() and "body" in received:
size = len(response.content)
log_event(
"http_request",
raw=True,
request={
"method": method,
"host": parts.netloc.rpartition("@")[2],
"path": parts.path or "/",
"query": parts.query or None,
"attempt": attempt,
**request_fields,
},
response={"status": status, "size": int(size) if str(size).isdigit() else None, **received},
duration_ms=None if duration is None else round(duration * 1000, 1),
failure=failure_reason(error) if error is not None else None,
)
class RecordedAdapter:
"""Wrap a transport adapter so that each send writes an ``http_request`` debug-log entry.
urllib3 retries inside one send, so the attempts before the last come from its retry history, with no
duration or size. A failed send records only its last failure. Attributes read through to the adapter,
but a write stays on the wrapper: change ``session.adapters`` instead.
"""
def __init__(self, adapter: BaseAdapter) -> None:
self.adapter = adapter
def __getattr__(self, name: str) -> Any:
if name == "adapter":
raise AttributeError(name)
return getattr(self.adapter, name)
def send(self, request: PreparedRequest, **kwargs: Any) -> Response:
method, url = request.method or "", request.url or ""
sent = (request.headers.get("Content-Type") or "", request.body)
started = time.monotonic()
try:
response = self.adapter.send(request, **kwargs)
except Exception as e:
record_request(method, url, None, duration=time.monotonic() - started, error=e, sent=sent)
raise
history = getattr(getattr(response.raw, "retries", None), "history", None) or ()
for attempt, past in enumerate(history, 1):
record_request(method, url, attempt, status=past.status, error=past.error)
record_request(
method,
url,
len(history) + 1,
duration=time.monotonic() - started,
response=response,
body=not kwargs.get("stream"),
sent=sent,
)
return response
class RecordedSession(Session):
"""A requests.Session that writes an ``http_request`` debug-log entry for each request and redirect hop.
``record_request = False`` turns it off.
"""
record_request = True
def get_adapter(self, url: str) -> BaseAdapter:
adapter = super().get_adapter(url)
return RecordedAdapter(adapter) if self.record_request and config.debug_requests else adapter # type: ignore[return-value]
def record_requests(session: Any) -> None:
"""With debug_requests on, make a requests.Session write an ``http_request`` debug-log entry per request.
The session gets a subclass made at run time, so it no longer pickles. Only the HTTP sessions that core builds
call this: a service's own extra requests.Session writes no entry.
"""
if config.debug_requests and isinstance(session, Session) and not isinstance(session, RecordedSession):
cls: type = type(session)
if cls not in RECORDED_CLASSES:
RECORDED_CLASSES[cls] = type(cls.__name__, (RecordedSession, cls), {})
session.__class__ = RECORDED_CLASSES[cls]
RECORDED_CLASSES: dict[type, type] = {}
def unrecorded_view(session: Session) -> Session:
"""A shallow copy of a requests ``session`` that writes no debug_requests entry.
copy() would keep only ``Session.__attrs__`` and drop the attributes that a subclass sets.
"""
view = object.__new__(type(session))
view.__dict__.update(session.__dict__)
view.record_request = False # type: ignore[attr-defined]
return view
def unrecorded(session: Any, method: str, url: str, **kwargs: Any) -> Any:
"""Call ``session.<method>(url)`` with no debug_requests debug-log entry, for a range read or probe of media bytes."""
if isinstance(session, RnetSession):
kwargs["record_request"] = False
elif isinstance(session, RecordedSession):
session = unrecorded_view(session)
return getattr(session, method)(url, **kwargs)
class RnetSession:
"""TLS-fingerprinted HTTP session powered by rnet (Rust/BoringSSL).
@@ -844,13 +1060,58 @@ class RnetSession:
pass
return response
def send_attempt(
self,
client: Any,
rnet_method: Any,
method: str,
url: str,
attempt: int,
record: bool,
body: bool,
sent: tuple[str, Any] | None,
kwargs: dict[str, Any],
) -> RnetResponse:
"""Send one HTTP attempt. With debug_requests on, log it, and when ``record`` is set write its debug-log entry.
``body`` puts the response body in the entry, and ``sent`` the request body.
"""
started = time.monotonic()
try:
response = self.absorb_cookies(RnetResponse(client.request(rnet_method, url, **kwargs)))
except Exception as e:
if record:
record_request(method, url, attempt, duration=time.monotonic() - started, error=e, sent=sent)
raise
if config.debug_requests:
parsed_url = urlsplit(url)
port_str = f":{parsed_url.port}" if parsed_url.port else ""
if not port_str:
port_str = ":443" if parsed_url.scheme == "https" else ":80"
host_url = f"{parsed_url.scheme}://{parsed_url.hostname}{port_str}"
path_and_query = parsed_url.path + (f"?{parsed_url.query}" if parsed_url.query else "")
if not path_and_query:
path_and_query = "/"
content_length = response.headers.get("content-length") or response.content_length
log_msg = (
f'{host_url} "{method} {path_and_query} {response.version}" {response.status_code} {content_length}'
)
self.log.debug(log_msg)
if record:
record_request(
method, url, attempt, duration=time.monotonic() - started, response=response, body=body, sent=sent
)
return response
def request(self, method: str, url: str, **kwargs: Any) -> RnetResponse:
"""Send a request, retrying on the status forcelist and on the caught exception types.
This method retries only the methods in allowed_methods. Any other method gets one try.
A max_retries kwarg overrides the HTTP session retry budget for this call alone, where 0
means one try with no retries. Once the budget is spent, this method raises
MaxRetriesError with the last failure as its cause.
MaxRetriesError with the last failure as its cause. A record_request=False kwarg keeps
this call out of the debug_requests debug-log entries.
"""
client = self.ensure_client()
method_upper = method.upper() if isinstance(method, str) else str(method).upper()
@@ -876,7 +1137,7 @@ class RnetSession:
kwargs.setdefault("verify", False)
# Remove kwargs rnet doesn't understand
kwargs.pop("stream", None) # rnet responses are always lazy
stream = kwargs.pop("stream", None) # rnet responses are always lazy
data = kwargs.pop("data", None)
if data is not None:
@@ -895,29 +1156,21 @@ class RnetSession:
if kwargs.get("headers") is not None:
kwargs["headers"] = dict(kwargs["headers"])
record = kwargs.pop("record_request", True) and config.debug_requests
body = record and not stream
sent = rnet_sent(kwargs, self.headers) if record else None
if method_upper not in self.allowed_methods:
return self.absorb_cookies(RnetResponse(client.request(rnet_method, url, **kwargs)))
return self.send_attempt(client, rnet_method, method_upper, url, 1, record, body, sent, kwargs)
last_exception: Exception | None = None
response: RnetResponse | None = None
for attempt in range(max_retries + 1):
try:
response = self.absorb_cookies(RnetResponse(client.request(rnet_method, url, **kwargs)))
if config.debug_requests:
parsed_url = urlparse(url)
port_str = f":{parsed_url.port}" if parsed_url.port else ""
if not port_str:
port_str = ":443" if parsed_url.scheme == "https" else ":80"
host_url = f"{parsed_url.scheme}://{parsed_url.hostname}{port_str}"
path_and_query = parsed_url.path + (f"?{parsed_url.query}" if parsed_url.query else "")
if not path_and_query:
path_and_query = "/"
content_length = response.headers.get("content-length") or response.content_length
log_msg = f'{host_url} "{method_upper} {path_and_query} {response.version}" {response.status_code} {content_length}'
self.log.debug(log_msg)
response = self.send_attempt(
client, rnet_method, method_upper, url, attempt + 1, record, body, sent, kwargs
)
if response.status_code not in self.status_forcelist:
return response
+6 -6
View File
@@ -39,7 +39,7 @@ from unshackle.core.drm.verify import (
walk,
)
from unshackle.core.events import events
from unshackle.core.session import MAX_BACKOFF, AnySession, RnetSession, utf8_text
from unshackle.core.session import MAX_BACKOFF, AnySession, RnetSession, unrecorded, utf8_text
from unshackle.core.temp import restore_segments, stash_segments
from unshackle.core.tracks import resume
from unshackle.core.utilities import language_name, log_event, try_ensure_utf8
@@ -545,7 +545,7 @@ class Track:
def read_to(end: int) -> None:
nonlocal head
if end > len(head):
res = session.get(url, headers={"Range": f"bytes={len(head)}-{end - 1}"})
res = unrecorded(session, "get", url, headers={"Range": f"bytes={len(head)}-{end - 1}"})
if res.ok:
head += res.content
@@ -1197,23 +1197,23 @@ class Track:
if start > end:
raise ValueError(f"The start range cannot be greater than the end range: {start}>{end}")
else:
size_test = session.head(url)
size_test = unrecorded(session, "head", url)
if "Content-Length" in size_test.headers:
content_length_header = int(size_test.headers["Content-Length"])
if content_length_header > 0:
content_length = min(content_length_header, maximum_size)
range_test = session.head(url, headers={"Range": "bytes=0-1"})
range_test = unrecorded(session, "head", url, headers={"Range": "bytes=0-1"})
if range_test.status_code == 206:
byte_range = f"0-{content_length - 1}"
init_data: bytes | None
if byte_range:
res = session.get(url=url, headers={"Range": f"bytes={byte_range}"})
res = unrecorded(session, "get", url, headers={"Range": f"bytes={byte_range}"})
res.raise_for_status()
init_data = res.content
else:
init_data = None
s = session.get(url, stream=True)
s = unrecorded(session, "get", url, stream=True)
if not s.ok:
s.close()
raise ValueError(f"Track URI returned HTTP {s.status_code}")
+43 -41
View File
@@ -35,7 +35,7 @@ from unidecode import unidecode
from unshackle.core.config import config
from unshackle.core.constants import LANGUAGE_EXACT_DISTANCE, LANGUAGE_MAX_DISTANCE
from unshackle.core.utils.redact import redact_all
from unshackle.core.utils.redact import redact_all, redact_path
"""
Utility functions for the unshackle media archival tool.
@@ -1124,6 +1124,7 @@ class DebugLogger:
response: dict[str, Any] | None = None,
duration_ms: float | None = None,
success: bool | None = None,
raw: bool = False,
**kwargs: Any,
) -> None:
"""
@@ -1140,70 +1141,71 @@ class DebugLogger:
response: Response details (status, headers, body)
duration_ms: Operation duration in milliseconds
success: Whether the operation succeeded
raw: True to write the values as received, with only the local folder prefixes redacted
**kwargs: Additional fields to include in the log entry
"""
if not self.enabled or not self.file_handle:
return
entry: dict[str, Any] = {
"timestamp": datetime.now(UTC).isoformat(),
"session_id": self.session_id,
"level": level,
}
if operation:
entry["operation"] = operation
if message:
entry["message"] = redact_all(message)
if service:
entry["service"] = service
if context:
entry["context"] = self.sanitize_data(context)
if request:
entry["request"] = self.sanitize_data(request)
if response:
entry["response"] = self.sanitize_data(response)
if duration_ms is not None:
entry["duration_ms"] = duration_ms
if success is not None:
entry["success"] = success
if error:
entry["error"] = {
"type": type(error).__name__,
"message": redact_all(str(error)),
"traceback": [
redact_all(line) for line in traceback.format_exception(type(error), error, error.__traceback__)
],
try:
entry: dict[str, Any] = {
"timestamp": datetime.now(UTC).isoformat(),
"session_id": self.session_id,
"level": level,
}
for key, value in kwargs.items():
if key not in entry:
entry[key] = self.sanitize_data(value)
if operation:
entry["operation"] = operation
if message:
entry["message"] = self.sanitize_data(message, raw)
if service:
entry["service"] = service
if context:
entry["context"] = self.sanitize_data(context, raw)
if request:
entry["request"] = self.sanitize_data(request, raw)
if response:
entry["response"] = self.sanitize_data(response, raw)
if duration_ms is not None:
entry["duration_ms"] = duration_ms
if success is not None:
entry["success"] = success
if error:
entry["error"] = {
"type": type(error).__name__,
"message": redact_all(str(error)),
"traceback": [
redact_all(line) for line in traceback.format_exception(type(error), error, error.__traceback__)
],
}
for key, value in kwargs.items():
if key not in entry:
entry[key] = self.sanitize_data(value, raw)
try:
self.file_handle.write(json.dumps(entry, default=str) + "\n")
self.file_handle.flush()
except Exception as e:
print(f"Failed to write debug log: {e}", file=sys.stderr)
def sanitize_data(self, data: Any) -> Any:
def sanitize_data(self, data: Any, raw: bool = False) -> Any:
"""
Sanitise data for JSON serialization.
Handles complex objects and removes sensitive information.
Handles complex objects and removes sensitive information. ``raw`` redacts only the local folder prefixes.
"""
if data is None:
return None
if isinstance(data, str):
# mask secrets, collapse content/CDN URLs, and strip local path prefixes
return redact_all(data)
return redact_path(data) if raw else redact_all(data)
if isinstance(data, (int, float, bool)):
return data
if isinstance(data, (list, tuple)):
return [self.sanitize_data(item) for item in data]
return [self.sanitize_data(item, raw) for item in data]
if isinstance(data, dict):
sanitized = {}
@@ -1221,12 +1223,12 @@ class DebugLogger:
and not any(safe in key_lower for safe in ["_count", "_id", "_type", "kid", "keys_", "key_found"])
)
should_redact = is_always_sensitive or (is_key_field and not self.log_keys)
should_redact = not raw and (is_always_sensitive or (is_key_field and not self.log_keys))
if should_redact:
sanitized[key] = "[REDACTED]"
else:
sanitized[key] = self.sanitize_data(value)
sanitized[key] = self.sanitize_data(value, raw)
return sanitized
if isinstance(data, bytes):
+4 -4
View File
@@ -15,7 +15,7 @@ from requests import Session
from unshackle.core.binaries import FFProbe
from unshackle.core.constants import TrackT
from unshackle.core.session import RnetSession, utf8_text
from unshackle.core.session import RnetSession, unrecorded, utf8_text
from unshackle.core.utils.subprocess import log_tool_run
if TYPE_CHECKING:
@@ -216,7 +216,7 @@ def pick_samples(segments: list[Segment], samples: int) -> list[Segment]:
def probe_size(segment: Segment, session: Session | RnetSession) -> int | None:
"""Return a segment's byte size with a HEAD request, falling back to a ranged GET. Validates status."""
try:
res = session.head(segment.url, allow_redirects=True, timeout=PROBE_TIMEOUT)
res = unrecorded(session, "head", segment.url, allow_redirects=True, timeout=PROBE_TIMEOUT)
if getattr(res, "status_code", 0) in (200, 206):
content_length = res.headers.get("Content-Length")
if content_length:
@@ -228,7 +228,7 @@ def probe_size(segment: Segment, session: Session | RnetSession) -> int | None:
# Require a 206 so a server that ignores Range (returning the whole 200 body)
# is not mistaken for a valid size or downloaded wholesale.
try:
res = session.get(segment.url, headers={"Range": "bytes=0-0"}, timeout=PROBE_TIMEOUT)
res = unrecorded(session, "get", segment.url, headers={"Range": "bytes=0-0"}, timeout=PROBE_TIMEOUT)
if getattr(res, "status_code", 0) == 206:
content_range = res.headers.get("Content-Range")
if content_range and "/" in content_range:
@@ -414,7 +414,7 @@ def ffprobe_duration(url: str, session: Session | RnetSession, *, log: logging.L
def ranged_get(url: str, session: Session | RnetSession, byte_range: str) -> bytes | None:
"""Fetch a byte range, only accepting a real 206 partial response (never a full 200 body)."""
try:
res = session.get(url, headers={"Range": byte_range}, timeout=PROBE_TIMEOUT)
res = unrecorded(session, "get", url, headers={"Range": byte_range}, timeout=PROBE_TIMEOUT)
if getattr(res, "status_code", 0) != 206:
return None
content = getattr(res, "content", None)
+3
View File
@@ -132,11 +132,14 @@ def run_proxy_for(frame: FrameType | None) -> str | None:
def fallback_session() -> requests.Session:
"""A new requests session for a core helper that got no session, on the proxy of the calling service."""
from unshackle.core.session import record_requests
session = requests.Session()
proxy = run_proxy_for(sys._getframe(1))
if proxy:
session.proxies.update({"all": proxy})
pin(session)
record_requests(session)
return session