"""One PostgreSQL transaction owns both a message and its retry result.""" import hashlib import json import re from uuid import uuid4 from .errors import ApiError, invalid def validate_key(key): if not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}', key): raise invalid() return key def store_message(conn, user_id, chat_id, text, key): canonical = json.dumps({'text': text}, ensure_ascii=False, sort_keys=True, separators=(',', ':')) fingerprint = hashlib.sha256(canonical.encode('utf-8')).hexdigest() params = (user_id, chat_id, key) # A competing INSERT waits for the other transaction, then the next statement sees its result. conn.execute("INSERT INTO idempotency_records(user_id,chat_id,key,request_hash,expires_at) " "VALUES (%s,%s,%s,%s,clock_timestamp()+interval '24 hours') ON CONFLICT DO NOTHING", (*params, fingerprint)) record = conn.execute('SELECT request_hash,message_id,expires_at > clock_timestamp() AS active ' 'FROM idempotency_records WHERE user_id=%s AND chat_id=%s AND key=%s FOR UPDATE', params).fetchone() if record['message_id'] is not None and record['active']: if record['request_hash'] != fingerprint: raise ApiError(409, 'conflict', 'Ключ уже использован с другим сообщением') return conn.execute('SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE id=%s', (record['message_id'],)).fetchone() 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', (uuid4(), chat_id, user_id, text)).fetchone() conn.execute("UPDATE idempotency_records SET request_hash=%s,message_id=%s,expires_at=clock_timestamp()+interval '24 hours' " 'WHERE user_id=%s AND chat_id=%s AND key=%s', (fingerprint, row['id'], *params)) return row