included rabbitmq as broker

This commit is contained in:
2026-11-10 07:01:17 +03:00
parent 0a70358829
commit 2b9fb3f375
49 changed files with 3072 additions and 287 deletions
+33
View File
@@ -0,0 +1,33 @@
"""Остановка фоновых процессов и безопасные сообщения об отказах."""
import asyncio
import logging
import signal
from aio_pika.exceptions import AMQPException, ChannelInvalidStateError
from sqlalchemy.exc import InterfaceError, OperationalError
from sqlalchemy.exc import TimeoutError as PoolTimeoutError
TRANSIENT_JOB_ERRORS = (AMQPException, ChannelInvalidStateError, InterfaceError, OperationalError, PoolTimeoutError, OSError)
logger = logging.getLogger(__name__)
def shutdown_event() -> asyncio.Event:
stop = asyncio.Event()
loop = asyncio.get_running_loop()
for signum in (signal.SIGTERM, signal.SIGINT):
loop.add_signal_handler(signum, stop.set)
return stop
async def wait_or_stop(stop: asyncio.Event, seconds: float) -> None:
try:
async with asyncio.timeout(seconds):
await stop.wait()
except TimeoutError:
pass
def log_background_error(operation: str, error: Exception) -> None:
# SDK/DB exceptions могут содержать параметры и credentials; выводим только тип.
logger.warning("%s: %s", operation, type(error).__name__)
+7 -3
View File
@@ -6,19 +6,22 @@ from dataclasses import asdict
import json
from app.core.config import Settings
from app.core.jobs import JobSettings
from app.core.database import create_db_engine, create_session_factory
from app.core.s3 import S3Settings
from app.domain.attachments import reconcile_attachments
from app.domain.attachment_jobs import cleanup_staging
from app.errors.handlers import RECOVERABLE_STORAGE_ERRORS, log_recoverable_error
from app.storage.s3 import create_s3_storage
async def cleanup_once(factory, storage, apply: bool) -> bool:
async def cleanup_once(factory, storage, apply: bool, jobs: JobSettings) -> bool:
completed = True
try:
async with factory() as session:
result = await reconcile_attachments(session, storage, dry_run=not apply)
print(json.dumps(asdict(result)), flush=True)
staging = await cleanup_staging(session, storage, jobs, apply=apply)
print(json.dumps({**asdict(result), "terminal_staging": staging}), flush=True)
except RECOVERABLE_STORAGE_ERRORS as error:
log_recoverable_error("Reconciliation", error)
completed = False
@@ -28,12 +31,13 @@ async def cleanup_once(factory, storage, apply: bool) -> bool:
async def run(once: bool, apply: bool) -> None:
settings = Settings() # type: ignore
s3_settings = S3Settings()
jobs = JobSettings()
engine = create_db_engine(settings)
factory = create_session_factory(engine)
storage = create_s3_storage(s3_settings)
try:
while True:
completed = await cleanup_once(factory, storage, apply)
completed = await cleanup_once(factory, storage, apply, jobs)
if once:
if not completed:
raise SystemExit(1)
+14
View File
@@ -0,0 +1,14 @@
"""Качество вариантов и пределы отдельного процесса обработки."""
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
class ImageSettings(BaseSettings):
model_config = SettingsConfigDict(env_prefix="IMAGE_", env_file=".env", extra="ignore")
jpeg_quality: int = Field(default=85, ge=1, le=95)
webp_quality: int = Field(default=80, ge=1, le=100)
webp_method: int = Field(default=4, ge=0, le=6)
memory_mib: int = Field(default=768, ge=256, le=1024)
cpu_seconds: int = Field(default=20, ge=1, le=120)
+65
View File
@@ -0,0 +1,65 @@
"""Операторский интерфейс failed registry. Доступ требует credentials стенда."""
import argparse
import asyncio
import json
from uuid import UUID
from app.core.background import log_background_error
from app.core.config import Settings
from app.core.database import create_db_engine, create_session_factory
from app.core.jobs import JobSettings
from app.domain.job_admin import REPLAY_REASONS, history, list_failed, replay_failed_job, show_job
from app.errors.exceptions import JobOperationError
from app.storage.s3 import create_s3_storage
async def execute(args):
settings = Settings()
engine = create_db_engine(settings)
storage = None
try:
factory = create_session_factory(engine)
async with factory() as session:
if args.command == "list-failed":
result = await list_failed(session, args.limit)
elif args.command == "show":
result = await show_job(session, args.job_id)
elif args.command == "history":
result = await history(session, args.job_id)
else:
storage = create_s3_storage(settings.s3)
result = await replay_failed_job(session, storage, JobSettings(), args.job_id,
request_id=args.request_id, actor=args.actor, reason=args.reason)
print(json.dumps(result, default=str), flush=True)
finally:
if storage is not None:
await storage.aclose()
await engine.dispose()
def main():
parser = argparse.ArgumentParser(description="Реестр failed и явный replay с аудитом")
commands = parser.add_subparsers(dest="command", required=True)
listing = commands.add_parser("list-failed")
listing.add_argument("--limit", type=int, choices=range(1, 501), default=50, metavar="1..500")
for name in ("show", "history", "replay"):
command = commands.add_parser(name)
command.add_argument("job_id", type=UUID)
if name == "replay":
command.add_argument("--request-id", type=UUID, required=True)
command.add_argument("--actor", required=True)
command.add_argument("--reason", choices=REPLAY_REASONS, required=True)
args = parser.parse_args()
try:
asyncio.run(execute(args))
except JobOperationError as error:
print(json.dumps({"error_code": error.code}), flush=True)
raise SystemExit(2) from None
except Exception as error:
log_background_error("Job administration failed", error)
raise SystemExit(1) from None
if __name__ == "__main__":
main()
+133 -13
View File
@@ -1,17 +1,137 @@
"""Заготовка отдельного worker lab5, не одноразового валидатора image_worker.
"""Отдельные consumers с ограниченной конкуренцией; API не выполняет resize."""
Здесь будут startup/shutdown ресурсов, цикл получения заданий, ограниченная
concurrency/prefetch, восстановление pending и остановка с сохранением работы.
Каждая задача получает отдельную AsyncSession. Обработка изображений идёт
в процессе с лимитами памяти/CPU/времени; CancelledError не подавляется.
В Compose и API модуль пока не подключён.
"""
import argparse
import asyncio
from dataclasses import dataclass
import json
import logging
import os
import signal
from uuid import UUID, uuid4
from PIL import features
from pydantic import ValidationError
from app.core.background import TRANSIENT_JOB_ERRORS, log_background_error, shutdown_event, wait_or_stop
from app.core.config import Settings
from app.core.database import create_db_engine, create_session_factory
from app.core.jobs import JobSettings
from app.domain.attachment_jobs import process_attachment_job
from app.errors.exceptions import ProcessingError
from app.schemas.job import JobMessage
from app.storage.broker import JobBroker
from app.storage.s3 import create_s3_storage
async def run_worker() -> None:
"""Запустить consumer с lease/retry, ограничением ресурсов и корректным ack.
@dataclass(frozen=True)
class Faults:
"""Только явные CLI-флаги; обычный worker не включает инъекции сбоев."""
SIGTERM должен завершить или оставить восстанавливаемую попытку; остановка
worker не заставляет API выполнять resize. Инициализация ресурсов — здесь.
"""
raise NotImplementedError("Lab5: отдельный worker ещё не реализован")
crash_after_object: UUID | None = None
crash_before_ack: UUID | None = None
fail_transient: UUID | None = None
fail_permanent: UUID | None = None
object_name: str = "optimized"
def kill(self, attachment_id: UUID, phase: str) -> None:
print(json.dumps({"fault": phase, "attachment_id": str(attachment_id)}), flush=True)
os.kill(os.getpid(), signal.SIGKILL)
def after_object(self, attachment_id: UUID, name: str) -> None:
if attachment_id == self.crash_after_object and name == self.object_name:
self.kill(attachment_id, "after_object:" + name)
def before_ack(self, attachment_id: UUID) -> None:
if attachment_id == self.crash_before_ack:
self.kill(attachment_id, "before_ack")
def before_processing(self, attachment_id: UUID) -> None:
if attachment_id == self.fail_transient:
raise TimeoutError("injected transient failure")
if attachment_id == self.fail_permanent:
raise ProcessingError("injected_permanent")
async def consume_connected(factory, storage, broker: JobBroker, settings: JobSettings, stop: asyncio.Event, faults: Faults) -> None:
consumer = uuid4().hex
while not stop.is_set():
try:
await broker.ensure_ready()
delivery = await broker.receive(consumer)
if delivery is None:
continue
try:
message = JobMessage.model_validate_json(delivery.payload)
except ValidationError:
await broker.reject_invalid(delivery.id)
continue
try:
async with factory() as session:
acknowledge = await process_attachment_job(
session, storage, message, settings,
after_object=faults.after_object, before_processing=faults.before_processing,
)
except ProcessingError:
await broker.reject_invalid(delivery.id)
else:
if acknowledge:
faults.before_ack(message.attachment_id)
await broker.acknowledge_job(delivery.id)
else:
await broker.defer_job(delivery.id)
except TRANSIENT_JOB_ERRORS as error:
log_background_error("Worker delivery deferred", error)
await broker.aclose()
await wait_or_stop(stop, settings.publisher_poll_seconds)
async def consume(factory, storage, settings, stop, faults) -> None:
broker = JobBroker(settings)
try:
await consume_connected(factory, storage, broker, settings, stop, faults)
finally:
await broker.aclose()
async def run_worker(faults: Faults) -> None:
settings = Settings()
jobs = JobSettings()
logging.basicConfig(level=settings.log_level)
if not features.check("webp"):
logging.error("Pillow requires WebP support for the image worker")
raise RuntimeError("WebP codec is unavailable")
stop = shutdown_event()
engine = create_db_engine(settings)
storage = None
try:
storage = create_s3_storage(settings.s3)
factory = create_session_factory(engine)
async with asyncio.TaskGroup() as group:
tasks = [group.create_task(consume(factory, storage, jobs, stop, faults)) for _ in range(jobs.worker_concurrency)]
await stop.wait()
# Отмена убивает resize-процесс, дожидается SDK и не отправляет ack.
for task in tasks:
task.cancel()
finally:
if storage is not None:
await storage.aclose()
await engine.dispose()
def main() -> None:
parser = argparse.ArgumentParser(description="Image worker с явными fault-injection hooks")
modes = parser.add_mutually_exclusive_group()
for flag in ("crash-after-object", "crash-before-ack", "fail-transient", "fail-permanent"):
modes.add_argument("--" + flag, type=UUID, metavar="ATTACHMENT_ID")
parser.add_argument("--object-name", choices=("original", "thumbnail", "crop", "optimized"), default="optimized")
args = parser.parse_args()
faults = Faults(**vars(args))
try:
asyncio.run(run_worker(faults))
except Exception as error:
log_background_error("Worker stopped", error)
raise SystemExit(1) from None
if __name__ == "__main__":
main()
+35
View File
@@ -0,0 +1,35 @@
"""Настройки очереди из .env; credentials брокера читаются отдельно из файла."""
from pathlib import Path
from typing import Self
from pydantic import Field, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
class JobSettings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
broker_host: str = "broker"
broker_port: int = Field(default=5672, ge=1, le=65535)
broker_password_file: Path = Path("/run/secrets/broker_password")
broker_queue: str = "attachment-jobs"
broker_user: str = "messenger"
broker_vhost: str = "/"
worker_concurrency: int = Field(default=2, ge=1, le=4)
job_max_attempts: int = Field(default=5, ge=1, le=100)
job_timeout_seconds: int = Field(default=60, ge=10, le=300)
job_lease_seconds: int = Field(default=90, ge=20, le=600)
job_retry_seconds: int = Field(default=5, ge=1, le=300)
job_retry_max_seconds: int = Field(default=120, ge=1, le=3600)
failed_staging_retention_seconds: int = Field(default=604800, ge=300)
publisher_poll_seconds: float = Field(default=1, gt=0, le=10)
staging_retention_seconds: int = Field(default=86400, ge=300)
@model_validator(mode="after")
def validate_lease(self) -> Self:
if self.job_lease_seconds < self.job_timeout_seconds + 30:
raise ValueError("Lease должен превышать timeout задания минимум на 30 секунд")
if self.job_retry_max_seconds < self.job_retry_seconds:
raise ValueError("Retry maximum must be at least the base delay")
return self
+66 -11
View File
@@ -1,15 +1,70 @@
"""Заготовка процесса доставки PostgreSQL outbox в durable broker.
"""Доставка намерений из PostgreSQL; crash hook включается только явно через CLI."""
Не держать транзакцию/блокировки во время бесконечного сетевого ожидания.
Согласовать lease publisher, ограниченные пачки и повтор после COMMIT/publish.
Процесс пока не подключён к Compose или жизненному циклу API.
"""
import argparse
import asyncio
import json
import logging
import os
import signal
from uuid import UUID
from app.core.background import TRANSIENT_JOB_ERRORS, log_background_error, shutdown_event, wait_or_stop
from app.core.config import Settings
from app.core.database import create_db_engine, create_session_factory
from app.core.jobs import JobSettings
from app.domain.attachment_jobs import publish_next_job, recover_expired_jobs
from app.storage.broker import JobBroker
async def run_publisher() -> None:
"""Публиковать сохранённые намерения и фиксировать подтверждение брокера.
def crash_before_publish(attachment_id: UUID) -> None:
"""Реальный SIGKILL после чтения принятой job, до publisher confirm и отметки publish."""
print(json.dumps({"fault": "before_publish", "attachment_id": str(attachment_id)}), flush=True)
os.kill(os.getpid(), signal.SIGKILL)
После crash между publish и отметкой допустим дубль того же job_id.
Недоступность брокера не должна терять уже принятые задания.
"""
raise NotImplementedError("Lab5: outbox publisher ещё не реализован")
async def run_publisher(crash_attachment_id: UUID | None = None) -> None:
settings = Settings()
jobs = JobSettings()
logging.basicConfig(level=settings.log_level)
stop = shutdown_event()
engine = create_db_engine(settings)
broker = None
try:
broker = JobBroker(jobs)
factory = create_session_factory(engine)
while not stop.is_set():
published = False
try:
await broker.ensure_ready()
async with factory() as session:
await recover_expired_jobs(session, jobs)
published = await publish_next_job(
session, broker, attachment_id=crash_attachment_id,
before_publish=crash_before_publish if crash_attachment_id is not None else None,
)
except TRANSIENT_JOB_ERRORS as error:
log_background_error("Publisher deferred", error)
if not published:
await wait_or_stop(stop, jobs.publisher_poll_seconds)
finally:
if broker is not None:
await broker.aclose()
await engine.dispose()
def main() -> None:
parser = argparse.ArgumentParser(description="Публикация устойчивых jobs в RabbitMQ")
parser.add_argument(
"--crash-before-publish", type=UUID, metavar="ATTACHMENT_ID",
help="аварийно завершить этот процесс перед публикацией только указанного вложения",
)
args = parser.parse_args()
try:
asyncio.run(run_publisher(args.crash_before_publish))
except Exception as error:
log_background_error("Publisher stopped", error)
raise SystemExit(1) from None
if __name__ == "__main__":
main()
+28
View File
@@ -0,0 +1,28 @@
"""Один pipeline изображений в Linux-процессе с лимитами памяти и CPU."""
from pathlib import Path
import resource
import sys
from app.core.image_processing import ImageSettings
from app.domain.image_pipeline import create_variants
from app.errors.exceptions import IMAGE_WORKER_ERRORS, pipeline_worker_error_code
def main() -> int:
settings = ImageSettings()
memory = settings.memory_mib * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (memory, memory))
resource.setrlimit(resource.RLIMIT_CPU, (settings.cpu_seconds, settings.cpu_seconds))
source, directory, metadata, content_type, maximum = sys.argv[1:]
code = 0
try:
result = create_variants(Path(source), Path(directory), content_type, int(maximum), settings)
Path(metadata).write_text(result.model_dump_json())
except IMAGE_WORKER_ERRORS as error:
code = pipeline_worker_error_code(error)
return code
if __name__ == "__main__":
raise SystemExit(main())
+186 -33
View File
@@ -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
View File
@@ -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(
+70 -25
View File
@@ -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)
+93
View File
@@ -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}
+61
View File
@@ -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())
+32
View File
@@ -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
+1 -1
View File
@@ -15,7 +15,7 @@ from app.schemas.attachment import Attachment
router = APIRouter(prefix='/api/v1', tags=['attachments'])
@router.post('/chats/{chat_id}/attachments', status_code=201)
@router.post('/chats/{chat_id}/attachments', status_code=202)
async def upload(
request: Request, chat_id: UUID, user: CurrentUser, session: DbSession,
storage: S3Storage, capacity: UploadCapacity,
+27
View File
@@ -1,3 +1,5 @@
import errno
from collections.abc import Mapping
from PIL import Image, UnidentifiedImageError
@@ -107,3 +109,28 @@ def image_validation_error(code: int) -> ApiError:
if code == 3 or code < 0:
error = payload_too_large("Превышен лимит пикселей или ресурсов изображения")
return error
class ProcessingError(Exception):
"""Постоянная ошибка pipeline с безопасным машинным кодом."""
def __init__(self, code: str) -> None:
super().__init__(code)
self.code = code
class JobOperationError(Exception):
"""Безопасный код отказа операторской команды."""
def __init__(self, code: str):
self.code = code
super().__init__(code)
def pipeline_worker_error_code(error: Exception) -> int:
"""Отделить ошибки файловой системы от ошибки декодирования изображения."""
if isinstance(error, OSError) and error.errno is not None:
if error.errno in {errno.EACCES, errno.EPERM, errno.EROFS, errno.ENOENT}:
return 5
return 4
return image_worker_error_code(error)
+1 -1
View File
@@ -45,7 +45,7 @@ def create_app(settings: Settings | None = None) -> FastAPI:
await redis.aclose()
await engine.dispose()
application = FastAPI(title="Messenger", version="1.4.0", lifespan=lifespan)
application = FastAPI(title="Messenger", version="1.5.0", lifespan=lifespan)
application.state.settings = settings
application.state.engine = engine
+3 -1
View File
@@ -1,4 +1,6 @@
from app.models.job_replay import JobReplay
from app.models.base import Base
from app.models.job import AttachmentJob
from app.models.attachment import Attachment, MessageAttachment, UploadIntent
from app.models.chat import Chat
from app.models.chat_member import ChatMember
@@ -7,4 +9,4 @@ from app.models.idempotency_key import IdempotencyKey
from app.models.message import Message
from app.models.user import User
__all__ = ["Base", "Attachment", "MessageAttachment", "UploadIntent", "Chat", "ChatMember", "Counter", "IdempotencyKey", "Message", "User"]
__all__ = ["JobReplay", "AttachmentJob", "Base", "Attachment", "MessageAttachment", "UploadIntent", "Chat", "ChatMember", "Counter", "IdempotencyKey", "Message", "User"]
+11 -4
View File
@@ -3,7 +3,8 @@
import uuid
from datetime import datetime
from sqlalchemy import CheckConstraint, ForeignKey, Index, String, func
from sqlalchemy import CheckConstraint, ForeignKey, Index, String, func, text
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
@@ -17,7 +18,8 @@ class Attachment(Base):
"content_type IN ('image/png', 'image/jpeg')", name="content_type"
),
CheckConstraint("sha256 ~ '^[a-f0-9]{64}$'", name="sha256"),
CheckConstraint("status = 'ready'", name="status"),
CheckConstraint("status IN ('queued', 'processing', 'ready', 'failed')", name="status"),
CheckConstraint("(status = 'failed' AND error_code IS NOT NULL) OR (status <> 'failed' AND error_code IS NULL)", name="error_code"),
Index("ix_attachments_chat_id", "chat_id"),
)
@@ -29,7 +31,12 @@ class Attachment(Base):
content_type: Mapped[str] = mapped_column(String(32))
size_bytes: Mapped[int]
sha256: Mapped[str] = mapped_column(String(64))
status: Mapped[str] = mapped_column(String(16), server_default="ready")
status: Mapped[str] = mapped_column(String(16), server_default="queued")
error_code: Mapped[str | None] = mapped_column(String(64))
thumbnail_key: Mapped[str | None] = mapped_column(String(128))
crop_key: Mapped[str | None] = mapped_column(String(128))
optimized_key: Mapped[str | None] = mapped_column(String(128))
variants: Mapped[list[dict]] = mapped_column(JSONB, default=list, server_default=text("'[]'::jsonb"))
created_at: Mapped[datetime] = mapped_column(server_default=func.clock_timestamp())
updated_at: Mapped[datetime] = mapped_column(server_default=func.clock_timestamp())
@@ -47,7 +54,7 @@ class MessageAttachment(Base):
class UploadIntent(Base):
"""Фиксируется до PUT; удаляется атомарно с публикацией ready-метаданных."""
"""Фиксируется до PUT; удаляется атомарно с принятием queued metadata/job."""
__tablename__ = "upload_intents"
__table_args__ = (Index("ix_upload_intents_created_at", "created_at"),)
+34 -13
View File
@@ -1,16 +1,37 @@
"""Место для будущих ORM-моделей job, outbox и вариантов lab5.
"""Устойчивая работа и намерение публикации; один pipeline на вложение."""
Пока моделей и регистрации в Base.metadata нет, чтобы не менять схему lab4
до реализации миграции. Планируемые данные:
from datetime import datetime
from uuid import UUID, uuid4
* job: job_id, attachment_id, pipeline_version, attempt/max_attempts,
status, lease token/deadline, next_attempt_at, безопасный error_code, timestamps;
* outbox: event_id, job_id, payload/version, состояние публикации и её lease;
* variant: attachment_id, pipeline_version, variant, приватный object_key,
content_type, size_bytes, sha256, размеры;
* replay audit: операторское действие и связь с прежней логической job.
from sqlalchemy import CheckConstraint, ForeignKey, Index, String, func
from sqlalchemy.orm import Mapped, mapped_column
Ключ эффекта (attachment_id, pipeline_version, variant) уникален. Старый worker
не публикует metadata поверх новой версии; точная схема зависит от трека 5.
Изменение ready-only constraints attachments — отдельная новая миграция.
"""
from app.models.base import Base
class AttachmentJob(Base):
__tablename__ = "attachment_jobs"
__table_args__ = (
CheckConstraint("pipeline_version = 1", name="pipeline_version"),
CheckConstraint("attempt >= 0 AND published_attempt >= 0", name="attempt"),
Index("ix_attachment_jobs_due", "next_attempt_at"),
Index("ix_attachment_jobs_lease", "lease_until"),
)
id: Mapped[UUID] = mapped_column(primary_key=True, default=uuid4)
attachment_id: Mapped[UUID] = mapped_column(
ForeignKey("attachments.id"), unique=True,
)
staging_key: Mapped[str | None] = mapped_column(String(128))
pipeline_version: Mapped[int] = mapped_column(server_default="1")
attempt: Mapped[int] = mapped_column(server_default="0")
cycle_start_attempt: Mapped[int] = mapped_column(server_default="0")
attempt_limit: Mapped[int | None]
last_error_permanent: Mapped[bool | None]
published_attempt: Mapped[int] = mapped_column(server_default="0")
next_attempt_at: Mapped[datetime] = mapped_column(server_default=func.clock_timestamp())
lease_token: Mapped[UUID | None]
lease_until: Mapped[datetime | None]
last_error_code: Mapped[str | None] = mapped_column(String(64))
finished_at: Mapped[datetime | None]
created_at: Mapped[datetime] = mapped_column(server_default=func.clock_timestamp())
+22
View File
@@ -0,0 +1,22 @@
"""Аудит явного повторного запуска failed; request id обеспечивает идемпотентность."""
from datetime import datetime
from uuid import UUID
from sqlalchemy import ForeignKey, String, func
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class JobReplay(Base):
__tablename__ = "job_replays"
id: Mapped[UUID] = mapped_column(primary_key=True)
job_id: Mapped[UUID] = mapped_column(ForeignKey("attachment_jobs.id"), index=True)
actor: Mapped[str] = mapped_column(String(64))
reason: Mapped[str] = mapped_column(String(32))
previous_attempt: Mapped[int]
attempt_limit: Mapped[int]
previous_error_code: Mapped[str | None] = mapped_column(String(64))
created_at: Mapped[datetime] = mapped_column(server_default=func.clock_timestamp())
+33 -5
View File
@@ -1,14 +1,25 @@
"""Публичные ready-метаданные lab4; приватный object_key не выдаётся клиенту."""
"""Публичные состояния и варианты; внутренние ключи S3 не сериализуются."""
from datetime import datetime
from typing import Literal
from uuid import UUID
from pydantic import Field
from pydantic import BaseModel, ConfigDict, Field, field_validator
from app.schemas.base import Base
class Variant(BaseModel):
model_config = ConfigDict(extra="forbid", from_attributes=True)
name: Literal["thumbnail", "crop", "optimized"]
content_type: Literal["image/jpeg", "image/png", "image/webp"]
size_bytes: int = Field(ge=1)
width: int = Field(ge=1)
height: int = Field(ge=1)
sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
class Attachment(Base):
chat_id: UUID
owner_id: UUID
@@ -16,8 +27,25 @@ class Attachment(Base):
content_type: Literal["image/png", "image/jpeg"]
size_bytes: int = Field(ge=1, le=10_485_760)
sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
status: Literal["ready"] = "ready"
variants: list[object] = Field(default_factory=list, max_length=0)
error_code: None = None
status: Literal["queued", "processing", "ready", "failed"]
variants: list[Variant] = Field(default_factory=list)
error_code: str | None = None
created_at: datetime
updated_at: datetime
VARIANT_FILENAMES = {
"thumbnail": "thumbnail.jpg", "crop": "crop.jpg", "optimized": "optimized.webp",
}
class PipelineResult(BaseModel):
model_config = ConfigDict(extra="forbid")
variants: list[Variant] = Field(min_length=3, max_length=3)
@field_validator("variants")
@classmethod
def require_all_variants(cls, variants: list[Variant]) -> list[Variant]:
if {item.name for item in variants} != set(VARIANT_FILENAMES):
raise ValueError("Нужны thumbnail, crop и optimized без повторов")
return variants
+19 -9
View File
@@ -1,10 +1,20 @@
"""Место для будущей схемы сообщения contracts/jobs.schema.json.
"""Сообщение брокера: только идентификаторы и служебные поля контракта v1."""
Пока классы не реализованы и сообщения не принимаются/не публикуются.
Обязательны schema_version=1, type=attachment.process.v1, job_id, attachment_id,
pipeline_version>=1, attempt>=1, created_at (UTC/RFC3339).
Допустимы traceparent и tracestate; дополнительные поля запрещены.
job_id сохраняется при redelivery; очередная управляемая попытка отражается
в attempt. Bytes, secrets, S3 keys и пользовательские пути не передаются.
Pydantic-схема должна соответствовать публичному JSON Schema, не менять его.
"""
from typing import Literal
from uuid import UUID
from pydantic import AwareDatetime, BaseModel, ConfigDict, Field
class JobMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
schema_version: Literal[1] = 1
type: Literal["attachment.process.v1"] = "attachment.process.v1"
job_id: UUID
attachment_id: UUID
pipeline_version: int = Field(default=1, ge=1)
attempt: int = Field(ge=1)
created_at: AwareDatetime
traceparent: str | None = Field(default=None, pattern=r"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$")
tracestate: str | None = Field(default=None, max_length=512)
+71 -20
View File
@@ -1,27 +1,78 @@
"""Заготовки адаптера durable broker; конкретный брокер ещё не выбран.
"""RabbitMQ: durable queue, persistent messages, publisher confirms и manual ack."""
Сообщения соответствуют contracts/jobs.schema.json, содержат ID и служебные
поля, но не bytes/credentials/произвольные URL. Подключение, consumer identity,
формат delivery handle и интерфейсы уточнить после выбора брокера/версии.
Здесь появятся только SDK-вызовы; решения о retry/ready находятся в domain/.
"""
import asyncio
import logging
from dataclasses import dataclass
from collections.abc import Mapping
import aio_pika
from aio_pika.abc import AbstractIncomingMessage
from app.core.jobs import JobSettings
from app.schemas.job import JobMessage
async def publish_job(payload: Mapping[str, object]) -> str:
"""Опубликовать устойчивое сообщение и вернуть идентификатор доставки.
Дождаться подтверждения сохранения брокером; неопределённый исход разрешает
повтор с тем же job_id. Не считать публикацию обработкой изображения.
"""
raise NotImplementedError("Lab5: публикация в брокер ещё не реализована")
@dataclass(frozen=True)
class Delivery:
id: AbstractIncomingMessage
payload: bytes
async def acknowledge_job(delivery_id: str) -> None:
"""Подтвердить доставку после устойчивого эффекта либо проверенного ready-дубля.
class JobBroker:
"""Один consumer/канал на экземпляр; publisher использует отдельный экземпляр."""
Retry сначала устойчиво планируется, затем закрывается старая доставка.
Конкретный delivery handle зависит от брокера; сигнатура предварительная.
"""
raise NotImplementedError("Lab5: ack ещё не реализован")
def __init__(self, settings: JobSettings) -> None:
self.settings = settings
self.connection = self.channel = self.queue = self.iterator = None
# Transport exceptions могут содержать URL с credentials.
logging.getLogger("aio_pika").setLevel(logging.CRITICAL)
logging.getLogger("aiormq").setLevel(logging.CRITICAL)
async def ensure_ready(self) -> None:
if self.connection is None or self.connection.is_closed or self.channel is None or self.channel.is_closed:
await self.aclose()
self.connection = await aio_pika.connect(
host=self.settings.broker_host, port=self.settings.broker_port,
login=self.settings.broker_user,
password=self.settings.broker_password_file.read_text().strip(),
virtualhost=self.settings.broker_vhost, timeout=5, heartbeat=30,
)
self.channel = await self.connection.channel(publisher_confirms=True, on_return_raises=True)
await self.channel.set_qos(prefetch_count=1)
self.queue = await self.channel.declare_queue(self.settings.broker_queue, durable=True)
async def publish_job(self, message: JobMessage) -> None:
await self.ensure_ready()
await self.channel.default_exchange.publish(
aio_pika.Message(
body=message.model_dump_json(exclude_none=True).encode(),
content_type="application/json", delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
message_id=f"{message.job_id}:{message.attempt}",
), routing_key=self.settings.broker_queue, mandatory=True, timeout=10,
)
async def receive(self, consumer: str) -> Delivery:
await self.ensure_ready()
if self.iterator is None:
self.iterator = self.queue.iterator(no_ack=False, consumer_tag=consumer)
await self.iterator.__aenter__()
message = await self.iterator.__anext__()
return Delivery(message, message.body)
async def acknowledge_job(self, delivery_id: AbstractIncomingMessage) -> None:
await delivery_id.ack()
async def defer_job(self, delivery_id: AbstractIncomingMessage) -> None:
# Живая чужая lease: не удерживать единственный prefetch slot навсегда.
await asyncio.sleep(self.settings.publisher_poll_seconds)
await delivery_id.nack(requeue=True)
async def reject_invalid(self, delivery_id: AbstractIncomingMessage) -> None:
# Failed jobs находятся в PostgreSQL; неизвестные payload не копируются в DLQ.
logging.getLogger(__name__).warning("Rejected invalid job envelope")
await delivery_id.reject(requeue=False)
async def aclose(self) -> None:
connection = self.connection
self.connection = self.channel = self.queue = self.iterator = None
if connection is not None and not connection.is_closed:
await connection.close()
+46
View File
@@ -0,0 +1,46 @@
"""Операторские выборки и журнал replay; транзакция принадлежит domain."""
from sqlalchemy import select
from sqlalchemy.dialects.postgresql import insert
from app.models.attachment import Attachment
from app.models.job import AttachmentJob
from app.models.job_replay import JobReplay
async def failed_jobs(session, limit: int):
result = await session.execute(
select(AttachmentJob, Attachment)
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
.where(Attachment.status == "failed")
.order_by(AttachmentJob.finished_at.desc(), AttachmentJob.id).limit(limit)
)
return result.all()
async def replay_record(session, request_id):
return await session.get(JobReplay, request_id)
async def insert_replay(session, **values) -> bool:
result = await session.scalar(insert(JobReplay).values(**values).on_conflict_do_nothing(index_elements=[JobReplay.id]).returning(JobReplay.id))
return result is not None
async def replay_history(session, job_id):
return (await session.scalars(select(JobReplay).where(JobReplay.job_id == job_id).order_by(JobReplay.created_at).limit(100))).all()
def reset_failed(job, attachment, now, attempt_limit):
job.cycle_start_attempt = job.attempt
job.attempt_limit = attempt_limit
job.published_attempt = job.attempt
job.next_attempt_at = now
job.lease_token = None
job.lease_until = None
job.finished_at = None
job.last_error_code = None
job.last_error_permanent = None
attachment.status = "queued"
attachment.error_code = None
attachment.updated_at = now
+116 -26
View File
@@ -1,37 +1,127 @@
"""Заготовки PostgreSQL-хранилища jobs lab5; скрытых commit здесь нет.
Будущие ORM-операции захвата, lease, retry и результата должны защищаться
от конкурирующих попыток. Границы транзакций находятся в domain/.
Тип результата захвата уточняется после определения модели job.
"""
"""SQL и изменения jobs/attachments; commit остаётся в domain."""
from dataclasses import dataclass
from datetime import datetime, timedelta
from uuid import UUID
from sqlalchemy import and_, or_, func, select
from sqlalchemy.ext.asyncio import AsyncSession
async def claim_job(session: AsyncSession, job_id: UUID) -> None:
"""Условно захватить допустимое задание и сохранить lease/номер попытки.
Ready и актуальная чужая аренда не переходят обратно в processing.
Будущий результат должен различать захват, завершённый дубль и занятость.
"""
raise NotImplementedError("Lab5: захват job ещё не реализован")
from app.models.attachment import Attachment
from app.models.job import AttachmentJob
from app.schemas.attachment import VARIANT_FILENAMES
async def complete_job(session: AsyncSession, job_id: UUID) -> None:
"""Атомарно записать metadata вариантов и ready после сохранения объектов.
@dataclass(frozen=True)
class JobWork:
job_id: UUID
attachment_id: UUID
lease_token: UUID
pipeline_version: int
staging_key: str
content_type: str
size_bytes: int
sha256: str
Предусловия lease/attempt/pipeline_version и структура результата будут
добавлены в сигнатуру вместе с ORM-моделью. Не делать commit в storage.
"""
raise NotImplementedError("Lab5: фиксация результата ещё не реализована")
@property
def original_key(self) -> str:
return f"originals/{self.attachment_id.hex}/v{self.pipeline_version}"
def variant_key(self, name: str) -> str:
filename = VARIANT_FILENAMES[name]
return f"variants/{self.attachment_id.hex}/v{self.pipeline_version}/{filename}"
async def record_job_failure(session: AsyncSession, job_id: UUID, error_code: str) -> None:
"""Записать безопасный код сбоя без stack trace и secrets.
async def create_job(session: AsyncSession, attachment_id: UUID, staging_key: str) -> UUID:
job = AttachmentJob(attachment_id=attachment_id, staging_key=staging_key)
session.add(job)
await session.flush()
return job.id
Domain выбирает queued с next_attempt_at либо конечный failed согласно
классификации ошибки и лимиту попыток; storage лишь сохраняет решение.
"""
raise NotImplementedError("Lab5: сохранение сбоя ещё не реализовано")
async def lock_job(session: AsyncSession, job_id: UUID):
result = await session.execute(
select(AttachmentJob, Attachment)
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
.where(AttachmentJob.id == job_id)
.with_for_update(of=AttachmentJob)
.execution_options(populate_existing=True)
)
return result.one_or_none()
async def database_time(session: AsyncSession) -> datetime:
return await session.scalar(select(func.clock_timestamp()))
async def expired_jobs(session: AsyncSession, limit: int = 20):
result = await session.execute(
select(AttachmentJob, Attachment)
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
.where(Attachment.status == "processing", AttachmentJob.lease_until < func.clock_timestamp())
.order_by(AttachmentJob.lease_until)
.limit(limit)
.with_for_update(of=AttachmentJob, skip_locked=True)
)
return result.all()
def start_job(job, attachment, token: UUID, now: datetime, lease_seconds: int) -> JobWork:
job.attempt += 1
job.lease_token = token
job.lease_until = now + timedelta(seconds=lease_seconds)
attachment.status = "processing"
attachment.updated_at = now
return JobWork(
job.id, attachment.id, token, job.pipeline_version, job.staging_key,
attachment.content_type, attachment.size_bytes, attachment.sha256,
)
def record_failure(job, attachment, now: datetime, error_code: str, *, terminal: bool, retry_seconds: float) -> None:
job.lease_token = None
job.lease_until = None
job.last_error_code = error_code
job.next_attempt_at = now + timedelta(seconds=retry_seconds)
job.finished_at = now if terminal else None
attachment.status = "failed" if terminal else "queued"
attachment.error_code = error_code if terminal else None
attachment.updated_at = now
def complete_job(job, attachment, work: JobWork, variants: list[dict], now: datetime) -> None:
attachment.object_key = work.original_key
attachment.thumbnail_key = work.variant_key("thumbnail")
attachment.crop_key = work.variant_key("crop")
attachment.optimized_key = work.variant_key("optimized")
attachment.variants = variants
attachment.status = "ready"
attachment.error_code = None
attachment.updated_at = now
job.lease_token = None
job.lease_until = None
job.last_error_code = None
job.last_error_permanent = None
job.finished_at = now
async def terminal_staging(session: AsyncSession, retention: int, failed_retention: int, limit: int = 20):
result = await session.execute(
select(AttachmentJob, Attachment)
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
.where(
AttachmentJob.staging_key.is_not(None),
or_(
and_(Attachment.status == "ready", AttachmentJob.finished_at < func.clock_timestamp() - timedelta(seconds=retention)),
and_(Attachment.status == "failed", AttachmentJob.finished_at < func.clock_timestamp() - timedelta(seconds=failed_retention)),
),
)
.order_by(AttachmentJob.finished_at)
.limit(limit)
.with_for_update(of=AttachmentJob, skip_locked=True)
)
return result.all()
def clear_staging(job) -> None:
job.staging_key = None
+23 -15
View File
@@ -1,23 +1,31 @@
"""Заготовки transactional outbox для разрыва PostgreSQL COMMIT → broker.
Outbox — таблица намерений публикации в той же транзакции, что и job.
Повторная публикация после неопределённого confirm допустима; job_id стабилен.
Форма записей, захват пачки и lease publisher уточняются вместе с моделью.
"""
"""Jobs одновременно хранят намерение публикации очередной попытки."""
from uuid import UUID
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
async def add_job_event(session: AsyncSession, job_id: UUID) -> None:
"""Сохранить намерение публикации job без commit и обращения к брокеру."""
raise NotImplementedError("Lab5: запись outbox ещё не реализована")
from app.models.attachment import Attachment
from app.models.job import AttachmentJob
async def mark_event_published(session: AsyncSession, event_id: UUID) -> None:
"""Отметить событие опубликованным после устойчивого подтверждения брокера.
async def next_unpublished_job(session: AsyncSession, *, attachment_id: UUID | None = None) -> AttachmentJob | None:
statement = (
select(AttachmentJob)
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
.where(
Attachment.status == "queued",
AttachmentJob.next_attempt_at <= func.clock_timestamp(),
AttachmentJob.published_attempt <= AttachmentJob.attempt,
)
.order_by(AttachmentJob.next_attempt_at, AttachmentJob.id)
.limit(1)
.with_for_update(of=AttachmentJob, skip_locked=True)
)
if attachment_id is not None:
statement = statement.where(AttachmentJob.attachment_id == attachment_id)
return await session.scalar(statement)
Не помечать job завершённой: publisher confirm отличается от consumer ack.
"""
raise NotImplementedError("Lab5: отметка outbox ещё не реализована")
def mark_published(job: AttachmentJob) -> None:
job.published_attempt = job.attempt + 1