284 lines
12 KiB
Python
284 lines
12 KiB
Python
"""Конфигурация процесса: значения приходят только из переменных окружения.
|
|
|
|
Секреты читаются либо напрямую (NAME), либо из файла (NAME_FILE) — второй
|
|
вариант используется стендом Swarm и Docker secrets. Значения секретов
|
|
никогда не попадают в текст ошибки.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import os
|
|
import re
|
|
import socket
|
|
import uuid
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
from typing import Mapping
|
|
|
|
DEFAULT_HOST = "0.0.0.0"
|
|
DEFAULT_PORT = 8080
|
|
DEFAULT_ENV = "lab"
|
|
DEFAULT_LOG_LEVEL = "info"
|
|
DEFAULT_GRACEFUL_SHUTDOWN_SECONDS = 5
|
|
DEFAULT_SHUTDOWN_DRAIN_SECONDS = 0.0
|
|
|
|
MAX_SHUTDOWN_BUDGET_SECONDS = 10
|
|
|
|
DEFAULT_SESSION_TTL_SECONDS = 3600
|
|
MIN_SESSION_TTL_SECONDS = 1
|
|
MAX_SESSION_TTL_SECONDS = 86400
|
|
|
|
DEFAULT_DB_POOL_SIZE = 5
|
|
MAX_DB_POOL_SIZE = 32
|
|
DEFAULT_DB_MAX_OVERFLOW = 5
|
|
MAX_DB_MAX_OVERFLOW = 32
|
|
DEFAULT_DB_POOL_TIMEOUT_SECONDS = 2.0
|
|
MAX_DB_POOL_TIMEOUT_SECONDS = 30.0
|
|
DEFAULT_DB_CONNECT_TIMEOUT_SECONDS = 1.5
|
|
MAX_DB_CONNECT_TIMEOUT_SECONDS = 30.0
|
|
DEFAULT_DB_COMMAND_TIMEOUT_SECONDS = 2.5
|
|
MAX_DB_COMMAND_TIMEOUT_SECONDS = 60.0
|
|
DEFAULT_DB_STATEMENT_TIMEOUT_MS = 2000
|
|
MAX_DB_STATEMENT_TIMEOUT_MS = 60000
|
|
|
|
DEFAULT_CACHE_TIMEOUT_SECONDS = 1.0
|
|
MAX_CACHE_TIMEOUT_SECONDS = 10.0
|
|
|
|
# Контракт лабораторной 4 фиксирует эти два предела; переменные окружения
|
|
# позволяют выбрать меньший предел для эксперимента, но не больший.
|
|
MAX_UPLOAD_BYTES_HARD_LIMIT = 10_485_760
|
|
MAX_IMAGE_PIXELS_HARD_LIMIT = 40_000_000
|
|
DEFAULT_MAX_UPLOAD_BYTES = MAX_UPLOAD_BYTES_HARD_LIMIT
|
|
DEFAULT_MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS_HARD_LIMIT
|
|
|
|
DEFAULT_S3_REGION = "us-east-1"
|
|
DEFAULT_S3_BUCKET = "messenger-attachments"
|
|
DEFAULT_S3_KEY_PREFIX = "attachments/"
|
|
DEFAULT_S3_CONNECT_TIMEOUT_SECONDS = 1.5
|
|
DEFAULT_S3_READ_TIMEOUT_SECONDS = 30.0
|
|
DEFAULT_S3_MAX_ATTEMPTS = 2
|
|
MAX_S3_READ_TIMEOUT_SECONDS = 120.0
|
|
DEFAULT_ATTACHMENT_ORPHAN_GRACE_SECONDS = 3600
|
|
MAX_ATTACHMENT_ORPHAN_GRACE_SECONDS = 7 * 24 * 3600
|
|
|
|
ENVIRONMENTS = ("lab", "dev", "prod")
|
|
LOG_LEVELS = ("debug", "info", "warning", "error")
|
|
|
|
SESSION_STORES = ("redis",)
|
|
DEFAULT_SESSION_STORE = "redis"
|
|
|
|
DATABASE_URL_SCHEME = "postgresql+asyncpg://"
|
|
CACHE_URL_SCHEMES = ("redis://", "rediss://", "unix://")
|
|
|
|
LOOPBACK_HOSTS = ("127.0.0.1", "localhost", "::1")
|
|
|
|
INSTANCE_ID_PATTERN = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
|
BUCKET_PATTERN = re.compile(r"^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$")
|
|
KEY_PREFIX_PATTERN = re.compile(r"^[A-Za-z0-9._/-]{0,128}$")
|
|
|
|
FAULT_MODES = ("none", "after_s3_put")
|
|
|
|
|
|
class ConfigError(RuntimeError):
|
|
"""Некорректная конфигурация. Текст не раскрывает значений переменных."""
|
|
|
|
|
|
def _choice(environ: Mapping[str, str], name: str, default: str, allowed: tuple[str, ...]) -> str:
|
|
value = environ.get(name, default).strip().lower()
|
|
if value not in allowed:
|
|
raise ConfigError(f"{name} must be one of: {', '.join(allowed)}")
|
|
return value
|
|
|
|
|
|
def _integer(environ: Mapping[str, str], name: str, default: int, minimum: int, maximum: int) -> int:
|
|
raw = environ.get(name, "").strip()
|
|
if not raw:
|
|
return default
|
|
try:
|
|
value = int(raw)
|
|
except ValueError:
|
|
raise ConfigError(f"{name} must be an integer") from None
|
|
if not minimum <= value <= maximum:
|
|
raise ConfigError(f"{name} must be within {minimum}..{maximum}")
|
|
return value
|
|
|
|
|
|
def _seconds(environ: Mapping[str, str], name: str, default: float, maximum: float) -> float:
|
|
raw = environ.get(name, "").strip()
|
|
if not raw:
|
|
return default
|
|
try:
|
|
value = float(raw)
|
|
except ValueError:
|
|
raise ConfigError(f"{name} must be a number of seconds") from None
|
|
if not 0.0 <= value <= maximum:
|
|
raise ConfigError(f"{name} must be within 0..{maximum}")
|
|
return value
|
|
|
|
|
|
def _secret(environ: Mapping[str, str], name: str) -> str | None:
|
|
direct = environ.get(name, "").strip()
|
|
path = environ.get(f"{name}_FILE", "").strip()
|
|
if direct and path:
|
|
raise ConfigError(f"{name} and {name}_FILE must not be set together")
|
|
if direct:
|
|
return direct
|
|
if not path:
|
|
return None
|
|
try:
|
|
value = Path(path).read_text(encoding="utf-8").strip()
|
|
except OSError:
|
|
raise ConfigError(f"{name}_FILE must point to a readable file") from None
|
|
if not value:
|
|
raise ConfigError(f"{name}_FILE must not be empty")
|
|
return value
|
|
|
|
|
|
def _required_secret(environ: Mapping[str, str], name: str) -> str:
|
|
value = _secret(environ, name)
|
|
if value is None:
|
|
raise ConfigError(f"{name} or {name}_FILE is required")
|
|
return value
|
|
|
|
|
|
def _checked_url(value: str, *, name: str, schemes: tuple[str, ...]) -> str:
|
|
if not value.startswith(schemes):
|
|
raise ConfigError(f"{name} must start with one of: {', '.join(schemes)}")
|
|
return value
|
|
|
|
|
|
def database_url_from_env(environ: Mapping[str, str] | None = None) -> str:
|
|
source: Mapping[str, str] = os.environ if environ is None else environ
|
|
return _checked_url(
|
|
_required_secret(source, "DATABASE_URL"),
|
|
name="DATABASE_URL",
|
|
schemes=(DATABASE_URL_SCHEME,),
|
|
)
|
|
|
|
|
|
def instance_id_from_env(environ: Mapping[str, str]) -> str:
|
|
raw = environ.get("INSTANCE_ID", "").strip() or socket.gethostname().strip()
|
|
if not raw:
|
|
raw = "api-" + uuid.uuid4().hex[:12]
|
|
if INSTANCE_ID_PATTERN.fullmatch(raw):
|
|
return raw
|
|
return "api-" + hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Config:
|
|
host: str
|
|
port: int
|
|
env: str
|
|
instance_id: str
|
|
log_level: str
|
|
graceful_shutdown_seconds: int
|
|
shutdown_drain_seconds: float
|
|
database_url: str
|
|
cache_url: str
|
|
session_store: str
|
|
session_ttl_seconds: int
|
|
db_pool_size: int
|
|
db_max_overflow: int
|
|
db_pool_timeout_seconds: float
|
|
db_connect_timeout_seconds: float
|
|
db_command_timeout_seconds: float
|
|
db_statement_timeout_ms: int
|
|
cache_timeout_seconds: float
|
|
cursor_secret: bytes | None
|
|
s3_endpoint: str
|
|
s3_region: str
|
|
s3_bucket: str
|
|
s3_key_prefix: str
|
|
s3_access_key_id: str
|
|
s3_secret_access_key: str
|
|
s3_connect_timeout_seconds: float
|
|
s3_read_timeout_seconds: float
|
|
s3_max_attempts: int
|
|
max_upload_bytes: int
|
|
max_image_pixels: int
|
|
attachment_orphan_grace_seconds: int
|
|
attachment_fault_mode: str
|
|
|
|
def __post_init__(self) -> None:
|
|
if self.shutdown_budget_seconds > MAX_SHUTDOWN_BUDGET_SECONDS:
|
|
raise ConfigError(
|
|
"GRACEFUL_SHUTDOWN_SECONDS + SHUTDOWN_DRAIN_SECONDS must be "
|
|
f"at most {MAX_SHUTDOWN_BUDGET_SECONDS} seconds"
|
|
)
|
|
if not self.s3_endpoint.startswith(("http://", "https://")):
|
|
raise ConfigError("S3_ENDPOINT must start with http:// or https://")
|
|
if not BUCKET_PATTERN.fullmatch(self.s3_bucket):
|
|
raise ConfigError("S3_BUCKET must be a valid S3 bucket name")
|
|
if not KEY_PREFIX_PATTERN.fullmatch(self.s3_key_prefix) or ".." in self.s3_key_prefix:
|
|
raise ConfigError("S3_KEY_PREFIX is not a safe object prefix")
|
|
|
|
@property
|
|
def shutdown_budget_seconds(self) -> float:
|
|
return self.graceful_shutdown_seconds + self.shutdown_drain_seconds
|
|
|
|
@property
|
|
def binds_to_loopback(self) -> bool:
|
|
return self.host in LOOPBACK_HOSTS
|
|
|
|
@classmethod
|
|
def from_env(cls, environ: Mapping[str, str] | None = None) -> "Config":
|
|
source: Mapping[str, str] = os.environ if environ is None else environ
|
|
env = _choice(source, "APP_ENV", DEFAULT_ENV, ENVIRONMENTS)
|
|
host = source.get("APP_HOST", DEFAULT_HOST).strip()
|
|
if not host:
|
|
raise ConfigError("APP_HOST must not be empty")
|
|
default_log_level = "debug" if env == "dev" else DEFAULT_LOG_LEVEL
|
|
database_url = database_url_from_env(source)
|
|
cache_url = _checked_url(
|
|
_required_secret(source, "CACHE_URL"),
|
|
name="CACHE_URL",
|
|
schemes=CACHE_URL_SCHEMES,
|
|
)
|
|
cursor_secret = _secret(source, "CURSOR_SECRET")
|
|
fault_mode = _choice(source, "ATTACHMENT_FAULT_MODE", "none", FAULT_MODES)
|
|
if env == "prod" and fault_mode != "none":
|
|
raise ConfigError("ATTACHMENT_FAULT_MODE must be none in prod")
|
|
key_prefix = source.get("S3_KEY_PREFIX", DEFAULT_S3_KEY_PREFIX).strip() or DEFAULT_S3_KEY_PREFIX
|
|
return cls(
|
|
host=host,
|
|
port=_integer(source, "APP_PORT", DEFAULT_PORT, 1, 65535),
|
|
env=env,
|
|
instance_id=instance_id_from_env(source),
|
|
log_level=_choice(source, "LOG_LEVEL", default_log_level, LOG_LEVELS),
|
|
graceful_shutdown_seconds=_integer(
|
|
source, "GRACEFUL_SHUTDOWN_SECONDS", DEFAULT_GRACEFUL_SHUTDOWN_SECONDS, 1, 10
|
|
),
|
|
shutdown_drain_seconds=_seconds(
|
|
source, "SHUTDOWN_DRAIN_SECONDS", DEFAULT_SHUTDOWN_DRAIN_SECONDS, 5.0
|
|
),
|
|
database_url=database_url,
|
|
cache_url=cache_url,
|
|
session_store=_choice(source, "SESSION_STORE", DEFAULT_SESSION_STORE, SESSION_STORES),
|
|
session_ttl_seconds=_integer(
|
|
source, "SESSION_TTL_SECONDS", DEFAULT_SESSION_TTL_SECONDS,
|
|
MIN_SESSION_TTL_SECONDS, MAX_SESSION_TTL_SECONDS,
|
|
),
|
|
db_pool_size=_integer(source, "DB_POOL_SIZE", DEFAULT_DB_POOL_SIZE, 1, MAX_DB_POOL_SIZE),
|
|
db_max_overflow=_integer(source, "DB_MAX_OVERFLOW", DEFAULT_DB_MAX_OVERFLOW, 0, MAX_DB_MAX_OVERFLOW),
|
|
db_pool_timeout_seconds=_seconds(source, "DB_POOL_TIMEOUT_SECONDS", DEFAULT_DB_POOL_TIMEOUT_SECONDS, MAX_DB_POOL_TIMEOUT_SECONDS),
|
|
db_connect_timeout_seconds=_seconds(source, "DB_CONNECT_TIMEOUT_SECONDS", DEFAULT_DB_CONNECT_TIMEOUT_SECONDS, MAX_DB_CONNECT_TIMEOUT_SECONDS),
|
|
db_command_timeout_seconds=_seconds(source, "DB_COMMAND_TIMEOUT_SECONDS", DEFAULT_DB_COMMAND_TIMEOUT_SECONDS, MAX_DB_COMMAND_TIMEOUT_SECONDS),
|
|
db_statement_timeout_ms=_integer(source, "DB_STATEMENT_TIMEOUT_MS", DEFAULT_DB_STATEMENT_TIMEOUT_MS, 1, MAX_DB_STATEMENT_TIMEOUT_MS),
|
|
cache_timeout_seconds=_seconds(source, "CACHE_TIMEOUT_SECONDS", DEFAULT_CACHE_TIMEOUT_SECONDS, MAX_CACHE_TIMEOUT_SECONDS),
|
|
cursor_secret=None if cursor_secret is None else cursor_secret.encode("utf-8"),
|
|
s3_endpoint=_checked_url(_required_secret(source, "S3_ENDPOINT"), name="S3_ENDPOINT", schemes=("http://", "https://")),
|
|
s3_region=source.get("S3_REGION", DEFAULT_S3_REGION).strip() or DEFAULT_S3_REGION,
|
|
s3_bucket=source.get("S3_BUCKET", DEFAULT_S3_BUCKET).strip() or DEFAULT_S3_BUCKET,
|
|
s3_key_prefix=key_prefix,
|
|
s3_access_key_id=_required_secret(source, "S3_ACCESS_KEY_ID"),
|
|
s3_secret_access_key=_required_secret(source, "S3_SECRET_ACCESS_KEY"),
|
|
s3_connect_timeout_seconds=_seconds(source, "S3_CONNECT_TIMEOUT_SECONDS", DEFAULT_S3_CONNECT_TIMEOUT_SECONDS, MAX_S3_READ_TIMEOUT_SECONDS),
|
|
s3_read_timeout_seconds=_seconds(source, "S3_READ_TIMEOUT_SECONDS", DEFAULT_S3_READ_TIMEOUT_SECONDS, MAX_S3_READ_TIMEOUT_SECONDS),
|
|
s3_max_attempts=_integer(source, "S3_MAX_ATTEMPTS", DEFAULT_S3_MAX_ATTEMPTS, 1, 5),
|
|
max_upload_bytes=_integer(source, "MAX_UPLOAD_BYTES", DEFAULT_MAX_UPLOAD_BYTES, 1, MAX_UPLOAD_BYTES_HARD_LIMIT),
|
|
max_image_pixels=_integer(source, "MAX_IMAGE_PIXELS", DEFAULT_MAX_IMAGE_PIXELS, 1, MAX_IMAGE_PIXELS_HARD_LIMIT),
|
|
attachment_orphan_grace_seconds=_integer(source, "ATTACHMENT_ORPHAN_GRACE_SECONDS", DEFAULT_ATTACHMENT_ORPHAN_GRACE_SECONDS, 0, MAX_ATTACHMENT_ORPHAN_GRACE_SECONDS),
|
|
attachment_fault_mode=fault_mode,
|
|
)
|