forked from mtusi2026/mtusi2026lab3
444 lines
19 KiB
Python
444 lines
19 KiB
Python
#!/usr/bin/env python3
|
|
import base64
|
|
import json
|
|
import os
|
|
import re
|
|
import secrets
|
|
import signal
|
|
import sys
|
|
import threading
|
|
import time
|
|
import traceback
|
|
import uuid
|
|
import hashlib
|
|
import bcrypt
|
|
import psycopg2
|
|
import psycopg2.pool
|
|
import redis
|
|
from datetime import datetime, timezone, timedelta
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from urllib.parse import urlparse, parse_qs
|
|
|
|
HOST = os.environ.get("APP_HOST", "0.0.0.0")
|
|
PORT = int(os.environ.get("APP_PORT", "8080"))
|
|
SESSION_TTL = int(os.environ.get("SESSION_TTL_SECONDS", 3600))
|
|
# Уникальный ID инстанса для балансировки
|
|
INSTANCE_ID = str(uuid.uuid4())[:8]
|
|
|
|
db_pool = psycopg2.pool.ThreadedConnectionPool(
|
|
1, 20,
|
|
host=os.environ.get("DB_HOST", "localhost"),
|
|
user=os.environ.get("DB_USER", "postgres"),
|
|
password=os.environ.get("DB_PASSWORD", "secret"),
|
|
dbname=os.environ.get("DB_NAME", "messenger")
|
|
)
|
|
|
|
redis_client = redis.Redis(
|
|
host=os.environ.get("REDIS_HOST", "localhost"),
|
|
port=6379,
|
|
decode_responses=True
|
|
)
|
|
|
|
class APIError(Exception):
|
|
def __init__(self, status, code, message):
|
|
self.status = status
|
|
self.code = code
|
|
self.message = message
|
|
|
|
def format_dt(dt_obj):
|
|
return dt_obj.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
|
|
|
def parse_limit(query):
|
|
if "limit" not in query:
|
|
return 50
|
|
values = query["limit"]
|
|
if len(values) != 1:
|
|
raise APIError(400, "invalid_request", "Invalid limit")
|
|
try:
|
|
limit = int(values[0])
|
|
except ValueError:
|
|
raise APIError(400, "invalid_request", "limit must be an integer")
|
|
if limit < 1 or limit > 100:
|
|
raise APIError(400, "invalid_request", "limit must be 1..100")
|
|
return limit
|
|
|
|
def encode_cursor(resource_type, resource_id, item):
|
|
payload = {"r": resource_type, "id": resource_id, "ts": item["created_at"], "iid": item["id"]}
|
|
raw = json.dumps(payload, separators=(",", ":")).encode("utf-8")
|
|
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
|
|
|
def decode_cursor(cursor, resource_type, resource_id):
|
|
try:
|
|
padding = "=" * (-len(cursor) % 4)
|
|
raw = base64.urlsafe_b64decode(cursor + padding)
|
|
payload = json.loads(raw.decode("utf-8"))
|
|
if payload.get("r") != resource_type or payload.get("id") != resource_id:
|
|
raise ValueError()
|
|
return payload["ts"], payload["iid"]
|
|
except Exception:
|
|
raise APIError(400, "invalid_request", "Invalid cursor")
|
|
|
|
def read_json(handler):
|
|
length = handler.headers.get("Content-Length")
|
|
if not length: raise APIError(400, "invalid_request", "Missing body")
|
|
raw = handler.rfile.read(int(length))
|
|
try: return json.loads(raw.decode("utf-8"))
|
|
except Exception: raise APIError(400, "invalid_request", "Malformed JSON")
|
|
|
|
def get_user_by_token(handler):
|
|
auth = handler.headers.get("Authorization")
|
|
if not auth or not auth.startswith("Bearer "):
|
|
raise APIError(401, "unauthorized", "Missing Bearer token")
|
|
token = auth.split(" ")[1]
|
|
|
|
user_id = redis_client.get(f"session:{token}")
|
|
if not user_id:
|
|
raise APIError(401, "unauthorized", "Invalid or expired token")
|
|
|
|
conn = db_pool.getconn()
|
|
try:
|
|
with conn.cursor() as cur:
|
|
cur.execute("SELECT id, username, display_name, created_at FROM users WHERE id = %s", (user_id,))
|
|
row = cur.fetchone()
|
|
if not row: raise APIError(401, "unauthorized", "User not found")
|
|
return {
|
|
"id": str(row[0]), "username": row[1], "display_name": row[2],
|
|
"created_at": format_dt(row[3])
|
|
}
|
|
finally:
|
|
db_pool.putconn(conn)
|
|
|
|
class Handler(BaseHTTPRequestHandler):
|
|
protocol_version = "HTTP/1.1"
|
|
server_version = "MessengerLab3/3.0"
|
|
|
|
def do_GET(self): self.handle_request("GET")
|
|
def do_POST(self): self.handle_request("POST")
|
|
def do_DELETE(self): self.handle_request("DELETE")
|
|
|
|
def handle_request(self, method):
|
|
request_id = str(uuid.uuid4())
|
|
self._status = None
|
|
try:
|
|
parsed = urlparse(self.path)
|
|
path = parsed.path
|
|
query = parse_qs(parsed.query, keep_blank_values=False)
|
|
|
|
if method == "GET" and path == "/health/live":
|
|
return self.send_json(200, {"status": "ok"}, request_id)
|
|
if method == "GET" and path == "/health/ready":
|
|
try:
|
|
conn = db_pool.getconn()
|
|
with conn.cursor() as cur: cur.execute("SELECT 1")
|
|
db_pool.putconn(conn)
|
|
return self.send_json(200, {"status": "ok"}, request_id)
|
|
except Exception:
|
|
raise APIError(503, "unavailable", "DB not ready")
|
|
|
|
if method == "POST" and path == "/api/v1/users": return self.create_user(request_id)
|
|
if method == "POST" and path == "/api/v1/auth/sessions": return self.create_session(request_id)
|
|
if method == "DELETE" and path == "/api/v1/auth/sessions/current": return self.delete_session(request_id)
|
|
if method == "GET" and path == "/api/v1/users/me": return self.get_me(request_id)
|
|
if method == "POST" and path == "/api/v1/chats": return self.create_chat(request_id)
|
|
if method == "GET" and path == "/api/v1/chats": return self.list_chats(request_id, query)
|
|
|
|
m = re.fullmatch(r"/api/v1/chats/([^/]+)", path)
|
|
if m and method == "GET": return self.get_chat(request_id, m.group(1))
|
|
|
|
m = re.fullmatch(r"/api/v1/chats/([^/]+)/messages", path)
|
|
if m:
|
|
if method == "POST": return self.create_message(request_id, m.group(1))
|
|
if method == "GET": return self.list_messages(request_id, m.group(1), query)
|
|
|
|
raise APIError(404, "not_found", "Not found")
|
|
except APIError as exc:
|
|
self.send_error_json(exc.status, exc.code, exc.message, request_id)
|
|
except Exception:
|
|
self.log_error("Unhandled: %s", traceback.format_exc())
|
|
self.send_error_json(500, "internal_error", "Internal error", request_id)
|
|
|
|
def create_user(self, request_id):
|
|
body = read_json(self)
|
|
username = body.get("username")
|
|
display_name = body.get("display_name")
|
|
password = body.get("password")
|
|
if not username or not re.fullmatch(r"[a-z0-9_]{3,32}", username):
|
|
raise APIError(400, "invalid_request", "Invalid username")
|
|
if not password or len(password) < 8:
|
|
raise APIError(400, "invalid_request", "Password must be at least 8 chars")
|
|
|
|
pw_hash = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
|
|
uid = str(uuid.uuid4())
|
|
|
|
conn = db_pool.getconn()
|
|
try:
|
|
with conn.cursor() as cur:
|
|
cur.execute(
|
|
"INSERT INTO users (id, username, display_name, password_hash) VALUES (%s, %s, %s, %s) RETURNING created_at",
|
|
(uid, username, display_name, pw_hash)
|
|
)
|
|
created_at = cur.fetchone()[0]
|
|
conn.commit()
|
|
self.send_json(201, {"id": uid, "username": username, "display_name": display_name, "created_at": format_dt(created_at)}, request_id)
|
|
except psycopg2.errors.UniqueViolation:
|
|
conn.rollback()
|
|
raise APIError(409, "conflict", "Username taken")
|
|
finally:
|
|
db_pool.putconn(conn)
|
|
|
|
def create_session(self, request_id):
|
|
auth = self.headers.get("Authorization")
|
|
if not auth or not auth.startswith("Basic "):
|
|
raise APIError(401, "unauthorized", "Missing Basic auth")
|
|
try:
|
|
decoded = base64.b64decode(auth.split(" ")[1]).decode('utf-8')
|
|
username, password = decoded.split(':', 1)
|
|
except Exception:
|
|
raise APIError(401, "unauthorized", "Invalid Basic format")
|
|
|
|
conn = db_pool.getconn()
|
|
try:
|
|
with conn.cursor() as cur:
|
|
cur.execute("SELECT id, display_name, password_hash, created_at FROM users WHERE username = %s", (username,))
|
|
row = cur.fetchone()
|
|
if not row or not bcrypt.checkpw(password.encode('utf-8'), row[2].encode('utf-8')):
|
|
raise APIError(401, "unauthorized", "Invalid credentials")
|
|
|
|
token = secrets.token_urlsafe(32)
|
|
redis_client.setex(f"session:{token}", SESSION_TTL, row[0])
|
|
expires_at = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL)
|
|
|
|
self.send_json(201, {
|
|
"token": token, "token_type": "Bearer", "expires_at": format_dt(expires_at),
|
|
"user": {"id": str(row[0]), "username": username, "display_name": row[1], "created_at": format_dt(row[3])}
|
|
}, request_id)
|
|
finally:
|
|
db_pool.putconn(conn)
|
|
|
|
def delete_session(self, request_id):
|
|
auth = self.headers.get("Authorization")
|
|
if auth and auth.startswith("Bearer "):
|
|
token = auth.split(" ")[1]
|
|
if redis_client.get(f"session:{token}"):
|
|
redis_client.delete(f"session:{token}")
|
|
self.send_json(204, None, request_id)
|
|
else:
|
|
raise APIError(401, "unauthorized", "Already logged out")
|
|
else:
|
|
raise APIError(401, "unauthorized", "Missing Bearer")
|
|
|
|
def get_me(self, request_id):
|
|
actor = get_user_by_token(self)
|
|
self.send_json(200, actor, request_id)
|
|
|
|
def create_chat(self, request_id):
|
|
actor = get_user_by_token(self)
|
|
body = read_json(self)
|
|
title = body.get("title")
|
|
member_ids = body.get("member_ids")
|
|
if not title or not isinstance(member_ids, list):
|
|
raise APIError(400, "invalid_request", "Invalid body")
|
|
|
|
cid = str(uuid.uuid4())
|
|
conn = db_pool.getconn()
|
|
try:
|
|
with conn.cursor() as cur:
|
|
cur.execute("INSERT INTO chats (id, title) VALUES (%s, %s) RETURNING created_at", (cid, title))
|
|
created_at = cur.fetchone()[0]
|
|
for uid in member_ids:
|
|
cur.execute("INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)", (cid, uid))
|
|
conn.commit()
|
|
self.send_json(201, {"id": cid, "title": title, "member_ids": member_ids, "created_at": format_dt(created_at)}, request_id)
|
|
except Exception:
|
|
conn.rollback()
|
|
raise
|
|
finally:
|
|
db_pool.putconn(conn)
|
|
|
|
def list_chats(self, request_id, query):
|
|
actor = get_user_by_token(self)
|
|
limit = parse_limit(query)
|
|
conn = db_pool.getconn()
|
|
try:
|
|
with conn.cursor() as cur:
|
|
cur.execute("""
|
|
SELECT c.id, c.title, c.created_at FROM chats c
|
|
JOIN chat_members cm ON c.id = cm.chat_id
|
|
WHERE cm.user_id = %s ORDER BY c.created_at DESC LIMIT %s
|
|
""", (actor["id"], limit + 1))
|
|
rows = cur.fetchall()
|
|
has_more = len(rows) > limit
|
|
rows = rows[:limit]
|
|
|
|
items = []
|
|
for r in rows:
|
|
cur.execute("SELECT user_id FROM chat_members WHERE chat_id = %s", (r[0],))
|
|
members = [str(m[0]) for m in cur.fetchall()]
|
|
items.append({
|
|
"id": str(r[0]), "title": r[1], "member_ids": members, "created_at": format_dt(r[2])
|
|
})
|
|
self.send_json(200, {"items": items, "next_cursor": None}, request_id)
|
|
finally:
|
|
db_pool.putconn(conn)
|
|
|
|
def get_chat(self, request_id, chat_id):
|
|
actor = get_user_by_token(self)
|
|
conn = db_pool.getconn()
|
|
try:
|
|
with conn.cursor() as cur:
|
|
cur.execute("""
|
|
SELECT c.id, c.title, c.created_at FROM chats c
|
|
JOIN chat_members cm ON c.id = cm.chat_id
|
|
WHERE c.id = %s AND cm.user_id = %s
|
|
""", (chat_id, actor["id"]))
|
|
row = cur.fetchone()
|
|
if not row: raise APIError(404, "not_found", "Chat not found")
|
|
|
|
cur.execute("SELECT user_id FROM chat_members WHERE chat_id = %s", (chat_id,))
|
|
members = [str(r[0]) for r in cur.fetchall()]
|
|
|
|
self.send_json(200, {"id": str(row[0]), "title": row[1], "member_ids": members, "created_at": format_dt(row[2])}, request_id)
|
|
finally:
|
|
db_pool.putconn(conn)
|
|
|
|
def create_message(self, request_id, chat_id):
|
|
actor = get_user_by_token(self)
|
|
|
|
# Идемпотентность (Lab 3)
|
|
idem_key = self.headers.get("Idempotency-Key")
|
|
if not idem_key:
|
|
raise APIError(400, "invalid_request", "Idempotency-Key header is required")
|
|
|
|
conn = db_pool.getconn()
|
|
try:
|
|
with conn.cursor() as cur:
|
|
# Проверяем членство
|
|
cur.execute("SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", (chat_id, actor["id"]))
|
|
if not cur.fetchone(): raise APIError(404, "not_found", "Chat not found")
|
|
|
|
body = read_json(self)
|
|
text = body.get("text")
|
|
if not text: raise APIError(400, "invalid_request", "Empty text")
|
|
|
|
# Хэш тела для проверки консистентности ключа
|
|
body_hash = hashlib.sha256(text.encode('utf-8')).hexdigest()
|
|
|
|
# Ищем ключ
|
|
cur.execute("SELECT message_id, body_hash FROM idempotency_keys WHERE user_id = %s AND idem_key = %s", (actor["id"], idem_key))
|
|
existing = cur.fetchone()
|
|
|
|
if existing:
|
|
if existing[1] != body_hash:
|
|
raise APIError(409, "conflict", "Idempotency key used with different body")
|
|
# Возвращаем старое сообщение
|
|
cur.execute("SELECT id, sender_id, text, created_at FROM messages WHERE id = %s", (existing[0],))
|
|
row = cur.fetchone()
|
|
return self.send_json(201, {
|
|
"id": str(row[0]), "chat_id": chat_id, "sender_id": str(row[1]), "text": row[2], "created_at": format_dt(row[3])
|
|
}, request_id)
|
|
|
|
mid = str(uuid.uuid4())
|
|
cur.execute(
|
|
"INSERT INTO messages (id, chat_id, sender_id, text) VALUES (%s, %s, %s, %s) RETURNING created_at",
|
|
(mid, chat_id, actor["id"], text)
|
|
)
|
|
created_at = cur.fetchone()[0]
|
|
|
|
cur.execute(
|
|
"INSERT INTO idempotency_keys (idem_key, user_id, message_id, body_hash) VALUES (%s, %s, %s, %s)",
|
|
(idem_key, actor["id"], mid, body_hash)
|
|
)
|
|
conn.commit()
|
|
self.send_json(201, {"id": mid, "chat_id": chat_id, "sender_id": actor["id"], "text": text, "created_at": format_dt(created_at)}, request_id)
|
|
except psycopg2.errors.UniqueViolation:
|
|
conn.rollback()
|
|
raise APIError(409, "conflict", "Concurrent request conflict")
|
|
finally:
|
|
db_pool.putconn(conn)
|
|
|
|
def list_messages(self, request_id, chat_id, query):
|
|
actor = get_user_by_token(self)
|
|
limit = parse_limit(query)
|
|
cursor = query.get("cursor", [None])[0]
|
|
|
|
conn = db_pool.getconn()
|
|
try:
|
|
with conn.cursor() as cur:
|
|
cur.execute("SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", (chat_id, actor["id"]))
|
|
if not cur.fetchone(): raise APIError(404, "not_found", "Chat not found")
|
|
|
|
if cursor:
|
|
ts, iid = decode_cursor(cursor, "messages", chat_id)
|
|
cur.execute("""
|
|
SELECT id, sender_id, text, created_at FROM messages
|
|
WHERE chat_id = %s AND (created_at, id) > (%s, %s)
|
|
ORDER BY created_at, id LIMIT %s
|
|
""", (chat_id, ts, iid, limit + 1))
|
|
else:
|
|
cur.execute("""
|
|
SELECT id, sender_id, text, created_at FROM messages
|
|
WHERE chat_id = %s ORDER BY created_at, id LIMIT %s
|
|
""", (chat_id, limit + 1))
|
|
|
|
rows = cur.fetchall()
|
|
has_more = len(rows) > limit
|
|
rows = rows[:limit]
|
|
|
|
items = [{"id": str(r[0]), "chat_id": chat_id, "sender_id": str(r[1]), "text": r[2], "created_at": format_dt(r[3])} for r in rows]
|
|
next_cursor = encode_cursor("messages", chat_id, items[-1]) if has_more and items else None
|
|
|
|
self.send_json(200, {"items": items, "next_cursor": next_cursor}, request_id)
|
|
finally:
|
|
db_pool.putconn(conn)
|
|
|
|
def send_json(self, status, payload, request_id):
|
|
self._status = status
|
|
if status == 204:
|
|
self.send_response(204)
|
|
self.send_header("X-Request-Id", request_id)
|
|
self.send_header("X-Instance-Id", INSTANCE_ID)
|
|
self.end_headers()
|
|
return
|
|
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
self.send_response(status)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("X-Request-Id", request_id)
|
|
self.send_header("X-Instance-Id", INSTANCE_ID)
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
def send_error_json(self, status, code, message, request_id):
|
|
self._status = status
|
|
body = json.dumps({"error": {"code": code, "message": message, "request_id": request_id}}, ensure_ascii=False).encode("utf-8")
|
|
self.send_response(status)
|
|
if status == 401:
|
|
parsed_path = urlparse(self.path).path
|
|
if parsed_path == "/api/v1/auth/sessions":
|
|
self.send_header("WWW-Authenticate", 'Basic realm="messenger", charset="UTF-8"')
|
|
else:
|
|
self.send_header("WWW-Authenticate", 'Bearer realm="messenger"')
|
|
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("X-Request-Id", request_id)
|
|
self.send_header("X-Instance-Id", INSTANCE_ID)
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
def main():
|
|
ThreadingHTTPServer.daemon_threads = True
|
|
ThreadingHTTPServer.allow_reuse_address = True
|
|
server = ThreadingHTTPServer((HOST, PORT), Handler)
|
|
def shutdown(signum, frame):
|
|
threading.Thread(target=server.shutdown, daemon=True).start()
|
|
signal.signal(signal.SIGTERM, shutdown)
|
|
signal.signal(signal.SIGINT, shutdown)
|
|
print(f"Listening on {HOST}:{PORT}", file=sys.stderr)
|
|
try:
|
|
server.serve_forever()
|
|
finally:
|
|
server.server_close()
|
|
|
|
if __name__ == "__main__":
|
|
main() |