RabbitMQ (quorum queue, publisher confirms, manual ack, DLX) + отдельный worker: staging в S3 + вложение/job/outbox одной транзакцией -> 202 queued; relay outbox, lease с heartbeat и fencing (worker_id, attempt), retry с backoff+jitter, failed-реестр, безопасный replay с audit; thumbnail/crop/WebP в изолированном процессе с лимитами. Тесты окон отказа (fault injection), трек 1 «Очередь под перегрузкой» с backpressure. Перенесено исправление замечания lab3 PR #99 (U+0000 в тексте). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
66 lines
2.3 KiB
Python
66 lines
2.3 KiB
Python
"""Ограниченный пул соединений 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
|