forked from kenzuya/unshackle
refactor(vaults): pick kv vault behaviour from class flags and keep the api batch size
This commit is contained in:
@@ -7,6 +7,7 @@ from typing import cast
|
||||
from uuid import UUID
|
||||
|
||||
import click
|
||||
from requests import RequestException
|
||||
from rich.console import RenderableType
|
||||
from rich.padding import Padding
|
||||
from rich.progress import (
|
||||
@@ -24,7 +25,7 @@ from unshackle.core.config import config
|
||||
from unshackle.core.console import GradientPulseBarColumn, console
|
||||
from unshackle.core.constants import context_settings
|
||||
from unshackle.core.services import Services
|
||||
from unshackle.core.vault import Vault, brief, is_null_key
|
||||
from unshackle.core.vault import Refused, Vault, brief, is_null_key
|
||||
from unshackle.core.vaults import Vaults, load_config_vaults
|
||||
|
||||
|
||||
@@ -57,6 +58,11 @@ def without_null_keys(pairs: Iterable[tuple[str, str]], log: logging.Logger) ->
|
||||
return kid_keys
|
||||
|
||||
|
||||
def is_refusal(error: Exception) -> bool:
|
||||
"""True when the vault answered and refused the write, not when it is unreachable or misconfigured."""
|
||||
return isinstance(error, Refused) or (isinstance(error, ValueError) and not isinstance(error, RequestException))
|
||||
|
||||
|
||||
def process_service_keys(from_vault: Vault, service: str, log: logging.Logger) -> dict[str, str]:
|
||||
"""Get and validate keys from a vault for a specific service."""
|
||||
return without_null_keys(from_vault.get_keys(service), log)
|
||||
@@ -71,12 +77,12 @@ class _PaddedProgress(Progress):
|
||||
|
||||
def add_keys_with_progress(vault: Vault, service: str, kid_keys: dict[str, str], log: logging.Logger) -> int:
|
||||
"""Add content keys to a vault. Network vaults write in batches behind a progress bar."""
|
||||
if type(vault).__name__ in ("MySQL", "SQLite"):
|
||||
if vault.bulk_writes:
|
||||
return vault.add_keys(service, cast(dict[UUID | str, str], kid_keys))
|
||||
|
||||
def chunk(i: int) -> int:
|
||||
# Probe with one key so a server that rejects batches costs one row, not 500.
|
||||
return 500 if i and getattr(vault, "batch_insert", True) else 1
|
||||
return 500 if i and vault.batch_insert else 1
|
||||
|
||||
kids = list(kid_keys)
|
||||
added = 0
|
||||
@@ -130,7 +136,10 @@ def copy_service_data(
|
||||
log.warning(f"{service}: No permission to create table in {to_vault}, skipped")
|
||||
return 0
|
||||
except Exception as e:
|
||||
raise click.ClickException(f"Could not write to {to_vault} ({brief(e)})") from None
|
||||
if not is_refusal(e):
|
||||
raise click.ClickException(f"Could not write to {to_vault} ({brief(e)})") from None
|
||||
log.warning(f"{service}: Could not write to {to_vault} ({brief(e)}), skipped")
|
||||
return 0
|
||||
|
||||
existed = total_count - added
|
||||
|
||||
@@ -318,7 +327,10 @@ def add(file: Path, service: str, vaults: list[str]) -> None:
|
||||
try:
|
||||
added_count = add_keys_with_progress(vault, service, kid_keys, log)
|
||||
except Exception as e:
|
||||
raise click.ClickException(f"Could not write to {vault} ({brief(e)})") from None
|
||||
if not is_refusal(e):
|
||||
raise click.ClickException(f"Could not write to {vault} ({brief(e)})") from None
|
||||
log.warning(f"Could not write to {vault} ({brief(e)}), skipped")
|
||||
continue
|
||||
existed_count = total_count - added_count
|
||||
log.info(f"{vault}: {added_count} newly added, {existed_count} already existed (skipped)")
|
||||
|
||||
@@ -430,7 +442,7 @@ def prepare(vaults: list[str]) -> None:
|
||||
vaults_ = load_vaults(vaults)
|
||||
|
||||
for vault in vaults_:
|
||||
if hasattr(vault, "resolve_table") and hasattr(vault, "create_table"):
|
||||
if vault.has_tables:
|
||||
for service_tag in dict.fromkeys(Services.get_vault_tag(tag) for tag in Services.get_tags()):
|
||||
existing = vault.resolve_table(service_tag)
|
||||
if existing:
|
||||
|
||||
@@ -91,10 +91,20 @@ class Refused(Exception):
|
||||
|
||||
|
||||
class Vault(metaclass=ABCMeta):
|
||||
"""A key vault of KID:KEY pairs.
|
||||
|
||||
Its class flags tell kv what it can do: bulk_writes (add_keys takes a whole service in one call),
|
||||
batch_insert (add_keys takes more than one content key; HTTP clears it when the server refuses
|
||||
batches) and has_tables (one table per service, with resolve_table and create_table).
|
||||
"""
|
||||
|
||||
# a vault on this machine; Vaults.get_key tries these first, before the network ones
|
||||
local: bool = False
|
||||
report_now: bool = False
|
||||
stores_flags: bool = False
|
||||
bulk_writes: bool = False
|
||||
batch_insert: bool = True
|
||||
has_tables: bool = False
|
||||
|
||||
def __init__(self, name: str, no_push: bool = False) -> None:
|
||||
self.name = name
|
||||
@@ -152,5 +162,13 @@ class Vault(metaclass=ABCMeta):
|
||||
def unflag_bad_key(self, kid: UUID | str, key: str) -> None:
|
||||
"""Forget a flagged KID:KEY, for example when a CDM licence confirmed it."""
|
||||
|
||||
def resolve_table(self, name: str) -> str | None:
|
||||
"""The stored name of the table of a service, or None. Only a vault with has_tables has tables."""
|
||||
return None
|
||||
|
||||
def create_table(self, name: str) -> None:
|
||||
"""Make the table of a service. Only a vault with has_tables has tables."""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
__all__ = ("Refused", "Vault", "brief", "json_body")
|
||||
|
||||
@@ -246,7 +246,7 @@ class Vaults:
|
||||
try:
|
||||
vault.unflag_bad_key(kid, key)
|
||||
except Exception as e:
|
||||
log.debug(f"Could not unflag {key} in Vault '{vault.name}': {e!r}")
|
||||
log.debug(f"Could not unflag {key} in Vault '{vault.name}': {brief(e)}")
|
||||
|
||||
def add_key(self, kid: UUID | str, key: str, excluding: KeySource | None = None) -> int:
|
||||
"""Add a KID:KEY to all Vaults, optionally with an exclusion.
|
||||
|
||||
+18
-3
@@ -21,6 +21,7 @@ class API(Vault):
|
||||
super().__init__(name, no_push)
|
||||
self.uri = uri.rstrip("/")
|
||||
self.timeout = timeout
|
||||
self.batch_size = 500
|
||||
self.session = vault_session(timeout)
|
||||
self.session.headers.update({"Authorization": f"Bearer {token}"})
|
||||
|
||||
@@ -142,14 +143,20 @@ class API(Vault):
|
||||
return added or updated
|
||||
|
||||
def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
|
||||
"""Post the keys in batches. A failed batch is sent again 100 content keys smaller, down to 1.
|
||||
|
||||
When a call shrank its batch because the server found it too large (400, 413, 414) and then
|
||||
stored every batch, later calls start at that size, so a server with a lower cap costs its
|
||||
failed posts once per vault, not once per call.
|
||||
"""
|
||||
normalized_keys = {str(kid).replace("-", ""): key for kid, key in kid_keys.items()}
|
||||
kid_list = list(normalized_keys.keys())
|
||||
|
||||
if not kid_list:
|
||||
return 0
|
||||
|
||||
# Try batches starting at 500, stepping down by 100 on failure, fallback to 1
|
||||
batch_size = 500
|
||||
batch_size = self.batch_size
|
||||
too_large = False
|
||||
total_added = 0
|
||||
i = 0
|
||||
|
||||
@@ -172,6 +179,7 @@ class API(Vault):
|
||||
batch_size -= 100
|
||||
else:
|
||||
batch_size = 1
|
||||
too_large = True
|
||||
continue
|
||||
|
||||
if response.status_code == 429:
|
||||
@@ -207,6 +215,9 @@ class API(Vault):
|
||||
total_added += added + updated
|
||||
i += batch_size
|
||||
|
||||
if too_large and batch_size > 1:
|
||||
self.batch_size = batch_size
|
||||
|
||||
return total_added
|
||||
|
||||
def flag_bad_key(self, service: str, kid: UUID | str, key: str, source: str) -> None:
|
||||
@@ -241,6 +252,8 @@ class API(Vault):
|
||||
def _check(response: Response, ignore: frozenset[int] = frozenset()) -> None:
|
||||
if response.status_code in (404, 405, 501):
|
||||
return
|
||||
if response.status_code == 429:
|
||||
raise Exceptions.TooManyRequests()
|
||||
response.raise_for_status()
|
||||
data = json_body(response)
|
||||
code = int(data.get("code", 0))
|
||||
@@ -253,6 +266,8 @@ class API(Vault):
|
||||
response = self.session.post(
|
||||
url=self.uri, headers={"Accept": "application/json"}, timeout=self.timeout, allow_redirects=False
|
||||
)
|
||||
if response.status_code == 429:
|
||||
raise Exceptions.TooManyRequests()
|
||||
response.raise_for_status()
|
||||
data = json_body(response)
|
||||
|
||||
@@ -291,5 +306,5 @@ class Exceptions:
|
||||
class KeyIdInvalid(Refused):
|
||||
"""The Key ID is invalid."""
|
||||
|
||||
class ContentKeyInvalid(Exception):
|
||||
class ContentKeyInvalid(Refused):
|
||||
"""The Content Key is invalid."""
|
||||
|
||||
@@ -54,7 +54,6 @@ class HTTP(Vault):
|
||||
|
||||
self.username = username
|
||||
self.api_mode = api_mode.lower()
|
||||
self.batch_insert = True
|
||||
self.current_title: str | None = None
|
||||
self.session = vault_session(timeout)
|
||||
self.api_session_id = None
|
||||
|
||||
@@ -17,6 +17,9 @@ from unshackle.core.vault import Vault, is_null_key
|
||||
class MySQL(Vault):
|
||||
"""Key Vault using a remotely-accessed mysql database connection."""
|
||||
|
||||
bulk_writes = True
|
||||
has_tables = True
|
||||
|
||||
def __init__(
|
||||
self, name: str, host: str, database: str, username: str, no_push: bool = False, **kwargs: Any
|
||||
) -> None:
|
||||
|
||||
@@ -13,6 +13,8 @@ class SQLite(Vault):
|
||||
|
||||
local = True
|
||||
stores_flags = True
|
||||
bulk_writes = True
|
||||
has_tables = True
|
||||
|
||||
def __init__(self, name: str, path: str | Path, no_push: bool = False) -> None:
|
||||
super().__init__(name, no_push)
|
||||
|
||||
Reference in New Issue
Block a user