feat: перенос логики с 4лабф

This commit is contained in:
Enterxx2
2026-11-09 22:33:50 +03:00
parent 276dbdad8a
commit 1d8dfb7ea4
166 changed files with 13171 additions and 6 deletions
@@ -0,0 +1,281 @@
from uuid import UUID
import asyncpg
from domain import (
AttachmentSchema,
AttachmentStatus,
NewAttachmentSchema,
StoredAttachmentSchema,
UnfinishedUploadSchema,
)
from domain.errors import NotFoundError
from infrastructure.utils import Pool, repository_logs
from interfaces import AttachmentRepository
class PostgresAttachmentRepository(AttachmentRepository):
def __init__(self, pool: Pool) -> None:
self._pool = pool
@repository_logs
async def create_pending(self, attachment: NewAttachmentSchema) -> UUID:
"""
Строка коммитится до PUT в S3. Владелец обязан быть участником чата —
это проверяет FK на chat_members.
"""
query = """
INSERT INTO attachments
(
chat_id,
owner_id,
filename,
content_type,
size_bytes,
sha256,
object_key,
status
)
VALUES
(
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8
)
RETURNING id;
"""
async with self._pool.acquire() as conn:
try:
attachment_id: UUID = await conn.fetchval(
query,
attachment.chat_id,
attachment.owner_id,
attachment.filename,
attachment.content_type,
attachment.size_bytes,
attachment.sha256,
attachment.object_key,
AttachmentStatus.PENDING,
)
except asyncpg.ForeignKeyViolationError:
raise NotFoundError() from None
return attachment_id
@repository_logs
async def mark_ready(
self, attachment_id: UUID, grace_seconds: int
) -> AttachmentSchema | None:
"""
Условие по возрасту на часах БД — тех же, по которым janitor отбирает
строки: загрузка, которую janitor уже может очищать, не подтверждается.
Одновременный claim janitor и это UPDATE сериализует блокировка строки.
"""
query = """
UPDATE attachments
SET
status = $2,
updated_at = clock_timestamp()
WHERE
id = $1
AND status = $3
AND created_at > clock_timestamp() - make_interval(secs => $4::integer)
RETURNING
id,
chat_id,
owner_id,
filename,
content_type,
size_bytes,
sha256,
created_at,
updated_at;
"""
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
query,
attachment_id,
AttachmentStatus.READY,
AttachmentStatus.PENDING,
grace_seconds,
)
return self._row_to_attachment(row) if row is not None else None
@repository_logs
async def claim_pending(self, attachment_id: UUID) -> UnfinishedUploadSchema | None:
query = """
UPDATE attachments
SET
status = $2,
updated_at = clock_timestamp()
WHERE
id = $1
AND status = $3
RETURNING id, object_key;
"""
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
query,
attachment_id,
AttachmentStatus.DELETING,
AttachmentStatus.PENDING,
)
return self._row_to_unfinished(row) if row is not None else None
@repository_logs
async def claim_unfinished(
self, grace_seconds: int, limit: int
) -> list[UnfinishedUploadSchema]:
"""
Перевод pending → deleting атомарен: после него mark_ready этой строки
невозможен. SKIP LOCKED — строку, которую сейчас подтверждает API,
janitor не ждёт и не забирает. deleting-строки возвращаются независимо
от возраста: их очистка прервалась и повторяется.
"""
query = """
WITH stale AS
(
SELECT id
FROM attachments
WHERE
status IN ($2, $3)
AND
(
status = $3
OR created_at < clock_timestamp() - make_interval(secs => $1::integer)
)
ORDER BY created_at
LIMIT $4
FOR UPDATE SKIP LOCKED
)
UPDATE attachments attachment
SET
status = $3,
updated_at = clock_timestamp()
FROM stale
WHERE attachment.id = stale.id
RETURNING attachment.id, attachment.object_key;
"""
async with self._pool.acquire() as conn:
rows = await conn.fetch(
query,
grace_seconds,
AttachmentStatus.PENDING,
AttachmentStatus.DELETING,
limit,
)
return [self._row_to_unfinished(row) for row in rows]
@repository_logs
async def list_unfinished(
self, grace_seconds: int, limit: int
) -> list[UnfinishedUploadSchema]:
query = """
SELECT
id,
object_key
FROM attachments
WHERE
status IN ($2, $3)
AND
(
status = $3
OR created_at < clock_timestamp() - make_interval(secs => $1::integer)
)
ORDER BY created_at
LIMIT $4;
"""
async with self._pool.acquire() as conn:
rows = await conn.fetch(
query,
grace_seconds,
AttachmentStatus.PENDING,
AttachmentStatus.DELETING,
limit,
)
return [self._row_to_unfinished(row) for row in rows]
@repository_logs
async def delete_claimed(self, attachment_ids: list[UUID]) -> int:
query = """
DELETE FROM attachments
WHERE
id = ANY($1::uuid[])
AND status = $2;
"""
async with self._pool.acquire() as conn:
status = await conn.execute(
query, attachment_ids, AttachmentStatus.DELETING
)
return int(status.split()[-1])
@repository_logs
async def get_for_member(
self, attachment_id: UUID, member_id: UUID
) -> StoredAttachmentSchema | None:
query = """
SELECT
attachment.id,
attachment.chat_id,
attachment.owner_id,
attachment.filename,
attachment.content_type,
attachment.size_bytes,
attachment.sha256,
attachment.object_key,
attachment.created_at,
attachment.updated_at
FROM attachments attachment
WHERE
attachment.id = $1
AND attachment.status = $3
AND EXISTS
(
SELECT 1
FROM chat_members caller
WHERE caller.chat_id = attachment.chat_id AND caller.user_id = $2
);
"""
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
query, attachment_id, member_id, AttachmentStatus.READY
)
if row is None:
return None
return StoredAttachmentSchema(
attachment=self._row_to_attachment(row), object_key=row["object_key"]
)
@repository_logs
async def find_known_keys(self, object_keys: list[str]) -> set[str]:
"""Поиск по уникальному индексу object_key"""
query = """
SELECT object_key
FROM attachments
WHERE object_key = ANY($1::text[]);
"""
async with self._pool.acquire() as conn:
rows = await conn.fetch(query, object_keys)
return {row["object_key"] for row in rows}
@staticmethod
def _row_to_attachment(row: asyncpg.Record) -> AttachmentSchema:
return AttachmentSchema(
id=row["id"],
chat_id=row["chat_id"],
owner_id=row["owner_id"],
filename=row["filename"],
content_type=row["content_type"],
size_bytes=row["size_bytes"],
sha256=row["sha256"].hex(),
created_at=row["created_at"],
updated_at=row["updated_at"],
)
@staticmethod
def _row_to_unfinished(row: asyncpg.Record) -> UnfinishedUploadSchema:
return UnfinishedUploadSchema(id=row["id"], object_key=row["object_key"])