Files
mtusi2026lab3/src/store.py
T

414 lines
14 KiB
Python
Executable File

from __future__ import annotations
import base64
import json
import uuid
from datetime import datetime, timezone
from typing import List, Optional, Tuple
import psycopg
from psycopg.errors import UniqueViolation
from .db import transaction
import hashlib
import json as _json
# ---------- ошибки ----------
class ApiError(Exception):
status = 500
code = "internal_error"
def __init__(self, message: str = "Internal error") -> None:
super().__init__(message)
self.message = message
class BadRequest(ApiError):
status = 400
code = "invalid_request"
class Unauthorized(ApiError):
status = 401
code = "unauthorized"
class NotFound(ApiError):
status = 404
code = "not_found"
class Conflict(ApiError):
status = 409
code = "conflict"
# ---------- утилиты ----------
def _now() -> datetime:
return datetime.now(timezone.utc)
def iso(dt: datetime) -> str:
return dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
def _user_dict(row: dict) -> dict:
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": iso(row["created_at"]),
}
def _chat_dict(row: dict, member_ids: List[str]) -> dict:
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": member_ids,
"created_at": iso(row["created_at"]),
}
def _message_dict(row: dict) -> dict:
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"created_at": iso(row["created_at"]),
}
# ---------- курсор ----------
def _encode_cursor(scope: str, created_at: str, item_id: str) -> str:
payload = json.dumps(
{"s": scope, "t": created_at, "i": item_id}, separators=(",", ":")
).encode()
return base64.urlsafe_b64encode(payload).decode().rstrip("=")
def _decode_cursor(scope: str, cursor: str) -> Tuple[str, str]:
pad = "=" * (-len(cursor) % 4)
try:
raw = base64.urlsafe_b64decode(cursor + pad)
data = json.loads(raw)
if data.get("s") != scope:
raise ValueError("scope mismatch")
return data["t"], data["i"]
except Exception as exc:
raise BadRequest("invalid cursor") from exc
# ---------- Store ----------
class Store:
# ---- users ----
def create_user(
self, username: str, display_name: str, password_hash: str
) -> dict:
uid = str(uuid.uuid4())
now = _now()
try:
with transaction() as conn:
with conn.cursor() as cur:
cur.execute(
"""
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES (%s, %s, %s, %s, %s)
""",
(uid, username, display_name, password_hash, now),
)
except UniqueViolation:
raise Conflict("username already taken") from None
return {
"id": uid,
"username": username,
"display_name": display_name,
"created_at": iso(now),
}
def get_user(self, user_id: str) -> Optional[dict]:
with transaction() as conn:
with conn.cursor() as cur:
cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
row = cur.fetchone()
return _user_dict(row) if row else None
def get_user_by_username(self, username: str) -> Optional[dict]:
"""Возвращает полную строку, включая password_hash (для входа)."""
with transaction() as conn:
with conn.cursor() as cur:
cur.execute("SELECT * FROM users WHERE username = %s", (username,))
row = cur.fetchone()
return row
# ---- chats ----
def create_chat(
self, title: str, member_ids: List[str], creator_id: str
) -> dict:
if creator_id not in member_ids:
raise BadRequest("creator must be in member_ids")
with transaction() as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT id FROM users WHERE id = ANY(%s)",
(member_ids,),
)
found = {str(r["id"]) for r in cur.fetchall()}
missing = set(member_ids) - found
if missing:
raise BadRequest("unknown member_id")
cid = str(uuid.uuid4())
now = _now()
with transaction() as conn:
with conn.cursor() as cur:
cur.execute(
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
(cid, title, now),
)
cur.executemany(
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
[(cid, uid) for uid in member_ids],
)
return {
"id": cid,
"title": title,
"member_ids": list(member_ids),
"created_at": iso(now),
}
def get_chat(self, chat_id: str, viewer_id: str) -> Optional[dict]:
with transaction() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT c.* FROM chats c
JOIN chat_members m ON m.chat_id = c.id
WHERE c.id = %s AND m.user_id = %s
""",
(chat_id, viewer_id),
)
row = cur.fetchone()
if row is None:
return None
cur.execute(
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id",
(chat_id,),
)
members = [str(r["user_id"]) for r in cur.fetchall()]
return _chat_dict(row, members)
def list_chats(
self, viewer_id: str, limit: int, cursor: Optional[str]
) -> Tuple[List[dict], Optional[str]]:
scope = "chats:" + viewer_id
params: list = [viewer_id]
where_cursor = ""
if cursor:
t, i = _decode_cursor(scope, cursor)
where_cursor = "AND (c.created_at, c.id) > (%s, %s)"
params.extend([t, i])
params.append(limit + 1) # +1, чтобы узнать, есть ли следующая страница
with transaction() as conn:
with conn.cursor() as cur:
cur.execute(
f"""
SELECT c.id, c.title, c.created_at
FROM chats c
JOIN chat_members m ON m.chat_id = c.id
WHERE m.user_id = %s {where_cursor}
ORDER BY c.created_at, c.id
LIMIT %s
""",
params,
)
rows = cur.fetchall()
has_more = len(rows) > limit
page = rows[:limit]
result = []
for row in page:
cur.execute(
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id",
(row["id"],),
)
members = [str(r["user_id"]) for r in cur.fetchall()]
result.append(_chat_dict(row, members))
next_cursor = None
if has_more and page:
last = page[-1]
next_cursor = _encode_cursor(scope, iso(last["created_at"]), str(last["id"]))
return result, next_cursor
# ---- messages ----
def add_message(
self,
chat_id: str,
sender_id: str,
text: str,
idempotency_key: str,
) -> tuple[dict, int]:
request_hash = hashlib.sha256(
_json.dumps({"text": text}, ensure_ascii=False, sort_keys=True).encode("utf-8")
).hexdigest()
path = f"/api/v1/chats/{chat_id}/messages"
method = "POST"
with transaction() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT request_hash, response_status, response_body
FROM idempotency_keys
WHERE user_id = %s AND method = %s AND path = %s AND key = %s
""",
(sender_id, method, path, idempotency_key),
)
row = cur.fetchone()
if row is not None:
if row["request_hash"] != request_hash:
raise Conflict("idempotency key reused with different body")
return row["response_body"], row["response_status"]
try:
with transaction() as conn:
with conn.cursor() as cur:
cur.execute(
"""
INSERT INTO idempotency_keys
(user_id, method, path, key, request_hash,
response_status, response_body, created_at)
VALUES (%s, %s, %s, %s, %s, 0, '{}'::jsonb, %s)
""",
(sender_id, method, path, idempotency_key, request_hash, _now()),
)
except UniqueViolation:
with transaction() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT request_hash, response_status, response_body
FROM idempotency_keys
WHERE user_id = %s AND method = %s AND path = %s AND key = %s
""",
(sender_id, method, path, idempotency_key),
)
row = cur.fetchone()
if row is None:
raise Conflict("idempotency key race, please retry")
if row["request_hash"] != request_hash:
raise Conflict("idempotency key reused with different body")
if row["response_status"] == 0:
raise Conflict("idempotency key in progress, please retry")
return row["response_body"], row["response_status"]
with transaction() as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
(chat_id, sender_id),
)
if cur.fetchone() is None:
cur.execute(
"DELETE FROM idempotency_keys WHERE user_id = %s AND method = %s AND path = %s AND key = %s",
(sender_id, method, path, idempotency_key),
)
raise NotFound()
mid = str(uuid.uuid4())
now = _now()
cur.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES (%s, %s, %s, %s, %s)
""",
(mid, chat_id, sender_id, text, now),
)
message = {
"id": mid,
"chat_id": chat_id,
"sender_id": sender_id,
"text": text,
"created_at": iso(now),
}
cur.execute(
"""
UPDATE idempotency_keys
SET response_status = 201, response_body = %s
WHERE user_id = %s AND method = %s AND path = %s AND key = %s
""",
(_json.dumps(message, ensure_ascii=False),
sender_id, method, path, idempotency_key),
)
return message, 201
def list_messages(
self,
chat_id: str,
viewer_id: str,
limit: int,
cursor: Optional[str],
) -> Tuple[List[dict], Optional[str]]:
with transaction() as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
(chat_id, viewer_id),
)
if cur.fetchone() is None:
raise NotFound()
scope = "chat:" + chat_id
params: list = [chat_id]
where_cursor = ""
if cursor:
t, i = _decode_cursor(scope, cursor)
where_cursor = "AND (created_at, id) > (%s, %s)"
params.extend([t, i])
params.append(limit + 1)
with transaction() as conn:
with conn.cursor() as cur:
cur.execute(
f"""
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = %s {where_cursor}
ORDER BY created_at, id
LIMIT %s
""",
params,
)
rows = cur.fetchall()
has_more = len(rows) > limit
page = rows[:limit]
result = [_message_dict(r) for r in page]
next_cursor = None
if has_more and page:
last = page[-1]
next_cursor = _encode_cursor(scope, iso(last["created_at"]), str(last["id"]))
return result, next_cursor
store = Store()