included rabbitmq as broker
This commit is contained in:
+186
-33
@@ -1,45 +1,198 @@
|
||||
"""Заготовки сценариев lab5; не подключены к upload или worker.
|
||||
"""Приём, durable публикация, попытки и фиксация результата обработки."""
|
||||
|
||||
Здесь появятся транзакционные границы и бизнес-условия; SQL и SDK остаются
|
||||
в storage/. Одна AsyncSession принадлежит одной последовательной задаче.
|
||||
"""
|
||||
|
||||
from uuid import UUID
|
||||
import asyncio
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from minio.error import MinioException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from urllib3.exceptions import HTTPError as StorageHTTPError
|
||||
|
||||
from app.core.jobs import JobSettings
|
||||
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
|
||||
|
||||
|
||||
async def enqueue_attachment_job(session: AsyncSession, attachment_id: UUID) -> UUID:
|
||||
"""Создать job и outbox в транзакции queued metadata после durable staging.
|
||||
|
||||
Возвращать стабильный job_id. Commit принадлежит сценарию приёма upload;
|
||||
202 допустим только после устойчивого оригинала и успешного commit.
|
||||
"""
|
||||
raise NotImplementedError("Lab5: постановка задания ещё не реализована")
|
||||
@dataclass(frozen=True)
|
||||
class Claim:
|
||||
work: JobWork | None = None
|
||||
acknowledge: bool = False
|
||||
|
||||
|
||||
async def process_attachment_job(session: AsyncSession, job_id: UUID) -> None:
|
||||
"""Захватить job с lease и опубликовать original и обязательные варианты.
|
||||
|
||||
Ready-дубль не меняет результат. Lease и версия защищают от устаревшей
|
||||
попытки. S3/metadata фиксируются до ack; отмена не подавляется.
|
||||
"""
|
||||
raise NotImplementedError("Lab5: обработка задания ещё не реализована")
|
||||
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 recover_expired_jobs(session: AsyncSession) -> int:
|
||||
"""Вернуть зависший processing в очередь после истечения lease.
|
||||
|
||||
Учитывать лимит попыток и защиту от конкурентного завершения старым worker.
|
||||
Точное правило heartbeat/deadline определяется до реализации.
|
||||
"""
|
||||
raise NotImplementedError("Lab5: восстановление lease ещё не реализовано")
|
||||
async def publish_next_job(
|
||||
session: AsyncSession, broker: JobBroker, *,
|
||||
attachment_id: UUID | None = None,
|
||||
before_publish: Callable[[UUID], None] | 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)
|
||||
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 replay_failed_job(session: AsyncSession, job_id: UUID) -> None:
|
||||
"""Явно повторить только failed job, сохранив аудит и ключ логического эффекта.
|
||||
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
|
||||
|
||||
Не переисполнять ready. Проверка допустимости, лимиты повторов и способ
|
||||
операторского вызова будут определены вместе с реестром failed/DLQ.
|
||||
"""
|
||||
raise NotImplementedError("Lab5: replay ещё не реализован")
|
||||
|
||||
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,
|
||||
) -> bool:
|
||||
"""Фиксированные ключи и блокировка job защищают PUT от устаревшей попытки."""
|
||||
with TemporaryDirectory(prefix="messenger-job-") as directory:
|
||||
source = Path(directory) / "original"
|
||||
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-потока до освобождения блокировки.
|
||||
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)
|
||||
jobs.complete_job(job, attachment, work, [variant.model_dump() for variant in result.variants], await jobs.database_time(session))
|
||||
await session.commit()
|
||||
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,
|
||||
) -> bool:
|
||||
claim = await claim_job(session, message, settings)
|
||||
acknowledge = claim.acknowledge
|
||||
if claim.work is not None:
|
||||
work = claim.work
|
||||
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)
|
||||
except (ProcessingError, MinioException, StorageHTTPError, OSError, TimeoutError) as error:
|
||||
code, permanent = classify_failure(error)
|
||||
await save_failure(session, work, settings, code, permanent=permanent)
|
||||
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)
|
||||
|
||||
+36
-19
@@ -13,6 +13,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.request_capacity import RequestCapacity
|
||||
from app.domain.chats import ensure_chat_member
|
||||
from app.domain.attachment_jobs import enqueue_attachment_job
|
||||
from app.domain.images import validate_filename, validate_image
|
||||
from app.errors.exceptions import (
|
||||
conflict,
|
||||
@@ -28,7 +29,7 @@ from app.errors.handlers import (
|
||||
log_recoverable_error,
|
||||
operation_timeout,
|
||||
)
|
||||
from app.schemas.attachment import Attachment
|
||||
from app.schemas.attachment import Attachment, VARIANT_FILENAMES
|
||||
from app.schemas.user import User
|
||||
from app.storage import attachments as repository
|
||||
from app.storage.s3 import MinioStorage
|
||||
@@ -151,7 +152,7 @@ async def recover_upload(
|
||||
await session.rollback()
|
||||
|
||||
|
||||
async def publish_original(
|
||||
async def stage_attachment(
|
||||
session: AsyncSession,
|
||||
storage: MinioStorage,
|
||||
user: User,
|
||||
@@ -161,8 +162,9 @@ async def publish_original(
|
||||
filename: str,
|
||||
content_type: str,
|
||||
) -> Attachment:
|
||||
"""Сохранить исходник в staging и атомарно принять metadata/job."""
|
||||
id = uuid4()
|
||||
key = f"originals/{uuid4().hex}"
|
||||
key = f"staging/{uuid4().hex}"
|
||||
# Журнал устойчив до PUT, включая аварию процесса и неоднозначный COMMIT.
|
||||
await repository.reserve_upload(session, id, key)
|
||||
await session.commit()
|
||||
@@ -181,13 +183,16 @@ async def publish_original(
|
||||
id=id,
|
||||
chat_id=chat_id,
|
||||
owner_id=user.id,
|
||||
object_key=key,
|
||||
object_key=f"originals/{id.hex}/v1",
|
||||
status="queued",
|
||||
filename=filename,
|
||||
content_type=content_type,
|
||||
size_bytes=original.size_bytes,
|
||||
sha256=original.sha256,
|
||||
)
|
||||
await enqueue_attachment_job(session, id, key)
|
||||
await repository.finish_upload(session, id)
|
||||
# Снимок queued строится до COMMIT, даже если worker очень быстрый.
|
||||
result = Attachment.model_validate(record)
|
||||
await session.commit()
|
||||
except BaseException:
|
||||
@@ -223,7 +228,7 @@ async def upload_attachment(
|
||||
settings.chunk_bytes,
|
||||
)
|
||||
await validate_image(original.path, content_type, settings)
|
||||
result = await publish_original(
|
||||
result = await stage_attachment(
|
||||
session,
|
||||
storage,
|
||||
user,
|
||||
@@ -245,6 +250,13 @@ async def get_attachment(
|
||||
return Attachment.model_validate(record)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DownloadInfo:
|
||||
filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
|
||||
|
||||
async def download_attachment(
|
||||
session: AsyncSession,
|
||||
storage: MinioStorage | None,
|
||||
@@ -252,25 +264,30 @@ async def download_attachment(
|
||||
attachment_id: UUID,
|
||||
*,
|
||||
variant: str = "original",
|
||||
) -> tuple[Attachment, AsyncIterator[bytes]]:
|
||||
) -> tuple[DownloadInfo, AsyncIterator[bytes]]:
|
||||
result = await get_attachment(session, user, attachment_id)
|
||||
if variant != "original":
|
||||
raise not_found()
|
||||
if result.status != "ready":
|
||||
raise conflict("Вложение пока недоступно для скачивания")
|
||||
storage = require_storage(storage)
|
||||
record = await repository.get_attachment(session, attachment_id)
|
||||
if record is None:
|
||||
raise not_found()
|
||||
key = record.object_key
|
||||
if variant == "original":
|
||||
key = record.object_key
|
||||
info = DownloadInfo(result.filename, result.content_type, result.size_bytes)
|
||||
else:
|
||||
selected = next((item for item in result.variants if item.name == variant), None)
|
||||
keys = {"thumbnail": record.thumbnail_key, "crop": record.crop_key, "optimized": record.optimized_key}
|
||||
key = keys.get(variant)
|
||||
if selected is None or key is None:
|
||||
raise not_found()
|
||||
info = DownloadInfo(VARIANT_FILENAMES[variant], selected.content_type, selected.size_bytes)
|
||||
await session.rollback()
|
||||
info = await storage.stat_object(key)
|
||||
if (
|
||||
info is None
|
||||
or info.size_bytes != result.size_bytes
|
||||
or info.content_type != result.content_type
|
||||
):
|
||||
raise unavailable("Оригинал временно недоступен")
|
||||
stored = await storage.stat_object(key)
|
||||
if stored.size_bytes != info.size_bytes or stored.content_type != info.content_type:
|
||||
raise unavailable("Файл временно недоступен")
|
||||
stream = await storage.open_object(key)
|
||||
return result, stream
|
||||
return info, stream
|
||||
|
||||
|
||||
async def validate_message_attachments(
|
||||
@@ -283,8 +300,8 @@ async def validate_message_attachments(
|
||||
records = await repository.get_for_chat(session, chat_id, attachment_ids)
|
||||
if len(records) != len(attachment_ids):
|
||||
raise not_found()
|
||||
if any(record.status != "ready" for record in records):
|
||||
raise conflict("Вложение ещё не готово")
|
||||
if any(record.status == "failed" for record in records):
|
||||
raise conflict("Обработка вложения завершилась ошибкой")
|
||||
|
||||
|
||||
async def reconcile_attachments(
|
||||
|
||||
@@ -1,34 +1,79 @@
|
||||
"""Заготовки преобразований lab5, без доступа к БД, брокеру и HTTP.
|
||||
|
||||
Pipeline запускается внутри ограниченного процесса worker. Исходные bytes
|
||||
не перекодируются; варианты удаляют метаданные по документированной политике.
|
||||
Значения качества JPEG/WebP предстоит выбрать и зафиксировать в REPORT.md.
|
||||
"""
|
||||
"""Thumbnail, crop и WebP; один ограниченный процесс, последовательная обработка."""
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
def create_thumbnail(source: Path, destination: Path) -> None:
|
||||
"""Создать JPEG, вписанный в 256×256 без увеличения.
|
||||
|
||||
Применить EXIF orientation, alpha положить на белый; округлять размеры
|
||||
вниз, минимум 1 px. Публичный fixture 320×200 должен дать 256×160.
|
||||
"""
|
||||
raise NotImplementedError("Lab5: thumbnail ещё не реализован")
|
||||
from app.core.image_processing import ImageSettings
|
||||
from app.domain.image_validation import decode_image
|
||||
from app.schemas.attachment import PipelineResult, Variant
|
||||
|
||||
|
||||
def create_crop(source: Path, destination: Path) -> None:
|
||||
"""Создать центрированный квадрат JPEG 128×128; увеличение допустимо.
|
||||
|
||||
Учитывать EXIF orientation и прозрачность по той же политике, что thumbnail.
|
||||
"""
|
||||
raise NotImplementedError("Lab5: crop ещё не реализован")
|
||||
def fitted_size(size: tuple[int, int], maximum: int) -> tuple[int, int]:
|
||||
"""Вписать без увеличения, округляя вниз, минимум один пиксель."""
|
||||
longest = max(size)
|
||||
result = size
|
||||
if longest > maximum:
|
||||
result = (max(1, size[0] * maximum // longest), max(1, size[1] * maximum // longest))
|
||||
return result
|
||||
|
||||
|
||||
def create_optimized(source: Path, destination: Path) -> None:
|
||||
"""Создать WebP, вписанный в 1280×1280 без увеличения.
|
||||
def describe_variant(name: str, content_type: str, path: Path, size: tuple[int, int]) -> Variant:
|
||||
checksum = hashlib.sha256()
|
||||
with path.open("rb") as source:
|
||||
for chunk in iter(lambda: source.read(65536), b""):
|
||||
checksum.update(chunk)
|
||||
return Variant(
|
||||
name=name, content_type=content_type, size_bytes=path.stat().st_size,
|
||||
width=size[0], height=size[1], sha256=checksum.hexdigest(),
|
||||
)
|
||||
|
||||
Удалить метаданные и применить описанную политику качества. Уменьшение
|
||||
размера любого маленького исходника не гарантируется контрактом.
|
||||
"""
|
||||
raise NotImplementedError("Lab5: optimized ещё не реализован")
|
||||
|
||||
def save_jpeg(image: Image.Image, destination: Path, quality: int) -> None:
|
||||
"""Белая подложка и новый image без EXIF/ICC/XMP/текстовых метаданных."""
|
||||
with Image.new("RGB", image.size, "white") as clean:
|
||||
with image.getchannel("A") as alpha:
|
||||
clean.paste(image, mask=alpha)
|
||||
clean.save(destination, format="JPEG", quality=quality, exif=b"")
|
||||
|
||||
|
||||
def create_thumbnail(image: Image.Image, destination: Path, quality: int) -> Variant:
|
||||
size = fitted_size(image.size, 256)
|
||||
with image.resize(size, Image.Resampling.LANCZOS) as resized:
|
||||
save_jpeg(resized, destination, quality)
|
||||
return describe_variant("thumbnail", "image/jpeg", destination, size)
|
||||
|
||||
|
||||
def create_crop(image: Image.Image, destination: Path, quality: int) -> Variant:
|
||||
"""Центрированный JPEG 128×128; маленький исходник допускает увеличение."""
|
||||
with ImageOps.fit(image, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5)) as crop:
|
||||
save_jpeg(crop, destination, quality)
|
||||
return describe_variant("crop", "image/jpeg", destination, (128, 128))
|
||||
|
||||
|
||||
def create_optimized(image: Image.Image, destination: Path, settings: ImageSettings) -> Variant:
|
||||
"""WebP ≤1280×1280 без увеличения; alpha сохраняется, метаданные удаляются."""
|
||||
size = fitted_size(image.size, 1280)
|
||||
with image.resize(size, Image.Resampling.LANCZOS) as resized:
|
||||
with Image.new("RGBA", size) as clean:
|
||||
clean.paste(resized)
|
||||
clean.save(
|
||||
destination, format="WEBP", lossless=False,
|
||||
quality=settings.webp_quality, method=settings.webp_method,
|
||||
exif=b"", icc_profile=b"", xmp=b"",
|
||||
)
|
||||
return describe_variant("optimized", "image/webp", destination, size)
|
||||
|
||||
|
||||
def create_variants(source: Path, directory: Path, content_type: str, max_pixels: int, settings: ImageSettings) -> PipelineResult:
|
||||
decode_image(source, content_type, max_pixels)
|
||||
with Image.open(source, formats=["PNG", "JPEG"]) as image:
|
||||
ImageOps.exif_transpose(image, in_place=True)
|
||||
with image.convert("RGBA") as pixels:
|
||||
variants = [
|
||||
create_thumbnail(pixels, directory / "thumbnail.jpg", settings.jpeg_quality),
|
||||
create_crop(pixels, directory / "crop.jpg", settings.jpeg_quality),
|
||||
create_optimized(pixels, directory / "optimized.webp", settings),
|
||||
]
|
||||
return PipelineResult(variants=variants)
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Replay только failed с проверенным исходником и ограниченным новым бюджетом."""
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from uuid import uuid4
|
||||
|
||||
from minio.error import S3Error
|
||||
|
||||
from app.domain.job_files import fetch_original
|
||||
from app.errors.exceptions import JobOperationError, ProcessingError
|
||||
from app.storage import job_admin, jobs
|
||||
from app.storage.jobs import JobWork
|
||||
|
||||
REPLAY_REASONS = ("dependency_restored", "configuration_fixed", "manual_review")
|
||||
|
||||
|
||||
def snapshot(job, attachment):
|
||||
return dict(job_id=str(job.id), attachment_id=str(attachment.id), status=attachment.status,
|
||||
attempt=job.attempt, attempt_limit=job.attempt_limit, cycle_start_attempt=job.cycle_start_attempt,
|
||||
error_code=attachment.error_code, last_error_code=job.last_error_code,
|
||||
last_error_permanent=job.last_error_permanent, staging_retained=job.staging_key is not None,
|
||||
next_attempt_at=job.next_attempt_at, lease_until=job.lease_until, finished_at=job.finished_at)
|
||||
|
||||
|
||||
async def list_failed(session, limit):
|
||||
return [snapshot(job, attachment) for job, attachment in await job_admin.failed_jobs(session, limit)]
|
||||
|
||||
|
||||
async def show_job(session, job_id):
|
||||
row = await jobs.lock_job(session, job_id)
|
||||
if row is None:
|
||||
raise JobOperationError("unknown_job")
|
||||
result = snapshot(*row)
|
||||
await session.rollback()
|
||||
return result
|
||||
|
||||
|
||||
async def history(session, job_id):
|
||||
return [dict(request_id=str(row.id), actor=row.actor, reason=row.reason,
|
||||
previous_attempt=row.previous_attempt, attempt_limit=row.attempt_limit,
|
||||
previous_error_code=row.previous_error_code, created_at=row.created_at)
|
||||
for row in await job_admin.replay_history(session, job_id)]
|
||||
|
||||
|
||||
def same_request(record, job_id, actor, reason):
|
||||
if record.job_id != job_id or record.actor != actor or record.reason != reason:
|
||||
raise JobOperationError("request_conflict")
|
||||
return {"request_id": str(record.id), "job_id": str(job_id), "already_applied": True}
|
||||
|
||||
|
||||
async def replay_failed_job(session, storage, settings, job_id, *, request_id, actor, reason):
|
||||
if re.fullmatch(r"[A-Za-z0-9._-]{1,64}", actor) is None or reason not in REPLAY_REASONS:
|
||||
raise JobOperationError("invalid_audit_fields")
|
||||
row = await jobs.lock_job(session, job_id)
|
||||
if row is None:
|
||||
raise JobOperationError("unknown_job")
|
||||
record = await job_admin.replay_record(session, request_id)
|
||||
if record is not None:
|
||||
result = same_request(record, job_id, actor, reason)
|
||||
await session.rollback()
|
||||
return result
|
||||
job, attachment = row
|
||||
if attachment.status != "failed":
|
||||
raise JobOperationError("job_not_failed")
|
||||
if job.staging_key is None:
|
||||
raise JobOperationError("source_expired")
|
||||
# Та же блокировка защищает исходник от cleanup до окончания проверки и COMMIT.
|
||||
work = JobWork(job.id, attachment.id, uuid4(), job.pipeline_version, job.staging_key,
|
||||
attachment.content_type, attachment.size_bytes, attachment.sha256)
|
||||
try:
|
||||
async with asyncio.timeout(settings.job_timeout_seconds):
|
||||
with TemporaryDirectory(prefix="replay-source-") as directory:
|
||||
await fetch_original(storage, work, Path(directory) / "original")
|
||||
except ProcessingError as error:
|
||||
raise JobOperationError(error.code) from None
|
||||
except S3Error as error:
|
||||
if error.code in {"NoSuchKey", "NoSuchObject"}:
|
||||
raise JobOperationError("source_missing") from None
|
||||
raise
|
||||
limit = job.attempt + settings.job_max_attempts
|
||||
inserted = await job_admin.insert_replay(
|
||||
session, id=request_id, job_id=job_id, actor=actor, reason=reason,
|
||||
previous_attempt=job.attempt, attempt_limit=limit, previous_error_code=job.last_error_code,
|
||||
)
|
||||
if not inserted:
|
||||
result = same_request(await job_admin.replay_record(session, request_id), job_id, actor, reason)
|
||||
await session.rollback()
|
||||
return result
|
||||
job_admin.reset_failed(job, attachment, await jobs.database_time(session), limit)
|
||||
await session.commit()
|
||||
return {"request_id": str(request_id), "job_id": str(job_id), "already_applied": False, "status": "queued", "attempt_limit": limit}
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Получение исходника и запуск изолированного процесса обработки вариантов."""
|
||||
|
||||
import asyncio
|
||||
import errno
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
from anyio import CancelScope
|
||||
|
||||
from app.errors.exceptions import ProcessingError
|
||||
from app.schemas.attachment import PipelineResult
|
||||
from app.storage.jobs import JobWork
|
||||
from app.storage.s3 import MinioStorage
|
||||
|
||||
|
||||
async def fetch_original(storage: MinioStorage, work: JobWork, destination: Path) -> None:
|
||||
if work.size_bytes > storage.settings.max_upload_bytes:
|
||||
raise ProcessingError("image_limits")
|
||||
checksum = hashlib.sha256()
|
||||
size = 0
|
||||
stream = await storage.open_object(work.staging_key)
|
||||
try:
|
||||
with destination.open("wb") as target:
|
||||
async for chunk in stream:
|
||||
size += len(chunk)
|
||||
if size > work.size_bytes:
|
||||
raise ProcessingError("source_mismatch")
|
||||
target.write(chunk)
|
||||
checksum.update(chunk)
|
||||
finally:
|
||||
await stream.aclose()
|
||||
if size != work.size_bytes or checksum.hexdigest() != work.sha256:
|
||||
raise ProcessingError("source_mismatch")
|
||||
|
||||
|
||||
async def render_variants(storage: MinioStorage, work: JobWork, source: Path, directory: Path) -> PipelineResult:
|
||||
metadata = directory / "variants.json"
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
sys.executable, "-m", "app.core.thumbnail_worker", str(source), str(directory),
|
||||
str(metadata), work.content_type, str(storage.settings.max_image_pixels),
|
||||
stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL,
|
||||
)
|
||||
try:
|
||||
code = await process.wait()
|
||||
finally:
|
||||
if process.returncode is None:
|
||||
process.kill()
|
||||
with CancelScope(shield=True):
|
||||
await process.wait()
|
||||
if code == 2:
|
||||
raise ProcessingError("invalid_image")
|
||||
if code == 3 or code < 0:
|
||||
raise ProcessingError("image_limits")
|
||||
if code == 4:
|
||||
raise OSError(errno.EIO, "Pipeline filesystem unavailable")
|
||||
if code == 5:
|
||||
raise ProcessingError("processing_configuration")
|
||||
if code != 0:
|
||||
raise RuntimeError("Image pipeline subprocess failed")
|
||||
return PipelineResult.model_validate_json(metadata.read_text())
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Ограниченный exponential backoff: jitter сохраняется вместе с новой попыткой."""
|
||||
|
||||
import errno
|
||||
import random
|
||||
|
||||
from minio.error import S3Error
|
||||
|
||||
from app.core.jobs import JobSettings
|
||||
from app.errors.exceptions import ProcessingError
|
||||
|
||||
|
||||
def retry_delay(settings: JobSettings, cycle_attempt: int) -> float:
|
||||
ceiling = min(settings.job_retry_max_seconds, settings.job_retry_seconds * 2 ** min(30, max(0, cycle_attempt - 1)))
|
||||
return random.uniform(ceiling / 2, ceiling)
|
||||
|
||||
|
||||
def classify_failure(error: Exception) -> tuple[str, bool]:
|
||||
if isinstance(error, ProcessingError):
|
||||
return error.code, True
|
||||
if isinstance(error, S3Error):
|
||||
if error.code in {"NoSuchKey", "NoSuchObject"}:
|
||||
return "source_missing", True
|
||||
if error.code in {"AccessDenied", "InvalidAccessKeyId", "SignatureDoesNotMatch", "NoSuchBucket"}:
|
||||
return "storage_configuration", True
|
||||
if error.code in {"InternalError", "SlowDown", "ServiceUnavailable", "RequestTimeout", "Throttling"}:
|
||||
return "storage_unavailable", False
|
||||
return "storage_rejected", True
|
||||
if isinstance(error, TimeoutError):
|
||||
return "processing_timeout", False
|
||||
if isinstance(error, OSError) and error.errno in {errno.EACCES, errno.EPERM, errno.EROFS, errno.ENOENT}:
|
||||
return "processing_configuration", True
|
||||
return "processing_unavailable", False
|
||||
Reference in New Issue
Block a user