"""Messenger HTTP handlers; state lives only in PostgreSQL/Redis.""" import hashlib import json import re import uuid import psycopg from argon2 import PasswordHasher from fastapi import APIRouter, Request from .auth import current_user, hasher, login, logout, public_user from .core import APIError, invalid, iso, make_cursor, parse_limit, parse_uuid, read_cursor from .models import CreateChat, CreateMessage, CreateUser from .storage import db router = APIRouter() KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$", re.ASCII) def actor(req: Request) -> dict: return getattr(req.state, "actor", None) or current_user(req) def chat_detail(conn, chat: dict) -> dict: members = conn.execute("SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY position", (chat["id"],)).fetchall() return {"id": str(chat["id"]), "title": bytes(chat["title"]).decode("utf-8"), "created_at": iso(chat["created_at"]), "member_ids": [str(x["user_id"]) for x in members]} def message_detail(row: dict) -> dict: return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), "text": bytes(row["text"]).decode("utf-8"), "created_at": iso(row["created_at"])} def require_chat(conn, chat_id: str, actor_id: str) -> dict: row = conn.execute("SELECT c.* FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE c.id=%s AND cm.user_id=%s", (chat_id, actor_id)).fetchone() if row is None: raise APIError(404, "not_found", "Object not found") return row @router.get("/health/live") def live(): return {"status": "ok"} @router.get("/health/ready") def ready(): from .storage import ready as storage_ready if not storage_ready(): raise APIError(503, "unavailable", "Service not ready") return {"status": "ok"} @router.post("/api/v1/users", status_code=201) def register(body: CreateUser): hashed = hasher.hash(body.password) ident = str(uuid.uuid4()) try: with db() as conn: row = conn.execute("INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING *", (ident, body.username, body.display_name.encode("utf-8"), hashed)).fetchone() return public_user(row) except psycopg.errors.UniqueViolation: raise APIError(409, "conflict", "Username already exists") from None @router.post("/api/v1/auth/sessions", status_code=201) def sessions(req: Request): return login(req) @router.delete("/api/v1/auth/sessions/current", status_code=204) def sessions_delete(req: Request): logout(req) return None @router.get("/api/v1/users/me") def users_me(req: Request): return actor(req) @router.post("/api/v1/chats", status_code=201) def chats_create(req: Request, body: CreateChat): ident = actor(req)["id"] if ident not in body.member_ids: raise invalid("Current user must belong to the chat") chat_id = str(uuid.uuid4()) try: with db() as conn: with conn.transaction(): # Validate all members; FK constraints are the final authority for races. found = conn.execute("SELECT id FROM users WHERE id = ANY(%s::uuid[])", (body.member_ids,)).fetchall() if len(found) != len(body.member_ids): raise invalid("Unknown member") row = conn.execute("INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING *", (chat_id, body.title.encode("utf-8"))).fetchone() for pos, member in enumerate(body.member_ids): conn.execute("INSERT INTO chat_members(chat_id,user_id,position) VALUES (%s,%s,%s)", (chat_id, member, pos)) result = chat_detail(conn, row) return result except psycopg.errors.ForeignKeyViolation: raise invalid("Unknown member") from None @router.get("/api/v1/chats") def chats_list(req: Request, limit: str | None = None, cursor: str | None = None): who = actor(req)["id"] n = parse_limit(limit) mark = read_cursor(cursor, "chats", who) with db() as conn: if mark: existing = conn.execute("SELECT 1 FROM chats c JOIN chat_members cm ON c.id=cm.chat_id WHERE c.id=%s AND c.created_at=%s AND cm.user_id=%s", (mark[1], mark[0], who)).fetchone() if not existing: raise invalid("Invalid cursor") rows = conn.execute(""" SELECT c.* FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE cm.user_id=%s AND (%s::timestamptz IS NULL OR (c.created_at,c.id)>(%s::timestamptz,%s::uuid)) ORDER BY c.created_at,c.id LIMIT %s """, (who, mark[0] if mark else None, mark[0] if mark else None, mark[1] if mark else None, n+1)).fetchall() items = [chat_detail(conn, row) for row in rows[:n]] more = len(rows) > n last = rows[n-1] if more else None return {"items": items, "next_cursor": make_cursor("chats", who, last["created_at"], str(last["id"])) if last else None} @router.get("/api/v1/chats/{chat_id}") def chats_get(req: Request, chat_id: str): who = actor(req)["id"] ident = parse_uuid(chat_id) with db() as conn: row = require_chat(conn, ident, who) return chat_detail(conn, row) @router.post("/api/v1/chats/{chat_id}/messages", status_code=201) def messages_create(req: Request, chat_id: str, body: CreateMessage): who = actor(req)["id"] ident = parse_uuid(chat_id) key = req.headers.get("Idempotency-Key") if not key or not KEY_RE.fullmatch(key): raise invalid("Invalid Idempotency-Key") # Lab3 has only text; canonical JSON avoids unstable formatting/field ordering. fingerprint = hashlib.sha256(json.dumps({"text": body.text}, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest() lock_scope = f"{who}:POST:/api/v1/chats/{ident}/messages:{key}" with db() as conn: with conn.transaction(): require_chat(conn, ident, who) # Transaction-scoped advisory lock is GLOBAL across API replicas. conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (lock_scope,)) previous = conn.execute(""" SELECT idem.body_sha256, m.* FROM message_idempotency idem JOIN messages m ON m.id=idem.message_id WHERE idem.actor_id=%s AND idem.chat_id=%s AND idem.method='POST' AND idem.idem_key=%s """, (who, ident, key)).fetchone() if previous: if previous["body_sha256"] != fingerprint: raise APIError(409, "conflict", "Idempotency key used with another body") return message_detail(previous) message_id = str(uuid.uuid4()) row = conn.execute("INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *", (message_id, ident, who, body.text.encode("utf-8"))).fetchone() conn.execute("INSERT INTO message_idempotency(actor_id,chat_id,method,idem_key,body_sha256,message_id) VALUES (%s,%s,'POST',%s,%s,%s)", (who, ident, key, fingerprint, message_id)) return message_detail(row) @router.get("/api/v1/chats/{chat_id}/messages") def messages_list(req: Request, chat_id: str, limit: str | None = None, cursor: str | None = None): who = actor(req)["id"] ident = parse_uuid(chat_id) n = parse_limit(limit) mark = read_cursor(cursor, "messages", ident) with db() as conn: require_chat(conn, ident, who) if mark: existing = conn.execute("SELECT 1 FROM messages WHERE id=%s AND chat_id=%s AND created_at=%s", (mark[1], ident, mark[0])).fetchone() if not existing: raise invalid("Invalid cursor") rows = conn.execute(""" SELECT * FROM messages WHERE chat_id=%s AND (%s::timestamptz IS NULL OR (created_at,id)>(%s::timestamptz,%s::uuid)) ORDER BY created_at,id LIMIT %s """, (ident, mark[0] if mark else None, mark[0] if mark else None, mark[1] if mark else None, n+1)).fetchall() items = [message_detail(row) for row in rows[:n]] last = rows[n-1] if len(rows)>n else None return {"items": items, "next_cursor": make_cursor("messages", ident, last["created_at"], str(last["id"])) if last else None}