from functools import lru_cache from pydantic import Field from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict(env_prefix="MONITOR_", case_sensitive=False) host: str = "0.0.0.0" port: int = Field(8000, ge=1, le=65535) log_level: str = "INFO" default_timeout_seconds: float = Field(5.0, gt=0, le=30) max_timeout_seconds: float = Field(15.0, gt=0, le=60) max_redirects: int = Field(3, ge=0, le=10) allowed_ports: str = "80,443" @property def allowed_port_set(self) -> frozenset[int]: try: ports = frozenset(int(value.strip()) for value in self.allowed_ports.split(",")) except ValueError as exc: raise ValueError("MONITOR_ALLOWED_PORTS must be comma-separated integers") from exc if not ports or any(port < 1 or port > 65535 for port in ports): raise ValueError("MONITOR_ALLOWED_PORTS contains an invalid port") return ports @lru_cache def get_settings() -> Settings: settings = Settings() settings.allowed_port_set if settings.default_timeout_seconds > settings.max_timeout_seconds: raise ValueError("default timeout cannot exceed maximum timeout") return settings