Реализовано хранилище вложений для лабораторной 4

This commit is contained in:
2026-11-02 23:40:07 +03:00
parent ec540a1a72
commit b99ad646e8
77 changed files with 2300 additions and 52 deletions
View File
+148
View File
@@ -0,0 +1,148 @@
import threading
import uuid
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from app.core.errors import ApiError
def now_utc() -> datetime:
return datetime.now(timezone.utc)
def iso_z(moment: datetime) -> str:
"""RFC 3339 UTC с Z и микросекундами: порядок (created_at, id) не теряет точность."""
return moment.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
def order_key(created_dt: datetime, row_id: str):
"""Контракт: порядок по (created_at, id), id сравнивается как значение UUID."""
return (created_dt, uuid.UUID(row_id).int)
@dataclass
class UserRow:
id: str
username: str
display_name: str
password_hash: str
created_at: str
@dataclass
class ChatRow:
id: str
title: str
member_ids: list
created_dt: datetime
created_at: str
@dataclass
class MessageRow:
id: str
chat_id: str
sender_id: str
text: str
created_dt: datetime
created_at: str
attachment_ids: list[str] = field(default_factory=list)
@dataclass
class AttachmentRow:
id: str
chat_id: str
owner_id: str
object_key: str
filename: str
content_type: str
size_bytes: int
sha256: str
status: str
created_at: str
updated_at: str
@dataclass
class SessionRow:
token: str
user_id: str
expires_at: datetime
class MemoryStorage:
"""Хранилище в памяти из скелета lab1. В lab2 его заменяет PgStorage."""
def __init__(self):
self._lock = threading.RLock()
self._users: dict[str, UserRow] = {}
self._by_username: dict[str, str] = {}
self._chats: dict[str, ChatRow] = {}
self._messages: dict[str, list[MessageRow]] = {}
self._sessions: dict[str, SessionRow] = {}
def ready(self) -> bool:
return True
def create_user(self, username: str, display_name: str, password_hash: str) -> UserRow:
with self._lock:
if username in self._by_username:
raise ApiError(409, 'Username is already taken')
row = UserRow(str(uuid.uuid4()), username, display_name, password_hash,
iso_z(now_utc()))
self._users[row.id] = row
self._by_username[username] = row.id
return row
def user_by_username(self, username: str) -> UserRow | None:
with self._lock:
uid = self._by_username.get(username)
return self._users.get(uid) if uid else None
def user(self, user_id: str) -> UserRow | None:
with self._lock:
return self._users.get(user_id)
def create_session(self, user_id: str, ttl_seconds: int) -> SessionRow:
from app.core.security import new_token
with self._lock:
row = SessionRow(new_token(), user_id, now_utc() + timedelta(seconds=ttl_seconds))
self._sessions[row.token] = row
return row
def session(self, token: str) -> SessionRow | None:
with self._lock:
row = self._sessions.get(token)
if row is None:
return None
if now_utc() >= row.expires_at:
del self._sessions[token]
return None
return row
def revoke(self, token: str) -> bool:
with self._lock:
return self._sessions.pop(token, None) is not None
def create_chat(self, title: str, member_ids: list, caller_id: str) -> ChatRow:
with self._lock:
if caller_id not in member_ids:
raise ApiError(400, 'Creator must be included in member_ids')
for mid in member_ids:
if mid not in self._users:
raise ApiError(400, 'Unknown member id')
moment = now_utc()
row = ChatRow(str(uuid.uuid4()), title, list(member_ids), moment, iso_z(moment))
self._chats[row.id] = row
self._messages[row.id] = []
return row
def chat(self, chat_id: str) -> ChatRow | None:
with self._lock:
return self._chats.get(chat_id)
def chats_of(self, user_id: str) -> list[ChatRow]:
with self._lock:
rows = [c for c in self._chats.values() if user_id in c.member_ids]
return sorted(rows, key=lambda c: order_key(c.created_dt, c.id))
+109
View File
@@ -0,0 +1,109 @@
import asyncio
import time
import boto3
from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError
from app.core.config import settings
from app.core.errors import ApiError
class S3ObjectStore:
"""Хранит байты в приватном S3 bucket, не в процессе API."""
def __init__(self):
self.bucket = settings.s3_bucket
self.client = boto3.client(
"s3",
endpoint_url=settings.s3_endpoint_url,
region_name=settings.s3_region,
aws_access_key_id=settings.resolved_s3_access_key_id(),
aws_secret_access_key=settings.resolved_s3_secret_access_key(),
config=Config(
connect_timeout=settings.s3_connect_timeout_seconds,
read_timeout=settings.s3_read_timeout_seconds,
max_pool_connections=16,
retries={"max_attempts": 2, "mode": "standard"},
s3={"addressing_style": "path"},
),
)
@staticmethod
def _unavailable():
return ApiError(503, "Object storage is unavailable")
def _ensure_bucket(self):
for attempt in range(30):
try:
self.client.head_bucket(Bucket=self.bucket)
return
except ClientError as exc:
code = str(exc.response.get("Error", {}).get("Code", ""))
if code not in {"404", "NoSuchBucket", "NotFound"}:
if code in {"403", "AccessDenied"} or attempt == 29:
raise self._unavailable() from None
else:
try:
self.client.create_bucket(Bucket=self.bucket)
except ClientError as create_exc:
create_code = str(create_exc.response.get("Error", {}).get("Code", ""))
if create_code not in {"BucketAlreadyOwnedByYou", "BucketAlreadyExists"}:
if attempt == 29:
raise self._unavailable() from None
else:
return
except (BotoCoreError, OSError, TimeoutError):
if attempt == 29:
raise self._unavailable() from None
time.sleep(0.5)
raise self._unavailable()
async def ensure_bucket(self):
await asyncio.to_thread(self._ensure_bucket)
def _head_bucket(self):
self.client.head_bucket(Bucket=self.bucket)
async def ready(self) -> bool:
try:
await asyncio.to_thread(self._head_bucket)
return True
except (ClientError, BotoCoreError, OSError, TimeoutError):
return False
def _put(self, key: str, data: bytes, content_type: str):
self.client.put_object(Bucket=self.bucket, Key=key, Body=data, ContentType=content_type)
async def put(self, key: str, data: bytes, content_type: str):
try:
await asyncio.to_thread(self._put, key, data, content_type)
except (ClientError, BotoCoreError, OSError, TimeoutError):
raise self._unavailable() from None
def _get(self, key: str) -> bytes:
result = self.client.get_object(Bucket=self.bucket, Key=key)
try:
return result["Body"].read(settings.max_upload_bytes + 1)
finally:
result["Body"].close()
async def get(self, key: str) -> bytes:
try:
data = await asyncio.to_thread(self._get, key)
if len(data) > settings.max_upload_bytes:
raise self._unavailable()
return data
except ApiError:
raise
except (ClientError, BotoCoreError, OSError, TimeoutError):
raise self._unavailable() from None
def _delete(self, key: str):
self.client.delete_object(Bucket=self.bucket, Key=key)
async def delete(self, key: str):
try:
await asyncio.to_thread(self._delete, key)
except (ClientError, BotoCoreError, OSError, TimeoutError):
raise self._unavailable() from None
+278
View File
@@ -0,0 +1,278 @@
import uuid
import asyncpg
from app.core.errors import ApiError
from app.repositories.memory import (
AttachmentRow, ChatRow, MessageRow, UserRow, iso_z,
)
def _user(row: asyncpg.Record | None) -> UserRow | None:
if row is None:
return None
return UserRow(
id=str(row['id']), username=row['username'], display_name=row['display_name'],
password_hash=row['password_hash'], created_at=iso_z(row['created_at']),
)
def _chat(row: asyncpg.Record) -> ChatRow:
moment = row['created_at']
return ChatRow(
id=str(row['id']), title=row['title'], member_ids=[str(x) for x in row['member_ids']],
created_dt=moment, created_at=iso_z(moment),
)
def _message(row: asyncpg.Record) -> MessageRow:
moment = row['created_at']
attachment_ids = row['attachment_ids'] if 'attachment_ids' in row else []
return MessageRow(
id=str(row['id']), chat_id=str(row['chat_id']), sender_id=str(row['sender_id']),
text=row['text'], created_dt=moment, created_at=iso_z(moment),
attachment_ids=[str(value) for value in (attachment_ids or [])],
)
def _attachment(row: asyncpg.Record) -> AttachmentRow:
return AttachmentRow(
id=str(row['id']), chat_id=str(row['chat_id']), owner_id=str(row['owner_id']),
object_key=row['object_key'], filename=row['filename'],
content_type=row['content_type'], size_bytes=row['size_bytes'],
sha256=row['sha256'], status=row['status'],
created_at=iso_z(row['created_at']), updated_at=iso_z(row['updated_at']),
)
_MESSAGE_SELECT = (
'SELECT m.*, COALESCE(array_agg(ma.attachment_id ORDER BY ma.position) '
"FILTER (WHERE ma.attachment_id IS NOT NULL), ARRAY[]::uuid[]) AS attachment_ids "
'FROM messages m LEFT JOIN message_attachments ma ON ma.message_id = m.id '
)
class PgStorage:
"""PostgreSQL — источник истины для метаданных; S3 хранит только байты."""
def __init__(self, pool: asyncpg.Pool, session_store, object_store):
self.pool = pool
self.session_store = session_store
self.object_store = object_store
async def ready(self) -> bool:
try:
async with self.pool.acquire() as connection:
database_ready = await connection.fetchval('SELECT 1') == 1
return (
database_ready
and await self.session_store.ready()
and await self.object_store.ready()
)
except (asyncpg.PostgresError, OSError, TimeoutError):
return False
async def create_user(self, username: str, display_name: str, password_hash: str) -> UserRow:
try:
async with self.pool.acquire() as connection:
row = await connection.fetchrow(
'INSERT INTO users (id, username, display_name, password_hash) '
'VALUES ($1, $2, $3, $4) RETURNING *',
uuid.uuid4(), username, display_name, password_hash,
)
except asyncpg.UniqueViolationError as exc:
if exc.constraint_name == 'users_username_key':
raise ApiError(409, 'Username is already taken') from None
raise
return _user(row)
async def user_by_username(self, username: str) -> UserRow | None:
async with self.pool.acquire() as connection:
return _user(await connection.fetchrow(
'SELECT * FROM users WHERE username = $1', username
))
async def user(self, user_id: str) -> UserRow | None:
async with self.pool.acquire() as connection:
return _user(await connection.fetchrow(
'SELECT * FROM users WHERE id = $1', uuid.UUID(user_id)
))
async def create_session(self, user_id: str, ttl_seconds: int):
return await self.session_store.create_session(user_id, ttl_seconds)
async def session(self, token: str):
return await self.session_store.session(token)
async def revoke(self, token: str) -> bool:
return await self.session_store.revoke(token)
async def create_chat(self, title: str, member_ids: list[str], caller_id: str) -> ChatRow:
if caller_id not in member_ids:
raise ApiError(400, 'Creator must be included in member_ids')
chat_id = uuid.uuid4()
try:
async with self.pool.acquire() as connection:
async with connection.transaction():
created_at = await connection.fetchval(
'INSERT INTO chats (id, title) VALUES ($1, $2) RETURNING created_at',
chat_id, title,
)
await connection.executemany(
'INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)',
[(chat_id, uuid.UUID(member_id)) for member_id in member_ids],
)
except asyncpg.ForeignKeyViolationError:
raise ApiError(400, 'Unknown member id') from None
return ChatRow(
id=str(chat_id), title=title, member_ids=list(member_ids),
created_dt=created_at, created_at=iso_z(created_at),
)
async def chat(self, chat_id: str) -> ChatRow | None:
async with self.pool.acquire() as connection:
row = await connection.fetchrow(
'SELECT c.id, c.title, c.created_at, '
'array_agg(cm.user_id ORDER BY cm.user_id) AS member_ids '
'FROM chats c JOIN chat_members cm ON cm.chat_id = c.id '
'WHERE c.id = $1 GROUP BY c.id', uuid.UUID(chat_id),
)
return _chat(row) if row else None
async def chats_of(self, user_id: str) -> list[ChatRow]:
async with self.pool.acquire() as connection:
rows = await connection.fetch(
'SELECT c.id, c.title, c.created_at, '
'array_agg(cm_all.user_id ORDER BY cm_all.user_id) AS member_ids '
'FROM chats c '
'JOIN chat_members mine ON mine.chat_id = c.id '
'JOIN chat_members cm_all ON cm_all.chat_id = c.id '
'WHERE mine.user_id = $1 '
'GROUP BY c.id ORDER BY c.created_at, c.id', uuid.UUID(user_id),
)
return [_chat(row) for row in rows]
async def create_attachment(
self, attachment_id: str, chat_id: str, owner_id: str, object_key: str,
filename: str, content_type: str, size_bytes: int, sha256: str,
) -> AttachmentRow:
async with self.pool.acquire() as connection:
row = await connection.fetchrow(
'INSERT INTO attachments '
'(id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256) '
'VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING *',
uuid.UUID(attachment_id), uuid.UUID(chat_id), uuid.UUID(owner_id),
object_key, filename, content_type, size_bytes, sha256,
)
return _attachment(row)
async def attachment_for_member(self, attachment_id: str, user_id: str) -> AttachmentRow | None:
try:
attachment_uuid = uuid.UUID(attachment_id)
except ValueError:
raise ApiError(400, 'attachment_id must be a UUID') from None
async with self.pool.acquire() as connection:
row = await connection.fetchrow(
'SELECT a.* FROM attachments a '
'JOIN chat_members cm ON cm.chat_id = a.chat_id '
'WHERE a.id = $1 AND cm.user_id = $2',
attachment_uuid, uuid.UUID(user_id),
)
return _attachment(row) if row else None
async def add_idempotent_message(
self, chat_id: str, sender_id: str, text: str, attachment_ids: list[str],
idempotency_key: str, request_hash: bytes,
) -> MessageRow:
"""Создать сообщение, его вложения и ключ повтора одной транзакцией."""
chat_uuid = uuid.UUID(chat_id)
sender_uuid = uuid.UUID(sender_id)
attachment_uuids = [uuid.UUID(value) for value in attachment_ids]
lock_scope = f'{sender_uuid}:POST:/api/v1/chats/{chat_uuid}/messages:{idempotency_key}'
async with self.pool.acquire() as connection:
async with connection.transaction():
await connection.fetchval(
'SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', lock_scope,
)
existing = await connection.fetchrow(
'SELECT k.request_hash, m.id FROM message_idempotency k '
'JOIN messages m ON m.id = k.message_id '
'WHERE k.user_id = $1 AND k.chat_id = $2 AND k.idempotency_key = $3 '
"AND k.created_at > now() - interval '24 hours'",
sender_uuid, chat_uuid, idempotency_key,
)
if existing is not None:
if bytes(existing['request_hash']) != request_hash:
raise ApiError(409, 'Idempotency-Key was already used with another request')
row = await connection.fetchrow(
_MESSAGE_SELECT + 'WHERE m.id = $1 GROUP BY m.id', existing['id'],
)
return _message(row)
if attachment_uuids:
available = await connection.fetch(
"SELECT id FROM attachments WHERE chat_id = $1 AND id = ANY($2::uuid[]) "
"AND status = 'ready' FOR SHARE",
chat_uuid, attachment_uuids,
)
if len(available) != len(attachment_uuids):
raise ApiError(404, 'Attachment is not available in this chat')
await connection.execute(
'DELETE FROM message_idempotency '
'WHERE user_id = $1 AND chat_id = $2 AND idempotency_key = $3',
sender_uuid, chat_uuid, idempotency_key,
)
await connection.execute(
"DELETE FROM message_idempotency WHERE ctid IN ("
'SELECT ctid FROM message_idempotency '
"WHERE created_at <= now() - interval '24 hours' "
'ORDER BY created_at LIMIT 100)'
)
message_id = uuid.uuid4()
await connection.execute(
'INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1, $2, $3, $4)',
message_id, chat_uuid, sender_uuid, text,
)
if attachment_uuids:
await connection.executemany(
'INSERT INTO message_attachments '
'(message_id, attachment_id, chat_id, position) VALUES ($1, $2, $3, $4)',
[(message_id, attachment_id, chat_uuid, index)
for index, attachment_id in enumerate(attachment_uuids)],
)
row = await connection.fetchrow(
_MESSAGE_SELECT + 'WHERE m.id = $1 GROUP BY m.id', message_id,
)
await connection.execute(
'INSERT INTO message_idempotency '
'(user_id, chat_id, idempotency_key, request_hash, message_id) '
'VALUES ($1, $2, $3, $4, $5)',
sender_uuid, chat_uuid, idempotency_key, request_hash, message_id,
)
return _message(row)
async def messages_page(self, chat_id: str, cursor_key, limit: int):
"""Прочитать ограниченную keyset-страницу вместе с ID прикреплённых файлов."""
chat_uuid = uuid.UUID(chat_id)
base = (
'SELECT m.*, COALESCE(array_agg(ma.attachment_id ORDER BY ma.position) '
"FILTER (WHERE ma.attachment_id IS NOT NULL), ARRAY[]::uuid[]) AS attachment_ids "
'FROM messages m LEFT JOIN message_attachments ma ON ma.message_id = m.id '
'WHERE m.chat_id = $1 '
)
async with self.pool.acquire() as connection:
if cursor_key is None:
rows = await connection.fetch(
base + 'GROUP BY m.id ORDER BY m.created_at, m.id LIMIT $2',
chat_uuid, limit + 1,
)
else:
created_at, id_value = cursor_key
rows = await connection.fetch(
base + 'AND (m.created_at, m.id) > ($2, $3) '
'GROUP BY m.id ORDER BY m.created_at, m.id LIMIT $4',
chat_uuid, created_at, uuid.UUID(int=id_value), limit + 1,
)
has_more = len(rows) > limit
return [_message(row) for row in rows[:limit]], has_more
+66
View File
@@ -0,0 +1,66 @@
import hashlib
import time
from datetime import datetime, timedelta, timezone
from redis.asyncio import Redis
from redis.exceptions import RedisError
from app.core.errors import ApiError
from app.core.security import new_token
from app.repositories.memory import SessionRow, now_utc
class RedisSessionStore:
"""Redis — источник истины для сессий; PXAT сохраняет исходный срок истечения после перезапуска."""
def __init__(self, client: Redis):
self.client = client
@staticmethod
def _key(token: str) -> str:
digest = hashlib.sha256(token.encode('utf-8')).hexdigest()
return 'session:' + digest
async def ready(self) -> bool:
try:
return bool(await self.client.ping())
except (RedisError, OSError, TimeoutError):
return False
async def create_session(self, user_id: str, ttl_seconds: int) -> SessionRow:
token = new_token()
current = now_utc()
expires_at = current.replace(microsecond=(current.microsecond // 1000) * 1000) + timedelta(seconds=ttl_seconds)
expires_ms = int(expires_at.timestamp() * 1000)
try:
await self.client.set(
self._key(token), f'{user_id}|{expires_ms}', pxat=expires_ms
)
except RedisError:
raise ApiError(503, 'Session storage is unavailable') from None
return SessionRow(token=token, user_id=user_id, expires_at=expires_at)
async def session(self, token: str) -> SessionRow | None:
try:
value = await self.client.get(self._key(token))
except RedisError:
raise ApiError(503, 'Session storage is unavailable') from None
if value is None:
return None
try:
user_id, expires_ms_text = value.split('|', 1)
expires_ms = int(expires_ms_text)
if expires_ms <= int(time.time() * 1000):
await self.client.delete(self._key(token))
return None
expires_at = datetime.fromtimestamp(expires_ms / 1000, timezone.utc)
return SessionRow(token=token, user_id=user_id, expires_at=expires_at)
except (ValueError, OverflowError):
await self.client.delete(self._key(token))
return None
async def revoke(self, token: str) -> bool:
try:
return bool(await self.client.delete(self._key(token)))
except RedisError:
raise ApiError(503, 'Session storage is unavailable') from None