forked from mtusi2026/mtusi2026lab5
RabbitMQ (quorum queue, publisher confirms, manual ack, DLX) + отдельный worker: staging в S3 + вложение/job/outbox одной транзакцией -> 202 queued; relay outbox, lease с heartbeat и fencing (worker_id, attempt), retry с backoff+jitter, failed-реестр, безопасный replay с audit; thumbnail/crop/WebP в изолированном процессе с лимитами. Тесты окон отказа (fault injection), трек 1 «Очередь под перегрузкой» с backpressure. Перенесено исправление замечания lab3 PR #99 (U+0000 в тексте). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
117 lines
4.9 KiB
Python
117 lines
4.9 KiB
Python
"""Настройки из переменных окружения. Секреты читаются только из файлов (*_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
|
||
broker_url: str
|
||
worker_concurrency: int
|
||
worker_prefetch: int
|
||
job_max_attempts: int
|
||
job_timeout: int
|
||
job_lease: int
|
||
retry_base_ms: int
|
||
retry_max_ms: int
|
||
staging_retention: int
|
||
max_pending_jobs: int
|
||
outbox_poll_ms: int
|
||
worker_memory_mb: int
|
||
worker_max_pixels: 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),
|
||
# lab5: брокер, worker, повторы, backpressure
|
||
broker_url=_required_secret('BROKER_URL'),
|
||
worker_concurrency=_int('WORKER_CONCURRENCY', 2, 1, 32),
|
||
worker_prefetch=_int('WORKER_PREFETCH', int(os.environ.get('WORKER_CONCURRENCY', 2)), 1, 256),
|
||
job_max_attempts=_int('JOB_MAX_ATTEMPTS', 5, 1, 50),
|
||
job_timeout=_int('JOB_TIMEOUT_SECONDS', 60, 5, 3600), # жёсткий лимит одной попытки
|
||
job_lease=_int('JOB_LEASE_SECONDS', 15, 3, 600), # аренда, продлевается heartbeat
|
||
retry_base_ms=_int('RETRY_BASE_MS', 1000, 10, 600000),
|
||
retry_max_ms=_int('RETRY_MAX_MS', 60000, 10, 3600000),
|
||
staging_retention=_int('STAGING_RETENTION_SECONDS', 86400, 60, 30 * 86400),
|
||
max_pending_jobs=_int('MAX_PENDING_JOBS', 200, 1, 1000000),
|
||
outbox_poll_ms=_int('OUTBOX_POLL_MS', 500, 50, 60000),
|
||
worker_memory_mb=_int('WORKER_TASK_MEMORY_MB', 512, 64, 8192),
|
||
worker_max_pixels=_int('MAX_IMAGE_PIXELS', 40_000_000, 1, 40_000_000),
|
||
)
|