create skeleton for lab 4

This commit is contained in:
2026-11-04 21:27:54 +03:00
parent ec540a1a72
commit 8503c1b6cd
133 changed files with 10856 additions and 40 deletions
+1
View File
@@ -0,0 +1 @@
"""Доступ к данным PostgreSQL и Redis."""
+70
View File
@@ -0,0 +1,70 @@
"""SQL-запросы метаданных и журнала; commit выполняется в domain."""
from datetime import timedelta
from uuid import UUID
from sqlalchemy import delete, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.attachment import Attachment, MessageAttachment, UploadIntent
async def create_attachment(session: AsyncSession, **values) -> Attachment:
record = Attachment(**values)
session.add(record)
await session.flush()
return record
async def get_attachment(session: AsyncSession, attachment_id: UUID) -> Attachment | None:
return await session.get(Attachment, attachment_id)
async def get_by_key(session: AsyncSession, key: str) -> Attachment | None:
return await session.scalar(select(Attachment).where(Attachment.object_key == key))
async def get_for_chat(session: AsyncSession, chat_id: UUID, attachment_ids: list[UUID]) -> list[Attachment]:
records = []
if attachment_ids:
records = list(await session.scalars(select(Attachment).where(
Attachment.id.in_(attachment_ids), Attachment.chat_id == chat_id,
)))
return records
async def bind_attachments(session: AsyncSession, message_id: UUID, attachment_ids: list[UUID]) -> None:
session.add_all(MessageAttachment(message_id=message_id, attachment_id=id, position=position)
for position, id in enumerate(attachment_ids))
await session.flush()
async def message_attachment_ids(session: AsyncSession, message_ids: list[UUID]) -> dict[UUID, list[UUID]]:
result: dict[UUID, list[UUID]] = {id: [] for id in message_ids}
if not message_ids:
return result
rows = await session.execute(select(MessageAttachment).where(
MessageAttachment.message_id.in_(message_ids)).order_by(MessageAttachment.position))
for link in rows.scalars():
result[link.message_id].append(link.attachment_id)
return result
async def reserve_upload(session: AsyncSession, id: UUID, key: str) -> None:
session.add(UploadIntent(id=id, object_key=key))
await session.flush()
async def lock_upload(session: AsyncSession, id: UUID) -> UploadIntent | None:
return await session.scalar(select(UploadIntent).where(UploadIntent.id == id).with_for_update())
async def finish_upload(session: AsyncSession, id: UUID) -> None:
await session.execute(delete(UploadIntent).where(UploadIntent.id == id))
async def stale_uploads(session: AsyncSession, grace_seconds: int, limit: int) -> list[UploadIntent]:
result = await session.scalars(select(UploadIntent).where(
UploadIntent.created_at < func.clock_timestamp() - timedelta(seconds=grace_seconds),
).order_by(UploadIntent.created_at).limit(limit).with_for_update(skip_locked=True))
return list(result)
+71
View File
@@ -0,0 +1,71 @@
from collections.abc import Sequence
from uuid import UUID
from sqlalchemy import exists, select, tuple_
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.chat import Chat
from app.models.chat_member import ChatMember
from app.storage.types import Position
async def create_chat(
session: AsyncSession,
*,
title: str,
member_ids: Sequence[UUID],
) -> Chat:
"""Добавляет чат вместе с участниками."""
chat = Chat(
title=title,
members=[ChatMember(user_id=user_id) for user_id in member_ids],
)
session.add(chat)
await session.flush()
return chat
async def get_chat_for_member(
session: AsyncSession,
chat_id: UUID,
user_id: UUID,
) -> Chat | None:
"""Возвращает чат, если пользователь в нём состоит, иначе None."""
stmt = (
select(Chat)
.join(ChatMember, ChatMember.chat_id == Chat.id)
.where(Chat.id == chat_id, ChatMember.user_id == user_id)
)
result = await session.execute(stmt)
chat = result.scalar_one_or_none()
return chat
async def is_chat_member(session: AsyncSession, chat_id: UUID, user_id: UUID) -> bool:
"""Возвращает True, если пользователь состоит в чате; одна проверка по PK."""
stmt = select(
exists().where(ChatMember.chat_id == chat_id, ChatMember.user_id == user_id)
)
result = await session.execute(stmt)
is_member = bool(result.scalar_one())
return is_member
async def list_chats_for_user(
session: AsyncSession,
user_id: UUID,
after: Position | None,
limit: int,
) -> list[Chat]:
"""Возвращает чаты пользователя по (created_at, id) строго после позиции after."""
stmt = (
select(Chat)
.join(ChatMember, ChatMember.chat_id == Chat.id)
.where(ChatMember.user_id == user_id)
)
if after is not None:
stmt = stmt.where(tuple_(Chat.created_at, Chat.id) > tuple_(*after))
stmt = stmt.order_by(Chat.created_at, Chat.id).limit(limit)
result = await session.execute(stmt)
chats = list(result.scalars().all())
return chats
+15
View File
@@ -0,0 +1,15 @@
"""Простые проверки соединения с общими хранилищами."""
from redis.asyncio import Redis
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncEngine
async def check_database(engine: AsyncEngine) -> bool:
async with engine.connect() as connection:
await connection.execute(text('SELECT 1'))
return True
async def check_redis(client: Redis) -> bool:
return bool(await client.ping())
+63
View File
@@ -0,0 +1,63 @@
"""Хранение и блокировка ключей в PostgreSQL."""
from datetime import timedelta
import hashlib
import json
from uuid import UUID
from sqlalchemy import BigInteger, func, literal, select, tuple_
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.idempotency_key import IdempotencyKey
Scope = tuple[UUID, str, str, str]
async def lock_key(session: AsyncSession, scope: Scope) -> None:
"""Сериализует один ключ до конца транзакции."""
raw = json.dumps([str(scope[0]), *scope[1:]]).encode()
lock_id = int.from_bytes(hashlib.sha256(raw).digest()[:8], signed=True)
await session.execute(
select(func.pg_advisory_xact_lock(literal(lock_id, type_=BigInteger)))
)
async def get_active_key(
session: AsyncSession, scope: Scope, ttl_seconds: int
) -> IdempotencyKey | None:
"""Читает результат, пока срок ключа не истёк."""
stmt = select(IdempotencyKey).where(
tuple_(
IdempotencyKey.user_id,
IdempotencyKey.method,
IdempotencyKey.path,
IdempotencyKey.key,
) == tuple_(*scope),
IdempotencyKey.created_at
> func.clock_timestamp() - timedelta(seconds=ttl_seconds),
)
return await session.scalar(stmt)
async def save_result(
session: AsyncSession, scope: Scope, request_hash: str, message_id: UUID
) -> None:
"""Сохраняет новый результат или заменяет истёкший."""
stmt = insert(IdempotencyKey).values(
user_id=scope[0], method=scope[1], path=scope[2], key=scope[3],
request_hash=request_hash, message_id=message_id,
)
await session.execute(
stmt.on_conflict_do_update(
index_elements=[
IdempotencyKey.user_id, IdempotencyKey.method,
IdempotencyKey.path, IdempotencyKey.key,
],
set_={
"request_hash": request_hash,
"message_id": message_id,
"created_at": func.clock_timestamp(),
},
)
)
+62
View File
@@ -0,0 +1,62 @@
from uuid import UUID
from sqlalchemy import select, tuple_
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.counter import Counter
from app.models.message import Message
from app.storage.types import Position
MESSAGES_COUNTER = "messages"
async def get_message(session: AsyncSession, message_id: UUID) -> Message | None:
return await session.get(Message, message_id)
async def create_message(
session: AsyncSession,
*,
chat_id: UUID,
sender_id: UUID,
text: str,
) -> Message:
"""Добавляет сообщение; id и created_at назначает сервер."""
message = Message(chat_id=chat_id, sender_id=sender_id, text=text)
session.add(message)
await session.flush()
return message
async def list_messages(
session: AsyncSession,
chat_id: UUID,
after: Position | None,
limit: int,
) -> list[Message]:
"""Возвращает сообщения чата по (created_at, id) строго после позиции after."""
stmt = select(Message).where(Message.chat_id == chat_id)
if after is not None:
stmt = stmt.where(tuple_(Message.created_at, Message.id) > tuple_(*after))
stmt = stmt.order_by(Message.created_at, Message.id).limit(limit)
result = await session.execute(stmt)
messages = list(result.scalars().all())
return messages
async def reserve_message_slot(session: AsyncSession, max_messages: int) -> bool:
"""Атомарно увеличивает счётчик сообщений, если лимит не исчерпан."""
stmt = (
insert(Counter)
.values(name=MESSAGES_COUNTER, value=1)
.on_conflict_do_update(
index_elements=[Counter.name],
set_={"value": Counter.value + 1},
where=Counter.value < max_messages,
)
.returning(Counter.value)
)
result = await session.execute(stmt)
is_reserved = result.scalar_one_or_none() is not None
return is_reserved
+151
View File
@@ -0,0 +1,151 @@
"""MinIO SDK выполняется в потоках; ресурсы живут до конца операции."""
import asyncio
from collections.abc import Callable
from contextlib import suppress
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import TypeVar
import time
from urllib.parse import urlsplit
from anyio import CancelScope
from minio import Minio
import urllib3
from app.core.s3 import S3Settings
T = TypeVar("T")
async def run_sync(operation: Callable[..., T], *args, discard_result=None, **kwargs) -> T:
"""При отмене дождаться потока: иначе PUT может догнать компенсацию удаления."""
task = asyncio.create_task(asyncio.to_thread(operation, *args, **kwargs))
try:
result = await asyncio.shield(task)
except asyncio.CancelledError:
with CancelScope(shield=True):
await settle_cancelled_call(task, discard_result)
raise
return result
async def settle_cancelled_call(task: asyncio.Task, discard_result: Callable | None) -> None:
"""wait не переносит исключение SDK; повторная отмена не прерывает компенсацию."""
while not task.done():
with suppress(asyncio.CancelledError):
await asyncio.wait([task])
completed = not task.cancelled() and task.exception() is None
if completed and discard_result is not None:
discard_result(task.result())
@dataclass(frozen=True)
class ObjectInfo:
key: str
size_bytes: int
content_type: str
last_modified: datetime
def close_response(response) -> None:
response.close()
response.release_conn()
class ObjectStream:
"""Закрывается даже если StreamingResponse не успел начать итерацию."""
def __init__(self, storage, response):
self.storage = storage
self.response = response
self.deadline = time.monotonic() + storage.settings.download_timeout_seconds
self.closed = False
def __aiter__(self):
return self
async def __anext__(self):
if self.closed:
raise StopAsyncIteration
try:
remaining = self.deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError
async with asyncio.timeout(remaining):
chunk = await self.storage._call(lambda: self.response.read(self.storage.settings.chunk_bytes))
if not chunk:
await self.aclose()
raise StopAsyncIteration
except BaseException:
await self.aclose()
raise
return chunk
async def aclose(self):
if not self.closed:
self.closed = True
close_response(self.response)
class MinioStorage:
def __init__(self, settings: S3Settings) -> None:
self.settings = settings
# Клиент создаётся в event loop один раз, не конкурентно в worker threads.
url = urlsplit(settings.endpoint)
self._http = urllib3.PoolManager(
timeout=urllib3.Timeout(connect=settings.connect_timeout_seconds, read=settings.read_timeout_seconds),
retries=urllib3.Retry(total=0), maxsize=32,
)
self._health_http = urllib3.PoolManager(
timeout=urllib3.Timeout(connect=0.25, read=0.5), retries=urllib3.Retry(total=0),
)
self._client = Minio(
url.netloc, secure=url.scheme == "https", region=settings.region,
access_key=settings.access_key_id_file.read_text().strip(),
secret_key=settings.secret_access_key_file.read_text().strip(), http_client=self._http,
)
async def _call(self, operation: Callable, *, discard_result=None):
return await run_sync(operation, discard_result=discard_result)
async def put_file(self, key: str, path: Path, *, size_bytes: int, content_type: str, sha256: str) -> None:
def put():
with path.open("rb") as source:
# Один PUT: размер части равен максимальному разрешённому файлу.
self._client.put_object(
self.settings.bucket, key, source, size_bytes,
content_type=content_type, metadata={"sha256": sha256},
part_size=10_485_760, num_parallel_uploads=1,
)
await self._call(put)
async def open_object(self, key: str) -> ObjectStream:
response = await self._call(
lambda: self._client.get_object(self.settings.bucket, key), discard_result=close_response,
)
return ObjectStream(self, response)
async def stat_object(self, key: str) -> ObjectInfo:
def stat():
info = self._client.stat_object(self.settings.bucket, key)
return ObjectInfo(key, info.size, info.content_type, info.last_modified)
return await self._call(stat)
async def delete_object(self, key: str) -> None:
await self._call(lambda: self._client.remove_object(self.settings.bucket, key))
async def check_available(self) -> bool:
status = await self._call(lambda: self._health_http.request(
"GET", self.settings.endpoint.rstrip("/") + "/minio/health/ready",
).status)
return status == 200
async def aclose(self) -> None:
self._http.clear()
self._health_http.clear()
def create_s3_storage(settings: S3Settings) -> MinioStorage:
return MinioStorage(settings)
+38
View File
@@ -0,0 +1,38 @@
from datetime import datetime
from uuid import UUID
from redis.asyncio import Redis
SESSION_KEY_PREFIX = "session:"
def session_key(token_hash: str) -> str:
"""Возвращает ключ Redis для хеша токена."""
return f"{SESSION_KEY_PREFIX}{token_hash}"
async def create_session(
redis: Redis,
*,
token_hash: str,
user_id: UUID,
expires_at: datetime,
) -> None:
"""Добавляет сессию с абсолютным временем истечения."""
await redis.set(session_key(token_hash), str(user_id), pxat=expires_at)
async def get_session_user_id(redis: Redis, token_hash: str) -> UUID | None:
"""Возвращает id владельца действующей сессии или None."""
raw_user_id = await redis.get(session_key(token_hash))
if isinstance(raw_user_id, bytes):
raw_user_id = raw_user_id.decode()
user_id = UUID(raw_user_id) if raw_user_id else None
return user_id
async def delete_session(redis: Redis, token_hash: str) -> bool:
"""Удаляет сессию; возвращает True, если она существовала."""
deleted_count = await redis.delete(session_key(token_hash))
is_deleted = deleted_count > 0
return is_deleted
+6
View File
@@ -0,0 +1,6 @@
"""Общие типы слоя хранения."""
from datetime import datetime
from uuid import UUID
Position = tuple[datetime, UUID]
+47
View File
@@ -0,0 +1,47 @@
from collections.abc import Collection
from uuid import UUID
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.user import User
async def create_user(
session: AsyncSession,
*,
username: str,
display_name: str,
password_hash: str,
) -> User:
"""Добавляет пользователя; занятый username даёт IntegrityError при flush."""
user = User(
username=username, display_name=display_name, password_hash=password_hash
)
session.add(user)
await session.flush()
return user
async def get_user_by_id(session: AsyncSession, user_id: UUID) -> User | None:
"""Возвращает пользователя по id или None."""
user = await session.get(User, user_id)
return user
async def get_user_by_username(session: AsyncSession, username: str) -> User | None:
"""Возвращает пользователя по username или None."""
stmt = select(User).where(User.username == username)
result = await session.execute(stmt)
user = result.scalar_one_or_none()
return user
async def get_existing_user_ids(
session: AsyncSession, user_ids: Collection[UUID]
) -> set[UUID]:
"""Возвращает те из user_ids, что существуют, одним запросом."""
stmt = select(User.id).where(User.id.in_(user_ids))
result = await session.execute(stmt)
existing_ids = set(result.scalars().all())
return existing_ids