Files
mtusi2026lab3-fork/messenger/api.py
T
nothingredmouth 0e20efe781 Реализовать общую идемпотентность отправки сообщения
Ключ Idempotency-Key с TTL (минимум 86400 c), таблица message_requests и
advisory-лок на (пользователь, чат, ключ): конкурентные повторные запросы
возвращают одно и то же сообщение, конфликт по body -> 409. Добавлена
миграция 002 и сценарий проверки scripts/check_idempotency.py.
2026-11-16 22:18:42 +00:00

120 lines
4.5 KiB
Python

"""HTTP adapter and composition root."""
import json
from uuid import uuid4
from flask import Flask, g, request, jsonify
from werkzeug.exceptions import HTTPException
from .domain import ApiError, invalid
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())
@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()
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()))
return app