"""PostgreSQL migrations, transactional writes and keyset reads.""" import hashlib import json import os from pathlib import Path from uuid import uuid4 import psycopg from psycopg.conninfo import make_conninfo from psycopg.rows import dict_row from psycopg_pool import ConnectionPool def setting(name): path = os.environ.get(name + "_FILE") return Path(path).read_text(encoding="utf-8").strip() if path else os.environ[name] def connection_string(): return make_conninfo( setting("DATABASE_URL"), connect_timeout=3, options="-c statement_timeout=4000 -c lock_timeout=2500", ) def migrate(): with psycopg.connect(connection_string(), autocommit=True) as connection: migrations = Path(__file__).with_name("migrations") with connection.transaction(): connection.execute("SELECT pg_advisory_xact_lock(17002026)") connection.execute(""" CREATE TABLE IF NOT EXISTS schema_migrations ( name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now() ) """) for file in sorted(migrations.glob("*.sql")): with connection.transaction(): connection.execute("SELECT pg_advisory_xact_lock(17002026)") if connection.execute( "SELECT 1 FROM schema_migrations WHERE name = %s", (file.name,) ).fetchone(): continue connection.execute(file.read_text(encoding="utf-8")) connection.execute("INSERT INTO schema_migrations(name) VALUES (%s)", (file.name,)) class KeyConflict(Exception): """The same active idempotency key has a different canonical request.""" class MissingAttachment(Exception): pass class UnusableAttachment(Exception): pass def lock_attachment(connection, attachment_id): connection.execute( "SELECT pg_advisory_xact_lock(hashtextextended(%s, 4412))", (str(attachment_id),) ) class Store: def __init__(self): self.pool = ConnectionPool( connection_string(), min_size=1, max_size=8, timeout=2, open=False, kwargs={"row_factory": dict_row}, ) self.pool.open() def ready(self): with self.pool.connection() as connection: connection.execute("SELECT 1") def register(self, username, display_name, password_hash): with self.pool.connection() as connection: return connection.execute(""" INSERT INTO users(id, username, display_name, password_hash) VALUES (%s, %s, %s, %s) RETURNING id, username, display_name, created_at """, (uuid4(), username, display_name, password_hash)).fetchone() def credential(self, username): with self.pool.connection() as connection: user = connection.execute(""" SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s """, (username,)).fetchone() if user: return user, user.pop("password_hash") return None, None def user(self, user_id): with self.pool.connection() as connection: return connection.execute(""" SELECT id, username, display_name, created_at FROM users WHERE id = %s """, (user_id,)).fetchone() def create_chat(self, title, members): with self.pool.connection() as connection: chat = connection.execute(""" INSERT INTO chats(id, title) VALUES (%s, %s) RETURNING * """, (uuid4(), title)).fetchone() connection.execute(""" INSERT INTO chat_members(chat_id, user_id, position) SELECT %s, member, ord FROM unnest(%s::uuid[]) WITH ORDINALITY AS m(member, ord) """, (chat["id"], members)) return {**chat, "member_ids": members} def chat(self, user_id, chat_id): with self.pool.connection() as connection: return connection.execute(""" SELECT c.*, ARRAY(SELECT user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.position) AS member_ids FROM chats c JOIN chat_members membership ON membership.chat_id = c.id WHERE membership.user_id = %s AND c.id = %s """, (user_id, chat_id)).fetchone() def chats(self, user_id, cursor, count): with self.pool.connection() as connection: return connection.execute(""" SELECT c.*, ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.position) AS member_ids FROM chats c JOIN chat_members membership ON membership.chat_id = c.id WHERE membership.user_id = %s AND (c.created_at, c.id) > (%s::timestamptz, %s::uuid) ORDER BY c.created_at, c.id LIMIT %s """, (user_id, *cursor, count)).fetchall() def message(self, user_id, chat_id, text, key, attachment_ids): scope = (user_id, chat_id, key) # Existing text-only requests still compare the same after migration. body = {"text": text} if attachment_ids: body["attachment_ids"] = [str(value) for value in attachment_ids] fingerprint = hashlib.sha256(json.dumps(body, separators=(",", ":")).encode()).digest() with self.pool.connection() as connection: accepted = connection.execute(""" INSERT INTO message_requests(user_id, chat_id, request_key, fingerprint) VALUES (%s, %s, %s, %s) ON CONFLICT (user_id, chat_id, request_key) DO UPDATE SET fingerprint = EXCLUDED.fingerprint, message_id = NULL, expires_at = clock_timestamp() + interval '24 hours' WHERE message_requests.expires_at <= clock_timestamp() RETURNING request_key """, (*scope, fingerprint)).fetchone() if accepted: self.check_attachments(connection, chat_id, attachment_ids) message = self.insert_message(connection, user_id, chat_id, text, attachment_ids) connection.execute(""" UPDATE message_requests SET message_id = %s WHERE user_id = %s AND chat_id = %s AND request_key = %s """, (message["id"], *scope)) return message existing = connection.execute(""" SELECT m.*, r.fingerprint FROM message_requests r JOIN messages m ON m.id = r.message_id WHERE r.user_id = %s AND r.chat_id = %s AND r.request_key = %s """, scope).fetchone() if existing.pop("fingerprint") != fingerprint: raise KeyConflict() return existing def check_attachments(self, connection, chat_id, attachment_ids): if not attachment_ids: return rows = connection.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 MissingAttachment() if any(row["status"] == "failed" for row in rows): raise UnusableAttachment() def insert_message(self, connection, user_id, chat_id, text, attachment_ids): return connection.execute(""" INSERT INTO messages(id, chat_id, sender_id, text, attachment_ids) VALUES (%s, %s, %s, %s, %s::uuid[]) RETURNING * """, (uuid4(), chat_id, user_id, text, attachment_ids)).fetchone() def save_attachment(self, chat_id, user_id, filename, mime, length, store_original): attachment_id = uuid4() with self.pool.connection() as connection: lock_attachment(connection, attachment_id) digest = store_original(attachment_id) return connection.execute(""" INSERT INTO attachments(id, chat_id, owner_id, filename, content_type, size_bytes, sha256) VALUES (%s, %s, %s, %s, %s, %s, %s) RETURNING * """, (attachment_id, chat_id, user_id, filename, mime, length, digest)).fetchone() def attachment(self, user_id, attachment_id): with self.pool.connection() as connection: return connection.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, user_id)).fetchone() def messages(self, chat_id, cursor, count): with self.pool.connection() as connection: return connection.execute(""" SELECT * FROM messages WHERE chat_id = %s AND (created_at, id) > (%s::timestamptz, %s::uuid) ORDER BY created_at, id LIMIT %s """, (chat_id, *cursor, count)).fetchall() if __name__ == "__main__": migrate()