Files
mtusi2026lab6/service-tests/repo_contract.py
T

1520 lines
50 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Один набор проверок условий repo на фейке и на настоящем SQL (design change
`unit-of-work`, решение 11).
`unit/test_repo_contract.py` гоняет его на фейке, `db/test_repo_contract_sql.py`
— на временной базе. Данные — только через методы портов и явное время. Каждая
проверка получает `new_uow`: новая единица работы над чистыми данными. Имя
проверки называет метод: если разошлись фейк и SQL, чинится фейк, выражения на SQL
этим изменением не меняются.
"""
from collections.abc import Callable
from dataclasses import dataclass, replace
from datetime import datetime
from uuid import UUID, uuid4
from builders import (
NOW,
PASSWORD_HASH,
at,
attachment_dto,
chat_dto,
job_dto,
message_dto,
user_dto,
variant_dto,
)
from src.core.ports.uow import AbstractUnitOfWork
from src.schemas import dataclasses
from src.schemas.enums import (
AttachmentErrorCode,
AttachmentJobReason,
AttachmentJobState,
AttachmentStatus,
AttachmentVariantName,
)
type NewUow = Callable[[], AbstractUnitOfWork]
@dataclass(frozen=True, slots=True)
class _World:
user_id: UUID
other_id: UUID
chat_id: UUID
async def _world(new_uow: NewUow) -> _World:
user = user_dto()
other = user_dto()
chat = chat_dto(member_ids=(user.id, other.id))
async with new_uow() as uow:
await uow.users.insert_user(user=user, password_hash=PASSWORD_HASH)
await uow.users.insert_user(user=other, password_hash=PASSWORD_HASH)
await uow.chats.insert_chat(chat=chat)
await uow.chats.insert_chat_members(chat=chat)
await uow.commit()
return _World(user.id, other.id, chat.id)
async def _attachment(
new_uow: NewUow,
world: _World,
*,
status: AttachmentStatus = AttachmentStatus.PENDING,
created_at: datetime = NOW,
updated_at: datetime | None = None,
staging: bool = True,
object_key: str | None = None,
) -> dataclasses.AttachmentFullDTO:
attachment = attachment_dto(
chat_id=world.chat_id,
owner_id=world.user_id,
status=status,
created_at=created_at,
updated_at=updated_at,
staging=staging,
object_key=object_key,
)
async with new_uow() as uow:
await uow.attachments.insert_attachment(attachment=attachment)
await uow.commit()
return attachment
async def _failed_attachment(
new_uow: NewUow,
world: _World,
*,
code: AttachmentErrorCode = AttachmentErrorCode.INVALID_IMAGE,
updated_at: datetime = NOW,
staging: bool = True,
) -> dataclasses.AttachmentFullDTO:
attachment = await _attachment(
new_uow,
world,
status=AttachmentStatus.QUEUED,
staging=staging,
)
async with new_uow() as uow:
assert await uow.attachments.commit_failed(
attachment_id=attachment.id,
error_code=code,
updated_at=updated_at,
)
await uow.commit()
return attachment
async def _row(
new_uow: NewUow,
attachment_id: UUID,
) -> dataclasses.AttachmentFullDTO | None:
async with new_uow() as uow:
return await uow.attachments.get_attachment(
attachment_id=attachment_id,
)
async def _job_row(
new_uow: NewUow,
job_id: UUID,
) -> dataclasses.AttachmentJobDTO | None:
async with new_uow() as uow:
return await uow.jobs.get_job(job_id=job_id)
async def _job(
new_uow: NewUow,
world: _World,
*,
created_at: datetime = NOW,
) -> dataclasses.AttachmentJobDTO:
attachment = await _attachment(
new_uow,
world,
status=AttachmentStatus.QUEUED,
created_at=created_at,
)
job = job_dto(attachment_id=attachment.id, created_at=created_at)
async with new_uow() as uow:
await uow.jobs.insert_job(job=job)
await uow.commit()
return job
async def _started_job(
new_uow: NewUow,
world: _World,
*,
lease_expires_at: datetime = NOW,
) -> dataclasses.AttachmentJobDTO:
job = await _job(new_uow, world)
async with new_uow() as uow:
started = await uow.jobs.start_attempt(
job_id=job.id,
lease_expires_at=lease_expires_at,
now=NOW,
)
await uow.commit()
assert started is not None
return started
async def _failed_job(
new_uow: NewUow,
world: _World,
*,
code: AttachmentErrorCode = AttachmentErrorCode.INVALID_IMAGE,
reason: AttachmentJobReason = AttachmentJobReason.UNDECODABLE,
finished_at: datetime = NOW,
) -> dataclasses.AttachmentJobDTO:
attachment = await _failed_attachment(new_uow, world, code=code)
job = job_dto(attachment_id=attachment.id)
async with new_uow() as uow:
await uow.jobs.insert_job(job=job)
await uow.jobs.finish_job(
job_id=job.id,
state=AttachmentJobState.FAILED,
reason=reason,
now=finished_at,
)
await uow.commit()
return job
# ---------------------------------------------------------------- вложения
async def check_mark_queued(new_uow: NewUow) -> None:
world = await _world(new_uow)
row = await _attachment(new_uow, world)
async with new_uow() as uow:
queued = await uow.attachments.mark_queued(
attachment_id=row.id,
updated_at=at(10),
)
await uow.commit()
assert queued is not None
assert queued.status == AttachmentStatus.QUEUED
assert queued.updated_at == at(10)
async with new_uow() as uow:
# уже не pending
assert (
await uow.attachments.mark_queued(
attachment_id=row.id,
updated_at=at(20),
)
is None
)
assert (
await uow.attachments.mark_queued(
attachment_id=uuid4(),
updated_at=at(20),
)
is None
)
async def check_mark_queued_marked_row(new_uow: NewUow) -> None:
"""Помеченную уборщиком строку не переводит."""
world = await _world(new_uow)
row = await _attachment(new_uow, world)
async with new_uow() as uow:
await uow.attachments.mark_removing(
attachment_id=row.id,
updated_at=at(5),
)
await uow.commit()
async with new_uow() as uow:
assert (
await uow.attachments.mark_queued(
attachment_id=row.id,
updated_at=at(10),
)
is None
)
async def check_mark_queued_clock_behind(new_uow: NewUow) -> None:
"""Часы отстают: `updated_at` не уходит назад."""
world = await _world(new_uow)
row = await _attachment(new_uow, world)
async with new_uow() as uow:
queued = await uow.attachments.mark_queued(
attachment_id=row.id,
updated_at=at(-100),
)
await uow.commit()
assert queued is not None
assert queued.updated_at == row.updated_at
async def check_mark_processing(new_uow: NewUow) -> None:
world = await _world(new_uow)
expected = {
AttachmentStatus.QUEUED: True,
AttachmentStatus.PROCESSING: True,
AttachmentStatus.READY: False,
AttachmentStatus.PENDING: False,
}
for status, result in expected.items():
row = await _attachment(new_uow, world, status=status)
async with new_uow() as uow:
assert (
await uow.attachments.mark_processing(
attachment_id=row.id,
updated_at=at(1),
)
is result
), status
failed = await _failed_attachment(new_uow, world)
async with new_uow() as uow:
assert not await uow.attachments.mark_processing(
attachment_id=failed.id,
updated_at=at(1),
)
async def check_attachment_return_to_queued(new_uow: NewUow) -> None:
world = await _world(new_uow)
processing = await _attachment(
new_uow,
world,
status=AttachmentStatus.PROCESSING,
)
queued = await _attachment(new_uow, world, status=AttachmentStatus.QUEUED)
async with new_uow() as uow:
assert await uow.attachments.return_to_queued(
attachment_id=processing.id,
updated_at=at(1),
)
assert not await uow.attachments.return_to_queued(
attachment_id=queued.id,
updated_at=at(1),
)
await uow.commit()
changed = await _row(new_uow, processing.id)
assert changed is not None
assert changed.status == AttachmentStatus.QUEUED
async def check_return_group_to_queued(new_uow: NewUow) -> None:
world = await _world(new_uow)
first = await _attachment(
new_uow,
world,
status=AttachmentStatus.PROCESSING,
)
second = await _attachment(
new_uow,
world,
status=AttachmentStatus.PROCESSING,
)
ready = await _attachment(new_uow, world, status=AttachmentStatus.READY)
async with new_uow() as uow:
count = await uow.attachments.return_group_to_queued(
attachment_ids=[first.id, second.id, ready.id, uuid4()],
updated_at=at(1),
)
await uow.commit()
assert count == 2
unchanged = await _row(new_uow, ready.id)
assert unchanged is not None
assert unchanged.status == AttachmentStatus.READY
async def check_replay_failed(new_uow: NewUow) -> None:
world = await _world(new_uow)
failed = await _failed_attachment(new_uow, world)
queued = await _attachment(new_uow, world, status=AttachmentStatus.QUEUED)
async with new_uow() as uow:
assert await uow.attachments.replay_failed(
attachment_id=failed.id,
updated_at=at(1),
)
assert not await uow.attachments.replay_failed(
attachment_id=queued.id,
updated_at=at(1),
)
await uow.commit()
row = await _row(new_uow, failed.id)
assert row is not None
assert row.status == AttachmentStatus.QUEUED
assert row.error_code is None
async def check_commit_ready(new_uow: NewUow) -> None:
world = await _world(new_uow)
for status in (AttachmentStatus.QUEUED, AttachmentStatus.PROCESSING):
row = await _attachment(new_uow, world, status=status)
async with new_uow() as uow:
assert await uow.attachments.commit_ready(
attachment_id=row.id,
updated_at=at(1),
)
await uow.commit()
ready = await _row(new_uow, row.id)
assert ready is not None
assert ready.status == AttachmentStatus.READY
# итог уже есть: updated_at не меняется
async with new_uow() as uow:
assert not await uow.attachments.commit_ready(
attachment_id=row.id,
updated_at=at(50),
)
await uow.commit()
again = await _row(new_uow, row.id)
assert again is not None
assert again.updated_at == at(1)
failed = await _failed_attachment(new_uow, world)
async with new_uow() as uow:
assert not await uow.attachments.commit_ready(
attachment_id=failed.id,
updated_at=at(1),
)
async def check_commit_failed(new_uow: NewUow) -> None:
world = await _world(new_uow)
row = await _attachment(
new_uow,
world,
status=AttachmentStatus.PROCESSING,
)
ready = await _attachment(new_uow, world, status=AttachmentStatus.READY)
async with new_uow() as uow:
assert await uow.attachments.commit_failed(
attachment_id=row.id,
error_code=AttachmentErrorCode.PROCESSING_FAILED,
updated_at=at(1),
)
assert not await uow.attachments.commit_failed(
attachment_id=ready.id,
error_code=AttachmentErrorCode.PROCESSING_FAILED,
updated_at=at(1),
)
await uow.commit()
failed = await _row(new_uow, row.id)
assert failed is not None
assert failed.status == AttachmentStatus.FAILED
assert failed.error_code == AttachmentErrorCode.PROCESSING_FAILED
async def check_get_stale_pending(new_uow: NewUow) -> None:
world = await _world(new_uow)
first = await _attachment(new_uow, world, created_at=at(-30))
second = await _attachment(new_uow, world, created_at=at(-20))
third = await _attachment(new_uow, world, created_at=at(-10))
await _attachment(new_uow, world, created_at=at(10))
await _attachment(
new_uow,
world,
status=AttachmentStatus.READY,
created_at=at(-40),
)
async with new_uow() as uow:
page = await uow.attachments.get_stale_pending(
older_than=NOW,
after=None,
limit=2,
)
rest = await uow.attachments.get_stale_pending(
older_than=NOW,
after=(page[-1].created_at, page[-1].id),
limit=2,
)
assert [item.id for item in page] == [first.id, second.id]
assert [item.id for item in rest] == [third.id]
assert page[0].object_key == first.object_key
assert page[0].staging_key == first.staging_key
async def check_lock_stale_pending(new_uow: NewUow) -> None:
world = await _world(new_uow)
old = await _attachment(new_uow, world, created_at=at(-30))
young = await _attachment(new_uow, world, created_at=at(30))
ready = await _attachment(
new_uow,
world,
status=AttachmentStatus.READY,
created_at=at(-30),
)
async with new_uow() as uow:
found = await uow.attachments.lock_stale_pending(
attachment_id=old.id,
older_than=NOW,
)
assert found is not None
assert found.id == old.id
for other in (young.id, ready.id, uuid4()):
assert (
await uow.attachments.lock_stale_pending(
attachment_id=other,
older_than=NOW,
)
is None
)
async def check_mark_removing(new_uow: NewUow) -> None:
world = await _world(new_uow)
row = await _attachment(new_uow, world)
async with new_uow() as uow:
assert await uow.attachments.mark_removing(
attachment_id=row.id,
updated_at=at(7),
)
assert not await uow.attachments.mark_removing(
attachment_id=uuid4(),
updated_at=at(7),
)
await uow.commit()
marked = await _row(new_uow, row.id)
assert marked is not None
assert marked.updated_at == at(7)
async def check_delete_attachment(new_uow: NewUow) -> None:
world = await _world(new_uow)
row = await _attachment(new_uow, world)
async with new_uow() as uow:
assert await uow.attachments.delete_attachment(attachment_id=row.id)
assert not await uow.attachments.delete_attachment(
attachment_id=row.id,
)
await uow.commit()
assert await _row(new_uow, row.id) is None
async def check_get_staging_candidates(new_uow: NewUow) -> None:
world = await _world(new_uow)
first = await _attachment(
new_uow,
world,
status=AttachmentStatus.READY,
created_at=at(-30),
)
second = await _attachment(
new_uow,
world,
status=AttachmentStatus.READY,
created_at=at(-20),
)
await _attachment(
new_uow,
world,
status=AttachmentStatus.READY,
staging=False,
)
await _attachment(new_uow, world, status=AttachmentStatus.QUEUED)
async with new_uow() as uow:
page = await uow.attachments.get_staging_candidates(
status=AttachmentStatus.READY,
updated_before=None,
after=None,
limit=1,
)
rest = await uow.attachments.get_staging_candidates(
status=AttachmentStatus.READY,
updated_before=None,
after=(page[0].updated_at, page[0].id),
limit=10,
)
bounded = await uow.attachments.get_staging_candidates(
status=AttachmentStatus.READY,
updated_before=at(-25),
after=None,
limit=10,
)
assert [item.id for item in page] == [first.id]
assert [item.id for item in rest] == [second.id]
assert [item.id for item in bounded] == [first.id]
assert page[0].status == AttachmentStatus.READY
assert page[0].updated_at == first.updated_at
assert page[0].staging_key == first.staging_key
async def check_lock_staging_candidate(new_uow: NewUow) -> None:
world = await _world(new_uow)
row = await _attachment(
new_uow,
world,
status=AttachmentStatus.READY,
created_at=at(-30),
)
bare = await _attachment(
new_uow,
world,
status=AttachmentStatus.READY,
staging=False,
)
async with new_uow() as uow:
found = await uow.attachments.lock_staging_candidate(
attachment_id=row.id,
status=AttachmentStatus.READY,
updated_before=None,
)
assert found is not None
assert found.staging_key == row.staging_key
assert (
await uow.attachments.lock_staging_candidate(
attachment_id=row.id,
status=AttachmentStatus.FAILED,
updated_before=None,
)
is None
)
assert (
await uow.attachments.lock_staging_candidate(
attachment_id=row.id,
status=AttachmentStatus.READY,
updated_before=at(-40),
)
is None
)
assert (
await uow.attachments.lock_staging_candidate(
attachment_id=bare.id,
status=AttachmentStatus.READY,
updated_before=None,
)
is None
)
async def check_clear_staging_key(new_uow: NewUow) -> None:
world = await _world(new_uow)
row = await _attachment(new_uow, world, status=AttachmentStatus.READY)
async with new_uow() as uow:
assert await uow.attachments.clear_staging_key(attachment_id=row.id)
assert not await uow.attachments.clear_staging_key(
attachment_id=uuid4(),
)
await uow.commit()
cleared = await _row(new_uow, row.id)
assert cleared is not None
assert cleared.staging_key is None
assert cleared.updated_at == row.updated_at
async def check_get_attachments_for_objects(new_uow: NewUow) -> None:
world = await _world(new_uow)
by_id = await _attachment(new_uow, world)
by_key = await _attachment(new_uow, world)
await _attachment(new_uow, world)
async with new_uow() as uow:
rows = await uow.attachments.get_attachments_for_objects(
attachment_ids=[by_id.id],
object_keys=[by_key.object_key],
)
empty = await uow.attachments.get_attachments_for_objects(
attachment_ids=[],
object_keys=[],
)
assert {row.id for row in rows} == {by_id.id, by_key.id}
assert empty == []
async def check_get_ready_page(new_uow: NewUow) -> None:
world = await _world(new_uow)
rows = [
await _attachment(new_uow, world, status=AttachmentStatus.READY)
for _ in range(3)
]
await _attachment(new_uow, world)
expected = sorted(row.id for row in rows)
async with new_uow() as uow:
page = await uow.attachments.get_ready_page(after=None, limit=2)
rest = await uow.attachments.get_ready_page(
after=page[-1].id,
limit=2,
)
assert [row.id for row in page] == expected[:2]
assert [row.id for row in rest] == expected[2:]
async def check_find_attachment_reference(new_uow: NewUow) -> None:
world = await _world(new_uow)
row = await _attachment(new_uow, world)
other = await _attachment(new_uow, world)
async with new_uow() as uow:
by_id = await uow.attachments.find_attachment_reference(
attachment_id=row.id,
object_key="absent",
)
by_key = await uow.attachments.find_attachment_reference(
attachment_id=uuid4(),
object_key=other.object_key,
)
both = await uow.attachments.find_attachment_reference(
attachment_id=row.id,
object_key=other.object_key,
)
none = await uow.attachments.find_attachment_reference(
attachment_id=uuid4(),
object_key="absent",
)
assert [item.id for item in by_id] == [row.id]
assert [item.id for item in by_key] == [other.id]
assert {item.id for item in both} == {row.id, other.id}
assert none == []
async def check_mark_lost_clear_lost(new_uow: NewUow) -> None:
world = await _world(new_uow)
row = await _attachment(new_uow, world, status=AttachmentStatus.READY)
queued = await _attachment(new_uow, world, status=AttachmentStatus.QUEUED)
async with new_uow() as uow:
repo = uow.attachments
assert not await repo.clear_lost(
attachment_id=row.id,
object_key=row.object_key,
)
assert not await repo.mark_lost(
attachment_id=row.id,
object_key="other",
lost_at=at(1),
)
assert not await repo.mark_lost(
attachment_id=queued.id,
object_key=queued.object_key,
lost_at=at(1),
)
assert await repo.mark_lost(
attachment_id=row.id,
object_key=row.object_key,
lost_at=at(1),
)
assert not await repo.mark_lost(
attachment_id=row.id,
object_key=row.object_key,
lost_at=at(2),
)
await uow.commit()
lost = await _row(new_uow, row.id)
assert lost is not None
assert lost.lost_at == at(1)
assert lost.status == AttachmentStatus.READY
assert lost.updated_at == row.updated_at
async with new_uow() as uow:
assert not await uow.attachments.clear_lost(
attachment_id=row.id,
object_key="other",
)
assert await uow.attachments.clear_lost(
attachment_id=row.id,
object_key=row.object_key,
)
await uow.commit()
cleared = await _row(new_uow, row.id)
assert cleared is not None
assert cleared.lost_at is None
async def check_get_attachments(new_uow: NewUow) -> None:
world = await _world(new_uow)
row = await _attachment(new_uow, world)
async with new_uow() as uow:
found = await uow.attachments.get_attachments(
attachment_ids=[row.id, uuid4()],
)
locked = await uow.attachments.lock_attachment(attachment_id=row.id)
absent = await uow.attachments.lock_attachment(attachment_id=uuid4())
assert [item.id for item in found] == [row.id]
assert locked is not None
assert locked.id == row.id
assert absent is None
# ---------------------------------------------------------------- задания
async def check_start_attempt(new_uow: NewUow) -> None:
world = await _world(new_uow)
job = await _job(new_uow, world)
async with new_uow() as uow:
started = await uow.jobs.start_attempt(
job_id=job.id,
lease_expires_at=at(70),
now=at(1),
)
missing = await uow.jobs.start_attempt(
job_id=uuid4(),
lease_expires_at=at(70),
now=at(1),
)
await uow.commit()
assert missing is None
assert started is not None
assert started.state == AttachmentJobState.PROCESSING
assert started.attempt == 1
assert started.lease_expires_at == at(70)
assert started.next_attempt_at is None
assert started.updated_at == at(1)
async def check_job_return_to_queued(new_uow: NewUow) -> None:
world = await _world(new_uow)
job = await _started_job(new_uow, world, lease_expires_at=at(70))
async with new_uow() as uow:
# чужая попытка
assert not await uow.jobs.return_to_queued(
job_id=job.id,
attempt=job.attempt + 1,
reason=AttachmentJobReason.TIMEOUT,
next_attempt_at=at(5),
now=at(1),
)
assert await uow.jobs.return_to_queued(
job_id=job.id,
attempt=job.attempt,
reason=AttachmentJobReason.TIMEOUT,
next_attempt_at=at(5),
now=at(1),
)
# уже queued
assert not await uow.jobs.return_to_queued(
job_id=job.id,
attempt=job.attempt,
reason=AttachmentJobReason.TIMEOUT,
next_attempt_at=at(5),
now=at(1),
)
await uow.commit()
row = await _job_row(new_uow, job.id)
assert row is not None
assert row.state == AttachmentJobState.QUEUED
assert row.last_error_code == AttachmentJobReason.TIMEOUT.value
assert row.next_attempt_at == at(5)
assert row.lease_expires_at is None
assert row.published_at is None
async def check_finish_job(new_uow: NewUow) -> None:
world = await _world(new_uow)
job = await _started_job(new_uow, world, lease_expires_at=at(70))
async with new_uow() as uow:
assert await uow.jobs.finish_job(
job_id=job.id,
state=AttachmentJobState.SUCCEEDED,
reason=None,
now=at(2),
)
assert not await uow.jobs.finish_job(
job_id=uuid4(),
state=AttachmentJobState.SUCCEEDED,
reason=None,
now=at(2),
)
await uow.commit()
row = await _job_row(new_uow, job.id)
assert row is not None
assert row.state == AttachmentJobState.SUCCEEDED
assert row.finished_at == at(2)
assert row.lease_expires_at is None
assert row.last_error_code is None
second = await _started_job(new_uow, world)
async with new_uow() as uow:
await uow.jobs.finish_job(
job_id=second.id,
state=AttachmentJobState.FAILED,
reason=AttachmentJobReason.UNDECODABLE,
now=at(3),
)
await uow.commit()
failed = await _job_row(new_uow, second.id)
assert failed is not None
assert failed.last_error_code == AttachmentJobReason.UNDECODABLE.value
async def check_lock_due_jobs(new_uow: NewUow) -> None:
world = await _world(new_uow)
first = await _job(new_uow, world, created_at=at(-30))
second = await _job(new_uow, world, created_at=at(-20))
await _job(new_uow, world, created_at=at(30))
# опубликованное и отложенное не выбираются
published = await _job(new_uow, world, created_at=at(-40))
delayed = await _started_job(new_uow, world)
async with new_uow() as uow:
await uow.jobs.mark_published(job_ids=[published.id], now=at(-1))
await uow.jobs.return_to_queued(
job_id=delayed.id,
attempt=delayed.attempt,
reason=AttachmentJobReason.TIMEOUT,
next_attempt_at=at(100),
now=at(-1),
)
await uow.commit()
async with new_uow() as uow:
due = await uow.jobs.lock_due_jobs(now=NOW, limit=10)
limited = await uow.jobs.lock_due_jobs(now=NOW, limit=1)
assert [job.id for job in due] == [first.id, second.id]
assert [job.id for job in limited] == [first.id]
async with new_uow() as uow:
later = await uow.jobs.lock_due_jobs(now=at(100), limit=10)
# срок — next_attempt_at, иначе created_at; порядок — по сроку
assert [job.id for job in later][-1] == delayed.id
assert delayed.id in {job.id for job in later}
async def check_count_and_mark_published(new_uow: NewUow) -> None:
world = await _world(new_uow)
first = await _job(new_uow, world)
second = await _job(new_uow, world)
async with new_uow() as uow:
assert await uow.jobs.count_published() == 0
marked = await uow.jobs.mark_published(
job_ids=[first.id, uuid4()],
now=at(1),
)
await uow.commit()
assert marked == 1
async with new_uow() as uow:
assert await uow.jobs.count_published() == 1
row = await _job_row(new_uow, first.id)
other = await _job_row(new_uow, second.id)
assert row is not None
assert other is not None
assert row.published_at == at(1)
assert other.published_at is None
async def check_count_unfinished(new_uow: NewUow) -> None:
world = await _world(new_uow)
async def count(limit: int) -> int:
async with new_uow() as uow:
return await uow.jobs.count_unfinished(limit=limit)
assert await count(1) == 0
# завершённые не считаются
await _failed_job(new_uow, world)
succeeded = await _started_job(new_uow, world)
async with new_uow() as uow:
await uow.jobs.finish_job(
job_id=succeeded.id,
state=AttachmentJobState.SUCCEEDED,
reason=None,
now=at(1),
)
await uow.commit()
assert await count(10) == 0
# queued без отметки
outbox = await _job(new_uow, world)
assert await count(10) == 1
# queued с отметкой
published = await _job(new_uow, world)
async with new_uow() as uow:
await uow.jobs.mark_published(job_ids=[published.id], now=at(1))
await uow.commit()
assert await count(10) == 2
# processing
await _started_job(new_uow, world, lease_expires_at=at(100))
assert await count(10) == 3
# queued со сроком следующей попытки: ждёт, но считается
retrying = await _started_job(new_uow, world, lease_expires_at=at(100))
async with new_uow() as uow:
assert await uow.jobs.return_to_queued(
job_id=retrying.id,
attempt=retrying.attempt,
reason=AttachmentJobReason.STORAGE_UNAVAILABLE,
next_attempt_at=at(1000),
now=at(1),
)
await uow.commit()
assert await count(10) == 4
# решение «не меньше предела»: ниже, на пределе и выше
assert await count(5) < 5
assert await count(4) >= 4
assert await count(3) >= 3
# одна группа больше предела: счёт обрывается, решение то же
assert outbox is not None
extra = [await _job(new_uow, world) for _ in range(3)]
assert len(extra) == 3
assert await count(2) >= 2
# в outbox теперь 5 строк (retrying с outbox), две другие группы по одной
assert await count(3) == 3 + 1 + 1
assert await count(1) == 3
TRACEPARENT = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"
async def check_job_trace_context(new_uow: NewUow) -> None:
"""Контекст задания сохраняется вставкой и читается выборками, в том
числе relay (design change `job-trace-propagation`, решение 4)."""
world = await _world(new_uow)
attachment = await _attachment(
new_uow,
world,
status=AttachmentStatus.QUEUED,
created_at=at(-10),
)
traced = replace(
job_dto(attachment_id=attachment.id, created_at=at(-10)),
traceparent=TRACEPARENT,
tracestate="vendor=value",
)
plain = await _job(new_uow, world, created_at=at(-5))
async with new_uow() as uow:
await uow.jobs.insert_job(job=traced)
await uow.commit()
row = await _job_row(new_uow, traced.id)
assert row is not None
assert row.traceparent == TRACEPARENT
assert row.tracestate == "vendor=value"
without = await _job_row(new_uow, plain.id)
assert without is not None
assert without.traceparent is None
assert without.tracestate is None
async with new_uow() as uow:
due = await uow.jobs.lock_due_jobs(now=NOW, limit=10)
by_id = {job.id: job for job in due}
assert by_id[traced.id].traceparent == TRACEPARENT
assert by_id[traced.id].tracestate == "vendor=value"
assert by_id[plain.id].traceparent is None
async def check_queue_snapshot(new_uow: NewUow) -> None:
world = await _world(new_uow)
async def snapshot(now: datetime = NOW) -> dataclasses.QueueSnapshotDTO:
async with new_uow() as uow:
return await uow.jobs.queue_snapshot(now=now)
empty = await snapshot()
assert empty == dataclasses.QueueSnapshotDTO(
taken_at=NOW,
scheduled=0,
outbox=0,
published=0,
processing=0,
oldest_created_at=None,
)
# завершённые не считаются
await _failed_job(new_uow, world)
# срок наступил, не опубликовано
outbox = await _job(new_uow, world, created_at=at(-30))
# ещё не наступил срок приёма — тоже ждёт срока
await _job(new_uow, world, created_at=at(20))
published = await _job(new_uow, world, created_at=at(-20))
retrying = await _started_job(new_uow, world, lease_expires_at=at(100))
processing = await _started_job(new_uow, world, lease_expires_at=at(100))
async with new_uow() as uow:
await uow.jobs.mark_published(job_ids=[published.id], now=at(-1))
assert await uow.jobs.return_to_queued(
job_id=retrying.id,
attempt=retrying.attempt,
reason=AttachmentJobReason.STORAGE_UNAVAILABLE,
next_attempt_at=at(60),
now=at(-1),
)
await uow.commit()
result = await snapshot()
assert (
result.scheduled,
result.outbox,
result.published,
result.processing,
) == (2, 1, 1, 1)
assert result.taken_at == NOW
assert result.oldest_created_at == outbox.created_at
# срок следующей попытки наступил — стадия outbox
later = await snapshot(at(61))
assert (later.scheduled, later.outbox) == (0, 3)
# старейший — среди всех незавершённых: в работе раньше других
async with new_uow() as uow:
await uow.jobs.finish_job(
job_id=outbox.id,
state=AttachmentJobState.SUCCEEDED,
reason=None,
now=at(1),
)
await uow.commit()
rest = await snapshot()
assert rest.oldest_created_at == min(
published.created_at,
processing.created_at,
retrying.created_at,
)
assert rest.outbox == 0
async def check_recover_expired_leases(new_uow: NewUow) -> None:
world = await _world(new_uow)
expired = await _started_job(new_uow, world, lease_expires_at=at(-5))
alive = await _started_job(new_uow, world, lease_expires_at=at(50))
async with new_uow() as uow:
rows = await uow.jobs.recover_expired_leases(now=NOW, limit=10)
await uow.commit()
assert [row.id for row in rows] == [expired.id]
assert rows[0].state == AttachmentJobState.QUEUED
assert rows[0].last_error_code == AttachmentJobReason.LEASE_EXPIRED.value
assert rows[0].lease_expires_at is None
assert rows[0].published_at is None
kept = await _job_row(new_uow, alive.id)
assert kept is not None
assert kept.state == AttachmentJobState.PROCESSING
async def check_published_before(new_uow: NewUow) -> None:
world = await _world(new_uow)
old = await _job(new_uow, world)
new = await _job(new_uow, world)
async with new_uow() as uow:
assert not await uow.jobs.has_published_before(older_than=NOW)
await uow.jobs.mark_published(job_ids=[old.id], now=at(-100))
await uow.jobs.mark_published(job_ids=[new.id], now=at(100))
await uow.commit()
async with new_uow() as uow:
assert await uow.jobs.has_published_before(older_than=NOW)
assert await uow.jobs.reset_published_before(
older_than=NOW,
now=at(101),
)
await uow.commit()
row = await _job_row(new_uow, old.id)
kept = await _job_row(new_uow, new.id)
assert row is not None
assert kept is not None
assert row.published_at is None
assert kept.published_at == at(100)
async with new_uow() as uow:
assert not await uow.jobs.has_published_before(older_than=NOW)
async def check_replay_job(new_uow: NewUow) -> None:
world = await _world(new_uow)
job = await _failed_job(new_uow, world)
queued = await _job(new_uow, world)
async with new_uow() as uow:
assert await uow.jobs.replay_job(job_id=job.id, now=at(1))
assert not await uow.jobs.replay_job(job_id=queued.id, now=at(1))
await uow.commit()
row = await _job_row(new_uow, job.id)
assert row is not None
assert row.state == AttachmentJobState.QUEUED
assert row.attempt_base == row.attempt
assert row.last_error_code is None
assert row.finished_at is None
async def check_list_failed(new_uow: NewUow) -> None:
world = await _world(new_uow)
older = await _failed_job(new_uow, world, finished_at=at(1))
newer = await _failed_job(
new_uow,
world,
code=AttachmentErrorCode.PROCESSING_FAILED,
reason=AttachmentJobReason.TIMEOUT,
finished_at=at(2),
)
await _job(new_uow, world)
async with new_uow() as uow:
rows = await uow.jobs.list_failed(
error_code=None,
reason=None,
limit=10,
)
by_code = await uow.jobs.list_failed(
error_code=AttachmentErrorCode.INVALID_IMAGE.value,
reason=None,
limit=10,
)
by_reason = await uow.jobs.list_failed(
error_code=None,
reason=AttachmentJobReason.TIMEOUT.value,
limit=10,
)
limited = await uow.jobs.list_failed(
error_code=None,
reason=None,
limit=1,
)
assert [row.job_id for row in rows] == [newer.id, older.id]
assert rows[1].error_code == AttachmentErrorCode.INVALID_IMAGE
assert [row.job_id for row in by_code] == [older.id]
assert [row.job_id for row in by_reason] == [newer.id]
assert [row.job_id for row in limited] == [newer.id]
async def check_get_attachment_job(new_uow: NewUow) -> None:
world = await _world(new_uow)
job = await _job(new_uow, world)
async with new_uow() as uow:
found = await uow.jobs.get_attachment_job(
attachment_id=job.attachment_id,
pipeline_version=job.pipeline_version,
)
other = await uow.jobs.get_attachment_job(
attachment_id=job.attachment_id,
pipeline_version=job.pipeline_version + 1,
)
locked = await uow.jobs.lock_job(job_id=job.id)
absent = await uow.jobs.lock_job(job_id=uuid4())
assert found is not None
assert found.id == job.id
assert other is None
assert locked is not None
assert locked.id == job.id
assert absent is None
# ------------------------------------------------- идемпотентность и сообщения
async def _message_with_key(
new_uow: NewUow,
world: _World,
*,
key: str,
created_at: datetime = NOW,
attachment_ids: tuple[UUID, ...] = (),
) -> dataclasses.MessageFullDTO:
message = message_dto(
chat_id=world.chat_id,
sender_id=world.user_id,
created_at=created_at,
attachment_ids=attachment_ids,
)
async with new_uow() as uow:
assert await uow.idempotency.claim_key(
user_id=world.user_id,
chat_id=world.chat_id,
key=key,
request_hash=b"h" * 32,
message_id=message.id,
created_at=created_at,
expired_before=at(-1000),
)
await uow.messages.insert_message(message=message, instance_id="test")
if attachment_ids:
await uow.messages.insert_message_attachments(message=message)
await uow.commit()
return message
async def check_claim_key(new_uow: NewUow) -> None:
world = await _world(new_uow)
first = await _message_with_key(
new_uow,
world,
key="k",
created_at=at(-10),
)
other = message_dto(chat_id=world.chat_id, sender_id=world.user_id)
claim = {
"user_id": world.user_id,
"chat_id": world.chat_id,
"key": "k",
"request_hash": b"z" * 32,
"message_id": other.id,
"created_at": NOW,
}
async with new_uow() as uow:
# действует: ничего не меняется
assert not await uow.idempotency.claim_key(
**claim,
expired_before=at(-20),
)
record = await uow.idempotency.get_key_result(
user_id=world.user_id,
chat_id=world.chat_id,
key="k",
)
await uow.commit()
assert record is not None
assert record.request_hash == b"h" * 32
assert record.message.id == first.id
# просрочен: заменён этим же вызовом
async with new_uow() as uow:
assert await uow.idempotency.claim_key(
**claim,
expired_before=at(-5),
)
await uow.messages.insert_message(message=other, instance_id="test")
await uow.commit()
async with new_uow() as uow:
replaced = await uow.idempotency.get_key_result(
user_id=world.user_id,
chat_id=world.chat_id,
key="k",
)
assert replaced is not None
assert replaced.request_hash == b"z" * 32
assert replaced.message.id == other.id
async def check_get_key_result(new_uow: NewUow) -> None:
world = await _world(new_uow)
first = await _attachment(new_uow, world, status=AttachmentStatus.READY)
second = await _attachment(new_uow, world, status=AttachmentStatus.READY)
message = await _message_with_key(
new_uow,
world,
key="k",
attachment_ids=(second.id, first.id),
)
async with new_uow() as uow:
record = await uow.idempotency.get_key_result(
user_id=world.user_id,
chat_id=world.chat_id,
key="k",
)
absent = await uow.idempotency.get_key_result(
user_id=world.other_id,
chat_id=world.chat_id,
key="k",
)
assert record is not None
assert record.message.id == message.id
assert record.message.attachment_ids == (second.id, first.id)
assert absent is None
async def check_get_chat_messages_page(new_uow: NewUow) -> None:
world = await _world(new_uow)
attachments = [
await _attachment(new_uow, world, status=AttachmentStatus.READY)
for _ in range(3)
]
# порядок вложений — отправки, а не по id
order = tuple(sorted((row.id for row in attachments), reverse=True))
first = await _message_with_key(
new_uow,
world,
key="a",
created_at=at(1),
attachment_ids=order,
)
second = await _message_with_key(
new_uow,
world,
key="b",
created_at=at(2),
)
third = await _message_with_key(
new_uow,
world,
key="c",
created_at=at(3),
)
async with new_uow() as uow:
page = await uow.messages.get_chat_messages_page(
chat_id=world.chat_id,
after=None,
limit=1,
)
rest = await uow.messages.get_chat_messages_page(
chat_id=world.chat_id,
after=(second.created_at, second.id),
limit=10,
)
foreign = await uow.messages.get_chat_messages_page(
chat_id=uuid4(),
after=None,
limit=10,
)
# limit + 1: лишний элемент — признак следующей страницы
assert [item.id for item in page] == [first.id, second.id]
assert page[0].attachment_ids == order
assert page[1].attachment_ids == ()
assert [item.id for item in rest] == [third.id]
assert foreign == []
# ------------------------------------------------------- пользователи и сессии
async def check_users(new_uow: NewUow) -> None:
user = user_dto()
same_name = replace(user_dto(), username=user.username)
async with new_uow() as uow:
created = await uow.users.insert_user(
user=user,
password_hash=PASSWORD_HASH,
)
assert created == user
assert (
await uow.users.insert_user(
user=same_name,
password_hash=f"{PASSWORD_HASH}x",
)
is None
)
await uow.commit()
async with new_uow() as uow:
credentials = await uow.users.get_user_credentials(
username=user.username,
)
absent = await uow.users.get_user_credentials(username="absent_user")
existing = await uow.users.get_existing_user_ids(
user_ids=[user.id, same_name.id],
)
assert credentials is not None
assert credentials.user == user
assert credentials.password_hash == PASSWORD_HASH
assert absent is None
assert existing == {user.id}
async def check_sessions(new_uow: NewUow) -> None:
world = await _world(new_uow)
session = dataclasses.SessionFullDTO(
id=uuid4(),
user_id=world.user_id,
token_hash=b"t" * 32,
expires_at=at(10),
created_at=NOW,
)
async with new_uow() as uow:
await uow.sessions.insert_session(session=session)
await uow.commit()
async with new_uow() as uow:
repo = uow.sessions
current = await repo.get_current_session(
token_hash=b"t" * 32,
now=at(9),
)
expired = await repo.get_current_session(
token_hash=b"t" * 32,
now=at(10),
)
unknown = await repo.get_current_session(
token_hash=b"u" * 32,
now=NOW,
)
assert await repo.delete_session(session_id=session.id)
assert not await repo.delete_session(session_id=session.id)
await uow.commit()
assert current is not None
assert current.id == session.id
assert current.user.id == world.user_id
assert expired is None
assert unknown is None
async def check_chats(new_uow: NewUow) -> None:
world = await _world(new_uow)
# порядок участников — переданный, а не по id
members = tuple(
sorted((world.user_id, world.other_id), key=lambda item: -item.int),
)
chats = [
chat_dto(member_ids=members, created_at=at(seconds))
for seconds in (3, 1, 2)
]
async with new_uow() as uow:
for chat in chats:
await uow.chats.insert_chat(chat=chat)
assert await uow.chats.insert_chat_members(chat=chat) == 2
await uow.commit()
ordered = sorted(chats, key=lambda chat: chat.created_at)
async with new_uow() as uow:
found = await uow.chats.get_chat(chat_id=chats[0].id)
absent = await uow.chats.get_chat(chat_id=uuid4())
page = await uow.chats.get_user_chats_page(
user_id=world.other_id,
# строго после чата мира: его время — NOW
after=(NOW, UUID(int=2**128 - 1)),
limit=1,
)
rest = await uow.chats.get_user_chats_page(
user_id=world.other_id,
after=(ordered[1].created_at, ordered[1].id),
limit=10,
)
foreign = await uow.chats.get_user_chats_page(
user_id=uuid4(),
after=None,
limit=10,
)
assert found is not None
assert found.member_ids == members
assert absent is None
assert [chat.id for chat in page] == [ordered[0].id, ordered[1].id]
assert [chat.id for chat in rest] == [ordered[2].id]
assert foreign == []
# ------------------------------------------------------- варианты и журнал
async def check_variants(new_uow: NewUow) -> None:
world = await _world(new_uow)
row = await _attachment(new_uow, world, status=AttachmentStatus.READY)
thumbnail = variant_dto(attachment_id=row.id)
crop = variant_dto(
attachment_id=row.id,
name=AttachmentVariantName.CROP,
)
newer = variant_dto(attachment_id=row.id, pipeline_version=2)
async with new_uow() as uow:
repo = uow.variants
assert await repo.insert_variant(
attachment_id=row.id,
variant=thumbnail,
)
assert not await repo.insert_variant(
attachment_id=row.id,
variant=replace(thumbnail, object_key="other"),
)
assert await repo.insert_variant(attachment_id=row.id, variant=crop)
await uow.commit()
async with new_uow() as uow:
listed = await uow.variants.get_variants(attachment_id=row.id)
assert await uow.variants.insert_variant(
attachment_id=row.id,
variant=newer,
)
latest = await uow.variants.get_variant(
attachment_id=row.id,
name=AttachmentVariantName.THUMBNAIL,
)
absent = await uow.variants.get_variant(
attachment_id=row.id,
name=AttachmentVariantName.OPTIMIZED,
)
assert [item.name for item in listed] == [
AttachmentVariantName.CROP,
AttachmentVariantName.THUMBNAIL,
]
assert listed[1].object_key == thumbnail.object_key
assert latest is not None
assert latest.pipeline_version == 2
assert absent is None
async def check_job_replays(new_uow: NewUow) -> None:
world = await _world(new_uow)
job = await _job(new_uow, world)
replays = [
dataclasses.AttachmentJobReplayDTO(
id=uuid4(),
job_id=job.id,
operator="op",
error_code=None,
reason=None,
attempt=1,
created_at=at(seconds),
)
for seconds in (2, 1)
]
async with new_uow() as uow:
for replay in replays:
await uow.job_replays.insert_replay(replay=replay)
await uow.commit()
async with new_uow() as uow:
found = await uow.job_replays.get_job_replays(job_id=job.id)
none = await uow.job_replays.get_job_replays(job_id=uuid4())
assert [item.id for item in found] == [replays[1].id, replays[0].id]
assert none == []
CHECKS = tuple(
check
for name, check in sorted(globals().items())
if name.startswith("check_")
)