ЛР5 БВТ2304 Запорожец на 5
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>
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
"""Запуск: python -m app (HTTP-процесс — PID 1 в контейнере).
|
||||
|
||||
SIGTERM (docker stop) обрабатывается в два этапа:
|
||||
1. drain: SHUTDOWN_DRAIN_MS процесс продолжает обслуживать запросы, но /health/ready отвечает 503 —
|
||||
балансировщик за это время исключает реплику по активной проверке и перестаёт слать новые запросы;
|
||||
2. обычный graceful shutdown uvicorn: новые соединения не принимаются, начатые запросы
|
||||
дообрабатываются до timeout_graceful_shutdown.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
|
||||
import uvicorn
|
||||
|
||||
from . import lifecycle
|
||||
|
||||
log = logging.getLogger('messenger')
|
||||
|
||||
|
||||
class DrainingServer(uvicorn.Server):
|
||||
drain_seconds = 0.0
|
||||
|
||||
def handle_exit(self, sig, frame):
|
||||
if lifecycle.draining or self.drain_seconds <= 0:
|
||||
# Повторный сигнал (или drain выключен) — сразу штатное завершение uvicorn.
|
||||
return super().handle_exit(sig, frame)
|
||||
lifecycle.start_draining()
|
||||
log.info('signal %s: draining for %.1fs before shutdown, instance=%s',
|
||||
sig, self.drain_seconds, lifecycle.INSTANCE_ID)
|
||||
timer = threading.Timer(self.drain_seconds, super().handle_exit, (sig, frame))
|
||||
timer.daemon = True
|
||||
timer.start()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(name)s %(message)s')
|
||||
config = uvicorn.Config('app.main:app', host=os.environ.get('APP_HOST', '0.0.0.0'),
|
||||
port=int(os.environ.get('APP_PORT', '8080')), proxy_headers=False,
|
||||
server_header=False, timeout_graceful_shutdown=10,
|
||||
timeout_keep_alive=30) # дольше, чем держит idle-соединение HAProxy
|
||||
server = DrainingServer(config)
|
||||
server.drain_seconds = int(os.environ.get('SHUTDOWN_DRAIN_MS', '3000')) / 1000
|
||||
log.info('starting instance %s', lifecycle.INSTANCE_ID)
|
||||
server.run()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,39 @@
|
||||
"""RabbitMQ: топология очередей заданий. Объявление идемпотентно — его выполняют и API (relay), и worker.
|
||||
|
||||
attachments (direct, durable) --attachment.process.v1--> quorum queue attachment.process.v1
|
||||
отклонённые/непарсящиеся и превысившие x-delivery-limit сообщения
|
||||
--> attachments.dlx --> quorum queue attachment.process.v1.dlq (просмотр оператором)
|
||||
|
||||
Quorum queue: сообщения реплицируются в Raft-журнал на диске (volume rabbitdata) и переживают рестарт
|
||||
брокера; persistent delivery_mode + publisher confirm у publisher; manual ack у consumer.
|
||||
"""
|
||||
import aio_pika
|
||||
from aio_pika import ExchangeType
|
||||
|
||||
EXCHANGE = 'attachments'
|
||||
DLX = 'attachments.dlx'
|
||||
QUEUE = 'attachment.process.v1'
|
||||
DLQ = 'attachment.process.v1.dlq'
|
||||
ROUTING_KEY = 'attachment.process.v1'
|
||||
# Защита от poison message, который валит worker до ack: после N доставок — в DLQ.
|
||||
# Состояние в БД при этом не теряется: reaper/sweeper вернёт работу по lease (см. app/outbox.py).
|
||||
DELIVERY_LIMIT = 20
|
||||
|
||||
|
||||
async def connect(url: str) -> aio_pika.abc.AbstractRobustConnection:
|
||||
return await aio_pika.connect_robust(url, timeout=5, client_properties={'connection_name': 'messenger'})
|
||||
|
||||
|
||||
async def declare(channel: aio_pika.abc.AbstractChannel):
|
||||
dlx = await channel.declare_exchange(DLX, ExchangeType.DIRECT, durable=True)
|
||||
dlq = await channel.declare_queue(DLQ, durable=True, arguments={'x-queue-type': 'quorum'})
|
||||
await dlq.bind(dlx, ROUTING_KEY)
|
||||
exchange = await channel.declare_exchange(EXCHANGE, ExchangeType.DIRECT, durable=True)
|
||||
queue = await channel.declare_queue(QUEUE, durable=True, arguments={
|
||||
'x-queue-type': 'quorum',
|
||||
'x-dead-letter-exchange': DLX,
|
||||
'x-dead-letter-routing-key': ROUTING_KEY,
|
||||
'x-delivery-limit': DELIVERY_LIMIT,
|
||||
})
|
||||
await queue.bind(exchange, ROUTING_KEY)
|
||||
return exchange, queue
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
"""Настройки из переменных окружения. Секреты читаются только из файлов (*_FILE)."""
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _int(name: str, default: int, low: int, high: int) -> int:
|
||||
value = int(os.environ.get(name, default))
|
||||
if not low <= value <= high:
|
||||
raise ValueError(f'{name} must be in [{low}, {high}]')
|
||||
return value
|
||||
|
||||
|
||||
def _secret(name: str) -> str | None:
|
||||
"""Значение из файла, путь к которому лежит в переменной NAME_FILE."""
|
||||
path = os.environ.get(name + '_FILE')
|
||||
if not path:
|
||||
return None
|
||||
return Path(path).read_text(encoding='utf-8').strip()
|
||||
|
||||
|
||||
def _required_secret(name: str) -> str:
|
||||
value = _secret(name)
|
||||
if not value:
|
||||
raise RuntimeError(f'{name}_FILE is not configured')
|
||||
return value
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
host: str
|
||||
port: int
|
||||
session_ttl: int
|
||||
session_store: str
|
||||
session_cache_ttl: int
|
||||
database_url: str
|
||||
cache_url: str | None
|
||||
db_pool_max: int
|
||||
db_statement_timeout_ms: int
|
||||
db_acquire_timeout: float
|
||||
cache_timeout: float
|
||||
hash_workers: int
|
||||
idempotency_ttl: int
|
||||
drain_seconds: float
|
||||
s3_endpoint: str
|
||||
s3_region: str
|
||||
s3_bucket: str
|
||||
s3_access_key: str
|
||||
s3_secret_key: str
|
||||
s3_timeout: float
|
||||
max_upload_bytes: int
|
||||
max_image_pixels: int
|
||||
image_workers: int
|
||||
broker_url: str
|
||||
worker_concurrency: int
|
||||
worker_prefetch: int
|
||||
job_max_attempts: int
|
||||
job_timeout: int
|
||||
job_lease: int
|
||||
retry_base_ms: int
|
||||
retry_max_ms: int
|
||||
staging_retention: int
|
||||
max_pending_jobs: int
|
||||
outbox_poll_ms: int
|
||||
worker_memory_mb: int
|
||||
worker_max_pixels: int
|
||||
|
||||
|
||||
def load() -> Settings:
|
||||
database_url = _secret('DATABASE_URL') or os.environ.get('DATABASE_URL')
|
||||
if not database_url:
|
||||
raise RuntimeError('DATABASE_URL_FILE is not configured')
|
||||
store = os.environ.get('SESSION_STORE', 'postgres')
|
||||
if store not in ('postgres', 'postgres+valkey'):
|
||||
raise ValueError('SESSION_STORE must be postgres or postgres+valkey')
|
||||
cache_url = _secret('CACHE_URL') if store == 'postgres+valkey' else None
|
||||
return Settings(
|
||||
host=os.environ.get('APP_HOST', '0.0.0.0'),
|
||||
port=_int('APP_PORT', 8080, 1, 65535),
|
||||
session_ttl=_int('SESSION_TTL_SECONDS', 3600, 1, 30 * 24 * 3600),
|
||||
session_store=store,
|
||||
session_cache_ttl=_int('SESSION_CACHE_TTL_SECONDS', 60, 1, 3600),
|
||||
database_url=database_url,
|
||||
cache_url=cache_url,
|
||||
db_pool_max=_int('DB_POOL_MAX', 10, 1, 100),
|
||||
db_statement_timeout_ms=_int('DB_STATEMENT_TIMEOUT_MS', 5000, 100, 600000),
|
||||
db_acquire_timeout=_int('DB_ACQUIRE_TIMEOUT_MS', 2000, 100, 60000) / 1000,
|
||||
cache_timeout=_int('CACHE_TIMEOUT_MS', 300, 10, 10000) / 1000,
|
||||
hash_workers=_int('PASSWORD_HASH_WORKERS', 4, 1, 32),
|
||||
idempotency_ttl=_int('IDEMPOTENCY_TTL_SECONDS', 86400, 86400, 30 * 24 * 3600), # контракт: не менее 24 ч
|
||||
drain_seconds=_int('SHUTDOWN_DRAIN_MS', 3000, 0, 60000) / 1000,
|
||||
s3_endpoint=os.environ.get('S3_ENDPOINT', 'http://s3:9000'),
|
||||
s3_region=os.environ.get('S3_REGION', 'us-east-1'),
|
||||
s3_bucket=os.environ.get('S3_BUCKET', 'messenger-attachments'),
|
||||
s3_access_key=_required_secret('S3_ACCESS_KEY_ID'),
|
||||
s3_secret_key=_required_secret('S3_SECRET_ACCESS_KEY'),
|
||||
s3_timeout=_int('S3_TIMEOUT_MS', 5000, 100, 12000) / 1000, # < timeout server HAProxy (15 с)
|
||||
# Контракт: не более 10 MiB и 40 млн пикселей; значения можно только уменьшить.
|
||||
max_upload_bytes=_int('MAX_UPLOAD_BYTES', 10485760, 1, 10485760),
|
||||
max_image_pixels=_int('MAX_IMAGE_PIXELS', 40_000_000, 1, 40_000_000),
|
||||
image_workers=_int('IMAGE_CHECK_WORKERS', 2, 1, 16),
|
||||
# lab5: брокер, worker, повторы, backpressure
|
||||
broker_url=_required_secret('BROKER_URL'),
|
||||
worker_concurrency=_int('WORKER_CONCURRENCY', 2, 1, 32),
|
||||
worker_prefetch=_int('WORKER_PREFETCH', int(os.environ.get('WORKER_CONCURRENCY', 2)), 1, 256),
|
||||
job_max_attempts=_int('JOB_MAX_ATTEMPTS', 5, 1, 50),
|
||||
job_timeout=_int('JOB_TIMEOUT_SECONDS', 60, 5, 3600), # жёсткий лимит одной попытки
|
||||
job_lease=_int('JOB_LEASE_SECONDS', 15, 3, 600), # аренда, продлевается heartbeat
|
||||
retry_base_ms=_int('RETRY_BASE_MS', 1000, 10, 600000),
|
||||
retry_max_ms=_int('RETRY_MAX_MS', 60000, 10, 3600000),
|
||||
staging_retention=_int('STAGING_RETENTION_SECONDS', 86400, 60, 30 * 86400),
|
||||
max_pending_jobs=_int('MAX_PENDING_JOBS', 200, 1, 1000000),
|
||||
outbox_poll_ms=_int('OUTBOX_POLL_MS', 500, 50, 60000),
|
||||
worker_memory_mb=_int('WORKER_TASK_MEMORY_MB', 512, 64, 8192),
|
||||
worker_max_pixels=_int('MAX_IMAGE_PIXELS', 40_000_000, 1, 40_000_000),
|
||||
)
|
||||
@@ -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
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Единый формат ошибок {"error":{"code","message","request_id"}}."""
|
||||
from contextvars import ContextVar
|
||||
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
request_id_var: ContextVar[str] = ContextVar('request_id', default='-')
|
||||
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status: int, code: str, message: str, headers: dict | None = None):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
def invalid(message: str = 'Некорректный запрос') -> ApiError:
|
||||
return ApiError(400, 'invalid_request', message)
|
||||
|
||||
|
||||
def not_found() -> ApiError:
|
||||
# Одинаковый ответ для "нет такого" и "чужое": существование чужого чата не раскрывается.
|
||||
return ApiError(404, 'not_found', 'Объект не найден')
|
||||
|
||||
|
||||
def unauthorized_bearer() -> ApiError:
|
||||
return ApiError(401, 'unauthorized', 'Требуется действительная сессия', {'WWW-Authenticate': BEARER_CHALLENGE})
|
||||
|
||||
|
||||
def unauthorized_basic() -> ApiError:
|
||||
return ApiError(401, 'unauthorized', 'Неверные учётные данные', {'WWW-Authenticate': BASIC_CHALLENGE})
|
||||
|
||||
|
||||
def unavailable() -> ApiError:
|
||||
return ApiError(503, 'unavailable', 'Сервис временно недоступен')
|
||||
|
||||
|
||||
def error_response(status: int, code: str, message: str, headers: dict | None = None) -> JSONResponse:
|
||||
rid = request_id_var.get()
|
||||
return JSONResponse(
|
||||
status_code=status,
|
||||
content={'error': {'code': code, 'message': message, 'request_id': rid}},
|
||||
headers=headers,
|
||||
)
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Точки внедрения отказов для тестов окон отказа (contracts/attachment-states.md).
|
||||
|
||||
Точка активируется файлом /tmp/fault-<name> внутри контейнера (tmpfs; создаётся тестом через
|
||||
`docker exec -u 10001 <c> touch /tmp/fault-<name>`). Срабатывает один раз: файл удаляется, процесс
|
||||
завершается os._exit — без finally, ack, закрытия соединений, как при kill -9. Docker перезапускает
|
||||
контейнер (restart: unless-stopped), tmpfs при этом пустой. В обычной работе файлов нет — это no-op.
|
||||
|
||||
Точки:
|
||||
api_crash_after_commit API: после COMMIT вложения+job+outbox, до ответа 202 и до publish;
|
||||
worker_crash_after_s3 worker: варианты и оригинал записаны в S3, COMMIT результата ещё нет;
|
||||
worker_crash_after_commit worker: результат зафиксирован (ready), ack брокеру ещё не отправлен.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
|
||||
log = logging.getLogger('messenger.faults')
|
||||
|
||||
|
||||
def hit(name: str) -> None:
|
||||
path = f'/tmp/fault-{name}'
|
||||
if not os.path.exists(path):
|
||||
return
|
||||
try:
|
||||
os.remove(path)
|
||||
except OSError:
|
||||
pass
|
||||
log.error('FAULT INJECTION %s: hard exit', name)
|
||||
os._exit(86)
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
"""Приём изображения: ограниченное чтение тела и проверка PNG/JPEG по содержимому.
|
||||
|
||||
Порядок выбран так, чтобы ни один лимит не проверялся ПОСЛЕ дорогой операции:
|
||||
1. Content-Length больше лимита -> 413 сразу, тело не читается;
|
||||
2. чтение потоком с обрывом на MAX_UPLOAD_BYTES + 1 байте (chunked без длины тоже ограничен);
|
||||
3. сигнатура (magic bytes) -> тип; несовпадение с Content-Type или чужой формат -> 415;
|
||||
4. размеры из заголовка изображения (Pillow читает только header) -> > MAX_IMAGE_PIXELS -> 413
|
||||
ДО распаковки пикселей (защита от decompression bomb);
|
||||
5. только потом проверка целостности: PNG verify() (CRC чанков), JPEG — декодирование в draft-режиме 1/8.
|
||||
"""
|
||||
import asyncio
|
||||
import io
|
||||
import warnings
|
||||
|
||||
from fastapi import Request
|
||||
from PIL import Image
|
||||
|
||||
from .errors import ApiError
|
||||
|
||||
# Лимит пикселей проверяем сами (п.4) с нужным кодом ответа; встроенный в Pillow оставляем как страховку.
|
||||
Image.MAX_IMAGE_PIXELS = 40_000_000
|
||||
Image.LOAD_TRUNCATED_IMAGES = False
|
||||
|
||||
SIGNATURES = {
|
||||
'image/png': b'\x89PNG\r\n\x1a\n',
|
||||
'image/jpeg': b'\xff\xd8\xff',
|
||||
}
|
||||
PIL_FORMATS = {'image/png': 'PNG', 'image/jpeg': 'JPEG'}
|
||||
|
||||
|
||||
def too_large(message: str = 'Файл превышает лимит') -> ApiError:
|
||||
return ApiError(413, 'payload_too_large', message)
|
||||
|
||||
|
||||
def unsupported(message: str = 'Ожидается корректное изображение PNG или JPEG') -> ApiError:
|
||||
return ApiError(415, 'unsupported_media_type', message)
|
||||
|
||||
|
||||
def declared_type(request: Request) -> str:
|
||||
media_type = request.headers.get('content-type', '').split(';')[0].strip().lower()
|
||||
if media_type not in SIGNATURES:
|
||||
raise unsupported('Content-Type должен быть image/png или image/jpeg')
|
||||
return media_type
|
||||
|
||||
|
||||
async def read_limited(request: Request, limit: int) -> bytes:
|
||||
length = request.headers.get('content-length')
|
||||
if length is not None and length.isdigit() and int(length) > limit:
|
||||
raise too_large()
|
||||
buf = bytearray()
|
||||
async for chunk in request.stream():
|
||||
buf += chunk
|
||||
if len(buf) > limit:
|
||||
raise too_large()
|
||||
return bytes(buf)
|
||||
|
||||
|
||||
class ImageChecker:
|
||||
def __init__(self, max_pixels: int, workers: int):
|
||||
self.max_pixels = max_pixels
|
||||
# Не больше N одновременных проверок на реплику: декодирование занимает CPU и память.
|
||||
self.slots = asyncio.Semaphore(workers)
|
||||
|
||||
async def inspect(self, data: bytes, declared: str) -> tuple[str, int, int]:
|
||||
detected = next((t for t, sig in SIGNATURES.items() if data.startswith(sig)), None)
|
||||
if detected is None or detected != declared:
|
||||
raise unsupported()
|
||||
async with self.slots:
|
||||
return await asyncio.to_thread(self._inspect, data, detected)
|
||||
|
||||
def _inspect(self, data: bytes, content_type: str) -> tuple[str, int, int]:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter('error', Image.DecompressionBombWarning)
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data)) # ленивый: читает только заголовок
|
||||
width, height = img.size
|
||||
if img.format != PIL_FORMATS[content_type]:
|
||||
raise unsupported()
|
||||
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
raise too_large('Изображение превышает лимит пикселей') from None
|
||||
except ApiError:
|
||||
raise
|
||||
except Exception:
|
||||
raise unsupported() from None
|
||||
if width <= 0 or height <= 0:
|
||||
raise unsupported()
|
||||
if width * height > self.max_pixels:
|
||||
raise too_large('Изображение превышает лимит пикселей')
|
||||
try:
|
||||
if content_type == 'image/png':
|
||||
img.verify() # CRC и структура чанков без хранения пикселей
|
||||
check_png_pixel_stream(data) # объём пиксельных данных совпадает с IHDR
|
||||
else:
|
||||
img.draft('RGB', (max(1, width // 8), max(1, height // 8)))
|
||||
img.load() # обрезанный/битый JPEG -> исключение
|
||||
except Exception:
|
||||
raise unsupported() from None
|
||||
finally:
|
||||
img.close()
|
||||
return content_type, width, height
|
||||
|
||||
|
||||
# ---------- PNG: потоковая проверка пиксельных данных ----------
|
||||
# verify() Pillow проверяет только CRC чанков. Файл с честным IHDR 6000x6000 и почти пустым IDAT он
|
||||
# пропустит. Полное декодирование 40 Мпикс заняло бы 160 MiB на запрос, поэтому IDAT распаковывается
|
||||
# потоково кусками по 64 KiB: считаются только байты, пиксели не хранятся. Распакованный объём должен
|
||||
# точно совпасть с вычисленным по IHDR, иначе файл повреждён (или это zip-бомба сверх заявленного).
|
||||
|
||||
CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
|
||||
ADAM7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2))
|
||||
|
||||
|
||||
def _row_bytes(width: int, bits_per_pixel: int) -> int:
|
||||
return (width * bits_per_pixel + 7) // 8
|
||||
|
||||
|
||||
def expected_png_raw_size(width: int, height: int, bit_depth: int, color_type: int, interlace: int) -> int:
|
||||
bpp = CHANNELS[color_type] * bit_depth
|
||||
if not interlace:
|
||||
return height * (1 + _row_bytes(width, bpp))
|
||||
total = 0
|
||||
for xs, ys, dx, dy in ADAM7:
|
||||
pw = (width - xs + dx - 1) // dx if width > xs else 0
|
||||
ph = (height - ys + dy - 1) // dy if height > ys else 0
|
||||
if pw and ph:
|
||||
total += ph * (1 + _row_bytes(pw, bpp))
|
||||
return total
|
||||
|
||||
|
||||
def check_png_pixel_stream(data: bytes) -> None:
|
||||
import struct
|
||||
import zlib
|
||||
pos, expected, produced = 8, None, 0
|
||||
inflater = zlib.decompressobj()
|
||||
while pos + 8 <= len(data):
|
||||
length, kind = struct.unpack('>I4s', data[pos:pos + 8])
|
||||
body = data[pos + 8:pos + 8 + length]
|
||||
pos += 12 + length
|
||||
if kind == b'IHDR':
|
||||
width, height, bit_depth, color_type, _c, _f, interlace = struct.unpack('>IIBBBBB', body)
|
||||
expected = expected_png_raw_size(width, height, bit_depth, color_type, interlace)
|
||||
elif kind == b'IDAT':
|
||||
if expected is None:
|
||||
raise ValueError('IDAT before IHDR')
|
||||
chunk = body
|
||||
while chunk:
|
||||
out = inflater.decompress(chunk, 64 * 1024)
|
||||
produced += len(out)
|
||||
if produced > expected:
|
||||
raise ValueError('pixel data larger than IHDR')
|
||||
chunk = inflater.unconsumed_tail
|
||||
elif kind == b'IEND':
|
||||
break
|
||||
produced += len(inflater.flush())
|
||||
if expected is None or produced != expected or not inflater.eof:
|
||||
raise ValueError('pixel data does not match IHDR')
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
"""Построение вариантов изображения (выполняется worker-ом в отдельном дочернем процессе).
|
||||
|
||||
Контракт (contracts/README.md, «Фоновая обработка»):
|
||||
- thumbnail: JPEG, вписан в 256x256 с сохранением пропорций, без увеличения, EXIF orientation применяется,
|
||||
alpha компонуется на белый, размеры округляются вниз, минимум 1 px (320x200 -> 256x160);
|
||||
- crop: JPEG, центрированный квадрат 128x128 (маленький исходник увеличивается);
|
||||
- optimized: WebP, вписан в 1280x1280 без увеличения.
|
||||
|
||||
Параметры: JPEG quality=85 (thumbnail, crop), optimize=True, progressive=False; WebP quality=80, method=4.
|
||||
Метаданные удаляются: EXIF/ICC/XMP не передаются в save() (Pillow не копирует их без явного exif=/icc_profile=),
|
||||
ориентация EXIF уже применена к пикселям. Все варианты — 8-bit sRGB без alpha.
|
||||
|
||||
Ограничения ресурсов: лимит пикселей проверяется по заголовку ДО декодирования; JPEG декодируется в draft-
|
||||
режиме с уменьшением до ближайшего масштаба >= 1280 (меньше памяти и CPU); процесс запускается с RLIMIT_AS
|
||||
(память) и убивается по таймауту (время) — см. run_isolated().
|
||||
"""
|
||||
import asyncio
|
||||
import hashlib
|
||||
import io
|
||||
import multiprocessing
|
||||
import resource
|
||||
import warnings
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
THUMB = 256
|
||||
CROP = 128
|
||||
OPTIMIZED = 1280
|
||||
|
||||
|
||||
class PermanentImageError(Exception):
|
||||
def __init__(self, code: str):
|
||||
super().__init__(code)
|
||||
self.code = code
|
||||
|
||||
|
||||
class TransientImageError(Exception):
|
||||
def __init__(self, code: str):
|
||||
super().__init__(code)
|
||||
self.code = code
|
||||
|
||||
|
||||
def fit(width: int, height: int, box: int) -> tuple[int, int]:
|
||||
"""Вписать в box x box без увеличения; целочисленно, округление вниз, минимум 1 px."""
|
||||
m = max(width, height)
|
||||
if m <= box:
|
||||
return width, height
|
||||
return max(1, width * box // m), max(1, height * box // m)
|
||||
|
||||
|
||||
def flatten(img: Image.Image) -> Image.Image:
|
||||
"""Alpha (RGBA/LA/P с прозрачностью) компонуется на белый фон; результат RGB."""
|
||||
if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
|
||||
rgba = img.convert('RGBA')
|
||||
background = Image.new('RGB', rgba.size, (255, 255, 255))
|
||||
background.paste(rgba, mask=rgba.getchannel('A'))
|
||||
return background
|
||||
if img.mode in ('I;16', 'I;16B', 'I;16L', 'I'):
|
||||
img = img.point(lambda v: v / 256).convert('L') # 16-bit серый -> 8-bit
|
||||
return img.convert('RGB')
|
||||
|
||||
|
||||
def encode(name: str, img: Image.Image, fmt: str, content_type: str, **params) -> dict:
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, fmt, **params)
|
||||
data = buf.getvalue()
|
||||
return {'name': name, 'content_type': content_type, 'width': img.width, 'height': img.height,
|
||||
'size_bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest(), 'data': data}
|
||||
|
||||
|
||||
def build_variants(data: bytes, max_pixels: int) -> list[dict]:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter('error', Image.DecompressionBombWarning)
|
||||
Image.MAX_IMAGE_PIXELS = max_pixels
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data))
|
||||
width, height = img.size
|
||||
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
raise PermanentImageError('image_too_large') from None
|
||||
except Exception:
|
||||
raise PermanentImageError('invalid_image') from None
|
||||
if img.format not in ('PNG', 'JPEG'):
|
||||
raise PermanentImageError('invalid_image')
|
||||
if width * height > max_pixels:
|
||||
raise PermanentImageError('image_too_large')
|
||||
try:
|
||||
if img.format == 'JPEG':
|
||||
img.draft('RGB', (OPTIMIZED, OPTIMIZED)) # декодер сам уменьшает в 2/4/8 раз, если можно
|
||||
img.load()
|
||||
img = ImageOps.exif_transpose(img)
|
||||
rgb = flatten(img)
|
||||
except MemoryError:
|
||||
raise
|
||||
except Exception:
|
||||
raise PermanentImageError('invalid_image') from None
|
||||
|
||||
# Размеры считаются от ориентированного ОРИГИНАЛА (не от draft-копии), иначе draft менял бы результат.
|
||||
ow, oh = _oriented_size(data, width, height)
|
||||
variants = []
|
||||
tw, th = fit(ow, oh, THUMB)
|
||||
variants.append(encode('thumbnail', rgb.resize((tw, th), Image.LANCZOS) if (tw, th) != rgb.size else rgb,
|
||||
'JPEG', 'image/jpeg', quality=85, optimize=True))
|
||||
side = min(rgb.size)
|
||||
left, top = (rgb.width - side) // 2, (rgb.height - side) // 2
|
||||
square = rgb.crop((left, top, left + side, top + side))
|
||||
variants.append(encode('crop', square.resize((CROP, CROP), Image.LANCZOS), 'JPEG', 'image/jpeg',
|
||||
quality=85, optimize=True))
|
||||
pw, ph = fit(ow, oh, OPTIMIZED)
|
||||
variants.append(encode('optimized', rgb.resize((pw, ph), Image.LANCZOS) if (pw, ph) != rgb.size else rgb,
|
||||
'WEBP', 'image/webp', quality=80, method=4))
|
||||
return variants
|
||||
|
||||
|
||||
def _orientation(data: bytes) -> int:
|
||||
try:
|
||||
return Image.open(io.BytesIO(data)).getexif().get(0x0112, 1)
|
||||
except Exception:
|
||||
return 1
|
||||
|
||||
|
||||
def _rotated(data: bytes) -> bool:
|
||||
return _orientation(data) in (5, 6, 7, 8)
|
||||
|
||||
|
||||
def _oriented_size(data: bytes, width: int, height: int) -> tuple[int, int]:
|
||||
"""Размер оригинала после применения EXIF orientation (5–8 меняют местами ширину и высоту)."""
|
||||
return (height, width) if _rotated(data) else (width, height)
|
||||
|
||||
|
||||
# ---------- изоляция: отдельный процесс с лимитом памяти и времени ----------
|
||||
|
||||
def _child(conn, data: bytes, max_pixels: int, memory_mb: int) -> None:
|
||||
limit = memory_mb * 1024 * 1024
|
||||
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
|
||||
try:
|
||||
conn.send(('ok', build_variants(data, max_pixels)))
|
||||
except PermanentImageError as exc:
|
||||
conn.send(('permanent', exc.code))
|
||||
except MemoryError:
|
||||
conn.send(('permanent', 'resource_limit'))
|
||||
except Exception:
|
||||
conn.send(('permanent', 'processing_failed'))
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
_ctx = multiprocessing.get_context('forkserver')
|
||||
# Preload app.worker: forkserver один раз импортирует главный модуль worker со всеми зависимостями
|
||||
# (aio-pika, jsonschema, minio, asyncpg, Pillow), дочерние процессы получают их готовыми через fork.
|
||||
# Без этого каждый запуск обработки заново импортировал app.worker (при `python -m` multiprocessing
|
||||
# восстанавливает __main__ по имени модуля): 0.7–2.3 с накладных расходов на задание при 0.07 с полезной
|
||||
# работы для 320x200 — найдено в эксперименте трека 1 (evidence/track1/, раздел «Итерация 1» в REPORT.md).
|
||||
# '__main__' по пути здесь не работает: при запуске через -m пути к главному модулю нет.
|
||||
_ctx.set_forkserver_preload(['app.worker', 'app.imaging'])
|
||||
|
||||
|
||||
async def run_isolated(data: bytes, max_pixels: int, memory_mb: int, timeout: float) -> list[dict]:
|
||||
"""Варианты строятся в дочернем процессе: зависание/бомба памяти не роняют и не блокируют worker.
|
||||
|
||||
Таймаут -> процесс убивается, TransientImageError('processing_timeout') (мог помешать перегруз CPU —
|
||||
повтор с backoff; при исчерпании попыток — failed retry_exhausted).
|
||||
RLIMIT_AS/смерть процесса -> PermanentImageError('resource_limit').
|
||||
"""
|
||||
parent, child = _ctx.Pipe(duplex=False)
|
||||
proc = _ctx.Process(target=_child, args=(child, data, max_pixels, memory_mb), daemon=True)
|
||||
proc.start()
|
||||
child.close()
|
||||
loop = asyncio.get_running_loop()
|
||||
try:
|
||||
ready = await loop.run_in_executor(None, parent.poll, timeout)
|
||||
if not ready:
|
||||
raise TransientImageError('processing_timeout')
|
||||
try:
|
||||
status, value = await loop.run_in_executor(None, parent.recv)
|
||||
except EOFError:
|
||||
raise PermanentImageError('resource_limit') from None
|
||||
finally:
|
||||
if proc.is_alive():
|
||||
proc.kill()
|
||||
await loop.run_in_executor(None, proc.join, 5)
|
||||
parent.close()
|
||||
if status == 'ok':
|
||||
return value
|
||||
raise PermanentImageError(value)
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
"""Общие операции над заданиями обработки вложений (API, relay, worker, replay).
|
||||
|
||||
Все переходы состояний выполняются SQL-транзакциями в PostgreSQL — это источник истины о работе.
|
||||
Брокер только доставляет "напоминание" (job_id), поэтому потеря/дубль сообщения не теряет и не
|
||||
дублирует эффект: worker всегда сверяется с attachment_jobs.
|
||||
"""
|
||||
import json
|
||||
import random
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
PIPELINE_VERSION = 1
|
||||
JOB_TYPE = 'attachment.process.v1'
|
||||
|
||||
|
||||
def payload(job_id: uuid.UUID, attachment_id: uuid.UUID, attempt: int) -> dict:
|
||||
"""Сообщение по contracts/jobs.schema.json: только ID и служебные поля — без bytes, URL и credentials."""
|
||||
return {
|
||||
'schema_version': 1,
|
||||
'job_id': str(job_id),
|
||||
'type': JOB_TYPE,
|
||||
'attachment_id': str(attachment_id),
|
||||
'pipeline_version': PIPELINE_VERSION,
|
||||
'attempt': attempt,
|
||||
'created_at': datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
|
||||
}
|
||||
|
||||
|
||||
def backoff_seconds(attempt: int, base_ms: int, max_ms: int) -> float:
|
||||
"""Экспоненциальный backoff с "equal jitter": половина задержки фиксирована, половина случайна.
|
||||
|
||||
Фиксированная половина не даёт повтору прийти мгновенно (full jitter может дать ~0),
|
||||
случайная — разводит повторы разных заданий после общего сбоя (нет "стада").
|
||||
"""
|
||||
cap = min(max_ms, base_ms * 2 ** max(0, attempt - 1))
|
||||
return (cap / 2 + random.uniform(0, cap / 2)) / 1000
|
||||
|
||||
|
||||
async def enqueue(conn, job_id: uuid.UUID, attachment_id: uuid.UUID, attempt: int, delay_s: float = 0.0) -> None:
|
||||
"""Намерение опубликовать job — строка outbox в ТЕКУЩЕЙ транзакции вызывающего."""
|
||||
await conn.execute(
|
||||
'INSERT INTO outbox (job_id, payload, available_at) '
|
||||
'VALUES ($1, $2::jsonb, clock_timestamp() + make_interval(secs => $3))',
|
||||
job_id, json.dumps(payload(job_id, attachment_id, attempt)), delay_s)
|
||||
|
||||
|
||||
async def create(conn, attachment_id: uuid.UUID, max_attempts: int) -> uuid.UUID:
|
||||
job_id = uuid.uuid4()
|
||||
await conn.execute(
|
||||
'INSERT INTO attachment_jobs (job_id, attachment_id, pipeline_version, max_attempts) VALUES ($1, $2, $3, $4)',
|
||||
job_id, attachment_id, PIPELINE_VERSION, max_attempts)
|
||||
await enqueue(conn, job_id, attachment_id, attempt=1)
|
||||
return job_id
|
||||
|
||||
|
||||
async def requeue(conn, job_id, attachment_id, next_attempt: int, delay_s: float, reason: str,
|
||||
worker_id: str | None = None, attempt: int | None = None) -> bool:
|
||||
"""processing -> queued: временная ошибка (worker) или истёкшая аренда (reaper).
|
||||
|
||||
worker_id/attempt заданы — фиксация от имени владельца аренды (fencing token = worker_id + номер попытки):
|
||||
чужую или уже перехваченную работу не трогаем.
|
||||
"""
|
||||
fence = 'AND worker_id = $4 AND attempt = $5' if worker_id else ''
|
||||
args = [job_id, delay_s, reason[:200]] + ([worker_id, attempt] if worker_id else [])
|
||||
updated = await conn.fetchval(
|
||||
"UPDATE attachment_jobs SET status = 'queued', lease_until = NULL, worker_id = NULL, "
|
||||
"next_attempt_at = clock_timestamp() + make_interval(secs => $2), last_error = $3, "
|
||||
f"updated_at = clock_timestamp() WHERE job_id = $1 AND status = 'processing' {fence} RETURNING 1",
|
||||
*args)
|
||||
if not updated:
|
||||
return False
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'queued', updated_at = clock_timestamp() "
|
||||
"WHERE id = $1 AND status IN ('queued', 'processing')", attachment_id)
|
||||
await enqueue(conn, job_id, attachment_id, next_attempt, delay_s)
|
||||
return True
|
||||
|
||||
|
||||
async def fail(conn, job_id, attachment_id, code: str, reason: str, worker_id: str | None = None,
|
||||
attempt: int | None = None) -> bool:
|
||||
"""-> failed: постоянная ошибка или исчерпаны попытки. Код машинный и безопасный для клиента."""
|
||||
fence = "AND worker_id = $5 AND attempt = $6 AND status = 'processing'" if worker_id else ''
|
||||
args = [job_id, code, reason[:200], attachment_id] + ([worker_id, attempt] if worker_id else [])
|
||||
updated = await conn.fetchval(
|
||||
"UPDATE attachment_jobs SET status = 'failed', lease_until = NULL, error_code = $2, last_error = $3, "
|
||||
"finished_at = clock_timestamp(), updated_at = clock_timestamp() "
|
||||
f"WHERE job_id = $1 AND attachment_id = $4 AND status IN ('queued', 'processing') {fence} RETURNING 1",
|
||||
*args)
|
||||
if not updated:
|
||||
return False
|
||||
# ready никогда не откатывается: условие по статусу.
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'failed', error_code = $2, updated_at = clock_timestamp() "
|
||||
"WHERE id = $1 AND status IN ('queued', 'processing')", attachment_id, code)
|
||||
return True
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Состояние процесса реплики: идентификатор для X-Instance-Id и флаг drain при SIGTERM."""
|
||||
import os
|
||||
import secrets
|
||||
import socket
|
||||
|
||||
# Стабилен в пределах жизни процесса, новый после перезапуска. Префикс — hostname контейнера
|
||||
# (= короткий ID контейнера в Docker), по нему scripts/stop-one.sh находит именно эту реплику.
|
||||
# В lab7 по контракту понадобится непрозрачный alias без hostname.
|
||||
INSTANCE_ID = os.environ.get('INSTANCE_ID') or f'{socket.gethostname()}-{secrets.token_hex(3)}'
|
||||
|
||||
draining = False
|
||||
|
||||
|
||||
def start_draining() -> None:
|
||||
global draining
|
||||
draining = True
|
||||
+588
@@ -0,0 +1,588 @@
|
||||
"""HTTP API мессенджера lab4 по contracts/openapi.json (stateless-реплика за балансировщиком).
|
||||
|
||||
lab4: вложения. Метаданные — PostgreSQL, байты — приватный S3-bucket (RustFS). Локальных файлов у API нет.
|
||||
lab5: upload -> устойчивый staging в S3 + вложение/job/outbox одной транзакцией -> 202 queued;
|
||||
обработку выполняет отдельный worker через RabbitMQ (app/worker.py), публикацию — relay outbox (app/outbox.py).
|
||||
"""
|
||||
import asyncio
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import quote
|
||||
from uuid import UUID
|
||||
|
||||
import asyncpg
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from . import config, faults, images, jobs, lifecycle, pgtext, validation as v
|
||||
from .db import DB_UNAVAILABLE, Database
|
||||
from .errors import (ApiError, error_response, invalid, not_found, request_id_var,
|
||||
unauthorized_basic, unauthorized_bearer, unavailable)
|
||||
from .security import PasswordService, new_token
|
||||
from .outbox import Relay
|
||||
from .sessions import SessionStore
|
||||
from .storage import Storage
|
||||
|
||||
log = logging.getLogger('messenger')
|
||||
settings = config.load()
|
||||
db = Database(settings)
|
||||
sessions = SessionStore(settings, db)
|
||||
passwords = PasswordService(settings.hash_workers)
|
||||
storage = Storage(settings)
|
||||
image_checker = images.ImageChecker(settings.max_image_pixels, settings.image_workers)
|
||||
relay = Relay(settings, db)
|
||||
|
||||
|
||||
async def purge_loop() -> None:
|
||||
while True:
|
||||
await asyncio.sleep(3600)
|
||||
try:
|
||||
removed = await sessions.purge_expired()
|
||||
keys = await purge_idempotency_keys()
|
||||
log.info('purged %d expired sessions, %d idempotency keys', removed, keys)
|
||||
except Exception: # очистка — фоновая гигиена, её сбой не должен ронять процесс
|
||||
log.warning('purge failed', exc_info=True)
|
||||
|
||||
|
||||
async def purge_idempotency_keys() -> int:
|
||||
# Удаление по одному ключу индекса created_at; параллельный запуск на нескольких репликах безопасен.
|
||||
async with db.connection() as conn:
|
||||
status = await conn.execute(
|
||||
'DELETE FROM idempotency_keys WHERE created_at < clock_timestamp() - make_interval(secs => $1)',
|
||||
settings.idempotency_ttl)
|
||||
return int(status.split()[-1])
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
await db.start()
|
||||
task = asyncio.create_task(purge_loop())
|
||||
relay_task = asyncio.create_task(relay.run())
|
||||
yield
|
||||
task.cancel()
|
||||
relay_task.cancel()
|
||||
await relay.close()
|
||||
await sessions.cache.close()
|
||||
await db.close()
|
||||
passwords.close()
|
||||
|
||||
|
||||
app = FastAPI(lifespan=lifespan, openapi_url=None, docs_url=None, redoc_url=None)
|
||||
|
||||
# ---------- request id, ошибки ----------
|
||||
|
||||
REQUEST_ID_RE = re.compile(r'[A-Za-z0-9._:-]{1,128}')
|
||||
|
||||
|
||||
@app.middleware('http')
|
||||
async def request_id_middleware(request: Request, call_next):
|
||||
incoming = request.headers.get('x-request-id', '')
|
||||
rid = incoming if REQUEST_ID_RE.fullmatch(incoming) else uuid.uuid4().hex
|
||||
request_id_var.set(rid)
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
log.exception('unhandled error, request_id=%s', rid)
|
||||
response = error_response(500, 'internal_error', 'Внутренняя ошибка сервера')
|
||||
response.headers['X-Request-Id'] = rid
|
||||
response.headers['X-Instance-Id'] = lifecycle.INSTANCE_ID
|
||||
if lifecycle.draining:
|
||||
# Во время drain закрываем keep-alive: следующий запрос LB откроет соединение уже к живой реплике.
|
||||
response.headers['Connection'] = 'close'
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def api_error_handler(_request: Request, exc: ApiError):
|
||||
return error_response(exc.status, exc.code, exc.message, exc.headers)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_error_handler(_request: Request, exc: StarletteHTTPException):
|
||||
if exc.status_code == 404:
|
||||
return error_response(404, 'not_found', 'Объект не найден')
|
||||
if exc.status_code == 405:
|
||||
return error_response(405, 'invalid_request', 'Метод не поддерживается', dict(exc.headers or {}))
|
||||
return error_response(exc.status_code, 'invalid_request', 'Некорректный запрос')
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error_handler(_request: Request, _exc: RequestValidationError):
|
||||
return error_response(400, 'invalid_request', 'Некорректный запрос')
|
||||
|
||||
|
||||
async def db_unavailable_handler(_request: Request, _exc: Exception):
|
||||
# Страховка: сбой связи с БД вне db.connection() тоже даёт ограниченный 503, а не 500.
|
||||
return error_response(503, 'unavailable', 'Сервис временно недоступен')
|
||||
|
||||
|
||||
for _exc_type in DB_UNAVAILABLE:
|
||||
app.add_exception_handler(_exc_type, db_unavailable_handler)
|
||||
|
||||
# ---------- представление ----------
|
||||
|
||||
|
||||
def ts(value: datetime) -> str:
|
||||
# RFC 3339 UTC с микросекундами: точность совпадает с timestamptz и с ключом пагинации.
|
||||
return value.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%fZ')
|
||||
|
||||
|
||||
def user_json(row) -> dict:
|
||||
return {'id': str(row['id']), 'username': row['username'],
|
||||
'display_name': pgtext.join(row['display_name'], row['display_name_raw']), 'created_at': ts(row['created_at'])}
|
||||
|
||||
|
||||
def chat_json(row) -> dict:
|
||||
return {'id': str(row['id']), 'title': pgtext.join(row['title'], row['title_raw']),
|
||||
'member_ids': [str(m) for m in row['member_ids']], 'created_at': ts(row['created_at'])}
|
||||
|
||||
|
||||
def message_json(row) -> dict:
|
||||
return {'id': str(row['id']), 'chat_id': str(row['chat_id']), 'sender_id': str(row['sender_id']),
|
||||
'text': pgtext.join(row['text'], row['text_raw']), 'created_at': ts(row['created_at']),
|
||||
'attachment_ids': [str(a) for a in row['attachment_ids']]}
|
||||
|
||||
|
||||
def attachment_json(row, variants=()) -> dict:
|
||||
# object_key/staging_key и внутренние адреса S3 в ответ не попадают.
|
||||
return {'id': str(row['id']), 'chat_id': str(row['chat_id']), 'owner_id': str(row['owner_id']),
|
||||
'filename': row['filename'], 'content_type': row['content_type'],
|
||||
'size_bytes': row['size_bytes'], 'sha256': row['sha256'], 'status': row['status'],
|
||||
'variants': [{'name': x['name'], 'content_type': x['content_type'], 'size_bytes': x['size_bytes'],
|
||||
'width': x['width'], 'height': x['height'], 'sha256': x['sha256']} for x in variants],
|
||||
'error_code': row['error_code'],
|
||||
'created_at': ts(row['created_at']), 'updated_at': ts(row['updated_at'])}
|
||||
|
||||
|
||||
USER_COLUMNS = 'id, username, display_name, display_name_raw, created_at'
|
||||
CHAT_COLUMNS = ('c.id, c.title, c.title_raw, c.created_at, '
|
||||
'ARRAY(SELECT cm.user_id FROM chat_members cm WHERE cm.chat_id = c.id ORDER BY cm.user_id) AS member_ids')
|
||||
MESSAGE_ATTACHMENTS = ('ARRAY(SELECT ma.attachment_id FROM message_attachments ma '
|
||||
'WHERE ma.message_id = {m}.id ORDER BY ma.position) AS attachment_ids')
|
||||
MESSAGE_COLUMNS = 'id, chat_id, sender_id, text, text_raw, created_at, ' + MESSAGE_ATTACHMENTS.format(m='messages')
|
||||
ATTACHMENT_COLUMNS = ('a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, '
|
||||
'a.status, a.error_code, a.object_key, a.pipeline_version, a.created_at, a.updated_at')
|
||||
|
||||
# ---------- аутентификация ----------
|
||||
|
||||
TOKEN_RE = re.compile(r'[A-Za-z0-9_-]{32,128}')
|
||||
|
||||
|
||||
def bearer_token(request: Request) -> str:
|
||||
"""Только Authorization: Bearer. X-User-Id и Basic здесь игнорируются/отклоняются."""
|
||||
scheme, _, token = request.headers.get('authorization', '').partition(' ')
|
||||
token = token.strip()
|
||||
if scheme.lower() != 'bearer' or not TOKEN_RE.fullmatch(token):
|
||||
raise unauthorized_bearer()
|
||||
return token
|
||||
|
||||
|
||||
async def current_user(request: Request) -> UUID:
|
||||
session = await sessions.resolve(bearer_token(request))
|
||||
if session is None:
|
||||
raise unauthorized_bearer()
|
||||
return session.user_id
|
||||
|
||||
|
||||
def basic_credentials(request: Request) -> tuple[str, str]:
|
||||
scheme, _, encoded = request.headers.get('authorization', '').partition(' ')
|
||||
if scheme.lower() != 'basic':
|
||||
raise unauthorized_basic()
|
||||
try:
|
||||
decoded = base64.b64decode(encoded.strip(), validate=True)
|
||||
username, sep, password = decoded.partition(b':') # двоеточие допустимо внутри пароля
|
||||
if not sep:
|
||||
raise ValueError
|
||||
return username.decode('ascii'), password.decode('utf-8')
|
||||
except (ValueError, binascii.Error, UnicodeDecodeError):
|
||||
raise unauthorized_basic() from None
|
||||
|
||||
# ---------- health ----------
|
||||
|
||||
|
||||
@app.get('/health/live')
|
||||
async def live():
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
@app.get('/health/ready')
|
||||
async def ready():
|
||||
# Критична только PostgreSQL (источник истины). Valkey — кэш: без него API работает медленнее, но корректно.
|
||||
# Во время drain (получен SIGTERM) реплика честно сообщает LB, что новых запросов ей давать не надо.
|
||||
if lifecycle.draining or not await db.ping():
|
||||
raise unavailable()
|
||||
return {'status': 'ok'}
|
||||
|
||||
# ---------- пользователи и сессии ----------
|
||||
|
||||
|
||||
@app.post('/api/v1/users', status_code=201)
|
||||
async def create_user(request: Request):
|
||||
data = await v.read_json(request)
|
||||
v.fields(data, {'username', 'display_name', 'password'})
|
||||
username = v.username(data)
|
||||
display_name = v.text_field(data, 'display_name', 1, 100)
|
||||
password = v.text_field(data, 'password', 12, 128)
|
||||
password_hash = await passwords.hash(password)
|
||||
try:
|
||||
async with db.connection() as conn:
|
||||
row = await conn.fetchrow(
|
||||
'INSERT INTO users (username, display_name, display_name_raw, password_hash) '
|
||||
f'VALUES ($1, $2, $3, $4) RETURNING {USER_COLUMNS}',
|
||||
username, *pgtext.split(display_name), password_hash)
|
||||
except asyncpg.UniqueViolationError:
|
||||
# Гонка двух одинаковых регистраций решается UNIQUE-индексом: COMMIT пройдёт только у одной.
|
||||
raise ApiError(409, 'conflict', 'username уже занят') from None
|
||||
return JSONResponse(user_json(row), status_code=201)
|
||||
|
||||
|
||||
@app.post('/api/v1/auth/sessions', status_code=201)
|
||||
async def create_session(request: Request):
|
||||
if await request.body():
|
||||
raise invalid('Тело запроса не допускается; используйте Authorization: Basic')
|
||||
username, password = basic_credentials(request)
|
||||
row = None
|
||||
if v.USERNAME_RE.fullmatch(username) and 12 <= len(password) <= 128:
|
||||
async with db.connection() as conn:
|
||||
row = await conn.fetchrow(
|
||||
f'SELECT {USER_COLUMNS}, password_hash FROM users WHERE username = $1', username)
|
||||
# verify выполняется всегда (и для несуществующего пользователя) — одинаковое время ответа.
|
||||
if not await passwords.verify(row['password_hash'] if row else None, password):
|
||||
raise unauthorized_basic()
|
||||
token = new_token()
|
||||
session = await sessions.create(row['id'], token)
|
||||
return JSONResponse({'token': token, 'token_type': 'Bearer', 'expires_at': ts(session.expires_at),
|
||||
'user': user_json(row)}, status_code=201, headers={'Cache-Control': 'no-store'})
|
||||
|
||||
|
||||
@app.delete('/api/v1/auth/sessions/current', status_code=204)
|
||||
async def delete_session(request: Request):
|
||||
token = bearer_token(request)
|
||||
if not await sessions.revoke(token):
|
||||
raise unauthorized_bearer()
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@app.get('/api/v1/users/me')
|
||||
async def me(request: Request):
|
||||
user_id = await current_user(request)
|
||||
async with db.connection() as conn:
|
||||
row = await conn.fetchrow(f'SELECT {USER_COLUMNS} FROM users WHERE id = $1', user_id)
|
||||
if row is None:
|
||||
raise not_found()
|
||||
return user_json(row)
|
||||
|
||||
# ---------- чаты ----------
|
||||
|
||||
|
||||
@app.post('/api/v1/chats', status_code=201)
|
||||
async def create_chat(request: Request):
|
||||
user_id = await current_user(request)
|
||||
data = await v.read_json(request)
|
||||
v.fields(data, {'title', 'member_ids'})
|
||||
title = v.text_field(data, 'title', 1, 100)
|
||||
raw_members = data['member_ids']
|
||||
if not isinstance(raw_members, list) or not 1 <= len(raw_members) <= 100:
|
||||
raise invalid('member_ids должен быть массивом из 1..100 UUID')
|
||||
members = [v.uuid_value(m, 'member_id') for m in raw_members]
|
||||
if len(set(members)) != len(members):
|
||||
raise invalid('member_ids содержит дубликаты')
|
||||
if user_id not in members:
|
||||
raise invalid('Создатель должен входить в member_ids')
|
||||
|
||||
async with db.connection() as conn:
|
||||
# Одна транзакция: чат и все участники появляются вместе или не появляются вовсе.
|
||||
async with conn.transaction():
|
||||
chat = await conn.fetchrow(
|
||||
'INSERT INTO chats (title, title_raw, created_by) VALUES ($1, $2, $3) RETURNING id, created_at',
|
||||
*pgtext.split(title), user_id)
|
||||
added = await conn.fetch(
|
||||
'INSERT INTO chat_members (chat_id, user_id) '
|
||||
'SELECT $1, u.id FROM users u WHERE u.id = ANY($2::uuid[]) RETURNING user_id',
|
||||
chat['id'], members)
|
||||
if len(added) != len(members):
|
||||
# Исключение внутри conn.transaction() -> ROLLBACK, строка chats тоже откатывается.
|
||||
raise invalid('member_ids содержит неизвестных пользователей')
|
||||
return JSONResponse({'id': str(chat['id']), 'title': title,
|
||||
'member_ids': sorted(str(m) for m in members),
|
||||
'created_at': ts(chat['created_at'])}, status_code=201)
|
||||
|
||||
|
||||
@app.get('/api/v1/chats')
|
||||
async def list_chats(request: Request):
|
||||
user_id = await current_user(request)
|
||||
limit = v.limit_param(request)
|
||||
after = v.decode_cursor(request, 'chats')
|
||||
query = (f'SELECT {CHAT_COLUMNS} FROM chats c '
|
||||
'JOIN chat_members m ON m.chat_id = c.id AND m.user_id = $1 ')
|
||||
params = [user_id, limit + 1]
|
||||
if after:
|
||||
query += 'WHERE (c.created_at, c.id) > ($3, $4) '
|
||||
params += after
|
||||
query += 'ORDER BY c.created_at, c.id LIMIT $2'
|
||||
async with db.connection() as conn:
|
||||
rows = await conn.fetch(query, *params)
|
||||
return page(rows, limit, 'chats', chat_json)
|
||||
|
||||
|
||||
def page(rows, limit: int, scope: str, render) -> dict:
|
||||
# Читаем limit+1 строку: если лишняя есть — следующая страница существует.
|
||||
items = rows[:limit]
|
||||
cursor = (v.encode_cursor(scope, items[-1]['created_at'], items[-1]['id'])
|
||||
if len(rows) > limit else None)
|
||||
return {'items': [render(r) for r in items], 'next_cursor': cursor}
|
||||
|
||||
|
||||
async def chat_for_member(conn, chat_id: UUID, user_id: UUID):
|
||||
return await conn.fetchrow(
|
||||
f'SELECT {CHAT_COLUMNS} FROM chats c '
|
||||
'WHERE c.id = $1 AND EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = $2)',
|
||||
chat_id, user_id)
|
||||
|
||||
|
||||
@app.get('/api/v1/chats/{chat_id}')
|
||||
async def get_chat(chat_id: str, request: Request):
|
||||
user_id = await current_user(request)
|
||||
cid = v.uuid_value(chat_id, 'chat_id')
|
||||
async with db.connection() as conn:
|
||||
row = await chat_for_member(conn, cid, user_id)
|
||||
if row is None:
|
||||
raise not_found()
|
||||
return chat_json(row)
|
||||
|
||||
# ---------- сообщения ----------
|
||||
|
||||
|
||||
IDEMPOTENCY_KEY_RE = re.compile(r'[A-Za-z0-9._:-]{1,128}')
|
||||
|
||||
|
||||
def idempotency_key(request: Request) -> str:
|
||||
key = request.headers.get('idempotency-key')
|
||||
if key is None or not IDEMPOTENCY_KEY_RE.fullmatch(key):
|
||||
raise invalid('Требуется заголовок Idempotency-Key: [A-Za-z0-9._:-]{1,128}')
|
||||
return key
|
||||
|
||||
|
||||
def request_fingerprint(text: str, attachments: list[UUID]) -> bytes:
|
||||
# Хешируем разобранное тело, а не байты: порядок ключей и пробелы JSON не делают запрос "другим",
|
||||
# отсутствующий attachment_ids равен []. Порядок вложений значим — он сохраняется в сообщении.
|
||||
canonical = json.dumps({'text': text, 'attachment_ids': [str(a) for a in attachments]},
|
||||
ensure_ascii=False, sort_keys=True, separators=(',', ':'))
|
||||
return hashlib.sha256(canonical.encode('utf-8')).digest()
|
||||
|
||||
|
||||
@app.post('/api/v1/chats/{chat_id}/messages', status_code=201)
|
||||
async def create_message(chat_id: str, request: Request):
|
||||
# Повтор заново проверяет сессию и членство: сохранённый ответ не выдаётся без текущего доступа.
|
||||
user_id = await current_user(request)
|
||||
cid = v.uuid_value(chat_id, 'chat_id')
|
||||
key = idempotency_key(request)
|
||||
data = await v.read_json(request)
|
||||
# sender_id в запросе не принимается — отправитель берётся из сессии
|
||||
v.fields(data, {'text'}, {'attachment_ids'})
|
||||
text = v.text_field(data, 'text', 0, 4000, allow_blank=True)
|
||||
attachments = v.attachment_ids(data)
|
||||
if not attachments and not text.strip():
|
||||
raise invalid('Нужен непустой текст или хотя бы одно вложение')
|
||||
fingerprint = request_fingerprint(text, attachments)
|
||||
async with db.connection() as conn:
|
||||
async with conn.transaction():
|
||||
member = await conn.fetchval(
|
||||
'SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2', cid, user_id)
|
||||
if member is None:
|
||||
raise not_found()
|
||||
# Ключ — "замок": параллельный INSERT того же PK с другой реплики ждёт COMMIT/ROLLBACK этой
|
||||
# транзакции. Просроченный (старше TTL) ключ атомарно переиспользуется как новый.
|
||||
message_id = await conn.fetchval(
|
||||
'INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id) '
|
||||
'VALUES ($1, $2, $3, $4, gen_random_uuid()) '
|
||||
'ON CONFLICT (user_id, chat_id, key) DO UPDATE '
|
||||
'SET request_hash = EXCLUDED.request_hash, message_id = EXCLUDED.message_id, '
|
||||
' created_at = clock_timestamp() '
|
||||
'WHERE idempotency_keys.created_at < clock_timestamp() - make_interval(secs => $5) '
|
||||
'RETURNING message_id',
|
||||
user_id, cid, key, fingerprint, settings.idempotency_ttl)
|
||||
if message_id is not None:
|
||||
# Ключ и сообщение фиксируются одним COMMIT: при сбое не остаётся ни того, ни другого,
|
||||
# поэтому транзиентная 5xx не становится "окончательным" результатом ключа.
|
||||
if attachments:
|
||||
# Все вложения — из ЭТОГО чата (иначе 404, как для чужого объекта). FOR SHARE
|
||||
# фиксирует строки до COMMIT; составной FK (attachment_id, chat_id) страхует на уровне БД.
|
||||
# lab5: queued/processing прикреплять можно, failed — 409 (контракт).
|
||||
statuses = await conn.fetch(
|
||||
'SELECT status FROM attachments WHERE chat_id = $1 AND id = ANY($2::uuid[]) FOR SHARE',
|
||||
cid, attachments)
|
||||
if len(statuses) != len(attachments):
|
||||
raise not_found()
|
||||
if any(r['status'] == 'failed' for r in statuses):
|
||||
raise ApiError(409, 'conflict', 'Вложение не обработано (failed)')
|
||||
row = await conn.fetchrow(
|
||||
'INSERT INTO messages (id, chat_id, sender_id, text, text_raw) VALUES ($1, $2, $3, $4, $5) '
|
||||
'RETURNING id, chat_id, sender_id, text, text_raw, created_at',
|
||||
message_id, cid, user_id, *pgtext.split(text))
|
||||
if attachments:
|
||||
await conn.execute(
|
||||
'INSERT INTO message_attachments (message_id, attachment_id, chat_id, position) '
|
||||
'SELECT $1, a.id, $2, a.ord - 1 FROM unnest($3::uuid[]) WITH ORDINALITY AS a(id, ord)',
|
||||
message_id, cid, attachments)
|
||||
row = {**dict(row), 'attachment_ids': attachments}
|
||||
else:
|
||||
row = await conn.fetchrow(
|
||||
'SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.text_raw, m.created_at, '
|
||||
+ MESSAGE_ATTACHMENTS.format(m='m') + ' '
|
||||
'FROM idempotency_keys k JOIN messages m ON m.id = k.message_id '
|
||||
'WHERE k.user_id = $1 AND k.chat_id = $2 AND k.key = $3', user_id, cid, key)
|
||||
if row is None:
|
||||
raise unavailable() # не должно случаться: ключ без сообщения не коммитится
|
||||
if row['request_hash'] != fingerprint:
|
||||
raise ApiError(409, 'conflict', 'Idempotency-Key уже использован с другим сообщением')
|
||||
return JSONResponse(message_json(row), status_code=201)
|
||||
|
||||
|
||||
@app.get('/api/v1/chats/{chat_id}/messages')
|
||||
async def list_messages(chat_id: str, request: Request):
|
||||
user_id = await current_user(request)
|
||||
cid = v.uuid_value(chat_id, 'chat_id')
|
||||
limit = v.limit_param(request)
|
||||
after = v.decode_cursor(request, 'messages:' + str(cid))
|
||||
async with db.connection() as conn:
|
||||
member = await conn.fetchval(
|
||||
'SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2', cid, user_id)
|
||||
if member is None:
|
||||
raise not_found()
|
||||
if after:
|
||||
# Keyset: продолжаем строго после последнего элемента прошлой страницы (без OFFSET).
|
||||
rows = await conn.fetch(
|
||||
f'SELECT {MESSAGE_COLUMNS} FROM messages WHERE chat_id = $1 AND (created_at, id) > ($3, $4) '
|
||||
'ORDER BY created_at, id LIMIT $2', cid, limit + 1, *after)
|
||||
else:
|
||||
rows = await conn.fetch(
|
||||
f'SELECT {MESSAGE_COLUMNS} FROM messages WHERE chat_id = $1 '
|
||||
'ORDER BY created_at, id LIMIT $2', cid, limit + 1)
|
||||
return page(rows, limit, 'messages:' + str(cid), message_json)
|
||||
|
||||
# ---------- вложения (lab4, асинхронная обработка с lab5) ----------
|
||||
|
||||
|
||||
async def attachment_for_member(conn, attachment_id: UUID, user_id: UUID):
|
||||
# Доступ = членство в чате вложения. Чужое и несуществующее неразличимы (404).
|
||||
return await conn.fetchrow(
|
||||
f'SELECT {ATTACHMENT_COLUMNS} FROM attachments a '
|
||||
'JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2 WHERE a.id = $1',
|
||||
attachment_id, user_id)
|
||||
|
||||
|
||||
async def variants_of(conn, row) -> list:
|
||||
if row['status'] != 'ready':
|
||||
return [] # варианты объявляются только вместе с ready
|
||||
return await conn.fetch(
|
||||
'SELECT name, content_type, size_bytes, width, height, sha256, object_key FROM attachment_variants '
|
||||
'WHERE attachment_id = $1 AND pipeline_version = $2 ORDER BY name', row['id'], row['pipeline_version'])
|
||||
|
||||
|
||||
@app.post('/api/v1/chats/{chat_id}/attachments', status_code=202)
|
||||
async def upload_attachment(chat_id: str, request: Request):
|
||||
user_id = await current_user(request)
|
||||
cid = v.uuid_value(chat_id, 'chat_id')
|
||||
async with db.connection() as conn:
|
||||
member = await conn.fetchval(
|
||||
'SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2', cid, user_id)
|
||||
if member is None:
|
||||
raise not_found() # посторонний не загружает ни байта в чужой чат
|
||||
# Backpressure: ограничение принятой, но не обработанной работы. При переполнении — 503 до
|
||||
# чтения тела, клиент повторит позже (Retry-After). Счётчик — по частичному индексу.
|
||||
pending = await conn.fetchval(
|
||||
"SELECT count(*) FROM attachment_jobs WHERE status IN ('queued', 'processing')")
|
||||
if pending >= settings.max_pending_jobs:
|
||||
raise ApiError(503, 'unavailable', 'Очередь обработки переполнена, повторите позже',
|
||||
{'Retry-After': '5'})
|
||||
filename = v.filename_param(request)
|
||||
declared = images.declared_type(request)
|
||||
data = await images.read_limited(request, settings.max_upload_bytes)
|
||||
# Дешёвые синхронные проверки (сигнатура, лимит пикселей по заголовку, целостность) остаются в API:
|
||||
# заведомо битый/огромный файл получает 413/415 сразу. Декодирование и resize — только в worker.
|
||||
content_type, width, height = await image_checker.inspect(data, declared)
|
||||
sha256 = hashlib.sha256(data).hexdigest()
|
||||
|
||||
attachment_id = uuid.uuid4()
|
||||
staging_key = f'staging/{attachment_id}' # устойчивый staging: приватный prefix S3
|
||||
object_key = f'originals/{attachment_id}' # конечный ключ, его публикует worker
|
||||
# 1) все байты — в устойчивый staging. Сбой -> 503, в БД ничего нет.
|
||||
await storage.put(staging_key, data, content_type)
|
||||
# 2) вложение (queued) + job + outbox — ОДНОЙ транзакцией. После COMMIT работа не теряется:
|
||||
# даже если процесс умрёт до publish, relay любой реплики опубликует job из outbox.
|
||||
try:
|
||||
async with db.connection() as conn:
|
||||
async with conn.transaction():
|
||||
row = await conn.fetchrow(
|
||||
'INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, '
|
||||
"width, height, object_key, staging_key, status) "
|
||||
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, 'queued') "
|
||||
'RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, '
|
||||
'error_code, created_at, updated_at',
|
||||
attachment_id, cid, user_id, filename, content_type, len(data), sha256, width, height,
|
||||
object_key, staging_key)
|
||||
await jobs.create(conn, attachment_id, settings.job_max_attempts)
|
||||
except BaseException:
|
||||
await storage.delete_quietly(staging_key) # COMMIT не прошёл: staging без метаданных не нужен
|
||||
raise
|
||||
faults.hit('api_crash_after_commit') # окно отказа «после COMMIT до publish» (тесты)
|
||||
relay.kick()
|
||||
return JSONResponse(attachment_json(row), status_code=202)
|
||||
|
||||
|
||||
@app.get('/api/v1/attachments/{attachment_id}')
|
||||
async def get_attachment(attachment_id: str, request: Request):
|
||||
user_id = await current_user(request)
|
||||
aid = v.uuid_value(attachment_id, 'attachment_id')
|
||||
async with db.connection() as conn:
|
||||
row = await attachment_for_member(conn, aid, user_id)
|
||||
if row is None:
|
||||
raise not_found()
|
||||
variants = await variants_of(conn, row)
|
||||
return attachment_json(row, variants)
|
||||
|
||||
|
||||
VARIANTS = {'original', 'thumbnail', 'crop', 'optimized'}
|
||||
|
||||
|
||||
@app.get('/api/v1/attachments/{attachment_id}/content')
|
||||
async def download_attachment(attachment_id: str, request: Request):
|
||||
user_id = await current_user(request)
|
||||
aid = v.uuid_value(attachment_id, 'attachment_id')
|
||||
variant = request.query_params.get('variant', 'original')
|
||||
if variant not in VARIANTS:
|
||||
raise invalid('Неизвестный variant')
|
||||
async with db.connection() as conn:
|
||||
row = await attachment_for_member(conn, aid, user_id)
|
||||
if row is None:
|
||||
raise not_found()
|
||||
if row['status'] != 'ready':
|
||||
# queued/processing/failed: содержимое ещё (или уже) недоступно.
|
||||
raise ApiError(409, 'conflict', 'Вложение ещё не готово' if row['status'] != 'failed'
|
||||
else 'Вложение не обработано')
|
||||
if variant == 'original':
|
||||
key, content_type, digest, name = row['object_key'], row['content_type'], row['sha256'], row['filename']
|
||||
else:
|
||||
found = [x for x in await variants_of(conn, row) if x['name'] == variant]
|
||||
if not found:
|
||||
raise not_found() # отсутствующий вариант ready-объекта
|
||||
x = found[0]
|
||||
key, content_type, digest, name = x['object_key'], x['content_type'], x['sha256'], variant
|
||||
# Байты идут через API после проверки доступа, без redirect на S3.
|
||||
data = await storage.get(key)
|
||||
return Response(data, media_type=content_type, headers={
|
||||
'Cache-Control': 'private, no-store',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Content-Disposition': "inline; filename*=UTF-8''" + quote(name, safe=''),
|
||||
'ETag': '"' + digest + '"',
|
||||
})
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Версионированные миграции: migrations/NNNN_name.sql применяются по порядку, каждая в своей транзакции.
|
||||
|
||||
Повторный запуск безопасен: применённые версии записаны в schema_migrations и пропускаются,
|
||||
изменённый задним числом файл (другая контрольная сумма) останавливает запуск.
|
||||
Advisory lock не даёт двум параллельным запускам применить одну миграцию дважды.
|
||||
"""
|
||||
import asyncio
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
import asyncpg
|
||||
|
||||
from . import config
|
||||
|
||||
MIGRATIONS = Path(__file__).resolve().parent.parent / 'migrations'
|
||||
LOCK_ID = 2026_0002
|
||||
|
||||
|
||||
async def connect(url: str, attempts: int = 30) -> asyncpg.Connection:
|
||||
for attempt in range(attempts):
|
||||
try:
|
||||
return await asyncpg.connect(url, timeout=3)
|
||||
except (OSError, asyncpg.CannotConnectNowError, asyncpg.PostgresConnectionError):
|
||||
if attempt == attempts - 1:
|
||||
raise
|
||||
await asyncio.sleep(1)
|
||||
|
||||
|
||||
async def migrate() -> None:
|
||||
# Только DATABASE_URL: сервису migrate не нужны (и не выдаются) S3-credentials API.
|
||||
database_url = config._secret('DATABASE_URL')
|
||||
if not database_url:
|
||||
raise SystemExit('DATABASE_URL_FILE is not configured')
|
||||
conn = await connect(database_url)
|
||||
try:
|
||||
await conn.execute('SELECT pg_advisory_lock($1)', LOCK_ID)
|
||||
await conn.execute(
|
||||
'CREATE TABLE IF NOT EXISTS schema_migrations ('
|
||||
' version text PRIMARY KEY, checksum text NOT NULL,'
|
||||
' applied_at timestamptz NOT NULL DEFAULT clock_timestamp())')
|
||||
applied = {r['version']: r['checksum'] for r in await conn.fetch('SELECT version, checksum FROM schema_migrations')}
|
||||
for path in sorted(MIGRATIONS.glob('[0-9][0-9][0-9][0-9]_*.sql')):
|
||||
version = path.stem
|
||||
sql = path.read_text(encoding='utf-8')
|
||||
checksum = hashlib.sha256(sql.encode()).hexdigest()
|
||||
if version in applied:
|
||||
if applied[version] != checksum:
|
||||
raise SystemExit(f'migration {version} was modified after being applied')
|
||||
print(f'skip {version}')
|
||||
continue
|
||||
async with conn.transaction():
|
||||
await conn.execute(sql)
|
||||
await conn.execute('INSERT INTO schema_migrations (version, checksum) VALUES ($1, $2)', version, checksum)
|
||||
print(f'apply {version}')
|
||||
finally:
|
||||
await conn.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(migrate())
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
"""Transactional outbox relay + восстановление работы. Фоновая задача в каждой реплике API.
|
||||
|
||||
1. publish: строки outbox (published_at IS NULL, available_at <= now) берутся FOR UPDATE SKIP LOCKED —
|
||||
две реплики не публикуют одну строку одновременно. Каждое сообщение публикуется persistent с
|
||||
publisher confirm; published_at ставится только после confirm. Падение между confirm и UPDATE даёт
|
||||
повторную публикацию — это at-least-once, worker идемпотентен.
|
||||
2. reap: processing с истёкшей арендой (worker умер, heartbeat прекратился) -> queued + новая строка outbox
|
||||
(или failed, если попытки исчерпаны).
|
||||
3. sweep: queued-задания без неопубликованной строки outbox, "застрявшие" дольше STALE_QUEUED_SECONDS
|
||||
(сообщение потеряно в DLQ по delivery-limit и т.п.), получают новую строку outbox.
|
||||
|
||||
Брокер недоступен -> API продолжает отвечать 202: намерение уже в PostgreSQL, relay допубликует позже.
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
|
||||
import aio_pika
|
||||
|
||||
from . import broker, jobs
|
||||
from .config import Settings
|
||||
from .db import Database
|
||||
|
||||
log = logging.getLogger('messenger.outbox')
|
||||
BATCH = 100
|
||||
STALE_QUEUED_SECONDS = 120
|
||||
|
||||
|
||||
class Relay:
|
||||
def __init__(self, settings: Settings, db: Database):
|
||||
self.settings = settings
|
||||
self.db = db
|
||||
self.wake = asyncio.Event()
|
||||
self.connection = None
|
||||
self.channel = None
|
||||
self.exchange = None
|
||||
self.broker_ok = False
|
||||
self._last_maintenance = 0.0
|
||||
|
||||
def kick(self) -> None:
|
||||
"""Сразу после COMMIT upload: не ждать следующего опроса (низкая задержка до worker)."""
|
||||
self.wake.set()
|
||||
|
||||
async def _ensure_channel(self) -> None:
|
||||
if self.channel is not None and not self.channel.is_closed:
|
||||
return
|
||||
if self.connection is None:
|
||||
self.connection = await broker.connect(self.settings.broker_url)
|
||||
self.channel = await self.connection.channel(publisher_confirms=True)
|
||||
self.exchange, _queue = await broker.declare(self.channel)
|
||||
|
||||
async def publish_batch(self) -> int:
|
||||
await self._ensure_channel()
|
||||
async with self.db.connection() as conn:
|
||||
async with conn.transaction():
|
||||
rows = await conn.fetch(
|
||||
'SELECT id, job_id, payload FROM outbox '
|
||||
'WHERE published_at IS NULL AND available_at <= clock_timestamp() '
|
||||
'ORDER BY available_at, id LIMIT $1 FOR UPDATE SKIP LOCKED', BATCH)
|
||||
published, error = [], None
|
||||
for row in rows:
|
||||
body = row['payload'] if isinstance(row['payload'], str) else json.dumps(row['payload'])
|
||||
try:
|
||||
# await = ожидание publisher confirm; mandatory=True — неприроутированное сообщение
|
||||
# вернётся ошибкой, а не исчезнет молча.
|
||||
await self.exchange.publish(
|
||||
aio_pika.Message(body.encode(), content_type='application/json',
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
message_id=str(row['job_id']), type=jobs.JOB_TYPE),
|
||||
routing_key=broker.ROUTING_KEY, mandatory=True, timeout=5)
|
||||
except Exception as exc:
|
||||
error = exc
|
||||
break
|
||||
published.append(row['id'])
|
||||
# Подтверждённые брокером отмечаем даже при ошибке на середине пачки (COMMIT ниже),
|
||||
# неподтверждённые остаются для следующего прохода.
|
||||
if published:
|
||||
await conn.execute('UPDATE outbox SET published_at = clock_timestamp(), '
|
||||
'publish_attempts = publish_attempts + 1 WHERE id = ANY($1::bigint[])',
|
||||
published)
|
||||
if error is not None:
|
||||
raise error
|
||||
return len(rows)
|
||||
|
||||
async def maintenance(self) -> None:
|
||||
"""reap + sweep раз в ~1 с; pg_try_advisory_xact_lock — одна реплика за раз."""
|
||||
loop = asyncio.get_running_loop()
|
||||
if loop.time() - self._last_maintenance < 1.0:
|
||||
return
|
||||
self._last_maintenance = loop.time()
|
||||
async with self.db.connection() as conn:
|
||||
async with conn.transaction():
|
||||
if not await conn.fetchval('SELECT pg_try_advisory_xact_lock(20260005)'):
|
||||
return
|
||||
expired = await conn.fetch(
|
||||
"SELECT job_id, attachment_id, attempt, max_attempts FROM attachment_jobs "
|
||||
"WHERE status = 'processing' AND lease_until < clock_timestamp() "
|
||||
"ORDER BY lease_until LIMIT $1 FOR UPDATE SKIP LOCKED", BATCH)
|
||||
for j in expired:
|
||||
if j['attempt'] >= j['max_attempts']:
|
||||
await jobs.fail(conn, j['job_id'], j['attachment_id'], 'retry_exhausted',
|
||||
'lease expired on last attempt')
|
||||
else:
|
||||
await jobs.requeue(conn, j['job_id'], j['attachment_id'], j['attempt'] + 1, 0.0,
|
||||
'lease expired (worker died or hung)')
|
||||
log.warning('lease expired: job %s attempt %s', j['job_id'], j['attempt'])
|
||||
stale = await conn.fetch(
|
||||
"SELECT j.job_id, j.attachment_id, j.attempt FROM attachment_jobs j "
|
||||
"WHERE j.status = 'queued' AND j.updated_at < clock_timestamp() - make_interval(secs => $1) "
|
||||
"AND j.next_attempt_at < clock_timestamp() - make_interval(secs => $1) "
|
||||
"AND NOT EXISTS (SELECT 1 FROM outbox o WHERE o.job_id = j.job_id AND o.published_at IS NULL) "
|
||||
"LIMIT $2 FOR UPDATE OF j SKIP LOCKED", STALE_QUEUED_SECONDS, BATCH)
|
||||
for j in stale:
|
||||
await jobs.enqueue(conn, j['job_id'], j['attachment_id'], j['attempt'] + 1)
|
||||
await conn.execute('UPDATE attachment_jobs SET updated_at = clock_timestamp() WHERE job_id = $1',
|
||||
j['job_id'])
|
||||
log.warning('stale queued job %s re-enqueued', j['job_id'])
|
||||
|
||||
async def run(self) -> None:
|
||||
delay = self.settings.outbox_poll_ms / 1000
|
||||
while True:
|
||||
try:
|
||||
n = await self.publish_batch()
|
||||
self.broker_ok = True
|
||||
await self.maintenance()
|
||||
if n == BATCH:
|
||||
continue # есть ещё — без паузы
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
if self.broker_ok:
|
||||
log.warning('outbox relay error (%s); will retry', type(exc).__name__)
|
||||
self.broker_ok = False
|
||||
self.channel = None
|
||||
try:
|
||||
await self.maintenance() # reap/sweep не зависят от брокера
|
||||
except Exception:
|
||||
pass
|
||||
await asyncio.sleep(1.0)
|
||||
continue
|
||||
self.wake.clear()
|
||||
try:
|
||||
await asyncio.wait_for(self.wake.wait(), delay)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
async def close(self) -> None:
|
||||
if self.connection is not None:
|
||||
await self.connection.close()
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Точное хранение строк с U+0000 в PostgreSQL.
|
||||
|
||||
Тип text в PostgreSQL не может содержать байт 0x00, а JSON-контракт допускает "\\u0000" в тексте
|
||||
сообщения, display_name и title. Раньше такой INSERT падал с 500 (замечание к lab3, PR #99).
|
||||
|
||||
Схема (только expand, совместима с предыдущей версией при rolling update):
|
||||
- столбец text/display_name/title получает ту же строку, где U+0000 заменён на U+FFFD: длина в code points
|
||||
не меняется, поэтому CHECK char_length и прежние реплики продолжают работать;
|
||||
- столбец *_raw bytea получает точные UTF-8 байты исходной строки, но ТОЛЬКО если в ней был U+0000
|
||||
(иначе NULL, лишнего места не занимает);
|
||||
- при чтении API возвращает декодированный *_raw, если он есть, иначе обычный столбец.
|
||||
"""
|
||||
|
||||
|
||||
def split(value: str) -> tuple[str, bytes | None]:
|
||||
if '\x00' in value:
|
||||
return value.replace('\x00', '\ufffd'), value.encode('utf-8')
|
||||
return value, None
|
||||
|
||||
|
||||
def join(text: str, raw: bytes | None) -> str:
|
||||
return bytes(raw).decode('utf-8') if raw is not None else text
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Явный операторский replay failed-заданий (failed -> queued) и просмотр реестра failed/DLQ.
|
||||
|
||||
docker compose --env-file .env run --rm --no-deps worker python -m app.replay list
|
||||
docker compose --env-file .env run --rm --no-deps worker python -m app.replay replay --attachment <uuid> --reason "..." [--dry-run]
|
||||
docker compose --env-file .env run --rm --no-deps worker python -m app.replay replay --all-failed --reason "..." [--dry-run]
|
||||
|
||||
Безопасность: переводится только задание в статусе failed (строка блокируется FOR UPDATE). Для ready/done
|
||||
replay — отказ: "повторить" не означает исполнить дубль успешной работы. Каждое действие пишется в
|
||||
job_audit (прежний статус и ошибка, actor, причина), счётчик попыток начинается заново, job_id тот же —
|
||||
логический эффект (attachment_id, pipeline_version, variant) защищён от дубля так же, как при redelivery.
|
||||
"""
|
||||
import argparse
|
||||
import asyncio
|
||||
import getpass
|
||||
import os
|
||||
import sys
|
||||
from uuid import UUID
|
||||
|
||||
from . import config, jobs
|
||||
from .db import Database
|
||||
|
||||
|
||||
async def list_failed(db: Database) -> None:
|
||||
async with db.connection() as conn:
|
||||
rows = await conn.fetch(
|
||||
"SELECT j.job_id, j.attachment_id, j.attempt, j.max_attempts, j.error_code, j.last_error, j.finished_at "
|
||||
"FROM attachment_jobs j WHERE j.status = 'failed' ORDER BY j.finished_at")
|
||||
print(f'failed jobs: {len(rows)}')
|
||||
for r in rows:
|
||||
print(f" attachment={r['attachment_id']} job={r['job_id']} attempts={r['attempt']}/{r['max_attempts']} "
|
||||
f"code={r['error_code']} reason={r['last_error']!r} at={r['finished_at']:%Y-%m-%dT%H:%M:%SZ}")
|
||||
|
||||
|
||||
async def replay(db: Database, attachment: UUID | None, all_failed: bool, reason: str, dry_run: bool) -> int:
|
||||
actor = os.environ.get('REPLAY_ACTOR') or getpass.getuser()
|
||||
done = 0
|
||||
async with db.connection() as conn:
|
||||
async with conn.transaction():
|
||||
if all_failed:
|
||||
targets = await conn.fetch("SELECT job_id, attachment_id, status, error_code FROM attachment_jobs "
|
||||
"WHERE status = 'failed' ORDER BY finished_at FOR UPDATE")
|
||||
else:
|
||||
targets = await conn.fetch('SELECT job_id, attachment_id, status, error_code FROM attachment_jobs '
|
||||
'WHERE attachment_id = $1 FOR UPDATE', attachment)
|
||||
if not targets:
|
||||
print('no such job')
|
||||
return 1
|
||||
for t in targets:
|
||||
if t['status'] != 'failed':
|
||||
print(f"skip attachment={t['attachment_id']}: status={t['status']} — replay only for failed")
|
||||
continue
|
||||
print(f"{'would replay' if dry_run else 'replay'} attachment={t['attachment_id']} "
|
||||
f"job={t['job_id']} previous={t['error_code']}")
|
||||
if dry_run:
|
||||
continue
|
||||
await conn.execute(
|
||||
'INSERT INTO job_audit (job_id, action, previous_status, previous_error, actor, reason) '
|
||||
"VALUES ($1, 'replay', $2, $3, $4, $5)", t['job_id'], t['status'], t['error_code'], actor, reason)
|
||||
await conn.execute(
|
||||
"UPDATE attachment_jobs SET status = 'queued', attempt = 0, error_code = NULL, last_error = NULL, "
|
||||
"next_attempt_at = clock_timestamp(), finished_at = NULL, worker_id = NULL, "
|
||||
"updated_at = clock_timestamp() WHERE job_id = $1 AND status = 'failed'", t['job_id'])
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = clock_timestamp() "
|
||||
"WHERE id = $1 AND status = 'failed'", t['attachment_id'])
|
||||
await jobs.enqueue(conn, t['job_id'], t['attachment_id'], attempt=1)
|
||||
done += 1
|
||||
print(f'replayed: {done}' + (' (dry run, nothing changed)' if dry_run else ''))
|
||||
return 0
|
||||
|
||||
|
||||
async def main_async(args) -> int:
|
||||
db = Database(config.load())
|
||||
await db.start()
|
||||
try:
|
||||
if args.command == 'list':
|
||||
await list_failed(db)
|
||||
return 0
|
||||
return await replay(db, args.attachment, args.all_failed, args.reason, args.dry_run)
|
||||
finally:
|
||||
await db.close()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
sub = p.add_subparsers(dest='command', required=True)
|
||||
sub.add_parser('list')
|
||||
r = sub.add_parser('replay')
|
||||
target = r.add_mutually_exclusive_group(required=True)
|
||||
target.add_argument('--attachment', type=UUID)
|
||||
target.add_argument('--all-failed', action='store_true')
|
||||
r.add_argument('--reason', required=True)
|
||||
r.add_argument('--dry-run', action='store_true')
|
||||
sys.exit(asyncio.run(main_async(p.parse_args())))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Bootstrap S3: создаёт приватный bucket для вложений. Запуск: python -m app.s3_bootstrap (сервис s3-init).
|
||||
|
||||
Идемпотентно: повторный запуск не трогает существующий bucket и данные в нём.
|
||||
"Приватный" = у bucket нет политики анонимного доступа. Если политика есть (например, кто-то включил
|
||||
public read руками), она удаляется. В конце выполняется проверка снаружи API: анонимный GET объекта
|
||||
должен получить отказ (403), иначе bootstrap завершается ошибкой и API не стартует.
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from minio import Minio
|
||||
from minio.error import S3Error
|
||||
|
||||
|
||||
def secret(name: str) -> str:
|
||||
return Path(os.environ[name + '_FILE']).read_text(encoding='utf-8').strip()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
endpoint = os.environ.get('S3_ENDPOINT', 'http://s3:9000')
|
||||
bucket = os.environ.get('S3_BUCKET', 'messenger-attachments')
|
||||
region = os.environ.get('S3_REGION', 'us-east-1')
|
||||
url = urlparse(endpoint)
|
||||
client = Minio(url.netloc, access_key=secret('S3_ACCESS_KEY_ID'), secret_key=secret('S3_SECRET_ACCESS_KEY'),
|
||||
secure=url.scheme == 'https', region=region)
|
||||
|
||||
for attempt in range(30):
|
||||
try:
|
||||
exists = client.bucket_exists(bucket)
|
||||
break
|
||||
except Exception as exc: # S3 ещё стартует
|
||||
if attempt == 29:
|
||||
raise SystemExit(f's3 not reachable: {type(exc).__name__}')
|
||||
time.sleep(1)
|
||||
if exists:
|
||||
print(f'bucket {bucket}: exists')
|
||||
else:
|
||||
client.make_bucket(bucket, location=region)
|
||||
print(f'bucket {bucket}: created')
|
||||
|
||||
try:
|
||||
client.get_bucket_policy(bucket)
|
||||
client.delete_bucket_policy(bucket)
|
||||
print(f'bucket {bucket}: anonymous policy removed')
|
||||
except S3Error as exc:
|
||||
if exc.code not in ('NoSuchBucketPolicy', 'NoSuchPolicy'):
|
||||
raise
|
||||
print(f'bucket {bucket}: no bucket policy (private)')
|
||||
|
||||
# Проверка приватности без credentials: служебный объект, анонимный GET, ожидаем 403.
|
||||
probe = '_bootstrap/private-check'
|
||||
client.put_object(bucket, probe, io.BytesIO(b'private'), 7, content_type='text/plain')
|
||||
try:
|
||||
urllib.request.urlopen(f'{endpoint}/{bucket}/{probe}', timeout=5)
|
||||
print('ERROR: anonymous GET returned object, bucket is public', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
except urllib.error.HTTPError as exc:
|
||||
print(f'anonymous GET {bucket}/{probe}: HTTP {exc.code} (denied)')
|
||||
if exc.code not in (401, 403):
|
||||
sys.exit(1)
|
||||
finally:
|
||||
client.remove_object(bucket, probe)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Пароли (Argon2id) и непрозрачные токены сессий."""
|
||||
import asyncio
|
||||
import hashlib
|
||||
import secrets
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError
|
||||
|
||||
# Параметры по умолчанию argon2-cffi = профиль RFC 9106 "low memory": Argon2id, m=64 MiB, t=3, p=4.
|
||||
_hasher = PasswordHasher()
|
||||
# Хеш для несуществующего пользователя: вход выполняет ту же работу и не выдаёт по времени,
|
||||
# что такого username нет.
|
||||
_DUMMY_HASH = _hasher.hash('dummy-password-for-timing')
|
||||
|
||||
|
||||
class PasswordService:
|
||||
"""KDF дорогой по CPU и памяти: считаем в отдельном ограниченном пуле потоков,
|
||||
чтобы не блокировать event loop и не съесть всю память параллельными входами."""
|
||||
|
||||
def __init__(self, workers: int):
|
||||
self._pool = ThreadPoolExecutor(max_workers=workers, thread_name_prefix='argon2')
|
||||
|
||||
async def hash(self, password: str) -> str:
|
||||
return await asyncio.get_running_loop().run_in_executor(self._pool, _hasher.hash, password)
|
||||
|
||||
async def verify(self, password_hash: str | None, password: str) -> bool:
|
||||
def check() -> bool:
|
||||
try:
|
||||
return _hasher.verify(password_hash or _DUMMY_HASH, password) and password_hash is not None
|
||||
except (VerificationError, InvalidHashError):
|
||||
return False
|
||||
return await asyncio.get_running_loop().run_in_executor(self._pool, check)
|
||||
|
||||
def close(self) -> None:
|
||||
self._pool.shutdown(wait=False)
|
||||
|
||||
|
||||
def new_token() -> str:
|
||||
# 32 случайных байта = 256 бит энтропии из CSPRNG ОС; base64url -> 43 символа.
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def token_hash(token: str) -> bytes:
|
||||
# Для токена с 256 битами энтропии быстрый SHA-256 достаточен: перебор невозможен.
|
||||
# Для паролей (низкая энтропия) так нельзя — там нужен медленный KDF.
|
||||
return hashlib.sha256(token.encode('ascii')).digest()
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
"""Сессии: PostgreSQL — источник истины, Valkey — read-through кэш с TTL.
|
||||
|
||||
Политика:
|
||||
- создание: INSERT в PostgreSQL (COMMIT), затем SET в кэш с TTL = min(остаток жизни, SESSION_CACHE_TTL_SECONDS);
|
||||
- проверка: кэш -> при промахе PostgreSQL -> заполнить кэш;
|
||||
- logout: UPDATE revoked_at в PostgreSQL (COMMIT), затем DEL из кэша;
|
||||
- любой сбой Valkey: работаем только с PostgreSQL и SESSION_CACHE_TTL_SECONDS не доверяем кэшу
|
||||
(все записи, сделанные до сбоя, за это время гарантированно истекут — например, не удалённая
|
||||
при logout копия отозванной сессии). Flush/рестарт Valkey = пустой кэш, сессии не теряются.
|
||||
- lab3, несколько реплик: окно недоверия ОБЩЕЕ. Реплика, получившая ошибку Valkey, записывает его
|
||||
в PostgreSQL (cache_state), а попадание в кэш принимается, только если общий признак проверен
|
||||
не раньше SHARED_STATE_MAX_AGE назад. Иначе реплика, которая сама сбоя не видела, могла бы
|
||||
отдать копию сессии, отозванной на другой реплике во время разрыва с Valkey.
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from uuid import UUID
|
||||
|
||||
import redis.asyncio as redis
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from .config import Settings
|
||||
from .db import Database
|
||||
from .security import token_hash
|
||||
|
||||
log = logging.getLogger('messenger.sessions')
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Session:
|
||||
user_id: UUID
|
||||
expires_at: datetime
|
||||
|
||||
|
||||
# Насколько устаревшим может быть знание реплики об общем окне недоверия (не чаще 2 запросов/с к БД).
|
||||
SHARED_STATE_MAX_AGE = 0.5
|
||||
|
||||
|
||||
class SessionCache:
|
||||
def __init__(self, url: str | None, ttl: int, timeout: float, db: Database):
|
||||
self.ttl = ttl
|
||||
self.db = db
|
||||
self.client = redis.Redis.from_url(
|
||||
url, socket_timeout=timeout, socket_connect_timeout=timeout,
|
||||
retry_on_timeout=False, health_check_interval=30,
|
||||
) if url else None
|
||||
self._distrust_until = 0.0 # локально (monotonic): своя ошибка действует сразу
|
||||
self._shared_trusted = False # результат последней проверки общего признака
|
||||
self._shared_checked = -1e9
|
||||
self._lock = asyncio.Lock()
|
||||
|
||||
@staticmethod
|
||||
def key(digest: bytes) -> str:
|
||||
return 'session:' + digest.hex()
|
||||
|
||||
def usable(self) -> bool:
|
||||
return self.client is not None and time.monotonic() >= self._distrust_until
|
||||
|
||||
async def trusted(self) -> bool:
|
||||
"""Можно ли принять попадание в кэш: нет ни своего, ни общего (с других реплик) окна недоверия."""
|
||||
if not self.usable():
|
||||
return False
|
||||
if time.monotonic() - self._shared_checked > SHARED_STATE_MAX_AGE:
|
||||
async with self._lock:
|
||||
if time.monotonic() - self._shared_checked > SHARED_STATE_MAX_AGE:
|
||||
try:
|
||||
async with self.db.pool.acquire(timeout=1) as conn:
|
||||
self._shared_trusted = await conn.fetchval(
|
||||
'SELECT distrust_until <= clock_timestamp() FROM cache_state WHERE id = 1',
|
||||
timeout=1) is True
|
||||
except Exception: # без БД сессию всё равно не проверить; кэшу не доверяем
|
||||
self._shared_trusted = False
|
||||
self._shared_checked = time.monotonic()
|
||||
return self._shared_trusted
|
||||
|
||||
async def _failed(self, op: str) -> None:
|
||||
# Не знаем, что успело/не успело записаться: перестаём читать кэш на один максимальный TTL —
|
||||
# сами сразу и все остальные реплики через общий признак в PostgreSQL.
|
||||
self._distrust_until = time.monotonic() + self.ttl
|
||||
self._shared_checked = -1e9
|
||||
log.warning('valkey %s failed; bypassing cache for %ss on all replicas', op, self.ttl)
|
||||
try:
|
||||
async with self.db.pool.acquire(timeout=1) as conn:
|
||||
await conn.execute(
|
||||
'UPDATE cache_state SET distrust_until = greatest(distrust_until, '
|
||||
'clock_timestamp() + make_interval(secs => $1)) WHERE id = 1', self.ttl, timeout=1)
|
||||
except Exception: # БД недоступна — и кэш, и сессии всё равно проверить нельзя
|
||||
log.warning('could not publish cache distrust window', exc_info=True)
|
||||
|
||||
async def get(self, digest: bytes) -> Session | None:
|
||||
if not await self.trusted():
|
||||
return None
|
||||
try:
|
||||
raw = await self.client.get(self.key(digest))
|
||||
except (RedisError, OSError):
|
||||
await self._failed('get')
|
||||
return None
|
||||
if raw is None:
|
||||
return None
|
||||
data = json.loads(raw)
|
||||
return Session(UUID(data['u']), datetime.fromtimestamp(data['e'], timezone.utc))
|
||||
|
||||
async def put(self, digest: bytes, session: Session) -> None:
|
||||
if not self.usable():
|
||||
return
|
||||
remaining = int((session.expires_at - datetime.now(timezone.utc)).total_seconds())
|
||||
ttl = min(self.ttl, remaining)
|
||||
if ttl <= 0:
|
||||
return
|
||||
value = json.dumps({'u': str(session.user_id), 'e': session.expires_at.timestamp()})
|
||||
try:
|
||||
await self.client.set(self.key(digest), value, ex=ttl)
|
||||
except (RedisError, OSError):
|
||||
await self._failed('set')
|
||||
|
||||
async def delete(self, digest: bytes) -> None:
|
||||
if self.client is None:
|
||||
return
|
||||
try:
|
||||
await self.client.delete(self.key(digest))
|
||||
except (RedisError, OSError):
|
||||
await self._failed('delete')
|
||||
|
||||
async def close(self) -> None:
|
||||
if self.client is not None:
|
||||
await self.client.aclose()
|
||||
|
||||
|
||||
class SessionStore:
|
||||
def __init__(self, settings: Settings, db: Database):
|
||||
self.ttl = settings.session_ttl
|
||||
self.db = db
|
||||
self.cache = SessionCache(settings.cache_url, settings.session_cache_ttl, settings.cache_timeout, db)
|
||||
|
||||
async def create(self, user_id: UUID, token: str) -> Session:
|
||||
digest = token_hash(token)
|
||||
async with self.db.connection() as conn:
|
||||
# Время берём из БД, чтобы срок не зависел от часов конкретной реплики API.
|
||||
expires_at = await conn.fetchval(
|
||||
'INSERT INTO sessions (token_hash, user_id, expires_at) '
|
||||
'VALUES ($1, $2, clock_timestamp() + make_interval(secs => $3)) RETURNING expires_at',
|
||||
digest, user_id, self.ttl,
|
||||
)
|
||||
session = Session(user_id, expires_at)
|
||||
await self.cache.put(digest, session)
|
||||
return session
|
||||
|
||||
async def resolve(self, token: str) -> Session | None:
|
||||
digest = token_hash(token)
|
||||
now = datetime.now(timezone.utc)
|
||||
cached = await self.cache.get(digest)
|
||||
if cached is not None and cached.expires_at > now:
|
||||
return cached
|
||||
async with self.db.connection() as conn:
|
||||
row = await conn.fetchrow(
|
||||
'SELECT user_id, expires_at FROM sessions '
|
||||
'WHERE token_hash = $1 AND revoked_at IS NULL AND expires_at > clock_timestamp()',
|
||||
digest,
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
session = Session(row['user_id'], row['expires_at'])
|
||||
await self.cache.put(digest, session)
|
||||
return session
|
||||
|
||||
async def revoke(self, token: str) -> bool:
|
||||
digest = token_hash(token)
|
||||
async with self.db.connection() as conn:
|
||||
status = await conn.execute(
|
||||
'UPDATE sessions SET revoked_at = clock_timestamp() '
|
||||
'WHERE token_hash = $1 AND revoked_at IS NULL AND expires_at > clock_timestamp()',
|
||||
digest,
|
||||
)
|
||||
# Инвалидация кэша строго после COMMIT в источнике истины.
|
||||
await self.cache.delete(digest)
|
||||
return status == 'UPDATE 1'
|
||||
|
||||
async def purge_expired(self) -> int:
|
||||
async with self.db.connection() as conn:
|
||||
status = await conn.execute(
|
||||
"DELETE FROM sessions WHERE expires_at < clock_timestamp() - interval '1 day'")
|
||||
return int(status.split()[-1])
|
||||
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
"""Приватное S3-хранилище оригиналов вложений (MinIO, S3 API).
|
||||
|
||||
Клиент minio-py синхронный, поэтому вызовы уходят в пул потоков (asyncio.to_thread) и не блокируют
|
||||
event loop. Таймауты и число повторов ограничены: недоступный S3 даёт 503 за секунды, а не зависание.
|
||||
Ключи объектов назначает сервер; bucket приватный, байты отдаёт только API после проверки доступа.
|
||||
"""
|
||||
import asyncio
|
||||
import io
|
||||
import logging
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import urllib3
|
||||
from minio import Minio
|
||||
from minio.error import MinioException, S3Error
|
||||
|
||||
from .config import Settings
|
||||
from .errors import ApiError, unavailable
|
||||
|
||||
log = logging.getLogger('messenger.storage')
|
||||
|
||||
|
||||
class ObjectMissing(Exception):
|
||||
"""Метаданные в БД есть, а объекта в bucket нет (рассогласование хранилищ)."""
|
||||
|
||||
|
||||
class Storage:
|
||||
def __init__(self, settings: Settings):
|
||||
endpoint = urlparse(settings.s3_endpoint)
|
||||
self.bucket = settings.s3_bucket
|
||||
# Без повторов на уровне HTTP-клиента: повтор удваивал бы время отказа. Общий дедлайн операции —
|
||||
# в _call: getaddrinfo (DNS остановленного контейнера ~8 с) таймаутами urllib3 не ограничен.
|
||||
self.deadline = settings.s3_timeout
|
||||
http = urllib3.PoolManager(
|
||||
timeout=urllib3.Timeout(connect=2, read=settings.s3_timeout),
|
||||
retries=urllib3.Retry(total=0, redirect=0),
|
||||
maxsize=16,
|
||||
)
|
||||
self.client = Minio(endpoint.netloc, access_key=settings.s3_access_key,
|
||||
secret_key=settings.s3_secret_key, secure=endpoint.scheme == 'https',
|
||||
region=settings.s3_region, http_client=http)
|
||||
|
||||
async def _call(self, fn, *args, **kwargs):
|
||||
try:
|
||||
return await asyncio.wait_for(asyncio.to_thread(fn, *args, **kwargs), self.deadline)
|
||||
except asyncio.TimeoutError:
|
||||
# Поток дорабатывает в фоне (его нельзя прервать), но клиент получает 503 в пределах дедлайна.
|
||||
log.warning('S3 deadline %.1fs exceeded on %s', self.deadline, fn.__name__)
|
||||
raise unavailable() from None
|
||||
except S3Error as exc:
|
||||
if exc.code in ('NoSuchKey', 'NoSuchObject'):
|
||||
raise ObjectMissing() from None
|
||||
log.warning('S3 error %s on %s', exc.code, fn.__name__)
|
||||
raise unavailable() from None
|
||||
except (MinioException, urllib3.exceptions.HTTPError, OSError, ValueError):
|
||||
# Нет связи, таймаут, 5xx после повтора — для клиента это временная недоступность.
|
||||
log.warning('S3 unavailable on %s', fn.__name__, exc_info=True)
|
||||
raise unavailable() from None
|
||||
|
||||
async def put(self, key: str, data: bytes, content_type: str) -> None:
|
||||
await self._call(self.client.put_object, self.bucket, key, io.BytesIO(data), len(data),
|
||||
content_type=content_type)
|
||||
|
||||
async def get(self, key: str) -> bytes:
|
||||
def read() -> bytes:
|
||||
response = self.client.get_object(self.bucket, key)
|
||||
try:
|
||||
return response.read()
|
||||
finally:
|
||||
response.close()
|
||||
response.release_conn()
|
||||
try:
|
||||
return await self._call(read)
|
||||
except ObjectMissing:
|
||||
log.error('object %s is missing in bucket %s', key, self.bucket)
|
||||
raise ApiError(500, 'internal_error', 'Внутренняя ошибка сервера') from None
|
||||
|
||||
async def delete(self, key: str) -> None:
|
||||
await self._call(self.client.remove_object, self.bucket, key)
|
||||
|
||||
async def delete_quietly(self, key: str) -> None:
|
||||
"""Компенсация после неудачной записи метаданных. Сбой здесь не меняет ответ клиенту."""
|
||||
try:
|
||||
await asyncio.shield(self.delete(key))
|
||||
except Exception:
|
||||
log.error('compensation failed: orphan object %s left in bucket', key)
|
||||
|
||||
# ---------- lab5: операции worker ----------
|
||||
|
||||
async def get_raw(self, key: str) -> bytes:
|
||||
"""Как get(), но отсутствие объекта — ObjectMissing (worker решает сам: это постоянная ошибка)."""
|
||||
def read() -> bytes:
|
||||
response = self.client.get_object(self.bucket, key)
|
||||
try:
|
||||
return response.read()
|
||||
finally:
|
||||
response.close()
|
||||
response.release_conn()
|
||||
return await self._call(read)
|
||||
|
||||
async def copy(self, source_key: str, target_key: str) -> None:
|
||||
"""Server-side copy внутри bucket: байты оригинала не гоняются через worker повторно."""
|
||||
from minio.commonconfig import CopySource
|
||||
await self._call(self.client.copy_object, self.bucket, target_key, CopySource(self.bucket, source_key))
|
||||
|
||||
async def exists(self, key: str) -> bool:
|
||||
try:
|
||||
await self._call(self.client.stat_object, self.bucket, key)
|
||||
return True
|
||||
except ObjectMissing:
|
||||
return False
|
||||
|
||||
async def list_older(self, prefix: str, older_than_seconds: int) -> list[str]:
|
||||
"""Ключи под prefix старше заданного возраста (для retention staging)."""
|
||||
import datetime as dt
|
||||
|
||||
def scan() -> list[str]:
|
||||
border = dt.datetime.now(dt.timezone.utc) - dt.timedelta(seconds=older_than_seconds)
|
||||
return [o.object_name for o in self.client.list_objects(self.bucket, prefix=prefix, recursive=True)
|
||||
if o.last_modified is not None and o.last_modified < border]
|
||||
return await self._call(scan)
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Строгий разбор JSON и параметров: лишние поля, неверные типы, malformed JSON -> 400."""
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Request
|
||||
|
||||
from .errors import ApiError, invalid
|
||||
|
||||
MAX_BODY_BYTES = 64 * 1024
|
||||
USERNAME_RE = re.compile(r'[a-z0-9_]{3,32}')
|
||||
|
||||
|
||||
async def read_json(request: Request) -> dict:
|
||||
media_type = request.headers.get('content-type', '').split(';')[0].strip().lower()
|
||||
if media_type != 'application/json':
|
||||
raise ApiError(415, 'unsupported_media_type', 'Ожидается Content-Type: application/json')
|
||||
body = await request.body()
|
||||
if len(body) > MAX_BODY_BYTES:
|
||||
raise ApiError(413, 'payload_too_large', 'Слишком большое тело запроса')
|
||||
try:
|
||||
data = json.loads(body.decode('utf-8'))
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
raise invalid('Некорректный JSON') from None
|
||||
if not isinstance(data, dict):
|
||||
raise invalid('Ожидается JSON-объект')
|
||||
return data
|
||||
|
||||
|
||||
def fields(data: dict, required: set[str], optional: set[str] = frozenset()) -> None:
|
||||
extra = set(data) - required - optional
|
||||
if extra:
|
||||
raise invalid('Неизвестные поля: ' + ', '.join(sorted(extra)))
|
||||
missing = required - set(data)
|
||||
if missing:
|
||||
raise invalid('Отсутствуют поля: ' + ', '.join(sorted(missing)))
|
||||
|
||||
|
||||
def text_field(data: dict, name: str, min_len: int, max_len: int, *, allow_blank: bool = False) -> str:
|
||||
value = data[name]
|
||||
if not isinstance(value, str):
|
||||
raise invalid(f'Поле {name} должно быть строкой')
|
||||
try:
|
||||
value.encode('utf-8') # отсекает одиночные суррогаты из \uD800-экранирования
|
||||
except UnicodeEncodeError:
|
||||
raise invalid(f'Поле {name} содержит некорректный Unicode') from None
|
||||
if not min_len <= len(value) <= max_len: # len(str) в Python = число code points
|
||||
raise invalid(f'Длина поля {name} должна быть {min_len}..{max_len} символов')
|
||||
if not allow_blank and not value.strip():
|
||||
raise invalid(f'Поле {name} не может состоять из пробелов')
|
||||
return value
|
||||
|
||||
|
||||
def username(data: dict) -> str:
|
||||
value = data['username']
|
||||
if not isinstance(value, str) or not USERNAME_RE.fullmatch(value):
|
||||
raise invalid('username должен соответствовать [a-z0-9_]{3,32}')
|
||||
return value
|
||||
|
||||
|
||||
def uuid_value(value, what: str = 'идентификатор') -> UUID:
|
||||
if not isinstance(value, str):
|
||||
raise invalid(f'Некорректный {what}')
|
||||
try:
|
||||
parsed = UUID(value)
|
||||
except ValueError:
|
||||
raise invalid(f'Некорректный {what}') from None
|
||||
if str(parsed) != value.lower(): # только каноническая форма 8-4-4-4-12
|
||||
raise invalid(f'Некорректный {what}')
|
||||
return parsed
|
||||
|
||||
|
||||
def limit_param(request: Request) -> int:
|
||||
raw = request.query_params.get('limit')
|
||||
if raw is None:
|
||||
return 50
|
||||
if not re.fullmatch(r'[0-9]{1,3}', raw) or not 1 <= int(raw) <= 100:
|
||||
raise invalid('limit должен быть целым 1..100')
|
||||
return int(raw)
|
||||
|
||||
|
||||
# Курсор: base64url(JSON {"s": область, "t": created_at, "i": id}). Для клиента это непрозрачная строка.
|
||||
# Подделка курсора ничего не даёт: доступ к чату проверяется отдельно, а область привязывает
|
||||
# курсор к конкретному чату/списку — курсор другого чата отклоняется с 400.
|
||||
|
||||
def encode_cursor(scope: str, created_at: datetime, item_id: UUID) -> str:
|
||||
raw = json.dumps({'s': scope, 't': created_at.isoformat(), 'i': str(item_id)}, separators=(',', ':'))
|
||||
return base64.urlsafe_b64encode(raw.encode()).decode().rstrip('=')
|
||||
|
||||
|
||||
def decode_cursor(request: Request, scope: str) -> tuple[datetime, UUID] | None:
|
||||
raw = request.query_params.get('cursor')
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
if len(raw) > 512:
|
||||
raise ValueError
|
||||
data = json.loads(base64.urlsafe_b64decode(raw + '=' * (-len(raw) % 4)))
|
||||
if not isinstance(data, dict) or set(data) != {'s', 't', 'i'} or data['s'] != scope:
|
||||
raise ValueError
|
||||
created_at = datetime.fromisoformat(data['t'])
|
||||
if created_at.tzinfo is None:
|
||||
raise ValueError
|
||||
return created_at, UUID(data['i'])
|
||||
except (ValueError, TypeError, UnicodeDecodeError):
|
||||
raise invalid('Некорректный cursor') from None
|
||||
|
||||
|
||||
# Имя файла — только для отображения: в ключ S3 и пути оно не попадает. Разделители путей,
|
||||
# NUL и управляющие символы (C0, DEL, C1) отклоняются, чтобы имя нельзя было выдать за путь.
|
||||
FILENAME_FORBIDDEN_RE = re.compile(r'[/\\\x00-\x1f\x7f-\x9f]')
|
||||
|
||||
|
||||
def filename_param(request: Request) -> str:
|
||||
values = request.query_params.getlist('filename')
|
||||
if len(values) != 1:
|
||||
raise invalid('Требуется ровно один параметр filename')
|
||||
value = values[0]
|
||||
try:
|
||||
value.encode('utf-8')
|
||||
except UnicodeEncodeError:
|
||||
raise invalid('filename содержит некорректный Unicode') from None
|
||||
if not 1 <= len(value) <= 255 or not value.strip() or value in ('.', '..') \
|
||||
or FILENAME_FORBIDDEN_RE.search(value):
|
||||
raise invalid('Недопустимое имя файла')
|
||||
return value
|
||||
|
||||
|
||||
def attachment_ids(data: dict) -> list[UUID]:
|
||||
raw = data.get('attachment_ids', [])
|
||||
if not isinstance(raw, list) or len(raw) > 10:
|
||||
raise invalid('attachment_ids должен быть массивом из 0..10 UUID')
|
||||
ids = [uuid_value(x, 'attachment_id') for x in raw]
|
||||
if len(set(ids)) != len(ids):
|
||||
raise invalid('attachment_ids содержит дубликаты')
|
||||
return ids
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
"""Worker обработки вложений: python -m app.worker (отдельный сервис, не API).
|
||||
|
||||
Одна доставка сообщения:
|
||||
1. проверить сообщение по contracts/jobs.schema.json (иначе reject без requeue -> DLQ);
|
||||
2. claim в PostgreSQL: queued (или processing с истёкшей арендой) -> processing, attempt+1, lease;
|
||||
done/failed/чужая живая аренда/ещё не время retry -> no-op + ack;
|
||||
3. heartbeat продлевает lease, пока идёт работа (отличает долгую обработку от зависшей/мёртвой);
|
||||
4. оригинал из staging, сверка size/sha256 с доверенными метаданными из БД;
|
||||
5. варианты в дочернем процессе (лимиты памяти/времени), запись в S3 по ДЕТЕРМИНИРОВАННЫМ ключам
|
||||
variants/<id>/v<pipeline>/<name> + server-side copy staging -> originals/<id>;
|
||||
6. COMMIT результата с fencing по (worker_id, attempt): variants (ON CONFLICT DO NOTHING) + ready;
|
||||
7. удалить staging (после безопасной фиксации), затем ack.
|
||||
Сбой на любом шаге до ack -> redelivery/reaper -> повтор шагов 4–6 перезаписывает те же ключи тем же
|
||||
содержимым и не создаёт второй набор вариантов (ключ эффекта (attachment_id, pipeline_version, variant)).
|
||||
"""
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
import signal
|
||||
import socket
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import jsonschema
|
||||
|
||||
from . import broker, config, faults, imaging, jobs
|
||||
from .db import Database
|
||||
from .errors import ApiError
|
||||
from .storage import ObjectMissing, Storage
|
||||
|
||||
log = logging.getLogger('messenger.worker')
|
||||
SCHEMA = json.loads((Path(__file__).resolve().parent.parent / 'contracts/jobs.schema.json').read_text(encoding='utf-8'))
|
||||
VALIDATOR = jsonschema.Draft202012Validator(SCHEMA, format_checker=jsonschema.FormatChecker())
|
||||
ALIVE_FILE = Path('/tmp/worker-alive')
|
||||
|
||||
|
||||
class LostLease(Exception):
|
||||
"""Аренду перехватили (истекла): результат фиксирует новый владелец, этот — только ack."""
|
||||
|
||||
|
||||
class Worker:
|
||||
def __init__(self):
|
||||
self.settings = config.load()
|
||||
self.db = Database(self.settings)
|
||||
self.storage = Storage(self.settings)
|
||||
self.worker_id = f'{socket.gethostname()}-{secrets.token_hex(3)}'
|
||||
self.slots = asyncio.Semaphore(self.settings.worker_concurrency)
|
||||
self.inflight: set[asyncio.Task] = set()
|
||||
self.stopping = asyncio.Event()
|
||||
self.connection = None
|
||||
|
||||
# ---------- приём сообщения ----------
|
||||
|
||||
async def on_message(self, message) -> None:
|
||||
task = asyncio.current_task()
|
||||
self.inflight.add(task)
|
||||
try:
|
||||
try:
|
||||
payload = json.loads(message.body)
|
||||
VALIDATOR.validate(payload)
|
||||
except (ValueError, jsonschema.ValidationError):
|
||||
log.error('invalid job message %s -> DLQ', message.message_id)
|
||||
await message.reject(requeue=False)
|
||||
return
|
||||
async with self.slots:
|
||||
try:
|
||||
await self.process(payload)
|
||||
except Exception:
|
||||
# Инфраструктура (БД/S3) недоступна настолько, что даже состояние не записать:
|
||||
# вернуть сообщение в очередь с паузой; delivery-limit страхует от бесконечного цикла.
|
||||
log.exception('job %s: infrastructure error, requeue', payload['job_id'])
|
||||
await asyncio.sleep(2)
|
||||
await message.nack(requeue=True)
|
||||
return
|
||||
await message.ack() # только после устойчивого эффекта (или no-op)
|
||||
finally:
|
||||
self.inflight.discard(task)
|
||||
|
||||
# ---------- обработка ----------
|
||||
|
||||
async def claim(self, job_id: str, attachment_id: str):
|
||||
async with self.db.connection() as conn:
|
||||
async with conn.transaction():
|
||||
j = await conn.fetchrow(
|
||||
'SELECT j.status, j.attempt, j.max_attempts, '
|
||||
' coalesce(j.lease_until > clock_timestamp(), false) AS leased, '
|
||||
' j.next_attempt_at > clock_timestamp() AS not_yet, '
|
||||
' a.staging_key, a.object_key, a.size_bytes, a.sha256, a.pipeline_version '
|
||||
'FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id '
|
||||
'WHERE j.job_id = $1 AND j.attachment_id = $2 FOR UPDATE OF j', job_id, attachment_id)
|
||||
if j is None:
|
||||
return None, 'unknown job'
|
||||
if j['status'] in ('done', 'failed'):
|
||||
return None, f"already {j['status']} (duplicate delivery)"
|
||||
if j['status'] == 'processing' and j['leased']:
|
||||
return None, 'leased by another live worker (duplicate delivery)'
|
||||
if j['status'] == 'queued' and j['not_yet']:
|
||||
return None, 'retry is scheduled later (stale message)'
|
||||
if j['attempt'] >= j['max_attempts']:
|
||||
await jobs.fail(conn, job_id, attachment_id, 'retry_exhausted', 'no attempts left')
|
||||
return None, 'attempts exhausted'
|
||||
attempt = await conn.fetchval(
|
||||
"UPDATE attachment_jobs SET status = 'processing', attempt = attempt + 1, worker_id = $2, "
|
||||
"lease_until = clock_timestamp() + make_interval(secs => $3), started_at = clock_timestamp(), "
|
||||
"updated_at = clock_timestamp() WHERE job_id = $1 RETURNING attempt",
|
||||
job_id, self.worker_id, self.settings.job_lease)
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'processing', updated_at = clock_timestamp() "
|
||||
"WHERE id = $1 AND status IN ('queued', 'processing')", attachment_id)
|
||||
return {**dict(j), 'attempt': attempt, 'max_attempts': j['max_attempts']}, None
|
||||
|
||||
async def heartbeat(self, job_id: str, attempt: int) -> None:
|
||||
interval = max(1.0, self.settings.job_lease / 3)
|
||||
while True:
|
||||
await asyncio.sleep(interval)
|
||||
try:
|
||||
async with self.db.connection() as conn:
|
||||
ok = await conn.fetchval(
|
||||
"UPDATE attachment_jobs SET lease_until = clock_timestamp() + make_interval(secs => $3) "
|
||||
"WHERE job_id = $1 AND worker_id = $2 AND attempt = $4 AND status = 'processing' RETURNING 1",
|
||||
job_id, self.worker_id, self.settings.job_lease, attempt)
|
||||
if not ok:
|
||||
log.warning('job %s: lease lost', job_id)
|
||||
return
|
||||
except Exception:
|
||||
log.warning('job %s: heartbeat failed', job_id)
|
||||
|
||||
async def process(self, payload: dict) -> None:
|
||||
job_id, attachment_id = payload['job_id'], payload['attachment_id']
|
||||
job, reason = await self.claim(job_id, attachment_id)
|
||||
if job is None:
|
||||
log.info('job %s: no-op, %s', job_id, reason)
|
||||
return
|
||||
started = time.monotonic()
|
||||
beat = asyncio.create_task(self.heartbeat(job_id, job['attempt']))
|
||||
try:
|
||||
stages = await self.execute(job_id, attachment_id, job)
|
||||
log.info('job %s: ready in %.2fs (attempt %d) %s', job_id, time.monotonic() - started, job['attempt'],
|
||||
' '.join(f'{k}={v:.3f}' for k, v in stages.items()))
|
||||
except imaging.PermanentImageError as exc:
|
||||
await self.finish_failed(job_id, attachment_id, job['attempt'], exc.code, exc.code)
|
||||
except LostLease:
|
||||
log.warning('job %s: result not committed, lease taken over', job_id)
|
||||
except (imaging.TransientImageError, ApiError) as exc:
|
||||
code = getattr(exc, 'code', 'unavailable')
|
||||
await self.retry_or_fail(job_id, attachment_id, job, f'transient: {code}')
|
||||
finally:
|
||||
beat.cancel()
|
||||
|
||||
async def execute(self, job_id: str, attachment_id: str, job) -> None:
|
||||
version = job['pipeline_version']
|
||||
stages, mark = {}, time.monotonic()
|
||||
|
||||
def lap(name):
|
||||
nonlocal mark
|
||||
now = time.monotonic()
|
||||
stages[name] = now - mark
|
||||
mark = now
|
||||
try:
|
||||
data = await self.storage.get_raw(job['staging_key'])
|
||||
except ObjectMissing:
|
||||
raise imaging.PermanentImageError('source_missing') from None
|
||||
# Доверенные метаданные — из БД, а не из сообщения брокера.
|
||||
if len(data) != job['size_bytes'] or hashlib.sha256(data).hexdigest() != job['sha256']:
|
||||
raise imaging.PermanentImageError('source_corrupted')
|
||||
lap('fetch')
|
||||
variants = await imaging.run_isolated(data, self.settings.worker_max_pixels,
|
||||
self.settings.worker_memory_mb, self.settings.job_timeout)
|
||||
lap('build')
|
||||
ext = {'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/png': 'png'}
|
||||
for v in variants:
|
||||
v['object_key'] = f"variants/{attachment_id}/v{version}/{v['name']}.{ext[v['content_type']]}"
|
||||
await self.storage.put(v['object_key'], v.pop('data'), v['content_type'])
|
||||
await self.storage.copy(job['staging_key'], job['object_key'])
|
||||
lap('store')
|
||||
faults.hit('worker_crash_after_s3')
|
||||
async with self.db.connection() as conn:
|
||||
async with conn.transaction():
|
||||
owned = await conn.fetchval(
|
||||
"UPDATE attachment_jobs SET status = 'done', lease_until = NULL, error_code = NULL, "
|
||||
"last_error = NULL, finished_at = clock_timestamp(), updated_at = clock_timestamp() "
|
||||
"WHERE job_id = $1 AND status = 'processing' AND worker_id = $2 AND attempt = $3 RETURNING 1",
|
||||
job_id, self.worker_id, job['attempt'])
|
||||
if not owned:
|
||||
raise LostLease()
|
||||
for v in variants:
|
||||
await conn.execute(
|
||||
'INSERT INTO attachment_variants (attachment_id, pipeline_version, name, content_type, '
|
||||
'size_bytes, width, height, sha256, object_key) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) '
|
||||
'ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING',
|
||||
attachment_id, version, v['name'], v['content_type'], v['size_bytes'],
|
||||
v['width'], v['height'], v['sha256'], v['object_key'])
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'ready', error_code = NULL, updated_at = clock_timestamp() "
|
||||
"WHERE id = $1 AND status = 'processing'", attachment_id)
|
||||
lap('commit')
|
||||
faults.hit('worker_crash_after_commit')
|
||||
try:
|
||||
await self.storage.delete(job['staging_key']) # staging больше не нужен: результат зафиксирован
|
||||
except ApiError:
|
||||
log.warning('job %s: staging cleanup deferred to retention sweeper', job_id)
|
||||
lap('cleanup')
|
||||
return stages
|
||||
|
||||
async def finish_failed(self, job_id, attachment_id, attempt: int, code: str, reason: str) -> None:
|
||||
async with self.db.connection() as conn:
|
||||
async with conn.transaction():
|
||||
await jobs.fail(conn, job_id, attachment_id, code, reason, worker_id=self.worker_id, attempt=attempt)
|
||||
log.warning('job %s: failed (%s)', job_id, code)
|
||||
|
||||
async def retry_or_fail(self, job_id, attachment_id, job, reason: str) -> None:
|
||||
async with self.db.connection() as conn:
|
||||
async with conn.transaction():
|
||||
if job['attempt'] >= job['max_attempts']:
|
||||
await jobs.fail(conn, job_id, attachment_id, 'retry_exhausted', reason,
|
||||
worker_id=self.worker_id, attempt=job['attempt'])
|
||||
log.warning('job %s: failed, retry_exhausted after %d attempts', job_id, job['attempt'])
|
||||
return
|
||||
delay = jobs.backoff_seconds(job['attempt'], self.settings.retry_base_ms, self.settings.retry_max_ms)
|
||||
await jobs.requeue(conn, job_id, attachment_id, job['attempt'] + 1, delay, reason,
|
||||
worker_id=self.worker_id, attempt=job['attempt'])
|
||||
log.warning('job %s: %s, retry in %.1fs (attempt %d/%d)', job_id, reason, delay,
|
||||
job['attempt'], job['max_attempts'])
|
||||
|
||||
# ---------- обслуживание ----------
|
||||
|
||||
async def maintenance(self) -> None:
|
||||
"""Пульс для healthcheck + retention staging (одна реплика за раз через advisory lock)."""
|
||||
last_sweep = 0.0
|
||||
while not self.stopping.is_set():
|
||||
if self.connection is not None and not self.connection.is_closed:
|
||||
ALIVE_FILE.touch()
|
||||
if time.monotonic() - last_sweep > 300:
|
||||
last_sweep = time.monotonic()
|
||||
try:
|
||||
await self.sweep_staging()
|
||||
except Exception:
|
||||
log.warning('staging sweep failed', exc_info=True)
|
||||
try:
|
||||
await asyncio.wait_for(self.stopping.wait(), 5)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
async def sweep_staging(self) -> None:
|
||||
old = await self.storage.list_older('staging/', self.settings.staging_retention)
|
||||
if not old:
|
||||
return
|
||||
async with self.db.connection() as conn:
|
||||
async with conn.transaction():
|
||||
if not await conn.fetchval('SELECT pg_try_advisory_xact_lock(20260006)'):
|
||||
return
|
||||
# Удаляем только staging, по которому НЕТ текущей работы (queued/processing).
|
||||
active = {r['staging_key'] for r in await conn.fetch(
|
||||
"SELECT staging_key FROM attachments WHERE staging_key = ANY($1::text[]) "
|
||||
"AND status IN ('queued', 'processing')", old)}
|
||||
removed = 0
|
||||
for key in old:
|
||||
if key not in active:
|
||||
await self.storage.delete(key)
|
||||
removed += 1
|
||||
log.info('staging retention: removed %d objects older than %ds', removed, self.settings.staging_retention)
|
||||
|
||||
# ---------- жизненный цикл ----------
|
||||
|
||||
async def run(self) -> None:
|
||||
await self.db.start()
|
||||
loop = asyncio.get_running_loop()
|
||||
for sig in (signal.SIGTERM, signal.SIGINT):
|
||||
loop.add_signal_handler(sig, self.stopping.set)
|
||||
housekeeping = asyncio.create_task(self.maintenance())
|
||||
while True:
|
||||
try:
|
||||
self.connection = await broker.connect(self.settings.broker_url)
|
||||
break
|
||||
except Exception as exc:
|
||||
if self.stopping.is_set():
|
||||
return
|
||||
log.warning('broker not reachable (%s), retrying', type(exc).__name__)
|
||||
await asyncio.sleep(2)
|
||||
channel = await self.connection.channel()
|
||||
# prefetch = сколько неподтверждённых сообщений брокер отдаёт этому worker (ограниченная конкуренция).
|
||||
await channel.set_qos(prefetch_count=self.settings.worker_prefetch)
|
||||
_exchange, queue = await broker.declare(channel)
|
||||
tag = await queue.consume(self.on_message, no_ack=False)
|
||||
log.info('worker %s consuming %s, concurrency=%d prefetch=%d', self.worker_id, broker.QUEUE,
|
||||
self.settings.worker_concurrency, self.settings.worker_prefetch)
|
||||
await self.stopping.wait()
|
||||
# Graceful: перестать брать новые, дождаться текущих (неподтверждённые prefetch вернутся в очередь).
|
||||
await queue.cancel(tag)
|
||||
if self.inflight:
|
||||
log.info('draining %d in-flight jobs', len(self.inflight))
|
||||
await asyncio.wait(self.inflight, timeout=self.settings.job_timeout)
|
||||
housekeeping.cancel()
|
||||
await self.connection.close()
|
||||
await self.db.close()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(name)s %(message)s')
|
||||
asyncio.run(Worker().run())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user