feat: store messenger data in PostgreSQL
Replace the in-memory store with PostgreSQL 18.6: SQLAlchemy 2.1 async engine on asyncpg, alembic migrations with an async env.py, repos on AsyncSession and services that own the transaction. Username uniqueness is enforced by the database (ON CONFLICT), a chat and its members are created in one transaction, member order is kept in chat_members.position, and a composite foreign key makes the sender a member of the chat. History and chat lists use keyset pagination on (chat_id, created_at, id) and (user_id, created_at, chat_id). The compose stand runs postgres, a one-shot migrate service on the API image and the API. All Postgres addresses come from .env without literals; only the 127.0.0.1 publish address stays literal. make run_dev starts Postgres and applies migrations before the server, and make env_setup generates a random Postgres password. Unavailable PostgreSQL yields 503: get_db_session bounds the request with asyncio and classifies driver errors. BoundedCloseConnection limits asyncpg's graceful close, which otherwise waited without limit on a frozen server and held the request until it was resumed. Add scripts/restart.sh for make test-persistence and make test_isolated, which runs the image on a throwaway test database. Remove make run_no_compose. X-User-Id identification is unchanged until the session-auth change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+42
-1
@@ -1,13 +1,14 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal
|
||||
|
||||
from pydantic import BaseModel, BeforeValidator, Field
|
||||
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
|
||||
|
||||
@@ -39,6 +40,45 @@ class App(BaseModel):
|
||||
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 Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
extra="ignore",
|
||||
@@ -49,6 +89,7 @@ class Settings(BaseSettings):
|
||||
)
|
||||
|
||||
app: App = App()
|
||||
database: Database = Database()
|
||||
|
||||
@classmethod
|
||||
def settings_customise_sources(
|
||||
|
||||
Reference in New Issue
Block a user