forked from mtusi2026/mtusi2026lab2
60 lines
1.9 KiB
Python
60 lines
1.9 KiB
Python
"""Runtime configuration from environment variables / secret files.
|
|
|
|
Only logical interface names from ``.env.example`` are consumed; secret values
|
|
are read from files (``*_FILE``) so that no credential is baked into the image
|
|
or committed. The mapping is documented in REPORT.md.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
|
|
|
|
def _read_secret(file_key: str, value_key: str, default: str = "") -> str:
|
|
path = os.environ.get(file_key)
|
|
if path:
|
|
try:
|
|
return Path(path).read_text(encoding="utf-8").strip()
|
|
except OSError:
|
|
return default
|
|
return os.environ.get(value_key, default)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Settings:
|
|
app_host: str
|
|
app_port: int
|
|
app_env: str
|
|
session_ttl_seconds: int
|
|
session_store: str
|
|
database_url: str
|
|
cache_url: str
|
|
db_pool_min: int
|
|
db_pool_max: int
|
|
db_pool_timeout: float
|
|
db_statement_timeout_ms: int
|
|
|
|
@property
|
|
def cache_enabled(self) -> bool:
|
|
return bool(self.cache_url) and self.session_store in {"valkey", "redis"}
|
|
|
|
|
|
def load_settings() -> Settings:
|
|
return Settings(
|
|
app_host=os.environ.get("APP_HOST", "0.0.0.0"),
|
|
app_port=int(os.environ.get("APP_PORT", "8080")),
|
|
app_env=os.environ.get("APP_ENV", "lab"),
|
|
session_ttl_seconds=int(os.environ.get("SESSION_TTL_SECONDS", "3600")),
|
|
session_store=os.environ.get("SESSION_STORE", "postgres").lower(),
|
|
database_url=_read_secret("DATABASE_URL_FILE", "DATABASE_URL"),
|
|
cache_url=_read_secret("CACHE_URL_FILE", "CACHE_URL"),
|
|
db_pool_min=int(os.environ.get("DB_POOL_MIN", "1")),
|
|
db_pool_max=int(os.environ.get("DB_POOL_MAX", "10")),
|
|
db_pool_timeout=float(os.environ.get("DB_POOL_TIMEOUT", "5")),
|
|
db_statement_timeout_ms=int(os.environ.get("DB_STATEMENT_TIMEOUT_MS", "5000")),
|
|
)
|
|
|
|
|
|
settings = load_settings()
|