Step 0.2: .env/TOML loader и базовый settings.py

This commit is contained in:
Ilgiz Kalmetyev 2026-04-15 09:41:20 +05:00
parent 2a07617c90
commit e02e98ced7
9 changed files with 412 additions and 2 deletions

8
.env.example Normal file
View File

@ -0,0 +1,8 @@
AGENT_ENV=dev
AGENT_LOG_LEVEL=INFO
AGENT_CONFIG_PATH=./config/agent.toml
AGENT_ENV_FILE=./.env
HOST_ID=robot-17
SITE_ID=warehouse-a
WEBHOOK_URL=https://example.local/webhook
WEBHOOK_TOKEN=secret-token

View File

@ -1,2 +1,103 @@
"""Environment loading placeholders."""
"""Environment loading helpers for the agent bootstrap."""
from __future__ import annotations
import ast
import os
from dataclasses import dataclass
from pathlib import Path
from typing import MutableMapping
DEFAULT_ENV_FILENAME = ".env"
@dataclass(slots=True, frozen=True)
class DotenvLoadResult:
"""Outcome of a dotenv load operation."""
path: Path | None
exists: bool
loaded_keys: tuple[str, ...]
skipped_keys: tuple[str, ...]
@property
def loaded(self) -> bool:
return self.exists and bool(self.loaded_keys)
def load_dotenv(
path: str | Path | None = None,
*,
env: MutableMapping[str, str] | None = None,
override: bool = False,
) -> DotenvLoadResult:
"""Load variables from a dotenv file into *env*.
Existing keys are preserved unless ``override`` is true.
"""
mapping: MutableMapping[str, str] = os.environ if env is None else env
dotenv_path = _resolve_dotenv_path(path)
if dotenv_path is None or not dotenv_path.exists():
return DotenvLoadResult(path=dotenv_path, exists=False, loaded_keys=(), skipped_keys=())
loaded: list[str] = []
skipped: list[str] = []
for raw_line in dotenv_path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#"):
continue
if line.startswith("export "):
line = line[len("export ") :].lstrip()
if "=" not in line:
continue
key, raw_value = line.split("=", 1)
key = key.strip()
if not _is_valid_key(key):
continue
value = _parse_value(raw_value)
if key in mapping and not override:
skipped.append(key)
continue
mapping[key] = value
loaded.append(key)
return DotenvLoadResult(
path=dotenv_path,
exists=True,
loaded_keys=tuple(loaded),
skipped_keys=tuple(skipped),
)
def _resolve_dotenv_path(path: str | Path | None) -> Path | None:
if path is None:
return Path.cwd() / DEFAULT_ENV_FILENAME
return Path(path)
def _is_valid_key(key: str) -> bool:
if not key:
return False
first = key[0]
if not (first == "_" or first.isalpha()):
return False
return all(char == "_" or char.isalnum() for char in key)
def _parse_value(raw_value: str) -> str:
value = raw_value.strip()
if not value:
return ""
if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
try:
parsed = ast.literal_eval(value)
except (SyntaxError, ValueError):
return value[1:-1]
return parsed if isinstance(parsed, str) else str(parsed)
return value

View File

@ -1,2 +1,116 @@
"""Settings bootstrap placeholders."""
"""Bootstrap settings for the agent."""
from __future__ import annotations
import os
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Mapping
from .env import DotenvLoadResult, load_dotenv
from .utils.toml_loader import load_toml
DEFAULT_CONFIG_PATH = Path("config/agent.toml")
DEFAULT_LOG_LEVEL = "INFO"
DEFAULT_AGENT_ENV = "dev"
@dataclass(slots=True, frozen=True)
class RuntimeSettings:
"""Environment-driven bootstrap settings."""
agent_env: str = DEFAULT_AGENT_ENV
log_level: str = DEFAULT_LOG_LEVEL
config_path: Path = DEFAULT_CONFIG_PATH
host_id: str | None = None
site_id: str | None = None
env_file: Path | None = None
@classmethod
def from_env(cls, env: Mapping[str, str]) -> "RuntimeSettings":
return cls(
agent_env=env.get("AGENT_ENV", DEFAULT_AGENT_ENV),
log_level=env.get("AGENT_LOG_LEVEL", DEFAULT_LOG_LEVEL),
config_path=Path(env.get("AGENT_CONFIG_PATH", str(DEFAULT_CONFIG_PATH))),
host_id=env.get("HOST_ID"),
site_id=env.get("SITE_ID"),
env_file=_optional_path(env.get("AGENT_ENV_FILE")),
)
@dataclass(slots=True, frozen=True)
class Settings:
"""Complete bootstrap configuration for the application."""
runtime: RuntimeSettings
config: dict[str, Any]
config_path: Path
env_file: Path | None = None
dotenv_result: DotenvLoadResult | None = None
def section(self, name: str, default: Any | None = None) -> Any:
return self.config.get(name, default)
@property
def agent(self) -> dict[str, Any]:
value = self.config.get("agent", {})
return value if isinstance(value, dict) else {}
def load_settings(
*,
env_file: str | Path | None = None,
config_path: str | Path | None = None,
env: Mapping[str, str] | None = None,
load_env_file: bool = True,
) -> Settings:
"""Load environment and TOML config into a single settings object."""
mapping = os.environ if env is None else env
dotenv_result: DotenvLoadResult | None = None
effective_env_file = _resolve_env_file_path(env_file, mapping)
if load_env_file:
dotenv_result = load_dotenv(effective_env_file, env=mapping)
runtime = RuntimeSettings.from_env(mapping)
resolved_config_path = _resolve_config_path(config_path, runtime)
config = load_toml(resolved_config_path, env=mapping)
runtime = RuntimeSettings(
agent_env=runtime.agent_env,
log_level=runtime.log_level,
config_path=resolved_config_path,
host_id=runtime.host_id,
site_id=runtime.site_id,
env_file=effective_env_file,
)
return Settings(
runtime=runtime,
config=config,
config_path=resolved_config_path,
env_file=effective_env_file,
dotenv_result=dotenv_result,
)
def _resolve_config_path(
config_path: str | Path | None,
runtime: RuntimeSettings,
) -> Path:
if config_path is not None:
return Path(config_path)
return runtime.config_path
def _resolve_env_file_path(
env_file: str | Path | None,
env: Mapping[str, str],
) -> Path | None:
if env_file is not None:
return Path(env_file)
candidate = env.get("AGENT_ENV_FILE")
return Path(candidate) if candidate else Path.cwd() / ".env"
def _optional_path(value: str | None) -> Path | None:
return Path(value) if value else None

View File

@ -1,2 +1,5 @@
"""Utility helpers."""
from .toml_loader import expand_env, load_toml, loads_toml
__all__ = ["expand_env", "load_toml", "loads_toml"]

View File

@ -0,0 +1,50 @@
"""Deterministic TOML loading with optional environment expansion."""
from __future__ import annotations
import os
import re
from pathlib import Path
from typing import Any, Mapping
try: # Python 3.11+ stdlib
import tomllib
except ModuleNotFoundError: # pragma: no cover - fallback for alternative runtimes
import tomli as tomllib # type: ignore[no-redef]
_ENV_PATTERN = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
def load_toml(path: str | Path, *, env: Mapping[str, str] | None = None) -> dict[str, Any]:
"""Load TOML from *path* and expand ``${VAR}`` placeholders in strings."""
source = Path(path)
with source.open("rb") as handle:
data = tomllib.load(handle)
return expand_env(data, env=env)
def loads_toml(text: str, *, env: Mapping[str, str] | None = None) -> dict[str, Any]:
"""Load TOML from text and expand ``${VAR}`` placeholders in strings."""
data = tomllib.loads(text)
return expand_env(data, env=env)
def expand_env(value: Any, *, env: Mapping[str, str] | None = None) -> Any:
"""Recursively expand environment placeholders in TOML values."""
mapping = os.environ if env is None else env
return _expand_value(value, mapping)
def _expand_value(value: Any, env: Mapping[str, str]) -> Any:
if isinstance(value, str):
return _ENV_PATTERN.sub(lambda match: env.get(match.group(1), match.group(0)), value)
if isinstance(value, list):
return [_expand_value(item, env) for item in value]
if isinstance(value, tuple):
return tuple(_expand_value(item, env) for item in value)
if isinstance(value, dict):
return {key: _expand_value(item, env) for key, item in value.items()}
return value

9
tests/conftest.py Normal file
View File

@ -0,0 +1,9 @@
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "src"
if str(SRC) not in sys.path:
sys.path.insert(0, str(SRC))

53
tests/unit/test_env.py Normal file
View File

@ -0,0 +1,53 @@
from __future__ import annotations
import tempfile
from pathlib import Path
from agent.env import load_dotenv
ROOT = Path(__file__).resolve().parents[2]
TEMP_ROOT = ROOT / ".tmp-tests"
TEMP_ROOT.mkdir(exist_ok=True)
def test_load_dotenv_sets_missing_values() -> None:
with tempfile.TemporaryDirectory(dir=TEMP_ROOT) as tmp_dir:
env_file = Path(tmp_dir) / ".env"
env_file.write_text(
"\n".join(
[
"AGENT_ENV=dev",
"AGENT_LOG_LEVEL='DEBUG'",
"HOST_ID=robot-17",
"# comment",
"export SITE_ID=warehouse-a",
]
),
encoding="utf-8",
)
target: dict[str, str] = {"HOST_ID": "existing"}
result = load_dotenv(env_file, env=target)
assert result.exists is True
assert result.path == env_file
assert result.loaded_keys == ("AGENT_ENV", "AGENT_LOG_LEVEL", "SITE_ID")
assert result.skipped_keys == ("HOST_ID",)
assert target["AGENT_ENV"] == "dev"
assert target["AGENT_LOG_LEVEL"] == "DEBUG"
assert target["HOST_ID"] == "existing"
assert target["SITE_ID"] == "warehouse-a"
def test_load_dotenv_override_replaces_existing_values() -> None:
with tempfile.TemporaryDirectory(dir=TEMP_ROOT) as tmp_dir:
env_file = Path(tmp_dir) / ".env"
env_file.write_text("HOST_ID=robot-18", encoding="utf-8")
target: dict[str, str] = {"HOST_ID": "existing"}
result = load_dotenv(env_file, env=target, override=True)
assert result.loaded_keys == ("HOST_ID",)
assert result.skipped_keys == ()
assert target["HOST_ID"] == "robot-18"

View File

@ -0,0 +1,50 @@
from __future__ import annotations
import tempfile
from pathlib import Path
from agent.settings import load_settings
ROOT = Path(__file__).resolve().parents[2]
TEMP_ROOT = ROOT / ".tmp-tests"
TEMP_ROOT.mkdir(exist_ok=True)
def test_load_settings_uses_env_file_for_config_path() -> None:
with tempfile.TemporaryDirectory(dir=TEMP_ROOT) as tmp_dir:
temp_dir = Path(tmp_dir)
config_file = temp_dir / "agent.toml"
config_file.write_text(
"""
[agent]
name = "wifi-event-agent"
""".strip(),
encoding="utf-8",
)
env_file = temp_dir / ".env"
env_file.write_text(
"\n".join(
[
f"AGENT_CONFIG_PATH={config_file}",
"AGENT_ENV=prod",
"AGENT_LOG_LEVEL=WARNING",
"HOST_ID=robot-17",
"SITE_ID=warehouse-a",
]
),
encoding="utf-8",
)
env: dict[str, str] = {}
settings = load_settings(env_file=env_file, env=env)
assert settings.config_path == config_file
assert settings.runtime.config_path == config_file
assert settings.runtime.agent_env == "prod"
assert settings.runtime.log_level == "WARNING"
assert settings.runtime.host_id == "robot-17"
assert settings.runtime.site_id == "warehouse-a"
assert settings.agent["name"] == "wifi-event-agent"
assert env["AGENT_CONFIG_PATH"] == str(config_file)

View File

@ -0,0 +1,22 @@
from __future__ import annotations
from agent.utils.toml_loader import loads_toml
def test_loads_toml_expands_environment_placeholders() -> None:
data = loads_toml(
"""
[transport.webhook]
url = "${WEBHOOK_URL}"
timeout_ms = 3000
[agent]
name = "wifi-event-agent"
tags = ["${SITE_ID}", "warehouse"]
""".strip(),
env={"WEBHOOK_URL": "https://example.local/webhook", "SITE_ID": "warehouse-a"},
)
assert data["transport"]["webhook"]["url"] == "https://example.local/webhook"
assert data["transport"]["webhook"]["timeout_ms"] == 3000
assert data["agent"]["tags"] == ["warehouse-a", "warehouse"]