fix(vaults): log each vault failure once in one line without the request url

This commit is contained in:
imSp4rky
2026-11-27 09:47:49 -07:00
parent 5a6428521c
commit b719c44679
8 changed files with 274 additions and 48 deletions
+35 -2
View File
@@ -1,14 +1,17 @@
import re
from abc import ABCMeta, abstractmethod
from collections.abc import Iterator
from urllib.parse import urlsplit
from uuid import UUID
from requests import ConnectionError as RequestsConnectionError
from requests import Session, Timeout
from requests import RequestException, Response, Session, Timeout
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from unshackle.core import __version__
from unshackle.core.session import POOL_MAX_SIZE
from unshackle.core.utils.redact import redact_text
RATE_LIMIT_RETRIES = 3
@@ -22,6 +25,36 @@ class RateLimited(Exception):
UNREACHABLE = (RequestsConnectionError, Timeout, ConnectionError, TimeoutError)
OS_REASON_RE = re.compile(r"\[(?:Errno -?\d+|WinError -?\d+|SSL: \w+)\] ([^'\"()\[\]]+)")
def brief(error: BaseException) -> str:
"""One line for a vault failure, without the request URL, whose query can hold the vault password."""
if not isinstance(error, RequestException) or (error.request is None and error.response is None):
text = (redact_text(str(error).strip().split("\n", 1)[0]) or "")[:200]
return text or type(error).__name__
url = getattr(error.request, "url", None)
host = urlsplit(url).netloc.rpartition("@")[2] if url else "vault"
if error.response is not None:
return f"HTTP {error.response.status_code} from {host}"
text = str(error)
reasons = OS_REASON_RE.findall(text)
reason = reasons[-1].strip() if reasons else "timed out" if "timed out" in text else ""
return f"{type(error).__name__} to {host}" + (f" ({reason})" if reason else "")
def json_body(r: Response) -> dict:
"""The response body as a JSON object. Any other body means the host is not a vault, so it is unreachable."""
try:
data = r.json()
except ValueError:
data = None
if not isinstance(data, dict):
mime = re.match(r"[\w.+-]{1,64}/[\w.+-]{1,64}", r.headers.get("Content-Type", ""))
content_type = mime.group() if mime else "unknown"
raise ConnectionError(f"HTTP {r.status_code} {content_type} response is not a JSON object")
return data
def is_null_key(key: str | None) -> bool:
"""True for a blank or all-zero content key, the null key that no vault stores."""
@@ -115,4 +148,4 @@ class Vault(metaclass=ABCMeta):
"""Forget a flagged KID:KEY, for example when a CDM licence confirmed it."""
__all__ = ("Vault",)
__all__ = ("Vault", "brief", "json_body")
+15 -4
View File
@@ -9,7 +9,7 @@ from uuid import UUID
from unshackle.core.config import config
from unshackle.core.utilities import get_debug_logger, import_module_by_path
from unshackle.core.vault import UNREACHABLE, RateLimited, Vault, is_null_key
from unshackle.core.vault import UNREACHABLE, RateLimited, Vault, brief, is_null_key
log = logging.getLogger(__name__)
@@ -30,6 +30,7 @@ class Vaults:
self.flagged: set[tuple[UUID | str, str]] = set()
self.candidates: dict[UUID | str, list[tuple[str, Vault]]] = {}
self.warned: set[tuple[str, UUID | str, str]] = set()
self.failed: set[tuple[str, str]] = set()
self.unreachable: set[Vault] = set()
self.unreported: dict[tuple[UUID | str, str], Vault] = {}
@@ -110,7 +111,7 @@ class Vaults:
except (PermissionError, NotImplementedError):
return None
except Exception as e:
log.warning(f"Failed to get key from Vault '{vault.name}': {e}")
self.warn_failure(vault, "get key from", e)
self.mark_unreachable(vault, e)
if dl:
dl.log_vault_query(
@@ -209,7 +210,7 @@ class Vaults:
except (PermissionError, NotImplementedError):
return 0
except Exception as e:
log.warning(f"Failed to add key to Vault '{vault.name}': {e}")
self.warn_failure(vault, "add key to", e)
self.mark_unreachable(vault, e)
if dl:
dl.log_vault_query(vault.name, "add_key", kid=str(kid), success=False, error=e)
@@ -240,7 +241,7 @@ class Vaults:
except (PermissionError, NotImplementedError):
return 0
except Exception as e:
log.warning(f"Failed to add keys to Vault '{vault.name}': {e}")
self.warn_failure(vault, "add keys to", e)
self.mark_unreachable(vault, e)
return 0
@@ -252,6 +253,16 @@ class Vaults:
"""True when a local vault already holds this KID:KEY."""
return any(self.query_vault(vault, kid) == key for vault in self.vaults if vault.local)
def warn_failure(self, vault: Vault, action: str, error: Exception) -> None:
"""Warn once per vault for each distinct failure; a repeat goes to the debug log."""
text = brief(error)
message = f"Failed to {action} Vault '{vault.name}': {text}"
if (vault.name, text) in self.failed:
log.debug(message)
else:
self.failed.add((vault.name, text))
log.warning(message)
def mark_unreachable(self, vault: Vault, error: Exception) -> None:
"""Skip a vault that is down or still rate limited for the rest of the run, so it costs one
timeout, not one per KID."""