Files
mtusi2026lab6/service-tests/fakes/repos.py
T

1027 lines
30 KiB
Python

"""Фейки девяти repo по контракту портов (design change `unit-of-work`, решение
11): условия переходов, keyset по полям и порядок результата; без блокировок,
планов и внешних ключей. Каждый метод пишет событие `<repo>.<метод>` в журнал и
бросает заданный `fail_on`.
"""
import functools
import inspect
from collections.abc import Collection, Iterable
from dataclasses import replace
from datetime import datetime
from uuid import UUID
from src.core.ports.attachment import AbstractAttachmentRepository
from src.core.ports.attachment_job import AbstractAttachmentJobRepository
from src.core.ports.attachment_job_replay import (
AbstractAttachmentJobReplayRepository,
)
from src.core.ports.attachment_variant import (
AbstractAttachmentVariantRepository,
)
from src.core.ports.chat import AbstractChatRepository
from src.core.ports.idempotency import AbstractIdempotencyRepository
from src.core.ports.message import AbstractMessageRepository
from src.core.ports.session import AbstractSessionRepository
from src.core.ports.user import AbstractUserRepository
from src.schemas import dataclasses
from src.schemas.enums import (
AttachmentErrorCode,
AttachmentJobReason,
AttachmentJobState,
AttachmentStatus,
AttachmentVariantName,
)
from src.utils.cursor import CursorKey
from .database import FakeDatabase
def _recorded(method, event: str):
@functools.wraps(method)
async def wrapper(self, *args, **kwargs):
self._db.record(event)
return await method(self, *args, **kwargs)
return wrapper
class _FakeRepository:
"""Подкласс задаёт `event_prefix`; методы оборачиваются записью в журнал,
`functools.wraps` сохраняет сигнатуру для сверки с портом."""
event_prefix = ""
def __init__(self, database: FakeDatabase) -> None:
self._db = database
def __init_subclass__(cls, **kwargs) -> None:
super().__init_subclass__(**kwargs)
for name, member in list(vars(cls).items()):
if not name.startswith("_") and inspect.iscoroutinefunction(
member,
):
setattr(
cls,
name,
_recorded(member, f"{cls.event_prefix}.{name}"),
)
class FakeUserRepository(_FakeRepository, AbstractUserRepository):
event_prefix = "users"
async def insert_user(
self,
*,
user: dataclasses.UserFullDTO,
password_hash: str,
) -> dataclasses.UserFullDTO | None:
if user.username in self._db.credentials:
return None
self._db.users[user.id] = user
self._db.credentials[user.username] = dataclasses.UserCredentialsDTO(
user=user,
password_hash=password_hash,
)
return user
async def get_user_credentials(
self,
*,
username: str,
) -> dataclasses.UserCredentialsDTO | None:
return self._db.credentials.get(username)
async def get_existing_user_ids(
self,
*,
user_ids: Iterable[UUID],
) -> set[UUID]:
return {item for item in user_ids if item in self._db.users}
class FakeSessionRepository(_FakeRepository, AbstractSessionRepository):
event_prefix = "sessions"
async def insert_session(
self,
*,
session: dataclasses.SessionFullDTO,
) -> dataclasses.SessionFullDTO:
self._db.sessions[session.id] = session
return session
async def get_current_session(
self,
*,
token_hash: bytes,
now: datetime,
) -> dataclasses.CurrentSessionDTO | None:
for session in self._db.sessions.values():
if session.token_hash == token_hash and session.expires_at > now:
return dataclasses.CurrentSessionDTO(
id=session.id,
user=self._db.users[session.user_id],
)
return None
async def delete_session(self, *, session_id: UUID) -> bool:
return self._db.sessions.pop(session_id, None) is not None
def _after_key(item, after: CursorKey | None) -> bool:
return after is None or (item.created_at, item.id) > after
class FakeChatRepository(_FakeRepository, AbstractChatRepository):
event_prefix = "chats"
async def insert_chat(
self,
*,
chat: dataclasses.ChatFullDTO,
) -> dataclasses.ChatFullDTO:
self._db.chats[chat.id] = replace(chat, member_ids=())
return chat
async def insert_chat_members(
self,
*,
chat: dataclasses.ChatFullDTO,
) -> int:
self._db.chats[chat.id] = chat
return len(chat.member_ids)
async def get_chat(
self,
*,
chat_id: UUID,
) -> dataclasses.ChatFullDTO | None:
return self._db.chats.get(chat_id)
async def get_user_chats_page(
self,
*,
user_id: UUID,
after: CursorKey | None,
limit: int,
) -> list[dataclasses.ChatFullDTO]:
rows = sorted(
(
chat
for chat in self._db.chats.values()
if user_id in chat.member_ids and _after_key(chat, after)
),
key=lambda chat: (chat.created_at, chat.id),
)
return rows[: limit + 1]
class FakeMessageRepository(_FakeRepository, AbstractMessageRepository):
event_prefix = "messages"
async def insert_message(
self,
*,
message: dataclasses.MessageFullDTO,
instance_id: str,
) -> dataclasses.MessageFullDTO:
self._db.messages[message.id] = replace(message, attachment_ids=())
return message
async def insert_message_attachments(
self,
*,
message: dataclasses.MessageFullDTO,
) -> int:
self._db.messages[message.id] = message
return len(message.attachment_ids)
async def get_chat_messages_page(
self,
*,
chat_id: UUID,
after: CursorKey | None,
limit: int,
) -> list[dataclasses.MessageFullDTO]:
rows = sorted(
(
message
for message in self._db.messages.values()
if message.chat_id == chat_id and _after_key(message, after)
),
key=lambda message: (message.created_at, message.id),
)
return rows[: limit + 1]
class FakeIdempotencyRepository(
_FakeRepository,
AbstractIdempotencyRepository,
):
event_prefix = "idempotency"
async def claim_key(
self,
*,
user_id: UUID,
chat_id: UUID,
key: str,
request_hash: bytes,
message_id: UUID,
created_at: datetime,
expired_before: datetime,
) -> bool:
current = self._db.idempotency.get((user_id, chat_id, key))
if current is not None and current[2] >= expired_before:
return False
self._db.idempotency[(user_id, chat_id, key)] = (
request_hash,
message_id,
created_at,
)
return True
async def get_key_result(
self,
*,
user_id: UUID,
chat_id: UUID,
key: str,
) -> dataclasses.IdempotencyRecordDTO | None:
current = self._db.idempotency.get((user_id, chat_id, key))
if current is None:
return None
message = self._db.messages.get(current[1])
if message is None:
return None
return dataclasses.IdempotencyRecordDTO(
request_hash=current[0],
message=message,
)
_IN_WORK = (AttachmentStatus.QUEUED, AttachmentStatus.PROCESSING)
class FakeAttachmentRepository(_FakeRepository, AbstractAttachmentRepository):
event_prefix = "attachments"
def _set(self, row, updated_at: datetime | None = None, **fields):
if updated_at is not None:
fields["updated_at"] = max(updated_at, row.updated_at)
changed = replace(row, **fields)
self._db.attachments[row.id] = changed
return changed
def _staging_matches(
self,
row,
status: AttachmentStatus,
updated_before: datetime | None,
) -> bool:
return (
row.staging_key is not None
and row.status == status
and (updated_before is None or row.updated_at < updated_before)
)
@staticmethod
def _staging_dto(row) -> dataclasses.AttachmentInListDTO:
return dataclasses.AttachmentInListDTO(
id=row.id,
object_key=row.object_key,
created_at=row.created_at,
staging_key=row.staging_key,
status=row.status,
updated_at=row.updated_at,
)
@staticmethod
def _stale_dto(row) -> dataclasses.AttachmentInListDTO:
return dataclasses.AttachmentInListDTO(
id=row.id,
object_key=row.object_key,
created_at=row.created_at,
staging_key=row.staging_key,
)
async def insert_attachment(
self,
*,
attachment: dataclasses.AttachmentFullDTO,
) -> dataclasses.AttachmentFullDTO:
# как INSERT: пометка, код ошибки и варианты в него не входят
self._db.attachments[attachment.id] = replace(
attachment,
lost_at=None,
error_code=None,
variants=(),
)
return attachment
async def mark_queued(
self,
*,
attachment_id: UUID,
updated_at: datetime,
) -> dataclasses.AttachmentFullDTO | None:
row = self._db.attachments.get(attachment_id)
if (
row is None
or row.status != AttachmentStatus.PENDING
or row.updated_at != row.created_at
):
return None
return self._set(
row,
updated_at=updated_at,
status=AttachmentStatus.QUEUED,
)
async def mark_processing(
self,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
row = self._db.attachments.get(attachment_id)
if row is None or row.status not in _IN_WORK:
return False
self._set(
row,
updated_at=updated_at,
status=AttachmentStatus.PROCESSING,
)
return True
async def return_to_queued(
self,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
row = self._db.attachments.get(attachment_id)
if row is None or row.status != AttachmentStatus.PROCESSING:
return False
self._set(row, updated_at=updated_at, status=AttachmentStatus.QUEUED)
return True
async def return_group_to_queued(
self,
*,
attachment_ids: Collection[UUID],
updated_at: datetime,
) -> int:
count = 0
for attachment_id in set(attachment_ids):
row = self._db.attachments.get(attachment_id)
if row is not None and row.status == AttachmentStatus.PROCESSING:
self._set(
row,
updated_at=updated_at,
status=AttachmentStatus.QUEUED,
)
count += 1
return count
async def replay_failed(
self,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
row = self._db.attachments.get(attachment_id)
if row is None or row.status != AttachmentStatus.FAILED:
return False
self._set(
row,
updated_at=updated_at,
status=AttachmentStatus.QUEUED,
error_code=None,
)
return True
async def lock_attachment(
self,
*,
attachment_id: UUID,
) -> dataclasses.AttachmentFullDTO | None:
return self._db.attachments.get(attachment_id)
async def get_staging_candidates(
self,
*,
status: AttachmentStatus,
updated_before: datetime | None,
after: tuple[datetime, UUID] | None,
limit: int,
) -> list[dataclasses.AttachmentInListDTO]:
rows = sorted(
(
row
for row in self._db.attachments.values()
if self._staging_matches(row, status, updated_before)
and (after is None or (row.updated_at, row.id) > after)
),
key=lambda row: (row.updated_at, row.id),
)
return [self._staging_dto(row) for row in rows[:limit]]
async def lock_staging_candidate(
self,
*,
attachment_id: UUID,
status: AttachmentStatus,
updated_before: datetime | None,
) -> dataclasses.AttachmentInListDTO | None:
row = self._db.attachments.get(attachment_id)
if (
row is None
or attachment_id in self._db.held
or not self._staging_matches(row, status, updated_before)
):
return None
return self._staging_dto(row)
async def clear_staging_key(self, *, attachment_id: UUID) -> bool:
row = self._db.attachments.get(attachment_id)
if row is None:
return False
self._set(row, staging_key=None)
return True
async def commit_ready(
self,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
row = self._db.attachments.get(attachment_id)
if row is None or row.status not in _IN_WORK:
return False
self._set(row, updated_at=updated_at, status=AttachmentStatus.READY)
return True
async def commit_failed(
self,
*,
attachment_id: UUID,
error_code: AttachmentErrorCode,
updated_at: datetime,
) -> bool:
row = self._db.attachments.get(attachment_id)
if row is None or row.status not in _IN_WORK:
return False
self._set(
row,
updated_at=updated_at,
status=AttachmentStatus.FAILED,
error_code=error_code,
)
return True
async def get_attachment(
self,
*,
attachment_id: UUID,
) -> dataclasses.AttachmentFullDTO | None:
return self._db.attachments.get(attachment_id)
async def get_attachments(
self,
*,
attachment_ids: Collection[UUID],
) -> list[dataclasses.AttachmentFullDTO]:
return [
self._db.attachments[item]
for item in set(attachment_ids)
if item in self._db.attachments
]
async def get_stale_pending(
self,
*,
older_than: datetime,
after: tuple[datetime, UUID] | None,
limit: int,
) -> list[dataclasses.AttachmentInListDTO]:
rows = sorted(
(
row
for row in self._db.attachments.values()
if row.status == AttachmentStatus.PENDING
and row.created_at < older_than
and (after is None or (row.created_at, row.id) > after)
),
key=lambda row: (row.created_at, row.id),
)
return [self._stale_dto(row) for row in rows[:limit]]
async def lock_stale_pending(
self,
*,
attachment_id: UUID,
older_than: datetime,
) -> dataclasses.AttachmentInListDTO | None:
row = self._db.attachments.get(attachment_id)
if (
row is None
or attachment_id in self._db.held
or row.status != AttachmentStatus.PENDING
or row.created_at >= older_than
):
return None
return self._stale_dto(row)
async def mark_removing(
self,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
row = self._db.attachments.get(attachment_id)
if row is None:
return False
self._db.attachments[attachment_id] = replace(
row,
updated_at=updated_at,
)
return True
async def delete_attachment(self, *, attachment_id: UUID) -> bool:
return self._db.attachments.pop(attachment_id, None) is not None
async def get_attachments_for_objects(
self,
*,
attachment_ids: Collection[UUID],
object_keys: Collection[str],
) -> list[dataclasses.AttachmentFullDTO]:
ids = set(attachment_ids)
keys = set(object_keys)
return [
row
for row in self._db.attachments.values()
if row.id in ids or row.object_key in keys
]
async def get_ready_page(
self,
*,
after: UUID | None,
limit: int,
) -> list[dataclasses.AttachmentFullDTO]:
rows = sorted(
(
row
for row in self._db.attachments.values()
if row.status == AttachmentStatus.READY
and (after is None or row.id > after)
),
key=lambda row: row.id,
)
return rows[:limit]
async def find_attachment_reference(
self,
*,
attachment_id: UUID,
object_key: str,
) -> list[dataclasses.AttachmentFullDTO]:
return [
row
for row in self._db.attachments.values()
if row.id == attachment_id or row.object_key == object_key
]
async def mark_lost(
self,
*,
attachment_id: UUID,
object_key: str,
lost_at: datetime,
) -> bool:
row = self._db.attachments.get(attachment_id)
if (
row is None
or row.status != AttachmentStatus.READY
or row.lost_at is not None
or row.object_key != object_key
):
return False
self._set(row, lost_at=lost_at)
return True
async def clear_lost(
self,
*,
attachment_id: UUID,
object_key: str,
) -> bool:
row = self._db.attachments.get(attachment_id)
if row is None or row.lost_at is None or row.object_key != object_key:
return False
self._set(row, lost_at=None)
return True
def _due_at(job: dataclasses.AttachmentJobDTO) -> datetime:
return job.next_attempt_at or job.created_at
class FakeAttachmentJobRepository(
_FakeRepository,
AbstractAttachmentJobRepository,
):
event_prefix = "jobs"
def _set(self, job, now: datetime | None = None, **fields):
if now is not None:
fields["updated_at"] = max(now, job.updated_at)
changed = replace(job, **fields)
self._db.jobs[job.id] = changed
return changed
def _published(self, older_than: datetime | None = None):
return [
job
for job in self._db.jobs.values()
if job.state == AttachmentJobState.QUEUED
and job.published_at is not None
and (older_than is None or job.published_at < older_than)
]
async def insert_job(
self,
*,
job: dataclasses.AttachmentJobDTO,
) -> dataclasses.AttachmentJobDTO:
self._db.jobs[job.id] = dataclasses.AttachmentJobDTO(
id=job.id,
attachment_id=job.attachment_id,
pipeline_version=job.pipeline_version,
state=job.state,
attempt=job.attempt,
created_at=job.created_at,
updated_at=job.updated_at,
traceparent=job.traceparent,
tracestate=job.tracestate,
)
return job
async def lock_job(
self,
*,
job_id: UUID,
) -> dataclasses.AttachmentJobDTO | None:
return self._db.jobs.get(job_id)
async def get_job(
self,
*,
job_id: UUID,
) -> dataclasses.AttachmentJobDTO | None:
return self._db.jobs.get(job_id)
async def count_unfinished(self, *, limit: int) -> int:
groups = (
[
job
for job in self._db.jobs.values()
if job.state == AttachmentJobState.QUEUED
and job.published_at is None
],
self._published(),
[
job
for job in self._db.jobs.values()
if job.state == AttachmentJobState.PROCESSING
],
)
return sum(min(len(group), limit) for group in groups)
async def queue_snapshot(
self,
*,
now: datetime,
) -> dataclasses.QueueSnapshotDTO:
unfinished = [
job
for job in self._db.jobs.values()
if job.state
in {AttachmentJobState.QUEUED, AttachmentJobState.PROCESSING}
]
outbox = [
job
for job in unfinished
if job.state == AttachmentJobState.QUEUED
and job.published_at is None
]
return dataclasses.QueueSnapshotDTO(
taken_at=now,
scheduled=sum(1 for job in outbox if _due_at(job) > now),
outbox=sum(1 for job in outbox if _due_at(job) <= now),
published=len(self._published()),
processing=sum(
1
for job in unfinished
if job.state == AttachmentJobState.PROCESSING
),
oldest_created_at=min(
(job.created_at for job in unfinished),
default=None,
),
)
async def get_attachment_job(
self,
*,
attachment_id: UUID,
pipeline_version: int,
) -> dataclasses.AttachmentJobDTO | None:
for job in self._db.jobs.values():
if (
job.attachment_id == attachment_id
and job.pipeline_version == pipeline_version
):
return job
return None
async def start_attempt(
self,
*,
job_id: UUID,
lease_expires_at: datetime,
now: datetime,
) -> dataclasses.AttachmentJobDTO | None:
job = self._db.jobs.get(job_id)
if job is None:
return None
return self._set(
job,
now=now,
state=AttachmentJobState.PROCESSING,
attempt=job.attempt + 1,
lease_expires_at=lease_expires_at,
next_attempt_at=None,
)
async def return_to_queued(
self,
*,
job_id: UUID,
attempt: int,
reason: AttachmentJobReason,
next_attempt_at: datetime,
now: datetime,
) -> bool:
job = self._db.jobs.get(job_id)
if (
job is None
or job.state != AttachmentJobState.PROCESSING
or job.attempt != attempt
):
return False
self._set(
job,
now=now,
state=AttachmentJobState.QUEUED,
last_error_code=reason.value,
next_attempt_at=next_attempt_at,
lease_expires_at=None,
published_at=None,
)
return True
async def finish_job(
self,
*,
job_id: UUID,
state: AttachmentJobState,
reason: AttachmentJobReason | None,
now: datetime,
) -> bool:
job = self._db.jobs.get(job_id)
if job is None:
return False
fields = {} if reason is None else {"last_error_code": reason.value}
self._set(
job,
now=now,
state=state,
lease_expires_at=None,
next_attempt_at=None,
finished_at=now,
**fields,
)
return True
async def lock_due_jobs(
self,
*,
now: datetime,
limit: int,
) -> list[dataclasses.AttachmentJobDTO]:
rows = sorted(
(
job
for job in self._db.jobs.values()
if job.state == AttachmentJobState.QUEUED
and job.published_at is None
and now >= _due_at(job)
and job.id not in self._db.held
),
key=lambda job: (_due_at(job), job.id),
)
return rows[:limit]
async def count_published(self) -> int:
return len(self._published())
async def mark_published(
self,
*,
job_ids: Collection[UUID],
now: datetime,
) -> int:
count = 0
for job_id in set(job_ids):
job = self._db.jobs.get(job_id)
if job is not None:
self._set(job, now=now, published_at=now)
count += 1
return count
async def recover_expired_leases(
self,
*,
now: datetime,
limit: int,
) -> list[dataclasses.AttachmentJobDTO]:
expired = sorted(
(
job
for job in self._db.jobs.values()
if job.state == AttachmentJobState.PROCESSING
and job.lease_expires_at is not None
and job.lease_expires_at < now
and job.id not in self._db.held
),
key=lambda job: job.lease_expires_at,
)
return [
self._set(
job,
now=now,
state=AttachmentJobState.QUEUED,
last_error_code=AttachmentJobReason.LEASE_EXPIRED.value,
lease_expires_at=None,
next_attempt_at=None,
published_at=None,
)
for job in expired[:limit]
]
async def has_published_before(self, *, older_than: datetime) -> bool:
return bool(self._published(older_than))
async def reset_published_before(
self,
*,
older_than: datetime,
now: datetime,
) -> int:
rows = self._published(older_than)
for job in rows:
self._set(job, now=now, published_at=None)
return len(rows)
async def replay_job(self, *, job_id: UUID, now: datetime) -> bool:
job = self._db.jobs.get(job_id)
if job is None or job.state != AttachmentJobState.FAILED:
return False
self._set(
job,
now=now,
state=AttachmentJobState.QUEUED,
attempt_base=job.attempt,
last_error_code=None,
next_attempt_at=None,
lease_expires_at=None,
published_at=None,
finished_at=None,
)
return True
async def list_failed(
self,
*,
error_code: str | None,
reason: str | None,
limit: int,
) -> list[dataclasses.FailedJobDTO]:
rows = []
for job in self._db.jobs.values():
attachment = self._db.attachments.get(job.attachment_id)
if (
job.state != AttachmentJobState.FAILED
or attachment is None
or (
error_code is not None
and attachment.error_code != error_code
)
or (reason is not None and job.last_error_code != reason)
):
continue
rows.append(
dataclasses.FailedJobDTO(
job_id=job.id,
attachment_id=job.attachment_id,
error_code=attachment.error_code,
reason=job.last_error_code,
attempt=job.attempt,
attempt_base=job.attempt_base,
finished_at=job.finished_at,
),
)
# finished_at по убыванию, затем id по возрастанию: сортировки
# устойчивы
rows.sort(key=lambda row: row.job_id)
rows.sort(key=lambda row: row.finished_at, reverse=True)
return rows[:limit]
class FakeAttachmentVariantRepository(
_FakeRepository,
AbstractAttachmentVariantRepository,
):
event_prefix = "variants"
async def insert_variant(
self,
*,
attachment_id: UUID,
variant: dataclasses.AttachmentVariantDTO,
) -> bool:
key = (attachment_id, variant.pipeline_version, variant.name)
if key in self._db.variants:
return False
self._db.variants[key] = variant
return True
async def get_variants(
self,
*,
attachment_id: UUID,
) -> list[dataclasses.AttachmentVariantDTO]:
rows = [
variant
for key, variant in self._db.variants.items()
if key[0] == attachment_id
]
return sorted(rows, key=lambda variant: variant.name.value)
async def get_variant(
self,
*,
attachment_id: UUID,
name: AttachmentVariantName,
) -> dataclasses.AttachmentVariantDTO | None:
rows = [
variant
for key, variant in self._db.variants.items()
if key[0] == attachment_id and key[2] == name
]
if not rows:
return None
return max(rows, key=lambda variant: variant.pipeline_version)
class FakeAttachmentJobReplayRepository(
_FakeRepository,
AbstractAttachmentJobReplayRepository,
):
event_prefix = "job_replays"
async def insert_replay(
self,
*,
replay: dataclasses.AttachmentJobReplayDTO,
) -> dataclasses.AttachmentJobReplayDTO:
self._db.job_replays[replay.id] = replay
return replay
async def get_job_replays(
self,
*,
job_id: UUID,
) -> list[dataclasses.AttachmentJobReplayDTO]:
rows = [
replay
for replay in self._db.job_replays.values()
if replay.job_id == job_id
]
return sorted(rows, key=lambda replay: (replay.created_at, replay.id))