forked from mtusi2026/mtusi2026lab2
reworked
This commit is contained in:
+276
@@ -0,0 +1,276 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional, Tuple
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import asyncpg
|
||||
|
||||
from app import cache, db
|
||||
from app.errors import AppError
|
||||
|
||||
|
||||
def format_ts(dt: datetime) -> str:
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
return dt.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def user_dict(row) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def chat_dict(row, member_ids: List[str]) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": member_ids,
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def message_dict(row) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
async def _run(coro):
|
||||
try:
|
||||
return await coro
|
||||
except AppError:
|
||||
raise
|
||||
except db.INTEGRITY:
|
||||
raise
|
||||
except Exception:
|
||||
raise AppError(503, "service unavailable") from None
|
||||
|
||||
|
||||
async def create_user(username: str, display_name: str, password_hash: str) -> Tuple[Optional[dict], Optional[str]]:
|
||||
user_id = uuid4()
|
||||
created = datetime.now(timezone.utc)
|
||||
try:
|
||||
async with db.require().acquire() as conn:
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
""",
|
||||
user_id,
|
||||
username,
|
||||
display_name,
|
||||
password_hash,
|
||||
created,
|
||||
)
|
||||
except asyncpg.UniqueViolationError:
|
||||
return None, "conflict"
|
||||
except Exception:
|
||||
raise AppError(503, "service unavailable") from None
|
||||
return user_dict({"id": user_id, "username": username, "display_name": display_name, "created_at": created}), None
|
||||
|
||||
|
||||
async def get_user(user_id: str) -> Optional[dict]:
|
||||
row = await _run(
|
||||
_fetchrow("SELECT id, username, display_name, created_at FROM users WHERE id = $1", UUID(user_id))
|
||||
)
|
||||
return user_dict(row) if row else None
|
||||
|
||||
|
||||
async def get_user_by_username(username: str):
|
||||
return await _run(
|
||||
_fetchrow(
|
||||
"SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1",
|
||||
username,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def _fetchrow(sql: str, *args):
|
||||
async with db.require().acquire() as conn:
|
||||
return await conn.fetchrow(sql, *args)
|
||||
|
||||
|
||||
async def _fetch(sql: str, *args):
|
||||
async with db.require().acquire() as conn:
|
||||
return await conn.fetch(sql, *args)
|
||||
|
||||
|
||||
async def member_ids_of(chat_id: UUID) -> List[str]:
|
||||
rows = await _run(_fetch("SELECT user_id FROM chat_members WHERE chat_id = $1 ORDER BY user_id", chat_id))
|
||||
return [str(r["user_id"]) for r in rows]
|
||||
|
||||
|
||||
async def create_chat(title: str, member_ids: List[str], caller_id: str) -> Tuple[Optional[dict], Optional[str]]:
|
||||
if caller_id not in member_ids:
|
||||
return None, "caller not in members"
|
||||
if len(set(member_ids)) != len(member_ids):
|
||||
return None, "duplicate members"
|
||||
ids = [UUID(x) for x in member_ids]
|
||||
chat_id = uuid4()
|
||||
created = datetime.now(timezone.utc)
|
||||
try:
|
||||
async with db.require().acquire() as conn:
|
||||
async with conn.transaction():
|
||||
existing = await conn.fetch("SELECT id FROM users WHERE id = ANY($1::uuid[])", ids)
|
||||
if len(existing) != len(ids):
|
||||
return None, "unknown member"
|
||||
await conn.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)",
|
||||
chat_id,
|
||||
title,
|
||||
created,
|
||||
)
|
||||
await conn.executemany(
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)",
|
||||
[(chat_id, mid) for mid in ids],
|
||||
)
|
||||
except AppError:
|
||||
raise
|
||||
except Exception:
|
||||
raise AppError(503, "service unavailable") from None
|
||||
return chat_dict({"id": chat_id, "title": title, "created_at": created}, member_ids), None
|
||||
|
||||
|
||||
async def get_chat(chat_id: str, user_id: str) -> Optional[dict]:
|
||||
row = await load_chat_for_member(chat_id, user_id)
|
||||
if row is None:
|
||||
return None
|
||||
return chat_dict(row, await member_ids_of(UUID(chat_id)))
|
||||
|
||||
|
||||
async def load_chat_for_member(chat_id: str, user_id: str):
|
||||
return await _run(
|
||||
_fetchrow(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id AND m.user_id = $2
|
||||
WHERE c.id = $1
|
||||
""",
|
||||
UUID(chat_id),
|
||||
UUID(user_id),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def list_chats(user_id: str, limit: int, after: Optional[Tuple[str, str]] = None):
|
||||
args: list = [UUID(user_id)]
|
||||
clause = ""
|
||||
if after is not None:
|
||||
clause = "AND (c.created_at, c.id) > ($2, $3)"
|
||||
args.extend([datetime.fromisoformat(after[0].replace("Z", "+00:00")), UUID(after[1])])
|
||||
rows = await _run(
|
||||
_fetch(
|
||||
f"""
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1
|
||||
WHERE 1=1 {clause}
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT {int(limit) + 1}
|
||||
""",
|
||||
*args,
|
||||
)
|
||||
)
|
||||
page = rows[:limit]
|
||||
items = [chat_dict(row, await member_ids_of(row["id"])) for row in page]
|
||||
next_key = None
|
||||
if len(rows) > limit:
|
||||
last = page[-1]
|
||||
next_key = (format_ts(last["created_at"]), str(last["id"]))
|
||||
return items, next_key
|
||||
|
||||
|
||||
async def add_message(chat_id: str, sender_id: str, text: str) -> Tuple[Optional[dict], Optional[str]]:
|
||||
if await load_chat_for_member(chat_id, sender_id) is None:
|
||||
return None, "not_found"
|
||||
message_id = uuid4()
|
||||
created = datetime.now(timezone.utc)
|
||||
try:
|
||||
async with db.require().acquire() as conn:
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
""",
|
||||
message_id,
|
||||
UUID(chat_id),
|
||||
UUID(sender_id),
|
||||
text,
|
||||
created,
|
||||
)
|
||||
except Exception:
|
||||
raise AppError(503, "service unavailable") from None
|
||||
await cache.invalidate_history(chat_id)
|
||||
return message_dict(
|
||||
{
|
||||
"id": message_id,
|
||||
"chat_id": UUID(chat_id),
|
||||
"sender_id": UUID(sender_id),
|
||||
"text": text,
|
||||
"created_at": created,
|
||||
}
|
||||
), None
|
||||
|
||||
|
||||
async def list_messages(chat_id: str, user_id: str, limit: int, after: Optional[Tuple[str, str]] = None):
|
||||
if await load_chat_for_member(chat_id, user_id) is None:
|
||||
return None, None, "not_found"
|
||||
cursor = ""
|
||||
after_ts = after_id = None
|
||||
if after is not None:
|
||||
cursor = after[0] + ":" + after[1]
|
||||
after_ts = datetime.fromisoformat(after[0].replace("Z", "+00:00"))
|
||||
after_id = UUID(after[1])
|
||||
|
||||
async def loader() -> dict:
|
||||
await cache.incr_history_sql()
|
||||
if after_ts is None:
|
||||
rows = await _run(
|
||||
_fetch(
|
||||
"""
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY created_at, id
|
||||
LIMIT $2
|
||||
""",
|
||||
UUID(chat_id),
|
||||
limit + 1,
|
||||
)
|
||||
)
|
||||
else:
|
||||
rows = await _run(
|
||||
_fetch(
|
||||
"""
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4
|
||||
""",
|
||||
UUID(chat_id),
|
||||
after_ts,
|
||||
after_id,
|
||||
limit + 1,
|
||||
)
|
||||
)
|
||||
page = rows[:limit]
|
||||
items = [message_dict(r) for r in page]
|
||||
next_key = None
|
||||
if len(rows) > limit:
|
||||
last = page[-1]
|
||||
next_key = (format_ts(last["created_at"]), str(last["id"]))
|
||||
return {"items": items, "next_key": next_key}
|
||||
|
||||
page = await cache.get_history_page(chat_id, cursor, limit, loader)
|
||||
return page["items"], page.get("next_key"), None
|
||||
Reference in New Issue
Block a user