From c80afdb7757d951a2ee6cd1e20b807923dd99419 Mon Sep 17 00:00:00 2001 From: vasyukova Date: Sat, 10 Oct 2026 11:45:20 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9F=D0=BE=D1=84=D0=B8=D0=BA=D1=81=D0=B8?= =?UTF-8?q?=D0=BB=D0=B0=202=20=D0=B7=D0=B0=D0=BC=D0=B5=D1=87=D0=B0=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F:=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB?= =?UTF-8?q?=D0=B0=20one-shot=20=D0=BC=D0=B8=D0=B3=D1=80=D0=B0=D1=86=D0=B8?= =?UTF-8?q?=D0=B8=20=D0=B8=20=D0=BB=D0=B8=D0=BC=D0=B8=D1=82=D1=8B=20=D1=80?= =?UTF-8?q?=D0=B5=D1=81=D1=83=D1=80=D1=81=D0=BE=D0=B2=20=D0=B4=D0=BB=D1=8F?= =?UTF-8?q?=20=D0=B2=D1=81=D0=B5=D1=85=20=D1=81=D0=B5=D1=80=D0=B2=D0=B8?= =?UTF-8?q?=D1=81=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- compose.yaml | 54 ++++++++++++++++++++++++++++++++++++++++++- src/app/main.py | 4 ++-- src/app/storage/db.py | 37 +++++++++++++++++++++++++++-- 3 files changed, 90 insertions(+), 5 deletions(-) diff --git a/compose.yaml b/compose.yaml index e12ca318..2f4d322e 100644 --- a/compose.yaml +++ b/compose.yaml @@ -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: diff --git a/src/app/main.py b/src/app/main.py index a0c63d3c..1073e238 100644 --- a/src/app/main.py +++ b/src/app/main.py @@ -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"), diff --git a/src/app/storage/db.py b/src/app/storage/db.py index 1beb6fcb..06ac4a0d 100644 --- a/src/app/storage/db.py +++ b/src/app/storage/db.py @@ -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() \ No newline at end of file + 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") \ No newline at end of file