Files
mtusi2026lab2/src/config/settings.py
T
ricoromaandClaude Opus 5.5 cae4b09147 feat: cache chat cards in Valkey
Valkey 9.1 in compose caches the immutable chat card (title, members,
created_at) used by GET /chats/{id} and by the membership check of the
message endpoints. Cache-aside with a write after commit, keys per
database, TTL plus allkeys-lru, persistence off. redis-py runs without
retries; on failure the cache is skipped for a few seconds and requests
go to PostgreSQL. Readiness does not depend on Valkey.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 21:17:55 +03:00

155 lines
5.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from pathlib import Path
from typing import Annotated, Literal
from pydantic import BaseModel, BeforeValidator, Field, SecretStr
from pydantic_settings import (
BaseSettings,
PydanticBaseSettingsSource,
SettingsConfigDict,
TomlConfigSettingsSource,
)
from sqlalchemy.engine import URL
from src.schemas.enums import RunModeEnum
BASE_DIR = Path(__file__).resolve().parent.parent.parent
ENV_PATH = BASE_DIR.joinpath(".env")
TOML_SETTINGS_PATH = BASE_DIR.joinpath("config.toml")
LogLevel = Annotated[
Literal["DEBUG", "INFO", "WARNING", "ERROR"],
BeforeValidator(
lambda value: value.upper() if isinstance(value, str) else value,
),
]
class App(BaseModel):
run_mode: RunModeEnum = RunModeEnum.CONSOLE
port: int = Field(default=8080, ge=1, le=65535)
log_level: LogLevel = "INFO"
# секунды, которые uvicorn ждёт текущие запросы после SIGTERM;
# docker шлёт SIGKILL через 10 с, поэтому не больше 9
graceful_shutdown_seconds: int = Field(default=8, ge=1, le=9)
@property
def host(self) -> str:
"""Адрес прослушивания: localhost в console, все интерфейсы в docker."""
if self.run_mode == RunModeEnum.DOCKER:
return "0.0.0.0"
return "127.0.0.1"
class Database(BaseModel):
"""Подключение к PostgreSQL.
Адрес и учётные данные приходят из `.env`: в console — мостами к
`POSTGRES_*`, в docker — из `environment` compose. Пул и таймауты —
из `config.toml`.
"""
host: str = "127.0.0.1"
port: int = Field(default=5432, ge=1, le=65535)
user: str = "messenger"
password: SecretStr = SecretStr("")
name: str = "messenger"
pool_size: int = Field(default=10, ge=1)
max_overflow: int = Field(default=5, ge=0)
# секунды ожидания свободного соединения пула
pool_timeout_seconds: float = Field(default=5, gt=0)
# секунды на установку соединения
connect_timeout_seconds: float = Field(default=3, gt=0)
# миллисекунды, серверный statement_timeout; 0 — без ограничения
statement_timeout_ms: int = Field(default=5000, ge=0)
# секунды на всю работу запроса с БД (asyncio): зависший сервер или
# обрыв сети, где серверный таймаут не сработает
request_timeout_seconds: float = Field(default=6, gt=0)
@property
def url(self) -> URL:
"""URL asyncpg; пароль экранирует `URL.create`, строку не собираем."""
return URL.create(
drivername="postgresql+asyncpg",
username=self.user,
password=self.password.get_secret_value(),
host=self.host,
port=self.port,
database=self.name,
)
class Auth(BaseModel):
"""Сессии и пароли; значения — из `config.toml`.
Контрактное `SESSION_TTL_SECONDS` сопоставлено с `session_ttl_seconds`
в `REPORT.md`; разовая подмена — окружением `AUTH__SESSION_TTL_SECONDS`.
"""
# секунды жизни сессии с момента входа
session_ttl_seconds: int = Field(default=3600, gt=0)
# сколько хэшей пароля считается одновременно: Argon2id берёт 64 MiB
# памяти на каждый
kdf_concurrency: int = Field(default=4, gt=0)
class Cache(BaseModel):
"""Подключение к Valkey (кэш карточек чатов).
Адрес и пароль приходят из `.env`: в console — мостами к `VALKEY_*`,
в docker — из `environment` compose. Таймауты и срок записей — из
`config.toml`.
"""
host: str = "127.0.0.1"
port: int = Field(default=6379, ge=1, le=65535)
password: SecretStr = SecretStr("")
# секунды на соединение и ответ; дольше — запрос идёт в PostgreSQL
timeout_seconds: float = Field(default=0.2, gt=0)
# секунды, на которые кэш пропускается после отказа Valkey
retry_after_seconds: float = Field(default=5, gt=0)
# секунды жизни карточки чата в кэше
chat_ttl_seconds: int = Field(default=3600, gt=0)
# соединений в пуле клиента
max_connections: int = Field(default=10, ge=1)
class Settings(BaseSettings):
model_config = SettingsConfigDict(
extra="ignore",
env_file=ENV_PATH,
toml_file=TOML_SETTINGS_PATH,
env_nested_delimiter="__",
case_sensitive=False,
)
app: App = App()
database: Database = Database()
auth: Auth = Auth()
cache: Cache = Cache()
@classmethod
def settings_customise_sources(
cls,
settings_cls: type[BaseSettings],
init_settings: PydanticBaseSettingsSource,
env_settings: PydanticBaseSettingsSource,
dotenv_settings: PydanticBaseSettingsSource,
file_secret_settings: PydanticBaseSettingsSource, # noqa: ARG003
) -> tuple[PydanticBaseSettingsSource, ...]:
"""Приоритет: окружение → .env → config.toml → дефолты.
Оба файловых источника сами пропускают отсутствующий файл: без
.env и config.toml сервис поднимается на значениях по умолчанию.
"""
return (
init_settings,
env_settings,
dotenv_settings,
TomlConfigSettingsSource(settings_cls),
)
settings = Settings()