Files
2026-03-16 16:35:08 +09:00

219 lines
7.8 KiB
Python

"""
Structured application settings for StemEngine.
Provides a single validated settings object that consolidates all
runtime configuration currently scattered across ``config.py``.
Usage::
from backend.app_settings import settings
# Access any setting
print(settings.app_env)
print(settings.admin_token)
print(settings.cors_origins_resolved)
# Startup validation (called by main.py lifespan)
errors = settings.validate_startup()
for err in errors:
log.warning("Startup warning: %s", err)
Design notes
------------
* ``config.py`` remains the single place that reads env vars and creates
directory constants. ``AppSettings`` references those values so there is
no double-parsing and no risk of divergence.
* ``validate_startup()`` performs lightweight checks (path writability) that
are too heavy for module-import time but important to surface early.
* The singleton ``settings`` is created at module load using the current
process environment, so it reflects the same values as ``config.py``.
"""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import List, Optional
@dataclass(frozen=True)
class AppSettings:
"""Immutable snapshot of runtime application configuration.
All attributes are derived from environment variables at construction time.
Use the module-level ``settings`` singleton rather than constructing this
directly.
"""
# -----------------------------------------------------------------
# Operational / security
# -----------------------------------------------------------------
app_env: str
"""Deployment environment tag. One of ``development``, ``production``, etc."""
admin_token: str
"""Secret token for high-power endpoints. Empty string disables enforcement."""
cors_origins: List[str]
"""Explicit CORS allowed-origin list (comma-separated env var). Empty means
use env-based defaults (wildcard in dev, none in prod)."""
cors_origin_regex: str
"""Optional regex pattern for dynamic origin matching (e.g. Tailscale/LAN hosts)."""
# -----------------------------------------------------------------
# Filesystem paths
# -----------------------------------------------------------------
media_dir: Path
upload_dir: Path
jobs_dir: Path
projects_dir: Path
db_path: Path
lrc_sync_dir: Path
imports_dir: Path
settings_path: Path
# -----------------------------------------------------------------
# Upload limits
# -----------------------------------------------------------------
max_upload_bytes: int
"""Maximum upload file size in bytes."""
# -----------------------------------------------------------------
# Hardware
# -----------------------------------------------------------------
cpu_separation: bool
"""When True force CPU inference even if a GPU is present."""
# -----------------------------------------------------------------
# Properties
# -----------------------------------------------------------------
@property
def is_development(self) -> bool:
"""True when running in a local/development/test environment."""
return self.app_env in {"dev", "development", "local", "test"}
@property
def is_production(self) -> bool:
return not self.is_development
@property
def cors_origins_resolved(self) -> List[str]:
"""Compute the effective CORS allowed-origins list.
Priority:
1. ``CORS_ORIGINS`` env var (explicit list)
2. Wildcard (``["*"]``) when running in a dev/local environment
3. Empty list (deny all) for production when no list is configured
"""
if self.cors_origins:
return list(self.cors_origins)
if self.is_development:
return ["*"]
return []
@property
def cors_origin_regex_resolved(self) -> Optional[str]:
"""Return regex matcher string when configured, else ``None``."""
value = self.cors_origin_regex.strip()
return value or None
@property
def admin_token_required(self) -> bool:
"""True when ``ADMIN_TOKEN`` is configured and enforcement is active."""
return bool(self.admin_token)
# -----------------------------------------------------------------
# Startup validation
# -----------------------------------------------------------------
def validate_startup(self) -> List[str]:
"""Perform lightweight startup health checks.
Returns a list of human-readable warning/error strings. An empty list
means all checks passed. Callers should log warnings but should *not*
abort startup for most of these — the readiness endpoint exposes live
status for orchestration probes.
"""
issues: List[str] = []
# Check all required directories are writable
probe_dirs = [
("media_dir", self.media_dir),
("upload_dir", self.upload_dir),
("jobs_dir", self.jobs_dir),
("projects_dir", self.projects_dir),
("lrc_sync_dir", self.lrc_sync_dir),
]
for name, path in probe_dirs:
if not path.exists():
try:
path.mkdir(parents=True, exist_ok=True)
except OSError as exc:
issues.append(f"{name} cannot be created: {exc}")
continue
probe = path / ".startup_probe"
try:
probe.write_text("ok")
probe.unlink()
except OSError as exc:
issues.append(f"{name} ({path}) is not writable: {exc}")
# Warn when production runs without an admin token
if self.is_production and not self.admin_token_required:
issues.append(
"Running in production without ADMIN_TOKEN — "
"high-power endpoints are unprotected."
)
# Warn about wildcard CORS in production
if self.is_production and "*" in self.cors_origins_resolved:
issues.append(
"Wildcard CORS origin is active in a non-development environment."
)
# Warn about missing DB parent directory
if not self.db_path.parent.exists():
try:
self.db_path.parent.mkdir(parents=True, exist_ok=True)
except OSError as exc:
issues.append(f"DB directory cannot be created: {exc}")
return issues
# -----------------------------------------------------------------
# Factory
# -----------------------------------------------------------------
@classmethod
def from_env(cls) -> "AppSettings":
"""Create an ``AppSettings`` instance from the current environment."""
# Import config.py to avoid double env-var parsing; config.py already
# read all env vars and created the canonical path objects.
from . import config as cfg
return cls(
app_env=cfg.APP_ENV,
admin_token=cfg.ADMIN_TOKEN,
cors_origins=list(cfg.CORS_ORIGINS),
cors_origin_regex=cfg.CORS_ORIGIN_REGEX,
media_dir=cfg.MEDIA_DIR,
upload_dir=cfg.UPLOAD_DIR,
jobs_dir=cfg.JOBS_DIR,
projects_dir=cfg.PROJECTS_DIR,
db_path=cfg.DB_PATH,
lrc_sync_dir=cfg.LRC_SYNC_DIR,
imports_dir=cfg.IMPORTS_DIR,
settings_path=cfg.SETTINGS_PATH,
max_upload_bytes=cfg.MAX_UPLOAD_BYTES,
cpu_separation=cfg.CPU_SEPARATION,
)
# ---------------------------------------------------------------------------
# Module-level singleton — use this in application code.
# ---------------------------------------------------------------------------
settings: AppSettings = AppSettings.from_env()