Перенести реализацию лабораторной 5

This commit is contained in:
2026-11-17 19:52:39 +03:00
parent 470d9d6f1e
commit 58f3d4c457
72 changed files with 4753 additions and 0 deletions
+10
View File
@@ -0,0 +1,10 @@
from .attachments import AttachmentRepository
from .chats import ChatRepository
from .messages import MessageRepository
from .users import UserRepository
from .jobs import JobRepository, OutboxRepository
__all__ = [
'AttachmentRepository', 'ChatRepository', 'JobRepository', 'MessageRepository',
'OutboxRepository', 'UserRepository',
]
+173
View File
@@ -0,0 +1,173 @@
from __future__ import annotations
from datetime import datetime
from uuid import UUID, uuid4
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from ..domain.models import Attachment, AttachmentVariant
from ..models.attachment import AttachmentRow, AttachmentVariantRow
from ..models.chat import ChatMemberRow, ChatRow
from ..models.job import AttachmentJobRow, OutboxEventRow
def job_payload(job_id: UUID, attachment_id: UUID, pipeline_version: int, attempt: int, now: datetime) -> dict:
return {
'schema_version': 1,
'job_id': str(job_id),
'type': 'attachment.process.v1',
'attachment_id': str(attachment_id),
'pipeline_version': pipeline_version,
'attempt': attempt,
'created_at': now.isoformat().replace('+00:00', 'Z'),
}
class AttachmentRepository:
def __init__(self, sessions: async_sessionmaker[AsyncSession]) -> None:
self._sessions = sessions
@staticmethod
def _variant(row: AttachmentVariantRow) -> AttachmentVariant:
return AttachmentVariant(
name=row.name,
object_key=row.object_key,
content_type=row.content_type,
size_bytes=row.size_bytes,
width=row.width,
height=row.height,
sha256=row.sha256,
)
@classmethod
def _to_domain(
cls, row: AttachmentRow, variants: tuple[AttachmentVariantRow, ...] = ()
) -> Attachment:
return Attachment(
id=row.id,
chat_id=row.chat_id,
owner_id=row.owner_id,
filename=row.filename,
original_key=row.original_key,
staging_key=row.staging_key,
pipeline_version=row.pipeline_version,
content_type=row.content_type,
size_bytes=row.size_bytes,
sha256=row.sha256,
width=row.width,
height=row.height,
status=row.status,
error_code=row.error_code,
created_at=row.created_at,
updated_at=row.updated_at,
variants=tuple(cls._variant(item) for item in variants),
)
async def chat_exists_for_member(self, chat_id: UUID, user_id: UUID) -> bool:
async with self._sessions() as session:
found = await session.scalar(
select(ChatRow.id)
.join(ChatMemberRow, ChatMemberRow.chat_id == ChatRow.id)
.where(ChatRow.id == chat_id, ChatMemberRow.user_id == user_id)
)
return found is not None
async def create_queued(
self,
*,
attachment_id: UUID,
job_id: UUID,
chat_id: UUID,
owner_id: UUID,
filename: str,
staging_key: str,
content_type: str,
size_bytes: int,
sha256: str,
width: int,
height: int,
max_attempts: int,
now: datetime,
) -> Attachment:
row = AttachmentRow(
id=attachment_id,
chat_id=chat_id,
owner_id=owner_id,
filename=filename,
original_key=None,
staging_key=staging_key,
pipeline_version=1,
content_type=content_type,
size_bytes=size_bytes,
sha256=sha256,
width=width,
height=height,
status='queued',
error_code=None,
created_at=now,
updated_at=now,
)
job = AttachmentJobRow(
id=job_id,
attachment_id=attachment_id,
pipeline_version=1,
state='queued',
attempt=1,
max_attempts=max_attempts,
next_attempt_at=now,
lease_owner=None,
lease_until=None,
last_error_code=None,
replay_count=0,
created_at=now,
updated_at=now,
)
outbox = OutboxEventRow(
id=uuid4(),
event_type='attachment.process.v1',
job_id=job_id,
payload=job_payload(job_id, attachment_id, 1, 1, now),
available_at=now,
published_at=None,
claim_owner=None,
claim_until=None,
publish_attempts=0,
last_error_code=None,
created_at=now,
updated_at=now,
)
async with self._sessions() as session:
async with session.begin():
session.add_all((row, job, outbox))
await session.flush()
return self._to_domain(row)
async def _variants(
self, session: AsyncSession, attachment_id: UUID, pipeline_version: int
) -> tuple[AttachmentVariantRow, ...]:
rows = await session.scalars(
select(AttachmentVariantRow)
.where(
AttachmentVariantRow.attachment_id == attachment_id,
AttachmentVariantRow.pipeline_version == pipeline_version,
)
.order_by(AttachmentVariantRow.name)
)
return tuple(rows)
async def get_for_member(self, attachment_id: UUID, user_id: UUID) -> Attachment | None:
async with self._sessions() as session:
row = await session.scalar(
select(AttachmentRow)
.join(ChatMemberRow, ChatMemberRow.chat_id == AttachmentRow.chat_id)
.where(
AttachmentRow.id == attachment_id,
ChatMemberRow.user_id == user_id,
)
)
if row is None:
return None
return self._to_domain(
row, await self._variants(session, row.id, row.pipeline_version)
)
+69
View File
@@ -0,0 +1,69 @@
from __future__ import annotations
from datetime import datetime
from typing import Sequence
from uuid import UUID
from sqlalchemy import select, tuple_
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from ..domain.errors import Invalid
from ..domain.models import Chat, Keyset
from ..models.chat import ChatMemberRow, ChatRow
from ..models.user import UserRow
class ChatRepository:
def __init__(self, sessions: async_sessionmaker[AsyncSession]) -> None:
self._sessions = sessions
@staticmethod
def _to_domain(row: ChatRow, member_ids: Sequence[UUID]) -> Chat:
return Chat(id=row.id, title=row.title, member_ids=tuple(member_ids), created_at=row.created_at)
@staticmethod
async def _members(session: AsyncSession, chat_id: UUID) -> tuple[UUID, ...]:
result = await session.scalars(
select(ChatMemberRow.user_id)
.where(ChatMemberRow.chat_id == chat_id)
.order_by(ChatMemberRow.user_id)
)
return tuple(result)
async def create(self, chat_id: UUID, title: str, member_ids: Sequence[UUID], created_at: datetime) -> Chat:
async with self._sessions() as session:
async with session.begin():
found = set(await session.scalars(select(UserRow.id).where(UserRow.id.in_(member_ids))))
if len(found) != len(member_ids):
raise Invalid(f'member_ids содержит неизвестных участников: {len(member_ids) - len(found)}')
row = ChatRow(id=chat_id, title=title, created_at=created_at)
session.add(row)
await session.flush()
session.add_all(ChatMemberRow(chat_id=chat_id, user_id=user_id) for user_id in member_ids)
await session.flush()
return self._to_domain(row, member_ids)
async def get_for_member(self, chat_id: UUID, user_id: UUID) -> Chat | None:
async with self._sessions() as session:
row = await session.scalar(
select(ChatRow)
.join(ChatMemberRow, ChatMemberRow.chat_id == ChatRow.id)
.where(ChatRow.id == chat_id, ChatMemberRow.user_id == user_id)
)
if row is None:
return None
return self._to_domain(row, await self._members(session, row.id))
async def page_for_member(self, user_id: UUID, after: Keyset | None, limit: int) -> list[Chat]:
async with self._sessions() as session:
query = (
select(ChatRow)
.join(ChatMemberRow, ChatMemberRow.chat_id == ChatRow.id)
.where(ChatMemberRow.user_id == user_id)
.order_by(ChatRow.created_at, ChatRow.id)
.limit(limit)
)
if after is not None:
query = query.where(tuple_(ChatRow.created_at, ChatRow.id) > tuple_(after.created_at, after.id))
rows = list((await session.scalars(query)).all())
return [self._to_domain(row, await self._members(session, row.id)) for row in rows]
+366
View File
@@ -0,0 +1,366 @@
from __future__ import annotations
from datetime import datetime, timedelta
from uuid import UUID, uuid4
from sqlalchemy import or_, select, update
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from ..domain.models import Attachment, AttachmentJob, AttachmentVariant, OutboxEvent
from ..models.attachment import AttachmentRow, AttachmentVariantRow
from ..models.job import AttachmentJobRow, JobEventRow, OutboxEventRow
from .attachments import AttachmentRepository, job_payload
class JobRepository:
def __init__(self, sessions: async_sessionmaker[AsyncSession]) -> None:
self._sessions = sessions
@staticmethod
def _job(row: AttachmentJobRow) -> AttachmentJob:
return AttachmentJob(
id=row.id,
attachment_id=row.attachment_id,
pipeline_version=row.pipeline_version,
state=row.state,
attempt=row.attempt,
max_attempts=row.max_attempts,
next_attempt_at=row.next_attempt_at,
lease_owner=row.lease_owner,
lease_until=row.lease_until,
last_error_code=row.last_error_code,
replay_count=row.replay_count,
created_at=row.created_at,
updated_at=row.updated_at,
)
async def claim(
self,
job_id: UUID,
attempt: int,
worker_id: str,
now: datetime,
lease_seconds: int,
) -> tuple[AttachmentJob, Attachment] | None:
async with self._sessions() as session:
async with session.begin():
row = await session.scalar(
select(AttachmentJobRow).where(AttachmentJobRow.id == job_id).with_for_update()
)
if row is None or row.state != 'queued' or row.attempt != attempt:
return None
attachment_row = await session.get(AttachmentRow, row.attachment_id)
if attachment_row is None:
return None
row.state = 'processing'
row.lease_owner = worker_id
row.lease_until = now + timedelta(seconds=lease_seconds)
row.updated_at = now
attachment_row.status = 'processing'
attachment_row.updated_at = now
session.add(
JobEventRow(
job_id=row.id,
kind='claimed',
attempt=row.attempt,
error_code=None,
created_at=now,
)
)
await session.flush()
return self._job(row), AttachmentRepository._to_domain(attachment_row)
async def state(self, job_id: UUID) -> AttachmentJob | None:
async with self._sessions() as session:
row = await session.get(AttachmentJobRow, job_id)
return self._job(row) if row is not None else None
async def id_for_attachment(self, attachment_id: UUID) -> UUID | None:
async with self._sessions() as session:
return await session.scalar(
select(AttachmentJobRow.id).where(
AttachmentJobRow.attachment_id == attachment_id
)
)
async def failed_staging_key(self, job_id: UUID) -> str | None:
async with self._sessions() as session:
return await session.scalar(
select(AttachmentRow.staging_key)
.join(AttachmentJobRow, AttachmentJobRow.attachment_id == AttachmentRow.id)
.where(AttachmentJobRow.id == job_id, AttachmentJobRow.state == 'failed')
)
async def ready_effect_complete(self, job_id: UUID) -> bool:
async with self._sessions() as session:
job = await session.get(AttachmentJobRow, job_id)
if job is None or job.state != 'ready':
return False
attachment = await session.get(AttachmentRow, job.attachment_id)
if attachment is None or not attachment.original_key:
return False
names = set(
await session.scalars(
select(AttachmentVariantRow.name).where(
AttachmentVariantRow.attachment_id == job.attachment_id,
AttachmentVariantRow.pipeline_version == job.pipeline_version,
)
)
)
return names == {'thumbnail', 'crop', 'optimized'}
async def complete(
self,
job_id: UUID,
worker_id: str,
original_key: str,
variants: tuple[AttachmentVariant, ...],
now: datetime,
) -> bool:
async with self._sessions() as session:
async with session.begin():
job = await session.scalar(
select(AttachmentJobRow).where(AttachmentJobRow.id == job_id).with_for_update()
)
if job is None or job.state == 'ready':
return job is not None
if job.state != 'processing' or job.lease_owner != worker_id:
return False
attachment = await session.get(AttachmentRow, job.attachment_id)
if attachment is None:
return False
for variant in variants:
statement = (
insert(AttachmentVariantRow)
.values(
attachment_id=attachment.id,
pipeline_version=job.pipeline_version,
name=variant.name,
object_key=variant.object_key,
content_type=variant.content_type,
size_bytes=variant.size_bytes,
width=variant.width,
height=variant.height,
sha256=variant.sha256,
created_at=now,
updated_at=now,
)
.on_conflict_do_update(
index_elements=[
AttachmentVariantRow.attachment_id,
AttachmentVariantRow.pipeline_version,
AttachmentVariantRow.name,
],
set_={
'object_key': variant.object_key,
'content_type': variant.content_type,
'size_bytes': variant.size_bytes,
'width': variant.width,
'height': variant.height,
'sha256': variant.sha256,
'updated_at': now,
},
)
)
await session.execute(statement)
attachment.original_key = original_key
attachment.status = 'ready'
attachment.error_code = None
attachment.updated_at = now
job.state = 'ready'
job.lease_owner = None
job.lease_until = None
job.last_error_code = None
job.updated_at = now
session.add(
JobEventRow(
job_id=job.id,
kind='ready',
attempt=job.attempt,
error_code=None,
created_at=now,
)
)
return True
async def retry_or_fail(
self,
job_id: UUID,
worker_id: str | None,
error_code: str,
permanent: bool,
available_at: datetime,
now: datetime,
) -> str:
async with self._sessions() as session:
async with session.begin():
job = await session.scalar(
select(AttachmentJobRow).where(AttachmentJobRow.id == job_id).with_for_update()
)
if job is None or job.state in {'ready', 'failed'}:
return job.state if job is not None else 'missing'
if job.state != 'processing':
return job.state
if worker_id is not None:
if job.lease_owner != worker_id:
return job.state
elif job.lease_until is None or job.lease_until >= now:
return job.state
attachment = await session.get(AttachmentRow, job.attachment_id)
exhausted = job.attempt >= job.max_attempts
if permanent or exhausted:
job.state = 'failed'
attachment.status = 'failed'
attachment.error_code = error_code if permanent else 'retry_exhausted'
kind = 'failed'
else:
job.attempt += 1
job.state = 'queued'
job.next_attempt_at = available_at
attachment.status = 'queued'
attachment.error_code = None
session.add(
OutboxEventRow(
id=uuid4(),
event_type='attachment.process.v1',
job_id=job.id,
payload=job_payload(
job.id,
job.attachment_id,
job.pipeline_version,
job.attempt,
now,
),
available_at=available_at,
published_at=None,
claim_owner=None,
claim_until=None,
publish_attempts=0,
last_error_code=None,
created_at=now,
updated_at=now,
)
)
kind = 'retry_scheduled'
job.last_error_code = error_code
job.lease_owner = None
job.lease_until = None
job.updated_at = now
attachment.updated_at = now
session.add(
JobEventRow(
job_id=job.id,
kind=kind,
attempt=job.attempt,
error_code=error_code,
created_at=now,
)
)
await session.flush()
return job.state
async def recover_expired(self, now: datetime) -> int:
async with self._sessions() as session:
ids = tuple(
await session.scalars(
select(AttachmentJobRow.id).where(
AttachmentJobRow.state == 'processing',
AttachmentJobRow.lease_until < now,
)
)
)
recovered = 0
for job_id in ids:
state = await self.retry_or_fail(
job_id, None, 'lease_expired', False, now, now
)
recovered += state in {'queued', 'failed'}
return recovered
async def replay(self, job_id: UUID, now: datetime, dry_run: bool = False) -> bool:
async with self._sessions() as session:
async with session.begin():
job = await session.scalar(
select(AttachmentJobRow).where(AttachmentJobRow.id == job_id).with_for_update()
)
if job is None or job.state != 'failed':
return False
attachment = await session.get(AttachmentRow, job.attachment_id)
if attachment is None or not attachment.staging_key:
return False
if dry_run:
return True
job.state = 'queued'
job.attempt += 1
job.max_attempts = job.attempt + 4
job.replay_count += 1
job.last_error_code = None
job.next_attempt_at = now
job.updated_at = now
attachment.status = 'queued'
attachment.error_code = None
attachment.updated_at = now
session.add_all(
(
OutboxEventRow(
id=uuid4(), event_type='attachment.process.v1', job_id=job.id,
payload=job_payload(job.id, job.attachment_id, job.pipeline_version, job.attempt, now),
available_at=now, published_at=None, claim_owner=None, claim_until=None,
publish_attempts=0, last_error_code=None, created_at=now, updated_at=now,
),
JobEventRow(job_id=job.id, kind='replayed', attempt=job.attempt, error_code=None, created_at=now),
)
)
return True
class OutboxRepository:
def __init__(self, sessions: async_sessionmaker[AsyncSession]) -> None:
self._sessions = sessions
async def claim(self, owner: str, now: datetime, lease_seconds: int, limit: int = 20) -> tuple[OutboxEvent, ...]:
async with self._sessions() as session:
async with session.begin():
rows = tuple(
await session.scalars(
select(OutboxEventRow)
.where(
OutboxEventRow.published_at.is_(None),
OutboxEventRow.available_at <= now,
or_(OutboxEventRow.claim_until.is_(None), OutboxEventRow.claim_until < now),
)
.order_by(OutboxEventRow.available_at, OutboxEventRow.created_at)
.limit(limit)
.with_for_update(skip_locked=True)
)
)
until = now + timedelta(seconds=lease_seconds)
for row in rows:
row.claim_owner = owner
row.claim_until = until
row.publish_attempts += 1
row.updated_at = now
return tuple(OutboxEvent(row.id, row.job_id, row.payload, row.available_at) for row in rows)
async def published(self, event_id: UUID, owner: str, now: datetime) -> None:
async with self._sessions() as session:
async with session.begin():
await session.execute(
update(OutboxEventRow)
.where(
OutboxEventRow.id == event_id,
OutboxEventRow.claim_owner == owner,
OutboxEventRow.published_at.is_(None),
)
.values(published_at=now, claim_owner=None, claim_until=None, last_error_code=None, updated_at=now)
)
async def failed(self, event_id: UUID, owner: str, code: str, now: datetime) -> None:
async with self._sessions() as session:
async with session.begin():
await session.execute(
update(OutboxEventRow)
.where(OutboxEventRow.id == event_id, OutboxEventRow.claim_owner == owner)
.values(claim_owner=None, claim_until=None, last_error_code=code, updated_at=now)
)
+149
View File
@@ -0,0 +1,149 @@
from __future__ import annotations
from datetime import datetime
from typing import Sequence
from uuid import UUID
from sqlalchemy import select, tuple_
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from ..domain.errors import Conflict, NotFound
from ..domain.models import Keyset, Message
from ..models.attachment import AttachmentRow, MessageAttachmentRow
from ..models.chat import ChatMemberRow, ChatRow
from ..models.message import MessageRow
class MessageRepository:
def __init__(self, sessions: async_sessionmaker[AsyncSession]) -> None:
self._sessions = sessions
@staticmethod
def _to_domain(row: MessageRow, attachment_ids: Sequence[UUID]) -> Message:
return Message(
id=row.id,
chat_id=row.chat_id,
sender_id=row.sender_id,
text=row.text,
created_at=row.created_at,
attachment_ids=tuple(attachment_ids),
)
@staticmethod
async def _attachment_ids(session: AsyncSession, message_id: UUID) -> tuple[UUID, ...]:
result = await session.scalars(
select(MessageAttachmentRow.attachment_id)
.where(MessageAttachmentRow.message_id == message_id)
.order_by(MessageAttachmentRow.position)
)
return tuple(result)
@staticmethod
async def _accessible_chat_id(session: AsyncSession, chat_id: UUID, user_id: UUID) -> UUID | None:
return await session.scalar(
select(ChatRow.id)
.join(ChatMemberRow, ChatMemberRow.chat_id == ChatRow.id)
.where(ChatRow.id == chat_id, ChatMemberRow.user_id == user_id)
)
async def create_for_member(
self,
message_id: UUID,
chat_id: UUID,
sender_id: UUID,
text: str,
attachment_ids: Sequence[UUID],
created_at: datetime,
idempotency_key: str,
) -> Message | None:
async with self._sessions() as session:
async with session.begin():
accessible_chat_id = await self._accessible_chat_id(session, chat_id, sender_id)
if accessible_chat_id is None:
return None
if attachment_ids:
found = {
attachment_id: status
for attachment_id, status in (
await session.execute(
select(AttachmentRow.id, AttachmentRow.status).where(
AttachmentRow.id.in_(attachment_ids),
AttachmentRow.chat_id == accessible_chat_id,
)
)
).all()
}
if set(found) != set(attachment_ids):
raise NotFound('вложение не найдено')
if any(status == 'failed' for status in found.values()):
raise Conflict('неуспешное вложение нельзя прикрепить')
statement = (
insert(MessageRow)
.values(
id=message_id,
chat_id=accessible_chat_id,
sender_id=sender_id,
text=text,
created_at=created_at,
idempotency_key=idempotency_key,
)
.on_conflict_do_nothing(
index_elements=[
MessageRow.sender_id,
MessageRow.chat_id,
MessageRow.idempotency_key,
]
)
.returning(MessageRow.id)
)
created_id = await session.scalar(statement)
if created_id is not None:
row = await session.get(MessageRow, created_id)
session.add_all(
MessageAttachmentRow(
message_id=created_id,
attachment_id=attachment_id,
position=position,
)
for position, attachment_id in enumerate(attachment_ids)
)
await session.flush()
result_attachment_ids = tuple(attachment_ids)
else:
row = await session.scalar(
select(MessageRow).where(
MessageRow.sender_id == sender_id,
MessageRow.chat_id == accessible_chat_id,
MessageRow.idempotency_key == idempotency_key,
)
)
if row is None:
raise RuntimeError('результат идемпотентной операции не найден')
result_attachment_ids = await self._attachment_ids(session, row.id)
if row.text != text or result_attachment_ids != tuple(attachment_ids):
raise Conflict('Idempotency-Key уже использован с другим сообщением')
return self._to_domain(row, result_attachment_ids)
async def page_for_member(
self, chat_id: UUID, user_id: UUID, after: Keyset | None, limit: int
) -> list[Message] | None:
async with self._sessions() as session:
accessible_chat_id = await self._accessible_chat_id(session, chat_id, user_id)
if accessible_chat_id is None:
return None
query = (
select(MessageRow)
.where(MessageRow.chat_id == accessible_chat_id)
.order_by(MessageRow.created_at, MessageRow.id)
.limit(limit)
)
if after is not None:
query = query.where(tuple_(MessageRow.created_at, MessageRow.id) > tuple_(after.created_at, after.id))
rows = list((await session.scalars(query)).all())
return [
self._to_domain(row, await self._attachment_ids(session, row.id))
for row in rows
]
+53
View File
@@ -0,0 +1,53 @@
from __future__ import annotations
from datetime import datetime
from uuid import UUID
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from ..domain.errors import Conflict
from ..domain.models import User
from ..models.user import UserRow
class UserRepository:
def __init__(self, sessions: async_sessionmaker[AsyncSession]) -> None:
self._sessions = sessions
@staticmethod
def _to_domain(row: UserRow) -> User:
return User(id=row.id, username=row.username, display_name=row.display_name, created_at=row.created_at)
async def register(
self, user_id: UUID, username: str, display_name: str, password_hash: str, created_at: datetime
) -> User:
row = UserRow(
id=user_id,
username=username,
display_name=display_name,
password_hash=password_hash,
created_at=created_at,
)
try:
async with self._sessions() as session:
async with session.begin():
session.add(row)
await session.flush()
except IntegrityError as exc:
raise Conflict('username уже занят') from exc
return self._to_domain(row)
async def get_by_id(self, user_id: UUID) -> User | None:
async with self._sessions() as session:
row = await session.get(UserRow, user_id)
return self._to_domain(row) if row is not None else None
async def get_credentials(self, username: str) -> UserRow | None:
async with self._sessions() as session:
return await session.scalar(select(UserRow).where(UserRow.username == username))
@classmethod
def to_domain(cls, row: UserRow) -> User:
return cls._to_domain(row)