import os from pathlib import Path from typing import Dict, Optional def read_setting( name: str, file_name: str, default: Optional[str] = None, default_file: Optional[str] = None, ) -> str: configured_secret_path = os.environ.get(file_name) secret_path = configured_secret_path or default_file if secret_path and (configured_secret_path or Path(secret_path).is_file()): try: return Path(secret_path).read_text(encoding="utf-8").strip() except OSError as exc: raise RuntimeError("Unable to read configured secret file") from exc value = os.environ.get(name, default) if value is None: if default_file: raise RuntimeError( "Required setting is missing: " + name + "; set " + file_name + " or mount the secret at " + default_file ) raise RuntimeError("Required application setting is missing: " + name) return value def database_connection() -> Dict[str, object]: return { "host": os.environ.get("DB_HOST", "localhost"), "port": int(os.environ.get("DB_PORT", "5432")), "dbname": os.environ.get("DB_NAME", "messenger"), "user": os.environ.get("DB_USER", "messenger"), "password": read_setting( "DB_PASSWORD", "DB_PASSWORD_FILE", default_file="/run/secrets/database_password", ), "connect_timeout": int(os.environ.get("DB_CONNECT_TIMEOUT_SECONDS", "3")), "options": "-c statement_timeout=5000 -c lock_timeout=3000", } def session_ttl_seconds() -> int: value = int(os.environ.get("SESSION_TTL_SECONDS", "3600")) if value < 1: raise RuntimeError("SESSION_TTL_SECONDS must be at least 1") return value