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:
+15
-5
@@ -8,8 +8,8 @@ from src.api import errors
|
||||
from src.api.middlewares import RequestContextMiddleware
|
||||
from src.api.routers import health_router, v1_router
|
||||
from src.config import settings
|
||||
from src.infra.db import create_engine, create_session_factory
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.infra.memory import MemoryStore
|
||||
from src.schemas.enums import RunModeEnum
|
||||
|
||||
logger: AbstractLogger = get_logger().bind(module="startup")
|
||||
@@ -17,17 +17,27 @@ logger: AbstractLogger = get_logger().bind(module="startup")
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
||||
# состояние лабы 1: живёт до остановки процесса
|
||||
app.state.store = MemoryStore()
|
||||
database = settings.database
|
||||
# engine не подключается при создании: без Postgres сервис стартует,
|
||||
# а /health/ready отвечает 503
|
||||
engine = create_engine(database)
|
||||
app.state.engine = engine
|
||||
app.state.session_factory = create_session_factory(engine)
|
||||
if not database.password.get_secret_value():
|
||||
logger.warning("Database password is empty")
|
||||
logger.info(
|
||||
"Started API",
|
||||
host=settings.app.host,
|
||||
port=settings.app.port,
|
||||
run_mode=settings.app.run_mode,
|
||||
database_host=database.host,
|
||||
database_port=database.port,
|
||||
database_name=database.name,
|
||||
)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
await engine.dispose()
|
||||
logger.info("Stopped API")
|
||||
|
||||
|
||||
@@ -52,8 +62,8 @@ def main() -> None:
|
||||
reload=reload,
|
||||
# без reload uvicorn пишет warning на reload_dirs при каждом старте
|
||||
reload_dirs=["src"] if reload else None,
|
||||
# один процесс: состояние лабы 1 в памяти, второй worker = второе
|
||||
# независимое состояние
|
||||
# один процесс: реплики — лаба 3, пул соединений рассчитан на один
|
||||
# процесс
|
||||
workers=1,
|
||||
timeout_graceful_shutdown=settings.app.graceful_shutdown_seconds,
|
||||
# логи uvicorn идут через наш JSON-форматтер (src/infra/logger.py)
|
||||
|
||||
Reference in New Issue
Block a user