Files
mtusi2026lab4/app/repositories.py
T
2026-10-30 16:53:49 +03:00

704 lines
21 KiB
Python

"""PostgreSQL repository functions for MTUSI Messenger Lab4."""
from __future__ import annotations
from collections.abc import Iterable
from datetime import datetime
from typing import Any
from uuid import UUID, uuid4
from sqlalchemy import text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
async def create_user(
db: AsyncSession,
*,
username: str,
display_name: str,
password_hash: str,
) -> dict[str, Any] | None:
user_id = uuid4()
try:
result = await db.execute(
text(
"""
INSERT INTO users (id, username, display_name, password_hash)
VALUES (:id, :username, :display_name, :password_hash)
RETURNING id, username, display_name, created_at
"""
),
{
"id": user_id,
"username": username,
"display_name": display_name,
"password_hash": password_hash,
},
)
await db.commit()
return dict(result.mappings().one())
except IntegrityError:
await db.rollback()
return None
async def get_user_by_username(
db: AsyncSession,
username: str,
) -> dict[str, Any] | None:
result = await db.execute(
text(
"""
SELECT id, username, display_name, password_hash, created_at
FROM users
WHERE username = :username
"""
),
{"username": username},
)
row = result.mappings().first()
return dict(row) if row is not None else None
async def get_user_by_id(
db: AsyncSession,
user_id: UUID,
) -> dict[str, Any] | None:
result = await db.execute(
text(
"""
SELECT id, username, display_name, created_at
FROM users
WHERE id = :user_id
"""
),
{"user_id": user_id},
)
row = result.mappings().first()
return dict(row) if row is not None else None
async def user_ids_that_exist(
db: AsyncSession,
member_ids: Iterable[UUID],
) -> set[UUID]:
values = list(member_ids)
if not values:
return set()
result = await db.execute(
text("SELECT id FROM users WHERE id = ANY(CAST(:member_ids AS uuid[]))"),
{"member_ids": values},
)
return {row.id for row in result}
async def create_session(
db: AsyncSession,
*,
user_id: UUID,
token_hash: str,
expires_at: datetime,
) -> None:
await db.execute(
text(
"""
INSERT INTO sessions (id, user_id, token_hash, expires_at)
VALUES (:id, :user_id, :token_hash, :expires_at)
"""
),
{
"id": uuid4(),
"user_id": user_id,
"token_hash": token_hash,
"expires_at": expires_at,
},
)
await db.commit()
async def get_active_session_user(
db: AsyncSession,
token_hash: str,
) -> dict[str, Any] | None:
result = await db.execute(
text(
"""
SELECT
s.id AS session_id,
s.token_hash,
s.expires_at,
u.id,
u.username,
u.display_name,
u.created_at
FROM sessions AS s
JOIN users AS u ON u.id = s.user_id
WHERE s.token_hash = :token_hash
AND s.revoked_at IS NULL
AND s.expires_at > now()
"""
),
{"token_hash": token_hash},
)
row = result.mappings().first()
return dict(row) if row is not None else None
async def revoke_active_session(
db: AsyncSession,
token_hash: str,
) -> bool:
result = await db.execute(
text(
"""
UPDATE sessions
SET revoked_at = now()
WHERE token_hash = :token_hash
AND revoked_at IS NULL
AND expires_at > now()
"""
),
{"token_hash": token_hash},
)
await db.commit()
return result.rowcount == 1
async def create_chat_with_members(
db: AsyncSession,
*,
title: str,
member_ids: Iterable[UUID],
) -> dict[str, Any]:
chat_id = uuid4()
members = list(member_ids)
try:
result = await db.execute(
text(
"""
INSERT INTO chats (id, title)
VALUES (:id, :title)
RETURNING id, title, created_at
"""
),
{"id": chat_id, "title": title},
)
chat = dict(result.mappings().one())
await db.execute(
text(
"""
INSERT INTO chat_members (chat_id, user_id)
VALUES (:chat_id, :user_id)
"""
),
[{"chat_id": chat_id, "user_id": user_id} for user_id in members],
)
await db.commit()
except Exception:
await db.rollback()
raise
chat["member_ids"] = members
return chat
async def get_accessible_chat(
db: AsyncSession,
*,
chat_id: UUID,
user_id: UUID,
) -> dict[str, Any] | None:
result = await db.execute(
text(
"""
SELECT c.id, c.title, c.created_at
FROM chats AS c
JOIN chat_members AS own_membership
ON own_membership.chat_id = c.id
AND own_membership.user_id = :user_id
WHERE c.id = :chat_id
"""
),
{"chat_id": chat_id, "user_id": user_id},
)
chat_row = result.mappings().first()
if chat_row is None:
return None
members_result = await db.execute(
text(
"""
SELECT user_id
FROM chat_members
WHERE chat_id = :chat_id
ORDER BY user_id ASC
"""
),
{"chat_id": chat_id},
)
chat = dict(chat_row)
chat["member_ids"] = [row.user_id for row in members_result]
return chat
async def list_chats_for_user(
db: AsyncSession,
*,
user_id: UUID,
limit: int,
cursor_created_at: datetime | None,
cursor_id: UUID | None,
) -> list[dict[str, Any]]:
query = """
SELECT c.id, c.title, c.created_at
FROM chats AS c
JOIN chat_members AS own_membership
ON own_membership.chat_id = c.id
AND own_membership.user_id = :user_id \
"""
params: dict[str, Any] = {
"user_id": user_id,
"limit_plus_one": limit + 1,
}
if cursor_created_at is not None and cursor_id is not None:
query += """
WHERE (c.created_at, c.id) > (:cursor_created_at, :cursor_id)
"""
params["cursor_created_at"] = cursor_created_at
params["cursor_id"] = cursor_id
query += " ORDER BY c.created_at ASC, c.id ASC LIMIT :limit_plus_one"
result = await db.execute(text(query), params)
chats = [dict(row) for row in result.mappings().all()]
if not chats:
return []
chat_ids = [chat["id"] for chat in chats]
members_result = await db.execute(
text(
"""
SELECT chat_id, user_id
FROM chat_members
WHERE chat_id = ANY(CAST(:chat_ids AS uuid[]))
ORDER BY chat_id ASC, user_id ASC
"""
),
{"chat_ids": chat_ids},
)
members_by_chat: dict[UUID, list[UUID]] = {chat_id: [] for chat_id in chat_ids}
for row in members_result:
members_by_chat[row.chat_id].append(row.user_id)
for chat in chats:
chat["member_ids"] = members_by_chat[chat["id"]]
return chats
# Attachment IDs of a message in the order of the request.
MESSAGE_ATTACHMENT_IDS = """
COALESCE(
(SELECT array_agg(ma.attachment_id ORDER BY ma.position)
FROM message_attachments AS ma
WHERE ma.message_id = m.id),
CAST('{}' AS uuid[])
) AS attachment_ids
"""
class AttachmentsNotFound(Exception):
"""Some attachment_ids do not exist or belong to another chat (-> 404)."""
async def create_message_idempotent(
db: AsyncSession,
*,
chat_id: UUID,
sender_id: UUID,
text_value: str,
attachment_ids: list[UUID],
idempotency_key: str,
request_hash: str,
ttl_seconds: int,
) -> tuple[dict[str, Any], bool] | None:
"""Insert a message at most once per idempotency key; one transaction.
1. INSERT the key row. Its primary key (user, chat, method, key) lives in
the shared PostgreSQL, so a concurrent request with the same key on
ANY replica blocks on this INSERT until the first transaction ends.
2. If the key was claimed: check that every attachment belongs to this
chat, INSERT the message and its attachment links, link the message
to the key and COMMIT everything together. A failure before COMMIT
(also AttachmentsNotFound) rolls back all of it, so an error is never
stored as the final answer and a retry with the same key runs again.
3. If the key already exists (committed by someone else): return the
stored message, or None when the body differs (-> 409).
A key older than ttl_seconds is reclaimed by the ON CONFLICT ... WHERE.
Returns (message, replayed) or None on a body mismatch.
"""
key_params = {
"user_id": sender_id,
"chat_id": chat_id,
"key": idempotency_key,
}
try:
claimed = await db.execute(
text(
"""
INSERT INTO idempotency_keys AS k
(user_id, chat_id, method, key, request_hash)
VALUES (:user_id, :chat_id, 'POST', :key, :request_hash)
ON CONFLICT (user_id, chat_id, method, key) DO UPDATE
SET request_hash = EXCLUDED.request_hash,
message_id = NULL,
created_at = now()
WHERE k.created_at < now() - make_interval(secs => :ttl)
RETURNING 1
"""
),
{**key_params, "request_hash": request_hash, "ttl": ttl_seconds},
)
if claimed.first() is not None:
if attachment_ids:
# Unknown and foreign IDs look the same (404): the response
# does not reveal that an attachment of another chat exists.
found = await db.execute(
text(
"""
SELECT id FROM attachments
WHERE chat_id = :chat_id
AND id = ANY(CAST(:ids AS uuid[]))
FOR SHARE
"""
),
{"chat_id": chat_id, "ids": attachment_ids},
)
if {row.id for row in found} != set(attachment_ids):
raise AttachmentsNotFound()
result = await db.execute(
text(
"""
INSERT INTO messages (id, chat_id, sender_id, text)
VALUES (:id, :chat_id, :sender_id, :text)
RETURNING id, chat_id, sender_id, text, created_at
"""
),
{
"id": uuid4(),
"chat_id": chat_id,
"sender_id": sender_id,
"text": text_value,
},
)
message = dict(result.mappings().one())
if attachment_ids:
await db.execute(
text(
"""
INSERT INTO message_attachments
(message_id, attachment_id, position)
VALUES (:message_id, :attachment_id, :position)
"""
),
[
{
"message_id": message["id"],
"attachment_id": attachment_id,
"position": position,
}
for position, attachment_id in enumerate(attachment_ids)
],
)
await db.execute(
text(
"""
UPDATE idempotency_keys
SET message_id = :message_id
WHERE user_id = :user_id
AND chat_id = :chat_id
AND method = 'POST'
AND key = :key
"""
),
{**key_params, "message_id": message["id"]},
)
await db.commit()
message["attachment_ids"] = list(attachment_ids)
return message, False
stored = await db.execute(
text(
f"""
SELECT k.request_hash,
m.id, m.chat_id, m.sender_id, m.text, m.created_at,
{MESSAGE_ATTACHMENT_IDS}
FROM idempotency_keys AS k
JOIN messages AS m ON m.id = k.message_id
WHERE k.user_id = :user_id
AND k.chat_id = :chat_id
AND k.method = 'POST'
AND k.key = :key
"""
),
key_params,
)
row = stored.mappings().first()
await db.commit()
except Exception:
await db.rollback()
raise
if row is None:
# Not reachable while the key row and the message commit together.
raise RuntimeError("idempotency key without a message")
message = dict(row)
if message.pop("request_hash") != request_hash:
return None
return message, True
async def list_messages_keyset(
db: AsyncSession,
*,
chat_id: UUID,
limit: int,
cursor_created_at: datetime | None,
cursor_id: UUID | None,
) -> list[dict[str, Any]]:
query = f"""
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
{MESSAGE_ATTACHMENT_IDS}
FROM messages AS m
WHERE m.chat_id = :chat_id
"""
params: dict[str, Any] = {
"chat_id": chat_id,
"limit_plus_one": limit + 1,
}
if cursor_created_at is not None and cursor_id is not None:
query += """
AND (m.created_at, m.id) > (:cursor_created_at, :cursor_id)
"""
params["cursor_created_at"] = cursor_created_at
params["cursor_id"] = cursor_id
query += " ORDER BY m.created_at ASC, m.id ASC LIMIT :limit_plus_one"
result = await db.execute(text(query), params)
return [dict(row) for row in result.mappings().all()]
# --- Attachments ------------------------------------------------------------
ATTACHMENT_COLUMNS = """
a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes,
a.sha256, a.status, a.error_code, a.object_key, a.created_at, a.updated_at
"""
async def create_upload_intent(
db: AsyncSession,
*,
object_key: str,
attachment_id: UUID,
chat_id: UUID,
) -> None:
"""Committed BEFORE the S3 PUT: from now on the object can be found and
cleaned up even if this process dies right after the PUT."""
try:
await db.execute(
text(
"""
INSERT INTO upload_intents (object_key, attachment_id, chat_id)
VALUES (:object_key, :attachment_id, :chat_id)
"""
),
{
"object_key": object_key,
"attachment_id": attachment_id,
"chat_id": chat_id,
},
)
await db.commit()
except Exception:
await db.rollback()
raise
async def finalize_attachment(
db: AsyncSession,
*,
attachment_id: UUID,
chat_id: UUID,
owner_id: UUID,
filename: str,
content_type: str,
size_bytes: int,
sha256: str,
width: int,
height: int,
object_key: str,
) -> dict[str, Any] | None:
"""Delete the intent and insert the ready attachment in ONE transaction.
Returns None if the intent is already gone: the janitor decided this
upload was abandoned and deleted the object, so the row must not be
created. The DELETE waits on the janitor's row lock, so the two can
never both succeed.
"""
try:
claimed = await db.execute(
text(
"DELETE FROM upload_intents WHERE object_key = :object_key RETURNING 1"
),
{"object_key": object_key},
)
if claimed.first() is None:
await db.rollback()
return None
result = await db.execute(
text(
f"""
INSERT INTO attachments AS a
(id, chat_id, owner_id, filename, content_type, size_bytes,
sha256, width, height, object_key)
VALUES (:id, :chat_id, :owner_id, :filename, :content_type,
:size_bytes, :sha256, :width, :height, :object_key)
RETURNING {ATTACHMENT_COLUMNS}
"""
),
{
"id": attachment_id,
"chat_id": chat_id,
"owner_id": owner_id,
"filename": filename,
"content_type": content_type,
"size_bytes": size_bytes,
"sha256": sha256,
"width": width,
"height": height,
"object_key": object_key,
},
)
row = dict(result.mappings().one())
await db.commit()
return row
except Exception:
await db.rollback()
raise
async def delete_upload_intent(db: AsyncSession, object_key: str) -> None:
try:
await db.execute(
text("DELETE FROM upload_intents WHERE object_key = :object_key"),
{"object_key": object_key},
)
await db.commit()
except Exception:
await db.rollback()
raise
async def get_accessible_attachment(
db: AsyncSession,
*,
attachment_id: UUID,
user_id: UUID,
) -> dict[str, Any] | None:
"""Only members of the attachment's chat see it; others get None (404)."""
result = await db.execute(
text(
f"""
SELECT {ATTACHMENT_COLUMNS}
FROM attachments AS a
JOIN chat_members AS cm
ON cm.chat_id = a.chat_id
AND cm.user_id = :user_id
WHERE a.id = :attachment_id
"""
),
{"attachment_id": attachment_id, "user_id": user_id},
)
row = result.mappings().first()
return dict(row) if row is not None else None
async def lock_upload_intent(
db: AsyncSession,
object_key: str,
) -> dict[str, Any] | None:
"""Lock the intent of one upload (waits for a finishing transaction);
the transaction stays open. None: no intent, nothing to compensate."""
result = await db.execute(
text(
"""
SELECT i.object_key,
EXISTS (SELECT 1 FROM attachments AS a
WHERE a.object_key = i.object_key) AS committed
FROM upload_intents AS i
WHERE i.object_key = :object_key
FOR UPDATE OF i
"""
),
{"object_key": object_key},
)
row = result.mappings().first()
return dict(row) if row is not None else None
async def lock_stale_intent(
db: AsyncSession,
grace_seconds: int,
) -> dict[str, Any] | None:
"""Lock ONE intent older than the grace period; the transaction stays open.
SKIP LOCKED: an upload that is finishing right now holds the row lock in
finalize_attachment and is skipped; several replicas can run the janitor
at once without touching the same intent.
"""
result = await db.execute(
text(
"""
SELECT i.object_key,
EXISTS (SELECT 1 FROM attachments AS a
WHERE a.object_key = i.object_key) AS committed
FROM upload_intents AS i
WHERE i.created_at < now() - make_interval(secs => :grace)
ORDER BY i.created_at
LIMIT 1
FOR UPDATE OF i SKIP LOCKED
"""
),
{"grace": grace_seconds},
)
row = result.mappings().first()
return dict(row) if row is not None else None
async def attachment_keys(db: AsyncSession) -> set[str]:
result = await db.execute(text("SELECT object_key FROM attachments"))
return {row.object_key for row in result}
async def intent_keys(db: AsyncSession) -> dict[str, datetime]:
result = await db.execute(
text("SELECT object_key, created_at FROM upload_intents")
)
return {row.object_key: row.created_at for row in result}