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) )