Files
mtusi2026lab2/app.py
T

374 lines
16 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 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))
# Пул подключений к PostgreSQL
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 для сессий
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 now_iso():
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
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
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": row[3].strftime("%Y-%m-%dT%H:%M:%S.%fZ")
}
finally:
db_pool.putconn(conn)
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
server_version = "MessengerLab2/2.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)
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": created_at.strftime("%Y-%m-%dT%H:%M:%SZ")}, 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 с TTL
redis_client.setex(f"session:{token}", SESSION_TTL, row[0])
expires_at = (datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL)).strftime("%Y-%m-%dT%H:%M:%SZ")
self.send_json(201, {
"token": token, "token_type": "Bearer", "expires_at": expires_at,
"user": {"id": str(row[0]), "username": username, "display_name": row[1], "created_at": row[3].strftime("%Y-%m-%dT%H:%M:%SZ")}
}, 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]
redis_client.delete(f"session:{token}")
self.send_json(204, None, request_id)
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": created_at.strftime("%Y-%m-%dT%H:%M:%SZ")}, 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)
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 50
""", (actor["id"],))
rows = cur.fetchall()
items = [{"id": str(r[0]), "title": r[1], "created_at": r[2].strftime("%Y-%m-%dT%H:%M:%SZ")} for r in rows]
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": row[2].strftime("%Y-%m-%dT%H:%M:%SZ")}, request_id)
finally:
db_pool.putconn(conn)
def create_message(self, request_id, chat_id):
actor = get_user_by_token(self)
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")
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]
conn.commit()
self.send_json(201, {"id": mid, "chat_id": chat_id, "sender_id": actor["id"], "text": text, "created_at": created_at.strftime("%Y-%m-%dT%H:%M:%SZ")}, request_id)
finally:
db_pool.putconn(conn)
def list_messages(self, request_id, chat_id, query):
actor = get_user_by_token(self)
limit = int(query.get("limit", ["50"])[0])
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": r[3].strftime("%Y-%m-%dT%H:%M:%S.%fZ")} 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.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("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)
self.send_header("Content-Type", "application/json")
self.send_header("X-Request-Id", request_id)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def main():
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)
server.serve_forever()
if __name__ == "__main__":
main()