"""`AttachmentRelayService`: порядок публикации, предел, аренды, потерянные.""" from dataclasses import replace from datetime import timedelta from uuid import uuid4 import pytest from builders import attachment_dto, job_dto from fakes import FakeDatabase, FakeJobPublisher, FakeUnitOfWork from src.core import exceptions from src.core.services.attachment_relay import AttachmentRelayService from src.schemas import dataclasses from src.schemas.enums import ( AttachmentJobReason, AttachmentJobState, AttachmentStatus, ) from src.utils.utc import utcnow pytestmark = pytest.mark.anyio @pytest.fixture def service( uow: FakeUnitOfWork, publisher: FakeJobPublisher, ) -> AttachmentRelayService: return AttachmentRelayService(uow, publisher) async def _jobs( uow: FakeUnitOfWork, database: FakeDatabase, count: int = 1, ) -> list[dataclasses.AttachmentJobDTO]: now = utcnow() - timedelta(seconds=1) jobs = [] async with uow: for index in range(count): row = attachment_dto( chat_id=uuid4(), owner_id=uuid4(), status=AttachmentStatus.QUEUED, created_at=now, ) job = job_dto( attachment_id=row.id, created_at=now + timedelta(milliseconds=index), ) await uow.attachments.insert_attachment(attachment=row) await uow.jobs.insert_job(job=job) jobs.append(job) await uow.commit() database.events.clear() return jobs async def _pass( service: AttachmentRelayService, *, batch_size: int = 10, max_backlog: int = 100, stop_requested=None, ): return await service.publish_pass( batch_size=batch_size, max_published_backlog=max_backlog, republish_after_seconds=60, **( {} if stop_requested is None else {"stop_requested": stop_requested} ), ) async def test_publish_order_in_one_block( service: AttachmentRelayService, uow: FakeUnitOfWork, database: FakeDatabase, ) -> None: """Сценарий «Порядок публикации».""" jobs = await _jobs(uow, database, 2) result = await _pass(service) assert result.published == 2 start = database.events.index("jobs.lock_due_jobs") assert database.events[start:] == [ "jobs.lock_due_jobs", "publisher.publish_many", "jobs.mark_published", "commit", "exit", ] assert database.inside_block("publisher.publish_many") assert all(database.jobs[job.id].published_at for job in jobs) async def test_confirmed_subset_marked( service: AttachmentRelayService, uow: FakeUnitOfWork, publisher: FakeJobPublisher, database: FakeDatabase, ) -> None: first, second = await _jobs(uow, database, 2) publisher.unconfirmed = {second.id} result = await _pass(service) assert result.published == 1 assert result.unconfirmed == 1 assert database.jobs[first.id].published_at is not None assert database.jobs[second.id].published_at is None async def test_nothing_confirmed_no_mark( service: AttachmentRelayService, uow: FakeUnitOfWork, publisher: FakeJobPublisher, database: FakeDatabase, ) -> None: (first,) = await _jobs(uow, database, 1) publisher.unconfirmed = {first.id} result = await _pass(service) assert result.unconfirmed == 1 assert "jobs.mark_published" not in database.events async def test_backlog_limit( service: AttachmentRelayService, uow: FakeUnitOfWork, publisher: FakeJobPublisher, database: FakeDatabase, ) -> None: jobs = await _jobs(uow, database, 3) result = await _pass(service, max_backlog=2) assert result.published == 2 assert result.published_backlog == 2 assert not result.backlog_full publisher.published.clear() result = await _pass(service, max_backlog=2) assert result.published == 0 assert result.backlog_full assert publisher.published == [] assert database.jobs[jobs[2].id].published_at is None async def test_held_job_skipped( service: AttachmentRelayService, uow: FakeUnitOfWork, database: FakeDatabase, publisher: FakeJobPublisher, ) -> None: first, second = await _jobs(uow, database, 2) database.held.add(first.id) await _pass(service) assert publisher.published == [second.id] async def test_expired_leases_one_block( service: AttachmentRelayService, uow: FakeUnitOfWork, database: FakeDatabase, ) -> None: (job,) = await _jobs(uow, database, 1) async with uow: await uow.jobs.start_attempt( job_id=job.id, lease_expires_at=utcnow() - timedelta(seconds=1), now=utcnow(), ) await uow.attachments.mark_processing( attachment_id=job.attachment_id, updated_at=utcnow(), ) await uow.commit() database.events.clear() result = await _pass(service) assert result.recovered == 1 assert database.events[:4] == [ "enter", "jobs.recover_expired_leases", "attachments.return_group_to_queued", "commit", ] stored = database.jobs[job.id] assert stored.last_error_code == AttachmentJobReason.LEASE_EXPIRED.value assert database.attachments[job.attachment_id].status == ( AttachmentStatus.QUEUED ) async def _published_long_ago( uow: FakeUnitOfWork, database: FakeDatabase, ) -> dataclasses.AttachmentJobDTO: (job,) = await _jobs(uow, database, 1) database.jobs[job.id] = replace( database.jobs[job.id], published_at=utcnow() - timedelta(seconds=600), ) database.events.clear() return job async def test_lost_messages_reset_at_zero_ready( service: AttachmentRelayService, uow: FakeUnitOfWork, database: FakeDatabase, publisher: FakeJobPublisher, ) -> None: job = await _published_long_ago(uow, database) publisher.ready = 0 result = await _pass(service) assert result.republished == 1 # тем же проходом опубликовано заново assert result.published == 1 assert database.jobs[job.id].published_at is not None assert not database.inside_block("publisher.ready_messages") async def test_lost_messages_kept_when_queue_has_ready( service: AttachmentRelayService, uow: FakeUnitOfWork, database: FakeDatabase, publisher: FakeJobPublisher, ) -> None: await _published_long_ago(uow, database) publisher.ready = 5 result = await _pass(service) assert result.republished == 0 assert "jobs.reset_published_before" not in database.events async def test_broker_not_asked_without_candidates( service: AttachmentRelayService, uow: FakeUnitOfWork, database: FakeDatabase, ) -> None: await _jobs(uow, database, 1) await _pass(service) assert "publisher.ready_messages" not in database.events @pytest.mark.parametrize( ("ready_calls", "expected_absent"), [ (1, ["jobs.has_published_before", "jobs.lock_due_jobs"]), (2, ["jobs.lock_due_jobs"]), ], ids=["after_recover", "after_lost"], ) async def test_stop_between_steps( service: AttachmentRelayService, uow: FakeUnitOfWork, database: FakeDatabase, ready_calls: int, expected_absent: list[str], ) -> None: await _jobs(uow, database, 1) calls = 0 def stop_requested() -> bool: nonlocal calls calls += 1 return calls >= ready_calls result = await _pass(service, stop_requested=stop_requested) assert result.published == 0 for name in expected_absent: assert name not in database.events async def test_broker_failure_rolls_back_block( service: AttachmentRelayService, uow: FakeUnitOfWork, database: FakeDatabase, ) -> None: (job,) = await _jobs(uow, database, 1) database.fail_on["publisher.publish_many"] = exceptions.BrokerUnavailable() with pytest.raises(exceptions.BrokerUnavailable): await _pass(service) stored = database.jobs[job.id] assert stored.published_at is None assert stored.state == AttachmentJobState.QUEUED