import tempfile import tomllib from dataclasses import dataclass from functools import cache from pathlib import Path from typing import Annotated from pydantic import ( DirectoryPath, Field, FilePath, PositiveFloat, PositiveInt, StringConstraints, ) from pydantic_settings import BaseSettings, SettingsConfigDict from app.domain.tool import Tool, Toolchain REPO_ROOT = Path(__file__).resolve().parents[1] @dataclass(frozen=True) class EngineLock: path: Path commit: str @cache def read_engine_lock(lock_file: Path = REPO_ROOT / "engines.lock") -> EngineLock: engine = tomllib.loads(lock_file.read_text(encoding="utf-8"))["engine"] return EngineLock(path=Path(engine["path"]), commit=engine["commit"]) class Settings(BaseSettings): model_config = SettingsConfigDict( env_prefix="AA_", env_file=REPO_ROOT / ".env", env_file_encoding="utf-8", extra="ignore" ) engine_root: DirectoryPath = Field(default_factory=lambda: read_engine_lock().path) tesseract_cmd: FilePath | None = None poppler_path: DirectoryPath | None = None jobs_root: Path = Path(tempfile.gettempdir()) / "audit-automation-jobs" job_ttl_seconds: PositiveFloat = 1800 sweep_interval_seconds: PositiveFloat = 30 max_jobs: PositiveInt = 200 max_upload_mb: PositiveInt = 50 max_request_mb: PositiveInt = 200 max_workers: PositiveInt = 2 tool_timeouts: dict[str, PositiveFloat] = Field(default_factory=dict) frontend_origin: Annotated[str, StringConstraints(pattern=r"^https?://[^/\s]+$")] = ( "http://localhost:3000" ) # The Firebase project whose sign-ins the jobs accept (a public id, not a secret). firebase_project_id: str = "audit-automation-2e276" # Off only for tests and local work: every request is then the one local user. auth_required: bool = True @property def max_file_bytes(self) -> int: return self.max_upload_mb * 1024 * 1024 @property def max_request_bytes(self) -> int: return self.max_request_mb * 1024 * 1024 def timeout_for(self, tool: Tool) -> float: return self.tool_timeouts.get(tool.id, tool.timeout_seconds) def toolchain(self) -> Toolchain: return Toolchain( engine_root=self.engine_root, tesseract_cmd=self.tesseract_cmd, poppler_path=self.poppler_path, )