forked from mtusi2026/mtusi2026lab3
перенесенная вторая и лабораторная 3
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
from .domain import compact_json
|
||||
from .errors import ApiError
|
||||
from .service import MessengerService
|
||||
|
||||
|
||||
def make_handler(service: MessengerService):
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "Messenger/1.0"
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
logging.info("%s %s", self.command, self.path.split("?", 1)[0])
|
||||
|
||||
def send_json(self, status, payload, headers=None):
|
||||
request_id = str(uuid.uuid4())
|
||||
if status >= 400 and isinstance(payload, dict) and "error" in payload:
|
||||
payload["error"]["request_id"] = request_id
|
||||
data = compact_json(payload).encode("utf-8")
|
||||
if status == 204:
|
||||
data = b""
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.send_header("X-Request-Id", request_id)
|
||||
self.send_header("X-Instance-Id", os.environ.get("INSTANCE_ID", "local"))
|
||||
for key, value in (headers or {}).items():
|
||||
self.send_header(key, value)
|
||||
self.end_headers()
|
||||
if status != 204:
|
||||
self.wfile.write(data)
|
||||
|
||||
def send_error_json(self, error):
|
||||
headers = {}
|
||||
if error.status == 401:
|
||||
if self.path.split("?", 1)[0] == "/api/v1/auth/sessions":
|
||||
headers["WWW-Authenticate"] = 'Basic realm="messenger", charset="UTF-8"'
|
||||
else:
|
||||
headers["WWW-Authenticate"] = 'Bearer realm="messenger"'
|
||||
self.send_json(error.status, {"error": {"code": error.code, "message": error.message, "request_id": ""}}, headers)
|
||||
|
||||
def read_json(self):
|
||||
if self.headers.get_content_type() != "application/json":
|
||||
raise ApiError(400, "invalid_request", "Ожидается application/json")
|
||||
try:
|
||||
length = int(self.headers.get("Content-Length", "-1"))
|
||||
if length < 0 or length > 1024 * 1024:
|
||||
raise ValueError
|
||||
return json.loads(self.rfile.read(length).decode("utf-8"))
|
||||
except (ValueError, UnicodeDecodeError, json.JSONDecodeError):
|
||||
raise ApiError(400, "invalid_request", "Некорректный JSON")
|
||||
|
||||
def route(self):
|
||||
parsed = urlparse(self.path)
|
||||
path = parsed.path
|
||||
query = parse_qs(parsed.query, keep_blank_values=True)
|
||||
if self.command == "GET" and path in ("/health/live", "/health/ready"):
|
||||
return self.send_json(200, {"status": "ok"})
|
||||
if self.command == "POST" and path == "/api/v1/users":
|
||||
return self.send_json(201, service.create_user(self.read_json()))
|
||||
if self.command == "POST" and path == "/api/v1/auth/sessions":
|
||||
return self.send_json(201, service.create_session(self.headers.get("Authorization", "")))
|
||||
if self.command == "DELETE" and path == "/api/v1/auth/sessions/current":
|
||||
service.revoke_session(self.headers)
|
||||
return self.send_json(204, None)
|
||||
if path == "/api/v1/users/me" and self.command == "GET":
|
||||
return self.send_json(200, service.current_user(self.headers))
|
||||
if path == "/api/v1/chats" and self.command == "POST":
|
||||
return self.send_json(201, service.create_chat(self.headers, self.read_json()))
|
||||
if path == "/api/v1/chats" and self.command == "GET":
|
||||
return self.send_json(200, service.list_chats(self.headers, query))
|
||||
match = re.fullmatch(r"/api/v1/chats/([^/]+)", path)
|
||||
if match and self.command == "GET":
|
||||
return self.send_json(200, service.get_chat(self.headers, match.group(1)))
|
||||
match = re.fullmatch(r"/api/v1/chats/([^/]+)/messages", path)
|
||||
if match and self.command == "POST":
|
||||
return self.send_json(201, service.create_message(self.headers, match.group(1), self.read_json()))
|
||||
if match and self.command == "GET":
|
||||
return self.send_json(200, service.list_messages(self.headers, match.group(1), query))
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
|
||||
def do_GET(self):
|
||||
self.handle_request()
|
||||
|
||||
def do_POST(self):
|
||||
self.handle_request()
|
||||
|
||||
def do_DELETE(self):
|
||||
self.handle_request()
|
||||
|
||||
def handle_request(self):
|
||||
try:
|
||||
self.route()
|
||||
except ApiError as error:
|
||||
self.send_error_json(error)
|
||||
except Exception:
|
||||
logging.exception("request failed")
|
||||
self.send_error_json(ApiError(500, "internal_error", "Внутренняя ошибка"))
|
||||
|
||||
return Handler
|
||||
Reference in New Issue
Block a user