level 5 track 2
This commit is contained in:
+82
-5
@@ -7,7 +7,7 @@ import threading
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import BinaryIO, Dict, List, Optional, Sequence, Set, Tuple
|
||||
from typing import BinaryIO, Dict, List, Optional, Sequence, Tuple
|
||||
|
||||
import asyncpg
|
||||
|
||||
@@ -101,6 +101,17 @@ class Attachment:
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AttachmentRef:
|
||||
"""One metadata row as the reconciler sees it. Not an API response."""
|
||||
|
||||
id: str
|
||||
object_key: str
|
||||
created_at: datetime
|
||||
in_use: bool
|
||||
sha256: str
|
||||
|
||||
|
||||
def _token_key(token: str) -> str:
|
||||
return hashlib.sha256(token.encode('utf-8')).hexdigest()
|
||||
|
||||
@@ -428,11 +439,77 @@ class Store:
|
||||
stamp,
|
||||
)
|
||||
|
||||
async def listed_object_keys(self) -> Set[str]:
|
||||
"""Object keys that have a metadata row. Used by the reconciler, not by the HTTP API."""
|
||||
async def attachment_index(self) -> List[AttachmentRef]:
|
||||
"""Every attachment row. `in_use` means a message still points at it.
|
||||
|
||||
The reconciler uses this instead of the HTTP API. A row linked from
|
||||
message_attachments must survive even when the object is gone: the
|
||||
foreign key has no ON DELETE CASCADE, and the message would lose its file.
|
||||
"""
|
||||
async with self._pool.acquire() as conn:
|
||||
rows = await conn.fetch('SELECT object_key FROM attachments')
|
||||
return {row['object_key'] for row in rows}
|
||||
rows = await conn.fetch(
|
||||
'''
|
||||
SELECT a.id, a.object_key, a.created_at, a.sha256,
|
||||
EXISTS (
|
||||
SELECT 1 FROM message_attachments m
|
||||
WHERE m.attachment_id = a.id
|
||||
) AS in_use
|
||||
FROM attachments a
|
||||
'''
|
||||
)
|
||||
return [
|
||||
AttachmentRef(
|
||||
str(row['id']),
|
||||
row['object_key'],
|
||||
row['created_at'],
|
||||
bool(row['in_use']),
|
||||
row['sha256'],
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
|
||||
async def object_key_referenced(self, object_key: str) -> bool:
|
||||
"""True when a metadata row owns this key. Checked again immediately before delete."""
|
||||
async with self._pool.acquire() as conn:
|
||||
found = await conn.fetchval(
|
||||
'SELECT 1 FROM attachments WHERE object_key = $1',
|
||||
object_key,
|
||||
)
|
||||
return found is not None
|
||||
|
||||
async def delete_attachment_if_unlinked(self, attachment_id: str, created_before: datetime) -> bool:
|
||||
"""Delete a stale row that no message references. A link or a young row keeps it.
|
||||
|
||||
`created_before` is the scan clock minus grace, so the row deleted here is the
|
||||
same row the scan classified as stale. The originals/ predicate matches the
|
||||
prefix the reconciler is allowed to own.
|
||||
"""
|
||||
async with self._pool.acquire() as conn:
|
||||
result = await conn.execute(
|
||||
'''
|
||||
DELETE FROM attachments
|
||||
WHERE id = $1
|
||||
AND object_key LIKE 'originals/%'
|
||||
AND created_at <= $2
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM message_attachments WHERE attachment_id = $1
|
||||
)
|
||||
''',
|
||||
_as_uuid(attachment_id, 'Некорректный attachment_id'),
|
||||
created_before,
|
||||
)
|
||||
return result == 'DELETE 1'
|
||||
|
||||
async def rewind_attachment_created_at(self, attachment_id: str, created_at: datetime) -> None:
|
||||
"""Move one row's clock back. The track-2 experiment uses this to age a fixture."""
|
||||
async with self._pool.acquire() as conn:
|
||||
result = await conn.execute(
|
||||
'UPDATE attachments SET created_at = $2 WHERE id = $1',
|
||||
_as_uuid(attachment_id, 'Некорректный attachment_id'),
|
||||
created_at,
|
||||
)
|
||||
if result != 'UPDATE 1':
|
||||
raise RuntimeError('attachment row missing')
|
||||
|
||||
async def find_attachment(self, attachment_id: str, user_id: str) -> Optional[Attachment]:
|
||||
"""Metadata for a chat member. Missing and foreign attachments are both absent."""
|
||||
|
||||
Reference in New Issue
Block a user