This commit is contained in:
2026-11-22 17:20:34 +03:00
parent c10bf08feb
commit 7e1780be67
14 changed files with 938 additions and 60 deletions
+168 -44
View File
@@ -11,9 +11,11 @@ from typing import BinaryIO, Dict, List, Optional, Sequence, Tuple
import asyncpg
from .config import job_max_attempts
from .errors import conflict, invalid_request, not_found, unavailable
from .jobs import PIPELINE_VERSION, dump_job, original_key, staging_key
from .migrate import expected_versions
from .objects import ORIGINAL_PREFIX, MissingObject, ObjectStore, StorageError
from .objects import MissingObject, ObjectStore, StorageError
from .pagination import Key
from .passwords import hash_password, password_matches
@@ -72,6 +74,26 @@ class Message:
}
@dataclass(frozen=True)
class Variant:
name: str
content_type: str
size_bytes: int
width: int
height: int
sha256: str
def to_dict(self) -> dict:
return {
'name': self.name,
'content_type': self.content_type,
'size_bytes': self.size_bytes,
'width': self.width,
'height': self.height,
'sha256': self.sha256,
}
@dataclass(frozen=True)
class Attachment:
id: str
@@ -84,6 +106,8 @@ class Attachment:
status: str
created_at: str
updated_at: str
variants: Tuple[Variant, ...] = ()
error_code: Optional[str] = None
def to_dict(self) -> dict:
return {
@@ -95,13 +119,19 @@ class Attachment:
'size_bytes': self.size_bytes,
'sha256': self.sha256,
'status': self.status,
'variants': [],
'error_code': None,
'variants': [item.to_dict() for item in self.variants],
'error_code': self.error_code if self.status == 'failed' else None,
'created_at': self.created_at,
'updated_at': self.updated_at,
}
@dataclass(frozen=True)
class QueuedUpload:
attachment: Attachment
body: bytes
@dataclass(frozen=True)
class AttachmentRef:
"""One metadata row as the reconciler sees it. Not an API response."""
@@ -391,45 +421,63 @@ class Store:
body: BinaryIO,
size_bytes: int,
sha256: str,
) -> Attachment:
) -> QueuedUpload:
chat_uuid = _as_uuid(chat_id, 'Некорректный chat_id')
owner_uuid = _as_uuid(owner_id, 'Некорректный user_id')
attachment_id = uuid.uuid4()
# The key is not derived from filename. A crash after PUT and before INSERT leaves an
# unreferenced object; a failed INSERT deletes it. 202 is returned only after both succeed.
# Status stays queued: readiness is a later metadata read, not this response.
object_key = ORIGINAL_PREFIX + str(attachment_id)
job_id = uuid.uuid4()
# filename is never a storage key. Bytes go to staging/ first; the worker copies them
# unchanged to originals/ and writes the thumbnail. 202 is sent only after the broker
# confirms the job, which happens in the route after this commit.
staged = staging_key(str(attachment_id))
final = original_key(str(attachment_id))
created = self._now()
try:
await asyncio.to_thread(self._objects.put_stream, object_key, body, size_bytes, content_type)
await asyncio.to_thread(self._objects.put_stream, staged, body, size_bytes, content_type)
except StorageError:
await self._discard_object(object_key)
await self._discard_object(staged)
raise unavailable('Хранилище недоступно') from None
try:
async with self._pool.acquire() as conn:
await conn.execute(
'''
INSERT INTO attachments (
id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
object_key, staging_key, status, created_at, updated_at
async with conn.transaction():
await conn.execute(
'''
INSERT INTO attachments (
id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
object_key, staging_key, status, created_at, updated_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 'queued', $10, $10)
''',
attachment_id,
chat_uuid,
owner_uuid,
filename,
content_type,
size_bytes,
sha256,
final,
staged,
created,
)
await conn.execute(
'''
INSERT INTO attachment_jobs (
id, attachment_id, pipeline_version, attempt, max_attempts,
created_at, updated_at
)
VALUES ($1, $2, $3, 1, $4, $5, $5)
''',
job_id,
attachment_id,
PIPELINE_VERSION,
job_max_attempts(),
created,
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $8, 'queued', $9, $9)
''',
attachment_id,
chat_uuid,
owner_uuid,
filename,
content_type,
size_bytes,
sha256,
object_key,
created,
)
except Exception:
await self._discard_object(object_key)
await self._discard_object(staged)
raise
stamp = _stamp(created)
return Attachment(
attachment = Attachment(
str(attachment_id),
str(chat_uuid),
str(owner_uuid),
@@ -441,6 +489,39 @@ class Store:
stamp,
stamp,
)
return QueuedUpload(
attachment,
dump_job(str(job_id), str(attachment_id), 1, stamp),
)
async def abandon_upload(self, attachment_id: str) -> None:
"""Drop a queued upload whose job never reached the broker."""
attachment_uuid = _as_uuid(attachment_id, 'Некорректный attachment_id')
staged: Optional[str] = None
async with self._pool.acquire() as conn:
async with conn.transaction():
row = await conn.fetchrow(
'''
SELECT staging_key
FROM attachments
WHERE id = $1 AND status = 'queued'
FOR UPDATE
''',
attachment_uuid,
)
if row is None:
return
staged = row['staging_key']
await conn.execute(
'DELETE FROM attachment_jobs WHERE attachment_id = $1',
attachment_uuid,
)
await conn.execute(
"DELETE FROM attachments WHERE id = $1 AND status = 'queued'",
attachment_uuid,
)
if staged:
await self._discard_object(staged)
async def attachment_index(self) -> List[AttachmentRef]:
"""Every attachment row. `in_use` means a message still points at it.
@@ -522,7 +603,7 @@ class Store:
row = await conn.fetchrow(
'''
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type,
a.size_bytes, a.sha256, a.status, a.created_at, a.updated_at
a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at
FROM attachments a
JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2
WHERE a.id = $1
@@ -530,6 +611,7 @@ class Store:
attachment_uuid,
user_uuid,
)
variants = () if row is None else await self._variants(conn, attachment_uuid)
if row is None:
return None
return Attachment(
@@ -543,22 +625,62 @@ class Store:
row['status'],
_stamp(row['created_at']),
_stamp(row['updated_at']),
variants,
row['error_code'],
)
async def read_original(self, attachment_id: str, user_id: str) -> Optional[Tuple[str, bytes]]:
async def _variants(self, conn: asyncpg.Connection, attachment_id: uuid.UUID) -> Tuple[Variant, ...]:
rows = await conn.fetch(
'''
SELECT name, content_type, size_bytes, width, height, sha256
FROM attachment_variants
WHERE attachment_id = $1 AND pipeline_version = $2
ORDER BY name
''',
attachment_id,
PIPELINE_VERSION,
)
return tuple(
Variant(
row['name'],
row['content_type'],
row['size_bytes'],
row['width'],
row['height'],
row['sha256'],
)
for row in rows
)
async def read_content(self, attachment_id: str, user_id: str, variant: str) -> Optional[Tuple[str, bytes]]:
attachment_uuid = _as_uuid(attachment_id, 'Некорректный attachment_id')
user_uuid = _as_uuid(user_id, 'Некорректный user_id')
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
'''
SELECT a.content_type, a.size_bytes, a.sha256, a.object_key
FROM attachments a
JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2
WHERE a.id = $1
''',
attachment_uuid,
user_uuid,
)
if variant == 'original':
row = await conn.fetchrow(
'''
SELECT a.content_type, a.size_bytes, a.sha256, a.object_key
FROM attachments a
JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2
WHERE a.id = $1
''',
attachment_uuid,
user_uuid,
)
else:
row = await conn.fetchrow(
'''
SELECT v.content_type, v.size_bytes, v.sha256, v.object_key
FROM attachment_variants v
JOIN attachments a ON a.id = v.attachment_id
JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2
WHERE v.attachment_id = $1 AND v.pipeline_version = $3 AND v.name = $4
''',
attachment_uuid,
user_uuid,
PIPELINE_VERSION,
variant,
)
if row is None:
return None
try:
@@ -635,12 +757,14 @@ class Store:
return await self._replay(conn, sender_uuid, path, key, request_hash)
if linked:
rows = await conn.fetch(
'SELECT id, chat_id FROM attachments WHERE id = ANY($1::uuid[])',
'SELECT id, chat_id, status FROM attachments WHERE id = ANY($1::uuid[])',
list(linked),
)
found = {row['id']: row['chat_id'] for row in rows}
if len(found) != len(linked) or any(found[item] != chat_uuid for item in linked):
found = {row['id']: row for row in rows}
if len(found) != len(linked) or any(found[item]['chat_id'] != chat_uuid for item in linked):
raise not_found('Вложение не найдено')
if any(found[item]['status'] == 'failed' for item in linked):
raise conflict('Нельзя прикрепить повреждённое вложение')
await conn.execute(
'''
INSERT INTO messages (id, chat_id, sender_id, text, created_at)