Files
mtusi2026lab7/app/domain/attachment_jobs.py
T
gytall 0b97f77d76
Skeleton contracts / contracts (pull_request) Canceled after 0s
skeleton lab7 and tasks for grade 3
2026-11-21 16:21:47 +03:00

290 lines
12 KiB
Python

"""Приём, durable публикация, попытки и фиксация результата обработки."""
import asyncio
from collections.abc import Callable
from contextlib import nullcontext
from dataclasses import dataclass
from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import UUID, uuid4
from minio.error import MinioException
from opentelemetry.context import Context
from opentelemetry.trace import SpanKind
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
from sqlalchemy.ext.asyncio import AsyncSession
from urllib3.exceptions import HTTPError as StorageHTTPError
from app.core.jobs import JobSettings
from app.core.telemetry import Telemetry
from app.domain.job_retry import classify_failure, retry_delay
from app.domain.job_files import fetch_original, render_variants
from app.errors.exceptions import ProcessingError
from app.schemas.attachment import VARIANT_FILENAMES
from app.schemas.job import JobMessage
from app.storage import jobs, outbox
from app.storage.broker import JobBroker
from app.storage.jobs import JobWork
from app.storage.s3 import MinioStorage
@dataclass(frozen=True)
class Claim:
work: JobWork | None = None
acknowledge: bool = False
async def enqueue_attachment_job(
session: AsyncSession, attachment_id: UUID, staging_key: str
) -> UUID:
"""Включить намерение обработки в транзакцию queued metadata; без commit."""
return await jobs.create_job(session, attachment_id, staging_key)
async def publish_next_job(
session: AsyncSession,
broker: JobBroker,
*,
attachment_id: UUID | None = None,
before_publish: Callable[[UUID], None] | None = None,
telemetry: Telemetry | None = None,
) -> bool:
"""Отметка publish следует за durable publisher confirm; crash допускает тот же job-дубль."""
job = await outbox.next_unpublished_job(session, attachment_id=attachment_id)
published = job is not None
if job is not None:
if before_publish is not None:
before_publish(job.attachment_id)
parent = TraceContextTextMapPropagator().extract(job.trace_context or {}, context=Context())
with telemetry.span(
"rabbitmq.publish", context=parent, kind=SpanKind.PRODUCER,
attributes={"messaging.system": "rabbitmq", "job.attempt": job.attempt + 1},
) if telemetry else nullcontext():
await broker.publish_job(
JobMessage(
job_id=job.id,
attachment_id=job.attachment_id,
pipeline_version=job.pipeline_version,
attempt=job.attempt + 1,
created_at=job.created_at,
)
)
outbox.mark_published(job)
await session.commit()
return published
async def claim_job(
session: AsyncSession, message: JobMessage, settings: JobSettings
) -> Claim:
"""Дубликат не захватывает живую аренду и не откатывает terminal-состояние."""
row = await jobs.lock_job(session, message.job_id)
result = Claim()
if row is None:
raise ProcessingError("unknown_job")
job, attachment = row
if (
message.attachment_id != attachment.id
or message.pipeline_version != job.pipeline_version
):
raise ProcessingError("invalid_job")
now = await jobs.database_time(session)
if job.attempt_limit is None:
job.attempt_limit = settings.job_max_attempts
if attachment.status in {"ready", "failed"}:
result = Claim(acknowledge=True)
elif message.attempt <= job.attempt and attachment.status == "queued":
# Предыдущая попытка уже устойчиво заменена новой в PostgreSQL.
result = Claim(acknowledge=True)
elif message.attempt < job.attempt:
result = Claim(acknowledge=True)
elif message.attempt > job.attempt + 1:
raise ProcessingError("invalid_attempt")
elif attachment.status == "queued" and job.next_attempt_at <= now:
if (
job.attempt >= (job.attempt_limit or settings.job_max_attempts)
or job.staging_key is None
):
jobs.record_failure(
job, attachment, now, "retry_exhausted", terminal=True, retry_seconds=0
)
result = Claim(acknowledge=True)
else:
result = Claim(
work=jobs.start_job(
job, attachment, uuid4(), now, settings.job_lease_seconds
)
)
await session.commit()
return result
async def save_failure(
session: AsyncSession,
work: JobWork,
settings: JobSettings,
code: str,
*,
permanent: bool,
) -> None:
# Неоднозначный COMMIT проверяется повторным чтением: ready сохраняется.
await session.rollback()
row = await jobs.lock_job(session, work.job_id)
if row is not None:
job, attachment = row
if attachment.status == "processing" and job.lease_token == work.lease_token:
exhausted = job.attempt >= (job.attempt_limit or settings.job_max_attempts)
jobs.record_failure(
job,
attachment,
await jobs.database_time(session),
"retry_exhausted" if exhausted and not permanent else code,
terminal=permanent or exhausted,
retry_seconds=retry_delay(
settings, job.attempt - job.cycle_start_attempt
),
)
job.last_error_code = code
job.last_error_permanent = permanent
await session.commit()
async def build_result(
session: AsyncSession,
storage: MinioStorage,
work: JobWork,
after_object: Callable[[UUID, str], None] | None = None,
telemetry: Telemetry | None = None,
) -> bool:
"""Фиксированные ключи и блокировка job защищают PUT от устаревшей попытки."""
with TemporaryDirectory(prefix="messenger-job-") as directory:
source = Path(directory) / "original"
with telemetry.span("s3.read_staging") if telemetry else nullcontext():
await fetch_original(storage, work, source)
result = await render_variants(storage, work, source, Path(directory))
row = await jobs.lock_job(session, work.job_id)
if row is None:
await session.rollback()
return True
job, attachment = row
now = await jobs.database_time(session)
if attachment.status != "processing" or job.lease_token != work.lease_token:
await session.rollback()
return True
if job.lease_until is None or job.lease_until <= now:
await session.rollback()
return False
# Блокировка остаётся до завершения PUT/COMMIT; reaper использует SKIP LOCKED.
# При отмене S3 adapter дожидается SDK-потока до освобождения блокировки.
with telemetry.span("s3.write_result") if telemetry else nullcontext():
await storage.put_file(
work.original_key,
source,
size_bytes=work.size_bytes,
content_type=work.content_type,
sha256=work.sha256,
)
if after_object is not None:
after_object(work.attachment_id, "original")
for variant in result.variants:
await storage.put_file(
work.variant_key(variant.name),
Path(directory) / VARIANT_FILENAMES[variant.name],
size_bytes=variant.size_bytes,
content_type=variant.content_type,
sha256=variant.sha256,
)
if after_object is not None:
after_object(work.attachment_id, variant.name)
with telemetry.span("postgres.commit_ready") if telemetry else nullcontext():
ready_at = await jobs.database_time(session)
accepted_at = job.created_at
jobs.complete_job(
job,
attachment,
work,
[variant.model_dump() for variant in result.variants],
ready_at,
)
await session.commit()
if telemetry and telemetry.enabled:
telemetry.time_to_ready.record(max(0, (ready_at - accepted_at).total_seconds()))
return True
async def process_attachment_job(
session: AsyncSession,
storage: MinioStorage,
message: JobMessage,
settings: JobSettings,
*,
after_object: Callable[[UUID, str], None] | None = None,
before_processing: Callable[[UUID], None] | None = None,
telemetry: Telemetry | None = None,
) -> bool:
with telemetry.span("postgres.claim_job") if telemetry else nullcontext():
claim = await claim_job(session, message, settings)
acknowledge = claim.acknowledge
if claim.work is not None:
work = claim.work
with telemetry.job_attempt() if telemetry else nullcontext({}) as result:
try:
async with asyncio.timeout(settings.job_timeout_seconds):
if before_processing is not None:
before_processing(work.attachment_id)
acknowledge = await build_result(session, storage, work, after_object, telemetry)
result["outcome"] = "success" if acknowledge else "deferred"
except (
ProcessingError,
MinioException,
StorageHTTPError,
OSError,
TimeoutError,
) as error:
code, permanent = classify_failure(error)
await save_failure(session, work, settings, code, permanent=permanent)
result.update(outcome="error", error_code=code)
acknowledge = True
# Ошибка БД/неизвестная ошибка или отмена не подтверждают доставку.
return acknowledge
async def recover_expired_jobs(session: AsyncSession, settings: JobSettings) -> int:
rows = await jobs.expired_jobs(session)
now = await jobs.database_time(session)
for job, attachment in rows:
if job.attempt_limit is None:
job.attempt_limit = settings.job_max_attempts
exhausted = job.attempt >= (job.attempt_limit or settings.job_max_attempts)
jobs.record_failure(
job,
attachment,
now,
"retry_exhausted" if exhausted else "worker_timeout",
terminal=exhausted,
retry_seconds=retry_delay(settings, job.attempt - job.cycle_start_attempt),
)
job.last_error_code = "worker_timeout"
job.last_error_permanent = False
await session.commit()
return len(rows)
async def cleanup_staging(
session: AsyncSession, storage: MinioStorage, settings: JobSettings, *, apply: bool
) -> int:
rows = await jobs.terminal_staging(
session,
settings.staging_retention_seconds,
settings.failed_staging_retention_seconds,
)
if apply:
for job, attachment in rows:
if job.staging_key != attachment.object_key:
await storage.delete_object(job.staging_key)
jobs.clear_staging(job)
await session.commit()
else:
await session.rollback()
return len(rows)