The three performance settings the review flagged, one of which turned out not to exist in any meaningful sense. db_pool_size 5 -> 15, and max_overflow named explicitly. FastAPI runs this app's def handlers in anyio's threadpool - 40 threads by default - and each holds a session for the whole request, so a pool of 5 put the sixth concurrent request on pool_timeout before it reached the database. The real ceiling was never 5 either: it was 15, because SQLAlchemy quietly adds max_overflow=10. Leaving that invisible is the actual hazard, since an operator raising pool_size has no way to see what they are raising it from, so both halves are settings now and the arithmetic is written down next to PostgreSQL's max_connections in the env example. pool_timeout is pinned at 30s rather than inherited: it has to stay finite, or a pool leak presents as requests hanging forever instead of an error that names the pool. worker_poll_interval_s 2.0 -> 5.0. This only ever delays noticing a job enqueued into an empty queue - the loop drains a queue that has work back to back without sleeping - so it costs latency nobody can perceive on a bird camera and halves the idle queries, 30 a minute down to 12. worker_batch_size is removed rather than raised to 5. Nothing read it. It has sat in Settings since Phase 1 looking like it tuned something while the worker claimed one job at a time regardless, which is worse than no setting at all. Implementing it would also be a mistake here: claiming five jobs marks all five 'running', so dying after the first leaves four locked by a process that no longer exists and invisible until requeue_stale reaches them up to fifteen minutes later. Single claims keep exactly one job at risk, and batching would only have saved claim round-trips on a loopback connection that no thumbnail decode would notice. The reasoning is at the claim loop, where the next person will ask. The test asserts against a pool an engine really built, because comparing Settings to itself would pass no matter what db.py does. It has to use values that differ from SQLAlchemy's own defaults - hence 17 and 7 - which is the point mutation testing earned: with max_overflow unwired the first version of this test still passed, because the default it fell back to was 10 and the setting also said 10. Tests: 193 -> 194. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
131 lines
5.5 KiB
Python
131 lines
5.5 KiB
Python
"""Configuration.
|
|
|
|
Every value comes from the environment (TODO.md Phase 1.2). Nothing is read
|
|
from a committed config file, and no path, host or secret is baked into code.
|
|
systemd supplies these via ``EnvironmentFile=/etc/poorbird/poorbird.env``; for
|
|
local development a ``.env`` in the working directory is picked up as well.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from functools import lru_cache
|
|
from pathlib import Path
|
|
from typing import Literal
|
|
|
|
from pydantic import SecretStr, field_validator
|
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
|
|
# Values that mean "nobody filled this in". The .example files ship with these,
|
|
# and a copied-but-unedited example must not boot as if it were configured.
|
|
_PLACEHOLDERS = frozenset({"change_me", "changeme", "todo", "xxx", "secret"})
|
|
|
|
|
|
class Settings(BaseSettings):
|
|
model_config = SettingsConfigDict(
|
|
env_prefix="POORBIRD_",
|
|
env_file=".env",
|
|
env_file_encoding="utf-8",
|
|
extra="ignore",
|
|
)
|
|
|
|
# --- database ---------------------------------------------------------
|
|
# Loopback TCP with scram-sha-256, deliberately not a Unix socket: a socket
|
|
# is the one genuinely container-hostile choice (TODO.md Phase 1.2).
|
|
#
|
|
# No default. A working URL in code means real credentials in code, and the
|
|
# module docstring above already promises none (REVIEW SEC-006). Absence is
|
|
# reported by ``poorbird check`` and raised with a readable message by db.py,
|
|
# rather than silently connecting to whatever happens to be on localhost.
|
|
database_url: str = ""
|
|
# FastAPI runs this app's ``def`` handlers in anyio's threadpool (40 threads
|
|
# by default), and each one holds a session for the whole request. A pool of
|
|
# 5 meant the 6th concurrent request waited on ``pool_timeout`` before it
|
|
# even reached the database (REVIEW §7). The real ceiling is
|
|
# pool_size + db_max_overflow, so both are named here rather than left to
|
|
# SQLAlchemy's invisible default of 10.
|
|
db_pool_size: int = 15
|
|
db_max_overflow: int = 10
|
|
db_echo: bool = False
|
|
|
|
# --- http -------------------------------------------------------------
|
|
api_host: str = "127.0.0.1"
|
|
api_port: int = 8080
|
|
|
|
# --- storage ----------------------------------------------------------
|
|
# A small number of explicit top-level directories, never scattered under
|
|
# the app dir: these are the future volume mounts.
|
|
#
|
|
# image_root is the single source of truth for the image path. Caddy reads
|
|
# the same value, because the auth-checked handoff (SPEC 3.3) needs the app
|
|
# and the proxy to agree on where the bytes live.
|
|
image_root: Path = Path("/srv/poorbird/images")
|
|
thumb_root: Path = Path("/srv/poorbird/thumbs")
|
|
state_dir: Path = Path("/var/lib/poorbird")
|
|
|
|
# --- devices ----------------------------------------------------------
|
|
# Shared bootstrap secret presented by a device in X-Enroll-Secret.
|
|
# See firmware/API.md: do NOT rotate this without shipping new firmware,
|
|
# or you remove the last-resort recovery path for a mounted camera.
|
|
#
|
|
# Environment only, never a literal here (REVIEW SEC-001). Empty is allowed
|
|
# so the Phase 1 commands still run on a fresh clone; the device endpoints
|
|
# refuse to serve without it.
|
|
enroll_secret: SecretStr = SecretStr("")
|
|
|
|
# --- rate limiting ----------------------------------------------------
|
|
# In-process token buckets (api/ratelimit.py), sized for one uvicorn
|
|
# process. Off by default in tests, which would otherwise exhaust a
|
|
# bucket and start asserting against 429s.
|
|
rate_limit_enabled: bool = True
|
|
|
|
# --- worker -----------------------------------------------------------
|
|
# Idle polling only: the loop drains a non-empty queue back to back without
|
|
# sleeping, so this is the delay before a *newly* enqueued job is noticed,
|
|
# not a per-job cost. 5s trades latency nobody can perceive on a bird camera
|
|
# for 12 idle queries a minute instead of 30.
|
|
worker_poll_interval_s: float = 5.0
|
|
job_max_attempts: int = 3
|
|
|
|
# --- logging ----------------------------------------------------------
|
|
# Always to stdout/stderr. journald catches it now; a log driver would
|
|
# catch it later. Never app-managed log files.
|
|
log_level: str = "INFO"
|
|
log_format: Literal["text", "json"] = "text"
|
|
|
|
@field_validator("database_url")
|
|
@classmethod
|
|
def _reject_unedited_example(cls, v: str) -> str:
|
|
if any(p in v.lower() for p in _PLACEHOLDERS):
|
|
raise ValueError(
|
|
"POORBIRD_DATABASE_URL still contains a placeholder from the "
|
|
"example file. Put the real password in, or leave the variable "
|
|
"unset."
|
|
)
|
|
return v
|
|
|
|
@field_validator("enroll_secret")
|
|
@classmethod
|
|
def _reject_placeholder_secret(cls, v: SecretStr) -> SecretStr:
|
|
if v.get_secret_value().strip().lower() in _PLACEHOLDERS:
|
|
raise ValueError(
|
|
"POORBIRD_ENROLL_SECRET is a placeholder. Generate one with "
|
|
"'openssl rand -hex 32', or leave it unset until Phase 2."
|
|
)
|
|
return v
|
|
|
|
@property
|
|
def database_url_is_set(self) -> bool:
|
|
return bool(self.database_url.strip())
|
|
|
|
@property
|
|
def enroll_secret_is_set(self) -> bool:
|
|
return bool(self.enroll_secret.get_secret_value())
|
|
|
|
def storage_paths(self) -> list[Path]:
|
|
return [self.image_root, self.thumb_root, self.state_dir]
|
|
|
|
|
|
@lru_cache
|
|
def get_settings() -> Settings:
|
|
return Settings()
|