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
+1 -1
View File
@@ -585,7 +585,7 @@ A few configuration toggles help when a title will not decrypt:
|------------|---------|--------| |------------|---------|--------|
| `debug` | `false` | Global debug output. | | `debug` | `false` | Global debug output. |
| `debug_keys` | `false` | Log decryption keys. | | `debug_keys` | `false` | Log decryption keys. |
| `debug_requests` | `false` | Log HTTP requests. | | `debug_requests` | `false` | Log HTTP requests to the console with `-d`, and each request with its response body to the [JSON debug log](troubleshooting.md#debug-requests). The log then holds tokens and content keys as received. |
```yaml title="unshackle.yaml" ```yaml title="unshackle.yaml"
debug_keys: true debug_keys: true
+54 -9
View File
@@ -54,7 +54,7 @@ There are two independent ways to enable debug logging, and they do slightly dif
## The structured JSON debug log ## The structured JSON debug log
Beyond the console output, unshackle writes a structured log in [JSON Lines](https://jsonlines.org/) format: one complete JSON object per line. You can filter, examine, and analyse this file with standard tooling (`jq`, `grep`, a text editor). It is safe to attach to a bug report, because unshackle redacts it. Beyond the console output, unshackle writes a structured log in [JSON Lines](https://jsonlines.org/) format: one complete JSON object per line. You can filter, examine, and analyse this file with standard tooling (`jq`, `grep`, a text editor). It is safe to attach to a bug report, because unshackle redacts it, unless `debug_requests` is on (see [Debugging HTTP traffic](#debug-requests)).
### Where it is written ### Where it is written
@@ -134,11 +134,15 @@ With `debug_keys: true`, the debug log stops masking content key fields. You can
!!! warning "Keys are sensitive, turn this back off" !!! warning "Keys are sensitive, turn this back off"
`debug_keys` writes real content keys into the log file in cleartext. Only enable it while you diagnose a content key problem. Never share a log written with it on, and set it back to `false` when you are done. Note that `debug_keys` only affects the **JSON debug log file**. It does not change what the console prints. `debug_keys` writes real content keys into the log file in cleartext. Only enable it while you diagnose a content key problem. Never share a log written with it on, and set it back to `false` when you are done. Note that `debug_keys` only affects the **JSON debug log file**. It does not change what the console prints.
Fields that are *always* redacted regardless of `debug_keys` (anything whose name contains `password`, `token`, `secret`, `auth`, or `cookie`) stay masked, so credentials never leak even in a keys-on log. Fields that are *always* redacted regardless of `debug_keys` (anything whose name contains `password`, `token`, `secret`, `auth`, or `cookie`) stay masked, so credentials never leak even in a keys-on log. The `http_request` entries of [`debug_requests`](#debug-requests) are the exception.
--- ---
## Debugging HTTP traffic with `debug_requests` ## Debugging HTTP traffic with `debug_requests` { #debug-requests }
`debug_requests` does two things: it keeps the HTTP library logs in the console, and it writes a record of each HTTP request to the JSON debug log.
### HTTP library logs in the console
When you pass `-d`, unshackle raises its own modules to `DEBUG` but deliberately **silences** the noisy low-level HTTP libraries (`urllib3`, `requests`, `rnet`, `httpx`, `httpcore`, `hpack`, `h2`) back down to `WARNING`. Without this, a single download would bury the useful output under thousands of connection-pool and HTTP/2 frame messages. When you pass `-d`, unshackle raises its own modules to `DEBUG` but deliberately **silences** the noisy low-level HTTP libraries (`urllib3`, `requests`, `rnet`, `httpx`, `httpcore`, `hpack`, `h2`) back down to `WARNING`. Without this, a single download would bury the useful output under thousands of connection-pool and HTTP/2 frame messages.
@@ -154,8 +158,47 @@ unshackle cfg debug_requests true
With `debug_requests: true`, unshackle leaves those libraries at `DEBUG` level when you operate it with `-d`, so their request/response chatter appears in the console. With `debug_requests: true`, unshackle leaves those libraries at `DEBUG` level when you operate it with `-d`, so their request/response chatter appears in the console.
!!! note "`debug_requests` needs `-d` to have any effect" !!! note "The console logs need `-d`"
The `debug_requests` toggle only decides whether unshackle silences the HTTP libraries when the `-d` flag is active. If you do not operate unshackle with `-d` (verbose console logging), it changes nothing. Combine them: `unshackle -d dl ...` with `debug_requests: true` in config. Without `-d` (verbose console logging), unshackle shows no HTTP library logs. Combine them: `unshackle -d dl ...` with `debug_requests: true` in config.
### Request records in the JSON debug log
`debug_requests` is the one switch that writes request records to the [JSON debug log](#the-structured-json-debug-log). With `debug_requests: true` and the JSON debug log on (`-d` or `debug: true`), unshackle writes one `http_request` entry for each HTTP attempt. With `debug_requests: false`, the default, a `-d` run writes no `http_request` entry. A request that unshackle retries gives one entry for each attempt. A redirect gives one entry for each hop.
| Field | Content |
|-------|---------|
| `request.method` | The HTTP method. |
| `request.host` | The host name and port, with no scheme and no user name or password. |
| `request.path` | The URL path, as sent. |
| `request.query` | The query string, as sent. |
| `request.attempt` | The attempt number, from 1. |
| `request.body` | The body of a JSON, form, XML or `text/*` request, as sent. A JSON body is an object. A binary body is not recorded. |
| `response.status` | The HTTP status, or `null` when no response came back. |
| `response.size` | The `Content-Length` of the response. When the server sent none, the length of the recorded body, else `null`. |
| `response.body` | The text response body, as received. A JSON body is a JSON object, so `jq` can query it. Other text is a string. |
| `response.body_size` | The full size of the decoded body in bytes, when unshackle cut it to `debug_requests_body_limit`. `response.size` is the size on the wire, which can be compressed. |
| `response.body_error` | The failure, when unshackle could not read the body. |
| `response.body_cut` | `true` when unshackle cut the body. A cut JSON body is a string. |
| `duration_ms` | The time from the start of the attempt to the response headers. |
| `failure` | The failure, without the URL, for an attempt that raised. |
unshackle records the body of a JSON, XML or `text/*` response. It records no body for a manifest (MPD, M3U8 or ISM, by its content type, or by the suffix of the request path when the response is not JSON), a binary content type, an event stream, a request sent with `stream=True`, or a server process. A request body is recorded by the same rule, by the request `Content-Type`; a form body counts as text. The entries contain no headers. Core writes no entry for the media requests that it makes. These are the segment and range-probe requests of a track download, and the init segment, index and probe reads before it. A range read that service code makes still writes an entry. Playlist and manifest fetches write an entry.
```console
jq 'select(.operation == "http_request") | [.request.method, .request.host, .request.path, .response.status]' \
unshackle_debug_EXAMPLE_20260703-142530.jsonl
jq 'select(.operation == "http_request" and .request.path == "/v1/titles") | .response.body' \
unshackle_debug_EXAMPLE_20260703-142530.jsonl
```
The record covers the HTTP sessions that unshackle builds: the session from the service's `get_session()`, the import and `--remote` sessions, and the sessions of core helpers. A separate `requests.Session` that service code makes itself writes no entry.
On a `serve` server, the entries for the requests of a service stay on the server, with no body. A download job whose `dl` run has the JSON debug log on writes them to that log. A remote session writes none, because `serve` opens no JSON debug log for it. unshackle never sends them to a remote client: not in the remote session log, the remote session channel, an API reply or an error. A remote client with its own `debug_requests: true` records its own requests to the server, with the response bodies, in its own JSON debug log.
On an HTTP session of the `requests` library, `urllib3` retries inside one send. The attempts before the last then have no `duration_ms` and no `response.size`. A request that fails after all its retries gives one entry for the last failure, with `request.attempt` set to `null`.
!!! danger "A request record holds secrets"
unshackle writes the `http_request` entries as received. It masks only the local folder prefixes (`redact_paths`). With `debug_requests` on, the JSONL file holds tokens, passwords, cookies, content keys and account data, in the path, the query and the body. `debug_keys` does not apply to these entries. Keep the file on your computer. Never attach it to a report.
--- ---
@@ -167,13 +210,15 @@ unshackle redacts logged strings so that debug output is safe to share. It appli
- **URLs**: unshackle collapses every `http(s)` URL to `redacted`. It keeps only the file extension, so a manifest still shows as `redacted.mpd` and a segment as `redacted.m4s`. This hides the CDN, manifest, segment, and licence-server locations, but keeps the *type* of resource. - **URLs**: unshackle collapses every `http(s)` URL to `redacted`. It keeps only the file extension, so a manifest still shows as `redacted.mpd` and a segment as `redacted.m4s`. This hides the CDN, manifest, segment, and licence-server locations, but keeps the *type* of resource.
- **Local paths**: unshackle replaces install-root, virtualenv, and home-directory prefixes with tokens, so your username and machine layout do not appear in logs. - **Local paths**: unshackle replaces install-root, virtualenv, and home-directory prefixes with tokens, so your username and machine layout do not appear in logs.
The [`http_request` entries](#debug-requests) of `debug_requests` get only the local path pass. Their secrets, URLs and bodies stay as received.
The `redact_paths` config key controls path redaction, and it is **on by default**: The `redact_paths` config key controls path redaction, and it is **on by default**:
```yaml ```yaml
redact_paths: true # default - mask local base directories in logged paths redact_paths: true # default - mask local base directories in logged paths
``` ```
Set `redact_paths: false` if you debug a path problem locally and want to see full, unmasked paths in the console and logs. unshackle always applies secret and URL redaction in the JSON debug log, and this toggle does not change that. Set `redact_paths: false` if you debug a path problem locally and want to see full, unmasked paths in the console and logs. unshackle always applies secret and URL redaction in the JSON debug log, except in the `http_request` entries, and this toggle does not change that.
--- ---
@@ -256,7 +301,7 @@ Each command reports how many files it removed and how much space it freed, then
!!! example "A network request fails at the connection or TLS layer" !!! example "A network request fails at the connection or TLS layer"
**Symptom:** timeouts, connection resets, or handshake errors, and unshackle's own logs do not give the full cause. **Symptom:** timeouts, connection resets, or handshake errors, and unshackle's own logs do not give the full cause.
**Inspect:** set `debug_requests: true` and operate unshackle with `-d` to show the underlying `urllib3` / `rnet` / `httpx` logs. In the JSON debug log, filter for `service_call` operations to see which request failed. If you use a proxy, also read [Proxies & VPN](proxies-and-vpn.md). **Inspect:** set `debug_requests: true` and operate unshackle with `-d` to show the underlying `urllib3` / `rnet` / `httpx` logs. In the JSON debug log, filter for `http_request` operations to see which request failed, with its status, attempt number and failure. If you use a proxy, also read [Proxies & VPN](proxies-and-vpn.md).
!!! example "A segment download fails after every retry" !!! example "A segment download fails after every retry"
**Symptom:** the download stops with a line like `MaxRetriesError: GET <host> failed: RequestError (stream closed because of a broken pipe), gave up after 5 failed attempts over 30s`. **Symptom:** the download stops with a line like `MaxRetriesError: GET <host> failed: RequestError (stream closed because of a broken pipe), gave up after 5 failed attempts over 30s`.
@@ -302,8 +347,8 @@ The debug log is tuned for **developers troubleshooting pipeline flow** (maximum
jq 'select(.level == "INFO")' unshackle_debug_EXAMPLE_20260703-142530.jsonl jq 'select(.level == "INFO")' unshackle_debug_EXAMPLE_20260703-142530.jsonl
``` ```
!!! warning "No raw dumps" !!! warning "No request bodies and no raw dumps"
Never log a full `Tracks` object, an MPD/manifest body, or a response payload. Log only **counts, ids, sizes, and `safe_display_url(url)`**. This keeps the log low-noise and prevents leaking title or manifest data into the file *before* redaction even runs. Redaction is a backstop, not a licence to dump raw objects. A `log_event` entry never holds a request body or a raw dump: no full `Tracks` object, no MPD/manifest body and no response payload. Only `debug_requests` records request and response bodies, in its `http_request` entries. Log only **counts, ids, sizes, and `safe_display_url(url)`**. This keeps the log low-noise and prevents leaking title or manifest data into the file *before* redaction even runs. Redaction is a backstop, not a licence to dump raw objects.
!!! note "Operation names: `<area>_<event>`, no registry" !!! note "Operation names: `<area>_<event>`, no registry"
Operation names are plain lowercase strings that follow an `<area>_<event>` convention: `manifest_dash_parse`, `drm_decrypt`, `vault_get_key`, `tool_run`. We write them inline at each call site on purpose. There is **no central registry or enum**. Do not look for one, and do not make one. The absence is a deliberate design choice, not an omission. Operation names are plain lowercase strings that follow an `<area>_<event>` convention: `manifest_dash_parse`, `drm_decrypt`, `vault_get_key`, `tool_run`. We write them inline at each call site on purpose. There is **no central registry or enum**. Do not look for one, and do not make one. The absence is a deliberate design choice, not an omission.
+1 -1
View File
@@ -40,5 +40,5 @@ Where the file lives, how unshackle discovers it, and how to edit it:
| [External API keys](misc.md#external-api-keys) | `omdb_api_key`, `tmdb_api_key`, `tvdb_api_key`, `tvdb_pin`, `tvdb_order`, `simkl_client_id`, `metadata_providers`, `anilist_title_language`, `disable_metadata`, `decrypt_labs_api_key`, `ipinfo_api_key` | | [External API keys](misc.md#external-api-keys) | `omdb_api_key`, `tmdb_api_key`, `tvdb_api_key`, `tvdb_pin`, `tvdb_order`, `simkl_client_id`, `metadata_providers`, `anilist_title_language`, `disable_metadata`, `decrypt_labs_api_key`, `ipinfo_api_key` |
| [Caching & updates](misc.md#caching-updates) | `title_cache_enabled`, `title_cache_time`, `title_cache_max_retention`, `update_checks`, `update_check_interval` | | [Caching & updates](misc.md#caching-updates) | `title_cache_enabled`, `title_cache_time`, `title_cache_max_retention`, `update_checks`, `update_check_interval` |
| [Appearance](misc.md#appearance) | `theme`, `wide_output` | | [Appearance](misc.md#appearance) | `theme`, `wide_output` |
| [Logging, privacy & debug](misc.md#logging-privacy-debug) | `redact_paths`, `debug`, `debug_keys`, `debug_requests`, `set_terminal_bg` | | [Logging, privacy & debug](misc.md#logging-privacy-debug) | `redact_paths`, `debug`, `debug_keys`, `debug_requests`, `debug_requests_body_limit`, `set_terminal_bg` |
| [Deprecated & removed](misc.md#deprecated-removed-keys) | `curl_impersonate`, `downloader`, `scene_naming` | | [Deprecated & removed](misc.md#deprecated-removed-keys) | `curl_impersonate`, `downloader`, `scene_naming` |
+8 -1
View File
@@ -157,7 +157,8 @@ calls.
| `redact_paths` | bool | `true` | Mask install-root / venv / home prefixes in logged paths (`<unshackle>`, `<venv>`, `~`). Set `false` to show full paths. | | `redact_paths` | bool | `true` | Mask install-root / venv / home prefixes in logged paths (`<unshackle>`, `<venv>`, `~`). Set `false` to show full paths. |
| `debug` | bool | `false` | Global debug mode. | | `debug` | bool | `false` | Global debug mode. |
| `debug_keys` | bool | `false` | Log decryption keys. | | `debug_keys` | bool | `false` | Log decryption keys. |
| `debug_requests` | bool | `false` | Log HTTP requests. | | `debug_requests` | bool | `false` | The one switch that writes an `http_request` entry for each HTTP attempt to the JSON debug log, with the text response body as received; `-d` and `debug` alone write none. With `-d` it also keeps the HTTP library logs in the console. See [Debugging HTTP traffic](../../guide/troubleshooting.md#debug-requests). |
| `debug_requests_body_limit` | int | `0` | The maximum number of bytes of a response body in an `http_request` entry. `0` or unset records the full body. unshackle cuts a longer body and records its full size. |
| `set_terminal_bg` | bool | `false` | Append the theme's background colour to output styling. | | `set_terminal_bg` | bool | `false` | Append the theme's background colour to output styling. |
!!! note "Effect of `set_terminal_bg`" !!! note "Effect of `set_terminal_bg`"
@@ -174,6 +175,12 @@ calls.
`debug_keys` affects **only** content-encryption keys (the `content_key`/`key` fields). `debug_keys` affects **only** content-encryption keys (the `content_key`/`key` fields).
Passwords, tokens, cookies, and session tokens are **always** redacted regardless of this Passwords, tokens, cookies, and session tokens are **always** redacted regardless of this
setting, and KIDs, content key counts, and other metadata are always logged either way. setting, and KIDs, content key counts, and other metadata are always logged either way.
The `http_request` entries of `debug_requests` are the exception.
!!! danger "`debug_requests` writes secrets"
With `debug_requests` on, the JSONL file holds tokens, passwords, cookies, content keys and account data
as the servers sent them. unshackle masks only the local folder prefixes in these entries. Keep the file on
your computer. Never attach it to a report.
--- ---
+7
View File
@@ -12,6 +12,7 @@ from typing import Any
import pytest import pytest
from unshackle.core import binaries from unshackle.core import binaries
from unshackle.core import session as http_session
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.proxies.proxy import CATALOGUES from unshackle.core.proxies.proxy import CATALOGUES
from unshackle.core.update_checker import UpdateChecker from unshackle.core.update_checker import UpdateChecker
@@ -45,6 +46,12 @@ def no_update_check(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(UpdateChecker, "check_for_updates_sync", lambda *args, **kwargs: None) monkeypatch.setattr(UpdateChecker, "check_for_updates_sync", lambda *args, **kwargs: None)
@pytest.fixture(autouse=True)
def client_process(monkeypatch: pytest.MonkeyPatch) -> None:
"""Start as a client process, so a test that ran serve or a job worker cannot turn response bodies off."""
monkeypatch.setattr(http_session, "record_bodies", True)
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def fresh_proxy_catalogues() -> None: def fresh_proxy_catalogues() -> None:
"""Fetch each proxy provider catalogue again, so one test's stub never answers another test.""" """Fetch each proxy provider catalogue again, so one test's stub never answers another test."""
+24
View File
@@ -84,6 +84,30 @@ def test_log_event_emits_with_level_message_and_context(debug_log: Path):
assert e["context"] == {"count": 3} assert e["context"] == {"count": 3}
def test_a_raw_entry_keeps_its_values_and_redacts_only_local_paths(debug_log: Path):
home = str(Path.home())
values = {"url": "https://h/x?access_token=T1", "password": "P1", "key": "K1", "file": f"{home}/a.txt"}
log_event("raw_event", raw=True, message=f"token=T1 {home}/m", context=values)
log_event("masked_event", message="token=T1", context=values)
entries = read_entries(debug_log)
raw, masked = find(entries, "raw_event"), find(entries, "masked_event")
assert raw["message"] == "token=T1 ~/m"
assert raw["context"] == {**values, "file": "~/a.txt"}
assert masked["message"] == "token=***"
assert masked["context"] == {"url": "redacted", "password": "[REDACTED]", "key": "[REDACTED]", "file": "~/a.txt"}
def test_a_value_too_deep_for_the_log_never_raises(debug_log: Path):
deep: list = []
for _ in range(5000):
deep = [deep]
log_event("deep_event", raw=True, context={"body": deep})
log_event("after_event")
assert find(read_entries(debug_log), "after_event")
def test_log_event_noop_when_disabled(): def test_log_event_noop_when_disabled():
close_debug_logger() close_debug_logger()
assert get_debug_logger() is None assert get_debug_logger() is None
+581
View File
@@ -0,0 +1,581 @@
"""The debug_requests http_request entry in the JSONL debug log, for both HTTP session types."""
from __future__ import annotations
import copy
import importlib
import json
import logging
import threading
from collections.abc import Iterator
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import m3u8
import pytest
import requests as rq
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from unshackle.core import service as service_module
from unshackle.core import session as http_session
from unshackle.core.config import Config, config
from unshackle.core.manifests import DASH, HLS
from unshackle.core.service import Service
from unshackle.core.session import MaxRetriesError, RecordedSession, RnetSession, record_requests, unrecorded
from unshackle.core.tracks.track import Track
from unshackle.core.utilities import close_debug_logger, init_debug_logger
from unshackle.core.utils import bitrate
from unshackle.core.utils.xml import load_xml
dl = importlib.import_module("unshackle.core.downloaders.requests")
pytestmark = pytest.mark.unit
BODY = b"x" * 64
class Server(ThreadingHTTPServer):
allow_reuse_address = True
daemon_threads = True
def __init__(self) -> None:
self.hits: list[str] = []
self.docs: dict[str, str] = {}
self.types: dict[str, str] = {}
self.lock = threading.Lock()
super().__init__(("127.0.0.1", 0), Handler)
self.host = f"127.0.0.1:{self.server_address[1]}"
self.url = f"http://{self.host}"
def handle_error(self, request: Any, client_address: Any) -> None:
pass
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
server: Server
def log_message(self, *_: Any) -> None:
pass
def reply(self) -> None:
if length := int(self.headers.get("Content-Length") or 0):
self.rfile.read(length)
path = self.path.partition("?")[0]
with self.server.lock:
first = path not in self.server.hits
self.server.hits.append(path)
if path == "/old":
self.send_response(302)
self.send_header("Location", "/new")
self.send_header("Content-Length", "0")
self.end_headers()
return
if path == "/busy" and first:
self.send_response(503)
self.send_header("Content-Length", "0")
self.end_headers()
return
ranged = bool(self.headers.get("Range")) and not path.startswith("/plain")
body = self.server.docs[path].encode() if path in self.server.docs else BODY[:1] if ranged else BODY
if path.startswith("/chunked"):
self.send_response(200)
self.send_header("Content-Type", self.server.types.get(path, "text/plain"))
self.send_header("Transfer-Encoding", "chunked")
self.end_headers()
self.wfile.write(f"{len(body):x}\r\n".encode() + body + b"\r\n0\r\n\r\n")
return
self.send_response(206 if ranged else 200)
if ranged:
self.send_header("Content-Range", f"bytes 0-0/{len(BODY)}")
if path in self.server.types:
self.send_header("Content-Type", self.server.types[path])
if not (path.startswith("/plain") and self.command == "HEAD"):
self.send_header("Content-Length", str(len(body)))
self.end_headers()
if self.command != "HEAD":
self.wfile.write(body)
do_GET = do_POST = do_PATCH = do_HEAD = reply
@pytest.fixture
def server() -> Iterator[Server]:
srv = Server()
thread = threading.Thread(target=srv.serve_forever, daemon=True)
thread.start()
yield srv
srv.shutdown()
srv.server_close()
@pytest.fixture
def debug_log(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]:
monkeypatch.setattr(config, "debug_requests", True)
path = tmp_path / "debug.jsonl"
init_debug_logger(log_path=path, enabled=True)
yield path
close_debug_logger()
def records(path: Path) -> list[dict]:
lines = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
return [e for e in lines if e.get("operation") == "http_request"]
def requests_session() -> rq.Session:
session = rq.Session()
adapter = HTTPAdapter(max_retries=Retry(total=2, backoff_factor=0, status_forcelist=[503]))
session.mount("http://", adapter)
record_requests(session)
return session
def rnet_session() -> RnetSession:
session = RnetSession(backoff_factor=0)
session.get_sleep_time = lambda *_: 0 # type: ignore[method-assign]
return session
def closed_port() -> str:
srv = Server()
srv.server_close()
return srv.url
SESSIONS = [pytest.param(requests_session, id="requests"), pytest.param(rnet_session, id="rnet")]
@pytest.mark.parametrize("make_session", SESSIONS)
def test_the_entry_keeps_host_path_and_query_as_received(server, debug_log, make_session):
make_session().get(f"{server.url}/api/{JWT}/items;hmac=a1b2?id=5&access_token=SECRET123")
(entry,) = records(debug_log)
assert entry["request"] == {
"method": "GET",
"host": server.host,
"path": f"/api/{JWT}/items;hmac=a1b2",
"query": "id=5&access_token=SECRET123",
"attempt": 1,
}
assert entry["response"] == {"status": 200, "size": len(BODY)}
assert entry["duration_ms"] >= 0
assert entry["failure"] is None
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_retried_request_writes_one_entry_per_attempt(server, debug_log, make_session):
make_session().get(f"{server.url}/busy")
entries = records(debug_log)
assert [(e["request"]["attempt"], e["response"]["status"]) for e in entries] == [(1, 503), (2, 200)]
@pytest.mark.parametrize(
("make_session", "kwargs", "error"),
[
pytest.param(requests_session, {}, rq.ConnectionError, id="requests"),
pytest.param(rnet_session, {"max_retries": 0}, MaxRetriesError, id="rnet"),
],
)
def test_a_failed_attempt_names_the_failure(debug_log, make_session, kwargs, error):
with pytest.raises(error):
make_session().get(f"{closed_port()}/gone", **kwargs)
(entry,) = records(debug_log)
assert entry["failure"]
assert entry["response"]["status"] is None
assert entry["request"]["path"] == "/gone"
def test_a_redirect_writes_one_entry_per_hop(server, debug_log):
requests_session().get(f"{server.url}/old")
assert [(e["request"]["path"], e["response"]["status"]) for e in records(debug_log)] == [
("/old", 302),
("/new", 200),
]
def test_an_rnet_method_outside_the_retry_methods_is_recorded(server, debug_log):
RnetSession(allowed_methods={"GET"}).patch(f"{server.url}/edit")
(entry,) = records(debug_log)
assert (entry["request"]["method"], entry["request"]["path"], entry["response"]["status"]) == (
"PATCH",
"/edit",
200,
)
@pytest.mark.parametrize("make_session", SESSIONS)
def test_segment_and_probe_requests_are_not_recorded(server, debug_log, tmp_path, make_session):
session = make_session()
list(dl.download(url=f"{server.url}/segment", save_path=tmp_path / "seg.mp4", session=session))
dl.probe_ranged(f"{server.url}/probe", session)
session.get(f"{server.url}/api")
assert server.hits.count("/segment") == 1 and server.hits.count("/probe") == 1
assert [e["request"]["path"] for e in records(debug_log)] == ["/api"]
@pytest.mark.parametrize("built_with_debug_requests", [True, False])
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_debug_run_without_debug_requests_records_nothing(
server, debug_log, monkeypatch, make_session, built_with_debug_requests
):
monkeypatch.setattr(config, "debug_requests", built_with_debug_requests)
session = make_session()
monkeypatch.setattr(config, "debug_requests", False)
session.get(f"{server.url}/api")
session.get(f"{server.url}/busy")
assert server.hits.count("/api") == 1
assert records(debug_log) == []
assert "session_start" in debug_log.read_text(encoding="utf-8")
def test_record_requests_leaves_the_session_alone_without_debug_requests(monkeypatch):
monkeypatch.setattr(config, "debug_requests", False)
session = rq.Session()
record_requests(session)
assert type(session) is rq.Session
def test_a_recorded_adapter_reads_through_and_copies(debug_log):
session = requests_session()
adapter = session.get_adapter("http://h")
assert adapter.max_retries.total == 2
assert copy.copy(adapter).max_retries.total == 2
def test_the_service_session_records_only_with_debug_requests(monkeypatch):
class Stop(Exception):
pass
stub = type("Stub", (Service,), dict.fromkeys(Service.__abstractmethods__, lambda *_: None))
ctx = SimpleNamespace(obj=SimpleNamespace(config={}))
monkeypatch.setattr(service_module, "Cacher", lambda *_: (_ for _ in ()).throw(Stop()))
for enabled in (True, False):
monkeypatch.setattr(config, "debug_requests", enabled)
instance = object.__new__(stub)
with pytest.raises(Stop):
Service.__init__(instance, ctx) # type: ignore[arg-type]
assert isinstance(instance.session, RecordedSession) is enabled
assert type(instance.session).__name__ == "TimeoutSession"
JWT = "eyJhbGciOi.eyJzdWIi.c2ln"
def test_the_rnet_console_line_keeps_the_query(server, debug_log, caplog):
with caplog.at_level("DEBUG"):
rnet_session().get(f"{server.url}/{JWT}/pts_0.mp4?sig=S2")
(line,) = [r.getMessage() for r in caplog.records if " 200 " in r.getMessage()]
assert f'"GET /{JWT}/pts_0.mp4?sig=S2 ' in line
def body_of(
server: Server, debug_log: Path, make_session: Any, path: str, kind: str | None, doc: str, **kw: Any
) -> dict:
server.docs[path] = doc
if kind:
server.types[path] = kind
make_session().get(f"{server.url}{path}", **kw)
(entry,) = records(debug_log)
return entry["response"]
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_json_body_is_stored_as_an_object_as_received(server, debug_log, make_session):
doc = json.dumps({"items": [{"lang": "xx-ZZ"}], "access_token": "T1", "key": "K1", "file": f"{Path.home()}/a"})
response = body_of(server, debug_log, make_session, "/api/json", "application/json; charset=utf-8", doc)
assert response["body"] == {"items": [{"lang": "xx-ZZ"}], "access_token": "T1", "key": "K1", "file": "~/a"}
assert str(Path.home()) not in debug_log.read_text(encoding="utf-8")
@pytest.mark.parametrize(
("path", "kind", "doc"),
[
pytest.param("/a.txt", "text/plain", "error inside a 200", id="text"),
pytest.param("/bad-json", "application/json", "{not json", id="bad-json"),
pytest.param("/m.xml", "application/xml", "<a/>", id="xml"),
],
)
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_text_body_is_stored_as_a_string(server, debug_log, make_session, path, kind, doc):
assert body_of(server, debug_log, make_session, path, kind, doc)["body"] == doc
@pytest.mark.parametrize(
("path", "kind", "kw"),
[
pytest.param("/seg.bin", "application/octet-stream", {}, id="binary"),
pytest.param("/seg.m3u8", "video/mp2t", {}, id="media-type"),
pytest.param("/no-type", None, {}, id="no-type"),
pytest.param("/api/stream", "application/json", {"stream": True}, id="stream"),
pytest.param("/events", "text/event-stream", {}, id="event-stream"),
pytest.param("/v/manifest.mpd", "application/dash+xml", {}, id="mpd"),
pytest.param("/v/manifest.mpd", "text/xml", {}, id="mpd-suffix"),
pytest.param("/master", "application/vnd.apple.mpegurl", {}, id="m3u8"),
pytest.param("/v.m3u8", "text/plain", {}, id="m3u8-suffix"),
pytest.param("/a.ism/Manifest", "application/vnd.ms-sstr+xml", {}, id="ism"),
pytest.param("/a.ism/Manifest", "text/xml", {}, id="ism-suffix"),
],
)
@pytest.mark.parametrize("make_session", SESSIONS)
def test_no_body_for_binary_or_streamed_responses(server, debug_log, make_session, path, kind, kw):
assert "body" not in body_of(server, debug_log, make_session, path, kind, '{"a": 1}', **kw)
@pytest.mark.parametrize(
("kw", "expected"),
[
pytest.param(
{"json": {"q": "query Me", "variables": {"id": 1}}}, {"q": "query Me", "variables": {"id": 1}}, id="json"
),
pytest.param({"data": {"a": "1", "b": "x y"}}, "a=1&b=x+y", id="form"),
pytest.param({"data": "<Envelope/>", "headers": {"Content-Type": "text/xml"}}, "<Envelope/>", id="xml"),
],
)
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_text_request_body_is_recorded_as_sent(server, debug_log, make_session, kw, expected):
make_session().post(f"{server.url}/api/send", **kw)
assert records(debug_log)[-1]["request"]["body"] == expected
@pytest.mark.parametrize(
"kw",
[
pytest.param({"data": b"\x08\x04\x12", "headers": {"Content-Type": "application/octet-stream"}}, id="binary"),
pytest.param({"data": b"\x08\x04\x12"}, id="no-type"),
pytest.param({}, id="none"),
],
)
@pytest.mark.parametrize("make_session", SESSIONS)
def test_no_request_body_for_a_binary_or_empty_request(server, debug_log, make_session, kw):
make_session().post(f"{server.url}/api/send", **kw)
assert "body" not in records(debug_log)[-1]["request"]
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_server_process_records_no_request_body(server, debug_log, make_session, monkeypatch):
monkeypatch.setattr(http_session, "record_bodies", False)
make_session().post(f"{server.url}/api/send", json={"a": 1})
assert "body" not in records(debug_log)[-1]["request"]
@pytest.mark.parametrize("make_session", SESSIONS)
def test_the_size_comes_from_the_body_without_a_content_length(server, debug_log, make_session):
server.docs["/chunked"] = '{"a": 1}'
server.types["/chunked"] = "application/json"
make_session().get(f"{server.url}/chunked")
assert records(debug_log)[-1]["response"]["size"] == len(server.docs["/chunked"])
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_json_reply_at_a_manifest_path_keeps_its_body(server, debug_log, make_session):
assert body_of(server, debug_log, make_session, "/playback/manifest", "application/json", '{"a": 1}')["body"] == {
"a": 1
}
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_recorded_body_stays_readable_by_the_caller(server, debug_log, make_session):
server.docs["/api/read"] = '{"a": 1}'
server.types["/api/read"] = "application/json"
session = make_session()
assert session.get(f"{server.url}/api/read").json() == {"a": 1}
assert b"".join(session.get(f"{server.url}/api/read").iter_content(3)) == b'{"a": 1}'
with session.get(f"{server.url}/api/read", stream=True) as streamed:
assert b"".join(streamed.iter_content(3)) == b'{"a": 1}'
@pytest.mark.parametrize("kind", ["application/json", "text/plain"])
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_body_over_the_limit_is_cut_and_marked(server, debug_log, monkeypatch, make_session, kind):
monkeypatch.setattr(config, "debug_requests_body_limit", 5)
response = body_of(server, debug_log, make_session, "/api/long", kind, '{"xyzwvu": 1}')
assert (response["body"], response["body_size"], response["body_cut"]) == ('{"xyz', 13, True)
def test_a_failed_body_read_is_recorded_and_left_to_the_caller(debug_log):
class Broken:
status_code = 200
headers = {"content-type": "application/json"}
@property
def content(self) -> bytes:
raise rq.exceptions.ChunkedEncodingError("cut short")
response = Broken()
http_session.record_request("GET", "http://h/api", 1, response=response, body=True)
(entry,) = records(debug_log)
assert entry["response"]["body_error"].startswith("ChunkedEncodingError")
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_body_too_deep_for_the_log_never_breaks_the_caller(server, debug_log, make_session):
deep = "[" * 5000 + "]" * 5000
server.docs["/api/deep"] = deep
server.types["/api/deep"] = "application/json"
assert make_session().get(f"{server.url}/api/deep").text == deep
@pytest.mark.parametrize(("value", "limit"), [(None, 0), ("5", 5), (-5, 0)])
def test_the_body_limit_is_a_byte_count(value, limit):
assert Config(debug_requests_body_limit=value).debug_requests_body_limit == limit
def serve_starts(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
from aiohttp import web
from click.testing import CliRunner
from unshackle.commands.serve import serve
monkeypatch.setattr(web, "run_app", lambda *a, **kw: None)
monkeypatch.setattr(config, "serve", {})
assert CliRunner().invoke(serve, ["--api-only", "--no-key"]).exit_code == 0
def worker_starts(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
from unshackle.core.api import download_worker
monkeypatch.setattr(download_worker, "perform_download", lambda *a, **kw: [])
monkeypatch.setattr(download_worker, "relay_prompts", lambda *a: None)
payload = tmp_path / "payload.json"
payload.write_text(json.dumps({"job_id": "j", "service": "EXAMPLE", "title_id": "t"}), encoding="utf-8")
assert download_worker.main(["w", str(payload), str(tmp_path / "result.json")]) == 0
@pytest.mark.parametrize("start", [serve_starts, worker_starts], ids=["serve", "job-worker"])
@pytest.mark.parametrize("make_session", SESSIONS)
def test_a_server_process_records_no_body(server, debug_log, monkeypatch, tmp_path, make_session, start):
start(monkeypatch, tmp_path)
response = body_of(server, debug_log, make_session, "/api/json", "application/json", '{"a": 1}')
assert http_session.record_bodies is False
assert response == {"status": 200, "size": 8}
def test_serve_keeps_request_lines_out_of_the_dashboard_log(monkeypatch, tmp_path, caplog):
from unshackle.core.api.stats import ring
serve_starts(monkeypatch, tmp_path)
with caplog.at_level(logging.DEBUG):
for name in ("RnetSession", "urllib3.connectionpool", "EXAMPLE"):
logging.getLogger(name).debug(f"EXAMPLE {name} line ?sig=S1")
logging.getLogger("RnetSession").warning("EXAMPLE retry warning")
lines = [r["msg"] for r in ring.since(0) if r["msg"].startswith("EXAMPLE")]
assert lines == ["EXAMPLE EXAMPLE line ?sig=S1", "EXAMPLE retry warning"]
def paths(path: Path) -> list[str]:
return [e["request"]["path"] for e in records(path)]
@pytest.mark.parametrize("make_session", SESSIONS)
def test_hls_media_probes_are_not_recorded_but_the_playlist_is(server, debug_log, make_session):
session = make_session()
server.docs["/v.m3u8"] = '#EXTM3U\n#EXT-X-MAP:URI="init.mp4",BYTERANGE="1@0"\n#EXTINF:4,\nseg.ts\n#EXT-X-ENDLIST\n'
HLS.probe_ts_info(f"{server.url}/v.m3u8", session)
playlist = m3u8.loads(server.docs["/v.m3u8"], uri=f"{server.url}/v.m3u8")
HLS.fetch_init_section(session, playlist.segments[0].init_section, 0)
HLS.get_track_kid_from_init(playlist, SimpleNamespace(get_key_id=lambda _: None), session) # type: ignore[arg-type]
assert (server.hits.count("/seg.ts"), server.hits.count("/init.mp4")) == (1, 2)
assert paths(debug_log) == ["/v.m3u8"]
assert "body" not in records(debug_log)[0]["response"]
@pytest.mark.parametrize("make_session", SESSIONS)
def test_dash_init_reads_are_not_recorded_but_the_manifest_is(server, debug_log, monkeypatch, make_session):
monkeypatch.setattr(Track, "get_key_id", lambda *_: None)
session = make_session()
server.docs["/manifest.mpd"] = f"""<?xml version="1.0"?>
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" mediaPresentationDuration="PT2S">
<BaseURL>{server.url}/</BaseURL>
<Period id="0" duration="PT2S">
<AdaptationSet contentType="video" mimeType="video/mp4" lang="en">
<Representation id="t" codecs="avc1.640028" bandwidth="1000000">
<SegmentTemplate timescale="1" duration="1" startNumber="1" initialization="init.mp4" media="$Number$.mp4"/>
</Representation>
<Representation id="b" codecs="avc1.640028" bandwidth="900000">
<BaseURL>file.mp4</BaseURL>
<SegmentBase indexRange="0-0"><Initialization range="0-0"/></SegmentBase>
</Representation>
<Representation id="l" codecs="avc1.640028" bandwidth="800000">
<SegmentList duration="1"><Initialization sourceURL="list.mp4"/><SegmentURL media="s1.mp4"/></SegmentList>
</Representation>
</AdaptationSet>
</Period>
</MPD>"""
DASH.from_url(f"{server.url}/manifest.mpd", session)
tree = load_xml(server.docs["/manifest.mpd"].encode())
period = tree.find("Period")
for rep in period.iter("Representation"):
track = Track(url=f"{server.url}/manifest.mpd", language="en")
DASH.get_period_segments(
period, period.find("AdaptationSet"), rep, tree, track, track.url, session, window=(0, 1)
)
assert [server.hits.count(p) for p in ("/init.mp4", "/file.mp4", "/list.mp4")] == [1, 2, 1]
assert paths(debug_log) == ["/manifest.mpd"]
@pytest.mark.parametrize("make_session", SESSIONS)
def test_bitrate_probes_are_not_recorded(server, debug_log, make_session):
session = make_session()
bitrate.ranged_get(f"{server.url}/a.mp4", session, "bytes=0-0")
bitrate.probe_size(bitrate.Segment(f"{server.url}/plain-b.mp4", None, None, 0.0), session)
assert server.hits == ["/a.mp4", "/plain-b.mp4", "/plain-b.mp4"]
assert records(debug_log) == []
@pytest.mark.parametrize("make_session", SESSIONS)
def test_track_init_and_sample_probes_are_not_recorded(server, debug_log, make_session):
session = make_session()
track = Track(url=f"{server.url}/c.mp4", language="en")
track.get_init_segment(session=session)
track.sample_byte_range(session)
Track(url=f"{server.url}/plain-c.mp4", language="en").get_init_segment(session=session)
assert (server.hits.count("/c.mp4"), server.hits.count("/plain-c.mp4")) == (4, 3)
assert records(debug_log) == []
def test_an_unrecorded_probe_keeps_the_session_attributes(server, debug_log):
class Own(rq.Session):
def __init__(self) -> None:
super().__init__()
self.token = "T"
def request(self, *args: Any, **kwargs: Any) -> rq.Response:
kwargs["headers"] = {"X-Token": self.token}
return super().request(*args, **kwargs)
session = Own()
record_requests(session)
unrecorded(session, "get", f"{server.url}/probe")
dl.probe_ranged(f"{server.url}/segment", session)
session.get(f"{server.url}/api")
assert paths(debug_log) == ["/api"]
+80
View File
@@ -8,6 +8,8 @@ import logging
import threading import threading
from collections.abc import Callable, Iterator from collections.abc import Callable, Iterator
from datetime import UTC, datetime from datetime import UTC, datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from threading import Event, Semaphore, Thread from threading import Event, Semaphore, Thread
from types import SimpleNamespace from types import SimpleNamespace
from typing import Any from typing import Any
@@ -32,9 +34,11 @@ from unshackle.core.remote_channel import PollingChannel, WebSocketChannel
from unshackle.core.remote_protocol import CHANNEL_ROUTE, LOGS_ROUTE, PROMPT_ROUTE, SESSION_ROUTE, APIErrorCode from unshackle.core.remote_protocol import CHANNEL_ROUTE, LOGS_ROUTE, PROMPT_ROUTE, SESSION_ROUTE, APIErrorCode
from unshackle.core.remote_service import RemoteError, RemoteService from unshackle.core.remote_service import RemoteError, RemoteService
from unshackle.core.service import Service from unshackle.core.service import Service
from unshackle.core.session import RnetSession, record_requests
from unshackle.core.titles.movie import Movie, Movies from unshackle.core.titles.movie import Movie, Movies
from unshackle.core.tracks import Audio, Chapters, Tracks from unshackle.core.tracks import Audio, Chapters, Tracks
from unshackle.core.tracks.track import Track from unshackle.core.tracks.track import Track
from unshackle.core.utilities import close_debug_logger, init_debug_logger
pytestmark = pytest.mark.unit pytestmark = pytest.mark.unit
@@ -59,6 +63,8 @@ class StubService:
self._input_bridge: Any = None self._input_bridge: Any = None
StubService.logins += 1 StubService.logins += 1
self.login = StubService.logins self.login = StubService.logins
if hook := self.hooks.get("init"):
hook(self)
def authenticate(self, cookies: Any, credential: Any) -> None: def authenticate(self, cookies: Any, credential: Any) -> None:
if self._input_bridge.request_input("Enter the EXAMPLE code") != CODE: if self._input_bridge.request_input("Enter the EXAMPLE code") != CODE:
@@ -404,6 +410,80 @@ def test_the_session_channel_carries_what_the_server_starts(
service.close() service.close()
class Origin(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *_: Any) -> None:
pass
def do_GET(self) -> None:
self.send_response(200)
self.send_header("Content-Length", "2")
self.end_headers()
self.wfile.write(b"{}")
@pytest.mark.parametrize("channel", ["socket", "polling"])
def test_server_request_records_never_reach_the_remote_client(
server: SimpleNamespace,
channel: str,
caplog: pytest.LogCaptureFixture,
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
"""The http_request entries of the service's requests stay in the server's JSONL, out of the session log."""
caplog.set_level(logging.DEBUG)
if channel == "polling":
monkeypatch.setattr(WebSocketChannel, "open", lambda self, timeout=0: False)
origin = ThreadingHTTPServer(("127.0.0.1", 0), Origin)
origin.daemon_threads = True
Thread(target=origin.serve_forever, daemon=True).start()
base = f"127.0.0.1:{origin.server_address[1]}"
monkeypatch.setattr(config, "debug_requests", True)
debug_log = tmp_path / "server.jsonl"
init_debug_logger(log_path=debug_log, enabled=True)
def fetch(step: str) -> None:
plain = requests.Session()
record_requests(plain)
plain.get(f"http://{base}/v1/{step}?access_token=EXAMPLE")
RnetSession().get(f"http://{base}/v1/{step}-rnet?access_token=EXAMPLE")
def init(stub: StubService) -> None:
fetch("init")
logging.getLogger("StubService").info("EXAMPLE init done")
def titles(stub: StubService) -> None:
fetch("titles")
stub.log.info("EXAMPLE titles fetched")
StubService.hooks.update(init=init, titles=titles)
service = make_client(server.url)
try:
service.authenticate()
assert len(service.get_titles()) == 3
service.drain_server_logs()
assert wait_until(lambda: {"EXAMPLE init done", "EXAMPLE titles fetched"} <= set(example_messages(caplog)), 10)
(entry,) = session_store.get_session_store()._sessions.values()
buffered = [r["message"] for r in entry.log_buffer.since(0)]
finally:
service.close()
origin.shutdown()
origin.server_close()
close_debug_logger()
assert {"EXAMPLE init done", "EXAMPLE titles fetched"} <= set(buffered)
sent = [*buffered, *example_messages(caplog), *(body.decode("utf-8", "replace") for _, body in server.bodies)]
for text in sent:
assert "http_request" not in text and base not in text and "/v1/" not in text
records = [json.loads(line) for line in debug_log.read_text(encoding="utf-8").splitlines()]
entries = [e for e in records if e.get("operation") == "http_request"]
assert {"/v1/init", "/v1/init-rnet", "/v1/titles", "/v1/titles-rnet"} <= {e["request"]["path"] for e in entries}
server_host = server.url.split("://")[1].rstrip("/")
own = [e for e in entries if e["request"]["host"] == server_host and e["request"]["path"].endswith("/titles")]
assert own and all(isinstance(e["response"]["body"], dict) for e in own)
def test_an_open_channel_keeps_the_session_alive(server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch) -> None: def test_an_open_channel_keeps_the_session_alive(server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch) -> None:
ttl = 0.3 ttl = 0.3
monkeypatch.setitem(config.serve, "session_ttl", ttl) monkeypatch.setitem(config.serve, "session_ttl", ttl)
+10 -1
View File
@@ -17,6 +17,7 @@ from aiohttp import web
import unshackle.core.config as config_module import unshackle.core.config as config_module
from unshackle.core import binaries 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 import cors_middleware, no_5xx_middleware, setup_routes
from unshackle.core.api.compression import compression_middleware from unshackle.core.api.compression import compression_middleware
from unshackle.core.api.events import publish_refresh_events, publish_service_event 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.config import Config, config
from unshackle.core.console import console 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.downloaders import format_speed, parse_speed_limit, set_speed_limit
from unshackle.core.remote_protocol import HEALTH_ROUTE from unshackle.core.remote_protocol import HEALTH_ROUTE
@@ -401,6 +402,8 @@ def serve(
from pyplayready.remote import serve as pyplayready_serve from pyplayready.remote import serve as pyplayready_serve
from pywidevine import serve as pywidevine_serve from pywidevine import serve as pywidevine_serve
http_session.record_bodies = False
if quiet: if quiet:
logging.basicConfig( logging.basicConfig(
force=True, force=True,
@@ -429,6 +432,12 @@ def serve(
logging.getLogger("api").setLevel(logging.WARNING) logging.getLogger("api").setLevel(logging.WARNING)
logging.getLogger("api.remote").setLevel(logging.WARNING) logging.getLogger("api.remote").setLevel(logging.WARNING)
ring.setFormatter(logging.Formatter("%(message)s")) 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: if not debug:
ring.addFilter(lambda record: record.name != "aiohttp.access") ring.addFilter(lambda record: record.name != "aiohttp.access")
logging.getLogger().addHandler(ring) 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.commands import Commands
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.console import ComfyRichHandler, console 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.update_checker import UpdateChecker
from unshackle.core.utilities import close_debug_logger, init_debug_logger 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) init_debug_logger(enabled=True)
if debug and not config.debug_requests: 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) logging.getLogger(noisy).setLevel(logging.WARNING)
urllib3.disable_warnings(InsecureRequestWarning) urllib3.disable_warnings(InsecureRequestWarning)
+2
View File
@@ -16,6 +16,7 @@ from pathlib import Path
from typing import Any from typing import Any
from uuid import uuid4 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.api.input_bridge import AUTH_INPUT_TIMEOUT
from unshackle.core.console import set_notice_handler, set_prompt_handler from unshackle.core.console import set_notice_handler, set_prompt_handler
from unshackle.core.downloaders import format_speed, set_speed_limit from unshackle.core.downloaders import format_speed, set_speed_limit
@@ -116,6 +117,7 @@ def main(argv: list[str]) -> int:
) )
return 2 return 2
http_session.record_bodies = False
payload_path = Path(argv[1]) payload_path = Path(argv[1])
result_path = Path(argv[2]) result_path = Path(argv[2])
progress_path = Path(argv[3]) if len(argv) > 3 else None 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: bool = kwargs.get("debug", False)
self.debug_keys: bool = kwargs.get("debug_keys", False) self.debug_keys: bool = kwargs.get("debug_keys", False)
self.debug_requests: bool = kwargs.get("debug_requests", 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: def validate_output_templates(self) -> None:
"""Validate output template configurations and warn about potential issues.""" """Validate output template configurations and warn about potential issues."""
+1
View File
@@ -8,6 +8,7 @@ DOWNLOAD_CANCELLED = Event()
DOWNLOAD_LICENCE_ONLY = Event() DOWNLOAD_LICENCE_ONLY = Event()
DEFAULT_SAMPLE = (120, 180) DEFAULT_SAMPLE = (120, 180)
HTTP_LOGGERS = ("urllib3", "urllib3.connectionpool", "requests", "rnet", "httpx", "httpcore", "hpack", "h2")
DOWNLOAD_ALL_DRM = Event() 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: def no_retry_session(session: Session) -> Session:
"""A shallow copy of ``session`` whose adapters never retry, sharing its state and pools. """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 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 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 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. 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() view.adapters = OrderedDict()
for prefix, adapter in session.adapters.items(): for prefix, adapter in session.adapters.items():
twin = copy(adapter) 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()) rest.setdefault("read_timeout", rnet_read_timeout())
# let download() own segment retries, with no nested session-level retry loop # let download() own segment retries, with no nested session-level retry loop
rest.setdefault("max_retries", 0) rest.setdefault("max_retries", 0)
rest.setdefault("record_request", False)
else: else:
rest.setdefault("timeout", (CONNECT_TIMEOUT, READ_TIMEOUT)) rest.setdefault("timeout", (CONNECT_TIMEOUT, READ_TIMEOUT))
session = no_retry_session(session) session = no_retry_session(session)
@@ -891,6 +896,7 @@ def download(
request_kwargs.setdefault("read_timeout", rnet_read_timeout()) request_kwargs.setdefault("read_timeout", rnet_read_timeout())
# own segment retries here, suppressing RnetSession's nested retry loop # own segment retries here, suppressing RnetSession's nested retry loop
request_kwargs.setdefault("max_retries", 0) request_kwargs.setdefault("max_retries", 0)
request_kwargs.setdefault("record_request", False)
else: else:
request_kwargs.setdefault("timeout", (CONNECT_TIMEOUT, READ_TIMEOUT)) request_kwargs.setdefault("timeout", (CONNECT_TIMEOUT, READ_TIMEOUT))
req_headers = dict(request_kwargs.get("headers", {}) or {}) 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.proxies.resolve import REGION_QUERY
from unshackle.core.remote_protocol import APIErrorCode, coded from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.remote_service import resolve_proxy_arg, segment_uri_filter 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.title_source import KeyArrival, TitleSource
from unshackle.core.titles import Episode, Movies, Series, Title_T, Titles_T, remap_titles 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 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")), {}) 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) self.session = self.build_session(ctx, self.region, headers)
record_requests(self.session)
@staticmethod @staticmethod
def legacy_entry(entry: mediaexport.Entry) -> dict[str, Any]: 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, license_drm,
) )
from unshackle.core.manifests.trim import trim_overlaps 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 import Audio, DownloadContext, Subtitle, Tracks, Video, resume
from unshackle.core.tracks.track import DRM_PREFERENCE_TYPES, Track, parse_sidx 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 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") init_url = segment_template.get("initialization")
if init_url and probe_kid: if init_url and probe_kid:
res = session.get( res = unrecorded(
session,
"get",
DASH.replace_fields( DASH.replace_fields(
init_url, Bandwidth=representation.get("bandwidth"), RepresentationID=representation.get("id") init_url, Bandwidth=representation.get("bandwidth"), RepresentationID=representation.get("id")
) ),
) )
res.raise_for_status() res.raise_for_status()
init_data = res.content init_data = res.content
@@ -1192,7 +1194,7 @@ class DASH:
else: else:
init_range_header = None 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() res.raise_for_status()
init_data = res.content init_data = res.content
track_kid = track.get_key_id(init_data) 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 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 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): 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() res.raise_for_status()
content_range = parse_content_range(res.headers.get("Content-Range")) content_range = parse_content_range(res.headers.get("Content-Range"))
if init_range_header and not ( if init_range_header and not (
@@ -1243,7 +1245,7 @@ class DASH:
subsegments: list[tuple[int, int, int]] = [] subsegments: list[tuple[int, int, int]] = []
index_range = segment_base.get("indexRange") index_range = segment_base.get("indexRange")
if window and index_range and not isinstance(track, Subtitle): 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() res.raise_for_status()
segment_timescale, subsegments = parse_sidx(res.content, int(index_range.split("-")[0])) 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, licensing,
remove_segment_dir, 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 import Audio, DownloadContext, Subtitle, Tracks, Video, resume
from unshackle.core.tracks.track import DRM_PREFERENCE_TYPES, Track, assert_fragments_decrypted 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 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) 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 # 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 data = res.content
return HLS.parse_ts_video_info(data) return HLS.parse_ts_video_info(data)
@@ -595,10 +595,7 @@ class HLS:
else: else:
init_range_header = {} init_range_header = {}
res = session.get( res = unrecorded(session, "get", urljoin(init_section.base_uri, init_section.uri), headers=init_range_header)
url=urljoin(init_section.base_uri, init_section.uri),
headers=init_range_header,
)
if not isinstance(res, (requests.Response, RnetResponse)): if not isinstance(res, (requests.Response, RnetResponse)):
raise TypeError(f"Expected response to be requests.Response or rnet.Response, not {type(res)}") 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}"} headers = {"Range": f"bytes={byte_range}"}
else: else:
headers = {} headers = {}
map_res = session.get(url=map_uri, headers=headers) map_res = unrecorded(session, "get", map_uri, headers=headers)
if map_res.ok: if map_res.ok:
return track.get_key_id(map_res.content) return track.get_key_id(map_res.content)
logging.getLogger("HLS").warning( logging.getLogger("HLS").warning(
+3 -1
View File
@@ -85,7 +85,7 @@ from unshackle.core.remote_protocol import (
coded, coded,
) )
from unshackle.core.search_result import SearchResult 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.title_source import KeyArrival, TitleSource
from unshackle.core.titles import Title_T, Titles_T, remap_titles from unshackle.core.titles import Title_T, Titles_T, remap_titles
from unshackle.core.titles.episode import Episode, Series from unshackle.core.titles.episode import Episode, Series
@@ -247,6 +247,7 @@ class RemoteClient:
from unshackle.core import __version__ from unshackle.core import __version__
self._session = requests.Session() self._session = requests.Session()
record_requests(self._session)
self._session.headers["User-Agent"] = f"unshackle/{__version__}" self._session.headers["User-Agent"] = f"unshackle/{__version__}"
if self.api_key: if self.api_key:
self._session.headers[self.auth_headers[self._auth_header_index]] = 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://"]) self.session.mount("http://", self.session.adapters["https://"])
record_requests(self.session)
svc_config = services_config.get(service_tag, {}) svc_config = services_config.get(service_tag, {})
self._server_cdm: bool | None = services_config.get("_server_cdm") self._server_cdm: bool | None = services_config.get("_server_cdm")
+2
View File
@@ -32,6 +32,7 @@ from unshackle.core.session import (
READ_TIMEOUT, READ_TIMEOUT,
RETRY_METHODS, RETRY_METHODS,
STATUS_FORCELIST, STATUS_FORCELIST,
record_requests,
) )
from unshackle.core.title_cacher import TitleCacher from unshackle.core.title_cacher import TitleCacher
from unshackle.core.title_source import TitleSource from unshackle.core.title_source import TitleSource
@@ -164,6 +165,7 @@ class Service(TitleSource):
self.log = logging.getLogger(self.__class__.__name__) self.log = logging.getLogger(self.__class__.__name__)
self.session = self.get_session() self.session = self.get_session()
record_requests(self.session)
self.cache = Cacher(self.__class__.__name__) self.cache = Cacher(self.__class__.__name__)
self.title_cache: TitleCacher = TitleCacher(self.__class__.__name__) self.title_cache: TitleCacher = TitleCacher(self.__class__.__name__)
self.cache_dir = config.directories.cache / self.__class__.__name__ self.cache_dir = config.directories.cache / self.__class__.__name__
+278 -25
View File
@@ -2,7 +2,9 @@
from __future__ import annotations from __future__ import annotations
import contextlib
import http import http
import json
import logging import logging
import math import math
import random import random
@@ -15,14 +17,16 @@ from datetime import UTC, datetime
from email.utils import parsedate_to_datetime from email.utils import parsedate_to_datetime
from http.cookiejar import Cookie, CookieJar from http.cookiejar import Cookie, CookieJar
from typing import Any from typing import Any
from urllib.parse import urlencode, urlparse, urlunparse from urllib.parse import urlencode, urlparse, urlsplit, urlunparse
import rnet 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.cookies import create_cookie
from requests.structures import CaseInsensitiveDict from requests.structures import CaseInsensitiveDict
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.utilities import get_debug_logger, log_event
from unshackle.core.utils import run_proxy from unshackle.core.utils import run_proxy
# rnet's only distinguishing role is TLS fingerprinting; retry, backoff, # 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]: def iter_content(self, chunk_size: int | None = None) -> Iterator[bytes]:
"""Re-chunk rnet's variable-size data into fixed-size pieces.""" """Re-chunk rnet's variable-size data, or the body already read, into fixed-size pieces."""
self._streamed = True
if chunk_size is None or chunk_size <= 0: if chunk_size is None or chunk_size <= 0:
yield from self._resp.stream() yield from self.stream()
return return
buf = bytearray() buf = bytearray()
for chunk in self._resp.stream(): for chunk in self.stream():
buf.extend(chunk) buf.extend(chunk)
while len(buf) >= chunk_size: while len(buf) >= chunk_size:
yield bytes(buf[:chunk_size]) yield bytes(buf[:chunk_size])
@@ -217,8 +220,11 @@ class RnetResponse:
yield bytes(buf) yield bytes(buf)
def stream(self) -> Iterator[bytes]: 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 self._streamed = True
if self._content is not None:
yield self._content
return
yield from self._resp.stream() yield from self._resp.stream()
def close(self) -> None: 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__ 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: class RnetSession:
"""TLS-fingerprinted HTTP session powered by rnet (Rust/BoringSSL). """TLS-fingerprinted HTTP session powered by rnet (Rust/BoringSSL).
@@ -844,13 +1060,58 @@ class RnetSession:
pass pass
return response 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: def request(self, method: str, url: str, **kwargs: Any) -> RnetResponse:
"""Send a request, retrying on the status forcelist and on the caught exception types. """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. 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 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 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() client = self.ensure_client()
method_upper = method.upper() if isinstance(method, str) else str(method).upper() method_upper = method.upper() if isinstance(method, str) else str(method).upper()
@@ -876,7 +1137,7 @@ class RnetSession:
kwargs.setdefault("verify", False) kwargs.setdefault("verify", False)
# Remove kwargs rnet doesn't understand # 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) data = kwargs.pop("data", None)
if data is not None: if data is not None:
@@ -895,29 +1156,21 @@ class RnetSession:
if kwargs.get("headers") is not None: if kwargs.get("headers") is not None:
kwargs["headers"] = dict(kwargs["headers"]) 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: 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 last_exception: Exception | None = None
response: RnetResponse | None = None response: RnetResponse | None = None
for attempt in range(max_retries + 1): for attempt in range(max_retries + 1):
try: try:
response = self.absorb_cookies(RnetResponse(client.request(rnet_method, url, **kwargs))) response = self.send_attempt(
client, rnet_method, method_upper, url, attempt + 1, record, body, sent, 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)
if response.status_code not in self.status_forcelist: if response.status_code not in self.status_forcelist:
return response return response
+6 -6
View File
@@ -39,7 +39,7 @@ from unshackle.core.drm.verify import (
walk, walk,
) )
from unshackle.core.events import events 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.temp import restore_segments, stash_segments
from unshackle.core.tracks import resume from unshackle.core.tracks import resume
from unshackle.core.utilities import language_name, log_event, try_ensure_utf8 from unshackle.core.utilities import language_name, log_event, try_ensure_utf8
@@ -545,7 +545,7 @@ class Track:
def read_to(end: int) -> None: def read_to(end: int) -> None:
nonlocal head nonlocal head
if end > len(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: if res.ok:
head += res.content head += res.content
@@ -1197,23 +1197,23 @@ class Track:
if start > end: if start > end:
raise ValueError(f"The start range cannot be greater than the end range: {start}>{end}") raise ValueError(f"The start range cannot be greater than the end range: {start}>{end}")
else: else:
size_test = session.head(url) size_test = unrecorded(session, "head", url)
if "Content-Length" in size_test.headers: if "Content-Length" in size_test.headers:
content_length_header = int(size_test.headers["Content-Length"]) content_length_header = int(size_test.headers["Content-Length"])
if content_length_header > 0: if content_length_header > 0:
content_length = min(content_length_header, maximum_size) 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: if range_test.status_code == 206:
byte_range = f"0-{content_length - 1}" byte_range = f"0-{content_length - 1}"
init_data: bytes | None init_data: bytes | None
if byte_range: 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() res.raise_for_status()
init_data = res.content init_data = res.content
else: else:
init_data = None init_data = None
s = session.get(url, stream=True) s = unrecorded(session, "get", url, stream=True)
if not s.ok: if not s.ok:
s.close() s.close()
raise ValueError(f"Track URI returned HTTP {s.status_code}") 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.config import config
from unshackle.core.constants import LANGUAGE_EXACT_DISTANCE, LANGUAGE_MAX_DISTANCE 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. Utility functions for the unshackle media archival tool.
@@ -1124,6 +1124,7 @@ class DebugLogger:
response: dict[str, Any] | None = None, response: dict[str, Any] | None = None,
duration_ms: float | None = None, duration_ms: float | None = None,
success: bool | None = None, success: bool | None = None,
raw: bool = False,
**kwargs: Any, **kwargs: Any,
) -> None: ) -> None:
""" """
@@ -1140,70 +1141,71 @@ class DebugLogger:
response: Response details (status, headers, body) response: Response details (status, headers, body)
duration_ms: Operation duration in milliseconds duration_ms: Operation duration in milliseconds
success: Whether the operation succeeded 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 **kwargs: Additional fields to include in the log entry
""" """
if not self.enabled or not self.file_handle: if not self.enabled or not self.file_handle:
return return
entry: dict[str, Any] = { try:
"timestamp": datetime.now(UTC).isoformat(), entry: dict[str, Any] = {
"session_id": self.session_id, "timestamp": datetime.now(UTC).isoformat(),
"level": level, "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__)
],
} }
for key, value in kwargs.items(): if operation:
if key not in entry: entry["operation"] = operation
entry[key] = self.sanitize_data(value) 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.write(json.dumps(entry, default=str) + "\n")
self.file_handle.flush() self.file_handle.flush()
except Exception as e: except Exception as e:
print(f"Failed to write debug log: {e}", file=sys.stderr) 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. 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: if data is None:
return None return None
if isinstance(data, str): if isinstance(data, str):
# mask secrets, collapse content/CDN URLs, and strip local path prefixes # 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)): if isinstance(data, (int, float, bool)):
return data return data
if isinstance(data, (list, tuple)): 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): if isinstance(data, dict):
sanitized = {} sanitized = {}
@@ -1221,12 +1223,12 @@ class DebugLogger:
and not any(safe in key_lower for safe in ["_count", "_id", "_type", "kid", "keys_", "key_found"]) 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: if should_redact:
sanitized[key] = "[REDACTED]" sanitized[key] = "[REDACTED]"
else: else:
sanitized[key] = self.sanitize_data(value) sanitized[key] = self.sanitize_data(value, raw)
return sanitized return sanitized
if isinstance(data, bytes): 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.binaries import FFProbe
from unshackle.core.constants import TrackT 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 from unshackle.core.utils.subprocess import log_tool_run
if TYPE_CHECKING: 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: 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.""" """Return a segment's byte size with a HEAD request, falling back to a ranged GET. Validates status."""
try: 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): if getattr(res, "status_code", 0) in (200, 206):
content_length = res.headers.get("Content-Length") content_length = res.headers.get("Content-Length")
if 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) # Require a 206 so a server that ignores Range (returning the whole 200 body)
# is not mistaken for a valid size or downloaded wholesale. # is not mistaken for a valid size or downloaded wholesale.
try: 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: if getattr(res, "status_code", 0) == 206:
content_range = res.headers.get("Content-Range") content_range = res.headers.get("Content-Range")
if content_range and "/" in 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: 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).""" """Fetch a byte range, only accepting a real 206 partial response (never a full 200 body)."""
try: 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: if getattr(res, "status_code", 0) != 206:
return None return None
content = getattr(res, "content", 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: def fallback_session() -> requests.Session:
"""A new requests session for a core helper that got no session, on the proxy of the calling service.""" """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() session = requests.Session()
proxy = run_proxy_for(sys._getframe(1)) proxy = run_proxy_for(sys._getframe(1))
if proxy: if proxy:
session.proxies.update({"all": proxy}) session.proxies.update({"all": proxy})
pin(session) pin(session)
record_requests(session)
return session return session