PLBA2-2. Реализация
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
from plba.settings.models import (
|
||||
SettingInvalidError,
|
||||
SettingKey,
|
||||
SettingNotFoundError,
|
||||
SettingsDatabaseUnavailableError,
|
||||
)
|
||||
from plba.settings.postgres import PostgresSettingsRepository
|
||||
from plba.settings.reader import SettingsReader
|
||||
from plba.settings.repository import SettingsRepository
|
||||
|
||||
__all__ = [
|
||||
"PostgresSettingsRepository",
|
||||
"SettingInvalidError",
|
||||
"SettingKey",
|
||||
"SettingNotFoundError",
|
||||
"SettingsDatabaseUnavailableError",
|
||||
"SettingsReader",
|
||||
"SettingsRepository",
|
||||
]
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,36 @@
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Generic, TypeVar
|
||||
|
||||
T = TypeVar("T")
|
||||
_MISSING = object()
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SettingKey(Generic[T]):
|
||||
name: str
|
||||
decoder: Callable[[str], T]
|
||||
required: bool = True
|
||||
default: Any = _MISSING
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.name or self.name.strip() != self.name:
|
||||
raise ValueError("setting key name must be non-empty")
|
||||
if self.required and self.default is not _MISSING:
|
||||
raise ValueError("a required setting cannot have a default")
|
||||
|
||||
@property
|
||||
def has_default(self) -> bool:
|
||||
return self.default is not _MISSING
|
||||
|
||||
|
||||
class SettingNotFoundError(LookupError):
|
||||
pass
|
||||
|
||||
|
||||
class SettingInvalidError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class SettingsDatabaseUnavailableError(RuntimeError):
|
||||
pass
|
||||
@@ -0,0 +1,43 @@
|
||||
from collections.abc import Mapping, Sequence
|
||||
import re
|
||||
from typing import Any, AsyncContextManager, Protocol
|
||||
|
||||
from plba.settings.models import SettingsDatabaseUnavailableError
|
||||
|
||||
|
||||
class PostgresConnection(Protocol):
|
||||
async def fetch(self, query: str, *parameters: object) -> Sequence[Mapping[str, Any]]: ...
|
||||
|
||||
|
||||
class PostgresPool(Protocol):
|
||||
def acquire(self) -> AsyncContextManager[PostgresConnection]: ...
|
||||
|
||||
|
||||
class PostgresSettingsRepository:
|
||||
_SCHEMA = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
||||
|
||||
def __init__(self, pool: PostgresPool, schema: str) -> None:
|
||||
if not self._SCHEMA.fullmatch(schema):
|
||||
raise ValueError("schema must be a PostgreSQL identifier")
|
||||
self._pool = pool
|
||||
self._table = f'"{schema}".settings'
|
||||
|
||||
async def fetch_values(
|
||||
self, setting_key: str, config_key: str | None = None
|
||||
) -> list[str]:
|
||||
query = (
|
||||
f"SELECT setting_value FROM {self._table} "
|
||||
"WHERE setting_key = $1 AND ($2 IS NULL OR config_key = $2) "
|
||||
"AND is_enabled = TRUE ORDER BY sort_order ASC, id ASC"
|
||||
)
|
||||
try:
|
||||
async with self._pool.acquire() as connection:
|
||||
rows = await connection.fetch(query, setting_key, config_key)
|
||||
values = [row["setting_value"] for row in rows]
|
||||
if any(not isinstance(value, str) for value in values):
|
||||
raise TypeError("settings.setting_value must be text")
|
||||
return values
|
||||
except Exception as error:
|
||||
raise SettingsDatabaseUnavailableError(
|
||||
"settings query failed"
|
||||
) from error
|
||||
@@ -0,0 +1,35 @@
|
||||
from typing import TypeVar
|
||||
|
||||
from plba.settings.models import (
|
||||
SettingInvalidError,
|
||||
SettingKey,
|
||||
SettingNotFoundError,
|
||||
)
|
||||
from plba.settings.repository import SettingsRepository
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class SettingsReader:
|
||||
def __init__(self, repository: SettingsRepository) -> None:
|
||||
self._repository = repository
|
||||
|
||||
async def read(
|
||||
self, key: SettingKey[T], config_key: str | None = None
|
||||
) -> list[T]:
|
||||
raw_values = await self._repository.fetch_values(key.name, config_key)
|
||||
if not raw_values:
|
||||
if key.has_default:
|
||||
return [key.default]
|
||||
if key.required:
|
||||
raise SettingNotFoundError(f"required setting not found: {key.name}")
|
||||
return []
|
||||
decoded: list[T] = []
|
||||
for index, value in enumerate(raw_values):
|
||||
try:
|
||||
decoded.append(key.decoder(value))
|
||||
except Exception as error:
|
||||
raise SettingInvalidError(
|
||||
f"setting {key.name} value at index {index} is invalid"
|
||||
) from error
|
||||
return decoded
|
||||
@@ -0,0 +1,7 @@
|
||||
from typing import Protocol
|
||||
|
||||
|
||||
class SettingsRepository(Protocol):
|
||||
async def fetch_values(
|
||||
self, setting_key: str, config_key: str | None = None
|
||||
) -> list[str]: ...
|
||||
Reference in New Issue
Block a user