refactor: improve backend type safety and import organization

- Add TYPE_CHECKING guards for runtime-expensive imports (aiohttp, aiosqlite)
- Reorganize imports to follow PEP 8 conventions
- Convert TypeAlias to modern PEP 695 type syntax (where appropriate)
- Use Sequence/Mapping from collections.abc for type hints (covariant)
- Replace string literals with cast() for improved type inference
- Fix casting of Fail2BanResponse and TypedDict patterns
- Add IpLookupResult TypedDict for precise return type annotation
- Reformat overlong lines for readability (120 char limit)
- Add asyncio_mode and filterwarnings to pytest config
- Update test fixtures with improved type hints

This improves mypy type checking and makes type relationships explicit.
This commit is contained in:
2026-03-20 13:44:14 +01:00
parent 6515164d53
commit 250bb1a2e5
30 changed files with 431 additions and 644 deletions

View File

@@ -10,7 +10,7 @@ HTTP/FastAPI concerns.
from __future__ import annotations
from typing import cast, TypeAlias
from typing import cast
import structlog
@@ -21,7 +21,7 @@ from app.utils.fail2ban_client import Fail2BanClient, Fail2BanCommand, Fail2BanR
# Types
# ---------------------------------------------------------------------------
Fail2BanSettingValue: TypeAlias = str | int | bool
type Fail2BanSettingValue = str | int | bool
"""Allowed values for server settings commands."""
log: structlog.stdlib.BoundLogger = structlog.get_logger()
@@ -106,7 +106,7 @@ async def _safe_get(
"""
try:
response = await client.send(command)
return _ok(cast(Fail2BanResponse, response))
return _ok(cast("Fail2BanResponse", response))
except Exception:
return default
@@ -189,7 +189,7 @@ async def update_settings(socket_path: str, update: ServerSettingsUpdate) -> Non
async def _set(key: str, value: Fail2BanSettingValue) -> None:
try:
response = await client.send(["set", key, value])
_ok(cast(Fail2BanResponse, response))
_ok(cast("Fail2BanResponse", response))
except ValueError as exc:
raise ServerOperationError(f"Failed to set {key!r} = {value!r}: {exc}") from exc
@@ -224,7 +224,7 @@ async def flush_logs(socket_path: str) -> str:
client = Fail2BanClient(socket_path=socket_path, timeout=_SOCKET_TIMEOUT)
try:
response = await client.send(["flushlogs"])
result = _ok(cast(Fail2BanResponse, response))
result = _ok(cast("Fail2BanResponse", response))
log.info("logs_flushed", result=result)
return str(result)
except ValueError as exc: