Сделал связку Alembic с общим источником конфигурации.

This commit is contained in:
Ilgiz Kalmetyev 2026-04-11 22:50:00 +05:00
parent f1dbf53796
commit 6b7a93c51f
7 changed files with 124 additions and 8 deletions

View File

@ -2,4 +2,5 @@
script_location = migrations
prepend_sys_path = .
path_separator = os
sqlalchemy.url = sqlite+aiosqlite:///wf_agent.sqlite3
# Overridden in migrations/env.py from the shared TOML config unless a test sets sqlalchemy.url explicitly.
sqlalchemy.url = sqlite+aiosqlite:///wf_agent.sqlite3

21
app/core/alembic.py Normal file
View File

@ -0,0 +1,21 @@
from __future__ import annotations
from pathlib import Path
from alembic.config import Config
from .config import load_settings
from .constants import DEFAULT_ALEMBIC_SQLALCHEMY_URL
def resolve_sqlalchemy_url(
alembic_config: Config,
*,
config_path: Path | None = None,
) -> str:
configured_url = (alembic_config.get_main_option('sqlalchemy.url') or '').strip()
if configured_url and configured_url != DEFAULT_ALEMBIC_SQLALCHEMY_URL:
return configured_url
settings = load_settings(config_path=config_path)
return settings.database_dsn

View File

@ -1,4 +1,4 @@
from __future__ import annotations
from __future__ import annotations
import os
import re
@ -18,6 +18,7 @@ from .constants import (
DEFAULT_CACHE_TTL_SECONDS,
DEFAULT_CONFIG_PATH,
DEFAULT_LOG_LEVEL,
CONFIG_PATH_ENV_VAR,
TEST_DATABASE_NAME_MARKERS,
)
from .exceptions import ConfigurationError, EnvironmentGuardError
@ -99,9 +100,17 @@ class Settings(BaseModel):
cache_ttl_seconds: int = DEFAULT_CACHE_TTL_SECONDS
def _resolve_config_path(value: Path | str | None) -> Path:
def _resolve_config_path(
value: Path | str | None,
*,
runtime_environment: Mapping[str, str] | None = None,
) -> Path:
if value is None or not str(value).strip():
return DEFAULT_CONFIG_PATH
environment = dict(runtime_environment or os.environ)
env_value = environment.get(CONFIG_PATH_ENV_VAR)
if env_value is None or not str(env_value).strip():
return DEFAULT_CONFIG_PATH
value = env_value
path = Path(str(value).strip())
if path.is_absolute():
return path
@ -124,7 +133,10 @@ def load_settings(
config_path: Path | None = None,
runtime_environment: Mapping[str, str] | None = None,
) -> Settings:
resolved_config_path = _resolve_config_path(config_path)
resolved_config_path = _resolve_config_path(
config_path,
runtime_environment=runtime_environment,
)
raw_config = _load_config_file(resolved_config_path)
raw_settings = {

View File

@ -1,9 +1,11 @@
from __future__ import annotations
from __future__ import annotations
from pathlib import Path
APP_NAME = "wf-agent"
CONFIG_PATH_ENV_VAR = "WF_AGENT_CONFIG_PATH"
APP_ENV_DEVELOPMENT = "development"
APP_ENV_TEST = "test"
APP_ENV_PRODUCTION = "production"
@ -11,6 +13,7 @@ APP_ENV_PRODUCTION = "production"
DEFAULT_LOG_LEVEL = "INFO"
DEFAULT_CACHE_TTL_SECONDS = 24 * 60 * 60
DEFAULT_CONFIG_PATH = Path("/etc/wf-agent/wf-agent.toml")
DEFAULT_ALEMBIC_SQLALCHEMY_URL = "sqlite+aiosqlite:///wf_agent.sqlite3"
ALLOWED_DATABASE_SCHEMES = ("sqlite+aiosqlite",)
TEST_DATABASE_NAME_MARKERS = ("test", "tests", "pytest")

View File

@ -7,6 +7,7 @@ from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
from app.core.alembic import resolve_sqlalchemy_url
from app.storage.models import ORMBase
config = context.config
@ -14,8 +15,14 @@ config = context.config
target_metadata = ORMBase.metadata
def _configure_sqlalchemy_url() -> str:
sqlalchemy_url = resolve_sqlalchemy_url(config)
config.set_main_option("sqlalchemy.url", sqlalchemy_url)
return sqlalchemy_url
def run_migrations_offline() -> None:
url = config.get_main_option("sqlalchemy.url")
url = _configure_sqlalchemy_url()
context.configure(
url=url,
target_metadata=target_metadata,
@ -40,6 +47,7 @@ def do_run_migrations(connection: Connection) -> None:
async def run_migrations_online() -> None:
_configure_sqlalchemy_url()
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",

View File

@ -0,0 +1,50 @@
from __future__ import annotations
from pathlib import Path
from alembic.config import Config
from app.core.alembic import resolve_sqlalchemy_url
from app.core.constants import DEFAULT_ALEMBIC_SQLALCHEMY_URL
def test_resolve_sqlalchemy_url_uses_shared_toml_config_when_placeholder_is_configured(
tmp_path: Path, monkeypatch
) -> None:
config_path = tmp_path / "wf-agent.toml"
config_path.write_text(
"""
app_env = "test"
database_dsn = "sqlite+aiosqlite:///wf_agent_test_runtime.sqlite3"
wifi_interface_name = "wlan0"
""".strip(),
encoding="utf-8",
)
monkeypatch.setenv("WF_AGENT_CONFIG_PATH", str(config_path))
alembic_config = Config("alembic.ini")
assert alembic_config.get_main_option("sqlalchemy.url") == DEFAULT_ALEMBIC_SQLALCHEMY_URL
assert resolve_sqlalchemy_url(alembic_config) == "sqlite+aiosqlite:///wf_agent_test_runtime.sqlite3"
def test_resolve_sqlalchemy_url_keeps_explicit_alembic_override(
tmp_path: Path, monkeypatch
) -> None:
config_path = tmp_path / "wf-agent.toml"
config_path.write_text(
"""
app_env = "test"
database_dsn = "sqlite+aiosqlite:///wf_agent_test_runtime.sqlite3"
wifi_interface_name = "wlan0"
""".strip(),
encoding="utf-8",
)
monkeypatch.setenv("WF_AGENT_CONFIG_PATH", str(config_path))
alembic_config = Config("alembic.ini")
alembic_config.set_main_option(
"sqlalchemy.url", "sqlite+aiosqlite:///wf_agent_override_test.sqlite3"
)
assert resolve_sqlalchemy_url(alembic_config) == "sqlite+aiosqlite:///wf_agent_override_test.sqlite3"

View File

@ -1,4 +1,4 @@
from __future__ import annotations
from __future__ import annotations
from pathlib import Path
@ -6,6 +6,7 @@ import pytest
from app.core.config import load_settings
from app.core.exceptions import ConfigurationError, EnvironmentGuardError
from app.core.constants import CONFIG_PATH_ENV_VAR
def test_load_settings_reads_single_toml_config(tmp_path: Path) -> None:
@ -103,3 +104,23 @@ def test_load_settings_rejects_invalid_cache_ttl_seconds(tmp_path: Path) -> None
with pytest.raises(ConfigurationError, match="must be a positive integer"):
load_settings(config_path=config_path)
def test_load_settings_uses_config_path_environment_variable(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
config_path = tmp_path / "wf-agent.toml"
config_path.write_text(
"""
app_env = "test"
database_dsn = "sqlite+aiosqlite:///wf_agent_test_config.sqlite3"
wifi_interface_name = "wlan0"
""".strip(),
encoding="utf-8",
)
monkeypatch.setenv(CONFIG_PATH_ENV_VAR, str(config_path))
settings = load_settings()
assert settings.config_path == config_path.resolve()
assert settings.database_dsn == "sqlite+aiosqlite:///wf_agent_test_config.sqlite3"