Files
mtusi2026lab4/app/db.py
T
RainakandClaude Opus 5.5 2dca5c114b ЛР4 БВТ2304 Запорожец на 3
Вложения: приватный S3-bucket (RustFS 1.0.4) + метаданные в PostgreSQL, upload PNG/JPEG
с лимитами до декодирования, авторизованный download, attachment_ids в сообщениях,
идемпотентный bootstrap bucket, failover/persistence/S3-down тесты и REPORT.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 18:49:12 +03:00

66 lines
2.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Ограниченный пул соединений 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