Пофиксила 2 замечания: добавила one-shot миграции и лимиты ресурсов для всех сервисов

This commit is contained in:
vasyukova
2026-10-10 11:45:20 +03:00
parent d56698c3e3
commit c80afdb775
3 changed files with 90 additions and 5 deletions
+53 -1
View File
@@ -4,7 +4,9 @@ x-required-roles:
- postgres
- load_balancer
# Лабораторная 3. LB + 2 API-реплики + PostgreSQL + Redis.
# Лабораторная 3. LB + 2 API-реплики + PostgreSQL + Redis + one-shot migrate.
# Миграции вынесены в отдельный сервис migrate.
# Лимиты CPU/RAM заданы для ВСЕХ сервисов
services:
postgres:
image: postgres:18.6-alpine
@@ -22,6 +24,14 @@ services:
retries: 20
start_period: 30s
restart: unless-stopped
deploy:
resources:
limits:
cpus: "1.0"
memory: 1G
reservations:
cpus: "0.25"
memory: 256M
redis:
image: redis:7.4.1-alpine
@@ -36,6 +46,35 @@ services:
retries: 10
start_period: 3s
restart: unless-stopped
deploy:
resources:
limits:
cpus: "0.5"
memory: 256M
reservations:
cpus: "0.1"
memory: 64M
migrate:
build: .
image: mtuci-messenger:lab3
# One-shot: применяет схему БД один раз и завершается с кодом 0.
# Реплики api стартуют только после успешного выхода (см. depends_on).
command: ["python", "-m", "app.storage.db"]
env_file:
- .env
depends_on:
postgres:
condition: service_healthy
restart: "no"
deploy:
resources:
limits:
cpus: "0.5"
memory: 256M
reservations:
cpus: "0.1"
memory: 64M
api:
build: .
@@ -45,6 +84,8 @@ services:
env_file:
- .env
depends_on:
migrate:
condition: service_completed_successfully
postgres:
condition: service_healthy
redis:
@@ -62,6 +103,9 @@ services:
limits:
cpus: "1.0"
memory: 512M
reservations:
cpus: "0.25"
memory: 128M
lb:
image: nginx:1.27.3-alpine
@@ -74,6 +118,14 @@ services:
api:
condition: service_healthy
restart: unless-stopped
deploy:
resources:
limits:
cpus: "0.5"
memory: 128M
reservations:
cpus: "0.1"
memory: 32M
volumes:
postgres-data:
+2 -2
View File
@@ -13,7 +13,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
import psycopg
import uvicorn
from .api import auth, chats, health, messages, users
from .storage.db import init_schema, init_pool, close_pool
from .storage.db import init_pool, close_pool
# --- Логирование: структурированный stdout, без содержимого сообщений ---
@@ -32,7 +32,7 @@ INSTANCE_ID = os.environ.get("INSTANCE_ID") or uuid.uuid4().hex[:12]
@asynccontextmanager
async def lifespan(app: FastAPI):
init_pool() # пул соединений PostgreSQL с таймаутами (уровень 4)
init_schema() # создать таблицы в БД если их ещё нет
# Схему готовит отдельный сервис migrate (service_completed_successfully)
logger.info(
"event=startup app_env=%s session_store=%s instance_id=%s",
os.environ.get("APP_ENV", "lab"),
+35 -2
View File
@@ -108,8 +108,41 @@ CREATE INDEX IF NOT EXISTS idx_idempotency_created
def init_schema() -> None:
"""Идемпотентная миграция: запускается на старте приложения."""
"""Идемпотентная миграция: безопасно вызывать многократно.
Вызывается ОДИН РАЗ отдельным one-shot сервисом migrate
(см. compose.yaml). Реплики API миграции больше не выполняют:
они ждут service_completed_successfully.
"""
with connection() as conn:
with conn.cursor() as cur:
cur.execute(SCHEMA_SQL)
conn.commit()
conn.commit()
def run_migrations() -> None:
"""Точка входа для one-shot migrate-контейнера.
Поднимает пул, применяет схему, закрывает пул. Завершается с кодом 0
при успехе — этого достаточно для service_completed_successfully.
"""
init_pool()
try:
init_schema()
finally:
close_pool()
if __name__ == "__main__":
# Запуск: python -m app.storage.db
# (в compose.yaml — command: ["python", "-m", "app.storage.db"])
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
log = logging.getLogger("migrate")
log.info("event=migrations_start")
run_migrations()
log.info("event=migrations_done")