forked from mtusi2026/mtusi2026lab7
229 lines
9.0 KiB
Python
229 lines
9.0 KiB
Python
import os
|
|
import socket
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
|
|
from app.vault import hydrate_secrets
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Settings:
|
|
host: str
|
|
port: int
|
|
env: str
|
|
app_role: str
|
|
instance_id: str
|
|
run_migrations: bool
|
|
session_ttl_seconds: int
|
|
idempotency_ttl_seconds: int
|
|
database_url: str
|
|
cache_url: str
|
|
s3_endpoint: str
|
|
s3_region: str
|
|
s3_bucket: str
|
|
s3_access_key_id: str
|
|
s3_secret_access_key: str
|
|
max_upload_bytes: int
|
|
max_image_pixels: int
|
|
attachment_gc_grace_seconds: int
|
|
migrations_dir: Path
|
|
db_pool_size: int
|
|
db_max_overflow: int
|
|
db_pool_timeout_seconds: float
|
|
db_connect_timeout_seconds: float
|
|
db_command_timeout_seconds: float
|
|
redis_socket_timeout_seconds: float
|
|
redis_max_connections: int
|
|
broker_url: str
|
|
worker_concurrency: int
|
|
job_max_attempts: int
|
|
job_timeout_seconds: int
|
|
job_lease_seconds: int
|
|
job_backoff_base_seconds: float
|
|
job_backoff_cap_seconds: float
|
|
pipeline_version: int
|
|
staging_retention_seconds: int
|
|
worker_image_memory_bytes: int
|
|
jpeg_quality: int
|
|
webp_quality: int
|
|
webp_method: int
|
|
faults_file: str
|
|
tls_ca_file: str
|
|
tls_cert_file: str
|
|
tls_key_file: str
|
|
mtls_enabled: bool
|
|
mtls_allowed_dns: str
|
|
internal_port: int
|
|
argon2_memory_kib: int
|
|
argon2_iterations: int
|
|
argon2_parallelism: int
|
|
login_rate_limit: int
|
|
login_rate_window_seconds: int
|
|
max_json_bytes: int
|
|
|
|
|
|
def _int(name: str, default: int, low: int, high: int) -> int:
|
|
raw = os.environ.get(name, str(default)).strip()
|
|
try:
|
|
value = int(raw)
|
|
except ValueError as exc:
|
|
raise SystemExit(f"{name} must be an integer") from exc
|
|
if not low <= value <= high:
|
|
raise SystemExit(f"{name} is out of range")
|
|
return value
|
|
|
|
|
|
def _float(name: str, default: float, low: float, high: float) -> float:
|
|
raw = os.environ.get(name, str(default)).strip()
|
|
try:
|
|
value = float(raw)
|
|
except ValueError as exc:
|
|
raise SystemExit(f"{name} must be a number") from exc
|
|
if not low <= value <= high:
|
|
raise SystemExit(f"{name} is out of range")
|
|
return value
|
|
|
|
|
|
def _secret(direct_name: str, file_name: str) -> str:
|
|
direct = os.environ.get(direct_name, "").strip()
|
|
if direct:
|
|
return direct
|
|
path = os.environ.get(file_name, "").strip()
|
|
if not path:
|
|
raise SystemExit(f"set {direct_name} or {file_name}")
|
|
try:
|
|
value = Path(path).read_text(encoding="utf-8").strip()
|
|
except OSError as exc:
|
|
raise SystemExit(f"cannot read {file_name}") from exc
|
|
if not value:
|
|
raise SystemExit(f"{file_name} is empty")
|
|
return value
|
|
|
|
|
|
def _migrations_dir() -> Path:
|
|
configured = os.environ.get("MIGRATIONS_DIR", "").strip()
|
|
if configured:
|
|
return Path(configured)
|
|
return Path(__file__).resolve().parents[2] / "migrations"
|
|
|
|
|
|
def _flag(name: str, default: bool) -> bool:
|
|
raw = os.environ.get(name, "1" if default else "0").strip().lower()
|
|
if raw in {"1", "true", "yes", "on"}:
|
|
return True
|
|
if raw in {"0", "false", "no", "off"}:
|
|
return False
|
|
raise SystemExit(f"{name} must be a boolean")
|
|
|
|
|
|
def _instance_id() -> str:
|
|
configured = os.environ.get("INSTANCE_ID", "").strip()
|
|
if configured:
|
|
return configured
|
|
host = os.environ.get("HOSTNAME", "").strip() or socket.gethostname()
|
|
if not host:
|
|
raise SystemExit("INSTANCE_ID is empty")
|
|
return host
|
|
|
|
|
|
def load_settings() -> Settings:
|
|
hydrate_secrets()
|
|
host = os.environ.get("APP_HOST", "0.0.0.0").strip() or "0.0.0.0"
|
|
env_name = os.environ.get("APP_ENV", "lab").strip() or "lab"
|
|
role = os.environ.get("APP_ROLE", "api").strip() or "api"
|
|
if role not in {"api", "migrate", "gc", "worker", "relay", "replay"}:
|
|
raise SystemExit("APP_ROLE must be api, migrate, gc, worker, relay or replay")
|
|
port = _int("APP_PORT", 8080, 1, 65535)
|
|
database_url = _secret("DATABASE_URL", "DATABASE_URL_FILE")
|
|
if not database_url.startswith("postgresql+asyncpg://"):
|
|
raise SystemExit("DATABASE_URL must start with postgresql+asyncpg://")
|
|
cache_url = ""
|
|
s3_endpoint = ""
|
|
s3_region = os.environ.get("S3_REGION", "us-east-1").strip() or "us-east-1"
|
|
s3_bucket = os.environ.get("S3_BUCKET", "messenger-attachments").strip() or "messenger-attachments"
|
|
s3_access_key_id = ""
|
|
s3_secret_access_key = ""
|
|
broker_url = ""
|
|
if role == "api":
|
|
cache_url = _secret("REDIS_URL", "CACHE_URL_FILE")
|
|
if not cache_url.startswith(("redis://", "rediss://")):
|
|
raise SystemExit("REDIS_URL must start with redis:// or rediss://")
|
|
if role in {"api", "gc", "worker"}:
|
|
s3_endpoint = os.environ.get("S3_ENDPOINT", "").strip()
|
|
if not s3_endpoint:
|
|
raise SystemExit("S3_ENDPOINT is required")
|
|
s3_access_key_id = _secret("S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE")
|
|
s3_secret_access_key = _secret("S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE")
|
|
if role in {"worker", "relay"}:
|
|
broker_url = _secret("BROKER_URL", "BROKER_URL_FILE")
|
|
if not broker_url.startswith(("amqp://", "amqps://")):
|
|
raise SystemExit("BROKER_URL must start with amqp:// or amqps://")
|
|
timeout_seconds = _int("JOB_TIMEOUT_SECONDS", 45, 1, 600)
|
|
lease_seconds = _int("JOB_LEASE_SECONDS", 90, 2, 3600)
|
|
mtls_enabled = _flag("MTLS_ENABLED", False)
|
|
internal_port = _int("INTERNAL_PORT", 8080, 1, 65535)
|
|
if mtls_enabled and internal_port == port:
|
|
raise SystemExit("INTERNAL_PORT must differ from APP_PORT when mTLS is enabled")
|
|
argon2_memory_kib = _int("ARGON2_MEMORY_KIB", 19456, 19456, 1048576)
|
|
argon2_iterations = _int("ARGON2_ITERATIONS", 2, 2, 16)
|
|
argon2_parallelism = _int("ARGON2_PARALLELISM", 1, 1, 8)
|
|
if lease_seconds <= timeout_seconds:
|
|
raise SystemExit("JOB_LEASE_SECONDS must be greater than JOB_TIMEOUT_SECONDS")
|
|
migrations = _migrations_dir()
|
|
if not migrations.is_dir():
|
|
raise SystemExit("migrations directory is missing")
|
|
return Settings(
|
|
host=host,
|
|
port=port,
|
|
env=env_name,
|
|
app_role=role,
|
|
instance_id=_instance_id(),
|
|
run_migrations=_flag("RUN_MIGRATIONS", True),
|
|
session_ttl_seconds=_int("SESSION_TTL_SECONDS", 3600, 1, 30 * 24 * 3600),
|
|
idempotency_ttl_seconds=_int("IDEMPOTENCY_TTL_SECONDS", 86400, 60, 30 * 24 * 3600),
|
|
database_url=database_url,
|
|
cache_url=cache_url,
|
|
s3_endpoint=s3_endpoint,
|
|
s3_region=s3_region,
|
|
s3_bucket=s3_bucket,
|
|
s3_access_key_id=s3_access_key_id,
|
|
s3_secret_access_key=s3_secret_access_key,
|
|
max_upload_bytes=_int("MAX_UPLOAD_BYTES", 10 * 1024 * 1024, 1024, 10 * 1024 * 1024),
|
|
max_image_pixels=_int("MAX_IMAGE_PIXELS", 40_000_000, 1, 40_000_000),
|
|
attachment_gc_grace_seconds=_int("ATTACHMENT_GC_GRACE_SECONDS", 900, 1, 24 * 3600),
|
|
migrations_dir=migrations,
|
|
db_pool_size=_int("DB_POOL_SIZE", 10, 1, 50),
|
|
db_max_overflow=_int("DB_MAX_OVERFLOW", 10, 0, 50),
|
|
db_pool_timeout_seconds=_float("DB_POOL_TIMEOUT_SECONDS", 5, 0.1, 30),
|
|
db_connect_timeout_seconds=_float("DB_CONNECT_TIMEOUT_SECONDS", 2, 0.1, 30),
|
|
db_command_timeout_seconds=_float("DB_COMMAND_TIMEOUT_SECONDS", 5, 0.1, 60),
|
|
redis_socket_timeout_seconds=_float("REDIS_SOCKET_TIMEOUT_SECONDS", 1, 0.1, 30),
|
|
redis_max_connections=_int("REDIS_MAX_CONNECTIONS", 50, 1, 200),
|
|
broker_url=broker_url,
|
|
worker_concurrency=_int("WORKER_CONCURRENCY", 2, 1, 8),
|
|
job_max_attempts=_int("JOB_MAX_ATTEMPTS", 5, 1, 20),
|
|
job_timeout_seconds=timeout_seconds,
|
|
job_lease_seconds=lease_seconds,
|
|
job_backoff_base_seconds=_float("JOB_BACKOFF_BASE_SECONDS", 0.4, 0.05, 60),
|
|
job_backoff_cap_seconds=_float("JOB_BACKOFF_CAP_SECONDS", 8, 0.1, 300),
|
|
pipeline_version=_int("PIPELINE_VERSION", 1, 1, 1000),
|
|
staging_retention_seconds=_int("STAGING_RETENTION_SECONDS", 86400, 30, 30 * 24 * 3600),
|
|
worker_image_memory_bytes=_int("WORKER_IMAGE_MEMORY_BYTES", 256 * 1024 * 1024, 8 * 1024 * 1024, 1024 * 1024 * 1024),
|
|
jpeg_quality=_int("JPEG_QUALITY", 85, 1, 95),
|
|
webp_quality=_int("WEBP_QUALITY", 80, 1, 100),
|
|
webp_method=_int("WEBP_METHOD", 6, 0, 6),
|
|
faults_file=os.environ.get("FAULTS_FILE", "").strip(),
|
|
tls_ca_file=os.environ.get("TLS_CA_FILE", "").strip(),
|
|
tls_cert_file=os.environ.get("TLS_CERT_FILE", "").strip(),
|
|
tls_key_file=os.environ.get("TLS_KEY_FILE", "").strip(),
|
|
mtls_enabled=mtls_enabled,
|
|
mtls_allowed_dns=os.environ.get("MTLS_ALLOWED_DNS", "lb.lab.internal").strip() or "lb.lab.internal",
|
|
internal_port=internal_port,
|
|
argon2_memory_kib=argon2_memory_kib,
|
|
argon2_iterations=argon2_iterations,
|
|
argon2_parallelism=argon2_parallelism,
|
|
login_rate_limit=_int("LOGIN_RATE_LIMIT", 10, 1, 1000),
|
|
login_rate_window_seconds=_int("LOGIN_RATE_WINDOW_SECONDS", 60, 1, 3600),
|
|
max_json_bytes=_int("MAX_JSON_BYTES", 65536, 1024, 1048576),
|
|
)
|