Files
mtusi2026lab5/app/repositories/jobs.py
T

367 lines
16 KiB
Python

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