Implement durable S3 attachments and reconciliation
This commit is contained in:
+433
@@ -0,0 +1,433 @@
|
||||
"""PostgreSQL repository: parameterised statements only, explicit transactions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
import psycopg
|
||||
from psycopg import AsyncCursor
|
||||
|
||||
from .errors import ApiProblem
|
||||
from .pagination import format_timestamp
|
||||
|
||||
# One expression keeps the member list of a chat consistent across endpoints.
|
||||
CHAT_COLUMNS = """
|
||||
c.id,
|
||||
c.title,
|
||||
c.created_at,
|
||||
ARRAY(
|
||||
SELECT m.user_id::text
|
||||
FROM chat_members m
|
||||
WHERE m.chat_id = c.id
|
||||
ORDER BY m.user_id::text
|
||||
) AS member_ids
|
||||
"""
|
||||
|
||||
|
||||
def user_json(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": format_timestamp(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def chat_json(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": [str(member) for member in row["member_ids"]],
|
||||
"created_at": format_timestamp(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def message_json(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": format_timestamp(row["created_at"]),
|
||||
"attachment_ids": [str(attachment_id) for attachment_id in row["attachment_ids"]],
|
||||
}
|
||||
|
||||
|
||||
def attachment_json(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": str(row["id"]), "chat_id": str(row["chat_id"]),
|
||||
"owner_id": str(row["owner_id"]), "filename": row["filename"],
|
||||
"content_type": row["content_type"], "size_bytes": row["size_bytes"],
|
||||
"sha256": row["sha256"], "status": row["status"], "variants": [],
|
||||
"error_code": None, "created_at": format_timestamp(row["created_at"]),
|
||||
"updated_at": format_timestamp(row["updated_at"]),
|
||||
}
|
||||
|
||||
|
||||
MESSAGE_COLUMNS = """
|
||||
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
|
||||
"""
|
||||
|
||||
|
||||
async def create_user(
|
||||
cursor: AsyncCursor,
|
||||
*,
|
||||
username: str,
|
||||
display_name: str,
|
||||
password_hash: str,
|
||||
) -> dict[str, Any]:
|
||||
try:
|
||||
await cursor.execute(
|
||||
"""
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES (%s, %s, %s, %s, now())
|
||||
RETURNING id, username, display_name, created_at
|
||||
""",
|
||||
(uuid.uuid4(), username, display_name, password_hash),
|
||||
)
|
||||
except psycopg.errors.UniqueViolation:
|
||||
raise ApiProblem(409, "conflict", "Username is already taken") from None
|
||||
row = await cursor.fetchone()
|
||||
return user_json(row)
|
||||
|
||||
|
||||
async def user_credentials(cursor: AsyncCursor, username: str) -> dict[str, Any] | None:
|
||||
await cursor.execute(
|
||||
"""
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = %s
|
||||
""",
|
||||
(username,),
|
||||
)
|
||||
return await cursor.fetchone()
|
||||
|
||||
|
||||
async def user_by_id(cursor: AsyncCursor, user_id: uuid.UUID) -> dict[str, Any] | None:
|
||||
await cursor.execute(
|
||||
"""
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = %s
|
||||
""",
|
||||
(user_id,),
|
||||
)
|
||||
return await cursor.fetchone()
|
||||
|
||||
|
||||
async def create_chat(
|
||||
cursor: AsyncCursor,
|
||||
*,
|
||||
actor_id: uuid.UUID,
|
||||
title: str,
|
||||
member_ids: list[uuid.UUID],
|
||||
) -> dict[str, Any]:
|
||||
"""Insert the chat and its membership in one transaction.
|
||||
|
||||
Unknown members are rejected by the foreign key, so the failure rolls the
|
||||
already inserted chat row back instead of leaving a chat without members.
|
||||
"""
|
||||
if actor_id not in member_ids:
|
||||
raise ApiProblem(400, "invalid_request", "Current user must be a chat member")
|
||||
chat_id = uuid.uuid4()
|
||||
try:
|
||||
await cursor.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, now())",
|
||||
(chat_id, title),
|
||||
)
|
||||
await cursor.execute(
|
||||
"""
|
||||
INSERT INTO chat_members (chat_id, user_id, joined_at)
|
||||
SELECT %s, member_id, now() FROM unnest(%s::uuid[]) AS member_id
|
||||
""",
|
||||
(chat_id, member_ids),
|
||||
)
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
raise ApiProblem(
|
||||
400, "invalid_request", "One or more members do not exist"
|
||||
) from None
|
||||
except psycopg.errors.UniqueViolation:
|
||||
raise ApiProblem(400, "invalid_request", "Chat members must be unique") from None
|
||||
await cursor.execute(
|
||||
"SELECT " + CHAT_COLUMNS + " FROM chats c WHERE c.id = %s",
|
||||
(chat_id,),
|
||||
)
|
||||
row = await cursor.fetchone()
|
||||
return chat_json(row)
|
||||
|
||||
|
||||
async def accessible_chat(
|
||||
cursor: AsyncCursor, *, actor_id: uuid.UUID, chat_id: uuid.UUID
|
||||
) -> dict[str, Any]:
|
||||
await cursor.execute(
|
||||
"""
|
||||
SELECT """
|
||||
+ CHAT_COLUMNS
|
||||
+ """
|
||||
FROM chats c
|
||||
JOIN chat_members membership
|
||||
ON membership.chat_id = c.id AND membership.user_id = %s
|
||||
WHERE c.id = %s
|
||||
""",
|
||||
(actor_id, chat_id),
|
||||
)
|
||||
row = await cursor.fetchone()
|
||||
if row is None:
|
||||
raise ApiProblem(404, "not_found", "Chat not found")
|
||||
return chat_json(row)
|
||||
|
||||
|
||||
async def chat_page(
|
||||
cursor: AsyncCursor,
|
||||
*,
|
||||
actor_id: uuid.UUID,
|
||||
limit: int,
|
||||
after: tuple[datetime, uuid.UUID] | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
query = (
|
||||
"SELECT "
|
||||
+ CHAT_COLUMNS
|
||||
+ """
|
||||
FROM chats c
|
||||
JOIN chat_members membership
|
||||
ON membership.chat_id = c.id AND membership.user_id = %(actor)s
|
||||
"""
|
||||
)
|
||||
params: dict[str, Any] = {"actor": actor_id, "limit": limit + 1}
|
||||
if after is not None:
|
||||
query += " WHERE (c.created_at, c.id) > (%(after_ts)s, %(after_id)s)"
|
||||
params["after_ts"], params["after_id"] = after
|
||||
query += " ORDER BY c.created_at, c.id LIMIT %(limit)s"
|
||||
await cursor.execute(query, params)
|
||||
return [chat_json(row) for row in await cursor.fetchall()]
|
||||
|
||||
|
||||
async def require_membership(
|
||||
cursor: AsyncCursor, *, actor_id: uuid.UUID, chat_id: uuid.UUID
|
||||
) -> None:
|
||||
await cursor.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, actor_id),
|
||||
)
|
||||
if await cursor.fetchone() is None:
|
||||
raise ApiProblem(404, "not_found", "Chat not found")
|
||||
|
||||
|
||||
async def get_idempotency_key(
|
||||
cursor: AsyncCursor, *, actor_id: uuid.UUID, chat_id: uuid.UUID, key: str
|
||||
) -> dict[str, Any] | None:
|
||||
"""Return a record only from this user's POST-message resource scope."""
|
||||
await cursor.execute(
|
||||
"""
|
||||
SELECT key, actor_id, chat_id, request_sha256, message_id, created_at
|
||||
FROM idempotency_keys
|
||||
WHERE actor_id = %s AND chat_id = %s AND key = %s
|
||||
""",
|
||||
(actor_id, chat_id, key),
|
||||
)
|
||||
return await cursor.fetchone()
|
||||
|
||||
|
||||
async def insert_idempotency_key(
|
||||
cursor: AsyncCursor,
|
||||
*,
|
||||
actor_id: uuid.UUID,
|
||||
key: str,
|
||||
chat_id: uuid.UUID,
|
||||
request_sha256: str,
|
||||
) -> bool:
|
||||
"""Atomically reserve a key without poisoning a concurrent transaction."""
|
||||
await cursor.execute(
|
||||
"""
|
||||
INSERT INTO idempotency_keys (actor_id, key, chat_id, request_sha256, created_at)
|
||||
VALUES (%s, %s, %s, %s, now())
|
||||
ON CONFLICT (actor_id, chat_id, key) DO NOTHING
|
||||
RETURNING key
|
||||
""",
|
||||
(actor_id, key, chat_id, request_sha256),
|
||||
)
|
||||
return await cursor.fetchone() is not None
|
||||
|
||||
|
||||
async def message_by_id(cursor: AsyncCursor, message_id: uuid.UUID) -> dict[str, Any] | None:
|
||||
await cursor.execute(
|
||||
"""
|
||||
SELECT """ + MESSAGE_COLUMNS + """
|
||||
FROM messages m WHERE m.id = %s
|
||||
""",
|
||||
(message_id,),
|
||||
)
|
||||
row = await cursor.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return message_json(row)
|
||||
|
||||
|
||||
async def create_message(
|
||||
cursor: AsyncCursor,
|
||||
*,
|
||||
actor_id: uuid.UUID,
|
||||
chat_id: uuid.UUID,
|
||||
text: str,
|
||||
attachment_ids: list[uuid.UUID],
|
||||
request_sha256: str,
|
||||
key: str,
|
||||
) -> dict[str, Any]:
|
||||
await require_membership(cursor, actor_id=actor_id, chat_id=chat_id)
|
||||
# The SHA-256 of the replayed body is recorded with the idempotency row so a
|
||||
# client cannot replay a request with different content under the same key.
|
||||
message_id = uuid.uuid4()
|
||||
if attachment_ids:
|
||||
await cursor.execute(
|
||||
"""
|
||||
SELECT id FROM attachments
|
||||
WHERE chat_id = %s AND status = 'ready' AND id = ANY(%s::uuid[])
|
||||
FOR UPDATE
|
||||
""",
|
||||
(chat_id, attachment_ids),
|
||||
)
|
||||
if len(await cursor.fetchall()) != len(attachment_ids):
|
||||
raise ApiProblem(404, "not_found", "Attachment not found")
|
||||
await cursor.execute(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES (%s, %s, %s, %s, now())
|
||||
RETURNING id
|
||||
""",
|
||||
(message_id, chat_id, actor_id, text),
|
||||
)
|
||||
await cursor.fetchone()
|
||||
if attachment_ids:
|
||||
await cursor.executemany(
|
||||
"""INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
VALUES (%s, %s, %s)""",
|
||||
[(message_id, attachment_id, position)
|
||||
for position, attachment_id in enumerate(attachment_ids)],
|
||||
)
|
||||
# Record the message_id so a replay can return the original message.
|
||||
await cursor.execute(
|
||||
"""
|
||||
UPDATE idempotency_keys
|
||||
SET request_sha256 = %s, message_id = %s
|
||||
WHERE actor_id = %s AND chat_id = %s AND key = %s
|
||||
""",
|
||||
(request_sha256, message_id, actor_id, chat_id, key),
|
||||
)
|
||||
return (await message_by_id(cursor, message_id)) # type: ignore[return-value]
|
||||
|
||||
|
||||
async def message_page(
|
||||
cursor: AsyncCursor,
|
||||
*,
|
||||
chat_id: uuid.UUID,
|
||||
limit: int,
|
||||
after: tuple[datetime, uuid.UUID] | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Keyset page over (created_at, id); the composite index serves both branches."""
|
||||
query = """
|
||||
SELECT """ + MESSAGE_COLUMNS + """
|
||||
FROM messages m
|
||||
WHERE m.chat_id = %(chat)s
|
||||
"""
|
||||
params: dict[str, Any] = {"chat": chat_id, "limit": limit + 1}
|
||||
if after is not None:
|
||||
query += " AND (m.created_at, m.id) > (%(after_ts)s, %(after_id)s)"
|
||||
params["after_ts"], params["after_id"] = after
|
||||
query += " ORDER BY m.created_at, m.id LIMIT %(limit)s"
|
||||
await cursor.execute(query, params)
|
||||
return [message_json(row) for row in await cursor.fetchall()]
|
||||
|
||||
|
||||
async def create_attachment(
|
||||
cursor: AsyncCursor, *, attachment_id: uuid.UUID, chat_id: uuid.UUID,
|
||||
owner_id: uuid.UUID, object_key: str, filename: str, content_type: str,
|
||||
size_bytes: int, sha256: str, width: int, height: int,
|
||||
) -> dict[str, Any]:
|
||||
await require_membership(cursor, actor_id=owner_id, chat_id=chat_id)
|
||||
await cursor.execute(
|
||||
"""INSERT INTO attachments
|
||||
(id, chat_id, owner_id, object_key, filename, content_type, size_bytes,
|
||||
sha256, width, height, status, created_at, updated_at)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'ready', now(), now())
|
||||
RETURNING *""",
|
||||
(attachment_id, chat_id, owner_id, object_key, filename, content_type,
|
||||
size_bytes, sha256, width, height),
|
||||
)
|
||||
return attachment_json(await cursor.fetchone())
|
||||
|
||||
|
||||
async def accessible_attachment(
|
||||
cursor: AsyncCursor, *, actor_id: uuid.UUID, attachment_id: uuid.UUID
|
||||
) -> dict[str, Any]:
|
||||
await cursor.execute(
|
||||
"""SELECT a.* FROM attachments a
|
||||
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = %s
|
||||
WHERE a.id = %s""",
|
||||
(actor_id, attachment_id),
|
||||
)
|
||||
row = await cursor.fetchone()
|
||||
if row is None:
|
||||
raise ApiProblem(404, "not_found", "Attachment not found")
|
||||
return row
|
||||
|
||||
|
||||
async def insert_session(
|
||||
cursor: AsyncCursor,
|
||||
*,
|
||||
user_id: uuid.UUID,
|
||||
token_hash: str,
|
||||
ttl_seconds: int,
|
||||
) -> datetime:
|
||||
await cursor.execute(
|
||||
"""
|
||||
INSERT INTO sessions (id, user_id, token_hash, created_at, expires_at)
|
||||
VALUES (%s, %s, %s, now(), now() + make_interval(secs => %s))
|
||||
RETURNING expires_at
|
||||
""",
|
||||
(uuid.uuid4(), user_id, token_hash, ttl_seconds),
|
||||
)
|
||||
row = await cursor.fetchone()
|
||||
return row["expires_at"]
|
||||
|
||||
|
||||
async def session_user(cursor: AsyncCursor, token_hash: str) -> dict[str, Any] | None:
|
||||
"""Resolve a live session row; expired and revoked sessions never match."""
|
||||
await cursor.execute(
|
||||
"""
|
||||
SELECT s.expires_at, u.id, u.username, u.display_name, u.created_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = %s AND s.revoked_at IS NULL AND s.expires_at > now()
|
||||
""",
|
||||
(token_hash,),
|
||||
)
|
||||
return await cursor.fetchone()
|
||||
|
||||
|
||||
async def revoke_session(cursor: AsyncCursor, token_hash: str) -> datetime | None:
|
||||
"""Revoke a live session and return its expiry, or None when it is not live."""
|
||||
await cursor.execute(
|
||||
"""
|
||||
UPDATE sessions SET revoked_at = now()
|
||||
WHERE token_hash = %s AND revoked_at IS NULL AND expires_at > now()
|
||||
RETURNING expires_at
|
||||
""",
|
||||
(token_hash,),
|
||||
)
|
||||
row = await cursor.fetchone()
|
||||
return None if row is None else row["expires_at"]
|
||||
|
||||
|
||||
async def purge_expired_sessions(cursor: AsyncCursor) -> int:
|
||||
await cursor.execute(
|
||||
"""
|
||||
DELETE FROM sessions
|
||||
WHERE expires_at < now() - interval '1 hour'
|
||||
OR (revoked_at IS NOT NULL AND revoked_at < now() - interval '1 hour')
|
||||
"""
|
||||
)
|
||||
return cursor.rowcount
|
||||
Reference in New Issue
Block a user