Files
mtusi2026lab5/app/settings.py
T

75 lines
2.6 KiB
Python

"""Process configuration. Secrets come from the environment or *_FILE, never from the image."""
from __future__ import annotations
import os
from dataclasses import dataclass
from pathlib import Path
def _raw(name: str, default: str | None = None) -> str:
file_name = os.environ.get(name + "_FILE")
if file_name:
return Path(file_name).read_text(encoding="utf-8").strip()
if name in os.environ and os.environ[name] != "":
return os.environ[name]
if default is not None:
return default
raise RuntimeError("missing configuration " + name)
def _int(name: str, default: int) -> int:
return int(_raw(name, str(default)))
@dataclass(frozen=True)
class Settings:
instance_id: str
database_url: str
session_ttl_seconds: int
idempotency_ttl_seconds: int
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
broker_url: str
worker_concurrency: int
job_max_attempts: int
job_timeout_seconds: int
job_backoff_base_seconds: float
job_backoff_cap_seconds: float
staging_retention_seconds: int
operator_token: str
max_queued_jobs: int
host: str
port: int
def load() -> Settings:
return Settings(
instance_id=_raw("INSTANCE_ID", "api-local"),
database_url=_raw("DATABASE_URL"),
session_ttl_seconds=_int("SESSION_TTL_SECONDS", 3600),
idempotency_ttl_seconds=_int("IDEMPOTENCY_TTL_SECONDS", 86400),
s3_endpoint=_raw("S3_ENDPOINT", "http://minio:9000"),
s3_region=_raw("S3_REGION", "us-east-1"),
s3_bucket=_raw("S3_BUCKET", "messenger-attachments"),
s3_access_key_id=_raw("S3_ACCESS_KEY_ID"),
s3_secret_access_key=_raw("S3_SECRET_ACCESS_KEY"),
max_upload_bytes=_int("MAX_UPLOAD_BYTES", 10485760),
max_image_pixels=_int("MAX_IMAGE_PIXELS", 40000000),
broker_url=_raw("BROKER_URL"),
worker_concurrency=max(1, _int("WORKER_CONCURRENCY", 2)),
job_max_attempts=max(1, _int("JOB_MAX_ATTEMPTS", 5)),
job_timeout_seconds=max(1, _int("JOB_TIMEOUT_SECONDS", 60)),
job_backoff_base_seconds=float(_raw("JOB_BACKOFF_BASE_SECONDS", "0.5")),
job_backoff_cap_seconds=float(_raw("JOB_BACKOFF_CAP_SECONDS", "30")),
staging_retention_seconds=_int("STAGING_RETENTION_SECONDS", 86400),
operator_token=_raw("OPERATOR_TOKEN", ""),
max_queued_jobs=_int("MAX_QUEUED_JOBS", 500),
host=_raw("APP_HOST", "0.0.0.0"),
port=_int("APP_PORT", 8080),
)