refactor(types): bring mypy to zero errors across unshackle

Fix the bugs the type errors exposed (RnetSession.send body, HLS proxy session, title cache fallback, mux progress) and gate mypy in pre-commit, warn-only in CI.
This commit is contained in:
imSp4rky
2026-10-30 20:51:21 -06:00
parent b493c9cd52
commit 7898ff6dd6
95 changed files with 810 additions and 589 deletions
+1 -1
View File
@@ -10,7 +10,7 @@ from unshackle.core.utils.redact import mask_proxy
class Basic(Proxy):
def __init__(self, **countries: Union[str, list[str]]):
def __init__(self, **countries: Union[str, list[str]]) -> None:
"""Basic proxy provider that uses the proxies given in the configuration file."""
self.countries = {k.lower(): v for k, v in countries.items()}
+3 -3
View File
@@ -91,7 +91,7 @@ class IPv4Adapter(HTTPAdapter):
class Resolver:
def __init__(self, url: str):
def __init__(self, url: str) -> None:
"""Resolve hostnames through one Control D DoH endpoint, caching answers for their TTL."""
self.url = url
self.session = requests.Session()
@@ -268,7 +268,7 @@ class Handler(socketserver.StreamRequestHandler):
class LocalProxy(socketserver.ThreadingTCPServer):
daemon_threads = True
def __init__(self, resolver: Resolver):
def __init__(self, resolver: Resolver) -> None:
"""An HTTP forward proxy on loopback that resolves every host through `resolver`."""
super().__init__(("127.0.0.1", 0), Handler)
self.resolver = resolver
@@ -331,7 +331,7 @@ class ControlD(Proxy):
resolver: Optional[str] = None,
profiles: Optional[list[dict]] = None,
max_profiles: int = 4,
):
) -> None:
"""
Proxy provider that uses Control D's transparent proxies.
+1 -1
View File
@@ -54,7 +54,7 @@ class ExpressVPN(Proxy):
cache_path: Optional[str] = None,
timeout: float = 10.0,
enable: bool = False,
):
) -> None:
"""
Proxy provider that uses ExpressVPN app proxy credentials.
+12 -12
View File
@@ -7,7 +7,7 @@ import subprocess
import tempfile
import threading
import time
from typing import Optional
from typing import Any, Optional
import requests
@@ -22,7 +22,7 @@ cleanup_lock = threading.Lock()
cleanup_registered = False
def cleanup_all_gluetun_containers():
def cleanup_all_gluetun_containers() -> None:
"""Cleanup all Gluetun containers on exit."""
# Get instances without holding the lock during cleanup
with cleanup_lock:
@@ -37,7 +37,7 @@ def cleanup_all_gluetun_containers():
pass
def register_cleanup():
def register_cleanup() -> None:
"""Add the cleanup handlers to atexit, one time only."""
global cleanup_registered
with cleanup_lock:
@@ -168,8 +168,8 @@ class Gluetun(Proxy):
auth_user: Optional[str] = None,
auth_password: Optional[str] = None,
verify_ip: bool = True,
**kwargs,
):
**kwargs: Any,
) -> None:
"""
Initialise the Gluetun proxy provider that can use more than one VPN provider.
@@ -202,7 +202,7 @@ class Gluetun(Proxy):
self.verify_ip = verify_ip
# Track active containers: {query_key: {"container_name": ..., "port": ..., ...}}
self.active_containers = {}
self.active_containers: dict[str, dict[str, Any]] = {}
self._port_lock = threading.Lock()
@@ -367,7 +367,7 @@ class Gluetun(Proxy):
del self.active_containers[query_key]
raise RuntimeError(f"Failed to create Gluetun container: {e}")
def cleanup(self):
def cleanup(self) -> None:
"""Stop and remove all managed Gluetun containers."""
container_count = len(self.active_containers)
@@ -438,7 +438,7 @@ class Gluetun(Proxy):
"org": container.get("ip_org"),
}
def validate_provider_config(self, provider_name: str, config: dict):
def validate_provider_config(self, provider_name: str, config: dict) -> None:
"""Validate a provider's configuration."""
vpn_type = config.get("vpn_type", "wireguard").lower()
credentials = config.get("credentials", {})
@@ -600,7 +600,7 @@ class Gluetun(Proxy):
country: Optional[str] = None,
city: Optional[str] = None,
hostname: Optional[str] = None,
):
) -> None:
"""
Make and start a Gluetun Docker container.
@@ -1073,7 +1073,7 @@ class Gluetun(Proxy):
except (subprocess.TimeoutExpired, FileNotFoundError):
return ""
def verify_container(self, query_key: str, max_retries: int = 3):
def verify_container(self, query_key: str, max_retries: int = 3) -> None:
"""
Make sure that the container's VPN IP and region are correct with an ipinfo.io lookup.
@@ -1271,7 +1271,7 @@ class Gluetun(Proxy):
except (subprocess.TimeoutExpired, FileNotFoundError):
return False
def remove_container(self, container_name: str):
def remove_container(self, container_name: str) -> None:
"""Stop and remove a Docker container."""
try:
if self.auto_cleanup:
@@ -1311,7 +1311,7 @@ class Gluetun(Proxy):
return f"http://{self.auth_user}:{self.auth_password}@localhost:{port}"
return f"http://localhost:{port}"
def __del__(self):
def __del__(self) -> None:
"""Cleanup containers on object destruction."""
if hasattr(self, "auto_cleanup") and self.auto_cleanup:
try:
+3 -3
View File
@@ -8,13 +8,13 @@ from unshackle.core.proxies.proxy import Proxy
class Hola(Proxy):
def __init__(self):
def __init__(self) -> None:
"""
Proxy provider that uses Hola's direct connections through the hola-proxy binary.
"""
self.binary = binaries.HolaProxy
if not self.binary:
if not binaries.HolaProxy:
raise EnvironmentError("hola-proxy executable not found but is required for the Hola proxy provider.")
self.binary = binaries.HolaProxy
self.countries = self.get_countries()
+2 -1
View File
@@ -11,7 +11,7 @@ from unshackle.core.utilities import COUNTRY_CODE_ALIASES
class NordVPN(Proxy):
def __init__(self, username: str, password: str, server_map: Optional[dict[str, Union[int, str]]] = None):
def __init__(self, username: str, password: str, server_map: Optional[dict[str, Union[int, str]]] = None) -> None:
"""
Proxy provider that uses NordVPN Service Credentials.
@@ -139,6 +139,7 @@ class NordVPN(Proxy):
[by_id is None or country["id"] == int(by_id), by_code is None or country["code"] == by_code.upper()]
):
return country
return None
@staticmethod
def get_all_servers(country_id: int) -> list[dict]:
+3 -2
View File
@@ -9,6 +9,7 @@ import sys
import time
from pathlib import Path
from typing import Optional
from urllib.parse import quote
import requests
@@ -62,7 +63,7 @@ class ProtonVPN(Proxy):
cache_path: Optional[str] = None,
timeout: float = 10.0,
enable: bool = False,
):
) -> None:
self.server_map = {str(k).lower().strip(): str(v).lower().strip() for k, v in (server_map or {}).items()}
self.timeout = timeout
self.enable = enable
@@ -109,7 +110,7 @@ class ProtonVPN(Proxy):
self.last_host = host = str(server.get("Domain") or "")
port = self.SECURE_CORE_PORT if int(server.get("Features") or 0) & self.SECURE_CORE_FEATURE else self.PROXY_PORT
# Username (a JWT) and Password are URL-safe, but quote so requests rebuilds Basic auth cleanly
user, pwd = (requests.utils.quote(c, safe="") for c in creds)
user, pwd = (quote(c, safe="") for c in creds)
return f"https://{user}:{pwd}@{host}:{port}"
def last_connection_display(self) -> Optional[str]:
+2 -2
View File
@@ -1,10 +1,10 @@
from abc import abstractmethod
from typing import Optional
from typing import Any, Optional
class Proxy:
@abstractmethod
def __init__(self, **kwargs):
def __init__(self, **kwargs: Any) -> None:
"""
The constructor initializes the Service using passed configuration data.
+1 -1
View File
@@ -83,7 +83,7 @@ def pinned(ip: str, hostname: str) -> int:
class SurfsharkVPN(Proxy):
def __init__(self, username: str, password: str, server_map: Optional[dict[str, str]] = None):
def __init__(self, username: str, password: str, server_map: Optional[dict[str, str]] = None) -> None:
"""
Proxy provider that uses SurfsharkVPN Service Credentials.
+1 -1
View File
@@ -10,7 +10,7 @@ from unshackle.core.proxies.proxy import Proxy
class WindscribeVPN(Proxy):
def __init__(self, username: str, password: str, server_map: Optional[dict[str, str]] = None):
def __init__(self, username: str, password: str, server_map: Optional[dict[str, str]] = None) -> None:
"""
Proxy provider that uses WindscribeVPN Service Credentials.