feat: крролик, по тщ 5 лаба

This commit is contained in:
Enterxx2
2026-11-10 12:38:09 +03:00
parent 1d8dfb7ea4
commit 595a959b96
65 changed files with 2692 additions and 216 deletions
@@ -1,3 +1,4 @@
import json
from uuid import UUID
import asyncpg
@@ -34,7 +35,8 @@ class PostgresAttachmentRepository(AttachmentRepository):
size_bytes,
sha256,
object_key,
status
status,
staging_key
)
VALUES
(
@@ -45,7 +47,8 @@ class PostgresAttachmentRepository(AttachmentRepository):
$5,
$6,
$7,
$8
$8,
'staging/' || $7
)
RETURNING id;
"""
@@ -67,43 +70,32 @@ class PostgresAttachmentRepository(AttachmentRepository):
return attachment_id
@repository_logs
async def mark_ready(
async def mark_queued(
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:
"""Одна транзакция: принятие upload, логическая job и событие outbox"""
async with self._pool.acquire() as conn, conn.transaction():
row = await conn.fetchrow(
query,
"""
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,
AttachmentStatus.READY,
AttachmentStatus.PENDING,
grace_seconds,
)
return self._row_to_attachment(row) if row is not None else None
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:
@@ -115,7 +107,7 @@ class PostgresAttachmentRepository(AttachmentRepository):
WHERE
id = $1
AND status = $3
RETURNING id, object_key;
RETURNING id, COALESCE(staging_key, object_key) AS object_key;
"""
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
@@ -131,7 +123,7 @@ class PostgresAttachmentRepository(AttachmentRepository):
self, grace_seconds: int, limit: int
) -> list[UnfinishedUploadSchema]:
"""
Перевод pending → deleting атомарен: после него mark_ready этой строки
Перевод pending → deleting атомарен: после него mark_queued этой строки
невозможен. SKIP LOCKED — строку, которую сейчас подтверждает API,
janitor не ждёт и не забирает. deleting-строки возвращаются независимо
от возраста: их очистка прервалась и повторяется.
@@ -158,7 +150,7 @@ class PostgresAttachmentRepository(AttachmentRepository):
updated_at = clock_timestamp()
FROM stale
WHERE attachment.id = stale.id
RETURNING attachment.id, attachment.object_key;
RETURNING attachment.id, COALESCE(attachment.staging_key, attachment.object_key) AS object_key;
"""
async with self._pool.acquire() as conn:
rows = await conn.fetch(
@@ -177,7 +169,7 @@ class PostgresAttachmentRepository(AttachmentRepository):
query = """
SELECT
id,
object_key
COALESCE(staging_key, object_key) AS object_key
FROM attachments
WHERE
status IN ($2, $3)
@@ -228,11 +220,18 @@ class PostgresAttachmentRepository(AttachmentRepository):
attachment.sha256,
attachment.object_key,
attachment.created_at,
attachment.updated_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 = $3
AND attachment.status IN ('queued', 'processing', 'ready', 'failed')
AND EXISTS
(
SELECT 1
@@ -241,22 +240,28 @@ class PostgresAttachmentRepository(AttachmentRepository):
);
"""
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
query, attachment_id, member_id, AttachmentStatus.READY
)
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"]
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]:
"""Поиск по уникальному индексу object_key"""
"""Ключи staging/результатов активных jobs и опубликованных вариантов"""
query = """
SELECT object_key
FROM attachments
WHERE object_key = ANY($1::text[]);
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)
@@ -272,6 +277,14 @@ class PostgresAttachmentRepository(AttachmentRepository):
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"],
)