formatted project by python-black

This commit is contained in:
2026-11-10 09:52:42 +03:00
parent 7cd02da51d
commit 9899ee4676
66 changed files with 2517 additions and 944 deletions
+95 -28
View File
@@ -29,13 +29,17 @@ class Claim:
acknowledge: bool = False
async def enqueue_attachment_job(session: AsyncSession, attachment_id: UUID, staging_key: str) -> UUID:
async def enqueue_attachment_job(
session: AsyncSession, attachment_id: UUID, staging_key: str
) -> UUID:
"""Включить намерение обработки в транзакцию queued metadata; без commit."""
return await jobs.create_job(session, attachment_id, staging_key)
async def publish_next_job(
session: AsyncSession, broker: JobBroker, *,
session: AsyncSession,
broker: JobBroker,
*,
attachment_id: UUID | None = None,
before_publish: Callable[[UUID], None] | None = None,
) -> bool:
@@ -45,24 +49,33 @@ async def publish_next_job(
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,
))
await broker.publish_job(
JobMessage(
job_id=job.id,
attachment_id=job.attachment_id,
pipeline_version=job.pipeline_version,
attempt=job.attempt + 1,
created_at=job.created_at,
)
)
outbox.mark_published(job)
await session.commit()
return published
async def claim_job(session: AsyncSession, message: JobMessage, settings: JobSettings) -> Claim:
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:
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:
@@ -77,16 +90,32 @@ async def claim_job(session: AsyncSession, message: JobMessage, settings: JobSet
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)
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))
result = Claim(
work=jobs.start_job(
job, attachment, uuid4(), now, settings.job_lease_seconds
)
)
await session.commit()
return result
async def save_failure(session: AsyncSession, work: JobWork, settings: JobSettings, code: str, *, permanent: bool) -> None:
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)
@@ -95,10 +124,14 @@ async def save_failure(session: AsyncSession, work: JobWork, settings: JobSettin
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),
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),
retry_seconds=retry_delay(
settings, job.attempt - job.cycle_start_attempt
),
)
job.last_error_code = code
job.last_error_permanent = permanent
@@ -106,7 +139,9 @@ async def save_failure(session: AsyncSession, work: JobWork, settings: JobSettin
async def build_result(
session: AsyncSession, storage: MinioStorage, work: JobWork,
session: AsyncSession,
storage: MinioStorage,
work: JobWork,
after_object: Callable[[UUID, str], None] | None = None,
) -> bool:
"""Фиксированные ключи и блокировка job защищают PUT от устаревшей попытки."""
@@ -129,26 +164,42 @@ async def build_result(
# Блокировка остаётся до завершения 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,
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,
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))
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,
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)
@@ -160,7 +211,13 @@ async def process_attachment_job(
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:
except (
ProcessingError,
MinioException,
StorageHTTPError,
OSError,
TimeoutError,
) as error:
code, permanent = classify_failure(error)
await save_failure(session, work, settings, code, permanent=permanent)
acknowledge = True
@@ -176,8 +233,12 @@ async def recover_expired_jobs(session: AsyncSession, settings: JobSettings) ->
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,
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
@@ -185,8 +246,14 @@ async def recover_expired_jobs(session: AsyncSession, settings: JobSettings) ->
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)
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: