forked from mtusi2026/mtusi2026lab4
Реализовать уровень 3: приватное S3, вложения и сохранность при отказах
This commit is contained in:
+23
-7
@@ -199,25 +199,41 @@ class PostgresStorage:
|
||||
next_cursor = self._encode_cursor('chats',user_id,page[-1].created_at,page[-1].id) if len(rows)>limit else None
|
||||
return page,next_cursor
|
||||
|
||||
def create_message(self, chat_id, sender_id, text, key):
|
||||
def create_message(self, chat_id, sender_id, text, key, attachment_ids=None):
|
||||
attachment_ids = attachment_ids or []
|
||||
normalized = {'text': text, 'attachment_ids': attachment_ids}
|
||||
# Блокировка сериализует один ключ на всех репликах; результат и сообщение атомарны.
|
||||
with self.pool.connection() as conn:
|
||||
scope = json.dumps([sender_id, chat_id, key])
|
||||
conn.execute('SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))', (scope,))
|
||||
old = conn.execute('SELECT * FROM message_requests WHERE user_id=%s AND chat_id=%s AND key=%s AND expires_at>clock_timestamp()', (sender_id,chat_id,key)).fetchone()
|
||||
if old:
|
||||
if old['body'] != text:
|
||||
if json.loads(old['body']) != normalized:
|
||||
raise ConflictError('ключ уже использован с другим сообщением')
|
||||
row = conn.execute('SELECT * FROM messages WHERE id=%s', (old['message_id'],)).fetchone()
|
||||
return Message(**public_row(row))
|
||||
optimized = os.getenv('OPTIMIZED_WRITES','1') == '1'
|
||||
return self.message_model(conn, row)
|
||||
for attachment_id in sorted(attachment_ids):
|
||||
attachment = conn.execute('SELECT state FROM attachments WHERE id=%s AND chat_id=%s FOR SHARE', (attachment_id,chat_id)).fetchone()
|
||||
if not attachment:
|
||||
raise NotFoundError('вложение не найдено')
|
||||
if attachment['state'] != 'ready':
|
||||
raise ConflictError('вложение недоступно')
|
||||
optimized = os.getenv('OPTIMIZED_WRITES','1') == '1'
|
||||
if not optimized:
|
||||
conn.execute('DELETE FROM message_requests WHERE user_id=%s AND chat_id=%s AND key=%s', (sender_id,chat_id,key))
|
||||
row = conn.execute('INSERT INTO messages (id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *', (uuid.uuid4(),chat_id,sender_id,text)).fetchone()
|
||||
# Под той же блокировкой UPSERT заменяет просроченный результат без отдельного DELETE.
|
||||
suffix = ' ON CONFLICT (user_id,chat_id,key) DO UPDATE SET body=EXCLUDED.body,message_id=EXCLUDED.message_id,expires_at=EXCLUDED.expires_at' if optimized else ''
|
||||
conn.execute("INSERT INTO message_requests VALUES (%s,%s,%s,%s,%s,clock_timestamp()+interval '24 hours')"+suffix, (sender_id,chat_id,key,text,row['id']))
|
||||
return Message(**public_row(row))
|
||||
conn.execute("INSERT INTO message_requests VALUES (%s,%s,%s,%s,%s,clock_timestamp()+interval '24 hours')"+suffix, (sender_id,chat_id,key,json.dumps(normalized,ensure_ascii=False),row['id']))
|
||||
for position, attachment_id in enumerate(attachment_ids):
|
||||
conn.execute('INSERT INTO message_attachments VALUES (%s,%s,%s)', (row['id'],attachment_id,position))
|
||||
result = self.message_model(conn,row)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def message_model(conn, row):
|
||||
ids = conn.execute('SELECT attachment_id FROM message_attachments WHERE message_id=%s ORDER BY position', (row['id'],)).fetchall()
|
||||
return Message(**public_row(row), attachment_ids=[str(x['attachment_id']) for x in ids])
|
||||
|
||||
def list_messages(self, chat_id, cursor, limit):
|
||||
with self.pool.connection() as conn:
|
||||
@@ -231,7 +247,7 @@ class PostgresStorage:
|
||||
boundary = ' AND (created_at,id) > (%s,%s)'
|
||||
params += [when,item]
|
||||
rows = conn.execute('SELECT * FROM messages WHERE chat_id=%s' + boundary + ' ORDER BY created_at,id LIMIT %s', params+[limit+1]).fetchall()
|
||||
page = [Message(**public_row(row)) for row in rows[:limit]]
|
||||
page = [self.message_model(conn,row) for row in rows[:limit]]
|
||||
next_cursor = self._encode_cursor('messages',chat_id,page[-1].created_at,page[-1].id) if len(rows)>limit else None
|
||||
return page,next_cursor
|
||||
|
||||
|
||||
Reference in New Issue
Block a user