ЛР3 БВТ2304 Запорожец на 4

HAProxy + 2 API-реплики, общие PostgreSQL/Valkey, обязательный Idempotency-Key,
graceful drain по SIGTERM, stop-one/restart/rolling-update, серии отказов и REPORT.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-05 17:36:07 +03:00
co-authored by Claude Opus 5.5
parent 0ab3a341aa
commit 95556845e6
46 changed files with 4300 additions and 16 deletions
+65
View File
@@ -0,0 +1,65 @@
"""Ограниченный пул соединений asyncpg и перевод сбоев БД в 503."""
import asyncio
from contextlib import asynccontextmanager
import asyncpg
from .config import Settings
from .errors import unavailable
# Ошибки "БД недоступна/перегружена" -> 503, а не 500 и тем более не пропуск запроса.
DB_UNAVAILABLE = (
OSError,
asyncio.TimeoutError,
asyncpg.PostgresConnectionError,
asyncpg.InterfaceError,
asyncpg.CannotConnectNowError,
asyncpg.TooManyConnectionsError,
asyncpg.QueryCanceledError, # statement_timeout
asyncpg.AdminShutdownError,
)
class Database:
def __init__(self, settings: Settings):
self.settings = settings
self.pool: asyncpg.Pool | None = None
async def start(self) -> None:
s = self.settings
# min_size соединений создаётся лениво (connect при первом acquire), поэтому API стартует
# даже при недоступной БД и честно отвечает 503 в /health/ready.
self.pool = asyncpg.create_pool(
s.database_url,
min_size=0,
max_size=s.db_pool_max,
timeout=3, # таймаут установления соединения
command_timeout=s.db_statement_timeout_ms / 1000 + 1,
max_inactive_connection_lifetime=300,
server_settings={
'application_name': 'messenger-api',
'statement_timeout': str(s.db_statement_timeout_ms),
'idle_in_transaction_session_timeout': '10000',
'timezone': 'UTC',
},
)
await self.pool
async def close(self) -> None:
if self.pool is not None:
await self.pool.close()
@asynccontextmanager
async def connection(self):
try:
async with self.pool.acquire(timeout=self.settings.db_acquire_timeout) as conn:
yield conn
except DB_UNAVAILABLE:
raise unavailable() from None
async def ping(self) -> bool:
try:
async with self.pool.acquire(timeout=1) as conn:
return await conn.fetchval('SELECT 1', timeout=1) == 1
except DB_UNAVAILABLE:
return False