chore: port lab 6 solution into the lab 7 skeleton
Source: mtusi2026lab6-safronov, solution/bvt2301-safronov, 6c6a065. Files follow AGENTS.md, "Переход в следующую лабу". Contracts, public tests, README, REPORT and evidence of lab 6 are not carried over; infra and scripts of the lab 7 skeleton stay as they are. Makefile is the lab 6 one with the lab 7 skeleton part restored (HTTPS BASE_URL on 8443, test-security); .gitignore and .dockerignore are taken from lab 6 because both skeletons have the same files; .env.example is the lab 6 one without changes. The compose project, image and CI prefix are renamed to lab7, and references to the previous lab now name lab6. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,209 @@
|
||||
"""Реестр `failed` и replay (design change `pipeline-reliability`, решение 5).
|
||||
|
||||
Реестр — строки `attachment_jobs` с `state = 'failed'`. Replay одного задания —
|
||||
одна транзакция, порядок блокировок общий: задание, затем вложение. Вложение `failed`
|
||||
→ `queued`, задание `queued` с новым бюджетом (`attempt_base = attempt`), запись аудита;
|
||||
сообщение публикует relay. Готовая работа, идущая работа и задание без исходника —
|
||||
отказ без изменений: повторить — не значит исполнить дубль. Блокировка строки вложения
|
||||
исключает гонку с очисткой staging.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable, Sequence
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from src.core.ports.uow import AbstractUnitOfWork
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.schemas import dataclasses
|
||||
from src.schemas.enums import AttachmentJobState, AttachmentStatus
|
||||
from src.utils.constants import ATTACHMENT_PIPELINE_VERSION
|
||||
from src.utils.utc import utcnow
|
||||
|
||||
logger: AbstractLogger = get_logger().bind(module="attachment_replay_service")
|
||||
|
||||
REFUSAL_NOT_FOUND = "not_found"
|
||||
REFUSAL_ALREADY_READY = "already_ready"
|
||||
REFUSAL_NOT_FAILED = "not_failed"
|
||||
REFUSAL_SOURCE_GONE = "source_gone"
|
||||
|
||||
|
||||
def _never() -> bool:
|
||||
return False
|
||||
|
||||
|
||||
class AttachmentReplayService:
|
||||
"""`uow` — единица работы процесса команды; брокер и S3 не нужны."""
|
||||
|
||||
def __init__(self, uow: AbstractUnitOfWork) -> None:
|
||||
self.uow = uow
|
||||
|
||||
async def replay_pass(
|
||||
self,
|
||||
*,
|
||||
attachment_ids: Sequence[UUID],
|
||||
error_code: str | None,
|
||||
reason: str | None,
|
||||
limit: int,
|
||||
apply: bool,
|
||||
operator: str,
|
||||
stop_requested: Callable[[], bool] = _never,
|
||||
) -> dataclasses.ReplayPassDTO:
|
||||
"""Показать выбранное или выполнить replay. Выбор — по `id` вложений
|
||||
либо по коду и причине, не больше `limit`; без выбора — весь реестр в
|
||||
пределах `limit` (только показ: `--apply` без выбора отвергает команда).
|
||||
Отказ PostgreSQL — `ServiceUnavailable` вызывающему."""
|
||||
log = logger.bind(method="replay", apply=apply)
|
||||
ids = list(attachment_ids[:limit])
|
||||
if not ids:
|
||||
async with self.uow:
|
||||
rows = await self.uow.jobs.list_failed(
|
||||
error_code=error_code,
|
||||
reason=reason,
|
||||
limit=limit,
|
||||
)
|
||||
ids = [row.attachment_id for row in rows]
|
||||
shown = 0
|
||||
replayed = 0
|
||||
refused = 0
|
||||
interrupted = False
|
||||
for attachment_id in ids:
|
||||
if stop_requested():
|
||||
interrupted = True
|
||||
break
|
||||
result = await self.replay_one(
|
||||
attachment_id=attachment_id,
|
||||
apply=apply,
|
||||
operator=operator,
|
||||
)
|
||||
if result.refusal is not None:
|
||||
refused += 1
|
||||
log.warning(
|
||||
"Refused job replay",
|
||||
attachment_id=result.attachment_id,
|
||||
job_id=result.job_id,
|
||||
refusal=result.refusal,
|
||||
)
|
||||
elif apply:
|
||||
replayed += 1
|
||||
log.info(
|
||||
"Replayed job",
|
||||
attachment_id=result.attachment_id,
|
||||
job_id=result.job_id,
|
||||
operator=operator,
|
||||
error_code=result.error_code,
|
||||
reason=result.reason,
|
||||
attempt=result.attempt,
|
||||
)
|
||||
else:
|
||||
shown += 1
|
||||
log.info(
|
||||
"Found failed job",
|
||||
attachment_id=result.attachment_id,
|
||||
job_id=result.job_id,
|
||||
error_code=result.error_code,
|
||||
reason=result.reason,
|
||||
attempt=result.attempt,
|
||||
finished_at=(
|
||||
None
|
||||
if result.finished_at is None
|
||||
else result.finished_at.isoformat()
|
||||
),
|
||||
)
|
||||
pass_result = dataclasses.ReplayPassDTO(
|
||||
shown=shown,
|
||||
replayed=replayed,
|
||||
refused=refused,
|
||||
interrupted=interrupted,
|
||||
)
|
||||
log.info(
|
||||
"Finished replay pass",
|
||||
shown=shown,
|
||||
replayed=replayed,
|
||||
refused=refused,
|
||||
interrupted=interrupted,
|
||||
)
|
||||
return pass_result
|
||||
|
||||
async def replay_one(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
apply: bool,
|
||||
operator: str,
|
||||
) -> dataclasses.ReplayResultDTO:
|
||||
"""Проверки под блокировками, с `apply` — запись одной транзакцией. Без
|
||||
`apply` транзакция откатывается: команда только называет, что сделала
|
||||
бы."""
|
||||
async with self.uow:
|
||||
found = await self.uow.jobs.get_attachment_job(
|
||||
attachment_id=attachment_id,
|
||||
pipeline_version=ATTACHMENT_PIPELINE_VERSION,
|
||||
)
|
||||
job = (
|
||||
None
|
||||
if found is None
|
||||
else await self.uow.jobs.lock_job(job_id=found.id)
|
||||
)
|
||||
attachment = await self.uow.attachments.lock_attachment(
|
||||
attachment_id=attachment_id,
|
||||
)
|
||||
refusal = self._refusal(job=job, attachment=attachment)
|
||||
if refusal is not None:
|
||||
return dataclasses.ReplayResultDTO(
|
||||
attachment_id=attachment_id,
|
||||
job_id=None if job is None else job.id,
|
||||
refusal=refusal,
|
||||
)
|
||||
error_code = (
|
||||
None
|
||||
if attachment.error_code is None
|
||||
else attachment.error_code.value
|
||||
)
|
||||
if apply:
|
||||
now = utcnow()
|
||||
await self.uow.attachments.replay_failed(
|
||||
attachment_id=attachment_id,
|
||||
updated_at=now,
|
||||
)
|
||||
await self.uow.jobs.replay_job(job_id=job.id, now=now)
|
||||
await self.uow.job_replays.insert_replay(
|
||||
replay=dataclasses.AttachmentJobReplayDTO(
|
||||
id=uuid4(),
|
||||
job_id=job.id,
|
||||
operator=operator,
|
||||
error_code=error_code,
|
||||
reason=job.last_error_code,
|
||||
attempt=job.attempt,
|
||||
created_at=now,
|
||||
),
|
||||
)
|
||||
await self.uow.commit()
|
||||
return dataclasses.ReplayResultDTO(
|
||||
attachment_id=attachment_id,
|
||||
job_id=job.id,
|
||||
refusal=None,
|
||||
error_code=error_code,
|
||||
reason=job.last_error_code,
|
||||
attempt=job.attempt,
|
||||
finished_at=job.finished_at,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _refusal(
|
||||
*,
|
||||
job: dataclasses.AttachmentJobDTO | None,
|
||||
attachment: dataclasses.AttachmentFullDTO | None,
|
||||
) -> str | None:
|
||||
if attachment is None:
|
||||
return REFUSAL_NOT_FOUND
|
||||
if attachment.status == AttachmentStatus.READY:
|
||||
return REFUSAL_ALREADY_READY
|
||||
if job is None:
|
||||
return REFUSAL_NOT_FOUND
|
||||
if (
|
||||
job.state != AttachmentJobState.FAILED
|
||||
or attachment.status != AttachmentStatus.FAILED
|
||||
):
|
||||
return REFUSAL_NOT_FAILED
|
||||
if attachment.staging_key is None:
|
||||
return REFUSAL_SOURCE_GONE
|
||||
return None
|
||||
Reference in New Issue
Block a user