Пользователи, аутентификация Argon2id, Bearer-сессии с TTL и отзывом, транзакционный репозиторий, keyset-пагинация, идемпотентные отправки (advisory lock + message_requests), версияемые миграции 001/002.
197 lines
9.8 KiB
Python
197 lines
9.8 KiB
Python
"""PostgreSQL repository: all SQL values are bound parameters."""
|
|
from datetime import datetime, timezone
|
|
import hashlib
|
|
import json
|
|
from uuid import UUID, uuid4
|
|
import psycopg
|
|
from .domain import ApiError, invalid
|
|
|
|
|
|
def serialize(row):
|
|
if row is None:
|
|
return None
|
|
result = {}
|
|
for key, value in row.items():
|
|
if isinstance(value, UUID):
|
|
value = str(value)
|
|
elif isinstance(value, datetime):
|
|
value = value.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
|
elif isinstance(value, list):
|
|
value = [str(item) if isinstance(item, UUID) else item for item in value]
|
|
result[key] = value
|
|
return result
|
|
|
|
|
|
USER_COLUMNS = 'id, username, display_name, created_at'
|
|
# Members retain the request order, with no password/session fields in public objects.
|
|
CHAT_COLUMNS = '''c.id, c.title, c.created_at,
|
|
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id=c.id ORDER BY m.position) AS member_ids'''
|
|
|
|
|
|
class PostgresRepository:
|
|
def __init__(self, database):
|
|
self.db = database
|
|
|
|
def ready(self):
|
|
with self.db.transaction() as conn:
|
|
conn.execute('SELECT id FROM users LIMIT 0')
|
|
conn.execute('SELECT token_hash FROM sessions LIMIT 0')
|
|
|
|
def cursor_key(self):
|
|
with self.db.transaction() as conn:
|
|
row = conn.execute("SELECT value FROM app_settings WHERE name='cursor_key'").fetchone()
|
|
if row is None:
|
|
raise ApiError(503, 'unavailable', 'Database is not initialized')
|
|
return bytes.fromhex(row['value'])
|
|
|
|
def create_user(self, username, display_name, password_hash):
|
|
try:
|
|
with self.db.transaction() as conn:
|
|
row = conn.execute('INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING ' + USER_COLUMNS,
|
|
(uuid4(), username, display_name, password_hash)).fetchone()
|
|
return serialize(row)
|
|
except psycopg.errors.UniqueViolation:
|
|
raise ApiError(409, 'conflict', 'Username already exists') from None
|
|
|
|
def credentials(self, username):
|
|
with self.db.transaction() as conn:
|
|
return serialize(conn.execute('SELECT ' + USER_COLUMNS + ', password_hash FROM users WHERE username=%s',
|
|
(username,)).fetchone())
|
|
|
|
def create_session(self, user_id, token_hash, ttl):
|
|
with self.db.transaction() as conn:
|
|
row = conn.execute('INSERT INTO sessions(token_hash,user_id,expires_at) VALUES (%s,%s,clock_timestamp() + %s * interval \'1 second\') RETURNING expires_at',
|
|
(token_hash, user_id, ttl)).fetchone()
|
|
return serialize(row)['expires_at']
|
|
|
|
def session_user(self, token_hash):
|
|
with self.db.transaction() as conn:
|
|
row = conn.execute('''SELECT u.id,u.username,u.display_name,u.created_at FROM users u
|
|
JOIN sessions s ON s.user_id=u.id
|
|
WHERE s.token_hash=%s AND s.expires_at>clock_timestamp()''', (token_hash,)).fetchone()
|
|
if row is None:
|
|
raise ApiError(401, 'unauthorized', 'Valid Bearer session required')
|
|
return serialize(row)
|
|
|
|
def revoke_session(self, token_hash):
|
|
with self.db.transaction() as conn:
|
|
conn.execute('DELETE FROM sessions WHERE token_hash=%s', (token_hash,))
|
|
|
|
@staticmethod
|
|
def _access(conn, actor, chat_id):
|
|
if conn.execute('SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s', (chat_id, actor)).fetchone() is None:
|
|
raise ApiError(404, 'not_found', 'Chat not found')
|
|
|
|
def create_chat(self, actor, title, members):
|
|
with self.db.transaction() as conn:
|
|
count = conn.execute('SELECT count(*) AS n FROM users WHERE id=ANY(%s::uuid[])', (members,)).fetchone()['n']
|
|
if actor not in members or count != len(members):
|
|
invalid('Members must exist and include the current user')
|
|
identifier = uuid4()
|
|
conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s)', (identifier, title))
|
|
with conn.cursor() as cur:
|
|
cur.executemany('INSERT INTO chat_members(chat_id,user_id,position) VALUES (%s,%s,%s)',
|
|
[(identifier, member, i) for i, member in enumerate(members)])
|
|
row = conn.execute('SELECT ' + CHAT_COLUMNS + ' FROM chats c WHERE c.id=%s', (identifier,)).fetchone()
|
|
return serialize(row)
|
|
|
|
def chat(self, actor, chat_id):
|
|
with self.db.transaction() as conn:
|
|
self._access(conn, actor, chat_id)
|
|
row = conn.execute('SELECT ' + CHAT_COLUMNS + ' FROM chats c WHERE c.id=%s', (chat_id,)).fetchone()
|
|
return serialize(row)
|
|
|
|
def chats(self, actor, limit, after):
|
|
params = [actor]
|
|
boundary = ''
|
|
if after is not None:
|
|
boundary = ' AND (c.created_at,c.id)>(%s::timestamptz,%s::uuid)'
|
|
params.extend(after)
|
|
params.append(limit)
|
|
with self.db.transaction() as conn:
|
|
rows = conn.execute('SELECT ' + CHAT_COLUMNS + ''' FROM chats c JOIN chat_members own
|
|
ON own.chat_id=c.id WHERE own.user_id=%s''' + boundary +
|
|
' ORDER BY c.created_at,c.id LIMIT %s', params).fetchall()
|
|
return [serialize(r) for r in rows]
|
|
|
|
@staticmethod
|
|
def _message(conn, message_id):
|
|
row = conn.execute('SELECT * FROM messages WHERE id=%s', (message_id,)).fetchone()
|
|
result = serialize(row)
|
|
result['attachment_ids'] = [str(r['attachment_id']) for r in conn.execute(
|
|
'SELECT attachment_id FROM message_attachments WHERE message_id=%s ORDER BY position',
|
|
(message_id,)).fetchall()]
|
|
return result
|
|
|
|
def create_message(self, actor, chat_id, text, attachments, key, ttl):
|
|
scope = json.dumps([actor, chat_id, key], separators=(',', ':')).encode()
|
|
lock_id = int.from_bytes(hashlib.sha256(scope).digest()[:8], 'big', signed=True)
|
|
with self.db.transaction() as conn:
|
|
self._access(conn, actor, chat_id)
|
|
conn.execute('SELECT pg_advisory_xact_lock(%s)', (lock_id,))
|
|
previous = conn.execute("""SELECT request_text, request_attachments, message_id
|
|
FROM message_requests WHERE user_id=%s AND chat_id=%s AND idempotency_key=%s
|
|
AND expires_at>clock_timestamp()""", (actor, chat_id, key)).fetchone()
|
|
if previous:
|
|
if previous['request_text'] != text or previous['request_attachments'] != attachments:
|
|
raise ApiError(409, 'conflict', 'Idempotency key already used with another message')
|
|
return self._message(conn, previous['message_id'])
|
|
conn.execute('DELETE FROM message_requests WHERE user_id=%s AND chat_id=%s AND idempotency_key=%s',
|
|
(actor, chat_id, key))
|
|
if attachments:
|
|
found = conn.execute('SELECT id FROM attachments WHERE chat_id=%s AND id=ANY(%s::uuid[])',
|
|
(chat_id, attachments)).fetchall()
|
|
if len(found) != len(attachments):
|
|
raise ApiError(404, 'not_found', 'Attachment not found')
|
|
message_id = uuid4()
|
|
conn.execute('INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s)',
|
|
(message_id, chat_id, actor, text))
|
|
for i, aid in enumerate(attachments):
|
|
conn.execute('INSERT INTO message_attachments(message_id,attachment_id,position) VALUES (%s,%s,%s)',
|
|
(message_id, aid, i))
|
|
conn.execute("""INSERT INTO message_requests
|
|
(user_id,chat_id,idempotency_key,request_text,request_attachments,message_id,expires_at)
|
|
VALUES (%s,%s,%s,%s,%s::jsonb,%s,clock_timestamp() + %s * interval '1 second')""",
|
|
(actor, chat_id, key, text, json.dumps(attachments), message_id, ttl))
|
|
return self._message(conn, message_id)
|
|
|
|
def messages(self, actor, chat_id, limit, after):
|
|
params = [chat_id]
|
|
boundary = ''
|
|
if after is not None:
|
|
boundary = ' AND (created_at,id)>(%s::timestamptz,%s::uuid)'
|
|
params.extend(after)
|
|
params.append(limit)
|
|
with self.db.transaction() as conn:
|
|
self._access(conn, actor, chat_id)
|
|
rows = conn.execute('SELECT id FROM messages WHERE chat_id=%s' + boundary +
|
|
' ORDER BY created_at,id LIMIT %s', params).fetchall()
|
|
return [self._message(conn, row['id']) for row in rows]
|
|
|
|
@staticmethod
|
|
def _attachment(row):
|
|
obj = serialize(row)
|
|
obj.pop('object_key', None)
|
|
obj['status'] = 'ready'
|
|
obj['variants'] = []
|
|
obj['error_code'] = None
|
|
return obj
|
|
|
|
def insert_attachment(self, actor, chat_id, metadata):
|
|
with self.db.transaction() as conn:
|
|
self._access(conn, actor, chat_id)
|
|
row = conn.execute("""INSERT INTO attachments
|
|
(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,object_key)
|
|
VALUES (%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *""",
|
|
(metadata['id'], chat_id, actor, metadata['filename'], metadata['content_type'],
|
|
metadata['size_bytes'], metadata['sha256'], metadata['object_key'])).fetchone()
|
|
return self._attachment(row)
|
|
|
|
def attachment(self, actor, attachment_id):
|
|
with self.db.transaction() as conn:
|
|
row = conn.execute("""SELECT a.* FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id
|
|
WHERE a.id=%s AND m.user_id=%s""", (attachment_id, actor)).fetchone()
|
|
if row is None:
|
|
raise ApiError(404, 'not_found', 'Attachment not found')
|
|
return self._attachment(row), row['object_key']
|