Files
mtusi2026lab3/app/storage.py
T

342 lines
12 KiB
Python

import asyncio
import hashlib
import json
import uuid
from datetime import datetime, timezone
from typing import Optional
import asyncpg
from app.cache import Cache
def _now_iso(value: datetime) -> str:
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
def _canonical_hash(payload: dict) -> str:
canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
class Storage:
def __init__(self, pool: asyncpg.Pool, cache: Cache) -> None:
self._pool = pool
self._cache = cache
async def create_user(
self, username: str, display_name: str, password_hash: str,
) -> dict:
user_id = str(uuid.uuid4())
try:
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
"""
INSERT INTO users (id, username, display_name, password_hash)
VALUES ($1, $2, $3, $4)
RETURNING id, username, display_name, created_at
""",
user_id, username, display_name, password_hash,
)
except asyncpg.UniqueViolationError:
raise ValueError("conflict")
return self._user_row(row)
async def get_user(self, user_id: str) -> Optional[dict]:
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
"SELECT id, username, display_name, created_at FROM users WHERE id = $1",
user_id,
)
return self._user_row(row) if row else None
async def get_user_by_username(self, username: str) -> Optional[dict]:
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
"""
SELECT id, username, display_name, password_hash, created_at
FROM users WHERE username = $1
""",
username,
)
return dict(row) if row else None
async def create_chat(
self, title: str, member_ids: list[str], creator_id: str,
) -> dict:
unique = list(dict.fromkeys(member_ids))
if creator_id not in unique:
raise ValueError("creator_not_member")
chat_id = str(uuid.uuid4())
async with self._pool.acquire() as conn:
async with conn.transaction():
existing = await conn.fetchval(
"SELECT count(*) FROM users WHERE id = ANY($1::uuid[])",
unique,
)
if existing != len(unique):
raise ValueError("invalid_member")
await conn.execute(
"INSERT INTO chats (id, title) VALUES ($1, $2)",
chat_id, title,
)
await conn.executemany(
"INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)",
[(chat_id, uid) for uid in unique],
)
created = await conn.fetchval(
"SELECT created_at FROM chats WHERE id = $1", chat_id,
)
return {
"id": chat_id,
"title": title,
"member_ids": unique,
"created_at": _now_iso(created),
}
async def get_chat(self, chat_id: str, actor_id: str) -> Optional[dict]:
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
"SELECT id, title, created_at FROM chats WHERE id = $1",
chat_id,
)
if row is None:
return None
members = await conn.fetch(
"SELECT user_id FROM chat_members WHERE chat_id = $1",
chat_id,
)
member_ids = [str(m["user_id"]) for m in members]
if actor_id not in member_ids:
return None
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": member_ids,
"created_at": _now_iso(row["created_at"]),
}
async def list_chats(
self, actor_id: str, limit: int, cursor: Optional[str],
) -> tuple[list[dict], Optional[str]]:
async with self._pool.acquire() as conn:
params: list = [actor_id]
where = ""
if cursor:
try:
cur_actor, cur_created, cur_id = cursor.split("|", 2)
except ValueError:
raise ValueError("bad_cursor")
if cur_actor != actor_id:
raise ValueError("bad_cursor")
where = "AND (c.created_at, c.id) > ($2, $3)"
params += [
datetime.fromisoformat(cur_created.replace("Z", "+00:00")),
cur_id,
]
rows = await conn.fetch(
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 = $1 {where}
ORDER BY c.created_at, c.id
LIMIT ${len(params) + 1}
""",
*params, limit + 1,
)
items = []
for row in rows[:limit]:
members = await conn.fetch(
"SELECT user_id FROM chat_members WHERE chat_id = $1",
row["id"],
)
items.append({
"id": str(row["id"]),
"title": row["title"],
"member_ids": [str(m["user_id"]) for m in members],
"created_at": _now_iso(row["created_at"]),
})
next_cursor = None
if len(rows) > limit:
last = rows[limit - 1]
next_cursor = f"{actor_id}|{_now_iso(last['created_at'])}|{last['id']}"
return items, next_cursor
async def add_message(
self,
chat_id: str,
sender_id: str,
text: str,
idempotency_key: Optional[str] = None,
) -> dict:
request_hash = _canonical_hash({"text": text})
path = f"/api/v1/chats/{chat_id}/messages"
method = "POST"
if idempotency_key is not None:
cached = await self._get_idempotent(
sender_id, method, path, idempotency_key, request_hash,
)
if cached is not None:
return cached
try:
async with self._pool.acquire() as conn:
async with conn.transaction():
message_id = str(uuid.uuid4())
row = await conn.fetchrow(
"""
INSERT INTO messages (id, chat_id, sender_id, text)
SELECT $1, $2, $3, $4
WHERE EXISTS (
SELECT 1 FROM chat_members
WHERE chat_id = $2 AND user_id = $3
)
RETURNING id, chat_id, sender_id, text, created_at
""",
message_id, chat_id, sender_id, text,
)
if row is None:
raise ValueError("not_found")
message = self._message_row(row)
if idempotency_key is not None:
await conn.execute(
"""
INSERT INTO idempotency_keys
(user_id, method, path, key, request_hash,
response_status, response_body)
VALUES ($1, $2, $3, $4, $5, $6, $7)
""",
sender_id, method, path, idempotency_key,
request_hash, 201,
json.dumps(message, ensure_ascii=False),
)
except asyncpg.UniqueViolationError:
cached = await self._get_idempotent(
sender_id, method, path, idempotency_key, request_hash,
)
if cached is not None:
return cached
raise
await self._cache.invalidate_chat(chat_id)
return message
async def _get_idempotent(
self,
user_id: str,
method: str,
path: str,
key: Optional[str],
request_hash: str,
) -> Optional[dict]:
if key is None:
return None
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
"""
SELECT request_hash, response_body
FROM idempotency_keys
WHERE user_id = $1 AND method = $2 AND path = $3 AND key = $4
""",
user_id, method, path, key,
)
if row is None:
return None
if row["request_hash"] != request_hash:
raise ValueError("idempotency_conflict")
return json.loads(row["response_body"])
async def list_messages(
self, chat_id: str, actor_id: str, limit: int, cursor: Optional[str],
) -> tuple[list[dict], Optional[str]]:
async with self._pool.acquire() as conn:
is_member = await conn.fetchval(
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
chat_id, actor_id,
)
if is_member is None:
raise ValueError("not_found")
cache_key = f"messages:{chat_id}:{limit}:{cursor or ''}"
cached = await self._cache.get_json(cache_key)
if cached is not None:
return cached["items"], cached["next_cursor"]
lock_key = f"lock:{cache_key}"
got_lock = await self._cache.try_lock(lock_key, ttl=10)
if not got_lock:
for _ in range(50):
await asyncio.sleep(0.1)
cached = await self._cache.get_json(cache_key)
if cached is not None:
return cached["items"], cached["next_cursor"]
cached = await self._cache.get_json(cache_key)
if cached is not None:
return cached["items"], cached["next_cursor"]
try:
async with self._pool.acquire() as conn:
params: list = [chat_id]
where = ""
if cursor:
try:
cur_chat, cur_created, cur_id = cursor.split("|", 2)
except ValueError:
raise ValueError("bad_cursor")
if cur_chat != chat_id:
raise ValueError("bad_cursor")
where = "AND (created_at, id) > ($2, $3)"
params += [
datetime.fromisoformat(cur_created.replace("Z", "+00:00")),
cur_id,
]
rows = await conn.fetch(
f"""
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1 {where}
ORDER BY created_at, id
LIMIT ${len(params) + 1}
""",
*params, limit + 1,
)
items = [self._message_row(row) for row in rows[:limit]]
next_cursor = None
if len(rows) > limit:
last = rows[limit - 1]
next_cursor = f"{chat_id}|{_now_iso(last['created_at'])}|{last['id']}"
if got_lock:
await self._cache.set_json(
cache_key,
{"items": items, "next_cursor": next_cursor},
)
return items, next_cursor
finally:
if got_lock:
await self._cache.unlock(lock_key)
@staticmethod
def _user_row(row) -> dict:
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": _now_iso(row["created_at"]),
}
@staticmethod
def _message_row(row) -> dict:
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"created_at": _now_iso(row["created_at"]),
}