Add initial shared code packages
This commit is contained in:
commit
838a97d344
54 files changed
+6265
No files matched your search
@@ -0,0 +1,49 @@
|
||||
"""Dependency-free environment configuration helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from typing import Mapping
|
||||
|
||||
|
||||
def _int_value(env: Mapping[str, str], key: str, fallback: int, minimum: int) -> int:
|
||||
try:
|
||||
value = int(env.get(key, ""))
|
||||
except (TypeError, ValueError):
|
||||
return fallback
|
||||
return value if value >= minimum else fallback
|
||||
|
||||
|
||||
def database_url_from_env(env: Mapping[str, str] | None = None) -> str:
|
||||
source = os.environ if env is None else env
|
||||
value = str(source.get("DATABASE_URL", "")).strip()
|
||||
if not value:
|
||||
raise RuntimeError("DATABASE_URL environment variable is required")
|
||||
return value
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DatabaseConfig:
|
||||
dsn: str
|
||||
min_size: int = 0
|
||||
max_size: int = 20
|
||||
timeout: float = 5.0
|
||||
command_timeout: float = 15.0
|
||||
|
||||
@classmethod
|
||||
def from_env(cls, env: Mapping[str, str] | None = None) -> "DatabaseConfig":
|
||||
source = os.environ if env is None else env
|
||||
max_size = _int_value(source, "DATABASE_MAX_CONNS", 20, 1)
|
||||
min_size = _int_value(source, "DATABASE_MIN_CONNS", 0, 0)
|
||||
if min_size > max_size:
|
||||
raise ValueError("DATABASE_MIN_CONNS must not exceed DATABASE_MAX_CONNS")
|
||||
return cls(
|
||||
dsn=database_url_from_env(source),
|
||||
min_size=min_size,
|
||||
max_size=max_size,
|
||||
timeout=float(_int_value(source, "DATABASE_CONNECT_TIMEOUT_SECONDS", 5, 1)),
|
||||
command_timeout=float(
|
||||
_int_value(source, "DATABASE_COMMAND_TIMEOUT_SECONDS", 15, 1)
|
||||
),
|
||||
)
|
||||
Reference in new issue
Block a user