chore: port lab 5 solution into the lab 6 skeleton

Source: mtusi2026lab5-safronov, solution/bvt2301-safronov, 046ec9e.
Contracts, public tests and evidence of lab 5 are not carried over.
The compose project, image and CI prefix are renamed to lab6; the first
broker start defect is recorded in KNOWN_ISSUES.md; PLAN.md outlines the
OpenSpec changes of lab 6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-11 04:46:56 +03:00
co-authored by Claude Opus 5.5
parent 470d9d6f1e
commit 9cc6c0c7a6
621 changed files with 151446 additions and 29 deletions
+46
View File
@@ -0,0 +1,46 @@
"""Фейки единицы работы, repo и клиентов для быстрых тестов сервисов.
Метод фейка реализует контракт из докстринга порта (design change
`unit-of-work`, решение 11). Совпадение с SQL закрепляет
`service-tests/repo_contract.py`, сигнатуры — `unit/test_architecture.py`.
"""
from .clients import (
FakeCache,
FakeImageRenderer,
FakeJobPublisher,
FakeObjectStorage,
FakeStoredObject,
)
from .database import FakeDatabase
from .repos import (
FakeAttachmentJobReplayRepository,
FakeAttachmentJobRepository,
FakeAttachmentRepository,
FakeAttachmentVariantRepository,
FakeChatRepository,
FakeIdempotencyRepository,
FakeMessageRepository,
FakeSessionRepository,
FakeUserRepository,
)
from .uow import FakeUnitOfWork
__all__ = [
"FakeAttachmentJobReplayRepository",
"FakeAttachmentJobRepository",
"FakeAttachmentRepository",
"FakeAttachmentVariantRepository",
"FakeCache",
"FakeChatRepository",
"FakeDatabase",
"FakeIdempotencyRepository",
"FakeImageRenderer",
"FakeJobPublisher",
"FakeMessageRepository",
"FakeObjectStorage",
"FakeSessionRepository",
"FakeStoredObject",
"FakeUnitOfWork",
"FakeUserRepository",
]
+245
View File
@@ -0,0 +1,245 @@
"""Фейки клиентов: настоящие `chat_cache` и `attachment_object` работают поверх
них, ключи и формат значения не дублируются (design change `unit-of-work`,
решение 8). Журнал и заданные отказы — общие с `FakeDatabase`: порядок вызовов S3
и издателя виден рядом с блоками.
"""
from collections import Counter
from collections.abc import AsyncIterator, Sequence
from contextlib import asynccontextmanager
from datetime import UTC, datetime
from types import MappingProxyType
from typing import BinaryIO
from uuid import UUID
from src.core import exceptions
from src.infra.s3 import (
StorageStats,
StoredObjectInfo,
StoredObjectPage,
)
from src.schemas.dataclasses import RenderedVariantsDTO
from .database import FakeDatabase
_FAR_PAST = datetime(2000, 1, 1, tzinfo=UTC)
_CHUNK_BYTES = 1024
_CALL_NAMES = ("list", "head", "get", "delete", "put")
class FakeCache:
"""`failing` — Valkey недоступен: промах и пропуск, как у `Cache`."""
def __init__(
self,
database: FakeDatabase,
*,
namespace: str = "testdb",
) -> None:
self.namespace = namespace
self._db = database
self.values: dict[str, str] = {}
self.failing = False
async def get(self, key: str) -> str | None:
self._db.events.append("cache.get")
return None if self.failing else self.values.get(key)
async def set(self, key: str, value: str, *, ttl_seconds: int) -> bool:
self._db.events.append("cache.set")
if self.failing:
return False
self.values[key] = value
return True
async def aclose(self) -> None:
return None
class FakeStoredObject:
def __init__(self, info: StoredObjectInfo, data: bytes, storage) -> None:
self.info = info
self._data = data
self._storage = storage
@property
def size(self) -> int:
return self.info.size
@property
def content_type(self) -> str | None:
return self.info.content_type
async def iter_chunks(
self,
chunk_bytes: int = _CHUNK_BYTES,
) -> AsyncIterator[bytes]:
for start in range(0, len(self._data), chunk_bytes):
chunk = self._data[start : start + chunk_bytes]
self._storage.read_bytes += len(chunk)
yield chunk
async def read(self) -> bytes:
self._storage.read_bytes += len(self._data)
return self._data
class FakeObjectStorage:
"""Объекты в памяти. Событие — `storage.<операция>`, отказ — `fail_on` базы
(`storage.put`, `storage.list`, …): счётчик растёт до вызова, как у клиента.
`seed` кладёт объект мимо счётчиков и журнала."""
def __init__(
self,
database: FakeDatabase,
*,
namespace: str = "testdb",
) -> None:
self.namespace = namespace
self._db = database
self.objects: dict[str, tuple[bytes, str | None, datetime]] = {}
self.calls: Counter[str] = Counter()
self.listed_keys = 0
self.read_bytes = 0
def seed(
self,
key: str,
data: bytes = b"x",
*,
content_type: str | None = "image/png",
last_modified: datetime = _FAR_PAST,
) -> None:
self.objects[key] = (data, content_type, last_modified)
def _call(self, name: str) -> None:
self.calls[name] += 1
self._db.record(f"storage.{name}")
def _info(self, key: str) -> StoredObjectInfo:
data, content_type, last_modified = self.objects[key]
return StoredObjectInfo(
key=key,
size=len(data),
content_type=content_type,
last_modified=last_modified,
)
def stats(self) -> StorageStats:
return StorageStats(
calls=MappingProxyType(
{name: self.calls[name] for name in _CALL_NAMES},
),
listed_keys=self.listed_keys,
read_bytes=self.read_bytes,
)
async def start(self) -> None:
return None
async def aclose(self) -> None:
return None
async def put(
self,
key: str,
body: BinaryIO,
*,
size: int,
content_type: str,
) -> None:
self._call("put")
self.objects[key] = (
body.read(),
content_type,
datetime.now(tz=UTC),
)
async def head(self, key: str) -> StoredObjectInfo | None:
self._call("head")
return self._info(key) if key in self.objects else None
async def list_page(
self,
prefix: str,
*,
token: str | None,
max_keys: int,
) -> StoredObjectPage:
self._call("list")
keys = sorted(
key
for key in self.objects
if key.startswith(prefix) and (token is None or key > token)
)
page = keys[:max_keys]
self.listed_keys += len(page)
return StoredObjectPage(
objects=tuple(self._info(key) for key in page),
next_token=page[-1] if len(keys) > max_keys else None,
)
@asynccontextmanager
async def open(self, key: str) -> AsyncIterator[FakeStoredObject]:
self._call("get")
if key not in self.objects:
raise exceptions.StoredObjectMissing
yield FakeStoredObject(self._info(key), self.objects[key][0], self)
async def delete(self, key: str) -> None:
self._call("delete")
self.objects.pop(key, None)
class FakeJobPublisher:
"""Подтверждает всё или заданное подмножество (`unconfirmed`); журнал —
`publisher.publish_many`, `publisher.ready_messages`."""
def __init__(
self,
database: FakeDatabase,
*,
namespace: str = "testdb",
) -> None:
self.namespace = namespace
self.queue = f"{namespace}.attachment.process.v1"
self._db = database
self.unconfirmed: set[UUID] = set()
self.ready = 0
self.published: list[UUID] = []
async def publish_many(
self,
items: Sequence[tuple[UUID, bytes]],
) -> set[UUID]:
self._db.record("publisher.publish_many")
confirmed = {
job_id for job_id, _ in items if job_id not in self.unconfirmed
}
self.published.extend(job_id for job_id, _ in items)
return confirmed
async def ready_messages(self) -> int:
self._db.record("publisher.ready_messages")
return self.ready
async def aclose(self) -> None:
return None
class FakeImageRenderer:
"""`result` — итог, `fail_on["renderer.render"]` — отказ процесса обработки."""
def __init__(
self,
database: FakeDatabase,
result: RenderedVariantsDTO | None = None,
) -> None:
self._db = database
self.result = result
async def render(self, data: bytes) -> RenderedVariantsDTO:
self._db.record("renderer.render")
if self.result is None:
raise AssertionError("FakeImageRenderer has no result")
return self.result
+77
View File
@@ -0,0 +1,77 @@
"""Хранилище фейков: таблицы-словари замороженных DTO, общие для экземпляров
единицы работы, как PostgreSQL для процессов.
Нет плана запроса, блокировок и ожидания, индексов и внешних ключей: занятую
строку тест объявляет явно (`held`), отказ — тоже (`fail_on`, `fail_commit`).
Порядок действий виден в общем журнале `events`: вход, выражения, вызовы S3 и
издателя, фиксация, выход.
"""
from dataclasses import dataclass, field
from typing import Any
from uuid import UUID
_TABLES = (
"users",
"credentials",
"sessions",
"chats",
"messages",
"idempotency",
"attachments",
"jobs",
"variants",
"job_replays",
)
@dataclass
class FakeDatabase:
users: dict[UUID, Any] = field(default_factory=dict)
# username → UserCredentialsDTO
credentials: dict[str, Any] = field(default_factory=dict)
sessions: dict[UUID, Any] = field(default_factory=dict)
chats: dict[UUID, Any] = field(default_factory=dict)
messages: dict[UUID, Any] = field(default_factory=dict)
# (user_id, chat_id, key) → (request_hash, message_id, created_at)
idempotency: dict[tuple, tuple] = field(default_factory=dict)
attachments: dict[UUID, Any] = field(default_factory=dict)
jobs: dict[UUID, Any] = field(default_factory=dict)
# (attachment_id, pipeline_version, имя) → AttachmentVariantDTO
variants: dict[tuple, Any] = field(default_factory=dict)
job_replays: dict[UUID, Any] = field(default_factory=dict)
events: list[str] = field(default_factory=list)
# id строк, которые держит другой процесс: SKIP LOCKED их пропускает
held: set[UUID] = field(default_factory=set)
# имя события → исключение, которое бросит это действие
fail_on: dict[str, BaseException] = field(default_factory=dict)
# исключение фиксации и сколько фиксаций пропустить до него
fail_commit: BaseException | None = None
commits_before_fail: int = 0
def record(self, name: str) -> None:
"""Записать действие; заданный отказ — бросить."""
self.events.append(name)
failure = self.fail_on.get(name)
if failure is not None:
raise failure
def snapshot(self) -> dict[str, dict]:
return {name: dict(getattr(self, name)) for name in _TABLES}
def restore(self, snapshot: dict[str, dict]) -> None:
for name, table in snapshot.items():
setattr(self, name, dict(table))
def inside_block(self, name: str) -> bool:
"""Было ли действие `name` между входом в блок и выходом из него."""
depth = 0
for event in self.events:
if event == "enter":
depth += 1
elif event == "exit":
depth -= 1
elif event == name and depth > 0:
return True
return False
+991
View File
@@ -0,0 +1,991 @@
"""Фейки девяти 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,
)
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 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))
+72
View File
@@ -0,0 +1,72 @@
"""Фейковая единица работы на том же базовом классе: те же ошибки вложенного
блока и repo вне блока, откат возвращает снимок таблиц.
"""
from types import TracebackType
from src.core.ports.uow import AbstractUnitOfWork, Repositories
from .database import FakeDatabase
from .repos import (
FakeAttachmentJobReplayRepository,
FakeAttachmentJobRepository,
FakeAttachmentRepository,
FakeAttachmentVariantRepository,
FakeChatRepository,
FakeIdempotencyRepository,
FakeMessageRepository,
FakeSessionRepository,
FakeUserRepository,
)
class FakeUnitOfWork(AbstractUnitOfWork):
def __init__(self, database: FakeDatabase) -> None:
super().__init__()
self.database = database
self._snapshot: dict[str, dict] | None = None
async def _open(self) -> Repositories:
self.database.record("enter")
self._snapshot = self.database.snapshot()
return Repositories(
users=FakeUserRepository(self.database),
sessions=FakeSessionRepository(self.database),
chats=FakeChatRepository(self.database),
messages=FakeMessageRepository(self.database),
idempotency=FakeIdempotencyRepository(self.database),
attachments=FakeAttachmentRepository(self.database),
jobs=FakeAttachmentJobRepository(self.database),
variants=FakeAttachmentVariantRepository(self.database),
job_replays=FakeAttachmentJobReplayRepository(self.database),
)
async def _close(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> bool | None:
# после фиксации снимка нет: откатывать нечего
if self._snapshot is not None:
self.database.restore(self._snapshot)
self._snapshot = None
self.database.events.append("exit")
return None
async def _commit(self) -> None:
database = self.database
if database.fail_commit is not None:
if database.commits_before_fail == 0:
failure, database.fail_commit = database.fail_commit, None
database.events.append("commit_failed")
raise failure
database.commits_before_fail -= 1
database.events.append("commit")
self._snapshot = None
async def _rollback(self) -> None:
if self._snapshot is not None:
self.database.restore(self._snapshot)
self._snapshot = None
self.database.events.append("rollback")