forked from mtusi2026/mtusi2026lab3
two api-replicas with LB-nginx
This commit is contained in:
+27
-9
@@ -1,11 +1,16 @@
|
||||
from enum import StrEnum
|
||||
from pathlib import Path
|
||||
from typing import Literal, Self
|
||||
|
||||
from pydantic import Field, SecretStr, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
from pydantic_settings import BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict
|
||||
from sqlalchemy import URL
|
||||
|
||||
ASYNC_DRIVER = "postgresql+asyncpg"
|
||||
SECRETS_DIR = next(
|
||||
(path for path in (Path("/run/secrets"), Path(__file__).resolve().parents[2] / "secrets") if (path / "db_password").is_file()),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
class LogLevel(StrEnum):
|
||||
@@ -51,23 +56,36 @@ class Settings(BaseSettings):
|
||||
db_connect_timeout_seconds: int = Field(default=3, ge=1)
|
||||
db_statement_timeout_ms: int = Field(default=5000, ge=1)
|
||||
|
||||
# Балансировка между репликами и идемпотентность
|
||||
instance_id: str | None = None # TODO(3.2): None -> вычислить в resolve_instance_id
|
||||
idempotency_ttl_seconds: int = Field(default=86400, ge=1) # TODO(3.4)
|
||||
shutdown_drain_seconds: float = Field(default=0, ge=0) # TODO(4.1)
|
||||
graceful_shutdown_timeout_seconds: int = Field(default=5, ge=1) # TODO(4.1)
|
||||
instance_id: str | None = None
|
||||
idempotency_ttl_seconds: int = Field(default=86400, ge=1)
|
||||
shutdown_drain_seconds: float = Field(default=1, ge=0)
|
||||
graceful_shutdown_timeout_seconds: int = Field(default=5, ge=1)
|
||||
readiness_timeout_seconds: float = Field(default=2, gt=0, lt=2.5)
|
||||
|
||||
# TODO(4.3): секреты из файлов (Docker secrets): pydantic-settings умеет
|
||||
# secrets_dir="/run/secrets" — имя файла = имя поля (db_password, ...).
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
env_file_encoding="utf-8",
|
||||
case_sensitive=False,
|
||||
extra="ignore",
|
||||
secrets_dir=SECRETS_DIR,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def settings_customise_sources(
|
||||
cls,
|
||||
settings_cls: type[BaseSettings],
|
||||
init_settings: PydanticBaseSettingsSource,
|
||||
env_settings: PydanticBaseSettingsSource,
|
||||
dotenv_settings: PydanticBaseSettingsSource,
|
||||
file_secret_settings: PydanticBaseSettingsSource,
|
||||
) -> tuple[PydanticBaseSettingsSource, ...]:
|
||||
"""Явные параметры и файлы имеют приоритет над окружением."""
|
||||
return init_settings, file_secret_settings, env_settings, dotenv_settings
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _require_database_source(self) -> Self:
|
||||
if self.shutdown_drain_seconds + self.graceful_shutdown_timeout_seconds >= 8:
|
||||
raise ValueError("Drain и graceful shutdown должны суммарно занимать менее 8 секунд")
|
||||
if self.database_url is not None:
|
||||
if not self.database_url.get_secret_value().startswith(ASYNC_DRIVER):
|
||||
raise ValueError(f"DATABASE_URL должен начинаться с {ASYNC_DRIVER}://")
|
||||
@@ -75,7 +93,7 @@ class Settings(BaseSettings):
|
||||
|
||||
if not (self.db_host and self.db_name and self.db_user and self.db_password):
|
||||
raise ValueError(
|
||||
"Задайте DATABASE_URL или DB_HOST, DB_NAME, DB_USER и DB_PASSWORD"
|
||||
"Нужны DATABASE_URL либо DB_HOST, DB_NAME, DB_USER и секрет db_password"
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
Reference in New Issue
Block a user