Files
mtusi2026lab4/app/config.py
T
RainakandClaude Opus 5.5 2dca5c114b ЛР4 БВТ2304 Запорожец на 3
Вложения: приватный S3-bucket (RustFS 1.0.4) + метаданные в PostgreSQL, upload PNG/JPEG
с лимитами до декодирования, авторизованный download, attachment_ids в сообщениях,
идемпотентный bootstrap bucket, failover/persistence/S3-down тесты и REPORT.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 18:49:12 +03:00

90 lines
3.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Настройки из переменных окружения. Секреты читаются только из файлов (*_FILE)."""
import os
from dataclasses import dataclass
from pathlib import Path
def _int(name: str, default: int, low: int, high: int) -> int:
value = int(os.environ.get(name, default))
if not low <= value <= high:
raise ValueError(f'{name} must be in [{low}, {high}]')
return value
def _secret(name: str) -> str | None:
"""Значение из файла, путь к которому лежит в переменной NAME_FILE."""
path = os.environ.get(name + '_FILE')
if not path:
return None
return Path(path).read_text(encoding='utf-8').strip()
def _required_secret(name: str) -> str:
value = _secret(name)
if not value:
raise RuntimeError(f'{name}_FILE is not configured')
return value
@dataclass(frozen=True)
class Settings:
host: str
port: int
session_ttl: int
session_store: str
session_cache_ttl: int
database_url: str
cache_url: str | None
db_pool_max: int
db_statement_timeout_ms: int
db_acquire_timeout: float
cache_timeout: float
hash_workers: int
idempotency_ttl: int
drain_seconds: float
s3_endpoint: str
s3_region: str
s3_bucket: str
s3_access_key: str
s3_secret_key: str
s3_timeout: float
max_upload_bytes: int
max_image_pixels: int
image_workers: int
def load() -> Settings:
database_url = _secret('DATABASE_URL') or os.environ.get('DATABASE_URL')
if not database_url:
raise RuntimeError('DATABASE_URL_FILE is not configured')
store = os.environ.get('SESSION_STORE', 'postgres')
if store not in ('postgres', 'postgres+valkey'):
raise ValueError('SESSION_STORE must be postgres or postgres+valkey')
cache_url = _secret('CACHE_URL') if store == 'postgres+valkey' else None
return Settings(
host=os.environ.get('APP_HOST', '0.0.0.0'),
port=_int('APP_PORT', 8080, 1, 65535),
session_ttl=_int('SESSION_TTL_SECONDS', 3600, 1, 30 * 24 * 3600),
session_store=store,
session_cache_ttl=_int('SESSION_CACHE_TTL_SECONDS', 60, 1, 3600),
database_url=database_url,
cache_url=cache_url,
db_pool_max=_int('DB_POOL_MAX', 10, 1, 100),
db_statement_timeout_ms=_int('DB_STATEMENT_TIMEOUT_MS', 5000, 100, 600000),
db_acquire_timeout=_int('DB_ACQUIRE_TIMEOUT_MS', 2000, 100, 60000) / 1000,
cache_timeout=_int('CACHE_TIMEOUT_MS', 300, 10, 10000) / 1000,
hash_workers=_int('PASSWORD_HASH_WORKERS', 4, 1, 32),
idempotency_ttl=_int('IDEMPOTENCY_TTL_SECONDS', 86400, 86400, 30 * 24 * 3600), # контракт: не менее 24 ч
drain_seconds=_int('SHUTDOWN_DRAIN_MS', 3000, 0, 60000) / 1000,
s3_endpoint=os.environ.get('S3_ENDPOINT', 'http://s3:9000'),
s3_region=os.environ.get('S3_REGION', 'us-east-1'),
s3_bucket=os.environ.get('S3_BUCKET', 'messenger-attachments'),
s3_access_key=_required_secret('S3_ACCESS_KEY_ID'),
s3_secret_key=_required_secret('S3_SECRET_ACCESS_KEY'),
s3_timeout=_int('S3_TIMEOUT_MS', 5000, 100, 12000) / 1000, # < timeout server HAProxy (15 с)
# Контракт: не более 10 MiB и 40 млн пикселей; значения можно только уменьшить.
max_upload_bytes=_int('MAX_UPLOAD_BYTES', 10485760, 1, 10485760),
max_image_pixels=_int('MAX_IMAGE_PIXELS', 40_000_000, 1, 40_000_000),
image_workers=_int('IMAGE_CHECK_WORKERS', 2, 1, 16),
)