Лабораторная 5 — фоновая обработка вложений
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
"""MTUSI Messenger lab1: in-memory HTTP API (standard library only)."""
|
||||
|
||||
__version__ = '1.0.0'
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Entry point: python -m messenger."""
|
||||
import sys
|
||||
|
||||
from .server import main
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,299 @@
|
||||
"""Domain logic and routing for the lab2 API: PostgreSQL state, Bearer sessions."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import datetime as dt
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from . import cursor as cursor_codec
|
||||
from . import security
|
||||
from . import validation
|
||||
from .attachments import AttachmentStorage, filename_from, upload_file
|
||||
from .db import Database
|
||||
from .errors import ApiError, Conflict, InvalidRequest, NotFound, Unauthorized, Unavailable, UnsupportedMediaType
|
||||
from .store import Store, utc_now, rfc3339
|
||||
|
||||
SCOPE_CHATS = 'chats'
|
||||
SCOPE_MESSAGES = 'chat/{chat_id}/messages'
|
||||
|
||||
|
||||
class Request:
|
||||
"""One parsed HTTP request; the API layer never touches sockets."""
|
||||
|
||||
__slots__ = ('method', 'path', 'query', 'headers', 'body', 'request_id', 'client')
|
||||
|
||||
def __init__(self, method, path, query, headers, body, request_id, client):
|
||||
self.method = method
|
||||
self.path = path
|
||||
self.query = query
|
||||
self.headers = headers
|
||||
self.body = body
|
||||
self.request_id = request_id
|
||||
self.client = client
|
||||
|
||||
|
||||
class Api:
|
||||
UPLOAD_PATH = re.compile(r'^/api/v1/chats/(?P<chat_id>[^/]+)/attachments$')
|
||||
ROUTES = (
|
||||
('POST', UPLOAD_PATH, 'upload_attachment'),
|
||||
('GET', re.compile(r'^/api/v1/attachments/(?P<id>[^/]+)$'), 'get_attachment'),
|
||||
('GET', re.compile(r'^/api/v1/attachments/(?P<id>[^/]+)/content$'), 'download_attachment'),
|
||||
('GET', re.compile(r'^/health/live$'), 'health_live'),
|
||||
('GET', re.compile(r'^/health/ready$'), 'health_ready'),
|
||||
('POST', re.compile(r'^/api/v1/users$'), 'create_user'),
|
||||
('GET', re.compile(r'^/api/v1/users/me$'), 'current_user'),
|
||||
('GET', re.compile(r'^/api/v1/chats$'), 'list_chats'),
|
||||
('POST', re.compile(r'^/api/v1/chats$'), 'create_chat'),
|
||||
('GET', re.compile(r'^/api/v1/chats/(?P<chat_id>[^/]+)$'), 'get_chat'),
|
||||
('GET', re.compile(r'^/api/v1/chats/(?P<chat_id>[^/]+)/messages$'), 'list_messages'),
|
||||
('POST', re.compile(r'^/api/v1/chats/(?P<chat_id>[^/]+)/messages$'), 'post_message'),
|
||||
('POST', re.compile(r'^/api/v1/auth/sessions$'), 'create_session'),
|
||||
('DELETE', re.compile(r'^/api/v1/auth/sessions/current$'), 'revoke_session'),
|
||||
)
|
||||
|
||||
def __init__(self, config, store: Store, database: Database):
|
||||
self.config = config
|
||||
self.store = store
|
||||
self.database = database
|
||||
self.attachments = AttachmentStorage()
|
||||
|
||||
def dispatch(self, request):
|
||||
"""Return (status, payload). Only ApiError and payloads leave this method."""
|
||||
path_matched = False
|
||||
for method, pattern, handler in self.ROUTES:
|
||||
match = pattern.match(request.path)
|
||||
if match:
|
||||
path_matched = True
|
||||
if method == request.method:
|
||||
return getattr(self, handler)(request, match.groupdict())
|
||||
raise NotFound('Маршрут не найден' if not path_matched else 'Метод не поддерживается')
|
||||
|
||||
# ------------------------------------------------------------- health
|
||||
def health_live(self, request, path_params):
|
||||
return 200, {'status': 'ok'}
|
||||
|
||||
def health_ready(self, request, path_params):
|
||||
try:
|
||||
self.database.ping()
|
||||
except Exception:
|
||||
raise Unavailable('База данных недоступна')
|
||||
return 200, {'status': 'ok'}
|
||||
|
||||
# -------------------------------------------------------------- users
|
||||
def create_user(self, request, path_params):
|
||||
payload = self._json_object(request)
|
||||
validation.require_fields(payload, ('username', 'display_name', 'password'),
|
||||
('username', 'display_name', 'password'))
|
||||
username = validation.require_username(payload)
|
||||
display_name = validation.require_text_field(
|
||||
payload, 'display_name', 1, self.config.max_display_name_code_points)
|
||||
password = validation.require_text_field(
|
||||
payload, 'password', 12, 128, strip_check=False)
|
||||
password_hash = security.hash_password(password)
|
||||
return 201, self.store.create_user(username, display_name, password_hash)
|
||||
|
||||
def current_user(self, request, path_params):
|
||||
return 200, self._authenticate(request)
|
||||
|
||||
# -------------------------------------------------------------- chats
|
||||
def create_chat(self, request, path_params):
|
||||
actor = self._authenticate(request)
|
||||
payload = self._json_object(request)
|
||||
validation.require_fields(payload, ('title', 'member_ids'), ('title', 'member_ids'))
|
||||
title = validation.require_text_field(payload, 'title', 1,
|
||||
self.config.max_title_code_points)
|
||||
members = validation.require_member_ids(payload, 100)
|
||||
if actor['id'] not in members:
|
||||
raise InvalidRequest('Создатель чата должен быть указан в member_ids')
|
||||
if not self.store.users_exist(members):
|
||||
raise InvalidRequest('member_ids содержит неизвестных пользователей')
|
||||
return 201, self.store.create_chat(title, members)
|
||||
|
||||
def list_chats(self, request, path_params):
|
||||
actor = self._authenticate(request)
|
||||
limit, after_key = self._pagination(request, SCOPE_CHATS)
|
||||
items, has_more = self.store.page_chats(actor['id'], after_key, limit)
|
||||
for item in items:
|
||||
item['member_ids'] = self._chat_member_ids(item['id'])
|
||||
return 200, {'items': items, 'next_cursor': self._next_cursor(SCOPE_CHATS, items, has_more)}
|
||||
|
||||
def get_chat(self, request, path_params):
|
||||
actor = self._authenticate(request)
|
||||
chat = self._member_chat(actor, path_params['chat_id'])
|
||||
chat['member_ids'] = self._chat_member_ids(chat['id'])
|
||||
return 200, chat
|
||||
|
||||
# ----------------------------------------------------------- messages
|
||||
def post_message(self, request, path_params):
|
||||
actor = self._authenticate(request)
|
||||
chat = self._member_chat(actor, path_params['chat_id'])
|
||||
key = validation.require_idempotency_key(request.headers.get('Idempotency-Key'))
|
||||
payload = self._json_object(request)
|
||||
validation.require_fields(payload, ('text',), ('text', 'attachment_ids'))
|
||||
attachment_ids = validation.require_attachment_ids(payload)
|
||||
text = validation.require_text_field(payload, 'text', 0 if attachment_ids else 1,
|
||||
self.config.max_text_code_points,
|
||||
strip_check=not attachment_ids)
|
||||
return 201, self.store.add_message(chat['id'], actor['id'], text, key, attachment_ids)
|
||||
|
||||
def list_messages(self, request, path_params):
|
||||
actor = self._authenticate(request)
|
||||
chat = self._member_chat(actor, path_params['chat_id'])
|
||||
scope = SCOPE_MESSAGES.format(chat_id=chat['id'])
|
||||
limit, after_key = self._pagination(request, scope)
|
||||
items, has_more = self.store.page_messages(chat['id'], after_key, limit)
|
||||
return 200, {'items': items, 'next_cursor': self._next_cursor(scope, items, has_more)}
|
||||
|
||||
def upload_attachment(self, request, path_params):
|
||||
actor = self._authenticate(request)
|
||||
chat = self._member_chat(actor, path_params['chat_id'])
|
||||
filename = filename_from(request.query)
|
||||
mime = request.headers.get('Content-Type', '').split(';', 1)[0].strip().lower()
|
||||
with upload_file(request.body, mime) as (file, size, digest):
|
||||
aid = str(uuid.uuid4())
|
||||
key = 'attachments/staging/' + aid
|
||||
self.store.reserve_attachment(aid, chat['id'], actor['id'], filename,
|
||||
mime, size, digest, key)
|
||||
row = self.store.queue_attachment(
|
||||
aid, lambda object_key: self.attachments.put(object_key, file, size, mime))
|
||||
return 202, self.store.public_attachment(row)
|
||||
|
||||
def _visible_attachment(self, request, path_params):
|
||||
actor = self._authenticate(request)
|
||||
aid = validation.require_uuid_string(path_params['id'], 'attachment_id')
|
||||
row = self.store.visible_attachment(aid, actor['id'])
|
||||
if row is None:
|
||||
raise NotFound('Вложение не найдено')
|
||||
return row
|
||||
|
||||
def get_attachment(self, request, path_params):
|
||||
row = self._visible_attachment(request, path_params)
|
||||
variants = self.store.attachment_variants(row['id']) if row['status'] == 'ready' else ()
|
||||
return 200, self.store.public_attachment(row, variants)
|
||||
|
||||
def download_attachment(self, request, path_params):
|
||||
row = self._visible_attachment(request, path_params)
|
||||
if row['status'] != 'ready':
|
||||
raise Conflict('Вложение не готово')
|
||||
variant = request.query.get('variant', ['original'])
|
||||
if variant != ['original']:
|
||||
row = next((item for item in self.store.attachment_variants(row['id'])
|
||||
if [item['name']] == variant), None)
|
||||
if row is None:
|
||||
raise NotFound('Вариант вложения не найден')
|
||||
return 200, self.attachments.download(row)
|
||||
|
||||
# ----------------------------------------------------------- sessions
|
||||
def create_session(self, request, path_params):
|
||||
"""Login: only Authorization: Basic username:password, no JSON body."""
|
||||
authorization = request.headers.get('Authorization') or ''
|
||||
if not authorization.lower().startswith('basic '):
|
||||
raise Unauthorized('Требуется авторизация Basic')
|
||||
try:
|
||||
raw = base64.b64decode(authorization[len('basic '):].strip()).decode('utf-8')
|
||||
except Exception:
|
||||
raise Unauthorized('Некорректные учётные данные') from None
|
||||
if ':' not in raw:
|
||||
raise Unauthorized('Некорректные учётные данные')
|
||||
username, password = raw.split(':', 1)
|
||||
row = self.store.user_by_username(username)
|
||||
if row is None or not security.verify_password(password, row['password_hash']):
|
||||
raise Unauthorized('Неверное имя пользователя или пароль', www_authenticate='Basic realm="messenger", charset="UTF-8"')
|
||||
token = security.generate_token()
|
||||
token_hash = security.hash_token(token)
|
||||
expires_at = utc_now() + dt.timedelta(seconds=self.config.session_ttl_seconds)
|
||||
self.store.create_session(token_hash, row['id'], expires_at)
|
||||
user = self.store._public_user({
|
||||
'id': row['id'],
|
||||
'username': row['username'],
|
||||
'display_name': row['display_name'],
|
||||
'created_at': row['created_at'],
|
||||
})
|
||||
return 201, {
|
||||
'token': token,
|
||||
'token_type': 'Bearer',
|
||||
'expires_at': rfc3339(expires_at),
|
||||
'user': user,
|
||||
}
|
||||
|
||||
def revoke_session(self, request, path_params):
|
||||
actor = self._authenticate(request)
|
||||
token = self._bearer_token(request)
|
||||
self.store.delete_session(security.hash_token(token))
|
||||
return 204, None
|
||||
|
||||
# ------------------------------------------------------------- helpers
|
||||
def _authenticate(self, request):
|
||||
"""Lab2 identity: only Authorization: Bearer <token> identifies the actor.
|
||||
|
||||
X-User-Id is ignored: it does not change the session owner and alone
|
||||
grants no access. Basic on business endpoints is 401.
|
||||
"""
|
||||
token = self._bearer_token(request)
|
||||
if token is None:
|
||||
raise Unauthorized('Требуется идентификация пользователя',
|
||||
www_authenticate='Bearer realm="messenger"')
|
||||
user_id = self.store.get_session(security.hash_token(token))
|
||||
if user_id is None:
|
||||
raise Unauthorized('Сессия недействительна или истекла',
|
||||
www_authenticate='Bearer realm="messenger"')
|
||||
user = self.store.user(user_id)
|
||||
if user is None:
|
||||
raise Unauthorized('Пользователь не найден',
|
||||
www_authenticate='Bearer realm="messenger"')
|
||||
return user
|
||||
|
||||
def _bearer_token(self, request):
|
||||
authorization = request.headers.get('Authorization') or ''
|
||||
if not authorization.lower().startswith('bearer '):
|
||||
return None
|
||||
return authorization[len('bearer '):].strip()
|
||||
|
||||
def _chat_member_ids(self, chat_id):
|
||||
with self.database.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
'SELECT user_id FROM chat_members WHERE chat_id = %s', (str(chat_id),))
|
||||
return [str(row['user_id']) for row in cur.fetchall()]
|
||||
|
||||
def _member_chat(self, actor, raw_chat_id):
|
||||
"""Foreign and missing chats are indistinguishable: both are 404."""
|
||||
chat_id = validation.require_uuid_string(raw_chat_id, 'chat_id')
|
||||
chat = self.store.chat(chat_id)
|
||||
if chat is None or not self.store.is_member(chat, actor['id']):
|
||||
raise NotFound('Чат не найден')
|
||||
return chat
|
||||
|
||||
def _json_object(self, request):
|
||||
content_type = request.headers.get('Content-Type') or ''
|
||||
if content_type.split(';')[0].strip().lower() != 'application/json':
|
||||
raise UnsupportedMediaType('Ожидается Content-Type: application/json')
|
||||
if not request.body:
|
||||
raise InvalidRequest('Требуется JSON-тело запроса')
|
||||
try:
|
||||
payload = json.loads(request.body.decode('utf-8'))
|
||||
except (UnicodeError, ValueError):
|
||||
raise InvalidRequest('Тело запроса не является корректным JSON') from None
|
||||
return validation.require_object(payload)
|
||||
|
||||
def _pagination(self, request, scope):
|
||||
raw_limit = (request.query.get('limit') or [None])[0]
|
||||
limit = validation.parse_limit(raw_limit, self.config.default_page_limit,
|
||||
self.config.max_page_limit)
|
||||
raw_cursor = validation.parse_cursor((request.query.get('cursor') or [None])[0])
|
||||
if raw_cursor is None:
|
||||
return limit, None
|
||||
try:
|
||||
stamp, identifier = cursor_codec.decode(raw_cursor, scope, self.config.cursor_secret)
|
||||
except cursor_codec.InvalidCursor:
|
||||
raise InvalidRequest('cursor некорректен или относится к другому ресурсу') from None
|
||||
return limit, (stamp, identifier)
|
||||
|
||||
def _next_cursor(self, scope, items, has_more):
|
||||
if not has_more or not items:
|
||||
return None
|
||||
last = items[-1]
|
||||
return cursor_codec.encode(scope, last['created_at'], last['id'],
|
||||
self.config.cursor_secret)
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Bounded image validation and private S3 storage."""
|
||||
from contextlib import contextmanager
|
||||
import hashlib
|
||||
import os
|
||||
import struct
|
||||
import tempfile
|
||||
import threading
|
||||
import unicodedata
|
||||
from functools import cached_property
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from PIL import Image
|
||||
|
||||
from .errors import InvalidRequest, NotFound, PayloadTooLarge, Unavailable, UnsupportedMediaType
|
||||
|
||||
MAX_UPLOAD_BYTES = 10 * 1024 * 1024
|
||||
MAX_IMAGE_PIXELS = 40_000_000
|
||||
CHUNK_SIZE = 64 * 1024
|
||||
FORMATS = {'PNG': 'image/png', 'JPEG': 'image/jpeg'}
|
||||
# Pillow can allocate a full decoded image. Allow only one decode per API process.
|
||||
_decode_slot = threading.Lock()
|
||||
_upload_slots = threading.BoundedSemaphore(10)
|
||||
|
||||
|
||||
def filename_from(query):
|
||||
names = query.get('filename', [])
|
||||
if len(names) != 1:
|
||||
raise InvalidRequest('Укажите одно имя файла')
|
||||
name = names[0]
|
||||
if (not 1 <= len(name) <= 255 or not name.strip()
|
||||
or any(c in '/\\' or unicodedata.category(c) in {'Cc', 'Cs'} for c in name)):
|
||||
raise InvalidRequest('Некорректное имя файла')
|
||||
return name
|
||||
|
||||
|
||||
def validate_image(file, declared_type):
|
||||
try:
|
||||
with _decode_slot:
|
||||
file.seek(0)
|
||||
with Image.open(file, formats=list(FORMATS)) as image:
|
||||
if image.width * image.height > MAX_IMAGE_PIXELS:
|
||||
raise PayloadTooLarge('Изображение превышает 40 млн пикселей')
|
||||
if FORMATS[image.format] != declared_type:
|
||||
raise UnsupportedMediaType('Тип изображения не совпадает с Content-Type')
|
||||
image.verify()
|
||||
file.seek(0)
|
||||
with Image.open(file, formats=list(FORMATS)) as image:
|
||||
image.load()
|
||||
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
raise PayloadTooLarge('Изображение превышает 40 млн пикселей') from None
|
||||
except (OSError, SyntaxError, ValueError, OverflowError, EOFError, struct.error):
|
||||
raise UnsupportedMediaType('Повреждённое или неподдерживаемое изображение') from None
|
||||
|
||||
|
||||
@contextmanager
|
||||
def upload_file(read_chunks, content_type):
|
||||
if content_type not in FORMATS.values():
|
||||
raise UnsupportedMediaType('Ожидается PNG или JPEG')
|
||||
if not _upload_slots.acquire(blocking=False):
|
||||
raise Unavailable('Слишком много одновременных загрузок')
|
||||
try:
|
||||
with tempfile.TemporaryFile() as file:
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
for chunk in read_chunks():
|
||||
size += len(chunk)
|
||||
if size > MAX_UPLOAD_BYTES:
|
||||
raise PayloadTooLarge()
|
||||
digest.update(chunk)
|
||||
file.write(chunk)
|
||||
if size == 0:
|
||||
raise UnsupportedMediaType('Пустое изображение')
|
||||
validate_image(file, content_type)
|
||||
file.seek(0)
|
||||
yield file, size, digest.hexdigest()
|
||||
finally:
|
||||
_upload_slots.release()
|
||||
|
||||
|
||||
class BinaryResponse:
|
||||
def __init__(self, stream, content_type, size):
|
||||
self.stream = stream
|
||||
self.content_type = content_type
|
||||
self.size = size
|
||||
|
||||
def chunks(self):
|
||||
try:
|
||||
yield from self.stream.iter_chunks(CHUNK_SIZE)
|
||||
except (BotoCoreError, OSError) as exc:
|
||||
raise OSError('S3 response interrupted') from exc
|
||||
|
||||
def close(self):
|
||||
self.stream.close()
|
||||
|
||||
|
||||
class AttachmentStorage:
|
||||
@cached_property
|
||||
def client(self):
|
||||
def secret(name):
|
||||
with open(os.environ[name + '_FILE'], encoding='utf-8') as file:
|
||||
return file.read().strip()
|
||||
return boto3.session.Session().client(
|
||||
's3', endpoint_url=os.environ['S3_ENDPOINT'],
|
||||
region_name=os.environ.get('S3_REGION', 'us-east-1'),
|
||||
aws_access_key_id=secret('S3_ACCESS_KEY_ID'),
|
||||
aws_secret_access_key=secret('S3_SECRET_ACCESS_KEY'),
|
||||
config=Config(connect_timeout=2, read_timeout=5, retries={'total_max_attempts': 1},
|
||||
request_checksum_calculation="when_required",
|
||||
s3={"addressing_style": "path"}))
|
||||
|
||||
@property
|
||||
def bucket(self):
|
||||
return os.environ['S3_BUCKET']
|
||||
|
||||
def put(self, key, file, size, content_type):
|
||||
try:
|
||||
self.client.put_object(Bucket=self.bucket, Key=key, Body=file,
|
||||
ContentLength=size, ContentType=content_type)
|
||||
except (BotoCoreError, ClientError, OSError, KeyError):
|
||||
raise Unavailable('Хранилище вложений недоступно') from None
|
||||
|
||||
def delete(self, key):
|
||||
try:
|
||||
self.client.delete_object(Bucket=self.bucket, Key=key)
|
||||
except (BotoCoreError, ClientError, OSError, KeyError):
|
||||
raise Unavailable('Хранилище вложений недоступно') from None
|
||||
|
||||
def download(self, row):
|
||||
try:
|
||||
obj = self.client.get_object(Bucket=self.bucket, Key=row['object_key'])
|
||||
except ClientError as exc:
|
||||
if exc.response.get('Error', {}).get('Code') in {'NoSuchKey', '404'}:
|
||||
raise NotFound('Оригинал вложения не найден') from None
|
||||
raise Unavailable('Хранилище вложений недоступно') from None
|
||||
except (BotoCoreError, OSError, KeyError):
|
||||
raise Unavailable('Хранилище вложений недоступно') from None
|
||||
if obj['ContentLength'] != row['size_bytes']:
|
||||
obj['Body'].close()
|
||||
raise Unavailable('Размер оригинала не совпадает с метаданными')
|
||||
return BinaryResponse(obj['Body'], row['content_type'], row['size_bytes'])
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Redis session cache with TTL and graceful degradation.
|
||||
|
||||
PostgreSQL is the source of truth for sessions. Redis is a look-aside cache:
|
||||
- write: session is persisted in PostgreSQL first, then copied to Redis with TTL
|
||||
- read: Redis first (fast); on miss, read PostgreSQL and backfill Redis
|
||||
- when Redis is unavailable: fall back to PostgreSQL only, never treat an
|
||||
anonymous request as trusted
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import redis
|
||||
|
||||
from .config import Config
|
||||
|
||||
logger = logging.getLogger('messenger.cache')
|
||||
|
||||
|
||||
class SessionCache:
|
||||
"""Look-aside cache for session tokens in Redis/Valkey."""
|
||||
|
||||
def __init__(self, config: Config):
|
||||
self._config = config
|
||||
self._client = None
|
||||
self._available = False
|
||||
|
||||
def open(self):
|
||||
if not self._config.cache_url:
|
||||
self._available = False
|
||||
return
|
||||
try:
|
||||
self._client = redis.Redis.from_url(
|
||||
self._config.cache_url,
|
||||
socket_connect_timeout=2,
|
||||
socket_timeout=2,
|
||||
socket_keepalive=True,
|
||||
health_check_interval=30,
|
||||
decode_responses=True,
|
||||
)
|
||||
self._client.ping()
|
||||
self._available = True
|
||||
logger.info('cache_connected', extra={'event': 'cache_connected'})
|
||||
except Exception as exc: # noqa: BLE001 - Redis is optional, degrade safely
|
||||
self._available = False
|
||||
self._client = None
|
||||
logger.warning('cache_unavailable', extra={
|
||||
'event': 'cache_unavailable', 'detail': 'falling back to PostgreSQL'})
|
||||
|
||||
def close(self):
|
||||
if self._client is not None:
|
||||
try:
|
||||
self._client.close()
|
||||
except Exception:
|
||||
pass
|
||||
self._client = None
|
||||
self._available = False
|
||||
|
||||
@property
|
||||
def available(self):
|
||||
return self._available and self._client is not None
|
||||
|
||||
def get(self, token_hash):
|
||||
"""Return cached user_id or None (miss or unavailable)."""
|
||||
if not self.available:
|
||||
return None
|
||||
try:
|
||||
value = self._client.get('session:%s' % token_hash)
|
||||
return value
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning('cache_read_failed', extra={
|
||||
'event': 'cache_read_failed', 'detail': 'falling back to PostgreSQL'})
|
||||
self._available = False
|
||||
return None
|
||||
|
||||
def set(self, token_hash, user_id, ttl_seconds):
|
||||
"""Cache a session with TTL. Failure is non-fatal."""
|
||||
if not self.available:
|
||||
return
|
||||
try:
|
||||
self._client.setex('session:%s' % token_hash, ttl_seconds, user_id)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning('cache_write_failed', extra={
|
||||
'event': 'cache_write_failed', 'detail': 'continuing without cache'})
|
||||
self._available = False
|
||||
|
||||
def delete(self, token_hash):
|
||||
"""Remove a session from the cache (logout). Failure is non-fatal."""
|
||||
if not self.available:
|
||||
return
|
||||
try:
|
||||
self._client.delete('session:%s' % token_hash)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning('cache_delete_failed', extra={
|
||||
'event': 'cache_delete_failed'})
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Remove expired upload reservations and their S3 objects."""
|
||||
import argparse
|
||||
import logging
|
||||
import time
|
||||
|
||||
from .attachments import AttachmentStorage
|
||||
from .config import Config
|
||||
from .db import Database
|
||||
from .errors import Unavailable
|
||||
from .store import Store
|
||||
from .job_lifecycle import clean_staging, clean_abandoned_outputs
|
||||
|
||||
GRACE_SECONDS = 15 * 60
|
||||
INTERVAL_SECONDS = 60
|
||||
BATCH_SIZE = 25
|
||||
|
||||
|
||||
def clean_batch(store, storage):
|
||||
count = 0
|
||||
while count < BATCH_SIZE and store.clean_pending_attachment(GRACE_SECONDS, storage.delete):
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--once', action='store_true', help='Process one bounded batch and exit')
|
||||
args = parser.parse_args()
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
config = Config.from_env()
|
||||
database = Database(config)
|
||||
store = Store(config, database, None)
|
||||
storage = AttachmentStorage()
|
||||
try:
|
||||
database.open()
|
||||
while True:
|
||||
try:
|
||||
deleted = clean_batch(store, storage)
|
||||
for cleanup in (clean_staging, clean_abandoned_outputs):
|
||||
for _ in range(BATCH_SIZE):
|
||||
if not cleanup(database, storage.delete):
|
||||
break
|
||||
deleted += 1
|
||||
if deleted or args.once:
|
||||
logging.info('Expired attachment reservations removed: %s', deleted)
|
||||
except Unavailable:
|
||||
logging.warning('Attachment cleanup deferred because a dependency is unavailable')
|
||||
if args.once:
|
||||
return 1
|
||||
if args.once:
|
||||
return 0
|
||||
time.sleep(INTERVAL_SECONDS)
|
||||
finally:
|
||||
database.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Runtime configuration. Every value is read from the environment."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
|
||||
# Contract limits: they cannot be raised by configuration.
|
||||
CONTRACT_MAX_TEXT_CODE_POINTS = 4000
|
||||
CONTRACT_MAX_PAGE_LIMIT = 100
|
||||
CONTRACT_SESSION_TTL_MIN = 1
|
||||
CONTRACT_SESSION_TTL_MAX = 86400
|
||||
|
||||
|
||||
class ConfigError(ValueError):
|
||||
"""Raised when an environment value cannot be used."""
|
||||
|
||||
|
||||
def _str(environ, name, default):
|
||||
value = environ.get(name)
|
||||
if value is None or value == '':
|
||||
return default
|
||||
return value
|
||||
|
||||
|
||||
def _int(environ, name, default, minimum, maximum):
|
||||
raw = environ.get(name)
|
||||
if raw is None or raw == '':
|
||||
return default
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError:
|
||||
raise ConfigError('%s must be an integer, got %r' % (name, raw)) from None
|
||||
if not minimum <= value <= maximum:
|
||||
raise ConfigError('%s must be in %d..%d, got %d' % (name, minimum, maximum, value))
|
||||
return value
|
||||
|
||||
|
||||
def _log_level(environ, name, default):
|
||||
value = _str(environ, name, default).upper()
|
||||
if value not in ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'):
|
||||
raise ConfigError('%s must be one of DEBUG, INFO, WARNING, ERROR, CRITICAL' % name)
|
||||
return value
|
||||
|
||||
|
||||
def _secret_from_file(environ, name, default=None):
|
||||
"""Читает секрет из файла, путь к которому задаёт переменная окружения.
|
||||
|
||||
Секреты не лежат в переменных окружения напрямую: контейнер монтирует
|
||||
файл (например, Docker secret), а приложение читает его содержимое.
|
||||
Если файл не задан или не существует, используется значение переменной
|
||||
окружения без суффикса _FILE (удобно для локального запуска без секретов).
|
||||
"""
|
||||
path_name = name + '_FILE'
|
||||
path = environ.get(path_name)
|
||||
if path:
|
||||
try:
|
||||
with open(path, 'r', encoding='utf-8') as handle:
|
||||
return handle.read().strip()
|
||||
except OSError:
|
||||
pass
|
||||
return environ.get(name) or default
|
||||
|
||||
|
||||
class Config:
|
||||
"""Effective configuration of one process instance."""
|
||||
|
||||
def __init__(self, host, port, env, log_level, cursor_secret, shutdown_grace_seconds,
|
||||
max_text_code_points, max_display_name_code_points, max_title_code_points,
|
||||
default_page_limit, max_page_limit, max_body_bytes,
|
||||
database_url, cache_url, session_ttl_seconds, session_store,
|
||||
pool_min, pool_max, connect_timeout, statement_timeout):
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.env = env
|
||||
self.log_level = log_level
|
||||
self.cursor_secret = cursor_secret
|
||||
self.shutdown_grace_seconds = shutdown_grace_seconds
|
||||
self.max_text_code_points = max_text_code_points
|
||||
self.max_display_name_code_points = max_display_name_code_points
|
||||
self.max_title_code_points = max_title_code_points
|
||||
self.default_page_limit = default_page_limit
|
||||
self.max_page_limit = max_page_limit
|
||||
self.max_body_bytes = max_body_bytes
|
||||
self.database_url = database_url
|
||||
self.cache_url = cache_url
|
||||
self.session_ttl_seconds = session_ttl_seconds
|
||||
self.session_store = session_store
|
||||
self.pool_min = pool_min
|
||||
self.pool_max = pool_max
|
||||
self.connect_timeout = connect_timeout
|
||||
self.statement_timeout = statement_timeout
|
||||
|
||||
@classmethod
|
||||
def from_env(cls, environ=None):
|
||||
environ = os.environ if environ is None else environ
|
||||
secret = _secret_from_file(environ, 'CURSOR_SECRET', '')
|
||||
if not secret:
|
||||
secret = secrets.token_hex(32)
|
||||
session_store = _str(environ, 'SESSION_STORE', 'postgres')
|
||||
if session_store not in ('postgres', 'redis'):
|
||||
raise ConfigError('SESSION_STORE должен быть postgres или redis, got %r' % session_store)
|
||||
return cls(
|
||||
host=_str(environ, 'APP_HOST', '0.0.0.0'),
|
||||
port=_int(environ, 'APP_PORT', 8080, 1, 65535),
|
||||
env=_str(environ, 'APP_ENV', 'lab'),
|
||||
log_level=_log_level(environ, 'LOG_LEVEL', 'INFO'),
|
||||
cursor_secret=secret.encode('utf-8'),
|
||||
shutdown_grace_seconds=_int(environ, 'SHUTDOWN_GRACE_SECONDS', 8, 1, 10),
|
||||
max_text_code_points=_int(environ, 'MAX_TEXT_CODE_POINTS', CONTRACT_MAX_TEXT_CODE_POINTS,
|
||||
1, CONTRACT_MAX_TEXT_CODE_POINTS),
|
||||
max_display_name_code_points=_int(environ, 'MAX_DISPLAY_NAME_CODE_POINTS', 100, 1, 100),
|
||||
max_title_code_points=_int(environ, 'MAX_TITLE_CODE_POINTS', 100, 1, 100),
|
||||
default_page_limit=_int(environ, 'DEFAULT_PAGE_LIMIT', 50, 1, CONTRACT_MAX_PAGE_LIMIT),
|
||||
max_page_limit=_int(environ, 'MAX_PAGE_LIMIT', CONTRACT_MAX_PAGE_LIMIT, 1,
|
||||
CONTRACT_MAX_PAGE_LIMIT),
|
||||
max_body_bytes=_int(environ, 'MAX_BODY_BYTES', 1048576, 1024, 16 * 1048576),
|
||||
database_url=_secret_from_file(environ, 'DATABASE_URL', None),
|
||||
cache_url=_secret_from_file(environ, 'CACHE_URL', None),
|
||||
session_ttl_seconds=_int(environ, 'SESSION_TTL_SECONDS', 3600,
|
||||
CONTRACT_SESSION_TTL_MIN, CONTRACT_SESSION_TTL_MAX),
|
||||
session_store=session_store,
|
||||
pool_min=_int(environ, 'DB_POOL_MIN', 2, 1, 50),
|
||||
pool_max=_int(environ, 'DB_POOL_MAX', 10, 1, 100),
|
||||
connect_timeout=_int(environ, 'DB_CONNECT_TIMEOUT', 5, 1, 60),
|
||||
statement_timeout=_int(environ, 'DB_STATEMENT_TIMEOUT', 10, 1, 300),
|
||||
)
|
||||
|
||||
def as_log_fields(self):
|
||||
"""Configuration summary safe for logs (no secrets)."""
|
||||
return {
|
||||
'app_env': self.env,
|
||||
'host': self.host,
|
||||
'port': self.port,
|
||||
'log_level': self.log_level,
|
||||
'shutdown_grace_seconds': self.shutdown_grace_seconds,
|
||||
'default_page_limit': self.default_page_limit,
|
||||
'max_page_limit': self.max_page_limit,
|
||||
'max_text_code_points': self.max_text_code_points,
|
||||
'max_body_bytes': self.max_body_bytes,
|
||||
'cursor_secret_configured': bool(os.environ.get('CURSOR_SECRET')),
|
||||
'database_url_configured': bool(self.database_url),
|
||||
'cache_url_configured': bool(self.cache_url),
|
||||
'session_ttl_seconds': self.session_ttl_seconds,
|
||||
'session_store': self.session_store,
|
||||
'db_pool_min': self.pool_min,
|
||||
'db_pool_max': self.pool_max,
|
||||
'db_connect_timeout': self.connect_timeout,
|
||||
'db_statement_timeout': self.statement_timeout,
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Opaque keyset cursors: HMAC-protected (created_at, id) plus a resource scope."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import uuid
|
||||
|
||||
VERSION = 1
|
||||
MAC_BYTES = 16
|
||||
|
||||
|
||||
class InvalidCursor(ValueError):
|
||||
"""Cursor is malformed, forged, expired or belongs to another resource."""
|
||||
|
||||
|
||||
def _key(secret):
|
||||
return hashlib.sha256(b'mtusi-messenger-cursor-v1' + secret).digest()
|
||||
|
||||
|
||||
def encode(scope, created_at, object_id, secret):
|
||||
"""Serialize a keyset position bound to one resource scope."""
|
||||
payload = json.dumps(
|
||||
{'v': VERSION, 'scope': scope, 'created_at': created_at, 'id': str(object_id)},
|
||||
separators=(',', ':'), sort_keys=True).encode('utf-8')
|
||||
mac = hmac.new(_key(secret), payload, hashlib.sha256).digest()[:MAC_BYTES]
|
||||
return base64.urlsafe_b64encode(payload + mac).decode('ascii').rstrip('=')
|
||||
|
||||
|
||||
def decode(token, scope, secret):
|
||||
"""Return (created_at datetime, uuid) or raise InvalidCursor."""
|
||||
if not isinstance(token, str) or not token:
|
||||
raise InvalidCursor('empty cursor')
|
||||
padding = '=' * (-len(token) % 4)
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(token + padding)
|
||||
except (binascii.Error, ValueError):
|
||||
raise InvalidCursor('cursor is not base64url') from None
|
||||
if len(raw) <= MAC_BYTES:
|
||||
raise InvalidCursor('cursor is too short')
|
||||
payload, mac = raw[:-MAC_BYTES], raw[-MAC_BYTES:]
|
||||
if not hmac.compare_digest(mac, hmac.new(_key(secret), payload, hashlib.sha256).digest()[:MAC_BYTES]):
|
||||
raise InvalidCursor('cursor signature mismatch')
|
||||
try:
|
||||
data = json.loads(payload.decode('utf-8'))
|
||||
except (ValueError, UnicodeError):
|
||||
raise InvalidCursor('cursor payload is not JSON') from None
|
||||
if not isinstance(data, dict) or data.get('v') != VERSION:
|
||||
raise InvalidCursor('unsupported cursor version')
|
||||
if data.get('scope') != scope:
|
||||
raise InvalidCursor('cursor belongs to another resource')
|
||||
created_at = data.get('created_at')
|
||||
object_id = data.get('id')
|
||||
if not isinstance(created_at, str) or not isinstance(object_id, str):
|
||||
raise InvalidCursor('cursor payload types')
|
||||
try:
|
||||
stamp = dt.datetime.fromisoformat(created_at.replace('Z', '+00:00'))
|
||||
identifier = uuid.UUID(object_id)
|
||||
except ValueError:
|
||||
raise InvalidCursor('cursor payload values') from None
|
||||
if stamp.tzinfo is None:
|
||||
raise InvalidCursor('cursor timestamp has no timezone')
|
||||
return stamp.astimezone(dt.timezone.utc), identifier
|
||||
@@ -0,0 +1,97 @@
|
||||
"""PostgreSQL connection pool and schema migrations."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from psycopg2 import pool, OperationalError, InterfaceError
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from .config import Config
|
||||
from .errors import Unavailable
|
||||
|
||||
_ROOT = Path(__file__).resolve().parents[2]
|
||||
_MIGRATIONS_DIR = _ROOT / 'migrations'
|
||||
|
||||
|
||||
class Database:
|
||||
"""Thread-safe connection pool with prepared statement timeouts.
|
||||
|
||||
All queries are parameterised (%s). Connections are returned to the pool
|
||||
after every operation; the pool itself is closed on shutdown.
|
||||
"""
|
||||
|
||||
def __init__(self, config: Config):
|
||||
self._config = config
|
||||
self._pool = None
|
||||
|
||||
def open(self):
|
||||
if self._pool is not None:
|
||||
return
|
||||
try:
|
||||
self._pool = pool.ThreadedConnectionPool(
|
||||
minconn=self._config.pool_min,
|
||||
maxconn=self._config.pool_max,
|
||||
dsn=self._config.database_url,
|
||||
connect_timeout=self._config.connect_timeout,
|
||||
cursor_factory=RealDictCursor,
|
||||
)
|
||||
except Exception as exc: # psycopg2.Error or configuration error
|
||||
raise Unavailable('Не удалось подключиться к PostgreSQL: %s' % exc) from None
|
||||
|
||||
def close(self):
|
||||
if self._pool is not None:
|
||||
self._pool.closeall()
|
||||
self._pool = None
|
||||
|
||||
@contextmanager
|
||||
def connection(self):
|
||||
"""Yield a connection; rollback on exception, return to pool on exit."""
|
||||
if self._pool is None:
|
||||
raise Unavailable('База данных не инициализирована')
|
||||
try:
|
||||
conn = self._pool.getconn()
|
||||
except (pool.PoolError, OperationalError, InterfaceError):
|
||||
raise Unavailable('Пул соединений PostgreSQL недоступен') from None
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute('SET statement_timeout = %s',
|
||||
(self._config.statement_timeout * 1000,))
|
||||
yield conn
|
||||
except Exception as exc:
|
||||
try:
|
||||
conn.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
if isinstance(exc, (OperationalError, InterfaceError)):
|
||||
raise Unavailable('PostgreSQL недоступен') from None
|
||||
raise
|
||||
finally:
|
||||
self._pool.putconn(conn, close=bool(conn.closed))
|
||||
|
||||
@contextmanager
|
||||
def cursor(self):
|
||||
"""Yield a cursor inside a connection; commit on success, rollback on failure."""
|
||||
with self.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
yield cur
|
||||
conn.commit()
|
||||
|
||||
def ping(self):
|
||||
with self.cursor() as cur:
|
||||
cur.execute('SELECT 1')
|
||||
cur.fetchone()
|
||||
|
||||
def run_migrations(self):
|
||||
"""Apply versioned migrations once, under a transaction advisory lock."""
|
||||
with self.cursor() as cur:
|
||||
cur.execute('SELECT pg_advisory_xact_lock(3072026)')
|
||||
cur.execute('CREATE TABLE IF NOT EXISTS schema_migrations '
|
||||
'(name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())')
|
||||
for path in sorted(_MIGRATIONS_DIR.glob('*.sql')):
|
||||
cur.execute('SELECT 1 FROM schema_migrations WHERE name = %s', (path.name,))
|
||||
if cur.fetchone() is not None:
|
||||
continue
|
||||
cur.execute(path.read_text(encoding='utf-8'))
|
||||
cur.execute('INSERT INTO schema_migrations(name) VALUES (%s)', (path.name,))
|
||||
@@ -0,0 +1,73 @@
|
||||
"""API error taxonomy; every message is safe to return to a client."""
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
"""Base class for errors that map onto the public error payload."""
|
||||
|
||||
status = 500
|
||||
code = 'internal_error'
|
||||
default_message = 'Внутренняя ошибка сервера'
|
||||
|
||||
def __init__(self, message=None):
|
||||
self.message = message or self.default_message
|
||||
super().__init__(self.message)
|
||||
|
||||
|
||||
class InvalidRequest(ApiError):
|
||||
status = 400
|
||||
code = 'invalid_request'
|
||||
default_message = 'Некорректный запрос'
|
||||
|
||||
|
||||
class Unauthorized(ApiError):
|
||||
status = 401
|
||||
code = 'unauthorized'
|
||||
default_message = 'Требуется идентификация пользователя'
|
||||
www_authenticate = None
|
||||
|
||||
def __init__(self, message=None, www_authenticate=None):
|
||||
self.message = message or self.default_message
|
||||
self.www_authenticate = www_authenticate
|
||||
super().__init__(self.message)
|
||||
|
||||
|
||||
class NotFound(ApiError):
|
||||
status = 404
|
||||
code = 'not_found'
|
||||
default_message = 'Объект не найден'
|
||||
|
||||
|
||||
class Conflict(ApiError):
|
||||
status = 409
|
||||
code = 'conflict'
|
||||
default_message = 'Конфликт состояния'
|
||||
|
||||
|
||||
class PayloadTooLarge(ApiError):
|
||||
status = 413
|
||||
code = 'payload_too_large'
|
||||
default_message = 'Тело запроса слишком велико'
|
||||
|
||||
|
||||
class UnsupportedMediaType(ApiError):
|
||||
status = 415
|
||||
code = 'unsupported_media_type'
|
||||
default_message = 'Поддерживается только application/json'
|
||||
|
||||
|
||||
class RateLimited(ApiError):
|
||||
status = 429
|
||||
code = 'rate_limited'
|
||||
default_message = 'Слишком много запросов'
|
||||
|
||||
|
||||
class Unavailable(ApiError):
|
||||
status = 503
|
||||
code = 'unavailable'
|
||||
default_message = 'Сервис временно недоступен'
|
||||
|
||||
|
||||
class InternalError(ApiError):
|
||||
status = 500
|
||||
code = 'internal_error'
|
||||
default_message = 'Внутренняя ошибка сервера'
|
||||
@@ -0,0 +1,39 @@
|
||||
"""List failed jobs and explicitly replay a failed job with retained staging."""
|
||||
import argparse
|
||||
import json
|
||||
from uuid import UUID
|
||||
|
||||
from .config import Config
|
||||
from .db import Database
|
||||
from .errors import ApiError
|
||||
from .job_lifecycle import replay
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
actions = parser.add_subparsers(dest='action', required=True)
|
||||
actions.add_parser('list')
|
||||
command = actions.add_parser('replay')
|
||||
command.add_argument('job_id', type=UUID)
|
||||
command.add_argument('--operator', required=True)
|
||||
args = parser.parse_args()
|
||||
database = Database(Config.from_env())
|
||||
database.open()
|
||||
try:
|
||||
if args.action == 'replay':
|
||||
print(json.dumps({'job_id': str(args.job_id), 'attempt': replay(database, str(args.job_id), args.operator)}))
|
||||
else:
|
||||
with database.cursor() as cur:
|
||||
cur.execute("SELECT j.id AS job_id,a.id AS attachment_id,a.error_code,j.attempt, "
|
||||
"j.staging_cleaned_at IS NULL AS staging_retained "
|
||||
"FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id "
|
||||
"WHERE a.status='failed' ORDER BY a.updated_at DESC LIMIT 100")
|
||||
print(json.dumps(cur.fetchall(), default=str))
|
||||
except ApiError as exc:
|
||||
parser.exit(1, str(exc) + '\n')
|
||||
finally:
|
||||
database.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,135 @@
|
||||
"""Transactional claims, bounded retries and explicit failed-job recovery."""
|
||||
import os
|
||||
import random
|
||||
|
||||
from .errors import Conflict, NotFound
|
||||
|
||||
LEASE_SECONDS = 60
|
||||
STAGING_RETENTION_SECONDS = 86400
|
||||
MAX_ATTEMPTS = int(os.getenv('JOB_MAX_ATTEMPTS', '5'))
|
||||
if not 1 <= MAX_ATTEMPTS <= 20:
|
||||
raise ValueError('JOB_MAX_ATTEMPTS must be between 1 and 20')
|
||||
|
||||
|
||||
def _locked_job(cur, job_id):
|
||||
cur.execute(
|
||||
'SELECT j.*, a.status, a.updated_at, a.error_code, '
|
||||
'j.lease_until > clock_timestamp() AS lease_valid FROM attachment_jobs j '
|
||||
'JOIN attachments a ON a.id=j.attachment_id WHERE j.id=%s FOR UPDATE OF j,a',
|
||||
(job_id,))
|
||||
return cur.fetchone()
|
||||
|
||||
|
||||
def claim(db, delivery):
|
||||
with db.cursor() as cur:
|
||||
row = _locked_job(cur, delivery['job_id'])
|
||||
if (not row or row['status'] != 'queued' or row['attempt'] != delivery['attempt']
|
||||
or str(row['attachment_id']) != delivery['attachment_id']
|
||||
or row['pipeline_version'] != delivery['pipeline_version']):
|
||||
return None
|
||||
cur.execute('UPDATE attachment_jobs SET lease_until=clock_timestamp()+make_interval(secs => %s), '
|
||||
'attempts_used=attempts_used+1 WHERE id=%s', (LEASE_SECONDS, row['id']))
|
||||
cur.execute("UPDATE attachments SET status='processing', updated_at=now() "
|
||||
"WHERE id=%s RETURNING *", (row['attachment_id'],))
|
||||
return cur.fetchone()
|
||||
|
||||
|
||||
def _requeue(cur, row, delay, reset=False):
|
||||
attempt = row['attempt'] + 1
|
||||
cur.execute('UPDATE attachment_jobs SET attempt=%s, lease_until=NULL, attempts_used=%s WHERE id=%s',
|
||||
(attempt, 0 if reset else row['attempts_used'], row['id']))
|
||||
cur.execute("UPDATE attachments SET status='queued', error_code=NULL, updated_at=now() WHERE id=%s",
|
||||
(row['attachment_id'],))
|
||||
cur.execute('INSERT INTO attachment_outbox (job_id,attempt,available_at) '
|
||||
'VALUES (%s,%s,now()+make_interval(secs => %s))', (row['id'], attempt, delay))
|
||||
return attempt
|
||||
|
||||
|
||||
def _fail_or_retry(cur, row, error_code):
|
||||
if error_code is None and row['attempts_used'] < MAX_ATTEMPTS:
|
||||
delay = min(60, 2 ** row['attempts_used']) * random.uniform(.75, 1.25)
|
||||
_requeue(cur, row, delay)
|
||||
return
|
||||
cur.execute('UPDATE attachment_jobs SET lease_until=NULL WHERE id=%s', (row['id'],))
|
||||
cur.execute("UPDATE attachments SET status='failed', error_code=%s, updated_at=now() WHERE id=%s",
|
||||
(error_code or 'retry_exhausted', row['attachment_id']))
|
||||
|
||||
|
||||
def complete(db, delivery, result=None, error_code=None):
|
||||
with db.cursor() as cur:
|
||||
row = _locked_job(cur, delivery['job_id'])
|
||||
if (not row or row['status'] != 'processing'
|
||||
or row['attempt'] != delivery['attempt'] or not row['lease_valid']):
|
||||
return False
|
||||
if result is None:
|
||||
_fail_or_retry(cur, row, error_code)
|
||||
return True
|
||||
key, variants = result
|
||||
cur.executemany(
|
||||
'INSERT INTO attachment_variants (attachment_id,pipeline_version,variant,object_key,'
|
||||
'content_type,size_bytes,sha256,width,height) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)',
|
||||
[(row['attachment_id'], row['pipeline_version'], *item) for item in variants])
|
||||
cur.execute("UPDATE attachments SET object_key=%s,status='ready',updated_at=now() WHERE id=%s",
|
||||
(key, row['attachment_id']))
|
||||
cur.execute('UPDATE attachment_jobs SET lease_until=NULL WHERE id=%s', (row['id'],))
|
||||
return True
|
||||
|
||||
|
||||
def recover_expired(db):
|
||||
with db.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT j.* FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id "
|
||||
"WHERE a.status='processing' AND j.lease_until <= now() "
|
||||
"ORDER BY j.lease_until LIMIT 10 FOR UPDATE OF j,a SKIP LOCKED")
|
||||
for row in cur.fetchall():
|
||||
_fail_or_retry(cur, row, None)
|
||||
|
||||
|
||||
def replay(db, job_id, operator):
|
||||
with db.cursor() as cur:
|
||||
row = _locked_job(cur, job_id)
|
||||
if row is None:
|
||||
raise NotFound('Задача не найдена')
|
||||
if row['status'] != 'failed' or row['staging_cleaned_at'] is not None:
|
||||
raise Conflict('Повтор доступен только для failed с сохранённым исходником')
|
||||
attempt = _requeue(cur, row, 0, reset=True)
|
||||
cur.execute('INSERT INTO attachment_replays (job_id,attempt,operator) VALUES (%s,%s,%s)',
|
||||
(job_id, attempt, operator))
|
||||
return attempt
|
||||
|
||||
|
||||
def clean_staging(db, remove):
|
||||
with db.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT j.id,j.attachment_id FROM attachment_jobs j "
|
||||
"JOIN attachments a ON a.id=j.attachment_id "
|
||||
"WHERE j.staging_cleaned_at IS NULL AND (a.status='ready' OR "
|
||||
"(a.status='failed' AND a.updated_at < now()-make_interval(secs => %s))) "
|
||||
"LIMIT 1 FOR UPDATE OF j,a SKIP LOCKED", (STAGING_RETENTION_SECONDS,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return False
|
||||
remove('attachments/staging/' + str(row['attachment_id']))
|
||||
cur.execute('UPDATE attachment_jobs SET staging_cleaned_at=now() WHERE id=%s', (row['id'],))
|
||||
return True
|
||||
|
||||
|
||||
def clean_abandoned_outputs(db, remove):
|
||||
with db.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT j.id,j.attachment_id,j.pipeline_version,o.attempt "
|
||||
"FROM attachment_outbox o JOIN attachment_jobs j ON j.id=o.job_id "
|
||||
"JOIN attachments a ON a.id=j.attachment_id "
|
||||
"WHERE o.objects_cleaned_at IS NULL AND o.available_at < now()-interval '15 minutes' "
|
||||
"AND (o.attempt < j.attempt OR (a.status='failed' AND "
|
||||
"a.updated_at < now()-interval '15 minutes')) "
|
||||
"ORDER BY o.available_at LIMIT 1 FOR UPDATE OF o SKIP LOCKED")
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return False
|
||||
prefix = 'attachments/final/{attachment_id}/v{pipeline_version}/a{attempt}/'.format(**row)
|
||||
for name in ('original', 'thumbnail.jpeg', 'crop.jpeg', 'optimized.webp'):
|
||||
remove(prefix + name)
|
||||
cur.execute('UPDATE attachment_outbox SET objects_cleaned_at=now() WHERE job_id=%s AND attempt=%s',
|
||||
(row['id'], row['attempt']))
|
||||
return True
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Structured stdout logging without payload contents."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
|
||||
_FIELDS = ('event', 'request_id', 'method', 'route', 'status', 'duration_ms', 'actor_id',
|
||||
'error_code', 'client', 'outcome', 'count', 'detail', 'signal', 'version')
|
||||
|
||||
|
||||
class JsonFormatter(logging.Formatter):
|
||||
"""One JSON object per line; message text of API payloads is never logged."""
|
||||
|
||||
def format(self, record):
|
||||
payload = {
|
||||
'ts': time.strftime('%Y-%m-%dT%H:%M:%S', time.gmtime(record.created)) +
|
||||
'.%03dZ' % int(record.msecs),
|
||||
'level': record.levelname.lower(),
|
||||
'logger': record.name,
|
||||
'message': record.getMessage(),
|
||||
}
|
||||
for field in _FIELDS:
|
||||
value = getattr(record, field, None)
|
||||
if value is not None:
|
||||
payload[field] = value
|
||||
if record.exc_info and record.levelno >= logging.ERROR:
|
||||
payload['exception'] = record.exc_info[0].__name__
|
||||
return json.dumps(payload, ensure_ascii=False, sort_keys=True)
|
||||
|
||||
|
||||
def configure(level_name):
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setFormatter(JsonFormatter())
|
||||
root = logging.getLogger()
|
||||
for existing in list(root.handlers):
|
||||
root.removeHandler(existing)
|
||||
root.addHandler(handler)
|
||||
root.setLevel(getattr(logging, level_name))
|
||||
return logging.getLogger('messenger')
|
||||
|
||||
|
||||
def access_logger():
|
||||
return logging.getLogger('messenger.access')
|
||||
@@ -0,0 +1,17 @@
|
||||
"""One-shot schema migration entry point; API processes never migrate."""
|
||||
from .config import Config
|
||||
from .db import Database
|
||||
|
||||
|
||||
def main():
|
||||
database = Database(Config.from_env())
|
||||
try:
|
||||
database.open()
|
||||
database.run_migrations()
|
||||
print('PASS: migrations applied')
|
||||
finally:
|
||||
database.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Publish committed attachment jobs using RabbitMQ publisher confirms."""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import time
|
||||
|
||||
import pika
|
||||
|
||||
from .config import Config
|
||||
from .db import Database
|
||||
from .errors import Unavailable
|
||||
from .store import rfc3339
|
||||
from .job_lifecycle import recover_expired
|
||||
|
||||
QUEUE = 'attachment.process.v1'
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def connect():
|
||||
password = Path(os.environ['RABBITMQ_PASSWORD_FILE']).read_text().strip()
|
||||
return pika.BlockingConnection(pika.ConnectionParameters(
|
||||
host='rabbitmq', credentials=pika.PlainCredentials('lab5', password),
|
||||
heartbeat=30, socket_timeout=3, stack_timeout=5, blocked_connection_timeout=5))
|
||||
|
||||
|
||||
def publish_one(database, channel):
|
||||
with database.cursor() as cur:
|
||||
cur.execute(
|
||||
'SELECT j.id, j.attachment_id, j.pipeline_version, j.created_at, o.attempt '
|
||||
'FROM attachment_outbox o JOIN attachment_jobs j ON j.id=o.job_id '
|
||||
'WHERE o.published_at IS NULL AND o.available_at <= now() '
|
||||
'ORDER BY o.available_at, o.job_id LIMIT 1 FOR UPDATE OF o SKIP LOCKED')
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return False
|
||||
job = {
|
||||
'schema_version': 1, 'job_id': str(row['id']), 'type': QUEUE,
|
||||
'attachment_id': str(row['attachment_id']),
|
||||
'pipeline_version': row['pipeline_version'], 'attempt': row['attempt'],
|
||||
'created_at': rfc3339(row['created_at']),
|
||||
}
|
||||
channel.basic_publish(
|
||||
exchange='', routing_key=QUEUE, body=json.dumps(job).encode(),
|
||||
properties=pika.BasicProperties(content_type='application/json',
|
||||
delivery_mode=2, message_id=job['job_id']),
|
||||
mandatory=True)
|
||||
cur.execute('UPDATE attachment_outbox SET published_at=now() WHERE job_id=%s AND attempt=%s',
|
||||
(row['id'], row['attempt']))
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
database = Database(Config.from_env())
|
||||
database.open()
|
||||
try:
|
||||
while True:
|
||||
connection = None
|
||||
try:
|
||||
connection = connect()
|
||||
channel = connection.channel()
|
||||
channel.queue_declare(queue=QUEUE, durable=True)
|
||||
channel.confirm_delivery()
|
||||
next_recovery = 0
|
||||
while True:
|
||||
if time.monotonic() >= next_recovery:
|
||||
recover_expired(database)
|
||||
next_recovery = time.monotonic() + 1
|
||||
if not publish_one(database, channel):
|
||||
connection.sleep(.25)
|
||||
else:
|
||||
connection.process_data_events()
|
||||
except (pika.exceptions.AMQPError, OSError, Unavailable) as exc:
|
||||
log.warning('Publisher will retry: %s', type(exc).__name__)
|
||||
time.sleep(2)
|
||||
finally:
|
||||
if connection and connection.is_open:
|
||||
try:
|
||||
connection.close()
|
||||
except pika.exceptions.AMQPError:
|
||||
pass
|
||||
finally:
|
||||
database.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Password hashing and session tokens.
|
||||
|
||||
Passwords are hashed with a library password KDF: scrypt from the standard
|
||||
library when available, otherwise bcrypt with a SHA-256 pre-hash so that
|
||||
passwords longer than bcrypt's 72-byte limit are still supported.
|
||||
Session tokens are opaque random values (>= 256 bits of entropy); only their
|
||||
SHA-256 is stored in the database.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
|
||||
import bcrypt
|
||||
|
||||
try: # scrypt is part of hashlib on OpenSSL-enabled builds
|
||||
hashlib.scrypt(b'x', salt=b's', n=16, r=8, p=1, dklen=16)
|
||||
_HAS_SCRYPT = True
|
||||
except Exception:
|
||||
_HAS_SCRYPT = False
|
||||
|
||||
if not _HAS_SCRYPT:
|
||||
import bcrypt # type: ignore
|
||||
|
||||
SCRYPT_N = 16384
|
||||
SCRYPT_R = 8
|
||||
SCRYPT_P = 1
|
||||
SCRYPT_DKLEN = 32
|
||||
SALT_BYTES = 16
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""Hash a UTF-8 password with a library password KDF.
|
||||
|
||||
Returns a single storable string:
|
||||
scrypt:$n:$r:$p:$salt_b64:$hash_b64
|
||||
or
|
||||
bcrypt:$salt_b64:$hash_b64
|
||||
"""
|
||||
raw = password.encode('utf-8')
|
||||
if _HAS_SCRYPT:
|
||||
salt = secrets.token_bytes(SALT_BYTES)
|
||||
dk = hashlib.scrypt(
|
||||
raw,
|
||||
salt=salt,
|
||||
n=SCRYPT_N,
|
||||
r=SCRYPT_R,
|
||||
p=SCRYPT_P,
|
||||
dklen=SCRYPT_DKLEN,
|
||||
)
|
||||
return 'scrypt:%d:%d:%d:%s:%s' % (
|
||||
SCRYPT_N, SCRYPT_R, SCRYPT_P,
|
||||
base64.b64encode(salt).decode('ascii'),
|
||||
base64.b64encode(dk).decode('ascii'),
|
||||
)
|
||||
# bcrypt limits input to 72 bytes; pre-hash with SHA-256 so long passwords
|
||||
# (up to 128 code points per contract) are fully covered.
|
||||
digest = hashlib.sha256(raw).digest()
|
||||
hashed = bcrypt.hashpw(digest, bcrypt.gensalt(rounds=12))
|
||||
return 'bcrypt:%s' % hashed.decode('ascii')
|
||||
|
||||
|
||||
def verify_password(password: str, password_hash: str) -> bool:
|
||||
"""Verify a password against a KDF hash string. Constant-time compare."""
|
||||
try:
|
||||
raw = password.encode('utf-8')
|
||||
if password_hash.startswith('scrypt:'):
|
||||
parts = password_hash.split(':')
|
||||
if len(parts) != 6 or parts[0] != 'scrypt':
|
||||
return False
|
||||
_, n, r, p, salt_b64, hash_b64 = parts
|
||||
salt = base64.b64decode(salt_b64)
|
||||
expected = base64.b64decode(hash_b64)
|
||||
dk = hashlib.scrypt(
|
||||
raw,
|
||||
salt=salt,
|
||||
n=int(n), r=int(r), p=int(p),
|
||||
dklen=len(expected),
|
||||
)
|
||||
return hmac.compare_digest(dk, expected)
|
||||
if password_hash.startswith('bcrypt:'):
|
||||
stored = password_hash[len('bcrypt:'):].encode('ascii')
|
||||
digest = hashlib.sha256(raw).digest()
|
||||
return bcrypt.checkpw(digest, stored)
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def generate_token() -> str:
|
||||
"""Opaque random bearer token, at least 256 bits of entropy."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def hash_token(token: str) -> str:
|
||||
"""SHA-256 of a bearer token, stored in the database instead of the token itself."""
|
||||
return hashlib.sha256(token.encode('utf-8')).hexdigest()
|
||||
@@ -0,0 +1,305 @@
|
||||
"""HTTP/1.1 front end: request ids, structured logs, graceful SIGTERM shutdown."""
|
||||
from __future__ import annotations
|
||||
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import signal
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from . import __version__, logging_utils
|
||||
from .api import Api, Request
|
||||
from .attachments import BinaryResponse, CHUNK_SIZE, MAX_UPLOAD_BYTES
|
||||
from .cache import SessionCache
|
||||
from .config import Config, ConfigError
|
||||
from .db import Database
|
||||
from .errors import ApiError, InvalidRequest, PayloadTooLarge, Unavailable
|
||||
from .store import Store
|
||||
|
||||
MAX_REQUEST_ID_LENGTH = 128
|
||||
MAX_LOGGED_LINE = 200
|
||||
|
||||
|
||||
def sanitize_request_id(raw):
|
||||
"""Echo a safe client id, otherwise generate one. Never trust raw input."""
|
||||
if raw and len(raw) <= MAX_REQUEST_ID_LENGTH and all(0x21 <= ord(ch) <= 0x7E for ch in raw):
|
||||
return raw
|
||||
return uuid.uuid4().hex
|
||||
|
||||
|
||||
def route_template(path):
|
||||
for _method, pattern, _handler in Api.ROUTES:
|
||||
if pattern.match(path):
|
||||
return pattern.pattern.replace('[^/]+', '{chat_id}').strip('^$')
|
||||
return 'unmatched'
|
||||
|
||||
|
||||
def encode_payload(payload):
|
||||
return json.dumps(payload, ensure_ascii=False, separators=(',', ':')).encode('utf-8')
|
||||
|
||||
|
||||
class ApiServer(ThreadingHTTPServer):
|
||||
"""Threaded server that tracks in-flight requests and stops accepting on demand."""
|
||||
|
||||
daemon_threads = True
|
||||
allow_reuse_address = True
|
||||
request_queue_size = 128
|
||||
|
||||
def __init__(self, address, api, config, logger, database):
|
||||
self.api = api
|
||||
self.config = config
|
||||
self.logger = logger
|
||||
self.database = database
|
||||
self.instance_id = os.environ.get("HOSTNAME") or uuid.uuid4().hex
|
||||
self.shutting_down = False
|
||||
self._active = 0
|
||||
self._idle = threading.Condition()
|
||||
super().__init__(address, ApiHandler)
|
||||
|
||||
def enter(self):
|
||||
with self._idle:
|
||||
self._active += 1
|
||||
|
||||
def leave(self):
|
||||
with self._idle:
|
||||
self._active -= 1
|
||||
if self._active == 0:
|
||||
self._idle.notify_all()
|
||||
|
||||
def wait_idle(self, timeout):
|
||||
deadline = time.monotonic() + timeout
|
||||
with self._idle:
|
||||
while self._active > 0:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
return False
|
||||
self._idle.wait(remaining)
|
||||
return True
|
||||
|
||||
|
||||
class ApiHandler(BaseHTTPRequestHandler):
|
||||
protocol_version = 'HTTP/1.1'
|
||||
server_version = 'mtusi-messenger/' + __version__
|
||||
sys_version = ''
|
||||
timeout = 30
|
||||
|
||||
# --------------------------------------------------------- entry points
|
||||
def do_GET(self):
|
||||
self._handle()
|
||||
|
||||
do_HEAD = do_POST = do_PUT = do_PATCH = do_DELETE = do_OPTIONS = do_GET
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
"""Base-class chatter stays debug-only; access logs are structured."""
|
||||
self.server.logger.debug('http_note', extra={
|
||||
'event': 'http_note', 'detail': (fmt % args)[:MAX_LOGGED_LINE]})
|
||||
|
||||
# ------------------------------------------------------------- pipeline
|
||||
def _handle(self):
|
||||
started = time.monotonic()
|
||||
server = self.server
|
||||
request_id = sanitize_request_id(self.headers.get('X-Request-Id'))
|
||||
head_only = self.command == 'HEAD'
|
||||
path = urlsplit(self.path).path
|
||||
status, error_code = 500, None
|
||||
self._last_exc = None
|
||||
server.enter()
|
||||
try:
|
||||
if server.shutting_down:
|
||||
raise Unavailable('Сервер завершает работу')
|
||||
if self.command == 'POST' and Api.UPLOAD_PATH.fullmatch(path):
|
||||
# Rejected uploads may leave unread bytes in the connection.
|
||||
self.close_connection = True
|
||||
body = self._upload_chunks
|
||||
else:
|
||||
body = self._read_body()
|
||||
query = parse_qs(urlsplit(self.path).query, keep_blank_values=True)
|
||||
request = Request('GET' if head_only else self.command, path, query, self.headers,
|
||||
body, request_id, self.client_address[0])
|
||||
status, payload = server.api.dispatch(request)
|
||||
encoded = payload if isinstance(payload, BinaryResponse) else encode_payload(payload)
|
||||
except ApiError as exc:
|
||||
self._last_exc = exc
|
||||
status, error_code = exc.status, exc.code
|
||||
encoded = self._error_payload(exc, request_id)
|
||||
except Exception: # last resort: log privately, answer generically
|
||||
server.logger.exception('unhandled_error', extra={
|
||||
'event': 'unhandled_error', 'request_id': request_id,
|
||||
'method': self.command, 'route': route_template(path)})
|
||||
status, error_code = 500, 'internal_error'
|
||||
encoded = self._error_payload(ApiError(), request_id)
|
||||
finally:
|
||||
server.logger.info('http_request', extra={
|
||||
'event': 'http_request', 'request_id': request_id, 'method': self.command,
|
||||
'route': route_template(path), 'status': status,
|
||||
'duration_ms': round(1000 * (time.monotonic() - started), 3),
|
||||
'error_code': error_code, 'client': self.client_address[0]})
|
||||
try:
|
||||
self._send(status, encoded, request_id, head_only)
|
||||
finally:
|
||||
if isinstance(encoded, BinaryResponse):
|
||||
encoded.close()
|
||||
server.leave()
|
||||
|
||||
def _read_body(self):
|
||||
if self.headers.get('Transfer-Encoding'):
|
||||
self.close_connection = True
|
||||
raise InvalidRequest('Transfer-Encoding не поддерживается')
|
||||
raw_length = self.headers.get('Content-Length')
|
||||
if raw_length is None:
|
||||
return b''
|
||||
try:
|
||||
length = int(raw_length.strip())
|
||||
except ValueError:
|
||||
raise InvalidRequest('Некорректный Content-Length') from None
|
||||
if length < 0:
|
||||
raise InvalidRequest('Некорректный Content-Length')
|
||||
if length > self.server.config.max_body_bytes:
|
||||
self.close_connection = True
|
||||
raise PayloadTooLarge('Тело запроса больше %d байт' % self.server.config.max_body_bytes)
|
||||
if length == 0:
|
||||
return b''
|
||||
return self.rfile.read(length)
|
||||
|
||||
def _upload_chunks(self):
|
||||
if self.headers.get('Transfer-Encoding'):
|
||||
raise InvalidRequest('Требуется Content-Length')
|
||||
lengths = self.headers.get_all('Content-Length') or []
|
||||
try:
|
||||
length = int(lengths[0]) if len(lengths) == 1 else -1
|
||||
except ValueError:
|
||||
length = -1
|
||||
if length < 0:
|
||||
raise InvalidRequest('Некорректный Content-Length')
|
||||
if length > MAX_UPLOAD_BYTES:
|
||||
raise PayloadTooLarge()
|
||||
deadline = time.monotonic() + 30
|
||||
while length:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise InvalidRequest('Истекло время загрузки')
|
||||
self.connection.settimeout(min(5, remaining))
|
||||
try:
|
||||
chunk = self.rfile.read1(min(CHUNK_SIZE, length))
|
||||
except OSError:
|
||||
raise InvalidRequest('Загрузка прервана') from None
|
||||
finally:
|
||||
self.connection.settimeout(self.timeout)
|
||||
if not chunk:
|
||||
raise InvalidRequest('Загрузка прервана')
|
||||
length -= len(chunk)
|
||||
yield chunk
|
||||
|
||||
@staticmethod
|
||||
def _error_payload(exc, request_id):
|
||||
return encode_payload({'error': {
|
||||
'code': exc.code, 'message': exc.message, 'request_id': request_id}})
|
||||
|
||||
def _send(self, status, encoded, request_id, head_only):
|
||||
try:
|
||||
self.send_response(status)
|
||||
binary = isinstance(encoded, BinaryResponse)
|
||||
self.send_header('Content-Type', encoded.content_type if binary else 'application/json; charset=utf-8')
|
||||
self.send_header('X-Request-Id', request_id)
|
||||
self.send_header('X-Instance-Id', self.server.instance_id)
|
||||
self.send_header('Cache-Control', 'no-store')
|
||||
if status == 204:
|
||||
self.send_header('Content-Length', '0')
|
||||
if status == 503:
|
||||
self.send_header('Retry-After', '1')
|
||||
self.end_headers()
|
||||
return
|
||||
self.send_header('Content-Length', str(encoded.size if binary else len(encoded)))
|
||||
if status == 503:
|
||||
self.send_header('Retry-After', '1')
|
||||
if status == 401 and self._last_exc is not None:
|
||||
www_auth = getattr(self._last_exc, 'www_authenticate', None)
|
||||
if www_auth:
|
||||
self.send_header('WWW-Authenticate', www_auth)
|
||||
if self.close_connection:
|
||||
self.send_header('Connection', 'close')
|
||||
self.end_headers()
|
||||
if not head_only and encoded:
|
||||
if binary:
|
||||
for chunk in encoded.chunks():
|
||||
self.wfile.write(chunk)
|
||||
else:
|
||||
self.wfile.write(encoded)
|
||||
except OSError:
|
||||
self.close_connection = True
|
||||
|
||||
|
||||
def build_server(config, logger, api, database):
|
||||
"""Create the listening server; raises OSError when the port is taken."""
|
||||
return ApiServer((config.host, config.port), api, config, logger, database)
|
||||
|
||||
|
||||
def run(config, logger, database, cache):
|
||||
"""Serve until SIGTERM/SIGINT, then drain in-flight work within the grace period."""
|
||||
api = Api(config, Store(config, database, cache), database)
|
||||
try:
|
||||
server = build_server(config, logger, api, database)
|
||||
except OSError as exc:
|
||||
logger.error('listen_failed', extra={'event': 'listen_failed', 'detail': str(exc)})
|
||||
return 1
|
||||
stop = threading.Event()
|
||||
|
||||
def handle_signal(signum, _frame):
|
||||
if stop.is_set():
|
||||
return
|
||||
stop.set()
|
||||
server.shutting_down = True
|
||||
logger.warning('shutdown_signal', extra={
|
||||
'event': 'shutdown_signal', 'signal': signum,
|
||||
'detail': 'stop accepting new requests'})
|
||||
threading.Thread(target=server.shutdown, name='shutdown', daemon=True).start()
|
||||
|
||||
for name in ('SIGTERM', 'SIGINT'):
|
||||
if hasattr(signal, name):
|
||||
signal.signal(getattr(signal, name), handle_signal)
|
||||
|
||||
logger.info('server_started', extra=dict(
|
||||
{'event': 'server_started', 'version': __version__,
|
||||
'detail': 'pid %d, python %s' % (os.getpid(), platform.python_version())},
|
||||
**config.as_log_fields()))
|
||||
started = time.monotonic()
|
||||
try:
|
||||
server.serve_forever(poll_interval=0.2)
|
||||
finally:
|
||||
server.server_close()
|
||||
drained = server.wait_idle(config.shutdown_grace_seconds)
|
||||
database.close()
|
||||
logger.info('server_stopped', extra={
|
||||
'event': 'server_stopped',
|
||||
'outcome': 'graceful' if drained else 'grace_period_exceeded',
|
||||
'duration_ms': round(1000 * (time.monotonic() - started), 3)})
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
try:
|
||||
config = Config.from_env()
|
||||
except ConfigError as exc:
|
||||
print('configuration error: %s' % exc, file=sys.stderr)
|
||||
return 2
|
||||
logger = logging_utils.configure(config.log_level)
|
||||
database = Database(config)
|
||||
cache = SessionCache(config)
|
||||
try:
|
||||
database.open()
|
||||
cache.open()
|
||||
except Exception as exc: # noqa: BLE001 - startup must fail loud and clear
|
||||
logger.error('database_start_failed', extra={
|
||||
'event': 'database_start_failed', 'detail': str(exc)})
|
||||
database.close()
|
||||
cache.close()
|
||||
return 1
|
||||
try:
|
||||
return run(config, logger, database, cache)
|
||||
finally:
|
||||
cache.close()
|
||||
@@ -0,0 +1,390 @@
|
||||
"""PostgreSQL-backed state store. All writes go through parameterised queries
|
||||
inside explicit transactions; reads use keyset pagination over indexed columns."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
from psycopg2.extras import Json
|
||||
from psycopg2.errors import UniqueViolation, ForeignKeyViolation
|
||||
import uuid
|
||||
|
||||
from . import cursor as cursor_codec
|
||||
from . import security
|
||||
from .cache import SessionCache
|
||||
from .config import Config
|
||||
from .db import Database
|
||||
from .errors import Conflict, InvalidRequest, NotFound
|
||||
|
||||
|
||||
def utc_now():
|
||||
return dt.datetime.now(dt.timezone.utc)
|
||||
|
||||
|
||||
def rfc3339(stamp):
|
||||
"""RFC 3339 UTC with fixed microsecond precision and the Z suffix."""
|
||||
return stamp.astimezone(dt.timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
||||
|
||||
|
||||
class Store:
|
||||
"""PostgreSQL state: users, chats, membership, messages, sessions."""
|
||||
|
||||
def __init__(self, config: Config, database: Database, cache: SessionCache):
|
||||
self._config = config
|
||||
self._db = database
|
||||
self._cache = cache
|
||||
|
||||
# ---------------------------------------------------------------- reads
|
||||
def stats(self):
|
||||
with self._db.cursor() as cur:
|
||||
cur.execute('SELECT (SELECT count(*) FROM users) AS users,'
|
||||
' (SELECT count(*) FROM chats) AS chats,'
|
||||
' (SELECT count(*) FROM messages) AS messages')
|
||||
row = cur.fetchone()
|
||||
return {
|
||||
'users': row['users'],
|
||||
'chats': row['chats'],
|
||||
'messages': row['messages'],
|
||||
}
|
||||
|
||||
def user(self, user_id):
|
||||
with self._db.cursor() as cur:
|
||||
cur.execute(
|
||||
'SELECT id, username, display_name, created_at FROM users WHERE id = %s',
|
||||
(str(user_id),))
|
||||
row = cur.fetchone()
|
||||
return self._public_user(row) if row else None
|
||||
|
||||
def user_by_username(self, username):
|
||||
"""Return user row including password_hash, or None."""
|
||||
with self._db.cursor() as cur:
|
||||
cur.execute(
|
||||
'SELECT id, username, password_hash, display_name, created_at FROM users '
|
||||
'WHERE username = %s', (username,))
|
||||
return cur.fetchone()
|
||||
|
||||
def users_exist(self, identifiers):
|
||||
if not identifiers:
|
||||
return True
|
||||
with self._db.cursor() as cur:
|
||||
cur.execute(
|
||||
'SELECT count(*) AS c FROM users WHERE id = ANY(%s::uuid[])',
|
||||
([str(i) for i in identifiers],))
|
||||
row = cur.fetchone()
|
||||
return row['c'] == len(identifiers)
|
||||
|
||||
# --------------------------------------------------------------- writes
|
||||
def create_user(self, username, display_name, password_hash):
|
||||
with self._db.cursor() as cur:
|
||||
try:
|
||||
cur.execute(
|
||||
'INSERT INTO users (id, username, password_hash, display_name, created_at) '
|
||||
'VALUES (%s, %s, %s, %s, %s) '
|
||||
'RETURNING id, username, display_name, created_at',
|
||||
(str(uuid.uuid4()), username, password_hash, display_name, utc_now()))
|
||||
except UniqueViolation:
|
||||
# Unique violation on username -> conflict, rolled back by cursor context.
|
||||
raise Conflict('username уже занят') from None
|
||||
row = cur.fetchone()
|
||||
return self._public_user(row)
|
||||
|
||||
def create_chat(self, title, member_ids):
|
||||
"""Atomically create a chat and its membership. Rollback on any failure."""
|
||||
identifier = str(uuid.uuid4())
|
||||
stamp = utc_now()
|
||||
with self._db.cursor() as cur:
|
||||
try:
|
||||
cur.execute(
|
||||
'INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)',
|
||||
(identifier, title, stamp))
|
||||
for member_id in member_ids:
|
||||
cur.execute(
|
||||
'INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)',
|
||||
(identifier, str(member_id)))
|
||||
except ForeignKeyViolation:
|
||||
raise InvalidRequest('member_ids содержит неизвестных пользователей') from None
|
||||
return {
|
||||
'id': identifier,
|
||||
'title': title,
|
||||
'member_ids': list(member_ids),
|
||||
'created_at': rfc3339(stamp),
|
||||
}
|
||||
|
||||
def reserve_attachment(self, aid, chat_id, owner_id, filename, mime, size, digest, key):
|
||||
with self._db.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, "
|
||||
"size_bytes, sha256, object_key, status) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,'pending')",
|
||||
(aid, chat_id, owner_id, filename, mime, size, digest, key))
|
||||
|
||||
def queue_attachment(self, aid, put_object):
|
||||
"""Keep a row lock from before PUT until staging metadata, job and outbox commit."""
|
||||
with self._db.cursor() as cur:
|
||||
cur.execute("SELECT object_key FROM attachments WHERE id=%s "
|
||||
"AND status='pending' FOR UPDATE", (aid,))
|
||||
pending = cur.fetchone()
|
||||
if pending is None:
|
||||
raise Conflict('Загрузка вложения не может быть завершена')
|
||||
put_object(pending['object_key'])
|
||||
job_id = str(uuid.uuid4())
|
||||
cur.execute('INSERT INTO attachment_jobs (id, attachment_id, pipeline_version) '
|
||||
'VALUES (%s,%s,1)', (job_id, aid))
|
||||
cur.execute('INSERT INTO attachment_outbox (job_id, attempt) VALUES (%s,1)', (job_id,))
|
||||
cur.execute("UPDATE attachments SET status='queued', updated_at=now() "
|
||||
"WHERE id=%s RETURNING *", (aid,))
|
||||
return cur.fetchone()
|
||||
|
||||
def clean_pending_attachment(self, grace_seconds, delete_object):
|
||||
"""Remove one expired reservation and its object, or leave it for retry."""
|
||||
with self._db.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, object_key FROM attachments WHERE status='pending' "
|
||||
"AND updated_at < now() - make_interval(secs => %s) "
|
||||
"ORDER BY updated_at, id LIMIT 1 FOR UPDATE SKIP LOCKED",
|
||||
(grace_seconds,))
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return False
|
||||
delete_object(row['object_key'])
|
||||
cur.execute('DELETE FROM attachments WHERE id=%s', (row['id'],))
|
||||
return True
|
||||
|
||||
def visible_attachment(self, aid, user_id):
|
||||
with self._db.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT a.* FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id "
|
||||
"WHERE a.id=%s AND m.user_id=%s AND a.status<>'pending'", (aid, user_id))
|
||||
return cur.fetchone()
|
||||
|
||||
def attachment_variants(self, aid):
|
||||
with self._db.cursor() as cur:
|
||||
cur.execute(
|
||||
'SELECT DISTINCT ON (variant) variant AS name, object_key, content_type, '
|
||||
'size_bytes, sha256, width, height FROM attachment_variants '
|
||||
'WHERE attachment_id=%s ORDER BY variant, pipeline_version DESC', (aid,))
|
||||
return cur.fetchall()
|
||||
|
||||
@staticmethod
|
||||
def public_attachment(row, variants=()):
|
||||
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'],
|
||||
'error_code': row['error_code'],
|
||||
'variants': [{k: v for k, v in item.items() if k != 'object_key'} for item in variants],
|
||||
'created_at': rfc3339(row['created_at']), 'updated_at': rfc3339(row['updated_at']),
|
||||
}
|
||||
|
||||
def add_message(self, chat_id, sender_id, text, key, attachment_ids=()):
|
||||
"""One transaction owns both the message and its replayable result.
|
||||
|
||||
The advisory lock serializes only the same user/method/path/key across
|
||||
processes. Hash collisions serialize extra requests, never alias keys:
|
||||
the complete key is still checked against the primary key in the table.
|
||||
A crash before COMMIT rolls back the message, links and replay record. A lost reply after COMMIT
|
||||
is recovered by replay. Transient failures are never recorded.
|
||||
"""
|
||||
path = '/api/v1/chats/%s/messages' % chat_id
|
||||
body = {'text': text}
|
||||
# Keep the lab3 digest for text-only requests, including explicit [].
|
||||
if attachment_ids:
|
||||
body['attachment_ids'] = list(attachment_ids)
|
||||
body_hash = hashlib.sha256(json.dumps(body, ensure_ascii=False,
|
||||
sort_keys=True).encode('utf-8')).hexdigest()
|
||||
scope = json.dumps([str(sender_id), 'POST', path, key], separators=(',', ':'))
|
||||
lock_id = int.from_bytes(hashlib.sha256(scope.encode()).digest()[:8], 'big', signed=True)
|
||||
identifier = str(uuid.uuid4())
|
||||
stamp = utc_now()
|
||||
with self._db.cursor() as cur:
|
||||
cur.execute('SELECT pg_advisory_xact_lock(%s)', (lock_id,))
|
||||
cur.execute('SELECT request_hash, response_body FROM message_idempotency '
|
||||
'WHERE user_id=%s AND method=%s AND path=%s AND key=%s',
|
||||
(str(sender_id), 'POST', path, key))
|
||||
replay = cur.fetchone()
|
||||
if replay is not None:
|
||||
if replay['request_hash'] != body_hash:
|
||||
raise Conflict('Idempotency-Key уже использован с другим телом запроса')
|
||||
return {'attachment_ids': [], **replay['response_body']}
|
||||
if attachment_ids:
|
||||
cur.execute(
|
||||
'SELECT id, status FROM attachments WHERE chat_id=%s AND id=ANY(%s::uuid[]) FOR SHARE',
|
||||
(str(chat_id), list(attachment_ids)))
|
||||
attachments = cur.fetchall()
|
||||
if len(attachments) != len(attachment_ids):
|
||||
raise NotFound('Вложение не найдено')
|
||||
if any(row['status'] not in ('ready', 'queued', 'processing') for row in attachments):
|
||||
raise Conflict('Вложение не готово')
|
||||
cur.execute(
|
||||
'INSERT INTO messages (id, chat_id, sender_id, text, created_at) '
|
||||
'VALUES (%s, %s, %s, %s, %s) '
|
||||
'RETURNING id, chat_id, sender_id, text, created_at',
|
||||
(identifier, str(chat_id), str(sender_id), text, stamp))
|
||||
result = self._public_message(cur.fetchone())
|
||||
if attachment_ids:
|
||||
cur.executemany(
|
||||
'INSERT INTO message_attachments (message_id, attachment_id, chat_id, position) '
|
||||
'VALUES (%s,%s,%s,%s)',
|
||||
[(identifier, aid, str(chat_id), pos) for pos, aid in enumerate(attachment_ids)])
|
||||
result['attachment_ids'] = list(attachment_ids)
|
||||
cur.execute('INSERT INTO message_idempotency '
|
||||
'(user_id, method, path, key, request_hash, response_status, response_body) '
|
||||
'VALUES (%s,%s,%s,%s,%s,201,%s)',
|
||||
(str(sender_id), 'POST', path, key, body_hash, Json(result)))
|
||||
return result
|
||||
|
||||
# --------------------------------------------------------------- pages
|
||||
def page_messages(self, chat_id, after_key, limit):
|
||||
"""Return (public messages, has_more) for a keyset window."""
|
||||
with self._db.cursor() as cur:
|
||||
if after_key is None:
|
||||
cur.execute(
|
||||
'SELECT id, chat_id, sender_id, text, created_at FROM messages '
|
||||
'WHERE chat_id = %s '
|
||||
'ORDER BY created_at, id '
|
||||
'LIMIT %s', (str(chat_id), limit + 1))
|
||||
else:
|
||||
stamp, identifier = after_key
|
||||
cur.execute(
|
||||
'SELECT id, chat_id, sender_id, text, created_at FROM messages '
|
||||
'WHERE chat_id = %s '
|
||||
'AND (created_at, id) > (%s, %s) '
|
||||
'ORDER BY created_at, id '
|
||||
'LIMIT %s',
|
||||
(str(chat_id), stamp, str(identifier), limit + 1))
|
||||
rows = cur.fetchall()
|
||||
items = [self._public_message(row) for row in rows[:limit]]
|
||||
if items:
|
||||
by_id = {item['id']: item for item in items}
|
||||
cur.execute(
|
||||
'SELECT message_id, attachment_id FROM message_attachments '
|
||||
'WHERE message_id=ANY(%s::uuid[]) ORDER BY message_id, position',
|
||||
(list(by_id),))
|
||||
for row in cur.fetchall():
|
||||
by_id[str(row['message_id'])]['attachment_ids'].append(str(row['attachment_id']))
|
||||
has_more = len(rows) > limit
|
||||
return items, has_more
|
||||
|
||||
def page_chats(self, user_id, after_key, limit):
|
||||
"""Return (chats visible to the user, has_more) ordered by (created_at, id)."""
|
||||
with self._db.cursor() as cur:
|
||||
if after_key is None:
|
||||
cur.execute(
|
||||
'SELECT c.id, c.title, c.created_at FROM chats c '
|
||||
'JOIN chat_members cm ON cm.chat_id = c.id '
|
||||
'WHERE cm.user_id = %s '
|
||||
'ORDER BY c.created_at, c.id '
|
||||
'LIMIT %s', (str(user_id), limit + 1))
|
||||
else:
|
||||
stamp, identifier = after_key
|
||||
cur.execute(
|
||||
'SELECT c.id, c.title, c.created_at FROM chats c '
|
||||
'JOIN chat_members cm ON cm.chat_id = c.id '
|
||||
'WHERE cm.user_id = %s '
|
||||
'AND (c.created_at, c.id) > (%s, %s) '
|
||||
'ORDER BY c.created_at, c.id '
|
||||
'LIMIT %s',
|
||||
(str(user_id), stamp, str(identifier), limit + 1))
|
||||
rows = cur.fetchall()
|
||||
has_more = len(rows) > limit
|
||||
items = [self._public_chat(dict(row)) for row in rows[:limit]]
|
||||
return items, has_more
|
||||
|
||||
# ----------------------------------------------------------- projection
|
||||
def chat(self, chat_id):
|
||||
with self._db.cursor() as cur:
|
||||
cur.execute(
|
||||
'SELECT id, title, created_at FROM chats WHERE id = %s', (str(chat_id),))
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
chat = self._public_chat(dict(row))
|
||||
cur.execute(
|
||||
'SELECT user_id FROM chat_members WHERE chat_id = %s', (str(chat_id),))
|
||||
chat['member_ids'] = [str(r['user_id']) for r in cur.fetchall()]
|
||||
return chat
|
||||
|
||||
@staticmethod
|
||||
def is_member(chat, user_id):
|
||||
return str(user_id) in chat['member_ids']
|
||||
|
||||
@staticmethod
|
||||
def _public_user(row):
|
||||
return {
|
||||
'id': str(row['id']),
|
||||
'username': row['username'],
|
||||
'display_name': row['display_name'],
|
||||
'created_at': rfc3339(row['created_at']),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _public_chat(row):
|
||||
return {
|
||||
'id': str(row['id']),
|
||||
'title': row['title'],
|
||||
'member_ids': [], # filled by API when needed
|
||||
'created_at': rfc3339(row['created_at']),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _public_message(row):
|
||||
return {
|
||||
'id': str(row['id']),
|
||||
'chat_id': str(row['chat_id']),
|
||||
'sender_id': str(row['sender_id']),
|
||||
'text': row['text'],
|
||||
'attachment_ids': [],
|
||||
'created_at': rfc3339(row['created_at']),
|
||||
}
|
||||
|
||||
# --------------------------------------------------------------- sessions
|
||||
def create_session(self, token_hash, user_id, expires_at):
|
||||
with self._db.cursor() as cur:
|
||||
cur.execute(
|
||||
'INSERT INTO sessions (token_hash, user_id, expires_at, created_at) '
|
||||
'VALUES (%s, %s, %s, %s)',
|
||||
(token_hash, str(user_id), expires_at, utc_now()))
|
||||
ttl = max(1, int((expires_at - utc_now()).total_seconds()))
|
||||
self._cache.set(token_hash, str(user_id), ttl)
|
||||
|
||||
def get_session(self, token_hash):
|
||||
"""Return user_id for a valid non-expired session, or None.
|
||||
|
||||
The cache is consulted first, but every cache hit is re-validated
|
||||
against PostgreSQL so that a revoked or expired session is never
|
||||
trusted from a stale Redis key. On miss, read PostgreSQL and
|
||||
backfill the cache. Expired sessions found during lookup are deleted.
|
||||
"""
|
||||
cached = self._cache.get(token_hash)
|
||||
if cached is not None:
|
||||
with self._db.cursor() as cur:
|
||||
cur.execute(
|
||||
'SELECT 1 FROM sessions WHERE token_hash = %s AND expires_at > %s',
|
||||
(token_hash, utc_now()))
|
||||
if cur.fetchone() is None:
|
||||
self._cache.delete(token_hash)
|
||||
return None
|
||||
return cached
|
||||
with self._db.cursor() as cur:
|
||||
cur.execute(
|
||||
'SELECT user_id, expires_at FROM sessions WHERE token_hash = %s',
|
||||
(token_hash,))
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
if row['expires_at'] <= utc_now():
|
||||
cur.execute('DELETE FROM sessions WHERE token_hash = %s', (token_hash,))
|
||||
return None
|
||||
user_id = str(row['user_id'])
|
||||
ttl = max(1, int((row['expires_at'] - utc_now()).total_seconds()))
|
||||
self._cache.set(token_hash, user_id, ttl)
|
||||
return user_id
|
||||
|
||||
def delete_session(self, token_hash):
|
||||
self._cache.delete(token_hash)
|
||||
with self._db.cursor() as cur:
|
||||
cur.execute('DELETE FROM sessions WHERE token_hash = %s', (token_hash,))
|
||||
|
||||
def cleanup_expired_sessions(self):
|
||||
with self._db.cursor() as cur:
|
||||
cur.execute('DELETE FROM sessions WHERE expires_at <= %s', (utc_now(),))
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Strict request payload validation; any deviation is 400 invalid_request."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from .errors import InvalidRequest
|
||||
|
||||
USERNAME_PATTERN = re.compile(r'[a-z0-9_]{3,32}')
|
||||
DIGITS_PATTERN = re.compile(r'[0-9]+')
|
||||
|
||||
|
||||
def safe_label(value):
|
||||
"""Render untrusted text for an error message without breaking its encoding.
|
||||
|
||||
Field names come straight from the client JSON, so they may contain the same
|
||||
lone surrogates that the payload itself is rejected for.
|
||||
"""
|
||||
text = value if isinstance(value, str) else repr(value)
|
||||
return text.encode('utf-8', 'replace').decode('utf-8')
|
||||
|
||||
|
||||
def require_encodable(value, name):
|
||||
"""Reject text that cannot survive a UTF-8 round trip.
|
||||
|
||||
`json.loads` happily produces lone surrogates from `\ud800` escapes. Such a
|
||||
string cannot be UTF-8 encoded, so it must be rejected before it is stored;
|
||||
otherwise the write is committed and the response encoding fails afterwards.
|
||||
"""
|
||||
try:
|
||||
value.encode('utf-8')
|
||||
except UnicodeEncodeError:
|
||||
raise InvalidRequest(
|
||||
'Поле %s содержит недопустимые символы Unicode' % name) from None
|
||||
return value
|
||||
|
||||
|
||||
def require_object(payload):
|
||||
if not isinstance(payload, dict):
|
||||
raise InvalidRequest('Тело запроса должно быть JSON-объектом')
|
||||
return payload
|
||||
|
||||
|
||||
def require_fields(payload, required, allowed):
|
||||
"""Reject missing required fields and any unknown field."""
|
||||
missing = [name for name in required if name not in payload]
|
||||
if missing:
|
||||
raise InvalidRequest('Отсутствуют обязательные поля: ' + ', '.join(sorted(missing)))
|
||||
extra = [name for name in payload if name not in allowed]
|
||||
if extra:
|
||||
raise InvalidRequest('Неизвестные поля: ' + ', '.join(sorted(safe_label(n) for n in extra)))
|
||||
return payload
|
||||
|
||||
|
||||
def require_text_field(payload, name, minimum, maximum, strip_check=True):
|
||||
value = payload.get(name)
|
||||
if not isinstance(value, str):
|
||||
raise InvalidRequest('Поле %s должно быть строкой' % name)
|
||||
require_encodable(value, name)
|
||||
if strip_check and not value.strip():
|
||||
raise InvalidRequest('Поле %s не может быть пустым или состоять из пробелов' % name)
|
||||
if len(value) < minimum:
|
||||
raise InvalidRequest('Поле %s короче %d символов' % (name, minimum))
|
||||
if len(value) > maximum:
|
||||
raise InvalidRequest('Поле %s длиннее %d символов' % (name, maximum))
|
||||
return value
|
||||
|
||||
|
||||
def require_username(payload):
|
||||
username = payload.get('username')
|
||||
# fullmatch, not match: a trailing "$" would also accept a final newline.
|
||||
if not isinstance(username, str) or USERNAME_PATTERN.fullmatch(username) is None:
|
||||
raise InvalidRequest('username должен соответствовать ^[a-z0-9_]{3,32}$')
|
||||
return require_encodable(username, 'username')
|
||||
|
||||
|
||||
def require_uuid_string(value, name):
|
||||
if not isinstance(value, str):
|
||||
raise InvalidRequest('Поле %s должно быть строкой UUID' % name)
|
||||
try:
|
||||
return str(uuid.UUID(value))
|
||||
except ValueError:
|
||||
raise InvalidRequest('Поле %s не является корректным UUID' % name) from None
|
||||
|
||||
|
||||
def require_attachment_ids(payload):
|
||||
value = payload.get('attachment_ids', [])
|
||||
if not isinstance(value, list) or len(value) > 10:
|
||||
raise InvalidRequest('attachment_ids должен содержать от 0 до 10 UUID')
|
||||
identifiers = [require_uuid_string(item, 'attachment_ids') for item in value]
|
||||
if len(set(identifiers)) != len(identifiers):
|
||||
raise InvalidRequest('attachment_ids содержит повторяющиеся UUID')
|
||||
return identifiers
|
||||
|
||||
|
||||
def require_member_ids(payload, maximum, minimum=1):
|
||||
value = payload.get('member_ids')
|
||||
if not isinstance(value, list):
|
||||
raise InvalidRequest('member_ids должен быть массивом UUID')
|
||||
if not minimum <= len(value) <= maximum:
|
||||
raise InvalidRequest('member_ids должен содержать от %d до %d участников' % (minimum, maximum))
|
||||
identifiers = [require_uuid_string(item, 'member_ids') for item in value]
|
||||
if len(set(identifiers)) != len(identifiers):
|
||||
raise InvalidRequest('member_ids содержит повторяющихся участников')
|
||||
return identifiers
|
||||
|
||||
|
||||
def parse_limit(raw, default, maximum):
|
||||
"""Parse a limit query value strictly: absent means default, anything else must be a plain integer.
|
||||
|
||||
An empty value is a client error rather than an absent parameter, and the
|
||||
digit run is length-bounded before int() because Python refuses to convert
|
||||
strings longer than its integer-string limit, which would surface as a 500.
|
||||
"""
|
||||
if raw is None:
|
||||
return default
|
||||
if not DIGITS_PATTERN.fullmatch(raw):
|
||||
raise InvalidRequest('limit должен быть целым числом от 1 до %d' % maximum)
|
||||
# int() refuses absurdly long digit strings (ValueError -> 500). Comparing the
|
||||
# significant digits against the maximum first rejects them without converting.
|
||||
significant = raw.lstrip('0') or '0'
|
||||
if len(significant) > len(str(maximum)):
|
||||
raise InvalidRequest('limit должен быть в диапазоне 1..%d' % maximum)
|
||||
value = int(significant)
|
||||
if not 1 <= value <= maximum:
|
||||
raise InvalidRequest('limit должен быть в диапазоне 1..%d' % maximum)
|
||||
return value
|
||||
|
||||
|
||||
def parse_cursor(raw):
|
||||
if raw is None:
|
||||
return None
|
||||
if not isinstance(raw, str) or not raw:
|
||||
raise InvalidRequest('cursor должен быть непустой строкой')
|
||||
return raw
|
||||
|
||||
|
||||
def require_idempotency_key(value):
|
||||
"""Only the contract's bounded ASCII token is accepted."""
|
||||
if not isinstance(value, str) or re.fullmatch(r'[A-Za-z0-9._:-]{1,128}', value) is None:
|
||||
raise InvalidRequest('Требуется корректный Idempotency-Key (1–128 ASCII символов)')
|
||||
return value
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Process attachment jobs and acknowledge only committed results."""
|
||||
import hashlib
|
||||
from io import BytesIO
|
||||
import json
|
||||
import logging
|
||||
import signal
|
||||
import tempfile
|
||||
from uuid import UUID
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
import pika
|
||||
|
||||
from .attachments import AttachmentStorage, MAX_UPLOAD_BYTES, validate_image
|
||||
from .config import Config
|
||||
from .db import Database
|
||||
from .errors import NotFound, PayloadTooLarge, Unavailable, UnsupportedMediaType
|
||||
from .job_lifecycle import claim, complete
|
||||
from .publish_jobs import QUEUE, connect
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def fitted(image, bound):
|
||||
width, height = image.size
|
||||
longest = max(width, height)
|
||||
if longest <= bound:
|
||||
return image.copy()
|
||||
return image.resize((max(1, width * bound // longest),
|
||||
max(1, height * bound // longest)), Image.Resampling.LANCZOS)
|
||||
|
||||
|
||||
def save_variants(source, storage, prefix):
|
||||
with Image.open(source, formats=['PNG', 'JPEG']) as original:
|
||||
with ImageOps.exif_transpose(original) as corrected:
|
||||
with corrected.convert('RGBA') as rgba:
|
||||
rgb = Image.new('RGB', rgba.size, 'white')
|
||||
rgb.paste(rgba, mask=rgba.getchannel('A'))
|
||||
with rgb:
|
||||
specs = (
|
||||
('thumbnail', 'jpeg', 85, lambda: fitted(rgb, 256)),
|
||||
('crop', 'jpeg', 85, lambda: ImageOps.fit(rgb, (128, 128), Image.Resampling.LANCZOS)),
|
||||
('optimized', 'webp', 82, lambda: fitted(rgb, 1280)),
|
||||
)
|
||||
results = []
|
||||
for name, fmt, quality, render in specs:
|
||||
with render() as image, BytesIO() as file:
|
||||
image.save(file, format=fmt.upper(), quality=quality)
|
||||
size = file.tell()
|
||||
digest = hashlib.sha256(file.getbuffer()).hexdigest()
|
||||
file.seek(0)
|
||||
key = f'{prefix}/{name}.{fmt}'
|
||||
mime = f'image/{fmt}'
|
||||
storage.put(key, file, size, mime)
|
||||
results.append((name, key, mime, size, digest, image.width, image.height))
|
||||
return results
|
||||
|
||||
|
||||
def materialize(attachment, storage, version, attempt):
|
||||
prefix = f"attachments/final/{attachment['id']}/v{version}/a{attempt}"
|
||||
key = prefix + '/original'
|
||||
stream = storage.download(attachment)
|
||||
try:
|
||||
with tempfile.TemporaryFile() as source:
|
||||
digest, size = hashlib.sha256(), 0
|
||||
for chunk in stream.chunks():
|
||||
size += len(chunk)
|
||||
if size > MAX_UPLOAD_BYTES:
|
||||
raise PayloadTooLarge()
|
||||
digest.update(chunk)
|
||||
source.write(chunk)
|
||||
if size != attachment['size_bytes'] or digest.hexdigest() != attachment['sha256']:
|
||||
raise UnsupportedMediaType('Контрольная сумма оригинала не совпадает')
|
||||
validate_image(source, attachment['content_type'])
|
||||
source.seek(0)
|
||||
variants = save_variants(source, storage, prefix)
|
||||
source.seek(0)
|
||||
storage.put(key, source, size, attachment['content_type'])
|
||||
finally:
|
||||
stream.close()
|
||||
return key, variants
|
||||
|
||||
|
||||
def process(database, storage, job):
|
||||
attachment = claim(database, job)
|
||||
if attachment is None:
|
||||
return
|
||||
try:
|
||||
result = materialize(attachment, storage, job['pipeline_version'], job['attempt'])
|
||||
except (PayloadTooLarge, UnsupportedMediaType, NotFound):
|
||||
complete(database, job, error_code='invalid_image')
|
||||
except (Unavailable, OSError):
|
||||
complete(database, job)
|
||||
else:
|
||||
complete(database, job, result=result)
|
||||
|
||||
|
||||
def parse_job(body):
|
||||
job = json.loads(body)
|
||||
if not isinstance(job, dict) or job.get('type') != QUEUE or job.get('schema_version') != 1:
|
||||
raise ValueError('Unknown job format')
|
||||
for field in ('job_id', 'attachment_id'):
|
||||
UUID(job[field])
|
||||
for field in ('pipeline_version', 'attempt'):
|
||||
if type(job[field]) is not int or job[field] < 1:
|
||||
raise ValueError('Invalid job number')
|
||||
return job
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
database = Database(Config.from_env())
|
||||
database.open()
|
||||
storage = AttachmentStorage()
|
||||
connection = None
|
||||
|
||||
def timeout(_signal, _frame):
|
||||
raise TimeoutError('Attachment processing exceeded 20 seconds')
|
||||
|
||||
signal.signal(signal.SIGALRM, timeout)
|
||||
|
||||
def consume(channel, method, _properties, body):
|
||||
try:
|
||||
job = parse_job(body)
|
||||
except (ValueError, KeyError, TypeError, AttributeError):
|
||||
channel.basic_reject(method.delivery_tag, requeue=False)
|
||||
return
|
||||
signal.alarm(20)
|
||||
try:
|
||||
process(database, storage, job)
|
||||
finally:
|
||||
signal.alarm(0)
|
||||
channel.basic_ack(method.delivery_tag)
|
||||
|
||||
try:
|
||||
connection = connect()
|
||||
channel = connection.channel()
|
||||
channel.queue_declare(queue=QUEUE, durable=True)
|
||||
channel.basic_qos(prefetch_count=1)
|
||||
channel.basic_consume(queue=QUEUE, on_message_callback=consume)
|
||||
channel.start_consuming()
|
||||
finally:
|
||||
if connection and connection.is_open:
|
||||
connection.close()
|
||||
database.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user