295 lines
10 KiB
Python
295 lines
10 KiB
Python
import json
|
|
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,
|
|
staging_key
|
|
)
|
|
VALUES
|
|
(
|
|
$1,
|
|
$2,
|
|
$3,
|
|
$4,
|
|
$5,
|
|
$6,
|
|
$7,
|
|
$8,
|
|
'staging/' || $7
|
|
)
|
|
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_queued(
|
|
self, attachment_id: UUID, grace_seconds: int
|
|
) -> AttachmentSchema | None:
|
|
"""Одна транзакция: принятие upload, логическая job и событие outbox"""
|
|
async with self._pool.acquire() as conn, conn.transaction():
|
|
row = await conn.fetchrow(
|
|
"""
|
|
UPDATE attachments SET status = 'queued', updated_at = clock_timestamp()
|
|
WHERE id = $1 AND status = 'pending'
|
|
AND created_at > clock_timestamp() - make_interval(secs => $2::integer)
|
|
RETURNING *;
|
|
""",
|
|
attachment_id,
|
|
grace_seconds,
|
|
)
|
|
if row is None:
|
|
return None
|
|
job_id = await conn.fetchval(
|
|
"INSERT INTO attachment_jobs (attachment_id) VALUES ($1) RETURNING id;",
|
|
attachment_id,
|
|
)
|
|
await conn.execute(
|
|
"INSERT INTO attachment_outbox (job_id, attempt) VALUES ($1, 1);",
|
|
job_id,
|
|
)
|
|
return self._row_to_attachment(row)
|
|
|
|
@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, COALESCE(staging_key, object_key) AS 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_queued этой строки
|
|
невозможен. 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, COALESCE(attachment.staging_key, attachment.object_key) AS 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,
|
|
COALESCE(staging_key, object_key) AS 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,
|
|
attachment.status,
|
|
attachment.error_code,
|
|
COALESCE((SELECT json_agg(json_build_object(
|
|
'name', v.name, 'content_type', v.content_type, 'size_bytes', v.size_bytes,
|
|
'width', v.width, 'height', v.height, 'sha256', v.sha256,
|
|
'object_key', v.object_key) ORDER BY v.name)
|
|
FROM attachment_variants v WHERE v.attachment_id = attachment.id), '[]') AS variants
|
|
FROM attachments attachment
|
|
WHERE
|
|
attachment.id = $1
|
|
AND attachment.status IN ('queued', 'processing', 'ready', 'failed')
|
|
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)
|
|
if row is None:
|
|
return None
|
|
return StoredAttachmentSchema(
|
|
attachment=self._row_to_attachment(row),
|
|
object_key=row["object_key"],
|
|
variant_keys={
|
|
v["name"]: v["object_key"] for v in json.loads(row["variants"])
|
|
},
|
|
)
|
|
|
|
@repository_logs
|
|
async def find_known_keys(self, object_keys: list[str]) -> set[str]:
|
|
"""Ключи staging/результатов активных jobs и опубликованных вариантов"""
|
|
query = """
|
|
SELECT key AS object_key FROM attachments a
|
|
CROSS JOIN LATERAL unnest(ARRAY[a.object_key, a.staging_key,
|
|
a.object_key || '/thumbnail', a.object_key || '/crop',
|
|
a.object_key || '/optimized']) AS key
|
|
WHERE key = ANY($1::text[]) AND (a.status <> 'failed' OR a.staging_key IS NOT NULL)
|
|
UNION
|
|
SELECT object_key FROM attachment_variants 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(),
|
|
status=row["status"] if "status" in row else "ready",
|
|
error_code=row["error_code"] if "error_code" in row else None,
|
|
variants=[
|
|
{k: v for k, v in item.items() if k != "object_key"}
|
|
for item in json.loads(row["variants"])
|
|
]
|
|
if "variants" in row
|
|
else [],
|
|
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"])
|