Done Track 4

This commit is contained in:
2026-10-30 16:53:49 +03:00
parent e9ee60b0ba
commit fe4a32bb79
42 changed files with 3363 additions and 118 deletions
+270 -13
View File
@@ -1,4 +1,4 @@
"""PostgreSQL repository functions for MTUSI Messenger Lab3."""
"""PostgreSQL repository functions for MTUSI Messenger Lab4."""
from __future__ import annotations
from collections.abc import Iterable
@@ -301,12 +301,28 @@ async def list_chats_for_user(
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,
@@ -316,10 +332,11 @@ async def create_message_idempotent(
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: INSERT the message, link it to the key and
COMMIT both together. A failure before COMMIT rolls back both, so a
transient error is never stored as the final answer and a retry with
the same key simply runs again.
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).
@@ -351,6 +368,23 @@ async def create_message_idempotent(
)
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(
"""
@@ -368,6 +402,25 @@ async def create_message_idempotent(
)
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(
"""
@@ -382,13 +435,15 @@ async def create_message_idempotent(
{**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
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
@@ -424,10 +479,11 @@ async def list_messages_keyset(
cursor_created_at: datetime | None,
cursor_id: UUID | None,
) -> list[dict[str, Any]]:
query = """
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = :chat_id \
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,
@@ -436,11 +492,212 @@ async def list_messages_keyset(
if cursor_created_at is not None and cursor_id is not None:
query += """
AND (created_at, id) > (:cursor_created_at, :cursor_id)
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 created_at ASC, id ASC LIMIT :limit_plus_one"
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}