style: turn on ruff UP and B rules and fix every finding

This commit is contained in:
imSp4rky
2026-11-25 16:34:09 -07:00
parent 1a63076df2
commit d8058a3610
264 changed files with 2950 additions and 2966 deletions
+65 -68
View File
@@ -9,12 +9,13 @@ import tempfile
import threading
import uuid
from collections import deque
from collections.abc import Callable
from contextlib import suppress
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from enum import Enum
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, cast
from typing import TYPE_CHECKING, Any, cast
from unshackle.core.api.events import bus, publish_service_event
from unshackle.core.api.sanitize import sanitize_log
@@ -33,7 +34,7 @@ log = logging.getLogger("download_manager")
SENSITIVE_PARAM_KEYS = ("credential", "credentials", "password", "token", "api_key")
def redact_parameters(parameters: Dict[str, Any]) -> Dict[str, Any]:
def redact_parameters(parameters: dict[str, Any]) -> dict[str, Any]:
"""Return a copy of job parameters with secrets masked, safe to serialise."""
if not isinstance(parameters, dict):
return parameters
@@ -48,7 +49,7 @@ def redact_parameters(parameters: Dict[str, Any]) -> Dict[str, Any]:
return redacted
def credential_secrets(value: Any) -> List[str]:
def credential_secrets(value: Any) -> list[str]:
"""The secret parts of one credential in any form ``Credential.from_config`` loads."""
try:
credential = Credential.from_config(value)
@@ -63,11 +64,11 @@ def credential_secrets(value: Any) -> List[str]:
return [part for part in parts if len(part) >= 4] # short parts would blanket-replace and garble the text
def secret_values(parameters: Dict[str, Any], service: Optional[str] = None) -> List[str]:
def secret_values(parameters: dict[str, Any], service: str | None = None) -> list[str]:
"""Raw secret strings carried in job parameters and the credentials configured for ``service``, longest first."""
if not isinstance(parameters, dict):
return []
secrets: List[str] = []
secrets: list[str] = []
if service:
from unshackle.core.config import config
@@ -92,14 +93,14 @@ def secret_values(parameters: Dict[str, Any], service: Optional[str] = None) ->
return sorted(set(secrets), key=len, reverse=True) # longest first so substrings don't survive
def owner_id(api_key: Optional[str]) -> Optional[str]:
def owner_id(api_key: str | None) -> str | None:
"""A short digest of an API key for the on-disk history, so the key itself never lands in a file."""
if api_key is None:
return None
return hashlib.sha256(api_key.encode()).hexdigest()[:16]
def _redact_text(text: Optional[str], parameters: Dict[str, Any], service: Optional[str] = None) -> Optional[str]:
def _redact_text(text: str | None, parameters: dict[str, Any], service: str | None = None) -> str | None:
"""Mask proxy userinfo and any known parameter secrets that leaked into a free-text field
(error message / details / traceback / job worker stderr) before the API returns the field."""
return redact_text(text, secret_values(parameters, service))
@@ -127,54 +128,54 @@ class DownloadJob:
created_time: datetime
service: str
title_id: str
parameters: Dict[str, Any]
parameters: dict[str, Any]
started_time: Optional[datetime] = None
completed_time: Optional[datetime] = None
started_time: datetime | None = None
completed_time: datetime | None = None
progress: float = 0.0
output_files: List[str] = field(default_factory=list)
error_message: Optional[str] = None
error_details: Optional[str] = None
error_code: Optional[str] = None
error_traceback: Optional[str] = None
worker_stderr: Optional[str] = None
output_files: list[str] = field(default_factory=list)
error_message: str | None = None
error_details: str | None = None
error_code: str | None = None
error_traceback: str | None = None
worker_stderr: str | None = None
phase: Optional[str] = None
title: Optional[str] = None
current_title: Optional[str] = None
phase: str | None = None
title: str | None = None
current_title: str | None = None
completed_tracks: int = 0
total_tracks: int = 0
active_tracks: List[str] = field(default_factory=list)
track_progress: List[Dict[str, Any]] = field(default_factory=list)
active_tracks: list[str] = field(default_factory=list)
track_progress: list[dict[str, Any]] = field(default_factory=list)
segments_done: float = 0.0
segments_total: float = 0.0
speed: Optional[str] = None
speed: str | None = None
# Prompt a service raised through prompt_user() and waits on; answered by submit_input().
input_prompt: Optional[str] = None
input_prompt: str | None = None
# Message a service shows through show_notice() while it waits for an approval; needs no answer.
notice: Optional[str] = None
notice: str | None = None
# Subtitles skipped under skip_subtitle_errors (non-fatal). Each entry is a dl.SkippedSubtitle
# dict (id / language / title) so a client can report which weren't available.
skipped_subtitles: List[Dict[str, Any]] = field(default_factory=list)
skipped_subtitles: list[dict[str, Any]] = field(default_factory=list)
# Titles skipped because a requested track or language is missing; each a dl.SkippedTitle (title / reason).
skipped_titles: List[Dict[str, Any]] = field(default_factory=list)
skipped_titles: list[dict[str, Any]] = field(default_factory=list)
cancel_event: threading.Event = field(default_factory=threading.Event)
# Guards against writing the same job to the persistent history file twice.
history_recorded: bool = False
redacted: Optional[tuple[tuple, Dict[str, Optional[str]]]] = field(default=None, repr=False, compare=False)
redacted: tuple[tuple, dict[str, str | None]] | None = field(default=None, repr=False, compare=False)
# X-Secret-Key that created the job; scopes per-caller access, never serialized into to_dict().
owner_key: Optional[str] = None
owner_key: str | None = None
def to_dict(self, include_full_details: bool = False) -> Dict[str, Any]:
def to_dict(self, include_full_details: bool = False) -> dict[str, Any]:
"""Convert job to dictionary for JSON response."""
result: Dict[str, Any] = {
result: dict[str, Any] = {
"job_id": self.job_id,
"status": self.status.value,
"created_time": self.created_time.isoformat(),
@@ -207,7 +208,7 @@ class DownloadJob:
raw,
{
name: redact_path(_redact_text(text, self.parameters, self.service))
for name, text in zip(names, raw)
for name, text in zip(names, raw, strict=True)
},
)
result.update(
@@ -285,9 +286,7 @@ def record_job_history(job: DownloadJob) -> None:
log.warning(f"Could not write job history: {e}")
def read_job_history(
limit: int = 100, service: Optional[str] = None, owner: Optional[str] = None
) -> List[Dict[str, Any]]:
def read_job_history(limit: int = 100, service: str | None = None, owner: str | None = None) -> list[dict[str, Any]]:
"""Read persisted job history, newest first.
With ``owner`` (an :func:`owner_id`), only that owner's entries and ownerless legacy
@@ -301,7 +300,7 @@ def read_job_history(
except OSError as e:
log.warning(f"Could not read job history: {e}")
return []
entries: List[Dict[str, Any]] = []
entries: list[dict[str, Any]] = []
for line in lines:
line = line.strip()
if not line:
@@ -321,7 +320,7 @@ def read_job_history(
return entries[:limit] if limit and limit > 0 else entries
def delete_job_history(job_id: str, allowed: Optional[set] = None, owner: Optional[str] = None) -> bool:
def delete_job_history(job_id: str, allowed: set | None = None, owner: str | None = None) -> bool:
"""Remove a history entry by job_id (rewriting the file). Returns True if it removed one.
When you give `allowed`, this function treats an entry outside the caller's service
@@ -335,7 +334,7 @@ def delete_job_history(job_id: str, allowed: Optional[set] = None, owner: Option
except OSError as e:
log.warning(f"Could not read job history: {e}")
return False
kept: List[str] = []
kept: list[str] = []
deleted = False
for line in lines:
stripped = line.strip()
@@ -362,7 +361,7 @@ def delete_job_history(job_id: str, allowed: Optional[set] = None, owner: Option
return True
def client_sent_keys(params: Dict[str, Any]) -> set[str]:
def client_sent_keys(params: dict[str, Any]) -> set[str]:
"""Pop the server's ``client_keys`` stamp; a job without one counts every parameter as client-sent."""
return set(params.pop("client_keys", params))
@@ -371,9 +370,9 @@ def perform_download(
job_id: str,
service: str,
title_id: str,
params: Dict[str, Any],
progress_callback: Optional[Callable[[Dict[str, Any]], None]] = None,
) -> List[str]:
params: dict[str, Any],
progress_callback: Callable[[dict[str, Any]], None] | None = None,
) -> list[str]:
"""Do the synchronous download work for a job.
``params`` holds the API's form of the ``dl`` options; ``api_plan`` checks and casts them into the dl context,
@@ -455,14 +454,14 @@ def perform_download(
except RunStopped as exc:
log.debug("Stdout: %s", stdout_capture.getvalue())
raise APIError(APIErrorCode.DOWNLOAD_ERROR, f"Download failed: {exc.reason}")
raise APIError(APIErrorCode.DOWNLOAD_ERROR, f"Download failed: {exc.reason}") from exc
except SystemExit as exc:
if exc.code != 0:
log.error(f"Download exited with code {exc.code}")
log.debug("Stdout: %s", stdout_capture.getvalue())
log.debug("Stderr: %s", stderr_capture.getvalue())
raise APIError(APIErrorCode.DOWNLOAD_ERROR, f"Download failed with exit code {exc.code}")
raise APIError(APIErrorCode.DOWNLOAD_ERROR, f"Download failed with exit code {exc.code}") from exc
outcome = dl_instance.outcome()
except Exception as exc: # noqa: BLE001 - propagate to caller
@@ -493,25 +492,23 @@ class DownloadQueueManager:
self.max_concurrent_downloads = max_concurrent_downloads
self.job_retention_hours = job_retention_hours
self._jobs: Dict[str, DownloadJob] = {}
self._jobs: dict[str, DownloadJob] = {}
self._job_queue: asyncio.Queue = asyncio.Queue()
# asyncio.Queue has no reorder, so prioritized jobs go in a deque workers drain first.
self._priority_jobs: deque = deque()
self._promoted_ids: set = set() # their stale FIFO-queue copies get skipped via this set
self._active_downloads: Dict[str, asyncio.Task] = {}
self._download_processes: Dict[str, asyncio.subprocess.Process] = {}
self._job_temp_files: Dict[str, Dict[str, str]] = {}
self._active_downloads: dict[str, asyncio.Task] = {}
self._download_processes: dict[str, asyncio.subprocess.Process] = {}
self._job_temp_files: dict[str, dict[str, str]] = {}
self._workers_started = False
self._shutdown_event = asyncio.Event()
self._subscribers: Dict[str, List[asyncio.Queue]] = {}
self._subscribers: dict[str, list[asyncio.Queue]] = {}
log.info(
f"Initialized download queue manager: max_concurrent={max_concurrent_downloads}, retention_hours={job_retention_hours}"
)
def create_job(
self, service: str, title_id: str, owner_key: Optional[str] = None, **parameters: Any
) -> DownloadJob:
def create_job(self, service: str, title_id: str, owner_key: str | None = None, **parameters: Any) -> DownloadJob:
"""Make a new download job and add it to the queue."""
from unshackle.core.api.session_store import refuse_while_draining
@@ -534,11 +531,11 @@ class DownloadQueueManager:
bus.publish("job", {"event": "queued", **job.to_dict(include_full_details=True)})
return job
def get_job(self, job_id: str) -> Optional[DownloadJob]:
def get_job(self, job_id: str) -> DownloadJob | None:
"""Get job by ID."""
return self._jobs.get(job_id)
def list_jobs(self) -> List[DownloadJob]:
def list_jobs(self) -> list[DownloadJob]:
"""Get all jobs."""
return list(self._jobs.values())
@@ -585,7 +582,7 @@ class DownloadQueueManager:
schedule_pending_reload()
@staticmethod
def put(queue: asyncio.Queue, item: Optional[Dict[str, Any]]) -> None:
def put(queue: asyncio.Queue, item: dict[str, Any] | None) -> None:
"""Enqueue an item, discarding the oldest when a slow listener has filled the queue."""
try:
queue.put_nowait(item)
@@ -651,7 +648,7 @@ class DownloadQueueManager:
log.info(f"Removed job {sanitize_log(job_id)}")
return True
def clear_finished_jobs(self, owner_key: Optional[str] = None) -> int:
def clear_finished_jobs(self, owner_key: str | None = None) -> int:
"""Remove terminal (completed/failed/cancelled) jobs, returning the count removed.
With ``owner_key`` only that key's jobs and ownerless legacy jobs go.
@@ -739,7 +736,7 @@ class DownloadQueueManager:
for job_id, process in list(self._download_processes.items()):
try:
await asyncio.wait_for(process.wait(), timeout=5)
except asyncio.TimeoutError:
except TimeoutError:
log.warning(f"Worker process for job {job_id} did not exit, killing")
process.kill()
await process.wait()
@@ -806,7 +803,7 @@ class DownloadQueueManager:
if job.job_id in self._active_downloads:
del self._active_downloads[job.job_id]
except asyncio.TimeoutError:
except TimeoutError:
continue
except Exception as e:
log.error(f"Worker {worker_name} error: {e}")
@@ -839,7 +836,7 @@ class DownloadQueueManager:
log.error(f"Download failed for job {job.job_id}: {_redact_text(str(e), job.parameters, job.service)}")
raise
def worker_speed_limit(self) -> Optional[float]:
def worker_speed_limit(self) -> float | None:
"""Return one job worker's share of the locked global speed limit, or None when unset."""
requests_downloader = importlib.import_module("unshackle.core.downloaders.requests")
@@ -848,7 +845,7 @@ class DownloadQueueManager:
return None
return limiter.rate / max(1, self.max_concurrent_downloads)
async def run_download_async(self, job: DownloadJob) -> List[str]:
async def run_download_async(self, job: DownloadJob) -> list[str]:
"""Invoke a job worker subprocess to do the download."""
payload = {
@@ -894,8 +891,8 @@ class DownloadQueueManager:
stdout_bytes = b""
stderr_bytes = b""
last_progress_stat: Optional[tuple[int, int]] = None # (st_mtime_ns, st_size) of last parse
last_published: Optional[Dict[str, Any]] = None
last_progress_stat: tuple[int, int] | None = None # (st_mtime_ns, st_size) of last parse
last_published: dict[str, Any] | None = None
try:
while True:
@@ -906,7 +903,7 @@ class DownloadQueueManager:
stat = os.stat(progress_path)
stat_key = (stat.st_mtime_ns, stat.st_size)
if stat_key != last_progress_stat:
with open(progress_path, "r", encoding="utf-8") as handle:
with open(progress_path, encoding="utf-8") as handle:
progress_data = json.load(handle)
prompt_before = job.input_prompt
if progress_data.get("phase") and progress_data["phase"] != job.phase:
@@ -964,7 +961,7 @@ class DownloadQueueManager:
process.terminate()
try:
await asyncio.wait_for(communicate_task, timeout=5)
except asyncio.TimeoutError:
except TimeoutError:
log.warning(f"Worker process for job {job.job_id} did not terminate, killing")
process.kill()
await asyncio.wait_for(communicate_task, timeout=5)
@@ -987,10 +984,10 @@ class DownloadQueueManager:
else:
log.debug(f"Worker stderr for job {job.job_id}: {safe_stderr}")
result_data: Optional[Dict[str, Any]] = None
result_data: dict[str, Any] | None = None
for attempt in range(5):
try:
with open(result_path, "r", encoding="utf-8") as handle:
with open(result_path, encoding="utf-8") as handle:
result_data = json.load(handle)
except FileNotFoundError:
log.error(f"Result file missing for job {job.job_id}")
@@ -1049,7 +1046,7 @@ class DownloadQueueManager:
# Global instance
download_manager: Optional[DownloadQueueManager] = None
download_manager: DownloadQueueManager | None = None
def get_download_manager() -> DownloadQueueManager:
@@ -1077,10 +1074,10 @@ def busy_services() -> set[str]:
return busy
_reload_task: Optional[asyncio.Task[None]] = None
_reload_task: asyncio.Task[None] | None = None
def schedule_pending_reload(tag: Optional[str] = None) -> None:
def schedule_pending_reload(tag: str | None = None) -> None:
"""Swap in staged service updates whose last job or remote session has ended, off the event loop.
Runs on every job completion and remote session removal, because a busy service on a popular
+9 -8
View File
@@ -11,8 +11,9 @@ import sys
import threading
import time
import traceback
from collections.abc import Callable
from pathlib import Path
from typing import Any, Callable, Dict
from typing import Any
from uuid import uuid4
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT
@@ -25,7 +26,7 @@ from .download_manager import perform_download
log = logging.getLogger("download_worker")
def read_payload(path: Path) -> Dict[str, Any]:
def read_payload(path: Path) -> dict[str, Any]:
with path.open("r", encoding="utf-8") as handle:
return json.load(handle)
@@ -33,7 +34,7 @@ def read_payload(path: Path) -> Dict[str, Any]:
_replace_lock = threading.Lock()
def write_result(path: Path, payload: Dict[str, Any]) -> None:
def write_result(path: Path, payload: dict[str, Any]) -> None:
"""Write the payload with an atomic replace, because the parent polls this file during the write.
Each call gets its own temp name, so two threads writing this destination cannot replace away
@@ -60,7 +61,7 @@ def write_result(path: Path, payload: Dict[str, Any]) -> None:
raise
def relay_prompts(progress_callback: Callable[[Dict[str, Any]], None]) -> None:
def relay_prompts(progress_callback: Callable[[dict[str, Any]], None]) -> None:
"""Send each prompt_user() prompt to the parent as ``input_prompt`` progress, and read the answer from stdin.
The parent writes each answer as one JSON string per line, so an answer can hold a newline. The reader
@@ -97,7 +98,7 @@ def relay_prompts(progress_callback: Callable[[Dict[str, Any]], None]) -> None:
set_notice_handler(lambda message: progress_callback({"notice": message}))
def apply_payload_speed_limit(payload: Dict[str, Any]) -> None:
def apply_payload_speed_limit(payload: dict[str, Any]) -> None:
"""Lock this worker's share of the server speed limit so the job cannot clear it."""
limit = payload.get("speed_limit")
if not limit:
@@ -118,7 +119,7 @@ def main(argv: list[str]) -> int:
result_path = Path(argv[2])
progress_path = Path(argv[3]) if len(argv) > 3 else None
result: Dict[str, Any] = {}
result: dict[str, Any] = {}
exit_code = 0
try:
@@ -132,10 +133,10 @@ def main(argv: list[str]) -> int:
log.info(f"Worker starting job {job_id} ({service}:{title_id})")
# Merged so sparse keys (current_title, output_files) survive later writes.
progress_state: Dict[str, Any] = {}
progress_state: dict[str, Any] = {}
progress_lock = threading.Lock()
def progress_callback(progress_data: Dict[str, Any]) -> None:
def progress_callback(progress_data: dict[str, Any]) -> None:
"""Write progress updates to file for main process to read."""
if progress_path:
try:
+2 -2
View File
@@ -9,7 +9,7 @@ from __future__ import annotations
import secrets
import traceback
from datetime import datetime, timezone
from datetime import UTC, datetime
from typing import Any
from aiohttp import web
@@ -118,7 +118,7 @@ def build_error_response(
"error_code": error_code,
"message": f"{message} (ref {ref})",
"ref": ref,
"timestamp": datetime.now(timezone.utc).isoformat(),
"timestamp": datetime.now(UTC).isoformat(),
}
if details:
+11 -11
View File
@@ -6,18 +6,18 @@ import asyncio
import threading
from collections import deque
from contextlib import suppress
from typing import Any, Deque, Dict, List, Optional
from typing import Any
class EventBus:
"""Fan events out to every subscriber queue; drop when a subscriber falls behind."""
def __init__(self, history: int = 20000) -> None:
self._subs: List[asyncio.Queue] = []
self._subs: list[asyncio.Queue] = []
self.seq = 0
self.history: Deque[Dict[str, Any]] = deque(maxlen=history)
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._loop_thread: Optional[threading.Thread] = None
self.history: deque[dict[str, Any]] = deque(maxlen=history)
self._loop: asyncio.AbstractEventLoop | None = None
self._loop_thread: threading.Thread | None = None
self._lock = threading.RLock()
def subscribe(self) -> asyncio.Queue:
@@ -31,7 +31,7 @@ class EventBus:
with suppress(ValueError):
self._subs.remove(queue)
def since(self, seq: int) -> List[Dict[str, Any]]:
def since(self, seq: int) -> list[dict[str, Any]]:
"""Return the history after ``seq``.
``deque.copy()`` is one C call, so it is atomic against an append from another thread.
@@ -40,7 +40,7 @@ class EventBus:
"""
return [item for item in self.history.copy() if item["seq"] > seq]
def publish(self, event: str, data: Dict[str, Any]) -> None:
def publish(self, event: str, data: dict[str, Any]) -> None:
"""Record and fan out one event; safe to call from any thread.
The lock is re-entrant because a log call inside it publishes again. ``seq``
@@ -62,7 +62,7 @@ class EventBus:
self._loop.call_soon_threadsafe(_put_drop, queue, item)
def _put_drop(queue: asyncio.Queue, item: Dict[str, Any]) -> None:
def _put_drop(queue: asyncio.Queue, item: dict[str, Any]) -> None:
with suppress(asyncio.QueueFull):
queue.put_nowait(item)
@@ -70,18 +70,18 @@ def _put_drop(queue: asyncio.Queue, item: Dict[str, Any]) -> None:
bus = EventBus()
def publish_service_event(action: str, tags: List[str], errors: Optional[List[str]] = None) -> None:
def publish_service_event(action: str, tags: list[str], errors: list[str] | None = None) -> None:
"""Tell dashboard listeners that services were staged, applied, or failed to reload.
Lives here rather than in ``core.services`` so the service loader never imports the API layer.
"""
data: Dict[str, Any] = {"action": action, "tags": list(tags)}
data: dict[str, Any] = {"action": action, "tags": list(tags)}
if errors:
data["errors"] = list(errors)
bus.publish("service", data)
def publish_refresh_events(repos: List[Dict[str, Any]]) -> None:
def publish_refresh_events(repos: list[dict[str, Any]]) -> None:
"""Publish the ``service`` events one ``refresh_and_reload`` result implies.
A tag counts as applied only when it changed, was not deferred, and did not fail to
File diff suppressed because it is too large Load Diff
+10 -10
View File
@@ -12,7 +12,7 @@ import json
import threading
import uuid
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Any
from unshackle.core.remote_protocol import APIErrorCode, AuthStatus, coded
@@ -40,10 +40,10 @@ class Ask:
id: str
prompt: str
cdm_call: Optional[dict[str, Any]] = None
owner: Optional[str] = None # CHANNEL or POLL: the path that carried the ask, and the only one that answers it
response: Optional[str] = None
error: Optional[str] = None # the client could not answer, and says why
cdm_call: dict[str, Any] | None = None
owner: str | None = None # CHANNEL or POLL: the path that carried the ask, and the only one that answers it
response: str | None = None
error: str | None = None # the client could not answer, and says why
picked_up: threading.Event = field(default_factory=threading.Event)
answered: threading.Event = field(default_factory=threading.Event)
@@ -56,13 +56,13 @@ class InputBridge:
answers through the remote session channel or the prompt routes.
"""
channel: Optional[SessionChannel] = field(default=None, init=False, repr=False)
channel: SessionChannel | None = field(default=None, init=False, repr=False)
_asks: dict[str, Ask] = field(default_factory=dict, init=False, repr=False)
_status: AuthStatus = field(default=AuthStatus.AUTHENTICATING, init=False)
_cancelled: bool = field(default=False, init=False, repr=False)
_lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False)
def _open(self, prompt: str, cdm_call: Optional[dict[str, Any]] = None) -> Ask:
def _open(self, prompt: str, cdm_call: dict[str, Any] | None = None) -> Ask:
"""Register an ask and offer it to the attached channel; call it with the lock held."""
if self._cancelled:
raise RuntimeError("Session was cancelled")
@@ -147,7 +147,7 @@ class InputBridge:
"""
return [a for a in self._asks.values() if not a.answered.is_set() and a.owner != CHANNEL]
def get_pending_cdm_call(self) -> Optional[dict[str, Any]]:
def get_pending_cdm_call(self) -> dict[str, Any] | None:
"""Return the CDM call that service code waits on, if any, and mark it as fetched by a client."""
with self._lock:
ask = next((a for a in self._pollable() if a.cdm_call is not None), None)
@@ -157,7 +157,7 @@ class InputBridge:
ask.picked_up.set()
return ask.cdm_call
def get_pending_prompt(self) -> Optional[str]:
def get_pending_prompt(self) -> str | None:
"""Return the prompt of the first ask the prompt routes can serve, and keep that ask on them."""
with self._lock:
ask = next(iter(self._pollable()), None)
@@ -180,7 +180,7 @@ class InputBridge:
self._answer(ask, response)
return True
def answer(self, ask_id: str, response: str, error: Optional[str] = None) -> bool:
def answer(self, ask_id: str, response: str, error: str | None = None) -> bool:
"""Answer the ask with this id that the remote session channel carried; False when no such ask waits."""
with self._lock:
ask = self._asks.get(ask_id)
+7 -4
View File
@@ -7,7 +7,8 @@ a bitrate-weighted percentage, track counts, and the labels of the tracks downlo
from __future__ import annotations
import time
from typing import Any, Callable, Optional
from collections.abc import Callable
from typing import Any
from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.constants import AnyTrack
@@ -85,15 +86,17 @@ def build_job_progress_callables(
started = [False] * total
seg_done = [0.0] * total
seg_total = [0.0] * total
speeds: list[Optional[str]] = [None] * total
speeds: list[str | None] = [None] * total
last_emit = 0.0
last_shape: Optional[tuple[Any, ...]] = None
last_shape: tuple[Any, ...] | None = None
def emit() -> None:
nonlocal last_emit, last_shape
completed = sum(done)
# Downloads fill 0..DOWNLOAD_PROGRESS_CEILING; dl.result drives muxing up to 100.
progress = sum(w * f for w, f in zip(weights, fractions)) * DOWNLOAD_PROGRESS_CEILING / total_weight
progress = (
sum(w * f for w, f in zip(weights, fractions, strict=False)) * DOWNLOAD_PROGRESS_CEILING / total_weight
)
active = [labels[i] for i in range(total) if started[i] and not done[i]]
if active:
phase = "downloading " + ", ".join(active[:3])
+4 -4
View File
@@ -4,7 +4,7 @@ import logging
import re
import time
from collections.abc import Awaitable, Callable
from typing import Any, Optional
from typing import Any
import click
from aiohttp import web
@@ -184,7 +184,7 @@ def categorized(handler: Handler) -> Handler:
MAX_LOGIN_BODY_BYTES = 8 * 1024 * 1024
async def json_body(request: web.Request, max_size: Optional[int] = None) -> Any:
async def json_body(request: web.Request, max_size: int | None = None) -> Any:
"""The request's JSON object; raises INVALID_INPUT when it does not parse or is not an object.
``max_size`` replaces the body limit of the application for this read.
@@ -256,10 +256,10 @@ def heartbeat(handler: Handler) -> Handler:
UPDATE_CHECK_TTL = 300.0
UPDATE_CHECK: list[tuple[float, Optional[str]]] = []
UPDATE_CHECK: list[tuple[float, str | None]] = []
async def latest_release() -> Optional[str]:
async def latest_release() -> str | None:
"""The newer release the update check reports, kept for ``UPDATE_CHECK_TTL`` seconds: clients poll health."""
if UPDATE_CHECK and time.monotonic() - UPDATE_CHECK[0][0] < UPDATE_CHECK_TTL:
return UPDATE_CHECK[0][1]
+1 -2
View File
@@ -5,7 +5,6 @@ from __future__ import annotations
import json
import re
from pathlib import PureWindowsPath
from typing import Optional
MAX_CACHE_KEY_DEPTH = 8
MAX_SESSION_CACHE_KEYS = 256
@@ -20,7 +19,7 @@ def sanitize_log(value: object, keep_lines: bool = False) -> str:
return (CONTROL_CHARS_BUT_LF if keep_lines else CONTROL_CHARS).sub("", str(value))
def safe_cache_key(key: object) -> Optional[str]:
def safe_cache_key(key: object) -> str | None:
"""Return a relative posix path for a peer-supplied cache key, or None if it escapes its directory.
unshackle writes each cache key as ``<key>.json`` inside a fixed directory, and a key may
+7 -7
View File
@@ -10,7 +10,7 @@ from __future__ import annotations
import asyncio
import json
from typing import TYPE_CHECKING, Any, Optional, Union, cast
from typing import TYPE_CHECKING, Any, cast
from aiohttp import WSMsgType, web
@@ -32,7 +32,7 @@ if TYPE_CHECKING:
from unshackle.core.api.input_bridge import Ask
from unshackle.core.api.session_store import SessionEntry
Message = Union[ChannelPrompt, ChannelCdmCall, ChannelLog, ChannelStatus, ChannelDrain]
Message = ChannelPrompt | ChannelCdmCall | ChannelLog | ChannelStatus | ChannelDrain
GONE = object()
@@ -56,9 +56,9 @@ class SessionChannel:
"""
def __init__(self) -> None:
self.ws: Optional[web.WebSocketResponse] = None
self.queue: Optional[asyncio.Queue[Any]] = None
self.loop: Optional[asyncio.AbstractEventLoop] = None
self.ws: web.WebSocketResponse | None = None
self.queue: asyncio.Queue[Any] | None = None
self.loop: asyncio.AbstractEventLoop | None = None
self.ended = False
@property
@@ -134,7 +134,7 @@ class SessionChannel:
while True:
try:
message = await asyncio.wait_for(queue.get(), HEARTBEAT)
except asyncio.TimeoutError:
except TimeoutError:
session.touch()
continue
if message is GONE:
@@ -150,7 +150,7 @@ def log_message(record: LogRecord) -> ChannelLog:
return cast(ChannelLog, {"type": ChannelMessage.LOG, **record})
def ask_message(ask: Ask) -> Union[ChannelPrompt, ChannelCdmCall]:
def ask_message(ask: Ask) -> ChannelPrompt | ChannelCdmCall:
if ask.cdm_call is not None:
return ChannelCdmCall(type=ChannelMessage.CDM_CALL, id=ask.id, call=ask.cdm_call)
return ChannelPrompt(type=ChannelMessage.PROMPT, id=ask.id, prompt=ask.prompt)
+9 -8
View File
@@ -18,7 +18,8 @@ import threading
import time
import traceback
from collections import deque
from typing import Any, Callable, Deque, List, MutableMapping, Optional, Tuple
from collections.abc import Callable, MutableMapping
from typing import Any
from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.remote_protocol import LogRecord
@@ -34,10 +35,10 @@ class SessionLogBuffer:
"""
def __init__(self, maxlen: int = MAX_RECORDS) -> None:
self._records: Deque[LogRecord] = deque(maxlen=maxlen)
self._records: deque[LogRecord] = deque(maxlen=maxlen)
self._seq = 0
self._lock = threading.Lock()
self.listener: Optional[Callable[[LogRecord], None]] = None
self.listener: Callable[[LogRecord], None] | None = None
def append(self, level: int, message: str) -> None:
with self._lock:
@@ -52,7 +53,7 @@ class SessionLogBuffer:
if self.listener is not None:
self.listener(record)
def since(self, seq: int) -> List[LogRecord]:
def since(self, seq: int) -> list[LogRecord]:
"""Records with a sequence number greater than *seq*, oldest first."""
with self._lock:
return [r.copy() for r in self._records if r["seq"] > seq]
@@ -63,7 +64,7 @@ class SessionLogBuffer:
return self._seq
def format_message(msg: Any, args: Tuple[Any, ...]) -> str:
def format_message(msg: Any, args: tuple[Any, ...]) -> str:
"""Render a logging call's message the way ``LogRecord`` would."""
try:
return str(msg) % args if args else str(msg)
@@ -137,10 +138,10 @@ class capture_service_logs:
opened the window.
"""
def __init__(self, logger_name: str, buffer: Optional[SessionLogBuffer]) -> None:
def __init__(self, logger_name: str, buffer: SessionLogBuffer | None) -> None:
self._logger = logging.getLogger(logger_name)
self._handler: Optional[SessionLogHandler] = SessionLogHandler(buffer) if buffer else None
self._prev_level: Optional[int] = None
self._handler: SessionLogHandler | None = SessionLogHandler(buffer) if buffer else None
self._prev_level: int | None = None
def __enter__(self) -> None:
if self._handler:
+51 -50
View File
@@ -9,12 +9,13 @@ remote session.
from __future__ import annotations
import asyncio
import builtins
import logging
import uuid
from collections import Counter, deque
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, Deque, Dict, List, Optional
from datetime import UTC, datetime
from typing import Any
from unshackle.core.api.events import bus
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge
@@ -37,33 +38,33 @@ class SessionEntry:
service_tag: str
service_instance: Any
titles: Any = None # Titles_T from get_titles()
title_map: Dict[str, Any] = field(default_factory=dict)
current_title_id: Optional[str] = None # title the client last asked tracks for
tracks: Dict[str, Track] = field(default_factory=dict)
served_keys: Dict[str, tuple[str, str]] = field(
title_map: dict[str, Any] = field(default_factory=dict)
current_title_id: str | None = None # title the client last asked tracks for
tracks: dict[str, Track] = field(default_factory=dict)
served_keys: dict[str, tuple[str, str]] = field(
default_factory=dict
) # KID -> (KEY, serving vault name or "cdm") from server_cdm
tracks_by_title: Dict[str, Dict[str, Track]] = field(default_factory=dict)
chapters_by_title: Dict[str, List[Any]] = field(default_factory=dict)
tracks_by_title: dict[str, dict[str, Track]] = field(default_factory=dict)
chapters_by_title: dict[str, list[Any]] = field(default_factory=dict)
lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False, compare=False)
creator_ip: Optional[str] = None
owner_key: Optional[str] = None # X-Secret-Key that owns this session
cache_tag: Optional[str] = None
server_account: Optional[str] = None # profile name when the server lent its own account
creator_ip: str | None = None
owner_key: str | None = None # X-Secret-Key that owns this session
cache_tag: str | None = None
server_account: str | None = None # profile name when the server lent its own account
server_cdm: bool = False # False: the client's own device licenses this session
server_cdm_max_height: Optional[int] = None
server_cdm_max_height: int | None = None
server_vault: bool = False # a session the client's device licenses may still take keys from the server vault
server_device: bool = False # its service runs on the server's lent device, so keys come only from a vault
client_auth: bool = False # the login is the client's: it succeeded without a server account
user_config: Optional[Dict[str, Any]] = None # the serve.users entry the session was created with
input_bridge: Optional[InputBridge] = None
log_buffer: Optional[Any] = None # SessionLogBuffer mirroring the service's self.log
user_config: dict[str, Any] | None = None # the serve.users entry the session was created with
input_bridge: InputBridge | None = None
log_buffer: Any | None = None # SessionLogBuffer mirroring the service's self.log
channel: SessionChannel = field(default_factory=SessionChannel, repr=False, compare=False)
auth_error: Optional[str] = None
client: Dict[str, Any] = field(default_factory=dict) # version/argv/platform the client reported
actions: Deque[Dict[str, Any]] = field(default_factory=lambda: deque(maxlen=500))
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
last_accessed: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
auth_error: str | None = None
client: dict[str, Any] = field(default_factory=dict) # version/argv/platform the client reported
actions: deque[dict[str, Any]] = field(default_factory=lambda: deque(maxlen=500))
created_at: datetime = field(default_factory=lambda: datetime.now(UTC))
last_accessed: datetime = field(default_factory=lambda: datetime.now(UTC))
def __post_init__(self) -> None:
if self.input_bridge is not None:
@@ -78,13 +79,13 @@ class SessionEntry:
def add_tracks(self, title_id: str, tracks: Tracks) -> None:
"""Register the video, audio and subtitle tracks of a title, so the later routes find each one by its id."""
title_tracks: Dict[str, Track] = {str(t.id): t for t in [*tracks.videos, *tracks.audio, *tracks.subtitles]}
title_tracks: dict[str, Track] = {str(t.id): t for t in [*tracks.videos, *tracks.audio, *tracks.subtitles]}
self.tracks.update(title_tracks)
self.tracks_by_title[title_id] = title_tracks
def touch(self) -> None:
"""Update last_accessed timestamp."""
self.last_accessed = datetime.now(timezone.utc)
self.last_accessed = datetime.now(UTC)
@property
def in_use(self) -> bool:
@@ -101,11 +102,11 @@ class SessionEntry:
self.input_bridge.cancel()
self.channel.end()
def summary(self, include_actions: bool = True) -> Dict[str, Any]:
def summary(self, include_actions: bool = True) -> dict[str, Any]:
"""Dashboard view of the session: no service instance, no raw owner key."""
from unshackle.core.api.stats import mask_key
now = datetime.now(timezone.utc)
now = datetime.now(UTC)
title_id = (
self.current_title_id if self.current_title_id in self.title_map else next(iter(self.title_map), None)
)
@@ -144,7 +145,7 @@ def _schedule_pending_reload(service_tag: str) -> None:
def _publish(
action: str, entry: SessionEntry, reason: Optional[str] = None, action_entry: Optional[Dict[str, Any]] = None
action: str, entry: SessionEntry, reason: str | None = None, action_entry: dict[str, Any] | None = None
) -> None:
"""Tell dashboard listeners about a remote session; ``action_entry`` replaces the action log with that one action."""
data = {"action": action, **entry.summary(include_actions=action_entry is None)}
@@ -159,9 +160,9 @@ class SessionStore:
"""Thread-safe remote session store with TTL-based expiration."""
def __init__(self) -> None:
self._sessions: Dict[str, SessionEntry] = {}
self._sessions: dict[str, SessionEntry] = {}
self._lock = asyncio.Lock()
self._cleanup_task: Optional[asyncio.Task] = None
self._cleanup_task: asyncio.Task | None = None
self.draining = False
@property
@@ -170,7 +171,7 @@ class SessionStore:
return config.serve.get("session_ttl", 300)
@property
def max_sessions(self) -> Optional[int]:
def max_sessions(self) -> int | None:
"""Max concurrent sessions from config; None when the operator set no limit.
``max_sessions: null`` or ``0`` means unlimited, so a dashboard can tell "no cap" from
@@ -183,24 +184,24 @@ class SessionStore:
self,
service_tag: str,
service_instance: Any,
session_id: Optional[str] = None,
session_id: str | None = None,
*,
owner_key: Optional[str] = None,
creator_ip: Optional[str] = None,
server_account: Optional[str] = None,
cache_tag: Optional[str] = None,
user_config: Optional[Dict[str, Any]] = None,
owner_key: str | None = None,
creator_ip: str | None = None,
server_account: str | None = None,
cache_tag: str | None = None,
user_config: dict[str, Any] | None = None,
server_cdm: bool = False,
server_cdm_max_height: Optional[int] = None,
server_cdm_max_height: int | None = None,
server_vault: bool = False,
server_device: bool = False,
client_auth: bool = False,
client: Optional[Dict[str, Any]] = None,
input_bridge: Optional[InputBridge] = None,
log_buffer: Optional[Any] = None,
client: dict[str, Any] | None = None,
input_bridge: InputBridge | None = None,
log_buffer: Any | None = None,
) -> SessionEntry:
"""Make a new remote session, complete with every field the dashboard shows, and announce it."""
evicted_tag: Optional[str] = None
evicted_tag: str | None = None
async with self._lock:
max_sessions = self.max_sessions
if max_sessions is not None and len(self._sessions) >= max_sessions:
@@ -242,7 +243,7 @@ class SessionStore:
await self.remove_cache_dirs([evicted_tag])
return entry
async def get(self, session_id: str) -> Optional[SessionEntry]:
async def get(self, session_id: str) -> SessionEntry | None:
"""Get a remote session by ID, returns None if not found or expired."""
async with self._lock:
entry = self._sessions.get(session_id)
@@ -251,7 +252,7 @@ class SessionStore:
expired = False
if not entry.in_use and entry.auth_status != AuthStatus.AUTHENTICATING:
elapsed = (datetime.now(timezone.utc) - entry.last_accessed).total_seconds()
elapsed = (datetime.now(UTC) - entry.last_accessed).total_seconds()
if elapsed > self.ttl:
log.info(f"Session {sanitize_log(session_id)} expired (elapsed={elapsed:.0f}s, ttl={self.ttl}s)")
_publish("delete", self._sessions.pop(session_id), "expired")
@@ -264,7 +265,7 @@ class SessionStore:
await self.remove_cache_dirs([entry.cache_tag])
return None
def peek(self, session_id: str) -> Optional[SessionEntry]:
def peek(self, session_id: str) -> SessionEntry | None:
"""A remote session entry without touching it, for read-only observers.
``get`` refreshes ``last_accessed`` and expires stale entries, so an observer polling
@@ -288,7 +289,7 @@ class SessionStore:
async def cleanup_expired(self) -> int:
"""Remove all expired sessions. Returns count of removed sessions."""
async with self._lock:
now = datetime.now(timezone.utc)
now = datetime.now(UTC)
expired = []
for sid, entry in self._sessions.items():
if entry.in_use:
@@ -300,7 +301,7 @@ class SessionStore:
elif elapsed > self.ttl:
expired.append(sid)
ended_tags: set[str] = set()
cache_tags: list[Optional[str]] = []
cache_tags: list[str | None] = []
for sid in expired:
entry = self._sessions.pop(sid)
entry.end()
@@ -346,13 +347,13 @@ class SessionStore:
log.info(f"Cancelled bridges for {count} active session(s)")
@classmethod
async def remove_cache_dirs(cls, cache_tags: List[Optional[str]]) -> None:
async def remove_cache_dirs(cls, cache_tags: builtins.list[str | None]) -> None:
"""Remove the cache directories of ended remote sessions on a worker thread, outside the store lock."""
if any(cache_tags):
await asyncio.to_thread(lambda: [cls.cleanup_cache_dir(tag) for tag in cache_tags])
@staticmethod
def cleanup_cache_dir(cache_tag: Optional[str]) -> None:
def cleanup_cache_dir(cache_tag: str | None) -> None:
"""Remove the remote session cache directory and empty parents."""
if not cache_tag:
return
@@ -378,7 +379,7 @@ class SessionStore:
"""Tell dashboard listeners that a session's summary changed (titles or tracks loaded, auth settled)."""
_publish("update", entry)
def record_action(self, session_id: str, action: Dict[str, Any]) -> None:
def record_action(self, session_id: str, action: dict[str, Any]) -> None:
"""Append one request to the session's action log and tell dashboard listeners."""
entry = self._sessions.get(session_id)
if entry is None:
@@ -386,7 +387,7 @@ class SessionStore:
entry.actions.append(action)
_publish("update", entry, action_entry=action)
def list(self) -> List[SessionEntry]:
def list(self) -> builtins.list[SessionEntry]:
"""Snapshot of every live session."""
return list(self._sessions.values())
@@ -414,7 +415,7 @@ class SessionStore:
return len(self._sessions)
session_store: Optional[SessionStore] = None
session_store: SessionStore | None = None
def refuse_while_draining() -> None:
+33 -33
View File
@@ -9,8 +9,8 @@ import logging
import time
from collections import Counter, defaultdict, deque
from dataclasses import dataclass, field
from functools import lru_cache
from typing import Any, Deque, Dict, List, Optional, Tuple
from functools import cache
from typing import Any
from aiohttp import web
@@ -36,17 +36,17 @@ CDM_SESSION_ID_LIMIT = 64
CDM_DEVICE_LIMIT = 255
def _users() -> Dict[str, Any]:
def _users() -> dict[str, Any]:
users = (config.serve or {}).get("users")
return users if isinstance(users, dict) else {}
def _user_config(key: Optional[str]) -> Optional[Dict[str, Any]]:
def _user_config(key: str | None) -> dict[str, Any] | None:
user = _users().get(key) if key else None
return user if isinstance(user, dict) else None
def configured_key(key: Optional[str]) -> Optional[str]:
def configured_key(key: str | None) -> str | None:
"""``key`` when the config knows it (a user API key, the master secret or the dashboard API key), else None.
Open routes answer 200 to any header value, so attributing by the raw header would let an
@@ -62,7 +62,7 @@ def configured_key(key: Optional[str]) -> Optional[str]:
return key if key in known else None
def mask_key(key: Optional[str]) -> str:
def mask_key(key: str | None) -> str:
"""A display label for an API key: its configured username, else a truncated prefix."""
if not key:
return "anonymous"
@@ -72,7 +72,7 @@ def mask_key(key: Optional[str]) -> str:
return key[:4] + "…"
def key_id(key: Optional[str]) -> str:
def key_id(key: str | None) -> str:
"""A stable id for an API key. A hash prefix, so two unnamed keys never collide the way
``mask_key`` does, and the id carries no key material."""
if not key:
@@ -80,14 +80,14 @@ def key_id(key: Optional[str]) -> str:
return hashlib.sha256(key.encode()).hexdigest()[:12]
def key_tier(key: Optional[str]) -> Optional[str]:
def key_tier(key: str | None) -> str | None:
"""The tier name an API key references, when it names one that exists."""
user = _user_config(key)
tier = user.get("tier") if user else None
return str(tier) if tier else None
def key_rate_limit(key: Optional[str], serve: Optional[Dict[str, Any]] = None) -> Optional[int]:
def key_rate_limit(key: str | None, serve: dict[str, Any] | None = None) -> int | None:
"""Requests per hour allowed for a key: its own override, else its tier's, else unlimited.
``serve`` reads a config block that is not yet the live one, as the reload validator does.
@@ -107,7 +107,7 @@ def key_rate_limit(key: Optional[str], serve: Optional[Dict[str, Any]] = None) -
return limit if isinstance(limit, int) and limit > 0 else None
def rate_limit_error(where: str, value: Any) -> Optional[str]:
def rate_limit_error(where: str, value: Any) -> str | None:
"""Why *value* cannot serve as a rate limit, or None when it can. Unset is fine.
``key_rate_limit`` reads anything else as "no limit", so a mistyped value would silently
@@ -142,10 +142,10 @@ class ServerStats:
mode: str = "full"
requests_total: int = 0
requests_rejected: int = 0
keys: Dict[str, KeyStats] = field(default_factory=dict)
errors: Dict[str, Counter] = field(default_factory=lambda: defaultdict(Counter)) # service -> error_code -> count
keys: dict[str, KeyStats] = field(default_factory=dict)
errors: dict[str, Counter] = field(default_factory=lambda: defaultdict(Counter)) # service -> error_code -> count
def key_stats(self, key: Optional[str]) -> KeyStats:
def key_stats(self, key: str | None) -> KeyStats:
"""The counters for an API key, created on first sight."""
kid = key_id(key)
entry = self.keys.get(kid)
@@ -165,7 +165,7 @@ class ServerStats:
counter[entry.label] += entry.requests
return counter
def check_rate_limit(self, key: str) -> Optional[int]:
def check_rate_limit(self, key: str) -> int | None:
"""Seconds to wait when ``key`` is over its hourly limit, else None after counting the request.
A fixed window, not a sliding one: cheap, and an operator cap does not need the precision.
@@ -183,7 +183,7 @@ class ServerStats:
entry.window_used += 1
return None
def rate_limit_headers(self, key: str) -> Dict[str, str]:
def rate_limit_headers(self, key: str) -> dict[str, str]:
"""The ``X-RateLimit-*`` headers for ``key``'s current window; none for an API key with no limit."""
limit = key_rate_limit(key)
if limit is None:
@@ -195,7 +195,7 @@ class ServerStats:
"X-RateLimit-Reset": str(max(0, int(entry.window_start + RATE_LIMIT_WINDOW - time.time()))),
}
def to_dict(self) -> Dict[str, Any]:
def to_dict(self) -> dict[str, Any]:
return {
"version": __version__,
"code_hash": __code_hash__,
@@ -262,7 +262,7 @@ async def stats_middleware(request: web.Request, handler: Any) -> web.StreamResp
return response
async def _request_service(request: web.Request, session_id: Optional[str]) -> str:
async def _request_service(request: web.Request, session_id: str | None) -> str:
"""The installed service tag a request is for, from its remote session or its JSON body; ``-`` if none.
Only an installed tag counts, so a caller cannot grow ``stats.errors`` with made-up names.
@@ -282,10 +282,10 @@ class SeqRing:
"""Keep the last N records in memory, each with a ``seq`` one above the record before it."""
def __init__(self, maxlen: int) -> None:
self.records: Deque[Dict[str, Any]] = deque(maxlen=maxlen)
self.records: deque[dict[str, Any]] = deque(maxlen=maxlen)
self.seq = 0
def append(self, record: Dict[str, Any]) -> Dict[str, Any]:
def append(self, record: dict[str, Any]) -> dict[str, Any]:
"""Buffer one record; ``seq`` moves only after the append, as in ``EventBus``."""
seq = self.seq + 1
item = {"seq": seq, **record}
@@ -293,7 +293,7 @@ class SeqRing:
self.seq = seq
return item
def since(self, seq: int = 0) -> List[Dict[str, Any]]:
def since(self, seq: int = 0) -> list[dict[str, Any]]:
"""The records after ``seq``, oldest first, from a copy: ``append()`` can run on a worker thread."""
return [r for r in self.records.copy() if r["seq"] > seq]
@@ -317,7 +317,7 @@ class RingLogHandler(SeqRing, logging.Handler):
)
bus.publish("log", item)
def since(self, seq: int = 0, level: Optional[str] = None, logger: Optional[str] = None) -> List[Dict[str, Any]]:
def since(self, seq: int = 0, level: str | None = None, logger: str | None = None) -> list[dict[str, Any]]:
"""The records after ``seq`` at or above ``level``, from ``logger`` or one of its children."""
min_level = logging.getLevelName(level.upper()) if level else 0
if not isinstance(min_level, int):
@@ -335,8 +335,8 @@ ring = RingLogHandler()
cdm_calls = SeqRing(maxlen=5000)
@lru_cache(maxsize=None)
def _cdm_op(pattern: str) -> Optional[Tuple[str, str]]:
@cache
def _cdm_op(pattern: str) -> tuple[str, str] | None:
"""The ``(drm, op)`` of a route pattern, else None. Cached: the route table does not change."""
parts = pattern.strip("/").split("/")
drm = "widevine"
@@ -347,7 +347,7 @@ def _cdm_op(pattern: str) -> Optional[Tuple[str, str]]:
return drm, parts[1]
def _cdm_route(request: web.Request) -> Optional[Tuple[str, str]]:
def _cdm_route(request: web.Request) -> tuple[str, str] | None:
"""The ``(drm, op)`` of a CDM device route, else None.
Reads the matched route pattern, not the path, so a device name cannot pass for an operation
@@ -357,7 +357,7 @@ def _cdm_route(request: web.Request) -> Optional[Tuple[str, str]]:
return _cdm_op(resource.canonical) if resource is not None else None
def _hex_id(value: Any) -> Optional[str]:
def _hex_id(value: Any) -> str | None:
"""``value`` in lowercase when it is a hexadecimal string of a plausible length, else None."""
if not isinstance(value, str) or not value or len(value) > CDM_SESSION_ID_LIMIT:
return None
@@ -368,13 +368,13 @@ def _hex_id(value: Any) -> Optional[str]:
return value.lower()
def _key_fields(secret_key: Optional[str]) -> Dict[str, str]:
def _key_fields(secret_key: str | None) -> dict[str, str]:
"""The ``key_id`` and ``user`` of an API key: the ``id`` and ``label`` of its ``stats.keys`` entry."""
key = configured_key(secret_key)
return {"key_id": key_id(key), "user": mask_key(key)}
def _reply_json(response: Any) -> Dict[str, Any]:
def _reply_json(response: Any) -> dict[str, Any]:
"""The JSON object a handler answered, or ``{}``. ``compression_middleware`` runs inside the
CDM log middleware, so the body can arrive as gzip."""
try:
@@ -387,7 +387,7 @@ def _reply_json(response: Any) -> Dict[str, Any]:
return data if isinstance(data, dict) else {}
async def _consumed_json(request: web.Request) -> Dict[str, Any]:
async def _consumed_json(request: web.Request) -> dict[str, Any]:
"""The JSON object of the request body when the handler consumed it, else ``{}``.
``json_body`` keeps the object on the request, and aiohttp caches a direct read.
@@ -407,7 +407,7 @@ async def _consumed_json(request: web.Request) -> Dict[str, Any]:
return body if isinstance(body, dict) else {}
async def _cdm_record(request: web.Request, drm: str, op: str, outcome: Any) -> Dict[str, Any]:
async def _cdm_record(request: web.Request, drm: str, op: str, outcome: Any) -> dict[str, Any]:
"""The record of one call. ``outcome`` is the response, or the exception the handler raised.
An exception that is not an HTTP one gives its class name only: its text can hold the
@@ -416,7 +416,7 @@ async def _cdm_record(request: web.Request, drm: str, op: str, outcome: Any) ->
"""
from unshackle.core.api.handlers import request_secret_key
reply: Dict[str, Any] = {}
reply: dict[str, Any] = {}
if isinstance(outcome, web.StreamResponse):
status = outcome.status
if status >= 400 or op == "open":
@@ -446,7 +446,7 @@ async def _cdm_record(request: web.Request, drm: str, op: str, outcome: Any) ->
async def _record_cdm_call(
request: web.Request, route: Tuple[str, str], ts: float, started: float, outcome: Any
request: web.Request, route: tuple[str, str], ts: float, started: float, outcome: Any
) -> None:
"""Append one call to ``cdm_calls``. Logs a failure and does not raise it: it must never fail the CDM call."""
ms = round((time.perf_counter() - started) * 1000, 1)
@@ -475,7 +475,7 @@ async def cdm_log_middleware(request: web.Request, handler: Any) -> web.StreamRe
return response
def cdm_sessions(app: web.Application) -> List[Dict[str, Any]]:
def cdm_sessions(app: web.Application) -> list[dict[str, Any]]:
"""One row per live Cdm object: its open session count and the most it allows.
Both CDM libraries refuse an ``open`` only above ``MAX_NUM_OF_SESSIONS``, so the true limit
@@ -483,7 +483,7 @@ def cdm_sessions(app: web.Application) -> List[Dict[str, Any]]:
so those do not count as open.
"""
now = time.time()
rows: List[Dict[str, Any]] = []
rows: list[dict[str, Any]] = []
for drm, owner in (("widevine", app), ("playready", app.get("playready_app"))):
cdms = owner.get("cdms") if owner is not None else None
for (secret_key, device), cdm in (cdms or {}).items():