520 lines
18 KiB
Python
520 lines
18 KiB
Python
import json
|
|
import logging
|
|
import os
|
|
import re
|
|
import time
|
|
import uuid
|
|
from contextlib import asynccontextmanager
|
|
|
|
import anyio
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse, Response, StreamingResponse
|
|
from opentelemetry import trace
|
|
from opentelemetry.trace import SpanKind, Status, StatusCode
|
|
from pydantic import ValidationError
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
|
|
from blobs import MAX_BYTES, declared_type, inspect_image, open_object
|
|
from errors import ApiError, AttachmentNotReady, AttachmentRejected, DependencyDown, IdempotencyConflict, error_body
|
|
from schemas import CreateChat, CreateMessage, CreateUser
|
|
from store import Store, instance_id
|
|
from telemetry import record_http, route_template, setup as setup_telemetry, structured_log
|
|
|
|
LOGGER = logging.getLogger("messenger")
|
|
store = Store()
|
|
INSTANCE_ID = instance_id()
|
|
|
|
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
|
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
|
IDEMPOTENCY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
|
MAX_JSON_BYTES = 65536
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(_app):
|
|
setup_telemetry(os.environ.get("OTEL_SERVICE_NAME", "messenger-api"))
|
|
await anyio.to_thread.run_sync(store.startup)
|
|
yield
|
|
store.shutting_down = True
|
|
await anyio.to_thread.run_sync(store.shutdown)
|
|
|
|
|
|
app = FastAPI(
|
|
title="mtusi-messenger",
|
|
version="lab6",
|
|
lifespan=lifespan,
|
|
redirect_slashes=False,
|
|
docs_url="/docs",
|
|
redoc_url=None,
|
|
openapi_url="/openapi.json",
|
|
)
|
|
|
|
|
|
def request_id_of(request: Request):
|
|
rid = getattr(request.state, "request_id", None)
|
|
if rid:
|
|
return rid
|
|
return str(uuid.uuid4())
|
|
|
|
|
|
def stamp(request: Request, response):
|
|
response.headers["X-Request-Id"] = request_id_of(request)
|
|
response.headers["X-Instance-Id"] = INSTANCE_ID
|
|
return response
|
|
|
|
|
|
def json_ok(request: Request, payload, status_code=200):
|
|
return stamp(request, JSONResponse(payload, status_code=status_code))
|
|
|
|
|
|
def json_error(request: Request, status, code, message, extra_headers=None):
|
|
headers = {"X-Request-Id": request_id_of(request), "X-Instance-Id": INSTANCE_ID}
|
|
if extra_headers:
|
|
headers.update(extra_headers)
|
|
return JSONResponse(error_body(code, message, request_id_of(request)), status_code=status, headers=headers)
|
|
|
|
|
|
@app.middleware("http")
|
|
async def wrap_request(request: Request, call_next):
|
|
incoming = request.headers.get("X-Request-Id", "")
|
|
if incoming and len(incoming) <= 200 and incoming.isprintable() and incoming.strip():
|
|
request.state.request_id = incoming.strip()
|
|
else:
|
|
request.state.request_id = str(uuid.uuid4())
|
|
if store.shutting_down and request.url.path != "/health/live":
|
|
return json_error(request, 503, "unavailable", "Сервис временно недоступен")
|
|
started = time.perf_counter()
|
|
route = route_template(request.url.path)
|
|
is_health = request.url.path in ("/health/live", "/health/ready")
|
|
if is_health:
|
|
response = await call_next(request)
|
|
return stamp(request, response)
|
|
tracer = trace.get_tracer("messenger")
|
|
with tracer.start_as_current_span(
|
|
f"{request.method} {route}",
|
|
kind=SpanKind.SERVER,
|
|
attributes={
|
|
"http.request.method": request.method,
|
|
"http.route": route,
|
|
"service.instance.id": INSTANCE_ID,
|
|
},
|
|
) as span:
|
|
span.set_attribute("http.request_id", request.state.request_id)
|
|
try:
|
|
response = await call_next(request)
|
|
except Exception as exc:
|
|
span.record_exception(exc)
|
|
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
|
|
raise
|
|
stamped = stamp(request, response)
|
|
span.set_attribute("http.response.status_code", stamped.status_code)
|
|
if stamped.status_code >= 500:
|
|
span.set_status(Status(StatusCode.ERROR))
|
|
duration = time.perf_counter() - started
|
|
record_http(request.method, request.url.path, stamped.status_code, duration)
|
|
structured_log(
|
|
LOGGER,
|
|
"http_request",
|
|
method=request.method,
|
|
route=route,
|
|
status=stamped.status_code,
|
|
request_id=request.state.request_id,
|
|
duration_ms=round(duration * 1000, 3),
|
|
)
|
|
return stamped
|
|
|
|
|
|
@app.exception_handler(ApiError)
|
|
async def api_error_handler(request: Request, exc: ApiError):
|
|
return json_error(request, exc.status, exc.code, exc.message, exc.headers)
|
|
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def request_validation_handler(request: Request, _exc: RequestValidationError):
|
|
return json_error(request, 400, "invalid_request", "Некорректный запрос")
|
|
|
|
|
|
@app.exception_handler(ValidationError)
|
|
async def pydantic_handler(request: Request, _exc: ValidationError):
|
|
return json_error(request, 400, "invalid_request", "Некорректный запрос")
|
|
|
|
|
|
@app.exception_handler(StarletteHTTPException)
|
|
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
|
if exc.status_code == 404:
|
|
return json_error(request, 404, "not_found", "Объект не найден")
|
|
return json_error(request, exc.status_code if exc.status_code < 500 else 500, "invalid_request", "Некорректный запрос")
|
|
|
|
|
|
@app.exception_handler(Exception)
|
|
async def unexpected_handler(request: Request, exc: Exception):
|
|
if isinstance(exc, ApiError):
|
|
return json_error(request, exc.status, exc.code, exc.message, exc.headers)
|
|
LOGGER.error("unhandled %s", type(exc).__name__)
|
|
return json_error(request, 500, "internal_error", "Внутренняя ошибка")
|
|
|
|
|
|
def unavailable():
|
|
raise ApiError(503, "unavailable", "Сервис временно недоступен")
|
|
|
|
|
|
def bearer_unauthorized():
|
|
raise ApiError(401, "unauthorized", "Требуется авторизация", {"WWW-Authenticate": BEARER_CHALLENGE})
|
|
|
|
|
|
def basic_unauthorized():
|
|
raise ApiError(401, "unauthorized", "Неверные учётные данные", {"WWW-Authenticate": BASIC_CHALLENGE})
|
|
|
|
|
|
def invalid():
|
|
raise ApiError(400, "invalid_request", "Некорректный запрос")
|
|
|
|
|
|
async def call_store(func, *args):
|
|
try:
|
|
return await anyio.to_thread.run_sync(func, *args)
|
|
except DependencyDown:
|
|
unavailable()
|
|
except IdempotencyConflict:
|
|
raise ApiError(409, "conflict", "Ключ уже использован с другим телом")
|
|
except AttachmentRejected:
|
|
raise ApiError(409, "conflict", "Вложение нельзя прикрепить")
|
|
except AttachmentNotReady:
|
|
raise ApiError(409, "conflict", "Вложение недоступно")
|
|
|
|
|
|
def parse_basic(request: Request):
|
|
header = request.headers.get("Authorization", "")
|
|
if not header.lower().startswith("basic "):
|
|
basic_unauthorized()
|
|
raw = header.split(" ", 1)[1].strip()
|
|
try:
|
|
import base64
|
|
|
|
decoded = base64.b64decode(raw, validate=True).decode("utf-8")
|
|
except (ValueError, UnicodeError):
|
|
basic_unauthorized()
|
|
if ":" not in decoded:
|
|
basic_unauthorized()
|
|
username, password = decoded.split(":", 1)
|
|
return username, password
|
|
|
|
|
|
def parse_bearer(request: Request):
|
|
header = request.headers.get("Authorization", "")
|
|
# Basic на бизнес-методе не открывает сессию. X-User-Id не смотрим.
|
|
if not header.lower().startswith("bearer "):
|
|
bearer_unauthorized()
|
|
token = header.split(" ", 1)[1].strip()
|
|
if len(token) < 32 or len(token) > 512 or any(ch.isspace() for ch in token):
|
|
bearer_unauthorized()
|
|
return token
|
|
|
|
|
|
async def current_user(request: Request):
|
|
token = parse_bearer(request)
|
|
user = await call_store(store.user_for_token, token)
|
|
if user is None:
|
|
bearer_unauthorized()
|
|
request.state.user_id = user["id"]
|
|
request.state.token = token
|
|
return user
|
|
|
|
|
|
def parse_chat_id(chat_id):
|
|
try:
|
|
return str(uuid.UUID(chat_id))
|
|
except ValueError:
|
|
invalid()
|
|
|
|
|
|
def parse_limit(raw):
|
|
if raw is None:
|
|
return 50
|
|
if not isinstance(raw, str) or len(raw) > 3 or not raw.isdigit():
|
|
invalid()
|
|
value = int(raw)
|
|
if value < 1 or value > 100:
|
|
invalid()
|
|
return value
|
|
|
|
|
|
async def read_json(request: Request):
|
|
ctype = request.headers.get("content-type", "")
|
|
if "application/json" not in ctype.lower():
|
|
raise ApiError(415, "unsupported_media_type", "Нужен application/json")
|
|
length = request.headers.get("content-length")
|
|
if length is not None and (not length.isdigit() or int(length) > MAX_JSON_BYTES):
|
|
raise ApiError(413, "payload_too_large", "Слишком большое тело")
|
|
raw = await request.body()
|
|
if len(raw) > MAX_JSON_BYTES:
|
|
raise ApiError(413, "payload_too_large", "Слишком большое тело")
|
|
try:
|
|
payload = json.loads(raw)
|
|
except (ValueError, UnicodeError):
|
|
invalid()
|
|
if not isinstance(payload, dict):
|
|
invalid()
|
|
return payload
|
|
|
|
|
|
def parse_idempotency_key(request: Request):
|
|
key = request.headers.get("Idempotency-Key")
|
|
if key is None or not IDEMPOTENCY_RE.fullmatch(key):
|
|
invalid()
|
|
return key
|
|
|
|
|
|
@app.get("/health/live")
|
|
async def liveness(request: Request):
|
|
return json_ok(request, {"status": "ok"})
|
|
|
|
|
|
@app.get("/health/ready")
|
|
async def readiness(request: Request):
|
|
if store.shutting_down:
|
|
raise ApiError(503, "unavailable", "Сервис временно недоступен")
|
|
ok = await call_store(store.ready)
|
|
if not ok:
|
|
unavailable()
|
|
return json_ok(request, {"status": "ok"})
|
|
|
|
|
|
@app.post("/api/v1/users", status_code=201)
|
|
async def register_user(request: Request, body: CreateUser):
|
|
user = await call_store(store.create_user, body.username, body.display_name, body.password)
|
|
if user is None:
|
|
raise ApiError(409, "conflict", "Имя пользователя занято")
|
|
return json_ok(request, user, 201)
|
|
|
|
|
|
@app.post("/api/v1/auth/sessions", status_code=201)
|
|
async def create_session(request: Request):
|
|
username, password = parse_basic(request)
|
|
session = await call_store(store.login, username, password)
|
|
if session is None:
|
|
basic_unauthorized()
|
|
request.state.user_id = session["user"]["id"]
|
|
return json_ok(request, session, 201)
|
|
|
|
|
|
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
|
async def revoke_session(request: Request):
|
|
user = await current_user(request)
|
|
request.state.user_id = user["id"]
|
|
removed = await call_store(store.revoke, request.state.token)
|
|
if not removed:
|
|
bearer_unauthorized()
|
|
return stamp(request, Response(status_code=204))
|
|
|
|
|
|
@app.get("/api/v1/users/me")
|
|
async def me(request: Request):
|
|
user = await current_user(request)
|
|
return json_ok(request, user)
|
|
|
|
|
|
@app.post("/api/v1/chats", status_code=201)
|
|
async def create_chat(request: Request):
|
|
user = await current_user(request)
|
|
payload = await read_json(request)
|
|
try:
|
|
body = CreateChat.model_validate(payload)
|
|
except ValidationError:
|
|
invalid()
|
|
try:
|
|
chat = await call_store(store.create_chat, body.title, body.member_ids, user["id"])
|
|
except ValueError:
|
|
invalid()
|
|
return json_ok(request, chat, 201)
|
|
|
|
|
|
@app.get("/api/v1/chats")
|
|
async def list_chats(request: Request):
|
|
user = await current_user(request)
|
|
limit = parse_limit(request.query_params.get("limit"))
|
|
cursor = request.query_params.get("cursor")
|
|
if cursor is not None and (not cursor or len(cursor) > 512):
|
|
invalid()
|
|
try:
|
|
items, next_cursor = await call_store(store.list_chats, user["id"], limit, cursor)
|
|
except ValueError:
|
|
invalid()
|
|
return json_ok(request, {"items": items, "next_cursor": next_cursor})
|
|
|
|
|
|
@app.get("/api/v1/chats/{chat_id}")
|
|
async def get_chat(request: Request, chat_id: str):
|
|
user = await current_user(request)
|
|
chat = await call_store(store.get_chat, parse_chat_id(chat_id), user["id"])
|
|
if chat is None:
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
return json_ok(request, chat)
|
|
|
|
|
|
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
|
async def create_message(request: Request, chat_id: str):
|
|
user = await current_user(request)
|
|
canonical = parse_chat_id(chat_id)
|
|
payload = await read_json(request)
|
|
key = parse_idempotency_key(request)
|
|
try:
|
|
body = CreateMessage.model_validate(payload)
|
|
except ValidationError:
|
|
invalid()
|
|
try:
|
|
message = await call_store(
|
|
store.add_message, canonical, user["id"], body.text, key, body.attachment_ids
|
|
)
|
|
except ValueError:
|
|
invalid()
|
|
if message is None:
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
return json_ok(request, message, 201)
|
|
|
|
|
|
@app.get("/api/v1/chats/{chat_id}/messages")
|
|
async def list_messages(request: Request, chat_id: str):
|
|
user = await current_user(request)
|
|
canonical = parse_chat_id(chat_id)
|
|
limit = parse_limit(request.query_params.get("limit"))
|
|
cursor = request.query_params.get("cursor")
|
|
if cursor is not None and (not cursor or len(cursor) > 512):
|
|
invalid()
|
|
try:
|
|
result = await call_store(store.list_messages, canonical, user["id"], limit, cursor)
|
|
except ValueError:
|
|
invalid()
|
|
if result is None:
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
items, next_cursor = result
|
|
return json_ok(request, {"items": items, "next_cursor": next_cursor})
|
|
|
|
|
|
def check_filename(value):
|
|
if not isinstance(value, str) or not value or len(value) > 255:
|
|
invalid()
|
|
if "/" in value or "\\" in value or "\x00" in value:
|
|
invalid()
|
|
if any(ord(char) < 32 or ord(char) == 127 for char in value):
|
|
invalid()
|
|
return value
|
|
|
|
|
|
def parse_attachment_id(value):
|
|
try:
|
|
return str(uuid.UUID(value))
|
|
except (TypeError, ValueError):
|
|
invalid()
|
|
|
|
|
|
async def read_upload(request: Request):
|
|
header = request.headers.get("content-length")
|
|
if header is not None:
|
|
try:
|
|
announced = int(header)
|
|
except ValueError:
|
|
invalid()
|
|
if announced > MAX_BYTES:
|
|
raise ApiError(413, "payload_too_large", "Файл больше 10 МиБ")
|
|
if announced < 1:
|
|
raise ApiError(415, "unsupported_media_type", "Нужен PNG или JPEG")
|
|
chunks = []
|
|
total = 0
|
|
async for chunk in request.stream():
|
|
total += len(chunk)
|
|
if total > MAX_BYTES:
|
|
raise ApiError(413, "payload_too_large", "Файл больше 10 МиБ")
|
|
chunks.append(chunk)
|
|
if total < 1:
|
|
raise ApiError(415, "unsupported_media_type", "Нужен PNG или JPEG")
|
|
return b"".join(chunks)
|
|
|
|
|
|
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
|
|
async def upload_attachment(request: Request, chat_id: str):
|
|
user = await current_user(request)
|
|
canonical = parse_chat_id(chat_id)
|
|
member = await call_store(store.is_member, canonical, user["id"])
|
|
if not member:
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
filename = check_filename(request.query_params.get("filename"))
|
|
media = declared_type(request.headers.get("content-type"))
|
|
if media is None:
|
|
raise ApiError(415, "unsupported_media_type", "Нужен PNG или JPEG")
|
|
data = await read_upload(request)
|
|
content_type = await anyio.to_thread.run_sync(inspect_image, data, media)
|
|
saved = await call_store(
|
|
store.save_attachment, canonical, user["id"], filename, content_type, data
|
|
)
|
|
if saved is None:
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
return json_ok(request, saved, 202)
|
|
|
|
|
|
@app.get("/api/v1/attachments/{attachment_id}")
|
|
async def get_attachment(request: Request, attachment_id: str):
|
|
user = await current_user(request)
|
|
canonical = parse_attachment_id(attachment_id)
|
|
found = await call_store(store.get_attachment, canonical, user["id"])
|
|
if found is None:
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
return json_ok(request, found)
|
|
|
|
|
|
@app.get("/api/v1/attachments/{attachment_id}/content")
|
|
async def download_attachment(request: Request, attachment_id: str):
|
|
user = await current_user(request)
|
|
canonical = parse_attachment_id(attachment_id)
|
|
variant = request.query_params.get("variant")
|
|
if variant is None:
|
|
variant = "original"
|
|
if variant not in ("original", "thumbnail", "crop", "optimized"):
|
|
invalid()
|
|
opened = await call_store(store.open_attachment, canonical, user["id"], variant)
|
|
if opened is None:
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
|
|
def chunks():
|
|
body = open_object(opened["object_key"])
|
|
if body is None:
|
|
return
|
|
try:
|
|
for piece in body.stream(64 * 1024):
|
|
yield piece
|
|
finally:
|
|
body.close()
|
|
body.release_conn()
|
|
|
|
probe = await anyio.to_thread.run_sync(open_object, opened["object_key"])
|
|
if probe is None:
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
probe.close()
|
|
probe.release_conn()
|
|
response = StreamingResponse(chunks(), media_type=opened["content_type"])
|
|
response.headers["Content-Length"] = str(opened["size_bytes"])
|
|
return stamp(request, response)
|
|
|
|
|
|
def setup_logging():
|
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
|
|
setup_logging()
|
|
setup_telemetry(os.environ.get("OTEL_SERVICE_NAME", "messenger-api"))
|
|
host = os.environ.get("APP_HOST", "0.0.0.0")
|
|
port = int(os.environ.get("APP_PORT", "8080"))
|
|
uvicorn.run(
|
|
app,
|
|
host=host,
|
|
port=port,
|
|
timeout_graceful_shutdown=5,
|
|
timeout_keep_alive=2,
|
|
access_log=False,
|
|
log_config=None,
|
|
)
|