Files
mtusi2026lab4-fork/messenger/api.py
T
nothingredmouth 4b23b44eb8 Перенести приложение мессенджера с сессиями и идемпотентностью в PostgreSQL
Пользователи, аутентификация Argon2id, Bearer-сессии с TTL и отзывом,
транзакционный репозиторий, keyset-пагинация, идемпотентные отправки
(advisory lock + message_requests), версияемые миграции 001/002.
2026-11-17 03:37:07 +00:00

191 lines
7.9 KiB
Python

"""HTTP adapter and composition root."""
import json
import hashlib
import re
import unicodedata
from uuid import UUID
from .images import MAX_BYTES, validate_image
from .storage import ObjectStore
from uuid import uuid4
from flask import Flask, g, request, jsonify, Response, stream_with_context
from werkzeug.exceptions import HTTPException
from .domain import ApiError, invalid, uuid_value
from .postgres import PostgresRepository
from .database import Database
from .config import Settings
from .service import Messenger
def create_app(repository=None, settings=None):
app = Flask(__name__)
app.json.ensure_ascii = False
settings = settings or Settings.from_env()
repository = repository if repository is not None else PostgresRepository(Database(settings.database_url))
service = Messenger(repository, settings.session_ttl, settings.idempotency_ttl)
instance_id = str(uuid4())
store = None if app.config.get("TESTING_STORAGE_DISABLED") else (ObjectStore(settings) if repository is None or isinstance(repository, PostgresRepository) else None)
@app.before_request
def identify():
g.request_id = str(uuid4())
if app.config.get('DRAINING'):
raise ApiError(503, 'unavailable', 'Instance is shutting down')
if request.path.startswith('/api/v1/') and not (
request.path in ('/api/v1/users', '/api/v1/auth/sessions') and request.method == 'POST'
):
g.user, g.token_hash = service.auth.bearer(request.headers.get('Authorization'))
@app.after_request
def request_id(response):
response.headers['X-Request-Id'] = g.request_id
response.headers['X-Instance-Id'] = instance_id
return response
@app.errorhandler(Exception)
def error(exc):
if isinstance(exc, ApiError):
status, code, message = exc.status, exc.code, exc.message
elif isinstance(exc, HTTPException):
status = exc.code
code = {404: 'not_found', 413: 'payload_too_large', 415: 'unsupported_media_type'}.get(status, 'invalid_request')
message = exc.name
else:
app.logger.error('Unhandled error; request_id=%s', g.request_id)
status, code, message = 500, 'internal_error', 'Internal server error'
response = jsonify(error={'code': code, 'message': message, 'request_id': g.request_id})
response.status_code = status
if status == 401:
response.headers['WWW-Authenticate'] = (
'Basic realm="messenger", charset="UTF-8"'
if request.path == '/api/v1/auth/sessions' and request.method == 'POST'
else 'Bearer realm="messenger"')
return response
def body():
if request.mimetype != 'application/json':
raise ApiError(415, 'unsupported_media_type', 'Use application/json')
try:
def reject_constant(value):
raise ValueError(value)
return json.loads(request.get_data().decode('utf-8'), parse_constant=reject_constant)
except (ValueError, UnicodeError):
invalid('Malformed UTF-8 JSON')
def paging():
for key in ('limit', 'cursor'):
if len(request.args.getlist(key)) > 1:
invalid('Duplicate query parameter')
return request.args.get('limit', '50'), request.args.get('cursor')
@app.get('/health/live')
def health():
return jsonify(status='ok')
@app.get('/health/ready')
def ready():
repository.ready()
if store is not None:
store.ready()
return jsonify(status='ok')
@app.post('/api/v1/auth/sessions')
def login():
# Session creation accepts no request body.
if request.get_data():
invalid('Session creation does not accept a body')
return jsonify(service.auth.login(request.headers.get('Authorization'))), 201
@app.delete('/api/v1/auth/sessions/current')
def logout():
repository.revoke_session(g.token_hash)
return '', 204
@app.post('/api/v1/users')
def register():
return jsonify(service.register(body())), 201
@app.get('/api/v1/users/me')
def me():
return jsonify(g.user)
@app.route('/api/v1/chats', methods=['GET', 'POST'])
def chats():
if request.method == 'POST':
return jsonify(service.create_chat(g.user['id'], body())), 201
return jsonify(service.chats(g.user['id'], *paging()))
@app.get('/api/v1/chats/<chat_id>')
def chat(chat_id):
return jsonify(service.chat(g.user['id'], chat_id))
@app.route('/api/v1/chats/<chat_id>/messages', methods=['GET', 'POST'])
def messages(chat_id):
if request.method == 'POST':
service.chat(g.user['id'], chat_id)
return jsonify(service.send(g.user['id'], chat_id, body(), request.headers.get('Idempotency-Key'))), 201
return jsonify(service.history(g.user['id'], chat_id, *paging()))
@app.post('/api/v1/chats/<chat_id>/attachments')
def upload(chat_id):
chat_id = uuid_value(chat_id)
service.chat(g.user['id'], chat_id)
values = request.args.getlist('filename')
if len(values) != 1:
invalid('Exactly one filename is required')
filename = values[0]
if (not 1 <= len(filename) <= 255 or any(
c in ('/', '\\') or unicodedata.category(c) == 'Cc' for c in filename)):
invalid('Unsafe filename')
if request.mimetype not in ('image/png', 'image/jpeg'):
raise ApiError(415, 'unsupported_media_type', 'PNG or JPEG required')
if request.content_length is not None and request.content_length > MAX_BYTES:
raise ApiError(413, 'payload_too_large', 'Image exceeds 10 MiB')
# Bounded read even if Content-Length is absent or misleading.
content = request.stream.read(MAX_BYTES + 1)
if len(content) > MAX_BYTES:
raise ApiError(413, 'payload_too_large', 'Image exceeds 10 MiB')
validate_image(content, request.mimetype)
if store is None:
raise ApiError(503, 'unavailable', 'Object storage unavailable')
identifier = str(uuid4())
key = 'originals/' + uuid4().hex + '/' + uuid4().hex
metadata = {'id': identifier, 'filename': filename, 'content_type': request.mimetype,
'size_bytes': len(content), 'sha256': hashlib.sha256(content).hexdigest(),
'object_key': key}
store.put(key, content, request.mimetype)
try:
result = repository.insert_attachment(g.user['id'], chat_id, metadata)
except Exception:
store.delete(key) # best effort compensation for DB commit failure
raise
return jsonify(result), 201
@app.get('/api/v1/attachments/<attachment_id>')
def attachment(attachment_id):
obj, _key = repository.attachment(g.user['id'], uuid_value(attachment_id))
return jsonify(obj)
@app.get('/api/v1/attachments/<attachment_id>/content')
def download(attachment_id):
obj, key = repository.attachment(g.user['id'], uuid_value(attachment_id))
variants = request.args.getlist('variant')
if len(variants) > 1:
invalid('Duplicate variant')
if variants and variants[0] != 'original':
raise ApiError(404, 'not_found', 'Variant not found')
if store is None:
raise ApiError(503, 'unavailable', 'Object storage unavailable')
body = store.get(key)
def chunks():
try:
for chunk in body.iter_chunks(chunk_size=65536):
if chunk:
yield chunk
finally:
body.close()
return Response(stream_with_context(chunks()), mimetype=obj['content_type'],
headers={'Content-Length': str(obj['size_bytes']),
'Cache-Control': 'private, no-store'})
return app