Реализовать асинхронную обработку вложений
This commit is contained in:
@@ -2,5 +2,9 @@ from .attachments import AttachmentRepository
|
||||
from .chats import ChatRepository
|
||||
from .messages import MessageRepository
|
||||
from .users import UserRepository
|
||||
from .jobs import JobRepository, OutboxRepository
|
||||
|
||||
__all__ = ['AttachmentRepository', 'ChatRepository', 'MessageRepository', 'UserRepository']
|
||||
__all__ = [
|
||||
'AttachmentRepository', 'ChatRepository', 'JobRepository', 'MessageRepository',
|
||||
'OutboxRepository', 'UserRepository',
|
||||
]
|
||||
|
||||
@@ -1,14 +1,27 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from ..domain.models import Attachment
|
||||
from ..models.attachment import AttachmentRow
|
||||
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:
|
||||
@@ -16,13 +29,29 @@ class AttachmentRepository:
|
||||
self._sessions = sessions
|
||||
|
||||
@staticmethod
|
||||
def _to_domain(row: AttachmentRow) -> Attachment:
|
||||
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,
|
||||
object_key=row.object_key,
|
||||
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,
|
||||
@@ -32,6 +61,7 @@ class AttachmentRepository:
|
||||
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:
|
||||
@@ -43,19 +73,21 @@ class AttachmentRepository:
|
||||
)
|
||||
return found is not None
|
||||
|
||||
async def create(
|
||||
async def create_queued(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
job_id: UUID,
|
||||
chat_id: UUID,
|
||||
owner_id: UUID,
|
||||
filename: str,
|
||||
object_key: str,
|
||||
staging_key: str,
|
||||
content_type: str,
|
||||
size_bytes: int,
|
||||
sha256: str,
|
||||
width: int,
|
||||
height: int,
|
||||
max_attempts: int,
|
||||
now: datetime,
|
||||
) -> Attachment:
|
||||
row = AttachmentRow(
|
||||
@@ -63,23 +95,67 @@ class AttachmentRepository:
|
||||
chat_id=chat_id,
|
||||
owner_id=owner_id,
|
||||
filename=filename,
|
||||
object_key=object_key,
|
||||
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='ready',
|
||||
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(row)
|
||||
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(
|
||||
@@ -90,4 +166,8 @@ class AttachmentRepository:
|
||||
ChatMemberRow.user_id == user_id,
|
||||
)
|
||||
)
|
||||
return self._to_domain(row) if row is not None else None
|
||||
if row is None:
|
||||
return None
|
||||
return self._to_domain(
|
||||
row, await self._variants(session, row.id, row.pipeline_version)
|
||||
)
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
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 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)
|
||||
)
|
||||
@@ -77,8 +77,8 @@ class MessageRepository:
|
||||
}
|
||||
if set(found) != set(attachment_ids):
|
||||
raise NotFound('вложение не найдено')
|
||||
if any(status != 'ready' for status in found.values()):
|
||||
raise Conflict('оригинал вложения недоступен')
|
||||
if any(status == 'failed' for status in found.values()):
|
||||
raise Conflict('неуспешное вложение нельзя прикрепить')
|
||||
|
||||
statement = (
|
||||
insert(MessageRow)
|
||||
|
||||
Reference in New Issue
Block a user