forked from mtusi2026/mtusi2026lab6
297 lines
11 KiB
Python
297 lines
11 KiB
Python
import hashlib
|
|
import json
|
|
from uuid import UUID
|
|
|
|
from psycopg.errors import ForeignKeyViolation, UniqueViolation
|
|
|
|
from src.cache import UserCache
|
|
from src.database import Database
|
|
from src.domain import Chat, Key, Message, User
|
|
from src.errors import DomainError, invalid, not_found
|
|
|
|
MESSAGE_COLUMNS = (
|
|
"m.*, ARRAY(SELECT attachment_id FROM message_attachments ma "
|
|
"WHERE ma.message_id=m.id ORDER BY ma.position) attachment_ids"
|
|
)
|
|
|
|
USER_COLUMNS = "id, username, display_name, created_at"
|
|
|
|
|
|
def user_dto(row) -> User:
|
|
return User(
|
|
row["id"], row["username"], row["display_name"], row["created_at"]
|
|
)
|
|
|
|
|
|
def chat_dto(row) -> Chat:
|
|
return Chat(
|
|
row["id"], row["title"], tuple(row["member_ids"]), row["created_at"]
|
|
)
|
|
|
|
|
|
def message_dto(row) -> Message:
|
|
return Message(
|
|
row["id"],
|
|
row["chat_id"],
|
|
row["sender_id"],
|
|
row["text"],
|
|
row["created_at"],
|
|
tuple(row.get("attachment_ids", ())),
|
|
)
|
|
|
|
|
|
class PostgresRepository:
|
|
def __init__(self, *, database: Database, cache: UserCache):
|
|
self.database = database
|
|
self.cache = cache
|
|
|
|
def add_user(self, *, user: User, password_hash: str) -> User:
|
|
try:
|
|
with self.database.connection() as conn:
|
|
conn.execute(
|
|
"INSERT INTO users(id,username,display_name,"
|
|
"password_hash,created_at) VALUES(%s,%s,%s,%s,%s)",
|
|
(
|
|
user.id,
|
|
user.username,
|
|
user.display_name,
|
|
password_hash,
|
|
user.created_at,
|
|
),
|
|
)
|
|
except UniqueViolation:
|
|
raise DomainError(
|
|
409, "conflict", "Username already exists"
|
|
) from None
|
|
return user
|
|
|
|
def get_user(self, *, user_id: UUID) -> User | None:
|
|
cached = self.cache.get(user_id=user_id)
|
|
if cached is not None:
|
|
return cached
|
|
with self.database.connection() as conn:
|
|
row = conn.execute(
|
|
"SELECT " + USER_COLUMNS + " FROM users WHERE id=%s",
|
|
(user_id,),
|
|
).fetchone()
|
|
if row is None:
|
|
return None
|
|
user = user_dto(row)
|
|
self.cache.put(user=user)
|
|
return user
|
|
|
|
def credentials(self, *, username: str):
|
|
with self.database.connection() as conn:
|
|
row = conn.execute(
|
|
"SELECT "
|
|
+ USER_COLUMNS
|
|
+ ", password_hash FROM users WHERE username=%s",
|
|
(username,),
|
|
).fetchone()
|
|
if row is None:
|
|
return None, None
|
|
return user_dto(row), row["password_hash"]
|
|
|
|
def username_exists(self, *, username: str) -> bool:
|
|
with self.database.connection() as conn:
|
|
return (
|
|
conn.execute(
|
|
"SELECT 1 FROM users WHERE username=%s", (username,)
|
|
).fetchone()
|
|
is not None
|
|
)
|
|
|
|
def add_session(
|
|
self, *, digest: bytes, user_id: UUID, created_at, expires_at
|
|
):
|
|
with self.database.connection() as conn:
|
|
conn.execute(
|
|
"INSERT INTO sessions(token_digest,user_id,created_at,"
|
|
"expires_at) VALUES(%s,%s,%s,%s)",
|
|
(digest, user_id, created_at, expires_at),
|
|
)
|
|
|
|
def session_user(self, *, digest: bytes) -> UUID | None:
|
|
with self.database.connection() as conn:
|
|
row = conn.execute(
|
|
"SELECT user_id FROM sessions WHERE token_digest=%s "
|
|
"AND expires_at>clock_timestamp()",
|
|
(digest,),
|
|
).fetchone()
|
|
return row["user_id"] if row else None
|
|
|
|
def delete_session(self, *, digest: bytes):
|
|
with self.database.connection() as conn:
|
|
conn.execute(
|
|
"DELETE FROM sessions WHERE token_digest=%s", (digest,)
|
|
)
|
|
|
|
def add_chat(self, *, chat: Chat, actor_id: UUID) -> Chat:
|
|
members = chat.member_ids
|
|
if actor_id not in members or len(set(members)) != len(members):
|
|
raise invalid()
|
|
try:
|
|
with self.database.connection() as conn, conn.transaction():
|
|
conn.execute(
|
|
"INSERT INTO chats(id,title,created_at) VALUES(%s,%s,%s)",
|
|
(chat.id, chat.title, chat.created_at),
|
|
)
|
|
with conn.cursor() as cursor:
|
|
cursor.executemany(
|
|
"INSERT INTO members(chat_id,user_id,position) "
|
|
"VALUES(%s,%s,%s)",
|
|
[
|
|
(chat.id, user_id, position)
|
|
for position, user_id in enumerate(members)
|
|
],
|
|
)
|
|
except ForeignKeyViolation:
|
|
raise invalid() from None
|
|
return chat
|
|
|
|
def get_chat(self, *, chat_id: UUID, actor_id: UUID) -> Chat:
|
|
with self.database.connection() as conn:
|
|
row = conn.execute(
|
|
"SELECT c.id,c.title,c.created_at,"
|
|
"array_agg(m.user_id ORDER BY m.position) member_ids "
|
|
"FROM chats c JOIN members m ON m.chat_id=c.id "
|
|
"WHERE c.id=%s AND EXISTS(SELECT 1 FROM members own "
|
|
"WHERE own.chat_id=c.id AND own.user_id=%s) GROUP BY c.id",
|
|
(chat_id, actor_id),
|
|
).fetchone()
|
|
if row is None:
|
|
raise not_found()
|
|
return chat_dto(row)
|
|
|
|
def add_message(
|
|
self, *, message: Message, idempotency_key: str
|
|
) -> Message:
|
|
# Область включает пользователя, метод и нормализованный путь чата.
|
|
scope = f"{message.sender_id}:POST:{message.chat_id}:{idempotency_key}"
|
|
lock = int.from_bytes(
|
|
hashlib.sha256(scope.encode()).digest()[:8], "big", signed=True
|
|
)
|
|
fingerprint = hashlib.sha256(
|
|
json.dumps(
|
|
{
|
|
"text": message.text,
|
|
"attachment_ids": [str(x) for x in message.attachment_ids],
|
|
},
|
|
ensure_ascii=False,
|
|
sort_keys=True,
|
|
separators=(",", ":"),
|
|
).encode()
|
|
).digest()
|
|
try:
|
|
with self.database.connection() as conn, conn.transaction():
|
|
conn.execute("SELECT pg_advisory_xact_lock(%s)", (lock,))
|
|
prior = conn.execute(
|
|
"SELECT i.body_hash,i.message_id,"
|
|
"i.expires_at>clock_timestamp() active "
|
|
"FROM idempotency i WHERE user_id=%s AND chat_id=%s "
|
|
"AND key=%s FOR UPDATE",
|
|
(message.sender_id, message.chat_id, idempotency_key),
|
|
).fetchone()
|
|
if prior and prior["active"]:
|
|
if bytes(prior["body_hash"]) != fingerprint:
|
|
raise DomainError(409, "conflict", "Key already used")
|
|
row = conn.execute(
|
|
"SELECT "
|
|
+ MESSAGE_COLUMNS
|
|
+ " FROM messages m WHERE m.id=%s",
|
|
(prior["message_id"],),
|
|
).fetchone()
|
|
return message_dto(row)
|
|
if message.attachment_ids:
|
|
rows = conn.execute(
|
|
"SELECT id,state FROM attachments WHERE chat_id=%s "
|
|
"AND id=ANY(%s) FOR SHARE",
|
|
(message.chat_id, list(message.attachment_ids)),
|
|
).fetchall()
|
|
if len(rows) != len(message.attachment_ids):
|
|
raise not_found()
|
|
if any(row["state"] == "failed" for row in rows):
|
|
raise DomainError(
|
|
409, "conflict", "Attachment is not ready"
|
|
)
|
|
conn.execute(
|
|
"INSERT INTO messages(id,chat_id,sender_id,"
|
|
"text,created_at) "
|
|
"VALUES(%s,%s,%s,%s,%s)",
|
|
(
|
|
message.id,
|
|
message.chat_id,
|
|
message.sender_id,
|
|
message.text,
|
|
message.created_at,
|
|
),
|
|
)
|
|
if message.attachment_ids:
|
|
with conn.cursor() as cursor:
|
|
cursor.executemany(
|
|
"INSERT INTO message_attachments("
|
|
"message_id,chat_id,"
|
|
"attachment_id,position) "
|
|
"VALUES(%s,%s,%s,%s)",
|
|
[
|
|
(message.id, message.chat_id, aid, i)
|
|
for i, aid in enumerate(message.attachment_ids)
|
|
],
|
|
)
|
|
conn.execute(
|
|
"INSERT INTO idempotency(user_id,chat_id,key,body_hash,"
|
|
"message_id,expires_at) VALUES(%s,%s,%s,%s,%s,"
|
|
"clock_timestamp()+interval '24 hours') "
|
|
"ON CONFLICT(user_id,chat_id,key) DO UPDATE SET "
|
|
"body_hash=excluded.body_hash,message_id=excluded.message_id,"
|
|
"expires_at=excluded.expires_at",
|
|
(
|
|
message.sender_id,
|
|
message.chat_id,
|
|
idempotency_key,
|
|
fingerprint,
|
|
message.id,
|
|
),
|
|
)
|
|
except ForeignKeyViolation:
|
|
raise not_found() from None
|
|
return message
|
|
|
|
def list_chats(
|
|
self, *, actor_id: UUID, after: Key | None, limit: int
|
|
) -> list[Chat]:
|
|
condition = "AND (c.created_at,c.id)>(%s,%s)" if after else ""
|
|
parameters = (
|
|
[actor_id, *after, limit + 1] if after else [actor_id, limit + 1]
|
|
)
|
|
with self.database.connection() as conn:
|
|
rows = conn.execute(
|
|
"SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id "
|
|
"FROM members WHERE chat_id=c.id "
|
|
"ORDER BY position) member_ids "
|
|
"FROM chats c JOIN members own ON own.chat_id=c.id "
|
|
"WHERE own.user_id=%s "
|
|
+ condition
|
|
+ " ORDER BY c.created_at,c.id LIMIT %s",
|
|
parameters,
|
|
).fetchall()
|
|
return [chat_dto(row) for row in rows]
|
|
|
|
def list_messages(
|
|
self, *, chat_id: UUID, actor_id: UUID, after: Key | None, limit: int
|
|
) -> list[Message]:
|
|
condition = "AND (m.created_at,m.id)>(%s,%s)" if after else ""
|
|
parameters = (
|
|
[chat_id, *after, limit + 1] if after else [chat_id, limit + 1]
|
|
)
|
|
with self.database.connection() as conn:
|
|
rows = conn.execute(
|
|
"SELECT "
|
|
+ MESSAGE_COLUMNS
|
|
+ " FROM messages m WHERE m.chat_id=%s "
|
|
+ condition
|
|
+ " ORDER BY m.created_at,m.id LIMIT %s",
|
|
parameters,
|
|
).fetchall()
|
|
return [message_dto(row) for row in rows]
|