Files
mtusi2026lab3/src/messenger/app.py
T

253 lines
12 KiB
Python

"""Contract-compatible synchronous REST API, with short bounded I/O in worker threads."""
import json
import logging
import os
import re
from contextlib import asynccontextmanager
from uuid import uuid4
import psycopg
from fastapi import Depends, FastAPI, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from psycopg_pool import PoolTimeout, TooManyRequests
from redis.exceptions import RedisError
from starlette.exceptions import HTTPException
from starlette.concurrency import run_in_threadpool
from .db import Database
from .errors import ApiError, invalid, not_found, unauthorized
from .models import CreateChat, CreateMessage, CreateUser, uuid_value
from .messages import store_message, validate_key
from .pagination import decode_cursor, page, page_limit, public, stamp
from .security import HASHER, DUMMY_HASH, basic_credentials, bearer, check_password, digest, new_session
LOG = logging.getLogger('messenger')
USER_FIELDS = 'id, username, display_name, created_at'
def error_response(request, error):
return JSONResponse({'error': {'code': error.code, 'message': error.message,
'request_id': request.state.request_id}},
status_code=error.status, headers=error.headers)
def authenticate(request: Request):
token = bearer(request.headers.get('Authorization', ''))
token_hash = digest(token)
with request.app.state.db.pool.connection() as conn:
row = conn.execute('SELECT user_id FROM sessions WHERE token_hash=%s AND expires_at > clock_timestamp()',
(token_hash,)).fetchone()
if not row:
raise unauthorized()
request.state.token_hash = token_hash
return row['user_id']
def require_member(conn, chat_id, user_id):
found = conn.execute('SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s', (chat_id, user_id)).fetchone()
if not found:
raise not_found()
def chat_public(conn, row):
item = public(row)
item['member_ids'] = [str(member['user_id']) for member in conn.execute(
'SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id', (row['id'],)).fetchall()]
return item
def create_app():
@asynccontextmanager
async def lifespan(app):
app.state.db = Database()
app.state.db.open()
try:
yield
finally:
app.state.db.close()
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
app.state.instance_id = uuid4().hex
app.state.release = os.environ.get('APP_RELEASE', 'lab3-v1')
@app.middleware('http')
async def request_context(request: Request, call_next):
request.state.request_id = str(uuid4())
try:
path = request.url.path
json_endpoint = path in ('/api/v1/users', '/api/v1/chats') or re.fullmatch(r'/api/v1/chats/[^/]+/messages', path)
if request.method == 'POST' and json_endpoint:
media = request.headers.get('Content-Type', '').split(';')
unsupported = media[0].strip().lower() != 'application/json'
for parameter in media[1:]:
name, _, value = parameter.strip().partition('=')
if name.lower() == 'charset' and value.strip('"').lower() not in ('utf-8', 'utf8'):
unsupported = True
if unsupported:
if path != '/api/v1/users':
await run_in_threadpool(authenticate, request)
raise ApiError(415, 'unsupported_media_type', 'Требуется application/json в UTF-8')
try:
json.loads((await request.body()).decode('utf-8'))
except (UnicodeError, json.JSONDecodeError):
raise invalid() from None
response = await call_next(request)
except ApiError as exc:
response = error_response(request, exc)
except (psycopg.OperationalError, psycopg.InterfaceError, PoolTimeout, TooManyRequests):
response = error_response(request, ApiError(503, 'unavailable', 'Хранилище временно недоступно'))
except Exception as exc:
# Log exception class only: credentials, SQL and message content stay out of logs.
LOG.error('request_failed request_id=%s type=%s', request.state.request_id, type(exc).__name__)
response = error_response(request, ApiError(500, 'internal_error', 'Внутренняя ошибка'))
response.headers['X-Request-Id'] = request.state.request_id
response.headers['X-Instance-Id'] = app.state.instance_id
response.headers['X-App-Release'] = app.state.release
return response
@app.exception_handler(ApiError)
async def api_error(request, exc):
return error_response(request, exc)
@app.exception_handler(RequestValidationError)
async def validation_error(request, exc):
return error_response(request, invalid())
@app.exception_handler(HTTPException)
async def http_error(request, exc):
return error_response(request, not_found() if exc.status_code == 404 else invalid())
@app.get('/health/live')
def live():
return {'status': 'ok'}
@app.get('/health/ready')
def ready(request: Request):
try:
with request.app.state.db.pool.connection() as conn:
conn.execute('SELECT 1 FROM idempotency_records LIMIT 0')
except (psycopg.errors.UndefinedTable, psycopg.errors.UndefinedColumn):
raise ApiError(503, 'unavailable', 'Схема хранилища ещё не готова') from None
return {'status': 'ok'}
@app.post('/api/v1/users', status_code=201)
def register(body: CreateUser, request: Request):
password_hash = HASHER.hash(body.password)
try:
with request.app.state.db.pool.connection() as conn:
row = conn.execute(
f'INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING {USER_FIELDS}',
(uuid4(), body.username, body.display_name, password_hash)).fetchone()
except psycopg.errors.UniqueViolation:
raise ApiError(409, 'conflict', 'Имя пользователя занято') from None
return public(row)
@app.post('/api/v1/auth/sessions', status_code=201)
async def create_session(request: Request):
# Run hashing and synchronous database calls outside the event loop.
username, password = basic_credentials(request.headers.get('Authorization', ''))
if await request.body():
raise invalid()
return await run_in_threadpool(login, request, username, password)
def login(request, username, password):
db = request.app.state.db
with db.pool.connection() as conn:
row = conn.execute('SELECT '+USER_FIELDS+', password_hash FROM users WHERE username=%s', (username,)).fetchone()
valid = check_password(row['password_hash'] if row else DUMMY_HASH, password)
if not row or not valid:
raise unauthorized(basic=True)
row.pop('password_hash')
token, expires_at = new_session(db.session_ttl)
with db.pool.connection() as conn:
conn.execute('INSERT INTO sessions(token_hash,user_id,expires_at) VALUES (%s,%s,%s)',
(digest(token), row['id'], expires_at))
return {'token': token, 'token_type': 'Bearer', 'expires_at': stamp(expires_at), 'user': public(row)}
@app.get('/api/v1/users/me')
def me(request: Request, user_id=Depends(authenticate)):
db = request.app.state.db
key = 'user:' + str(user_id)
try:
cached = db.cache.get(key)
if cached:
return json.loads(cached)
except (RedisError, ValueError):
pass
with db.pool.connection() as conn:
row = conn.execute('SELECT '+USER_FIELDS+' FROM users WHERE id=%s', (user_id,)).fetchone()
if not row:
raise unauthorized()
result = public(row)
try:
db.cache.set(key, json.dumps(result), ex=60)
except RedisError:
pass
return result
@app.delete('/api/v1/auth/sessions/current', status_code=204)
def logout(request: Request, user_id=Depends(authenticate)):
with request.app.state.db.pool.connection() as conn:
conn.execute('DELETE FROM sessions WHERE token_hash=%s', (request.state.token_hash,))
return Response(status_code=204)
@app.post('/api/v1/chats', status_code=201)
def create_chat(body: CreateChat, request: Request, user_id=Depends(authenticate)):
if str(user_id) not in body.member_ids:
raise invalid()
try:
with request.app.state.db.pool.connection() as conn:
row = conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING id,title,created_at',
(uuid4(), body.title)).fetchone()
# An unknown user raises AFTER the chat INSERT; transaction context rolls it all back.
with conn.cursor() as cur:
cur.executemany('INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)',
[(row['id'], uuid_value(member)) for member in body.member_ids])
result = chat_public(conn, row)
except psycopg.errors.ForeignKeyViolation:
raise invalid() from None
return result
@app.get('/api/v1/chats')
def list_chats(request: Request, user_id=Depends(authenticate)):
limit = page_limit(request.query_params.get('limit', '50'))
scope = 'chats:' + str(user_id)
after = decode_cursor(scope, request.query_params.get('cursor'))
where = ' AND (c.created_at,c.id) > (%s,%s)' if after else ''
params = (user_id, *after, limit+1) if after else (user_id, limit+1)
with request.app.state.db.pool.connection() as conn:
rows = conn.execute('SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members m ON m.chat_id=c.id '
'WHERE m.user_id=%s'+where+' ORDER BY c.created_at,c.id LIMIT %s', params).fetchall()
result = page(scope, rows, limit)
result['items'] = [chat_public(conn, row) for row in rows[:limit]]
return result
@app.get('/api/v1/chats/{chat_id}')
def get_chat(chat_id: str, request: Request, user_id=Depends(authenticate)):
cid = uuid_value(chat_id)
with request.app.state.db.pool.connection() as conn:
require_member(conn, cid, user_id)
row = conn.execute('SELECT id,title,created_at FROM chats WHERE id=%s', (cid,)).fetchone()
return chat_public(conn, row)
@app.post('/api/v1/chats/{chat_id}/messages', status_code=201)
def send_message(chat_id: str, body: CreateMessage, request: Request, user_id=Depends(authenticate)):
cid = uuid_value(chat_id)
key = validate_key(request.headers.get('Idempotency-Key', ''))
with request.app.state.db.pool.connection() as conn:
require_member(conn, cid, user_id)
row = store_message(conn, user_id, cid, body.text, key)
return public(row)
@app.get('/api/v1/chats/{chat_id}/messages')
def history(chat_id: str, request: Request, user_id=Depends(authenticate)):
cid = uuid_value(chat_id)
limit = page_limit(request.query_params.get('limit', '50'))
scope = 'messages:' + str(cid)
with request.app.state.db.pool.connection() as conn:
require_member(conn, cid, user_id)
after = decode_cursor(scope, request.query_params.get('cursor'))
where = ' AND (created_at,id) > (%s,%s)' if after else ''
params = (cid, *after, limit+1) if after else (cid, limit+1)
rows = conn.execute('SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=%s'+where+
' ORDER BY created_at,id LIMIT %s', params).fetchall()
return page(scope, rows, limit)
return app