forked from mtusi2026/mtusi2026lab3
ЛР 3 — БПИ2303 — Щербаков — на 3
This commit is contained in:
+183
@@ -0,0 +1,183 @@
|
||||
"""Stateless lab3 HTTP replica. Migrations run as a separate Compose job."""
|
||||
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
|
||||
from .common import APIError, invalid, unique_object, reject_constant
|
||||
from .store import Store
|
||||
|
||||
|
||||
LOG = logging.getLogger("messenger")
|
||||
MAX_BODY = 64 * 1024
|
||||
SHUTDOWN_SECONDS = 5
|
||||
|
||||
|
||||
class Server(ThreadingHTTPServer):
|
||||
daemon_threads = True
|
||||
request_queue_size = 128
|
||||
|
||||
def __init__(self, address):
|
||||
self.instance_id = os.environ.get("INSTANCE_ID", "api") + "-" + uuid4().hex[:12]
|
||||
self.store = Store()
|
||||
self.stopping = threading.Event()
|
||||
self.workers = set()
|
||||
self.workers_lock = threading.Lock()
|
||||
super().__init__(address, Handler)
|
||||
self.timeout = 0.2
|
||||
|
||||
def process_request_thread(self, request, client_address):
|
||||
worker = threading.current_thread()
|
||||
with self.workers_lock:
|
||||
self.workers.add(worker)
|
||||
try:
|
||||
super().process_request_thread(request, client_address)
|
||||
finally:
|
||||
with self.workers_lock:
|
||||
self.workers.discard(worker)
|
||||
|
||||
def handle_error(self, request, client_address):
|
||||
LOG.error("connection_handler_failed")
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "Messenger"
|
||||
sys_version = ""
|
||||
|
||||
def setup(self):
|
||||
super().setup()
|
||||
self.connection.settimeout(2)
|
||||
|
||||
def log_message(self, format, *args):
|
||||
# Base handler includes raw paths and possibly user-supplied text.
|
||||
pass
|
||||
|
||||
def send_error(self, code, message=None, explain=None):
|
||||
self.request_id = getattr(self, "request_id", str(uuid4()))
|
||||
self.reply(400, {"error": {"code": "invalid_request", "message": "Invalid HTTP request", "request_id": self.request_id}})
|
||||
|
||||
def read_body(self):
|
||||
if self.headers.get_content_type() != "application/json":
|
||||
raise APIError(415, "unsupported_media_type", "Expected application/json")
|
||||
lengths = self.headers.get_all("Content-Length", [])
|
||||
if self.headers.get("Transfer-Encoding") or len(lengths) != 1 or not re.fullmatch(r"[0-9]{1,10}", lengths[0]):
|
||||
raise invalid()
|
||||
size = int(lengths[0])
|
||||
if size > MAX_BODY:
|
||||
raise APIError(413, "payload_too_large", "Request exceeds 65536 bytes")
|
||||
try:
|
||||
raw = self.rfile.read(size)
|
||||
if len(raw) != size:
|
||||
raise invalid()
|
||||
return json.loads(raw.decode("utf-8"), object_pairs_hook=unique_object, parse_constant=reject_constant)
|
||||
except (ValueError, UnicodeError, RecursionError, TimeoutError):
|
||||
raise invalid() from None
|
||||
|
||||
def reply(self, status, body):
|
||||
encoded = b"" if status == 204 else json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(encoded)))
|
||||
self.send_header("X-Request-Id", self.request_id)
|
||||
self.send_header("X-Instance-Id", self.server.instance_id)
|
||||
if status == 401:
|
||||
challenge = 'Basic realm="messenger", charset="UTF-8"' if urlsplit(self.path).path == "/api/v1/auth/sessions" else 'Bearer realm="messenger"'
|
||||
self.send_header("WWW-Authenticate", challenge)
|
||||
self.send_header("Connection", "close")
|
||||
self.end_headers()
|
||||
self.close_connection = True
|
||||
self.wfile.write(encoded)
|
||||
|
||||
def handle_api(self):
|
||||
started = time.monotonic()
|
||||
self.request_id = str(uuid4())
|
||||
status = 500
|
||||
try:
|
||||
server = self.server
|
||||
assert isinstance(server, Server)
|
||||
if server.stopping.is_set():
|
||||
raise APIError(503, "unavailable", "Server is stopping")
|
||||
parsed = urlsplit(self.path)
|
||||
path = parsed.path
|
||||
if path in ("/health/live", "/health/ready") and self.command == "GET":
|
||||
if path == "/health/ready":
|
||||
server.store.ready()
|
||||
status, body = 200, {"status": "ok"}
|
||||
else:
|
||||
store = server.store
|
||||
public = (path, self.command) in (("/api/v1/users", "POST"), ("/api/v1/auth/sessions", "POST"))
|
||||
actor = None if public else store.authenticate(self.headers.get("Authorization"))
|
||||
cached_body = None
|
||||
if path == "/api/v1/auth/sessions" and self.command == "POST":
|
||||
if self.headers.get("Transfer-Encoding") or self.headers.get("Content-Length", "0") != "0":
|
||||
raise invalid()
|
||||
status, body = store.login(self.headers.get("Authorization"))
|
||||
else:
|
||||
if self.command == "POST":
|
||||
match = re.fullmatch(r"/api/v1/chats/([^/]+)/messages", path)
|
||||
if match:
|
||||
store.check_chat(match[1], actor)
|
||||
cached_body = self.read_body()
|
||||
query = parse_qs(parsed.query, keep_blank_values=True, max_num_fields=10)
|
||||
keys = self.headers.get_all("Idempotency-Key", [])
|
||||
key = keys[0] if len(keys) == 1 else None
|
||||
status, body = store.dispatch(self.command, path, query, actor, lambda: cached_body, key)
|
||||
except APIError as exc:
|
||||
status = exc.status
|
||||
body = {"error": {"code": exc.code, "message": exc.message, "request_id": self.request_id}}
|
||||
except (psycopg.OperationalError, psycopg.InterfaceError):
|
||||
status = 503
|
||||
body = {"error": {"code": "unavailable", "message": "Storage unavailable", "request_id": self.request_id}}
|
||||
except ValueError:
|
||||
status = 400
|
||||
body = {"error": {"code": "invalid_request", "message": "Invalid request", "request_id": self.request_id}}
|
||||
except Exception as exc:
|
||||
LOG.error("request_failed request_id=%s exception=%s", self.request_id, type(exc).__name__)
|
||||
body = {"error": {"code": "internal_error", "message": "Internal error", "request_id": self.request_id}}
|
||||
try:
|
||||
self.reply(status, body)
|
||||
except OSError:
|
||||
LOG.info("client_disconnected request_id=%s", self.request_id)
|
||||
finally:
|
||||
LOG.info("request request_id=%s method=%s status=%d duration_ms=%.3f", self.request_id, self.command, status, (time.monotonic() - started) * 1000)
|
||||
|
||||
do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = do_OPTIONS = handle_api
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
server = Server((os.environ.get("APP_HOST", "0.0.0.0"), int(os.environ.get("APP_PORT", "8080"))))
|
||||
|
||||
def stop(signum, frame):
|
||||
server.stopping.set()
|
||||
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
LOG.info("started host=%s port=%d env=%s", *server.server_address, os.environ.get("APP_ENV", "lab"))
|
||||
try:
|
||||
while not server.stopping.is_set():
|
||||
server.handle_request()
|
||||
finally:
|
||||
server.stopping.set()
|
||||
server.server_close()
|
||||
LOG.info("shutdown_started listener_closed=true budget_seconds=%d", SHUTDOWN_SECONDS)
|
||||
deadline = time.monotonic() + SHUTDOWN_SECONDS
|
||||
with server.workers_lock:
|
||||
workers = list(server.workers)
|
||||
for worker in workers:
|
||||
worker.join(max(0, deadline - time.monotonic()))
|
||||
server.store.pool.close()
|
||||
LOG.info("shutdown_complete unfinished_requests=%d", sum(w.is_alive() for w in workers))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user