Files
mtusi2026lab3/src/config.py
T
Tmribob e084a29303 Реализация лабораторной 3: балансировка, отказ API-реплики, idempotency
- 2 API-реплики (api-1, api-2) с уникальным INSTANCE_ID
- Nginx load balancer с health-check и failover
- PostgreSQL источник истины, Valkey кэш сессий
- Idempotency-Key в заголовке, replay возвращает исходное сообщение
- X-Instance-Id в каждом ответе для идентификации реплики
- /version и /info эндпоинты
- Housekeeping-loop для очистки истёкших сессий и ключей
- stop-one.sh/cmd для failover-теста, restart.sh/cmd для persistence
- Исправлены импорты config/models/api/store/sessions
- Добавлены миграции 004 (idempotency), 005 (indexes), 006 (message_id)
- Отчёт с доказательствами критериев уровня 3 и 4
- Все тесты проходят: smoke, 26 student tests, failover, persistence, degradation
2026-10-30 21:14:37 +03:00

164 lines
5.7 KiB
Python

"""Runtime configuration: environment variables plus file-based secrets."""
from __future__ import annotations
import os
import re
import socket
from dataclasses import dataclass
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parents[1]
CONTRACT_PATH = PROJECT_ROOT / "contracts" / "openapi.json"
MIGRATIONS_DIR = Path(__file__).resolve().parent / "migrations"
DEFAULT_PAGE_SIZE = 50
MAX_PAGE_SIZE = 100
MAX_JSON_BYTES = 1_048_576
DEFAULT_SESSION_TTL_SECONDS = 3600
DEFAULT_CACHE_TTL_SECONDS = 300
# Idempotency-Key records are replayed for this long, then the key is reusable.
DEFAULT_IDEMPOTENCY_TTL_SECONDS = 86_400
SUPPORTED_SESSION_STORES = {"postgres"}
__version__ = "1.3.0"
# Key pattern of the contract: 1..128 ASCII characters of the allowed set.
IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
class ConfigurationError(Exception):
"""Startup configuration is unusable; the process must not serve traffic."""
@dataclass(frozen=True)
class Settings:
"""Everything the process needs, resolved once at startup."""
database_url: str
cache_url: str | None
session_store: str
session_ttl_seconds: int
cache_ttl_seconds: int
pool_min_size: int
pool_max_size: int
pool_timeout_seconds: float
connect_timeout_seconds: int
statement_timeout_ms: int
cache_timeout_seconds: float
idempotency_ttl_seconds: int
instance_id: str
app_env: str
version: str
@property
def cache_enabled(self) -> bool:
return self.cache_url is not None
def _secret(file_variable: str, plain_variable: str) -> str | None:
"""Read a secret from a mounted file, falling back to a plain variable."""
path_value = os.environ.get(file_variable, "").strip()
if path_value:
path = Path(path_value)
try:
value = path.read_text(encoding="utf-8").strip()
except OSError as exc:
raise ConfigurationError(
file_variable + " points to an unreadable file (" + type(exc).__name__ + ")"
) from None
if not value:
raise ConfigurationError(file_variable + " points to an empty file")
return value
plain = os.environ.get(plain_variable, "").strip()
return plain or None
def _integer(variable: str, default: int, minimum: int, maximum: int) -> int:
raw = os.environ.get(variable, "").strip()
if not raw:
return default
try:
value = int(raw)
except ValueError:
raise ConfigurationError(variable + " must be an integer") from None
if not minimum <= value <= maximum:
raise ConfigurationError(
variable + " must be between " + str(minimum) + " and " + str(maximum)
)
return value
def _number(variable: str, default: float, minimum: float, maximum: float) -> float:
raw = os.environ.get(variable, "").strip()
if not raw:
return default
try:
value = float(raw)
except ValueError:
raise ConfigurationError(variable + " must be a number") from None
if not minimum <= value <= maximum:
raise ConfigurationError(
variable + " must be between " + str(minimum) + " and " + str(maximum)
)
return value
def load_settings() -> Settings:
"""Resolve settings once; a bad configuration fails fast before serving."""
database_url = _secret("DATABASE_URL_FILE", "DATABASE_URL")
if database_url is None:
raise ConfigurationError("DATABASE_URL_FILE or DATABASE_URL is required")
cache_url = _secret("CACHE_URL_FILE", "CACHE_URL")
session_store = os.environ.get("SESSION_STORE", "postgres").strip().lower()
if session_store not in SUPPORTED_SESSION_STORES:
raise ConfigurationError(
"SESSION_STORE="
+ session_store
+ " is not implemented: sessions are stored in PostgreSQL "
"(the durable source of truth) and cached in Valkey. Use SESSION_STORE=postgres."
)
pool_min = _integer("DB_POOL_MIN", 1, 0, 100)
pool_max = _integer("DB_POOL_MAX", 10, 1, 200)
if pool_min > pool_max:
raise ConfigurationError("DB_POOL_MIN must not exceed DB_POOL_MAX")
return Settings(
database_url=database_url,
cache_url=cache_url,
session_store=session_store,
session_ttl_seconds=_integer(
"SESSION_TTL_SECONDS", DEFAULT_SESSION_TTL_SECONDS, 1, 2_592_000
),
cache_ttl_seconds=_integer(
"CACHE_TTL_SECONDS", DEFAULT_CACHE_TTL_SECONDS, 1, 86_400
),
pool_min_size=pool_min,
pool_max_size=pool_max,
pool_timeout_seconds=_number("DB_POOL_TIMEOUT_SECONDS", 2.0, 0.1, 60.0),
connect_timeout_seconds=_integer("DB_CONNECT_TIMEOUT_SECONDS", 2, 1, 60),
statement_timeout_ms=_integer("DB_STATEMENT_TIMEOUT_MS", 5000, 100, 120_000),
cache_timeout_seconds=_number("CACHE_TIMEOUT_SECONDS", 0.5, 0.05, 10.0),
idempotency_ttl_seconds=_integer(
"IDEMPOTENCY_TTL_SECONDS",
DEFAULT_IDEMPOTENCY_TTL_SECONDS,
60,
604_800,
),
# Stable for the life of the process. Inside a container this is the
# short container id, which is what scripts/stop-one.sh maps back to a
# single replica; outside Docker it stays a readable hostname.
instance_id=os.environ.get("INSTANCE_ID", "").strip() or socket.gethostname(),
app_env=os.environ.get("APP_ENV", "lab").strip() or "lab",
version=__version__,
)
def load_address() -> tuple[str, int]:
"""Read and validate the HTTP listen address from the environment."""
host = os.environ.get("APP_HOST", "0.0.0.0").strip()
if not host:
raise SystemExit("APP_HOST must not be empty")
port = _integer("APP_PORT", 8080, 1, 65535)
return host, port