175 lines
7.5 KiB
Python
175 lines
7.5 KiB
Python
from datetime import datetime
|
|
from uuid import UUID, uuid4
|
|
|
|
from psycopg.errors import ForeignKeyViolation, UniqueViolation
|
|
|
|
from src.db import connection
|
|
from src.errors import ApiError
|
|
from src.pagination import decode_cursor, encode_cursor
|
|
|
|
|
|
def public(value):
|
|
if isinstance(value, dict):
|
|
return {key: public(item) for key, item in value.items()}
|
|
if isinstance(value, list):
|
|
return [public(item) for item in value]
|
|
if isinstance(value, UUID):
|
|
return str(value)
|
|
if isinstance(value, datetime):
|
|
return value.isoformat().replace("+00:00", "Z")
|
|
return value
|
|
|
|
|
|
def create_user(data, password_hash):
|
|
try:
|
|
with connection() as conn:
|
|
row = conn.execute(
|
|
"INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING id,username,display_name,created_at",
|
|
(uuid4(), data.username, data.display_name, password_hash),
|
|
).fetchone()
|
|
return public(row)
|
|
except UniqueViolation:
|
|
raise ApiError(409, "conflict", "Username уже занят") from None
|
|
|
|
|
|
def create_chat(data, caller):
|
|
if caller not in data.member_ids:
|
|
raise ApiError(400, "invalid_request", "Создатель должен входить в member_ids")
|
|
try:
|
|
with connection() as conn:
|
|
chat = conn.execute("INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING id,title,created_at", (uuid4(), data.title)).fetchone()
|
|
# FK errors here MUST roll back the already inserted parent chat.
|
|
with conn.cursor() as cursor:
|
|
cursor.executemany("INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)", [(chat['id'], member) for member in data.member_ids])
|
|
chat['member_ids'] = data.member_ids
|
|
return public(chat)
|
|
except ForeignKeyViolation:
|
|
raise ApiError(400, "invalid_request", "Указан неизвестный участник") from None
|
|
|
|
|
|
CHAT_SELECT = """SELECT c.id,c.title,c.created_at,
|
|
ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id) AS member_ids
|
|
FROM chats c WHERE EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id=c.id AND m.user_id=%s)"""
|
|
|
|
|
|
def get_chat(chat_id, user_id):
|
|
with connection() as conn:
|
|
row = conn.execute(CHAT_SELECT + " AND c.id=%s", (user_id, chat_id)).fetchone()
|
|
if not row:
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
return public(row)
|
|
|
|
|
|
def page(rows, limit, resource, owner):
|
|
items = public(rows[:limit])
|
|
cursor = None
|
|
if len(rows) > limit:
|
|
last = items[-1]
|
|
cursor = encode_cursor(resource, owner, last['created_at'], last['id'])
|
|
return {"items": items, "next_cursor": cursor}
|
|
|
|
|
|
def list_chats(user_id, limit, cursor):
|
|
params = [user_id]
|
|
sql = CHAT_SELECT
|
|
if cursor is not None:
|
|
timestamp, object_id = decode_cursor(cursor, "chats", user_id)
|
|
sql += " AND (c.created_at,c.id) > (%s::timestamptz,%s::uuid)"
|
|
params += [timestamp, object_id]
|
|
sql += " ORDER BY c.created_at,c.id LIMIT %s"
|
|
params.append(limit + 1)
|
|
with connection() as conn:
|
|
rows = conn.execute(sql, params).fetchall()
|
|
return page(rows, limit, "chats", user_id)
|
|
|
|
|
|
MESSAGE_SELECT = """SELECT m.id,m.chat_id,m.sender_id,m.text,m.created_at,
|
|
ARRAY(SELECT ma.attachment_id FROM message_attachments ma
|
|
WHERE ma.message_id=m.id ORDER BY ma.position) AS attachment_ids
|
|
FROM messages m"""
|
|
|
|
|
|
def check_attachments(conn, chat_id, attachment_ids):
|
|
if not attachment_ids:
|
|
return
|
|
rows = conn.execute(
|
|
"""SELECT id,status FROM attachments
|
|
WHERE chat_id=%s AND id=ANY(%s::uuid[]) ORDER BY id FOR SHARE""",
|
|
(chat_id, attachment_ids),
|
|
).fetchall()
|
|
if len(rows) != len(attachment_ids):
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
if any(row["status"] != "ready" for row in rows):
|
|
raise ApiError(409, "conflict", "Вложение недоступно")
|
|
|
|
|
|
def create_message(chat_id, user_id, method, key, text, attachment_ids):
|
|
scope = (user_id, method, chat_id, key)
|
|
message_id = uuid4()
|
|
with connection() as conn:
|
|
if not conn.execute(
|
|
"SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s FOR KEY SHARE",
|
|
(chat_id, user_id),
|
|
).fetchone():
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
|
|
# A concurrent ON CONFLICT waits for the first transaction. The deferred
|
|
# FK allows reserving the proposed message ID before inserting the row.
|
|
claimed = conn.execute(
|
|
"""INSERT INTO message_idempotency (user_id,method,chat_id,key,message_id,expires_at)
|
|
VALUES (%s,%s,%s,%s,%s,clock_timestamp() + interval '24 hours')
|
|
ON CONFLICT (user_id,method,chat_id,key) DO UPDATE
|
|
SET message_id=EXCLUDED.message_id, expires_at=clock_timestamp() + interval '24 hours'
|
|
WHERE message_idempotency.expires_at <= clock_timestamp()
|
|
RETURNING message_id""",
|
|
(*scope, message_id),
|
|
).fetchone()
|
|
|
|
if claimed:
|
|
check_attachments(conn, chat_id, attachment_ids)
|
|
row = conn.execute(
|
|
"""INSERT INTO messages (id,chat_id,sender_id,text)
|
|
VALUES (%s,%s,%s,%s)
|
|
RETURNING id,chat_id,sender_id,text,created_at""",
|
|
(message_id, chat_id, user_id, text),
|
|
).fetchone()
|
|
if attachment_ids:
|
|
with conn.cursor() as cursor:
|
|
cursor.executemany(
|
|
"""INSERT INTO message_attachments
|
|
(chat_id,message_id,attachment_id,position) VALUES (%s,%s,%s,%s)""",
|
|
[
|
|
(chat_id, message_id, attachment_id, position)
|
|
for position, attachment_id in enumerate(attachment_ids, 1)
|
|
],
|
|
)
|
|
row["attachment_ids"] = attachment_ids
|
|
else:
|
|
# READ COMMITTED gives this statement a new snapshot. The UPSERT
|
|
# still holds the key row locked, including when its WHERE was false.
|
|
row = conn.execute(
|
|
MESSAGE_SELECT + """ JOIN message_idempotency i ON i.message_id=m.id
|
|
WHERE (i.user_id,i.method,i.chat_id,i.key)=(%s,%s,%s,%s)""",
|
|
scope,
|
|
).fetchone()
|
|
if row["text"] != text or [str(value) for value in row["attachment_ids"]] != attachment_ids:
|
|
raise ApiError(409, "conflict", "Ключ уже использован с другим сообщением")
|
|
return public(row)
|
|
|
|
|
|
def list_messages(chat_id, user_id, limit, cursor):
|
|
with connection() as conn:
|
|
# Access precedes cursor decoding, including malformed foreign cursors.
|
|
if not conn.execute("SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s", (chat_id, user_id)).fetchone():
|
|
raise ApiError(404, "not_found", "Объект не найден")
|
|
params = [chat_id]
|
|
sql = MESSAGE_SELECT + " WHERE m.chat_id=%s"
|
|
if cursor is not None:
|
|
timestamp, object_id = decode_cursor(cursor, "messages", chat_id)
|
|
sql += " AND (created_at,id) > (%s::timestamptz,%s::uuid)"
|
|
params += [timestamp, object_id]
|
|
sql += " ORDER BY created_at,id LIMIT %s"
|
|
params.append(limit + 1)
|
|
rows = conn.execute(sql, params).fetchall()
|
|
return page(rows, limit, "messages", chat_id)
|