refactor: move services to a unit of work over repository ports
Services depend only on src/core/ports: async with self.uow is one transaction, commit is explicit, leaving without it rolls back. A connection is held per step, the JSON routers keep a shared request deadline, and rollback runs under the block deadline. Adds service-tests with fakes, a repo contract run on both the fake and SQL, and make service_test / service_test_db. API, schema and settings are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+39
-65
@@ -1,26 +1,27 @@
|
||||
"""Зависимости ручек: сессия БД, сервисы, вход и текущая сессия, страница.
|
||||
"""Зависимости ручек: единица работы, сервисы, вход и текущая сессия, страница.
|
||||
|
||||
Сервисы получают сессию БД, а чаты и сообщения — ещё и кэш процесса
|
||||
(`src/infra/cache/instance.py`). Вложения — фабрику короткой сессии на
|
||||
шаг, кэш, хранилище объектов (`src/infra/s3/instance.py`) и места
|
||||
загрузок процесса (`src/infra/upload_slots.py`).
|
||||
Сервисы получают единицу работы запроса, а чаты и сообщения — ещё и кэш
|
||||
процесса (`src/infra/cache/instance.py`). Вложения — ещё хранилище объектов
|
||||
(`src/infra/s3/instance.py`) и места загрузок процесса
|
||||
(`src/infra/upload_slots.py`). Вход и операция сервиса — разные блоки одной
|
||||
единицы работы: соединение между ними в пуле (design change `unit-of-work`,
|
||||
решения 3 и 5).
|
||||
"""
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import re
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import AbstractAsyncContextManager
|
||||
from dataclasses import dataclass
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Depends, Query, Security
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from fastapi.security.http import HTTPBase
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.config import settings
|
||||
from src.core import exceptions
|
||||
from src.core.ports.uow import AbstractUnitOfWork
|
||||
from src.core.services import (
|
||||
AttachmentService,
|
||||
ChatService,
|
||||
@@ -30,8 +31,9 @@ from src.core.services import (
|
||||
)
|
||||
from src.infra.cache.instance import cache
|
||||
from src.infra.db import ping
|
||||
from src.infra.db.scope import session_scope
|
||||
from src.infra.db.scope import deadline_scope
|
||||
from src.infra.db.session import engine, session_factory
|
||||
from src.infra.db.uow import SqlAlchemyUnitOfWork
|
||||
from src.infra.logger import current_user_id
|
||||
from src.infra.s3.instance import object_storage
|
||||
from src.infra.upload_slots import upload_slots
|
||||
@@ -47,33 +49,32 @@ from src.utils.constants import (
|
||||
)
|
||||
|
||||
|
||||
def db_session_scope() -> AbstractAsyncContextManager[AsyncSession]:
|
||||
"""Сессия БД процесса API на один шаг; commit делает сервис.
|
||||
|
||||
`session_scope` (`src/infra/db/scope.py`) с фабрикой процесса API и
|
||||
сроком `[database] request_timeout_seconds`: незакоммиченное
|
||||
откатывается, отказ БД — 503 `unavailable`.
|
||||
"""
|
||||
return session_scope(
|
||||
async def get_uow() -> AbstractUnitOfWork:
|
||||
"""Единица работы запроса: кэш зависимостей FastAPI отдаёт вход и сервису
|
||||
один экземпляр, их блоки идут по очереди. Срок блока — `[database]
|
||||
request_timeout_seconds`."""
|
||||
return SqlAlchemyUnitOfWork(
|
||||
session_factory,
|
||||
timeout_seconds=settings.database.request_timeout_seconds,
|
||||
)
|
||||
|
||||
|
||||
async def get_db_session() -> AsyncIterator[AsyncSession]:
|
||||
"""Одна сессия БД на запрос — `db_session_scope` на весь запрос.
|
||||
UowDep = Annotated[AbstractUnitOfWork, Depends(get_uow)]
|
||||
|
||||
Зависимость с `yield` FastAPI закрывает после отправки ответа, поэтому
|
||||
срок и соединение пула охватывают и отдачу тела. Ручкам с длинной
|
||||
передачей (вложения) она не подходит: им — `CurrentUserBrief` и
|
||||
сервис с `db_session_scope` на шаг (design change `attachments`,
|
||||
решение 5).
|
||||
|
||||
async def request_deadline() -> AsyncIterator[None]:
|
||||
"""Общий срок JSON-запроса: блоки и очередь хэшей вместе, та же настройка.
|
||||
|
||||
Два блока дали бы до `2T` = 12 с при `timeout server` LB 10 с, а очередь
|
||||
хэшей осталась бы без срока (design change `unit-of-work`, решение 6).
|
||||
Зависимость с `yield` на роутере начинается раньше зависимостей ручки и
|
||||
переводит срок в ответ обработчика. Ручкам вложений не подходит: передача
|
||||
дольше срока одного блока.
|
||||
"""
|
||||
async with db_session_scope() as db_session:
|
||||
yield db_session
|
||||
|
||||
|
||||
DbSessionDep = Annotated[AsyncSession, Depends(get_db_session)]
|
||||
async with deadline_scope(
|
||||
timeout_seconds=settings.database.request_timeout_seconds,
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
async def require_database() -> None:
|
||||
@@ -88,26 +89,25 @@ async def require_database() -> None:
|
||||
raise exceptions.ServiceUnavailable from e
|
||||
|
||||
|
||||
async def get_user_service(db_session: DbSessionDep) -> UserService:
|
||||
return UserService(db_session=db_session)
|
||||
async def get_user_service(uow: UowDep) -> UserService:
|
||||
return UserService(uow=uow)
|
||||
|
||||
|
||||
async def get_chat_service(db_session: DbSessionDep) -> ChatService:
|
||||
return ChatService(db_session=db_session, cache=cache)
|
||||
async def get_chat_service(uow: UowDep) -> ChatService:
|
||||
return ChatService(uow=uow, cache=cache)
|
||||
|
||||
|
||||
async def get_message_service(db_session: DbSessionDep) -> MessageService:
|
||||
return MessageService(db_session=db_session, cache=cache)
|
||||
async def get_message_service(uow: UowDep) -> MessageService:
|
||||
return MessageService(uow=uow, cache=cache)
|
||||
|
||||
|
||||
async def get_session_service(db_session: DbSessionDep) -> SessionService:
|
||||
return SessionService(db_session=db_session)
|
||||
async def get_session_service(uow: UowDep) -> SessionService:
|
||||
return SessionService(uow=uow)
|
||||
|
||||
|
||||
async def get_attachment_service() -> AttachmentService:
|
||||
"""Без сессии запроса: сервис открывает `db_session_scope` на шаг."""
|
||||
async def get_attachment_service(uow: UowDep) -> AttachmentService:
|
||||
return AttachmentService(
|
||||
db_scope=db_session_scope,
|
||||
uow=uow,
|
||||
cache=cache,
|
||||
storage=object_storage,
|
||||
slots=upload_slots,
|
||||
@@ -221,32 +221,6 @@ async def get_current_user(
|
||||
CurrentUser = Annotated[dataclasses.UserFullDTO, Depends(get_current_user)]
|
||||
|
||||
|
||||
async def get_current_user_brief(
|
||||
credentials: Annotated[
|
||||
HTTPAuthorizationCredentials | None,
|
||||
Security(bearer_scheme),
|
||||
],
|
||||
) -> dataclasses.UserFullDTO:
|
||||
"""Пользователь по Bearer-токену с короткой сессией БД; иначе 401.
|
||||
|
||||
Обычная функция, а не генератор: сессия закрыта и соединение
|
||||
вернулось в пул до тела запроса. Для ручек с длинной передачей байтов
|
||||
(design change `attachments`, решение 5).
|
||||
"""
|
||||
async with db_session_scope() as db_session:
|
||||
current = await SessionService(db_session=db_session).authenticate(
|
||||
token=credentials.credentials if credentials else None,
|
||||
)
|
||||
current_user_id.set(str(current.user.id))
|
||||
return current.user
|
||||
|
||||
|
||||
CurrentUserBrief = Annotated[
|
||||
dataclasses.UserFullDTO,
|
||||
Depends(get_current_user_brief),
|
||||
]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PageQuery:
|
||||
limit: int
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
`v1_router` под `API_V1_PREFIX`. Новый домен регистрируется только тут.
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from src.api.dependencies import request_deadline
|
||||
from src.utils.constants import API_V1_PREFIX
|
||||
|
||||
from .attachment import router as attachment_router
|
||||
@@ -14,11 +15,15 @@ from .message import router as message_router
|
||||
from .session import router as session_router
|
||||
from .user import router as user_router
|
||||
|
||||
# общий срок JSON-запроса сверх срока блока (design change `unit-of-work`,
|
||||
# решение 6); у вложений срок только на шаг: передача дольше него
|
||||
json_deadline = [Depends(request_deadline)]
|
||||
|
||||
v1_router = APIRouter(prefix=API_V1_PREFIX)
|
||||
v1_router.include_router(user_router)
|
||||
v1_router.include_router(session_router)
|
||||
v1_router.include_router(chat_router)
|
||||
v1_router.include_router(message_router)
|
||||
v1_router.include_router(user_router, dependencies=json_deadline)
|
||||
v1_router.include_router(session_router, dependencies=json_deadline)
|
||||
v1_router.include_router(chat_router, dependencies=json_deadline)
|
||||
v1_router.include_router(message_router, dependencies=json_deadline)
|
||||
v1_router.include_router(attachment_router)
|
||||
|
||||
__all__ = [
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""Вложения: загрузка, метаданные, байты оригинала и вариантов.
|
||||
|
||||
Один роутер с двумя префиксами путей — `/chats/{chat_id}/attachments` и
|
||||
`/attachments/{attachment_id}`: домен один. Сессии БД на весь запрос
|
||||
нет: вход — `CurrentUserBrief`, сервис открывает короткую сессию на
|
||||
каждый шаг (design change `attachments`, решение 5).
|
||||
`/attachments/{attachment_id}`: домен один. Вход и шаги сервиса — отдельные
|
||||
блоки: соединение пула не занято передачей байтов. Общего срока запроса у этого
|
||||
роутера нет, только срок блока (design change `unit-of-work`, решение 6).
|
||||
"""
|
||||
|
||||
from collections.abc import AsyncIterator
|
||||
@@ -15,7 +15,7 @@ from fastapi.responses import StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from src.api.dependencies import AttachmentServiceDep, CurrentUserBrief
|
||||
from src.api.dependencies import AttachmentServiceDep, CurrentUser
|
||||
from src.api.schemas import Attachment, DisplayFilename, UuidIn
|
||||
from src.core import exceptions
|
||||
from src.schemas.enums import AttachmentVariantName, ImageType
|
||||
@@ -107,7 +107,7 @@ async def _body(request: Request) -> AsyncIterator[bytes]:
|
||||
openapi_extra=_UPLOAD_BODY,
|
||||
)
|
||||
async def upload_attachment(
|
||||
user: CurrentUserBrief,
|
||||
user: CurrentUser,
|
||||
chat_id: UuidIn,
|
||||
filename: FilenameQuery,
|
||||
request: Request,
|
||||
@@ -135,7 +135,7 @@ async def upload_attachment(
|
||||
|
||||
@router.get("/attachments/{attachment_id}", response_model=Attachment)
|
||||
async def get_attachment(
|
||||
user: CurrentUserBrief,
|
||||
user: CurrentUser,
|
||||
attachment_id: UuidIn,
|
||||
attachments: AttachmentServiceDep,
|
||||
) -> Attachment:
|
||||
@@ -152,7 +152,7 @@ async def get_attachment(
|
||||
responses=_DOWNLOAD_RESPONSES,
|
||||
)
|
||||
async def download_attachment(
|
||||
user: CurrentUserBrief,
|
||||
user: CurrentUser,
|
||||
attachment_id: UuidIn,
|
||||
attachments: AttachmentServiceDep,
|
||||
# перечисление контракта; иное значение — 400 по схеме
|
||||
|
||||
+6
-8
@@ -27,11 +27,9 @@ import argparse
|
||||
import asyncio
|
||||
import math
|
||||
import signal
|
||||
from contextlib import AbstractAsyncContextManager, suppress
|
||||
from contextlib import suppress
|
||||
from datetime import timedelta
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.config import settings
|
||||
from src.config.settings import Settings
|
||||
from src.core.services import (
|
||||
@@ -41,7 +39,7 @@ from src.core.services import (
|
||||
from src.core.services.attachment_cleanup import INTERRUPTED_BY_STOP
|
||||
from src.infra import early_stop
|
||||
from src.infra.db import create_engine, create_session_factory
|
||||
from src.infra.db.scope import session_scope
|
||||
from src.infra.db.uow import SqlAlchemyUnitOfWork
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.infra.s3 import create_object_storage
|
||||
from src.schemas import dataclasses
|
||||
@@ -209,14 +207,14 @@ async def run(
|
||||
namespace=settings.database.name,
|
||||
)
|
||||
|
||||
def db_scope() -> AbstractAsyncContextManager[AsyncSession]:
|
||||
return session_scope(
|
||||
def make_uow() -> SqlAlchemyUnitOfWork:
|
||||
return SqlAlchemyUnitOfWork(
|
||||
session_factory,
|
||||
timeout_seconds=settings.database.request_timeout_seconds,
|
||||
)
|
||||
|
||||
cleanup = AttachmentCleanupService(db_scope=db_scope, storage=storage)
|
||||
reconcile = AttachmentReconcileService(db_scope=db_scope, storage=storage)
|
||||
cleanup = AttachmentCleanupService(uow=make_uow(), storage=storage)
|
||||
reconcile = AttachmentReconcileService(uow=make_uow(), storage=storage)
|
||||
exit_code = EXIT_OK
|
||||
try:
|
||||
if not (
|
||||
|
||||
@@ -96,8 +96,10 @@ class Database(BaseModel):
|
||||
connect_timeout_seconds: float = Field(default=3, gt=0)
|
||||
# миллисекунды, серверный statement_timeout; 0 — без ограничения
|
||||
statement_timeout_ms: int = Field(default=5000, ge=0)
|
||||
# секунды на всю работу запроса с БД (asyncio): зависший сервер или
|
||||
# обрыв сети, где серверный таймаут не сработает
|
||||
# секунды на блок единицы работы, вместе с откатом при выходе (asyncio):
|
||||
# зависший сервер или обрыв сети, где серверный таймаут не сработает. На
|
||||
# JSON-ручке тот же срок ещё и на весь запрос (`request_deadline`): все
|
||||
# его блоки и очередь хэшей пароля вместе
|
||||
request_timeout_seconds: float = Field(default=6, gt=0)
|
||||
# миллисекунды, серверный idle_in_transaction_session_timeout: открытую
|
||||
# транзакцию замороженной реплики PostgreSQL прерывает и снимает её
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Порты слоя данных: абстрактные repo и единица работы.
|
||||
|
||||
Сервисы зависят только от них (design change `unit-of-work`, решение 1).
|
||||
Реализации на SQLAlchemy — `src/core/repos/` и `src/infra/db/uow.py`, их
|
||||
выбирают точки входа процессов.
|
||||
"""
|
||||
@@ -0,0 +1,233 @@
|
||||
import abc
|
||||
from collections.abc import Collection
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from src.schemas import dataclasses
|
||||
from src.schemas.enums import AttachmentErrorCode, AttachmentStatus
|
||||
|
||||
|
||||
class AbstractAttachmentRepository(abc.ABC):
|
||||
"""Метаданные вложений. Видимость `pending` решает сервис: repo отдаёт
|
||||
строку как есть. `updated_at` переходов растёт и не отстаёт от прежнего:
|
||||
часы процессов расходятся."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def insert_attachment(
|
||||
self,
|
||||
*,
|
||||
attachment: dataclasses.AttachmentFullDTO,
|
||||
) -> dataclasses.AttachmentFullDTO:
|
||||
"""Строка вложения со всеми колонками DTO."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def mark_queued(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
updated_at: datetime,
|
||||
) -> dataclasses.AttachmentFullDTO | None:
|
||||
"""`pending` → `queued`, только у непомеченной строки (`updated_at`
|
||||
равен `created_at`). `None` — строки `pending` нет или уборщик уже
|
||||
пометил её к уборке."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def mark_processing(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
updated_at: datetime,
|
||||
) -> bool:
|
||||
"""`queued` или `processing` (прежняя попытка потеряна) → `processing`.
|
||||
`ready` и `failed` не трогаются: `False`."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def return_to_queued(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
updated_at: datetime,
|
||||
) -> bool:
|
||||
"""Временная ошибка: `processing` → `queued`; `False` — статус другой."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def return_group_to_queued(
|
||||
self,
|
||||
*,
|
||||
attachment_ids: Collection[UUID],
|
||||
updated_at: datetime,
|
||||
) -> int:
|
||||
"""Истёкшие аренды пакета: `processing` → `queued`; результат — сколько
|
||||
строк переведено, строки других статусов не меняются."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def replay_failed(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
updated_at: datetime,
|
||||
) -> bool:
|
||||
"""Replay: `failed` → `queued`, `error_code` снимается. `False` —
|
||||
условие уже не выполняется."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def lock_attachment(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
) -> dataclasses.AttachmentFullDTO | None:
|
||||
"""Строка под блокировкой, которая не мешает отправке сообщения со
|
||||
ссылкой на вложение; `None` — строки нет."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get_staging_candidates(
|
||||
self,
|
||||
*,
|
||||
status: AttachmentStatus,
|
||||
updated_before: datetime | None,
|
||||
after: tuple[datetime, UUID] | None,
|
||||
limit: int,
|
||||
) -> list[dataclasses.AttachmentInListDTO]:
|
||||
"""Вложения этого статуса с объектом staging и `updated_at` раньше
|
||||
`updated_before` (если задан), keyset по `(updated_at, id)`, без
|
||||
блокировки."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def lock_staging_candidate(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
status: AttachmentStatus,
|
||||
updated_before: datetime | None,
|
||||
) -> dataclasses.AttachmentInListDTO | None:
|
||||
"""Та же строка с теми же условиями под блокировкой до конца
|
||||
транзакции. `None` — условия уже нет или строку держат."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def clear_staging_key(self, *, attachment_id: UUID) -> bool:
|
||||
"""Объект staging убран; `updated_at` не меняется. `False` — строки
|
||||
нет."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def commit_ready(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
updated_at: datetime,
|
||||
) -> bool:
|
||||
"""`queued` или `processing` → `ready`; `False` — итог уже есть:
|
||||
готовое вложение не откатывается и не меняет `updated_at`."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def commit_failed(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
error_code: AttachmentErrorCode,
|
||||
updated_at: datetime,
|
||||
) -> bool:
|
||||
"""`queued` или `processing` → `failed` с кодом; `False` — итог уже
|
||||
есть."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get_attachment(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
) -> dataclasses.AttachmentFullDTO | None:
|
||||
"""Строка без подстановки вариантов; `None` — строки нет."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get_attachments(
|
||||
self,
|
||||
*,
|
||||
attachment_ids: Collection[UUID],
|
||||
) -> list[dataclasses.AttachmentFullDTO]:
|
||||
"""Найденные строки по `id`, в любом порядке."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get_stale_pending(
|
||||
self,
|
||||
*,
|
||||
older_than: datetime,
|
||||
after: tuple[datetime, UUID] | None,
|
||||
limit: int,
|
||||
) -> list[dataclasses.AttachmentInListDTO]:
|
||||
"""Строки `pending` с `created_at` раньше `older_than`, keyset по
|
||||
`(created_at, id)` после `after`, без блокировки."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def lock_stale_pending(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
older_than: datetime,
|
||||
) -> dataclasses.AttachmentInListDTO | None:
|
||||
"""Та же строка с теми же условиями под блокировкой до конца
|
||||
транзакции. `None` — строки уже нет, она не `pending` или её держит
|
||||
другой процесс."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def mark_removing(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
updated_at: datetime,
|
||||
) -> bool:
|
||||
"""Пометить строку к уборке: `updated_at` позже `created_at`, и
|
||||
`mark_queued` её больше не переведёт. `False` — строки нет."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def delete_attachment(self, *, attachment_id: UUID) -> bool:
|
||||
"""Удалить строку; `False` — строки не было."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get_attachments_for_objects(
|
||||
self,
|
||||
*,
|
||||
attachment_ids: Collection[UUID],
|
||||
object_keys: Collection[str],
|
||||
) -> list[dataclasses.AttachmentFullDTO]:
|
||||
"""Строки страницы списка S3: `id` из `attachment_ids` или `object_key`
|
||||
из `object_keys`."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get_ready_page(
|
||||
self,
|
||||
*,
|
||||
after: UUID | None,
|
||||
limit: int,
|
||||
) -> list[dataclasses.AttachmentFullDTO]:
|
||||
"""Строки `ready` в порядке `id` после `after`."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def find_attachment_reference(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
object_key: str,
|
||||
) -> list[dataclasses.AttachmentFullDTO]:
|
||||
"""Строки, из-за которых объект нельзя удалить: строка этого `id` или
|
||||
любая строка с этим ключом."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def mark_lost(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
object_key: str,
|
||||
lost_at: datetime,
|
||||
) -> bool:
|
||||
"""Пометить оригинал потерянным: только `ready`, ещё не помеченное, с
|
||||
тем же ключом. `status` и `updated_at` не меняются. `False` — условие
|
||||
уже не выполняется."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def clear_lost(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
object_key: str,
|
||||
) -> bool:
|
||||
"""Снять пометку: оригинал снова есть. `False` — пометки нет или ключ
|
||||
другой."""
|
||||
@@ -0,0 +1,153 @@
|
||||
import abc
|
||||
from collections.abc import Collection
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from src.schemas import dataclasses
|
||||
from src.schemas.enums import AttachmentJobReason, AttachmentJobState
|
||||
|
||||
|
||||
class AbstractAttachmentJobRepository(abc.ABC):
|
||||
"""Задание обработки: одно на вложение и версию; `queued` без `published_at`
|
||||
— намерение, которое публикует relay. `attempt` монотонен, это
|
||||
fencing-токен. Порядок блокировок везде один: задание, затем вложение."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def insert_job(
|
||||
self,
|
||||
*,
|
||||
job: dataclasses.AttachmentJobDTO,
|
||||
) -> dataclasses.AttachmentJobDTO:
|
||||
"""Новая работа; вложение становится `queued` в той же транзакции."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def lock_job(
|
||||
self,
|
||||
*,
|
||||
job_id: UUID,
|
||||
) -> dataclasses.AttachmentJobDTO | None:
|
||||
"""Задание под блокировкой до конца транзакции (ждёт чужую); `None` —
|
||||
задания нет."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get_job(
|
||||
self,
|
||||
*,
|
||||
job_id: UUID,
|
||||
) -> dataclasses.AttachmentJobDTO | None:
|
||||
"""Задание без блокировки; `None` — задания нет."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get_attachment_job(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
pipeline_version: int,
|
||||
) -> dataclasses.AttachmentJobDTO | None:
|
||||
"""Задание вложения этой версии; `None` — задания нет."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def start_attempt(
|
||||
self,
|
||||
*,
|
||||
job_id: UUID,
|
||||
lease_expires_at: datetime,
|
||||
now: datetime,
|
||||
) -> dataclasses.AttachmentJobDTO | None:
|
||||
"""Начать попытку: счётчик +1, срок аренды, `processing`, срок
|
||||
следующей попытки снят. Вызывающий под блокировкой проверил, что итога
|
||||
и живой аренды нет. `None` — задания нет."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def return_to_queued(
|
||||
self,
|
||||
*,
|
||||
job_id: UUID,
|
||||
attempt: int,
|
||||
reason: AttachmentJobReason,
|
||||
next_attempt_at: datetime,
|
||||
now: datetime,
|
||||
) -> bool:
|
||||
"""Временная ошибка: `processing` → `queued`, только своя попытка (номер
|
||||
совпал), со сроком следующей; `published_at` снят. `False` — задание
|
||||
ведёт другая попытка или есть итог."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def finish_job(
|
||||
self,
|
||||
*,
|
||||
job_id: UUID,
|
||||
state: AttachmentJobState,
|
||||
reason: AttachmentJobReason | None,
|
||||
now: datetime,
|
||||
) -> bool:
|
||||
"""Итог задания: `succeeded` или `failed`, под блокировкой `lock_job`;
|
||||
аренда и срок следующей попытки сняты, причина меняется, только если
|
||||
задана. `False` — задания нет."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def lock_due_jobs(
|
||||
self,
|
||||
*,
|
||||
now: datetime,
|
||||
limit: int,
|
||||
) -> list[dataclasses.AttachmentJobDTO]:
|
||||
"""Намерения, срок которых наступил (`next_attempt_at`, иначе
|
||||
`created_at`), в порядке срока и `id`. Задание, которое публикует другой
|
||||
relay, пропускается. Блокировка — до конца транзакции."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def count_published(self) -> int:
|
||||
"""Опубликованные и не взятые задания: то, что считает предел."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def mark_published(
|
||||
self,
|
||||
*,
|
||||
job_ids: Collection[UUID],
|
||||
now: datetime,
|
||||
) -> int:
|
||||
"""Брокер подтвердил сообщения пакета: `published_at` = `now`;
|
||||
результат — число отмеченных."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def recover_expired_leases(
|
||||
self,
|
||||
*,
|
||||
now: datetime,
|
||||
limit: int,
|
||||
) -> list[dataclasses.AttachmentJobDTO]:
|
||||
"""Истёкшие аренды: `processing` → `queued` без паузы, причина
|
||||
`lease_expired`, отметка публикации снята; результат — новые строки.
|
||||
Вложения тех же `id` переводит вызывающий в той же транзакции."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def has_published_before(self, *, older_than: datetime) -> bool:
|
||||
"""Есть ли `queued` с отметкой публикации старше порога: кандидаты в
|
||||
потерянные."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def reset_published_before(
|
||||
self,
|
||||
*,
|
||||
older_than: datetime,
|
||||
now: datetime,
|
||||
) -> int:
|
||||
"""Потерянные сообщения: отметка старше порога снимается, задание снова
|
||||
намерение; результат — число строк."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def replay_job(self, *, job_id: UUID, now: datetime) -> bool:
|
||||
"""`failed` → `queued` с новым бюджетом (`attempt_base = attempt`),
|
||||
причина, сроки и отметка публикации сняты. `False` — состояние другое."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def list_failed(
|
||||
self,
|
||||
*,
|
||||
error_code: str | None,
|
||||
reason: str | None,
|
||||
limit: int,
|
||||
) -> list[dataclasses.FailedJobDTO]:
|
||||
"""Реестр `failed`, новые раньше (`finished_at` по убыванию, затем
|
||||
`id`), с фильтрами по коду вложения и причине задания."""
|
||||
@@ -0,0 +1,22 @@
|
||||
import abc
|
||||
from uuid import UUID
|
||||
|
||||
from src.schemas import dataclasses
|
||||
|
||||
|
||||
class AbstractAttachmentJobReplayRepository(abc.ABC):
|
||||
@abc.abstractmethod
|
||||
async def insert_replay(
|
||||
self,
|
||||
*,
|
||||
replay: dataclasses.AttachmentJobReplayDTO,
|
||||
) -> dataclasses.AttachmentJobReplayDTO:
|
||||
"""Запись аудита; пишется одной транзакцией с возвратом задания."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get_job_replays(
|
||||
self,
|
||||
*,
|
||||
job_id: UUID,
|
||||
) -> list[dataclasses.AttachmentJobReplayDTO]:
|
||||
"""Записи аудита задания в порядке `(created_at, id)`."""
|
||||
@@ -0,0 +1,34 @@
|
||||
import abc
|
||||
from uuid import UUID
|
||||
|
||||
from src.schemas import dataclasses
|
||||
from src.schemas.enums import AttachmentVariantName
|
||||
|
||||
|
||||
class AbstractAttachmentVariantRepository(abc.ABC):
|
||||
@abc.abstractmethod
|
||||
async def insert_variant(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
variant: dataclasses.AttachmentVariantDTO,
|
||||
) -> bool:
|
||||
"""Вариант по ключу эффекта `(attachment_id, pipeline_version, имя)`;
|
||||
`False` — такой уже есть, строка не изменилась."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get_variants(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
) -> list[dataclasses.AttachmentVariantDTO]:
|
||||
"""Варианты вложения в постоянном порядке — по имени."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get_variant(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
name: AttachmentVariantName,
|
||||
) -> dataclasses.AttachmentVariantDTO | None:
|
||||
"""Один вариант по имени, самой новой версии обработки; `None` — нет."""
|
||||
@@ -0,0 +1,43 @@
|
||||
import abc
|
||||
from uuid import UUID
|
||||
|
||||
from src.schemas import dataclasses
|
||||
from src.utils.cursor import CursorKey
|
||||
|
||||
|
||||
class AbstractChatRepository(abc.ABC):
|
||||
@abc.abstractmethod
|
||||
async def insert_chat(
|
||||
self,
|
||||
*,
|
||||
chat: dataclasses.ChatFullDTO,
|
||||
) -> dataclasses.ChatFullDTO:
|
||||
"""Только строка чата; участников пишет `insert_chat_members`."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def insert_chat_members(
|
||||
self,
|
||||
*,
|
||||
chat: dataclasses.ChatFullDTO,
|
||||
) -> int:
|
||||
"""Все участники одной вставкой, позиция — порядок в `member_ids`;
|
||||
результат — число строк."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get_chat(
|
||||
self,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
) -> dataclasses.ChatFullDTO | None:
|
||||
"""Чат с участниками в порядке создания; `None` — чата нет."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get_user_chats_page(
|
||||
self,
|
||||
*,
|
||||
user_id: UUID,
|
||||
after: CursorKey | None,
|
||||
limit: int,
|
||||
) -> list[dataclasses.ChatFullDTO]:
|
||||
"""До `limit + 1` чатов пользователя строго после ключа `after`, в
|
||||
порядке `(created_at, id)`."""
|
||||
@@ -0,0 +1,38 @@
|
||||
import abc
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from src.schemas import dataclasses
|
||||
|
||||
|
||||
class AbstractIdempotencyRepository(abc.ABC):
|
||||
@abc.abstractmethod
|
||||
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:
|
||||
"""Захват ключа под новое сообщение `message_id`.
|
||||
|
||||
`True` — ключ свободен: новый или просроченный (`created_at` раньше
|
||||
`expired_before`), он заменён этим же вызовом. `False` — ключ занят и
|
||||
действует, запись не изменилась. Занятая строка заблокирована до конца
|
||||
транзакции.
|
||||
"""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get_key_result(
|
||||
self,
|
||||
*,
|
||||
user_id: UUID,
|
||||
chat_id: UUID,
|
||||
key: str,
|
||||
) -> dataclasses.IdempotencyRecordDTO | None:
|
||||
"""Хэш тела и сообщение с вложениями, сохранённые под ключом; `None` —
|
||||
ключа нет."""
|
||||
@@ -0,0 +1,38 @@
|
||||
import abc
|
||||
from uuid import UUID
|
||||
|
||||
from src.schemas import dataclasses
|
||||
from src.utils.cursor import CursorKey
|
||||
|
||||
|
||||
class AbstractMessageRepository(abc.ABC):
|
||||
@abc.abstractmethod
|
||||
async def insert_message(
|
||||
self,
|
||||
*,
|
||||
message: dataclasses.MessageFullDTO,
|
||||
instance_id: str,
|
||||
) -> dataclasses.MessageFullDTO:
|
||||
"""Строка сообщения; `instance_id` — реплика, которая его записала
|
||||
(только для диагностики, в DTO и ответ не попадает). Связи с вложениями
|
||||
пишет `insert_message_attachments`."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def insert_message_attachments(
|
||||
self,
|
||||
*,
|
||||
message: dataclasses.MessageFullDTO,
|
||||
) -> int:
|
||||
"""Все связи одной вставкой, позиция — место в `attachment_ids`;
|
||||
вызывается только с непустым списком. Результат — число строк."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get_chat_messages_page(
|
||||
self,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
after: CursorKey | None,
|
||||
limit: int,
|
||||
) -> list[dataclasses.MessageFullDTO]:
|
||||
"""До `limit + 1` сообщений чата строго после ключа `after`, в порядке
|
||||
`(created_at, id)`; `attachment_ids` — в порядке отправки."""
|
||||
@@ -0,0 +1,32 @@
|
||||
import abc
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from src.schemas import dataclasses
|
||||
|
||||
|
||||
class AbstractSessionRepository(abc.ABC):
|
||||
@abc.abstractmethod
|
||||
async def insert_session(
|
||||
self,
|
||||
*,
|
||||
session: dataclasses.SessionFullDTO,
|
||||
) -> dataclasses.SessionFullDTO:
|
||||
"""Новая сессия."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get_current_session(
|
||||
self,
|
||||
*,
|
||||
token_hash: bytes,
|
||||
now: datetime,
|
||||
) -> dataclasses.CurrentSessionDTO | None:
|
||||
"""Действующая сессия по хэшу токена вместе с владельцем.
|
||||
|
||||
`None` — хэша нет или `expires_at <= now`; `now` передаёт сервис:
|
||||
срок сравнивается по часам приложения, которые его и поставили.
|
||||
"""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def delete_session(self, *, session_id: UUID) -> bool:
|
||||
"""Отзыв; `False` — сессию уже удалил параллельный запрос."""
|
||||
@@ -0,0 +1,173 @@
|
||||
"""Единица работы: одна граница транзакции в сервисе (design change
|
||||
`unit-of-work`, решения 2 и 3; Cosmic Python, глава 6).
|
||||
|
||||
```python
|
||||
async with self.uow:
|
||||
job = await self.uow.jobs.lock_job(job_id=job_id)
|
||||
if job is None:
|
||||
return JobOutcome.ACK # выход без commit — откат
|
||||
await self.uow.jobs.finish_job(...)
|
||||
await self.uow.commit()
|
||||
```
|
||||
|
||||
Один блок — одна транзакция. Отличия от книги: вложенный вход — ошибка, а не
|
||||
второе соединение; repo доступны только внутри блока и до `commit`: сессия после
|
||||
фиксации молча начала бы новую транзакцию без срока и отката. Правила — здесь,
|
||||
реальные шаги — у реализаций, поэтому фейк ловит те же ошибки, что и настоящая
|
||||
единица работы. Экземпляр принадлежит одной задаче: у него открытая сессия.
|
||||
"""
|
||||
|
||||
import abc
|
||||
from dataclasses import dataclass
|
||||
from types import TracebackType
|
||||
from typing import Self
|
||||
|
||||
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
|
||||
|
||||
|
||||
class UnitOfWorkError(RuntimeError):
|
||||
"""Нарушено правило блока: это ошибка программирования, а не отказ
|
||||
хранилища, поэтому до клиента она доходит как 500."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Repositories:
|
||||
"""Repo одного блока: реализация создаёт их при входе."""
|
||||
|
||||
users: AbstractUserRepository
|
||||
sessions: AbstractSessionRepository
|
||||
chats: AbstractChatRepository
|
||||
messages: AbstractMessageRepository
|
||||
idempotency: AbstractIdempotencyRepository
|
||||
attachments: AbstractAttachmentRepository
|
||||
jobs: AbstractAttachmentJobRepository
|
||||
variants: AbstractAttachmentVariantRepository
|
||||
job_replays: AbstractAttachmentJobReplayRepository
|
||||
|
||||
|
||||
class AbstractUnitOfWork(abc.ABC):
|
||||
"""`blocks_opened` — сколько раз входили в блок: итог сверки называет его
|
||||
`db_sessions`."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.blocks_opened = 0
|
||||
self._entered = False
|
||||
self._repositories: Repositories | None = None
|
||||
|
||||
async def __aenter__(self) -> Self:
|
||||
if self._entered:
|
||||
raise UnitOfWorkError("Unit of work block is already open")
|
||||
self._entered = True
|
||||
self.blocks_opened += 1
|
||||
try:
|
||||
self._repositories = await self._open()
|
||||
except BaseException:
|
||||
self._entered = False
|
||||
raise
|
||||
return self
|
||||
|
||||
async def __aexit__(
|
||||
self,
|
||||
exc_type: type[BaseException] | None,
|
||||
exc: BaseException | None,
|
||||
tb: TracebackType | None,
|
||||
) -> bool | None:
|
||||
self._repositories = None
|
||||
self._entered = False
|
||||
return await self._close(exc_type, exc, tb)
|
||||
|
||||
async def commit(self) -> None:
|
||||
"""Зафиксировать и закончить блок: дальше repo недоступны, следующая
|
||||
транзакция — следующим блоком. Сбой фиксации тоже заканчивает блок."""
|
||||
self._require_open("commit")
|
||||
self._repositories = None
|
||||
await self._commit()
|
||||
|
||||
async def rollback(self) -> None:
|
||||
"""Откатить и закончить блок раньше выхода из него."""
|
||||
self._require_open("rollback")
|
||||
self._repositories = None
|
||||
await self._rollback()
|
||||
|
||||
@property
|
||||
def users(self) -> AbstractUserRepository:
|
||||
return self._repos().users
|
||||
|
||||
@property
|
||||
def sessions(self) -> AbstractSessionRepository:
|
||||
return self._repos().sessions
|
||||
|
||||
@property
|
||||
def chats(self) -> AbstractChatRepository:
|
||||
return self._repos().chats
|
||||
|
||||
@property
|
||||
def messages(self) -> AbstractMessageRepository:
|
||||
return self._repos().messages
|
||||
|
||||
@property
|
||||
def idempotency(self) -> AbstractIdempotencyRepository:
|
||||
return self._repos().idempotency
|
||||
|
||||
@property
|
||||
def attachments(self) -> AbstractAttachmentRepository:
|
||||
return self._repos().attachments
|
||||
|
||||
@property
|
||||
def jobs(self) -> AbstractAttachmentJobRepository:
|
||||
return self._repos().jobs
|
||||
|
||||
@property
|
||||
def variants(self) -> AbstractAttachmentVariantRepository:
|
||||
return self._repos().variants
|
||||
|
||||
@property
|
||||
def job_replays(self) -> AbstractAttachmentJobReplayRepository:
|
||||
return self._repos().job_replays
|
||||
|
||||
def _repos(self) -> Repositories:
|
||||
if self._repositories is None:
|
||||
raise UnitOfWorkError(
|
||||
"Repository is available only inside an open block",
|
||||
)
|
||||
return self._repositories
|
||||
|
||||
def _require_open(self, action: str) -> None:
|
||||
if self._repositories is None:
|
||||
raise UnitOfWorkError(
|
||||
f"Unit of work has no open transaction to {action}",
|
||||
)
|
||||
|
||||
@abc.abstractmethod
|
||||
async def _open(self) -> Repositories:
|
||||
"""Начать блок и создать его repo."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def _close(
|
||||
self,
|
||||
exc_type: type[BaseException] | None,
|
||||
exc: BaseException | None,
|
||||
tb: TracebackType | None,
|
||||
) -> bool | None:
|
||||
"""Закончить блок: незафиксированное откатывается, соединение
|
||||
возвращается. Результат — как у `__aexit__`."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def _commit(self) -> None:
|
||||
"""Зафиксировать транзакцию блока."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def _rollback(self) -> None:
|
||||
"""Откатить транзакцию блока."""
|
||||
@@ -0,0 +1,33 @@
|
||||
import abc
|
||||
from collections.abc import Iterable
|
||||
from uuid import UUID
|
||||
|
||||
from src.schemas import dataclasses
|
||||
|
||||
|
||||
class AbstractUserRepository(abc.ABC):
|
||||
@abc.abstractmethod
|
||||
async def insert_user(
|
||||
self,
|
||||
*,
|
||||
user: dataclasses.UserFullDTO,
|
||||
password_hash: str,
|
||||
) -> dataclasses.UserFullDTO | None:
|
||||
"""Вставка; `None` — username занят (уникальность держит хранилище,
|
||||
а не проверка перед вставкой)."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get_user_credentials(
|
||||
self,
|
||||
*,
|
||||
username: str,
|
||||
) -> dataclasses.UserCredentialsDTO | None:
|
||||
"""Пользователь и хэш пароля; `None` — такого username нет."""
|
||||
|
||||
@abc.abstractmethod
|
||||
async def get_existing_user_ids(
|
||||
self,
|
||||
*,
|
||||
user_ids: Iterable[UUID],
|
||||
) -> set[UUID]:
|
||||
"""Те из переданных id, для которых пользователь существует."""
|
||||
+501
-504
File diff suppressed because it is too large
Load Diff
+321
-329
@@ -31,6 +31,7 @@ from sqlalchemy import (
|
||||
from sqlalchemy.dialects.postgresql import ARRAY
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.core.ports.attachment_job import AbstractAttachmentJobRepository
|
||||
from src.infra.db.models import Attachment, AttachmentJob
|
||||
from src.schemas import dataclasses
|
||||
from src.schemas.enums import (
|
||||
@@ -87,345 +88,336 @@ def _later_of_now(now: datetime) -> ColumnElement[datetime]:
|
||||
return func.greatest(now, AttachmentJob.updated_at)
|
||||
|
||||
|
||||
async def insert_job(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
job: dataclasses.AttachmentJobDTO,
|
||||
) -> dataclasses.AttachmentJobDTO:
|
||||
"""Новая работа; вложение становится `queued` в той же транзакции."""
|
||||
await db_session.execute(
|
||||
insert(AttachmentJob).values(
|
||||
id=job.id,
|
||||
attachment_id=job.attachment_id,
|
||||
pipeline_version=job.pipeline_version,
|
||||
state=job.state.value,
|
||||
attempt=job.attempt,
|
||||
created_at=job.created_at,
|
||||
updated_at=job.updated_at,
|
||||
),
|
||||
)
|
||||
return job
|
||||
class SqlAlchemyAttachmentJobRepository(AbstractAttachmentJobRepository):
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self._session = session
|
||||
|
||||
|
||||
async def lock_job(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
job_id: UUID,
|
||||
) -> dataclasses.AttachmentJobDTO | None:
|
||||
"""Задание под `FOR UPDATE` до конца транзакции."""
|
||||
statement = (
|
||||
select(*_JOB_COLUMNS)
|
||||
.where(AttachmentJob.id == job_id)
|
||||
.with_for_update()
|
||||
)
|
||||
row = (await db_session.execute(statement)).one_or_none()
|
||||
return None if row is None else _to_dto(row)
|
||||
|
||||
|
||||
async def get_job(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
job_id: UUID,
|
||||
) -> dataclasses.AttachmentJobDTO | None:
|
||||
statement = select(*_JOB_COLUMNS).where(AttachmentJob.id == job_id)
|
||||
row = (await db_session.execute(statement)).one_or_none()
|
||||
return None if row is None else _to_dto(row)
|
||||
|
||||
|
||||
async def get_attachment_job(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
pipeline_version: int,
|
||||
) -> dataclasses.AttachmentJobDTO | None:
|
||||
statement = select(*_JOB_COLUMNS).where(
|
||||
AttachmentJob.attachment_id == attachment_id,
|
||||
AttachmentJob.pipeline_version == pipeline_version,
|
||||
)
|
||||
row = (await db_session.execute(statement)).one_or_none()
|
||||
return None if row is None else _to_dto(row)
|
||||
|
||||
|
||||
async def start_attempt(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
job_id: UUID,
|
||||
lease_expires_at: datetime,
|
||||
now: datetime,
|
||||
) -> dataclasses.AttachmentJobDTO | None:
|
||||
"""Начать попытку под блокировкой `lock_job`: счётчик +1, срок аренды,
|
||||
`processing`. Вызывающий проверил, что итога и живой аренды нет."""
|
||||
statement = (
|
||||
update(AttachmentJob)
|
||||
.where(AttachmentJob.id == job_id)
|
||||
.values(
|
||||
state=AttachmentJobState.PROCESSING.value,
|
||||
attempt=AttachmentJob.attempt + 1,
|
||||
lease_expires_at=lease_expires_at,
|
||||
next_attempt_at=None,
|
||||
updated_at=_later_of_now(now),
|
||||
)
|
||||
.returning(*_JOB_COLUMNS)
|
||||
)
|
||||
row = (await db_session.execute(statement)).one_or_none()
|
||||
return None if row is None else _to_dto(row)
|
||||
|
||||
|
||||
async def return_to_queued(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
job_id: UUID,
|
||||
attempt: int,
|
||||
reason: AttachmentJobReason,
|
||||
next_attempt_at: datetime,
|
||||
now: datetime,
|
||||
) -> bool:
|
||||
"""Временная ошибка: `processing` → `queued`, только своя попытка (номер
|
||||
совпал), со сроком следующей. Сообщение ещё не передано, его опубликует
|
||||
relay: `published_at` — NULL. `False` — задание уже ведёт другая попытка или
|
||||
есть итог."""
|
||||
statement = (
|
||||
update(AttachmentJob)
|
||||
.where(
|
||||
AttachmentJob.id == job_id,
|
||||
AttachmentJob.state == AttachmentJobState.PROCESSING.value,
|
||||
AttachmentJob.attempt == attempt,
|
||||
)
|
||||
.values(
|
||||
state=AttachmentJobState.QUEUED.value,
|
||||
last_error_code=reason.value,
|
||||
next_attempt_at=next_attempt_at,
|
||||
lease_expires_at=None,
|
||||
published_at=None,
|
||||
updated_at=_later_of_now(now),
|
||||
)
|
||||
.returning(AttachmentJob.id)
|
||||
)
|
||||
return (await db_session.execute(statement)).one_or_none() is not None
|
||||
|
||||
|
||||
async def finish_job(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
job_id: UUID,
|
||||
state: AttachmentJobState,
|
||||
reason: AttachmentJobReason | None,
|
||||
now: datetime,
|
||||
) -> bool:
|
||||
"""Итог задания: `succeeded` или `failed`, под блокировкой `lock_job`."""
|
||||
values: dict[str, object] = {
|
||||
"state": state.value,
|
||||
"lease_expires_at": None,
|
||||
"next_attempt_at": None,
|
||||
"finished_at": now,
|
||||
"updated_at": _later_of_now(now),
|
||||
}
|
||||
if reason is not None:
|
||||
values["last_error_code"] = reason.value
|
||||
statement = (
|
||||
update(AttachmentJob)
|
||||
.where(AttachmentJob.id == job_id)
|
||||
.values(**values)
|
||||
.returning(AttachmentJob.id)
|
||||
)
|
||||
return (await db_session.execute(statement)).one_or_none() is not None
|
||||
|
||||
|
||||
async def lock_due_jobs(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
now: datetime,
|
||||
limit: int,
|
||||
) -> list[dataclasses.AttachmentJobDTO]:
|
||||
"""Намерения, срок которых наступил, в порядке срока, под `FOR UPDATE SKIP
|
||||
LOCKED`: задание, которое публикует другой relay, пропускается. Блокировка
|
||||
держится до отметки: worker, получивший сообщение раньше COMMIT, ждёт её в
|
||||
`lock_job`."""
|
||||
statement = (
|
||||
select(*_JOB_COLUMNS)
|
||||
.where(*_outbox_condition(), now >= _DUE_AT)
|
||||
.order_by(_DUE_AT, AttachmentJob.id)
|
||||
.limit(limit)
|
||||
.with_for_update(skip_locked=True)
|
||||
)
|
||||
rows = (await db_session.execute(statement)).all()
|
||||
return [_to_dto(row) for row in rows]
|
||||
|
||||
|
||||
async def count_published(db_session: AsyncSession) -> int:
|
||||
"""Опубликованные и не взятые задания: то, что считает предел."""
|
||||
statement = (
|
||||
select(func.count())
|
||||
.select_from(AttachmentJob)
|
||||
.where(_queued(), AttachmentJob.published_at.is_not(None))
|
||||
)
|
||||
return (await db_session.execute(statement)).scalar_one()
|
||||
|
||||
|
||||
async def mark_published(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
job_ids: Collection[UUID],
|
||||
now: datetime,
|
||||
) -> int:
|
||||
"""Брокер подтвердил сообщения пакета: время — отметка, а не условие.
|
||||
Вызывается под блокировкой `lock_due_jobs`."""
|
||||
statement = (
|
||||
update(AttachmentJob)
|
||||
.where(AttachmentJob.id == any_(_uuid_array(job_ids)))
|
||||
.values(published_at=now, updated_at=_later_of_now(now))
|
||||
.returning(AttachmentJob.id)
|
||||
)
|
||||
return len((await db_session.execute(statement)).all())
|
||||
|
||||
|
||||
async def recover_expired_leases(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
now: datetime,
|
||||
limit: int,
|
||||
) -> list[dataclasses.AttachmentJobDTO]:
|
||||
"""Истёкшие аренды: `processing` → `queued` без паузы, причина «истёк срок
|
||||
аренды» (design change `pipeline-reliability`, решения 2 и 3). Вложения
|
||||
тех же `id` переводит вызывающий в той же транзакции: порядок блокировок
|
||||
— задание, затем вложение."""
|
||||
expired = (
|
||||
select(AttachmentJob.id)
|
||||
.where(
|
||||
AttachmentJob.state
|
||||
== literal(
|
||||
AttachmentJobState.PROCESSING.value,
|
||||
literal_execute=True,
|
||||
async def insert_job(
|
||||
self,
|
||||
*,
|
||||
job: dataclasses.AttachmentJobDTO,
|
||||
) -> dataclasses.AttachmentJobDTO:
|
||||
"""Новая работа; вложение становится `queued` в той же транзакции."""
|
||||
await self._session.execute(
|
||||
insert(AttachmentJob).values(
|
||||
id=job.id,
|
||||
attachment_id=job.attachment_id,
|
||||
pipeline_version=job.pipeline_version,
|
||||
state=job.state.value,
|
||||
attempt=job.attempt,
|
||||
created_at=job.created_at,
|
||||
updated_at=job.updated_at,
|
||||
),
|
||||
AttachmentJob.lease_expires_at < now,
|
||||
)
|
||||
.order_by(AttachmentJob.lease_expires_at)
|
||||
.limit(limit)
|
||||
.with_for_update(skip_locked=True)
|
||||
)
|
||||
statement = (
|
||||
update(AttachmentJob)
|
||||
.where(AttachmentJob.id.in_(expired))
|
||||
.values(
|
||||
state=AttachmentJobState.QUEUED.value,
|
||||
last_error_code=AttachmentJobReason.LEASE_EXPIRED.value,
|
||||
lease_expires_at=None,
|
||||
next_attempt_at=None,
|
||||
published_at=None,
|
||||
updated_at=_later_of_now(now),
|
||||
return job
|
||||
|
||||
async def lock_job(
|
||||
self,
|
||||
*,
|
||||
job_id: UUID,
|
||||
) -> dataclasses.AttachmentJobDTO | None:
|
||||
"""Задание под `FOR UPDATE` до конца транзакции."""
|
||||
statement = (
|
||||
select(*_JOB_COLUMNS)
|
||||
.where(AttachmentJob.id == job_id)
|
||||
.with_for_update()
|
||||
)
|
||||
.returning(*_JOB_COLUMNS)
|
||||
)
|
||||
rows = (await db_session.execute(statement)).all()
|
||||
return [_to_dto(row) for row in rows]
|
||||
row = (await self._session.execute(statement)).one_or_none()
|
||||
return None if row is None else _to_dto(row)
|
||||
|
||||
async def get_job(
|
||||
self,
|
||||
*,
|
||||
job_id: UUID,
|
||||
) -> dataclasses.AttachmentJobDTO | None:
|
||||
statement = select(*_JOB_COLUMNS).where(AttachmentJob.id == job_id)
|
||||
row = (await self._session.execute(statement)).one_or_none()
|
||||
return None if row is None else _to_dto(row)
|
||||
|
||||
async def has_published_before(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
older_than: datetime,
|
||||
) -> bool:
|
||||
"""Есть ли отмеченные задания старше порога: кандидаты в потерянные."""
|
||||
# IS NOT NULL явно: условие индекса ix_attachment_jobs_published (проба)
|
||||
statement = select(
|
||||
exists().where(
|
||||
_queued(),
|
||||
AttachmentJob.published_at.is_not(None),
|
||||
AttachmentJob.published_at < older_than,
|
||||
),
|
||||
)
|
||||
return bool((await db_session.execute(statement)).scalar_one())
|
||||
|
||||
|
||||
async def reset_published_before(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
older_than: datetime,
|
||||
now: datetime,
|
||||
) -> int:
|
||||
"""Потерянные сообщения: отметка снимается, задание снова намерение."""
|
||||
statement = (
|
||||
update(AttachmentJob)
|
||||
.where(
|
||||
_queued(),
|
||||
AttachmentJob.published_at.is_not(None),
|
||||
AttachmentJob.published_at < older_than,
|
||||
async def get_attachment_job(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
pipeline_version: int,
|
||||
) -> dataclasses.AttachmentJobDTO | None:
|
||||
statement = select(*_JOB_COLUMNS).where(
|
||||
AttachmentJob.attachment_id == attachment_id,
|
||||
AttachmentJob.pipeline_version == pipeline_version,
|
||||
)
|
||||
.values(published_at=None, updated_at=_later_of_now(now))
|
||||
.returning(AttachmentJob.id)
|
||||
)
|
||||
return len((await db_session.execute(statement)).all())
|
||||
row = (await self._session.execute(statement)).one_or_none()
|
||||
return None if row is None else _to_dto(row)
|
||||
|
||||
|
||||
async def replay_job(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
job_id: UUID,
|
||||
now: datetime,
|
||||
) -> bool:
|
||||
"""`failed` → `queued` с новым бюджетом (design change
|
||||
`pipeline-reliability`, решение 5): `attempt` монотонен, это fencing-токен,
|
||||
поэтому бюджет считается от `attempt_base`. Сообщение публикует relay."""
|
||||
statement = (
|
||||
update(AttachmentJob)
|
||||
.where(
|
||||
AttachmentJob.id == job_id,
|
||||
AttachmentJob.state == AttachmentJobState.FAILED.value,
|
||||
async def start_attempt(
|
||||
self,
|
||||
*,
|
||||
job_id: UUID,
|
||||
lease_expires_at: datetime,
|
||||
now: datetime,
|
||||
) -> dataclasses.AttachmentJobDTO | None:
|
||||
"""Начать попытку под блокировкой `lock_job`: счётчик +1, срок аренды,
|
||||
`processing`. Вызывающий проверил, что итога и живой аренды нет."""
|
||||
statement = (
|
||||
update(AttachmentJob)
|
||||
.where(AttachmentJob.id == job_id)
|
||||
.values(
|
||||
state=AttachmentJobState.PROCESSING.value,
|
||||
attempt=AttachmentJob.attempt + 1,
|
||||
lease_expires_at=lease_expires_at,
|
||||
next_attempt_at=None,
|
||||
updated_at=_later_of_now(now),
|
||||
)
|
||||
.returning(*_JOB_COLUMNS)
|
||||
)
|
||||
.values(
|
||||
state=AttachmentJobState.QUEUED.value,
|
||||
attempt_base=AttachmentJob.attempt,
|
||||
last_error_code=None,
|
||||
next_attempt_at=None,
|
||||
lease_expires_at=None,
|
||||
published_at=None,
|
||||
finished_at=None,
|
||||
updated_at=_later_of_now(now),
|
||||
)
|
||||
.returning(AttachmentJob.id)
|
||||
)
|
||||
return (await db_session.execute(statement)).one_or_none() is not None
|
||||
row = (await self._session.execute(statement)).one_or_none()
|
||||
return None if row is None else _to_dto(row)
|
||||
|
||||
|
||||
async def list_failed(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
error_code: str | None,
|
||||
reason: str | None,
|
||||
limit: int,
|
||||
) -> list[dataclasses.FailedJobDTO]:
|
||||
"""Реестр `failed`, новые раньше. Индекса нет: выбор оператора редок, а
|
||||
строк `failed` мало (решение 10)."""
|
||||
statement = (
|
||||
select(
|
||||
AttachmentJob.id.label("job_id"),
|
||||
AttachmentJob.attachment_id,
|
||||
Attachment.error_code,
|
||||
AttachmentJob.last_error_code.label("reason"),
|
||||
AttachmentJob.attempt,
|
||||
AttachmentJob.attempt_base,
|
||||
AttachmentJob.finished_at,
|
||||
async def return_to_queued(
|
||||
self,
|
||||
*,
|
||||
job_id: UUID,
|
||||
attempt: int,
|
||||
reason: AttachmentJobReason,
|
||||
next_attempt_at: datetime,
|
||||
now: datetime,
|
||||
) -> bool:
|
||||
"""Временная ошибка: `processing` → `queued`, только своя попытка (номер
|
||||
совпал), со сроком следующей. Сообщение ещё не передано, его опубликует
|
||||
relay: `published_at` — NULL. `False` — задание уже ведёт другая попытка
|
||||
или есть итог."""
|
||||
statement = (
|
||||
update(AttachmentJob)
|
||||
.where(
|
||||
AttachmentJob.id == job_id,
|
||||
AttachmentJob.state == AttachmentJobState.PROCESSING.value,
|
||||
AttachmentJob.attempt == attempt,
|
||||
)
|
||||
.values(
|
||||
state=AttachmentJobState.QUEUED.value,
|
||||
last_error_code=reason.value,
|
||||
next_attempt_at=next_attempt_at,
|
||||
lease_expires_at=None,
|
||||
published_at=None,
|
||||
updated_at=_later_of_now(now),
|
||||
)
|
||||
.returning(AttachmentJob.id)
|
||||
)
|
||||
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
|
||||
.where(AttachmentJob.state == AttachmentJobState.FAILED.value)
|
||||
.order_by(AttachmentJob.finished_at.desc(), AttachmentJob.id)
|
||||
.limit(limit)
|
||||
)
|
||||
if error_code is not None:
|
||||
statement = statement.where(Attachment.error_code == error_code)
|
||||
if reason is not None:
|
||||
statement = statement.where(AttachmentJob.last_error_code == reason)
|
||||
rows = (await db_session.execute(statement)).all()
|
||||
return [
|
||||
dataclasses.FailedJobDTO(
|
||||
**{
|
||||
**row._mapping,
|
||||
"error_code": (
|
||||
None
|
||||
if row.error_code is None
|
||||
else AttachmentErrorCode(row.error_code)
|
||||
return (
|
||||
await self._session.execute(statement)
|
||||
).one_or_none() is not None
|
||||
|
||||
async def finish_job(
|
||||
self,
|
||||
*,
|
||||
job_id: UUID,
|
||||
state: AttachmentJobState,
|
||||
reason: AttachmentJobReason | None,
|
||||
now: datetime,
|
||||
) -> bool:
|
||||
"""Итог задания: `succeeded` или `failed`, под блокировкой
|
||||
`lock_job`."""
|
||||
values: dict[str, object] = {
|
||||
"state": state.value,
|
||||
"lease_expires_at": None,
|
||||
"next_attempt_at": None,
|
||||
"finished_at": now,
|
||||
"updated_at": _later_of_now(now),
|
||||
}
|
||||
if reason is not None:
|
||||
values["last_error_code"] = reason.value
|
||||
statement = (
|
||||
update(AttachmentJob)
|
||||
.where(AttachmentJob.id == job_id)
|
||||
.values(**values)
|
||||
.returning(AttachmentJob.id)
|
||||
)
|
||||
return (
|
||||
await self._session.execute(statement)
|
||||
).one_or_none() is not None
|
||||
|
||||
async def lock_due_jobs(
|
||||
self,
|
||||
*,
|
||||
now: datetime,
|
||||
limit: int,
|
||||
) -> list[dataclasses.AttachmentJobDTO]:
|
||||
"""Намерения, срок которых наступил, в порядке срока, под `FOR UPDATE
|
||||
SKIP LOCKED`: задание, которое публикует другой relay, пропускается.
|
||||
Блокировка держится до отметки: worker, получивший сообщение раньше
|
||||
COMMIT, ждёт её в `lock_job`."""
|
||||
statement = (
|
||||
select(*_JOB_COLUMNS)
|
||||
.where(*_outbox_condition(), now >= _DUE_AT)
|
||||
.order_by(_DUE_AT, AttachmentJob.id)
|
||||
.limit(limit)
|
||||
.with_for_update(skip_locked=True)
|
||||
)
|
||||
rows = (await self._session.execute(statement)).all()
|
||||
return [_to_dto(row) for row in rows]
|
||||
|
||||
async def count_published(self) -> int:
|
||||
"""Опубликованные и не взятые задания: то, что считает предел."""
|
||||
statement = (
|
||||
select(func.count())
|
||||
.select_from(AttachmentJob)
|
||||
.where(_queued(), AttachmentJob.published_at.is_not(None))
|
||||
)
|
||||
return (await self._session.execute(statement)).scalar_one()
|
||||
|
||||
async def mark_published(
|
||||
self,
|
||||
*,
|
||||
job_ids: Collection[UUID],
|
||||
now: datetime,
|
||||
) -> int:
|
||||
"""Брокер подтвердил сообщения пакета: время — отметка, а не условие.
|
||||
Вызывается под блокировкой `lock_due_jobs`."""
|
||||
statement = (
|
||||
update(AttachmentJob)
|
||||
.where(AttachmentJob.id == any_(_uuid_array(job_ids)))
|
||||
.values(published_at=now, updated_at=_later_of_now(now))
|
||||
.returning(AttachmentJob.id)
|
||||
)
|
||||
return len((await self._session.execute(statement)).all())
|
||||
|
||||
async def recover_expired_leases(
|
||||
self,
|
||||
*,
|
||||
now: datetime,
|
||||
limit: int,
|
||||
) -> list[dataclasses.AttachmentJobDTO]:
|
||||
"""Истёкшие аренды: `processing` → `queued` без паузы, причина «истёк
|
||||
срок аренды» (design change `pipeline-reliability`, решения 2 и 3).
|
||||
Вложения тех же `id` переводит вызывающий в той же транзакции: порядок
|
||||
блокировок — задание, затем вложение."""
|
||||
expired = (
|
||||
select(AttachmentJob.id)
|
||||
.where(
|
||||
AttachmentJob.state
|
||||
== literal(
|
||||
AttachmentJobState.PROCESSING.value,
|
||||
literal_execute=True,
|
||||
),
|
||||
},
|
||||
AttachmentJob.lease_expires_at < now,
|
||||
)
|
||||
.order_by(AttachmentJob.lease_expires_at)
|
||||
.limit(limit)
|
||||
.with_for_update(skip_locked=True)
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
statement = (
|
||||
update(AttachmentJob)
|
||||
.where(AttachmentJob.id.in_(expired))
|
||||
.values(
|
||||
state=AttachmentJobState.QUEUED.value,
|
||||
last_error_code=AttachmentJobReason.LEASE_EXPIRED.value,
|
||||
lease_expires_at=None,
|
||||
next_attempt_at=None,
|
||||
published_at=None,
|
||||
updated_at=_later_of_now(now),
|
||||
)
|
||||
.returning(*_JOB_COLUMNS)
|
||||
)
|
||||
rows = (await self._session.execute(statement)).all()
|
||||
return [_to_dto(row) for row in rows]
|
||||
|
||||
async def has_published_before(self, *, older_than: datetime) -> bool:
|
||||
"""Есть ли отмеченные задания старше порога: кандидаты в потерянные."""
|
||||
# IS NOT NULL явно: условие индекса ix_attachment_jobs_published (проба)
|
||||
statement = select(
|
||||
exists().where(
|
||||
_queued(),
|
||||
AttachmentJob.published_at.is_not(None),
|
||||
AttachmentJob.published_at < older_than,
|
||||
),
|
||||
)
|
||||
return bool((await self._session.execute(statement)).scalar_one())
|
||||
|
||||
async def reset_published_before(
|
||||
self,
|
||||
*,
|
||||
older_than: datetime,
|
||||
now: datetime,
|
||||
) -> int:
|
||||
"""Потерянные сообщения: отметка снимается, задание снова намерение."""
|
||||
statement = (
|
||||
update(AttachmentJob)
|
||||
.where(
|
||||
_queued(),
|
||||
AttachmentJob.published_at.is_not(None),
|
||||
AttachmentJob.published_at < older_than,
|
||||
)
|
||||
.values(published_at=None, updated_at=_later_of_now(now))
|
||||
.returning(AttachmentJob.id)
|
||||
)
|
||||
return len((await self._session.execute(statement)).all())
|
||||
|
||||
async def replay_job(self, *, job_id: UUID, now: datetime) -> bool:
|
||||
"""`failed` → `queued` с новым бюджетом (design change
|
||||
`pipeline-reliability`, решение 5): `attempt` монотонен, это
|
||||
fencing-токен, поэтому бюджет считается от `attempt_base`. Сообщение
|
||||
публикует relay."""
|
||||
statement = (
|
||||
update(AttachmentJob)
|
||||
.where(
|
||||
AttachmentJob.id == job_id,
|
||||
AttachmentJob.state == AttachmentJobState.FAILED.value,
|
||||
)
|
||||
.values(
|
||||
state=AttachmentJobState.QUEUED.value,
|
||||
attempt_base=AttachmentJob.attempt,
|
||||
last_error_code=None,
|
||||
next_attempt_at=None,
|
||||
lease_expires_at=None,
|
||||
published_at=None,
|
||||
finished_at=None,
|
||||
updated_at=_later_of_now(now),
|
||||
)
|
||||
.returning(AttachmentJob.id)
|
||||
)
|
||||
return (
|
||||
await self._session.execute(statement)
|
||||
).one_or_none() is not None
|
||||
|
||||
async def list_failed(
|
||||
self,
|
||||
*,
|
||||
error_code: str | None,
|
||||
reason: str | None,
|
||||
limit: int,
|
||||
) -> list[dataclasses.FailedJobDTO]:
|
||||
"""Реестр `failed`, новые раньше. Индекса нет: выбор оператора редок, а
|
||||
строк `failed` мало (решение 10)."""
|
||||
statement = (
|
||||
select(
|
||||
AttachmentJob.id.label("job_id"),
|
||||
AttachmentJob.attachment_id,
|
||||
Attachment.error_code,
|
||||
AttachmentJob.last_error_code.label("reason"),
|
||||
AttachmentJob.attempt,
|
||||
AttachmentJob.attempt_base,
|
||||
AttachmentJob.finished_at,
|
||||
)
|
||||
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
|
||||
.where(AttachmentJob.state == AttachmentJobState.FAILED.value)
|
||||
.order_by(AttachmentJob.finished_at.desc(), AttachmentJob.id)
|
||||
.limit(limit)
|
||||
)
|
||||
if error_code is not None:
|
||||
statement = statement.where(Attachment.error_code == error_code)
|
||||
if reason is not None:
|
||||
statement = statement.where(
|
||||
AttachmentJob.last_error_code == reason,
|
||||
)
|
||||
rows = (await self._session.execute(statement)).all()
|
||||
return [
|
||||
dataclasses.FailedJobDTO(
|
||||
**{
|
||||
**row._mapping,
|
||||
"error_code": (
|
||||
None
|
||||
if row.error_code is None
|
||||
else AttachmentErrorCode(row.error_code)
|
||||
),
|
||||
},
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
|
||||
@@ -7,6 +7,9 @@ from uuid import UUID
|
||||
from sqlalchemy import insert, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.core.ports.attachment_job_replay import (
|
||||
AbstractAttachmentJobReplayRepository,
|
||||
)
|
||||
from src.infra.db.models import AttachmentJobReplay
|
||||
from src.schemas import dataclasses
|
||||
|
||||
@@ -21,34 +24,41 @@ _REPLAY_COLUMNS = (
|
||||
)
|
||||
|
||||
|
||||
async def insert_replay(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
replay: dataclasses.AttachmentJobReplayDTO,
|
||||
) -> dataclasses.AttachmentJobReplayDTO:
|
||||
await db_session.execute(
|
||||
insert(AttachmentJobReplay).values(
|
||||
id=replay.id,
|
||||
job_id=replay.job_id,
|
||||
operator=replay.operator,
|
||||
error_code=replay.error_code,
|
||||
reason=replay.reason,
|
||||
attempt=replay.attempt,
|
||||
created_at=replay.created_at,
|
||||
),
|
||||
)
|
||||
return replay
|
||||
class SqlAlchemyAttachmentJobReplayRepository(
|
||||
AbstractAttachmentJobReplayRepository,
|
||||
):
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self._session = session
|
||||
|
||||
async def insert_replay(
|
||||
self,
|
||||
*,
|
||||
replay: dataclasses.AttachmentJobReplayDTO,
|
||||
) -> dataclasses.AttachmentJobReplayDTO:
|
||||
await self._session.execute(
|
||||
insert(AttachmentJobReplay).values(
|
||||
id=replay.id,
|
||||
job_id=replay.job_id,
|
||||
operator=replay.operator,
|
||||
error_code=replay.error_code,
|
||||
reason=replay.reason,
|
||||
attempt=replay.attempt,
|
||||
created_at=replay.created_at,
|
||||
),
|
||||
)
|
||||
return replay
|
||||
|
||||
async def get_job_replays(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
job_id: UUID,
|
||||
) -> list[dataclasses.AttachmentJobReplayDTO]:
|
||||
statement = (
|
||||
select(*_REPLAY_COLUMNS)
|
||||
.where(AttachmentJobReplay.job_id == job_id)
|
||||
.order_by(AttachmentJobReplay.created_at, AttachmentJobReplay.id)
|
||||
)
|
||||
rows = (await db_session.execute(statement)).all()
|
||||
return [dataclasses.AttachmentJobReplayDTO(**row._mapping) for row in rows]
|
||||
async def get_job_replays(
|
||||
self,
|
||||
*,
|
||||
job_id: UUID,
|
||||
) -> list[dataclasses.AttachmentJobReplayDTO]:
|
||||
statement = (
|
||||
select(*_REPLAY_COLUMNS)
|
||||
.where(AttachmentJobReplay.job_id == job_id)
|
||||
.order_by(AttachmentJobReplay.created_at, AttachmentJobReplay.id)
|
||||
)
|
||||
rows = (await self._session.execute(statement)).all()
|
||||
return [
|
||||
dataclasses.AttachmentJobReplayDTO(**row._mapping) for row in rows
|
||||
]
|
||||
|
||||
@@ -9,6 +9,9 @@ from sqlalchemy import Row, select
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.core.ports.attachment_variant import (
|
||||
AbstractAttachmentVariantRepository,
|
||||
)
|
||||
from src.infra.db.models import AttachmentVariant
|
||||
from src.schemas import dataclasses
|
||||
from src.schemas.enums import AttachmentVariantName
|
||||
@@ -32,65 +35,75 @@ def _to_dto(row: Row) -> dataclasses.AttachmentVariantDTO:
|
||||
return dataclasses.AttachmentVariantDTO(**fields)
|
||||
|
||||
|
||||
async def insert_variant(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
variant: dataclasses.AttachmentVariantDTO,
|
||||
) -> bool:
|
||||
"""Вариант по ключу эффекта; `False` — такой уже есть."""
|
||||
statement = (
|
||||
pg_insert(AttachmentVariant)
|
||||
.values(
|
||||
attachment_id=attachment_id,
|
||||
pipeline_version=variant.pipeline_version,
|
||||
variant=variant.name.value,
|
||||
object_key=variant.object_key,
|
||||
content_type=variant.content_type,
|
||||
size_bytes=variant.size_bytes,
|
||||
width=variant.width,
|
||||
height=variant.height,
|
||||
sha256=variant.sha256,
|
||||
created_at=variant.created_at,
|
||||
class SqlAlchemyAttachmentVariantRepository(
|
||||
AbstractAttachmentVariantRepository,
|
||||
):
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self._session = session
|
||||
|
||||
async def insert_variant(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
variant: dataclasses.AttachmentVariantDTO,
|
||||
) -> bool:
|
||||
"""Вариант по ключу эффекта; `False` — такой уже есть."""
|
||||
statement = (
|
||||
pg_insert(AttachmentVariant)
|
||||
.values(
|
||||
attachment_id=attachment_id,
|
||||
pipeline_version=variant.pipeline_version,
|
||||
variant=variant.name.value,
|
||||
object_key=variant.object_key,
|
||||
content_type=variant.content_type,
|
||||
size_bytes=variant.size_bytes,
|
||||
width=variant.width,
|
||||
height=variant.height,
|
||||
sha256=variant.sha256,
|
||||
created_at=variant.created_at,
|
||||
)
|
||||
.on_conflict_do_nothing(
|
||||
index_elements=[
|
||||
"attachment_id",
|
||||
"pipeline_version",
|
||||
"variant",
|
||||
],
|
||||
)
|
||||
.returning(AttachmentVariant.attachment_id)
|
||||
)
|
||||
.on_conflict_do_nothing(
|
||||
index_elements=["attachment_id", "pipeline_version", "variant"],
|
||||
return (
|
||||
await self._session.execute(statement)
|
||||
).one_or_none() is not None
|
||||
|
||||
async def get_variants(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
) -> list[dataclasses.AttachmentVariantDTO]:
|
||||
"""Варианты вложения в постоянном порядке."""
|
||||
statement = (
|
||||
select(*_VARIANT_COLUMNS)
|
||||
.where(AttachmentVariant.attachment_id == attachment_id)
|
||||
.order_by(AttachmentVariant.variant)
|
||||
)
|
||||
.returning(AttachmentVariant.attachment_id)
|
||||
)
|
||||
return (await db_session.execute(statement)).one_or_none() is not None
|
||||
rows = (await self._session.execute(statement)).all()
|
||||
return [_to_dto(row) for row in rows]
|
||||
|
||||
|
||||
async def get_variants(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
) -> list[dataclasses.AttachmentVariantDTO]:
|
||||
"""Варианты вложения в постоянном порядке."""
|
||||
statement = (
|
||||
select(*_VARIANT_COLUMNS)
|
||||
.where(AttachmentVariant.attachment_id == attachment_id)
|
||||
.order_by(AttachmentVariant.variant)
|
||||
)
|
||||
rows = (await db_session.execute(statement)).all()
|
||||
return [_to_dto(row) for row in rows]
|
||||
|
||||
|
||||
async def get_variant(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
name: AttachmentVariantName,
|
||||
) -> dataclasses.AttachmentVariantDTO | None:
|
||||
"""Один вариант по имени, самой новой версии обработки."""
|
||||
statement = (
|
||||
select(*_VARIANT_COLUMNS)
|
||||
.where(
|
||||
AttachmentVariant.attachment_id == attachment_id,
|
||||
AttachmentVariant.variant == name.value,
|
||||
async def get_variant(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
name: AttachmentVariantName,
|
||||
) -> dataclasses.AttachmentVariantDTO | None:
|
||||
"""Один вариант по имени, самой новой версии обработки."""
|
||||
statement = (
|
||||
select(*_VARIANT_COLUMNS)
|
||||
.where(
|
||||
AttachmentVariant.attachment_id == attachment_id,
|
||||
AttachmentVariant.variant == name.value,
|
||||
)
|
||||
.order_by(AttachmentVariant.pipeline_version.desc())
|
||||
.limit(1)
|
||||
)
|
||||
.order_by(AttachmentVariant.pipeline_version.desc())
|
||||
.limit(1)
|
||||
)
|
||||
row = (await db_session.execute(statement)).one_or_none()
|
||||
return None if row is None else _to_dto(row)
|
||||
row = (await self._session.execute(statement)).one_or_none()
|
||||
return None if row is None else _to_dto(row)
|
||||
|
||||
+79
-76
@@ -5,6 +5,7 @@ from sqlalchemy.dialects.postgresql import aggregate_order_by
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import aliased
|
||||
|
||||
from src.core.ports.chat import AbstractChatRepository
|
||||
from src.infra.db.models import Chat, ChatMember
|
||||
from src.schemas import dataclasses
|
||||
from src.utils.cursor import CursorKey
|
||||
@@ -32,81 +33,83 @@ def _to_dto(row: Row) -> dataclasses.ChatFullDTO:
|
||||
)
|
||||
|
||||
|
||||
async def insert_chat(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
chat: dataclasses.ChatFullDTO,
|
||||
) -> dataclasses.ChatFullDTO:
|
||||
"""Только строка чата; участников пишет `insert_chat_members`."""
|
||||
await db_session.execute(
|
||||
insert(Chat).values(
|
||||
id=chat.id,
|
||||
title=chat.title,
|
||||
created_at=chat.created_at,
|
||||
),
|
||||
)
|
||||
return chat
|
||||
class SqlAlchemyChatRepository(AbstractChatRepository):
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self._session = session
|
||||
|
||||
|
||||
async def insert_chat_members(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
chat: dataclasses.ChatFullDTO,
|
||||
) -> int:
|
||||
"""Все участники одной вставкой; позиция — порядок в `member_ids`.
|
||||
|
||||
`created_at` участника — копия времени чата: по нему идёт keyset
|
||||
списка чатов пользователя.
|
||||
"""
|
||||
result = await db_session.execute(
|
||||
insert(ChatMember).values(
|
||||
[
|
||||
{
|
||||
"chat_id": chat.id,
|
||||
"user_id": user_id,
|
||||
"position": position,
|
||||
"created_at": chat.created_at,
|
||||
}
|
||||
for position, user_id in enumerate(chat.member_ids)
|
||||
],
|
||||
),
|
||||
)
|
||||
return result.rowcount
|
||||
|
||||
|
||||
async def get_chat(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
) -> dataclasses.ChatFullDTO | None:
|
||||
statement = select(*_CHAT_COLUMNS).where(Chat.id == chat_id)
|
||||
row = (await db_session.execute(statement)).one_or_none()
|
||||
return None if row is None else _to_dto(row)
|
||||
|
||||
|
||||
async def get_user_chats_page(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
user_id: UUID,
|
||||
after: CursorKey | None,
|
||||
limit: int,
|
||||
) -> list[dataclasses.ChatFullDTO]:
|
||||
"""До `limit + 1` чатов пользователя строго после ключа `after`.
|
||||
|
||||
Keyset по индексу `(user_id, created_at, chat_id)` участников: их
|
||||
`created_at` равен времени чата, поэтому порядок — `(created_at, id)`
|
||||
чатов.
|
||||
"""
|
||||
statement = (
|
||||
select(*_CHAT_COLUMNS)
|
||||
.join(ChatMember, ChatMember.chat_id == Chat.id)
|
||||
.where(ChatMember.user_id == user_id)
|
||||
.order_by(ChatMember.created_at, ChatMember.chat_id)
|
||||
.limit(limit + 1)
|
||||
)
|
||||
if after is not None:
|
||||
statement = statement.where(
|
||||
tuple_(ChatMember.created_at, ChatMember.chat_id) > tuple_(*after),
|
||||
async def insert_chat(
|
||||
self,
|
||||
*,
|
||||
chat: dataclasses.ChatFullDTO,
|
||||
) -> dataclasses.ChatFullDTO:
|
||||
"""Только строка чата; участников пишет `insert_chat_members`."""
|
||||
await self._session.execute(
|
||||
insert(Chat).values(
|
||||
id=chat.id,
|
||||
title=chat.title,
|
||||
created_at=chat.created_at,
|
||||
),
|
||||
)
|
||||
rows = (await db_session.execute(statement)).all()
|
||||
return [_to_dto(row) for row in rows]
|
||||
return chat
|
||||
|
||||
async def insert_chat_members(
|
||||
self,
|
||||
*,
|
||||
chat: dataclasses.ChatFullDTO,
|
||||
) -> int:
|
||||
"""Все участники одной вставкой; позиция — порядок в `member_ids`.
|
||||
|
||||
`created_at` участника — копия времени чата: по нему идёт keyset
|
||||
списка чатов пользователя.
|
||||
"""
|
||||
result = await self._session.execute(
|
||||
insert(ChatMember).values(
|
||||
[
|
||||
{
|
||||
"chat_id": chat.id,
|
||||
"user_id": user_id,
|
||||
"position": position,
|
||||
"created_at": chat.created_at,
|
||||
}
|
||||
for position, user_id in enumerate(chat.member_ids)
|
||||
],
|
||||
),
|
||||
)
|
||||
return result.rowcount
|
||||
|
||||
async def get_chat(
|
||||
self,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
) -> dataclasses.ChatFullDTO | None:
|
||||
statement = select(*_CHAT_COLUMNS).where(Chat.id == chat_id)
|
||||
row = (await self._session.execute(statement)).one_or_none()
|
||||
return None if row is None else _to_dto(row)
|
||||
|
||||
async def get_user_chats_page(
|
||||
self,
|
||||
*,
|
||||
user_id: UUID,
|
||||
after: CursorKey | None,
|
||||
limit: int,
|
||||
) -> list[dataclasses.ChatFullDTO]:
|
||||
"""До `limit + 1` чатов пользователя строго после ключа `after`.
|
||||
|
||||
Keyset по индексу `(user_id, created_at, chat_id)` участников: их
|
||||
`created_at` равен времени чата, поэтому порядок — `(created_at, id)`
|
||||
чатов.
|
||||
"""
|
||||
statement = (
|
||||
select(*_CHAT_COLUMNS)
|
||||
.join(ChatMember, ChatMember.chat_id == Chat.id)
|
||||
.where(ChatMember.user_id == user_id)
|
||||
.order_by(ChatMember.created_at, ChatMember.chat_id)
|
||||
.limit(limit + 1)
|
||||
)
|
||||
if after is not None:
|
||||
statement = statement.where(
|
||||
tuple_(ChatMember.created_at, ChatMember.chat_id)
|
||||
> tuple_(*after),
|
||||
)
|
||||
rows = (await self._session.execute(statement)).all()
|
||||
return [_to_dto(row) for row in rows]
|
||||
|
||||
@@ -12,6 +12,7 @@ from sqlalchemy import select
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.core.ports.idempotency import AbstractIdempotencyRepository
|
||||
from src.core.repos.message import MESSAGE_COLUMNS, to_message_dto
|
||||
from src.infra.db.models import IdempotencyKey, Message
|
||||
from src.schemas import dataclasses
|
||||
@@ -23,67 +24,72 @@ _KEY_COLUMNS = (
|
||||
)
|
||||
|
||||
|
||||
async def claim_key(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
user_id: UUID,
|
||||
chat_id: UUID,
|
||||
key: str,
|
||||
request_hash: bytes,
|
||||
message_id: UUID,
|
||||
created_at: datetime,
|
||||
expired_before: datetime,
|
||||
) -> bool:
|
||||
"""Захват ключа под новое сообщение `message_id`.
|
||||
class SqlAlchemyIdempotencyRepository(AbstractIdempotencyRepository):
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self._session = session
|
||||
|
||||
True — ключ свободен: новый или просроченный (`created_at` раньше
|
||||
`expired_before`), который заменён этим же выражением. False — ключ
|
||||
занят и ещё действует. Одновременная вставка того же ключа ждёт
|
||||
commit или отката чужой транзакции, а занятая строка остаётся
|
||||
заблокированной до конца транзакции, даже если срок не истёк.
|
||||
"""
|
||||
insert = pg_insert(IdempotencyKey).values(
|
||||
user_id=user_id,
|
||||
chat_id=chat_id,
|
||||
key=key,
|
||||
request_hash=request_hash,
|
||||
message_id=message_id,
|
||||
created_at=created_at,
|
||||
)
|
||||
statement = insert.on_conflict_do_update(
|
||||
index_elements=list(_KEY_COLUMNS),
|
||||
set_={
|
||||
"request_hash": insert.excluded.request_hash,
|
||||
"message_id": insert.excluded.message_id,
|
||||
"created_at": insert.excluded.created_at,
|
||||
},
|
||||
where=IdempotencyKey.created_at < expired_before,
|
||||
).returning(IdempotencyKey.message_id)
|
||||
return (await db_session.execute(statement)).one_or_none() is not None
|
||||
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:
|
||||
"""Захват ключа под новое сообщение `message_id`.
|
||||
|
||||
True — ключ свободен: новый или просроченный (`created_at` раньше
|
||||
`expired_before`), который заменён этим же выражением. False — ключ
|
||||
занят и ещё действует. Одновременная вставка того же ключа ждёт
|
||||
commit или отката чужой транзакции, а занятая строка остаётся
|
||||
заблокированной до конца транзакции, даже если срок не истёк.
|
||||
"""
|
||||
insert = pg_insert(IdempotencyKey).values(
|
||||
user_id=user_id,
|
||||
chat_id=chat_id,
|
||||
key=key,
|
||||
request_hash=request_hash,
|
||||
message_id=message_id,
|
||||
created_at=created_at,
|
||||
)
|
||||
statement = insert.on_conflict_do_update(
|
||||
index_elements=list(_KEY_COLUMNS),
|
||||
set_={
|
||||
"request_hash": insert.excluded.request_hash,
|
||||
"message_id": insert.excluded.message_id,
|
||||
"created_at": insert.excluded.created_at,
|
||||
},
|
||||
where=IdempotencyKey.created_at < expired_before,
|
||||
).returning(IdempotencyKey.message_id)
|
||||
return (
|
||||
await self._session.execute(statement)
|
||||
).one_or_none() is not None
|
||||
|
||||
async def get_key_result(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
user_id: UUID,
|
||||
chat_id: UUID,
|
||||
key: str,
|
||||
) -> dataclasses.IdempotencyRecordDTO | None:
|
||||
"""Хэш тела и сообщение с вложениями, сохранённые под ключом; None —
|
||||
ключа нет."""
|
||||
statement = (
|
||||
select(IdempotencyKey.request_hash, *MESSAGE_COLUMNS)
|
||||
.join(Message, Message.id == IdempotencyKey.message_id)
|
||||
.where(
|
||||
IdempotencyKey.user_id == user_id,
|
||||
IdempotencyKey.chat_id == chat_id,
|
||||
IdempotencyKey.key == key,
|
||||
async def get_key_result(
|
||||
self,
|
||||
*,
|
||||
user_id: UUID,
|
||||
chat_id: UUID,
|
||||
key: str,
|
||||
) -> dataclasses.IdempotencyRecordDTO | None:
|
||||
"""Хэш тела и сообщение с вложениями, сохранённые под ключом; None —
|
||||
ключа нет."""
|
||||
statement = (
|
||||
select(IdempotencyKey.request_hash, *MESSAGE_COLUMNS)
|
||||
.join(Message, Message.id == IdempotencyKey.message_id)
|
||||
.where(
|
||||
IdempotencyKey.user_id == user_id,
|
||||
IdempotencyKey.chat_id == chat_id,
|
||||
IdempotencyKey.key == key,
|
||||
)
|
||||
)
|
||||
row = (await self._session.execute(statement)).one_or_none()
|
||||
if row is None:
|
||||
return None
|
||||
return dataclasses.IdempotencyRecordDTO(
|
||||
request_hash=row.request_hash,
|
||||
message=to_message_dto(row._mapping),
|
||||
)
|
||||
)
|
||||
row = (await db_session.execute(statement)).one_or_none()
|
||||
if row is None:
|
||||
return None
|
||||
return dataclasses.IdempotencyRecordDTO(
|
||||
request_hash=row.request_hash,
|
||||
message=to_message_dto(row._mapping),
|
||||
)
|
||||
|
||||
+75
-72
@@ -6,6 +6,7 @@ from sqlalchemy import Uuid, func, insert, select, tuple_
|
||||
from sqlalchemy.dialects.postgresql import ARRAY
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.core.ports.message import AbstractMessageRepository
|
||||
from src.infra.db.models import Message, MessageAttachment
|
||||
from src.schemas import dataclasses
|
||||
from src.utils.cursor import CursorKey
|
||||
@@ -46,77 +47,79 @@ def to_message_dto(fields: Mapping[str, Any]) -> dataclasses.MessageFullDTO:
|
||||
)
|
||||
|
||||
|
||||
async def insert_message(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
message: dataclasses.MessageFullDTO,
|
||||
instance_id: str,
|
||||
) -> dataclasses.MessageFullDTO:
|
||||
"""Строка сообщения; `instance_id` — реплика, которая его записала
|
||||
(колонка только для диагностики, в DTO и ответ не попадает). Связи с
|
||||
вложениями пишет `insert_message_attachments`."""
|
||||
await db_session.execute(
|
||||
insert(Message).values(
|
||||
id=message.id,
|
||||
chat_id=message.chat_id,
|
||||
sender_id=message.sender_id,
|
||||
text=message.text,
|
||||
created_at=message.created_at,
|
||||
instance_id=instance_id,
|
||||
),
|
||||
)
|
||||
return message
|
||||
class SqlAlchemyMessageRepository(AbstractMessageRepository):
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self._session = session
|
||||
|
||||
|
||||
async def insert_message_attachments(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
message: dataclasses.MessageFullDTO,
|
||||
) -> int:
|
||||
"""Все связи одной вставкой; `position` — место в `attachment_ids`.
|
||||
|
||||
Вызывается только с непустым `attachment_ids`. `created_at` связи —
|
||||
время сообщения.
|
||||
"""
|
||||
result = await db_session.execute(
|
||||
insert(MessageAttachment).values(
|
||||
[
|
||||
{
|
||||
"message_id": message.id,
|
||||
"position": position,
|
||||
"attachment_id": attachment_id,
|
||||
"created_at": message.created_at,
|
||||
}
|
||||
for position, attachment_id in enumerate(
|
||||
message.attachment_ids,
|
||||
)
|
||||
],
|
||||
),
|
||||
)
|
||||
return result.rowcount
|
||||
|
||||
|
||||
async def get_chat_messages_page(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
after: CursorKey | None,
|
||||
limit: int,
|
||||
) -> list[dataclasses.MessageFullDTO]:
|
||||
"""До `limit + 1` сообщений чата строго после ключа `after`.
|
||||
|
||||
Keyset по индексу `(chat_id, created_at, id)`, без OFFSET: страница
|
||||
не просматривает историю до курсора.
|
||||
"""
|
||||
statement = (
|
||||
select(*MESSAGE_COLUMNS)
|
||||
.where(Message.chat_id == chat_id)
|
||||
.order_by(Message.created_at, Message.id)
|
||||
.limit(limit + 1)
|
||||
)
|
||||
if after is not None:
|
||||
statement = statement.where(
|
||||
tuple_(Message.created_at, Message.id) > tuple_(*after),
|
||||
async def insert_message(
|
||||
self,
|
||||
*,
|
||||
message: dataclasses.MessageFullDTO,
|
||||
instance_id: str,
|
||||
) -> dataclasses.MessageFullDTO:
|
||||
"""Строка сообщения; `instance_id` — реплика, которая его записала
|
||||
(колонка только для диагностики, в DTO и ответ не попадает). Связи с
|
||||
вложениями пишет `insert_message_attachments`."""
|
||||
await self._session.execute(
|
||||
insert(Message).values(
|
||||
id=message.id,
|
||||
chat_id=message.chat_id,
|
||||
sender_id=message.sender_id,
|
||||
text=message.text,
|
||||
created_at=message.created_at,
|
||||
instance_id=instance_id,
|
||||
),
|
||||
)
|
||||
rows = (await db_session.execute(statement)).all()
|
||||
return [to_message_dto(row._mapping) for row in rows]
|
||||
return message
|
||||
|
||||
async def insert_message_attachments(
|
||||
self,
|
||||
*,
|
||||
message: dataclasses.MessageFullDTO,
|
||||
) -> int:
|
||||
"""Все связи одной вставкой; `position` — место в `attachment_ids`.
|
||||
|
||||
Вызывается только с непустым `attachment_ids`. `created_at` связи —
|
||||
время сообщения.
|
||||
"""
|
||||
result = await self._session.execute(
|
||||
insert(MessageAttachment).values(
|
||||
[
|
||||
{
|
||||
"message_id": message.id,
|
||||
"position": position,
|
||||
"attachment_id": attachment_id,
|
||||
"created_at": message.created_at,
|
||||
}
|
||||
for position, attachment_id in enumerate(
|
||||
message.attachment_ids,
|
||||
)
|
||||
],
|
||||
),
|
||||
)
|
||||
return result.rowcount
|
||||
|
||||
async def get_chat_messages_page(
|
||||
self,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
after: CursorKey | None,
|
||||
limit: int,
|
||||
) -> list[dataclasses.MessageFullDTO]:
|
||||
"""До `limit + 1` сообщений чата строго после ключа `after`.
|
||||
|
||||
Keyset по индексу `(chat_id, created_at, id)`, без OFFSET: страница
|
||||
не просматривает историю до курсора.
|
||||
"""
|
||||
statement = (
|
||||
select(*MESSAGE_COLUMNS)
|
||||
.where(Message.chat_id == chat_id)
|
||||
.order_by(Message.created_at, Message.id)
|
||||
.limit(limit + 1)
|
||||
)
|
||||
if after is not None:
|
||||
statement = statement.where(
|
||||
tuple_(Message.created_at, Message.id) > tuple_(*after),
|
||||
)
|
||||
rows = (await self._session.execute(statement)).all()
|
||||
return [to_message_dto(row._mapping) for row in rows]
|
||||
|
||||
+46
-43
@@ -5,55 +5,58 @@ from uuid import UUID
|
||||
from sqlalchemy import delete, insert, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.core.ports.session import AbstractSessionRepository
|
||||
from src.core.repos.user import USER_COLUMNS
|
||||
from src.infra.db.models import Session, User
|
||||
from src.schemas import dataclasses
|
||||
|
||||
|
||||
async def insert_session(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
session: dataclasses.SessionFullDTO,
|
||||
) -> dataclasses.SessionFullDTO:
|
||||
await db_session.execute(insert(Session).values(**asdict(session)))
|
||||
return session
|
||||
class SqlAlchemySessionRepository(AbstractSessionRepository):
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self._session = session
|
||||
|
||||
async def insert_session(
|
||||
self,
|
||||
*,
|
||||
session: dataclasses.SessionFullDTO,
|
||||
) -> dataclasses.SessionFullDTO:
|
||||
await self._session.execute(insert(Session).values(**asdict(session)))
|
||||
return session
|
||||
|
||||
async def get_current_session(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
token_hash: bytes,
|
||||
now: datetime,
|
||||
) -> dataclasses.CurrentSessionDTO | None:
|
||||
"""Действующая сессия по хэшу токена вместе с владельцем.
|
||||
async def get_current_session(
|
||||
self,
|
||||
*,
|
||||
token_hash: bytes,
|
||||
now: datetime,
|
||||
) -> dataclasses.CurrentSessionDTO | None:
|
||||
"""Действующая сессия по хэшу токена вместе с владельцем.
|
||||
|
||||
Один запрос по уникальному индексу `token_hash`. Истёкшая сессия —
|
||||
None; `now` передаёт сервис: срок сравнивается по часам приложения,
|
||||
которые его и поставили.
|
||||
"""
|
||||
statement = (
|
||||
select(Session.id.label("session_id"), *USER_COLUMNS)
|
||||
.join(User, User.id == Session.user_id)
|
||||
.where(Session.token_hash == token_hash, Session.expires_at > now)
|
||||
)
|
||||
row = (await db_session.execute(statement)).one_or_none()
|
||||
if row is None:
|
||||
return None
|
||||
fields = dict(row._mapping)
|
||||
session_id = fields.pop("session_id")
|
||||
return dataclasses.CurrentSessionDTO(
|
||||
id=session_id,
|
||||
user=dataclasses.UserFullDTO(**fields),
|
||||
)
|
||||
Один запрос по уникальному индексу `token_hash`. Истёкшая сессия —
|
||||
None; `now` передаёт сервис: срок сравнивается по часам приложения,
|
||||
которые его и поставили.
|
||||
"""
|
||||
statement = (
|
||||
select(Session.id.label("session_id"), *USER_COLUMNS)
|
||||
.join(User, User.id == Session.user_id)
|
||||
.where(Session.token_hash == token_hash, Session.expires_at > now)
|
||||
)
|
||||
row = (await self._session.execute(statement)).one_or_none()
|
||||
if row is None:
|
||||
return None
|
||||
fields = dict(row._mapping)
|
||||
session_id = fields.pop("session_id")
|
||||
return dataclasses.CurrentSessionDTO(
|
||||
id=session_id,
|
||||
user=dataclasses.UserFullDTO(**fields),
|
||||
)
|
||||
|
||||
|
||||
async def delete_session(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
session_id: UUID,
|
||||
) -> bool:
|
||||
"""Отзыв; False — сессию уже удалил параллельный запрос."""
|
||||
statement = (
|
||||
delete(Session).where(Session.id == session_id).returning(Session.id)
|
||||
)
|
||||
return (await db_session.execute(statement)).one_or_none() is not None
|
||||
async def delete_session(self, *, session_id: UUID) -> bool:
|
||||
"""Отзыв; False — сессию уже удалил параллельный запрос."""
|
||||
statement = (
|
||||
delete(Session)
|
||||
.where(Session.id == session_id)
|
||||
.returning(Session.id)
|
||||
)
|
||||
return (
|
||||
await self._session.execute(statement)
|
||||
).one_or_none() is not None
|
||||
|
||||
+46
-43
@@ -6,6 +6,7 @@ from sqlalchemy import select
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.core.ports.user import AbstractUserRepository
|
||||
from src.infra.db.models import User
|
||||
from src.schemas import dataclasses
|
||||
|
||||
@@ -14,49 +15,51 @@ from src.schemas import dataclasses
|
||||
USER_COLUMNS = (User.id, User.username, User.display_name, User.created_at)
|
||||
|
||||
|
||||
async def insert_user(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
user: dataclasses.UserFullDTO,
|
||||
password_hash: str,
|
||||
) -> dataclasses.UserFullDTO | None:
|
||||
"""Вставка; занятый username — None (уникальность держит БД)."""
|
||||
statement = (
|
||||
pg_insert(User)
|
||||
.values(**asdict(user), password_hash=password_hash)
|
||||
.on_conflict_do_nothing(index_elements=[User.username])
|
||||
.returning(*USER_COLUMNS)
|
||||
)
|
||||
row = (await db_session.execute(statement)).one_or_none()
|
||||
if row is None:
|
||||
return None
|
||||
return dataclasses.UserFullDTO(**row._mapping)
|
||||
class SqlAlchemyUserRepository(AbstractUserRepository):
|
||||
def __init__(self, session: AsyncSession) -> None:
|
||||
self._session = session
|
||||
|
||||
async def insert_user(
|
||||
self,
|
||||
*,
|
||||
user: dataclasses.UserFullDTO,
|
||||
password_hash: str,
|
||||
) -> dataclasses.UserFullDTO | None:
|
||||
"""Вставка; занятый username — None (уникальность держит БД)."""
|
||||
statement = (
|
||||
pg_insert(User)
|
||||
.values(**asdict(user), password_hash=password_hash)
|
||||
.on_conflict_do_nothing(index_elements=[User.username])
|
||||
.returning(*USER_COLUMNS)
|
||||
)
|
||||
row = (await self._session.execute(statement)).one_or_none()
|
||||
if row is None:
|
||||
return None
|
||||
return dataclasses.UserFullDTO(**row._mapping)
|
||||
|
||||
async def get_user_credentials(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
username: str,
|
||||
) -> dataclasses.UserCredentialsDTO | None:
|
||||
statement = select(*USER_COLUMNS, User.password_hash).where(
|
||||
User.username == username,
|
||||
)
|
||||
row = (await db_session.execute(statement)).one_or_none()
|
||||
if row is None:
|
||||
return None
|
||||
fields = dict(row._mapping)
|
||||
password_hash = fields.pop("password_hash")
|
||||
return dataclasses.UserCredentialsDTO(
|
||||
user=dataclasses.UserFullDTO(**fields),
|
||||
password_hash=password_hash,
|
||||
)
|
||||
async def get_user_credentials(
|
||||
self,
|
||||
*,
|
||||
username: str,
|
||||
) -> dataclasses.UserCredentialsDTO | None:
|
||||
statement = select(*USER_COLUMNS, User.password_hash).where(
|
||||
User.username == username,
|
||||
)
|
||||
row = (await self._session.execute(statement)).one_or_none()
|
||||
if row is None:
|
||||
return None
|
||||
fields = dict(row._mapping)
|
||||
password_hash = fields.pop("password_hash")
|
||||
return dataclasses.UserCredentialsDTO(
|
||||
user=dataclasses.UserFullDTO(**fields),
|
||||
password_hash=password_hash,
|
||||
)
|
||||
|
||||
|
||||
async def get_existing_user_ids(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
user_ids: Iterable[UUID],
|
||||
) -> set[UUID]:
|
||||
"""Те из переданных id, для которых пользователь существует."""
|
||||
statement = select(User.id).where(User.id.in_(list(user_ids)))
|
||||
return set((await db_session.scalars(statement)).all())
|
||||
async def get_existing_user_ids(
|
||||
self,
|
||||
*,
|
||||
user_ids: Iterable[UUID],
|
||||
) -> set[UUID]:
|
||||
"""Те из переданных id, для которых пользователь существует."""
|
||||
statement = select(User.id).where(User.id.in_(list(user_ids)))
|
||||
return set((await self._session.scalars(statement)).all())
|
||||
|
||||
@@ -2,22 +2,19 @@ import asyncio
|
||||
import hashlib
|
||||
import io
|
||||
import time
|
||||
from collections.abc import AsyncIterator, Callable
|
||||
from contextlib import AbstractAsyncContextManager, AsyncExitStack
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import AsyncExitStack
|
||||
from dataclasses import replace
|
||||
from typing import TYPE_CHECKING
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import anyio.to_thread
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.config import settings
|
||||
from src.core import exceptions
|
||||
from src.core.repos import attachment as attachment_repo
|
||||
from src.core.repos import attachment_job as attachment_job_repo
|
||||
from src.core.ports.uow import AbstractUnitOfWork
|
||||
from src.core.repos import attachment_object as attachment_object_repo
|
||||
from src.core.repos import attachment_variant as attachment_variant_repo
|
||||
from src.core.services.chat import ChatService
|
||||
from src.core.services.chat import require_member
|
||||
from src.infra.cache import Cache
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.infra.s3 import ObjectStorage
|
||||
@@ -52,9 +49,6 @@ logger: AbstractLogger = get_logger().bind(module="attachment_service")
|
||||
# Content-Type загрузки: тип без параметров, в нижнем регистре
|
||||
_ACCEPTED_MEDIA_TYPES = frozenset(image_type.value for image_type in ImageType)
|
||||
|
||||
# короткая сессия БД на один шаг: `db_session_scope` слоя API
|
||||
type DbScope = Callable[[], AbstractAsyncContextManager[AsyncSession]]
|
||||
|
||||
|
||||
def _inspect(data: bytes) -> tuple[ImageInfo, bytes]:
|
||||
"""Структура изображения и SHA-256 — одним вызовом в потоке."""
|
||||
@@ -65,8 +59,7 @@ def _inspect(data: bytes) -> tuple[ImageInfo, bytes]:
|
||||
class AttachmentService:
|
||||
"""Вложения: загрузка в S3 с метаданными в PostgreSQL, чтение, отдача.
|
||||
|
||||
Сессии на весь запрос нет: каждый шаг с БД — свой короткий
|
||||
`async with self.db_scope()`, без вложенных, поэтому ни одно
|
||||
Каждый шаг с БД — свой блок `async with self.uow`, поэтому ни одно
|
||||
соединение пула не занято передачей тела (design change
|
||||
`attachments`, решение 5). Загрузка идёт на месте из `slots` — мест
|
||||
процесса (design change `upload-memory`, решение 1); ожидающая
|
||||
@@ -78,28 +71,16 @@ class AttachmentService:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
db_scope: DbScope,
|
||||
uow: AbstractUnitOfWork,
|
||||
cache: Cache,
|
||||
storage: ObjectStorage,
|
||||
slots: "UploadSlots",
|
||||
) -> None:
|
||||
self.db_scope = db_scope
|
||||
self.uow = uow
|
||||
self.cache = cache
|
||||
self.storage = storage
|
||||
self.slots = slots
|
||||
|
||||
async def _require_member(
|
||||
self,
|
||||
*,
|
||||
db_session: AsyncSession,
|
||||
chat_id: UUID,
|
||||
user_id: UUID,
|
||||
) -> None:
|
||||
await ChatService(
|
||||
db_session=db_session,
|
||||
cache=self.cache,
|
||||
).get_chat_for_member(chat_id=chat_id, user_id=user_id)
|
||||
|
||||
async def upload(
|
||||
self,
|
||||
*,
|
||||
@@ -132,9 +113,10 @@ class AttachmentService:
|
||||
chat_id=chat_id,
|
||||
filename_length=len(filename),
|
||||
)
|
||||
async with self.db_scope() as db_session:
|
||||
await self._require_member(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
await require_member(
|
||||
self.uow,
|
||||
self.cache,
|
||||
chat_id=chat_id,
|
||||
user_id=owner_id,
|
||||
)
|
||||
@@ -235,12 +217,9 @@ class AttachmentService:
|
||||
staging = pending.staging_key
|
||||
if staging is None:
|
||||
raise RuntimeError("Pending attachment has no staging key")
|
||||
async with self.db_scope() as db_session:
|
||||
await attachment_repo.insert_attachment(
|
||||
db_session=db_session,
|
||||
attachment=pending,
|
||||
)
|
||||
await db_session.commit()
|
||||
async with self.uow:
|
||||
await self.uow.attachments.insert_attachment(attachment=pending)
|
||||
await self.uow.commit()
|
||||
log = log.bind(attachment_id=attachment_id)
|
||||
buffer.seek(0)
|
||||
try:
|
||||
@@ -296,16 +275,14 @@ class AttachmentService:
|
||||
commit_sent = False
|
||||
job: dataclasses.AttachmentJobDTO | None = None
|
||||
try:
|
||||
async with self.db_scope() as db_session:
|
||||
async with self.uow:
|
||||
now = utcnow()
|
||||
queued = await attachment_repo.mark_queued(
|
||||
db_session=db_session,
|
||||
queued = await self.uow.attachments.mark_queued(
|
||||
attachment_id=attachment_id,
|
||||
updated_at=now,
|
||||
)
|
||||
if queued is not None:
|
||||
job = await attachment_job_repo.insert_job(
|
||||
db_session=db_session,
|
||||
job = await self.uow.jobs.insert_job(
|
||||
job=dataclasses.AttachmentJobDTO(
|
||||
id=uuid4(),
|
||||
attachment_id=attachment_id,
|
||||
@@ -317,7 +294,7 @@ class AttachmentService:
|
||||
),
|
||||
)
|
||||
commit_sent = True
|
||||
await db_session.commit()
|
||||
await self.uow.commit()
|
||||
except Exception:
|
||||
# CancelledError сюда не попадает: при отмене задачи await
|
||||
# ненадёжен, остаток убирает уборщик
|
||||
@@ -409,9 +386,8 @@ class AttachmentService:
|
||||
одинаковый `AttachmentNotFound`. Варианты — только у `ready`: строка
|
||||
читается раньше вариантов, поэтому `ready` без них увидеть нельзя.
|
||||
"""
|
||||
async with self.db_scope() as db_session:
|
||||
attachment = await attachment_repo.get_attachment(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
attachment = await self.uow.attachments.get_attachment(
|
||||
attachment_id=attachment_id,
|
||||
)
|
||||
if (
|
||||
@@ -420,16 +396,16 @@ class AttachmentService:
|
||||
):
|
||||
raise exceptions.AttachmentNotFound
|
||||
try:
|
||||
await self._require_member(
|
||||
db_session=db_session,
|
||||
await require_member(
|
||||
self.uow,
|
||||
self.cache,
|
||||
chat_id=attachment.chat_id,
|
||||
user_id=user_id,
|
||||
)
|
||||
except exceptions.ChatNotFound as e:
|
||||
raise exceptions.AttachmentNotFound from e
|
||||
if attachment.status == AttachmentStatus.READY:
|
||||
variants = await attachment_variant_repo.get_variants(
|
||||
db_session=db_session,
|
||||
variants = await self.uow.variants.get_variants(
|
||||
attachment_id=attachment_id,
|
||||
)
|
||||
attachment = replace(attachment, variants=tuple(variants))
|
||||
|
||||
@@ -17,9 +17,8 @@ from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from src.core import exceptions
|
||||
from src.core.repos import attachment as attachment_repo
|
||||
from src.core.ports.uow import AbstractUnitOfWork
|
||||
from src.core.repos import attachment_object as attachment_object_repo
|
||||
from src.core.services.attachment import DbScope
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.infra.s3 import ObjectStorage
|
||||
from src.schemas import dataclasses
|
||||
@@ -42,13 +41,16 @@ def _never() -> bool:
|
||||
class AttachmentCleanupService:
|
||||
"""Уборщик строк `pending` и их объектов.
|
||||
|
||||
`db_scope` — фабрика короткой сессии процесса уборщика (`session_scope`
|
||||
со своей фабрикой), `storage` — клиент S3 с ключами пользователя
|
||||
уборщика.
|
||||
`uow` — единица работы процесса уборщика, `storage` — клиент S3 с ключами
|
||||
пользователя уборщика.
|
||||
"""
|
||||
|
||||
def __init__(self, db_scope: DbScope, storage: ObjectStorage) -> None:
|
||||
self.db_scope = db_scope
|
||||
def __init__(
|
||||
self,
|
||||
uow: AbstractUnitOfWork,
|
||||
storage: ObjectStorage,
|
||||
) -> None:
|
||||
self.uow = uow
|
||||
self.storage = storage
|
||||
|
||||
async def clean_stale_pending(
|
||||
@@ -77,9 +79,8 @@ class AttachmentCleanupService:
|
||||
after: tuple[datetime, UUID] | None = None
|
||||
try:
|
||||
while interrupted_by is None:
|
||||
async with self.db_scope() as db_session:
|
||||
candidates = await attachment_repo.get_stale_pending(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
candidates = await self.uow.attachments.get_stale_pending(
|
||||
older_than=older_than,
|
||||
after=after,
|
||||
limit=batch_size,
|
||||
@@ -107,7 +108,7 @@ class AttachmentCleanupService:
|
||||
# причину уже записал клиент S3 (`object_storage`)
|
||||
interrupted_by = INTERRUPTED_BY_OBJECT_STORAGE
|
||||
except exceptions.ServiceUnavailable:
|
||||
# причину уже записал `session_scope` (`database`)
|
||||
# причину уже записала единица работы (`database`)
|
||||
interrupted_by = INTERRUPTED_BY_DATABASE
|
||||
result = dataclasses.CleanupPassDTO(
|
||||
removed=removed,
|
||||
@@ -157,15 +158,13 @@ class AttachmentCleanupService:
|
||||
):
|
||||
after: tuple[datetime, UUID] | None = None
|
||||
while interrupted_by is None:
|
||||
async with self.db_scope() as db_session:
|
||||
candidates = (
|
||||
await attachment_repo.get_staging_candidates(
|
||||
db_session=db_session,
|
||||
status=status,
|
||||
updated_before=before,
|
||||
after=after,
|
||||
limit=batch_size,
|
||||
)
|
||||
async with self.uow:
|
||||
attachments = self.uow.attachments
|
||||
candidates = await attachments.get_staging_candidates(
|
||||
status=status,
|
||||
updated_before=before,
|
||||
after=after,
|
||||
limit=batch_size,
|
||||
)
|
||||
for candidate in candidates:
|
||||
if stop_requested():
|
||||
@@ -187,7 +186,7 @@ class AttachmentCleanupService:
|
||||
# причину уже записал клиент S3 (`object_storage`)
|
||||
interrupted_by = INTERRUPTED_BY_OBJECT_STORAGE
|
||||
except exceptions.ServiceUnavailable:
|
||||
# причину уже записал `session_scope` (`database`)
|
||||
# причину уже записала единица работы (`database`)
|
||||
interrupted_by = INTERRUPTED_BY_DATABASE
|
||||
result = dataclasses.StagingCleanupPassDTO(
|
||||
removed_ready=removed[AttachmentStatus.READY],
|
||||
@@ -233,9 +232,8 @@ class AttachmentCleanupService:
|
||||
ссылкой на вложение не ждёт DELETE в S3. У `failed` ещё объекты вариантов
|
||||
всех имён и конечный оригинал: скачать их нельзя, а без исходника replay
|
||||
невозможен. `False` — строку держат, её уже нет или ключ не свой."""
|
||||
async with self.db_scope() as db_session:
|
||||
locked = await attachment_repo.lock_staging_candidate(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
locked = await self.uow.attachments.lock_staging_candidate(
|
||||
attachment_id=candidate.id,
|
||||
status=status,
|
||||
updated_before=updated_before,
|
||||
@@ -270,11 +268,10 @@ class AttachmentCleanupService:
|
||||
self.storage,
|
||||
key=locked.staging_key,
|
||||
)
|
||||
await attachment_repo.clear_staging_key(
|
||||
db_session=db_session,
|
||||
await self.uow.attachments.clear_staging_key(
|
||||
attachment_id=locked.id,
|
||||
)
|
||||
await db_session.commit()
|
||||
await self.uow.commit()
|
||||
return True
|
||||
|
||||
async def remove_stale_pending(
|
||||
@@ -313,25 +310,22 @@ class AttachmentCleanupService:
|
||||
шага с БД, 6 с), и уборщик укладывается в срок остановки
|
||||
контейнера (10 с); помеченная строка ждёт следующего запуска.
|
||||
"""
|
||||
async with self.db_scope() as db_session:
|
||||
stale = await attachment_repo.lock_stale_pending(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
stale = await self.uow.attachments.lock_stale_pending(
|
||||
attachment_id=attachment_id,
|
||||
older_than=older_than,
|
||||
)
|
||||
if stale is None:
|
||||
return False
|
||||
await attachment_repo.mark_removing(
|
||||
db_session=db_session,
|
||||
await self.uow.attachments.mark_removing(
|
||||
attachment_id=stale.id,
|
||||
updated_at=utcnow(),
|
||||
)
|
||||
await db_session.commit()
|
||||
await self.uow.commit()
|
||||
if stop_requested():
|
||||
return False
|
||||
async with self.db_scope() as db_session:
|
||||
locked = await attachment_repo.lock_stale_pending(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
locked = await self.uow.attachments.lock_stale_pending(
|
||||
attachment_id=stale.id,
|
||||
older_than=older_than,
|
||||
)
|
||||
@@ -344,11 +338,10 @@ class AttachmentCleanupService:
|
||||
self.storage,
|
||||
key=object_key,
|
||||
)
|
||||
await attachment_repo.delete_attachment(
|
||||
db_session=db_session,
|
||||
await self.uow.attachments.delete_attachment(
|
||||
attachment_id=locked.id,
|
||||
)
|
||||
await db_session.commit()
|
||||
await self.uow.commit()
|
||||
log.info(
|
||||
"Removed stale attachment",
|
||||
attachment_id=stale.id,
|
||||
|
||||
@@ -23,15 +23,11 @@ import time
|
||||
from datetime import timedelta
|
||||
|
||||
from pydantic import ValidationError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.config import settings
|
||||
from src.core import exceptions
|
||||
from src.core.repos import attachment as attachment_repo
|
||||
from src.core.repos import attachment_job as attachment_job_repo
|
||||
from src.core.ports.uow import AbstractUnitOfWork
|
||||
from src.core.repos import attachment_object as attachment_object_repo
|
||||
from src.core.repos import attachment_variant as attachment_variant_repo
|
||||
from src.core.services.attachment import DbScope
|
||||
from src.infra.logger import AbstractLogger, get_logger, http_request_id
|
||||
from src.infra.render import ImageRenderer
|
||||
from src.infra.s3 import ObjectStorage
|
||||
@@ -82,18 +78,19 @@ class _PermanentError(Exception):
|
||||
|
||||
|
||||
class AttachmentProcessingService:
|
||||
"""Обработка заданий. `db_scope` — короткая сессия процесса worker,
|
||||
`storage` — клиент S3 с ключами worker, `renderer` — процесс обработки на
|
||||
задание, `stop` — сигнал остановки: он прерывает паузу при отказе БД."""
|
||||
"""Обработка заданий. `uow` — единица работы одной доставки: экземпляр
|
||||
сервиса на доставку (design change `unit-of-work`, решение 3), `storage` —
|
||||
клиент S3 с ключами worker, `renderer` — процесс обработки на задание,
|
||||
`stop` — сигнал остановки: он прерывает паузу при отказе БД."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
db_scope: DbScope,
|
||||
uow: AbstractUnitOfWork,
|
||||
storage: ObjectStorage,
|
||||
renderer: ImageRenderer,
|
||||
stop: asyncio.Event,
|
||||
) -> None:
|
||||
self.db_scope = db_scope
|
||||
self.uow = uow
|
||||
self.storage = storage
|
||||
self.renderer = renderer
|
||||
self.stop = stop
|
||||
@@ -121,7 +118,7 @@ class AttachmentProcessingService:
|
||||
)
|
||||
except exceptions.ServiceUnavailable:
|
||||
# записать нельзя: задание ждёт в очереди, попытка не считается.
|
||||
# Причину уже записал session_scope
|
||||
# Причину уже записала единица работы
|
||||
log.warning("Job waits for database")
|
||||
await self._pause()
|
||||
return JobOutcome.REQUEUE
|
||||
@@ -229,20 +226,13 @@ class AttachmentProcessingService:
|
||||
"""Взять задание под блокировкой (таблица решения 3) или вернуть итог
|
||||
без попытки. Сообщение без работы подтверждается: живую попытку ведёт её
|
||||
аренда, а следующую публикует relay."""
|
||||
async with self.db_scope() as db_session:
|
||||
job = await attachment_job_repo.lock_job(
|
||||
db_session=db_session,
|
||||
job_id=message.job_id,
|
||||
)
|
||||
async with self.uow:
|
||||
job = await self.uow.jobs.lock_job(job_id=message.job_id)
|
||||
if job is None or job.attachment_id != message.attachment_id:
|
||||
log.info("Skipped job message", reason="unknown")
|
||||
return JobOutcome.ACK
|
||||
if job.state == AttachmentJobState.SUCCEEDED:
|
||||
await self._check_finished(
|
||||
db_session=db_session,
|
||||
job=job,
|
||||
log=log,
|
||||
)
|
||||
await self._check_finished(job=job, log=log)
|
||||
return JobOutcome.ACK
|
||||
if job.state == AttachmentJobState.FAILED:
|
||||
log.info("Skipped job message", reason="finished")
|
||||
@@ -267,12 +257,11 @@ class AttachmentProcessingService:
|
||||
# попытка потеряна при исчерпанном бюджете: сообщение пришло, а
|
||||
# попытка уже посчитана
|
||||
await self._write_failed(
|
||||
db_session=db_session,
|
||||
job=job,
|
||||
error_code=AttachmentErrorCode.RETRY_EXHAUSTED,
|
||||
reason=None,
|
||||
)
|
||||
await db_session.commit()
|
||||
await self.uow.commit()
|
||||
log.warning(
|
||||
"Attachment failed",
|
||||
error_code=AttachmentErrorCode.RETRY_EXHAUSTED.value,
|
||||
@@ -280,12 +269,8 @@ class AttachmentProcessingService:
|
||||
attempt=job.attempt,
|
||||
)
|
||||
return JobOutcome.ACK
|
||||
taken = await self._start_attempt(
|
||||
db_session=db_session,
|
||||
job=job,
|
||||
now=now,
|
||||
)
|
||||
await db_session.commit()
|
||||
taken = await self._start_attempt(job=job, now=now)
|
||||
await self.uow.commit()
|
||||
if taken is None:
|
||||
log.info("Skipped job message", reason="unknown")
|
||||
return JobOutcome.ACK
|
||||
@@ -305,7 +290,6 @@ class AttachmentProcessingService:
|
||||
async def _start_attempt(
|
||||
self,
|
||||
*,
|
||||
db_session: AsyncSession,
|
||||
job: dataclasses.AttachmentJobDTO,
|
||||
now,
|
||||
) -> (
|
||||
@@ -313,8 +297,7 @@ class AttachmentProcessingService:
|
||||
| None
|
||||
):
|
||||
worker = settings.worker
|
||||
started = await attachment_job_repo.start_attempt(
|
||||
db_session=db_session,
|
||||
started = await self.uow.jobs.start_attempt(
|
||||
job_id=job.id,
|
||||
lease_expires_at=now
|
||||
+ timedelta(
|
||||
@@ -325,34 +308,29 @@ class AttachmentProcessingService:
|
||||
)
|
||||
if started is None:
|
||||
return None
|
||||
if not await attachment_repo.mark_processing(
|
||||
db_session=db_session,
|
||||
if not await self.uow.attachments.mark_processing(
|
||||
attachment_id=job.attachment_id,
|
||||
updated_at=now,
|
||||
):
|
||||
return None
|
||||
attachment = await attachment_repo.get_attachment(
|
||||
db_session=db_session,
|
||||
attachment = await self.uow.attachments.get_attachment(
|
||||
attachment_id=job.attachment_id,
|
||||
)
|
||||
return None if attachment is None else (started, attachment)
|
||||
|
||||
@staticmethod
|
||||
async def _check_finished(
|
||||
self,
|
||||
*,
|
||||
db_session: AsyncSession,
|
||||
job: dataclasses.AttachmentJobDTO,
|
||||
log: AbstractLogger,
|
||||
) -> None:
|
||||
"""Повторная доставка завершённого: проверка эффекта, без записи.
|
||||
Проверяется `thumbnail`: строки прежней версии других вариантов не
|
||||
имеют."""
|
||||
attachment = await attachment_repo.get_attachment(
|
||||
db_session=db_session,
|
||||
attachment = await self.uow.attachments.get_attachment(
|
||||
attachment_id=job.attachment_id,
|
||||
)
|
||||
variant = await attachment_variant_repo.get_variant(
|
||||
db_session=db_session,
|
||||
variant = await self.uow.variants.get_variant(
|
||||
attachment_id=job.attachment_id,
|
||||
name=AttachmentVariantName.THUMBNAIL,
|
||||
)
|
||||
@@ -465,56 +443,47 @@ class AttachmentProcessingService:
|
||||
"""Вложение `ready`, варианты и итог задания — одной транзакцией;
|
||||
`False` — задание ведёт другая попытка или итог уже есть: результат
|
||||
прежней попытки не фиксируется (fencing, решение 3)."""
|
||||
async with self.db_scope() as db_session:
|
||||
locked = await attachment_job_repo.lock_job(
|
||||
db_session=db_session,
|
||||
job_id=job.id,
|
||||
)
|
||||
async with self.uow:
|
||||
locked = await self.uow.jobs.lock_job(job_id=job.id)
|
||||
if not self._own_attempt(locked, job=job):
|
||||
log.info("Skipped job message", reason="superseded")
|
||||
return False
|
||||
now = utcnow()
|
||||
if not await attachment_repo.commit_ready(
|
||||
db_session=db_session,
|
||||
if not await self.uow.attachments.commit_ready(
|
||||
attachment_id=attachment.id,
|
||||
updated_at=now,
|
||||
):
|
||||
log.info("Skipped job message", reason="finished")
|
||||
return False
|
||||
for variant in variants:
|
||||
await attachment_variant_repo.insert_variant(
|
||||
db_session=db_session,
|
||||
await self.uow.variants.insert_variant(
|
||||
attachment_id=attachment.id,
|
||||
variant=variant,
|
||||
)
|
||||
await attachment_job_repo.finish_job(
|
||||
db_session=db_session,
|
||||
await self.uow.jobs.finish_job(
|
||||
job_id=job.id,
|
||||
state=AttachmentJobState.SUCCEEDED,
|
||||
reason=None,
|
||||
now=now,
|
||||
)
|
||||
await db_session.commit()
|
||||
await self.uow.commit()
|
||||
return True
|
||||
|
||||
async def _write_failed(
|
||||
self,
|
||||
*,
|
||||
db_session: AsyncSession,
|
||||
job: dataclasses.AttachmentJobDTO,
|
||||
error_code: AttachmentErrorCode,
|
||||
reason: AttachmentJobReason | None,
|
||||
) -> bool:
|
||||
now = utcnow()
|
||||
if not await attachment_repo.commit_failed(
|
||||
db_session=db_session,
|
||||
if not await self.uow.attachments.commit_failed(
|
||||
attachment_id=job.attachment_id,
|
||||
error_code=error_code,
|
||||
updated_at=now,
|
||||
):
|
||||
return False
|
||||
await attachment_job_repo.finish_job(
|
||||
db_session=db_session,
|
||||
await self.uow.jobs.finish_job(
|
||||
job_id=job.id,
|
||||
state=AttachmentJobState.FAILED,
|
||||
reason=reason,
|
||||
@@ -531,21 +500,17 @@ class AttachmentProcessingService:
|
||||
log: AbstractLogger,
|
||||
) -> JobOutcome:
|
||||
"""`failed` своей попытки; задание уже ведёт другая — без записи."""
|
||||
async with self.db_scope() as db_session:
|
||||
locked = await attachment_job_repo.lock_job(
|
||||
db_session=db_session,
|
||||
job_id=job.id,
|
||||
)
|
||||
async with self.uow:
|
||||
locked = await self.uow.jobs.lock_job(job_id=job.id)
|
||||
if not self._own_attempt(locked, job=job):
|
||||
log.info("Skipped job message", reason="superseded")
|
||||
return JobOutcome.ACK
|
||||
written = await self._write_failed(
|
||||
db_session=db_session,
|
||||
job=job,
|
||||
error_code=error_code,
|
||||
reason=reason,
|
||||
)
|
||||
await db_session.commit()
|
||||
await self.uow.commit()
|
||||
if written:
|
||||
log.warning(
|
||||
"Attachment failed",
|
||||
@@ -589,11 +554,10 @@ class AttachmentProcessingService:
|
||||
base=worker.retry_base_delay_seconds,
|
||||
maximum=worker.retry_max_delay_seconds,
|
||||
)
|
||||
async with self.db_scope() as db_session:
|
||||
async with self.uow:
|
||||
now = utcnow()
|
||||
next_attempt_at = now + timedelta(seconds=delay)
|
||||
own = await attachment_job_repo.return_to_queued(
|
||||
db_session=db_session,
|
||||
own = await self.uow.jobs.return_to_queued(
|
||||
job_id=job.id,
|
||||
attempt=job.attempt,
|
||||
reason=reason,
|
||||
@@ -603,12 +567,11 @@ class AttachmentProcessingService:
|
||||
if not own:
|
||||
log.info("Skipped job message", reason="superseded")
|
||||
return JobOutcome.ACK
|
||||
await attachment_repo.return_to_queued(
|
||||
db_session=db_session,
|
||||
await self.uow.attachments.return_to_queued(
|
||||
attachment_id=job.attachment_id,
|
||||
updated_at=now,
|
||||
)
|
||||
await db_session.commit()
|
||||
await self.uow.commit()
|
||||
log.warning(
|
||||
"Retrying job",
|
||||
reason=reason.value,
|
||||
|
||||
@@ -50,18 +50,15 @@ import hashlib
|
||||
import time
|
||||
from collections import Counter
|
||||
from collections.abc import Callable, Iterator
|
||||
from contextlib import AbstractAsyncContextManager, contextmanager
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, replace
|
||||
from datetime import datetime
|
||||
from types import MappingProxyType
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.core import exceptions
|
||||
from src.core.repos import attachment as attachment_repo
|
||||
from src.core.ports.uow import AbstractUnitOfWork
|
||||
from src.core.repos import attachment_object as attachment_object_repo
|
||||
from src.core.services.attachment import DbScope
|
||||
from src.core.services.attachment_cleanup import (
|
||||
INTERRUPTED_BY_DATABASE,
|
||||
INTERRUPTED_BY_OBJECT_STORAGE,
|
||||
@@ -219,26 +216,21 @@ class _Pass:
|
||||
class AttachmentReconcileService:
|
||||
"""Сверка объектов вложений своей базы с их метаданными.
|
||||
|
||||
`db_scope` — фабрика короткой сессии процесса уборщика, `storage` —
|
||||
клиент S3 с ключами пользователя уборщика (список — только по
|
||||
префиксу вложений своей базы). Зависшие загрузки убирает
|
||||
`AttachmentCleanupService` тем же шагом, что сервис уборки; его сеансы
|
||||
с PostgreSQL входят в счёт прохода (`db_sessions`).
|
||||
`uow` — единица работы процесса уборщика, `storage` — клиент S3 с ключами
|
||||
пользователя уборщика (список — только по префиксу вложений своей базы).
|
||||
Зависшие загрузки убирает `AttachmentCleanupService` тем же шагом, что
|
||||
сервис уборки, на том же экземпляре единицы работы: его блоки входят в счёт
|
||||
прохода (`db_sessions` — разность `uow.blocks_opened`).
|
||||
"""
|
||||
|
||||
def __init__(self, db_scope: DbScope, storage: ObjectStorage) -> None:
|
||||
self._db_scope = db_scope
|
||||
def __init__(
|
||||
self,
|
||||
uow: AbstractUnitOfWork,
|
||||
storage: ObjectStorage,
|
||||
) -> None:
|
||||
self.uow = uow
|
||||
self.storage = storage
|
||||
self._db_sessions = 0
|
||||
self.cleanup = AttachmentCleanupService(
|
||||
db_scope=self.db_scope,
|
||||
storage=storage,
|
||||
)
|
||||
|
||||
def db_scope(self) -> AbstractAsyncContextManager[AsyncSession]:
|
||||
"""Сессия на шаг со счётом сеансов прохода."""
|
||||
self._db_sessions += 1
|
||||
return self._db_scope()
|
||||
self.cleanup = AttachmentCleanupService(uow=uow, storage=storage)
|
||||
|
||||
async def reconcile(
|
||||
self,
|
||||
@@ -281,7 +273,7 @@ class AttachmentReconcileService:
|
||||
staging_older_than=staging_older_than,
|
||||
stop_requested=stop_requested,
|
||||
stats=self.storage.stats(),
|
||||
db_sessions=self._db_sessions,
|
||||
db_sessions=self.uow.blocks_opened,
|
||||
)
|
||||
interrupted_by: str | None = None
|
||||
try:
|
||||
@@ -307,7 +299,7 @@ class AttachmentReconcileService:
|
||||
else INTERRUPTED_BY_OBJECT_STORAGE
|
||||
)
|
||||
except exceptions.ServiceUnavailable:
|
||||
# причину уже записал `session_scope` (`database`)
|
||||
# причину уже записала единица работы (`database`)
|
||||
interrupted_by = (
|
||||
INTERRUPTED_BY_STOP
|
||||
if stop_requested()
|
||||
@@ -527,9 +519,8 @@ class AttachmentReconcileService:
|
||||
ids: list[UUID],
|
||||
) -> dict[UUID, dataclasses.AttachmentFullDTO]:
|
||||
state.check_stop()
|
||||
async with self.db_scope() as db_session:
|
||||
rows = await attachment_repo.get_attachments_for_objects(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
rows = await self.uow.attachments.get_attachments_for_objects(
|
||||
attachment_ids=ids,
|
||||
object_keys=[],
|
||||
)
|
||||
@@ -585,9 +576,8 @@ class AttachmentReconcileService:
|
||||
if parsed:
|
||||
# страница списка уже могла ждать S3 до срока
|
||||
state.check_stop()
|
||||
async with self.db_scope() as db_session:
|
||||
rows = await attachment_repo.get_attachments_for_objects(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
rows = await self.uow.attachments.get_attachments_for_objects(
|
||||
attachment_ids=ids,
|
||||
object_keys=keys,
|
||||
)
|
||||
@@ -630,9 +620,8 @@ class AttachmentReconcileService:
|
||||
"""`head`: строка объекта отдельной выборкой — по `id` стандартного
|
||||
ключа или по тексту нестандартного, как выражение страницы."""
|
||||
state.check_stop()
|
||||
async with self.db_scope() as db_session:
|
||||
rows = await attachment_repo.get_attachments_for_objects(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
rows = await self.uow.attachments.get_attachments_for_objects(
|
||||
attachment_ids=set()
|
||||
if attachment_id is None
|
||||
else {
|
||||
@@ -786,9 +775,8 @@ class AttachmentReconcileService:
|
||||
after: UUID | None = None
|
||||
while True:
|
||||
state.check_stop()
|
||||
async with self.db_scope() as db_session:
|
||||
rows = await attachment_repo.get_ready_page(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
rows = await self.uow.attachments.get_ready_page(
|
||||
after=after,
|
||||
limit=page_size,
|
||||
)
|
||||
@@ -868,9 +856,8 @@ class AttachmentReconcileService:
|
||||
after: tuple[datetime, UUID] | None = None
|
||||
while True:
|
||||
state.check_stop()
|
||||
async with self.db_scope() as db_session:
|
||||
rows = await attachment_repo.get_stale_pending(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
rows = await self.uow.attachments.get_stale_pending(
|
||||
older_than=state.older_than,
|
||||
after=after,
|
||||
limit=batch_size,
|
||||
@@ -1066,9 +1053,8 @@ class AttachmentReconcileService:
|
||||
if finding.attachment_id is None:
|
||||
return False
|
||||
state.check_stop()
|
||||
async with self.db_scope() as db_session:
|
||||
row = await attachment_repo.get_attachment(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
row = await self.uow.attachments.get_attachment(
|
||||
attachment_id=finding.attachment_id,
|
||||
)
|
||||
return row is not None and row.staging_key == finding.object_key
|
||||
@@ -1082,9 +1068,8 @@ class AttachmentReconcileService:
|
||||
if candidate.attachment_id is None:
|
||||
return None
|
||||
state.check_stop()
|
||||
async with self.db_scope() as db_session:
|
||||
row = await attachment_repo.get_attachment(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
row = await self.uow.attachments.get_attachment(
|
||||
attachment_id=candidate.attachment_id,
|
||||
)
|
||||
if row is None or row.object_key != candidate.object_key:
|
||||
@@ -1119,9 +1104,8 @@ class AttachmentReconcileService:
|
||||
if candidate.attachment_id is None:
|
||||
return []
|
||||
state.check_stop()
|
||||
async with self.db_scope() as db_session:
|
||||
return await attachment_repo.find_attachment_reference(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
return await self.uow.attachments.find_attachment_reference(
|
||||
attachment_id=candidate.attachment_id,
|
||||
object_key=candidate.object_key,
|
||||
)
|
||||
@@ -1239,27 +1223,25 @@ class AttachmentReconcileService:
|
||||
self,
|
||||
finding: dataclasses.ReconcileFindingDTO,
|
||||
) -> ReconcileAction | None:
|
||||
async with self.db_scope() as db_session:
|
||||
marked = await attachment_repo.mark_lost(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
marked = await self.uow.attachments.mark_lost(
|
||||
attachment_id=finding.attachment_id,
|
||||
object_key=finding.object_key,
|
||||
lost_at=utcnow(),
|
||||
)
|
||||
await db_session.commit()
|
||||
await self.uow.commit()
|
||||
return ReconcileAction.MARKED_LOST if marked else None
|
||||
|
||||
async def _clear_lost(
|
||||
self,
|
||||
finding: dataclasses.ReconcileFindingDTO,
|
||||
) -> ReconcileAction | None:
|
||||
async with self.db_scope() as db_session:
|
||||
cleared = await attachment_repo.clear_lost(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
cleared = await self.uow.attachments.clear_lost(
|
||||
attachment_id=finding.attachment_id,
|
||||
object_key=finding.object_key,
|
||||
)
|
||||
await db_session.commit()
|
||||
await self.uow.commit()
|
||||
return ReconcileAction.CLEARED_LOST if cleared else None
|
||||
|
||||
# ------------------------------------------------------------------ итог
|
||||
@@ -1349,7 +1331,7 @@ class AttachmentReconcileService:
|
||||
storage_objects=self._touched(state),
|
||||
s3_requests=MappingProxyType(s3_requests),
|
||||
read_bytes=stats.read_bytes - start.read_bytes,
|
||||
db_sessions=self._db_sessions - state.db_sessions_start,
|
||||
db_sessions=self.uow.blocks_opened - state.db_sessions_start,
|
||||
unchecked=state.unchecked,
|
||||
phase_ms=MappingProxyType(dict(state.phase_ms)),
|
||||
)
|
||||
|
||||
@@ -20,9 +20,7 @@ import time
|
||||
from collections.abc import Callable
|
||||
from datetime import timedelta
|
||||
|
||||
from src.core.repos import attachment as attachment_repo
|
||||
from src.core.repos import attachment_job as attachment_job_repo
|
||||
from src.core.services.attachment import DbScope
|
||||
from src.core.ports.uow import AbstractUnitOfWork
|
||||
from src.infra.broker import JobPublisher
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.schemas import dataclasses
|
||||
@@ -39,11 +37,15 @@ def _never() -> bool:
|
||||
|
||||
|
||||
class AttachmentRelayService:
|
||||
"""`db_scope` — короткая сессия процесса relay, `publisher` — издатель с
|
||||
"""`uow` — единица работы процесса relay, `publisher` — издатель с
|
||||
подтверждением. Состояние предела — только для записи на его смену."""
|
||||
|
||||
def __init__(self, db_scope: DbScope, publisher: JobPublisher) -> None:
|
||||
self.db_scope = db_scope
|
||||
def __init__(
|
||||
self,
|
||||
uow: AbstractUnitOfWork,
|
||||
publisher: JobPublisher,
|
||||
) -> None:
|
||||
self.uow = uow
|
||||
self.publisher = publisher
|
||||
self._backlog_full = False
|
||||
|
||||
@@ -104,20 +106,18 @@ class AttachmentRelayService:
|
||||
async def _recover_expired(self, *, limit: int) -> int:
|
||||
"""Вернуть задания с истёкшей арендой: worker потерян или заморожен, его
|
||||
прежняя попытка итог уже не зафиксирует (fencing)."""
|
||||
async with self.db_scope() as db_session:
|
||||
async with self.uow:
|
||||
now = utcnow()
|
||||
jobs = await attachment_job_repo.recover_expired_leases(
|
||||
db_session=db_session,
|
||||
jobs = await self.uow.jobs.recover_expired_leases(
|
||||
now=now,
|
||||
limit=limit,
|
||||
)
|
||||
if jobs:
|
||||
await attachment_repo.return_group_to_queued(
|
||||
db_session=db_session,
|
||||
await self.uow.attachments.return_group_to_queued(
|
||||
attachment_ids=[job.attachment_id for job in jobs],
|
||||
updated_at=now,
|
||||
)
|
||||
await db_session.commit()
|
||||
await self.uow.commit()
|
||||
for job in jobs:
|
||||
logger.warning(
|
||||
"Recovered expired lease",
|
||||
@@ -133,22 +133,20 @@ class AttachmentRelayService:
|
||||
очередь не обрастает копиями. Брокер спрашивается только при кандидатах:
|
||||
обычный проход его не трогает."""
|
||||
threshold = utcnow() - timedelta(seconds=after_seconds)
|
||||
async with self.db_scope() as db_session:
|
||||
has_old = await attachment_job_repo.has_published_before(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
has_old = await self.uow.jobs.has_published_before(
|
||||
older_than=threshold,
|
||||
)
|
||||
if not has_old:
|
||||
return 0
|
||||
if await self.publisher.ready_messages():
|
||||
return 0
|
||||
async with self.db_scope() as db_session:
|
||||
reset = await attachment_job_repo.reset_published_before(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
reset = await self.uow.jobs.reset_published_before(
|
||||
older_than=threshold,
|
||||
now=utcnow(),
|
||||
)
|
||||
await db_session.commit()
|
||||
await self.uow.commit()
|
||||
return reset
|
||||
|
||||
async def _publish(
|
||||
@@ -158,10 +156,8 @@ class AttachmentRelayService:
|
||||
max_backlog: int,
|
||||
) -> tuple[int, int, int, int]:
|
||||
"""Опубликовано, не подтверждено, опубликованных и не взятых, выбрано."""
|
||||
async with self.db_scope() as db_session:
|
||||
backlog = await attachment_job_repo.count_published(
|
||||
db_session=db_session,
|
||||
)
|
||||
async with self.uow:
|
||||
backlog = await self.uow.jobs.count_published()
|
||||
limit = batch_size
|
||||
if max_backlog > 0:
|
||||
limit = min(batch_size, max_backlog - backlog)
|
||||
@@ -172,8 +168,7 @@ class AttachmentRelayService:
|
||||
)
|
||||
if limit <= 0:
|
||||
return 0, 0, backlog, 0
|
||||
jobs = await attachment_job_repo.lock_due_jobs(
|
||||
db_session=db_session,
|
||||
jobs = await self.uow.jobs.lock_due_jobs(
|
||||
now=utcnow(),
|
||||
limit=limit,
|
||||
)
|
||||
@@ -186,12 +181,11 @@ class AttachmentRelayService:
|
||||
],
|
||||
)
|
||||
if confirmed:
|
||||
await attachment_job_repo.mark_published(
|
||||
db_session=db_session,
|
||||
await self.uow.jobs.mark_published(
|
||||
job_ids=confirmed,
|
||||
now=utcnow(),
|
||||
)
|
||||
await db_session.commit()
|
||||
await self.uow.commit()
|
||||
return (
|
||||
len(confirmed),
|
||||
len(jobs) - len(confirmed),
|
||||
|
||||
@@ -11,10 +11,7 @@
|
||||
from collections.abc import Callable, Sequence
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from src.core.repos import attachment as attachment_repo
|
||||
from src.core.repos import attachment_job as attachment_job_repo
|
||||
from src.core.repos import attachment_job_replay as attachment_job_replay_repo
|
||||
from src.core.services.attachment import DbScope
|
||||
from src.core.ports.uow import AbstractUnitOfWork
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.schemas import dataclasses
|
||||
from src.schemas.enums import AttachmentJobState, AttachmentStatus
|
||||
@@ -34,10 +31,10 @@ def _never() -> bool:
|
||||
|
||||
|
||||
class AttachmentReplayService:
|
||||
"""`db_scope` — короткая сессия процесса команды; брокер и S3 не нужны."""
|
||||
"""`uow` — единица работы процесса команды; брокер и S3 не нужны."""
|
||||
|
||||
def __init__(self, db_scope: DbScope) -> None:
|
||||
self.db_scope = db_scope
|
||||
def __init__(self, uow: AbstractUnitOfWork) -> None:
|
||||
self.uow = uow
|
||||
|
||||
async def replay_pass(
|
||||
self,
|
||||
@@ -57,9 +54,8 @@ class AttachmentReplayService:
|
||||
log = logger.bind(method="replay", apply=apply)
|
||||
ids = list(attachment_ids[:limit])
|
||||
if not ids:
|
||||
async with self.db_scope() as db_session:
|
||||
rows = await attachment_job_repo.list_failed(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
rows = await self.uow.jobs.list_failed(
|
||||
error_code=error_code,
|
||||
reason=reason,
|
||||
limit=limit,
|
||||
@@ -137,22 +133,17 @@ class AttachmentReplayService:
|
||||
"""Проверки под блокировками, с `apply` — запись одной транзакцией. Без
|
||||
`apply` транзакция откатывается: команда только называет, что сделала
|
||||
бы."""
|
||||
async with self.db_scope() as db_session:
|
||||
found = await attachment_job_repo.get_attachment_job(
|
||||
db_session=db_session,
|
||||
async with self.uow:
|
||||
found = await self.uow.jobs.get_attachment_job(
|
||||
attachment_id=attachment_id,
|
||||
pipeline_version=ATTACHMENT_PIPELINE_VERSION,
|
||||
)
|
||||
job = (
|
||||
None
|
||||
if found is None
|
||||
else await attachment_job_repo.lock_job(
|
||||
db_session=db_session,
|
||||
job_id=found.id,
|
||||
)
|
||||
else await self.uow.jobs.lock_job(job_id=found.id)
|
||||
)
|
||||
attachment = await attachment_repo.lock_attachment(
|
||||
db_session=db_session,
|
||||
attachment = await self.uow.attachments.lock_attachment(
|
||||
attachment_id=attachment_id,
|
||||
)
|
||||
refusal = self._refusal(job=job, attachment=attachment)
|
||||
@@ -169,18 +160,12 @@ class AttachmentReplayService:
|
||||
)
|
||||
if apply:
|
||||
now = utcnow()
|
||||
await attachment_repo.replay_failed(
|
||||
db_session=db_session,
|
||||
await self.uow.attachments.replay_failed(
|
||||
attachment_id=attachment_id,
|
||||
updated_at=now,
|
||||
)
|
||||
await attachment_job_repo.replay_job(
|
||||
db_session=db_session,
|
||||
job_id=job.id,
|
||||
now=now,
|
||||
)
|
||||
await attachment_job_replay_repo.insert_replay(
|
||||
db_session=db_session,
|
||||
await self.uow.jobs.replay_job(job_id=job.id, now=now)
|
||||
await self.uow.job_replays.insert_replay(
|
||||
replay=dataclasses.AttachmentJobReplayDTO(
|
||||
id=uuid4(),
|
||||
job_id=job.id,
|
||||
@@ -191,7 +176,7 @@ class AttachmentReplayService:
|
||||
created_at=now,
|
||||
),
|
||||
)
|
||||
await db_session.commit()
|
||||
await self.uow.commit()
|
||||
return dataclasses.ReplayResultDTO(
|
||||
attachment_id=attachment_id,
|
||||
job_id=job.id,
|
||||
|
||||
+65
-58
@@ -1,13 +1,10 @@
|
||||
from collections.abc import Sequence
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.config import settings
|
||||
from src.core import exceptions
|
||||
from src.core.repos import chat as chat_repo
|
||||
from src.core.ports.uow import AbstractUnitOfWork
|
||||
from src.core.repos import chat_cache as chat_cache_repo
|
||||
from src.core.repos import user as user_repo
|
||||
from src.core.services.pagination import decode_page_cursor, split_page
|
||||
from src.infra.cache import Cache
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
@@ -18,6 +15,35 @@ from src.utils.utc import utcnow
|
||||
logger: AbstractLogger = get_logger().bind(module="chat_service")
|
||||
|
||||
|
||||
async def require_member(
|
||||
uow: AbstractUnitOfWork,
|
||||
cache: Cache,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
user_id: UUID,
|
||||
) -> dataclasses.ChatFullDTO:
|
||||
"""Чат, если пользователь в нём состоит; иначе `ChatNotFound`. Требует
|
||||
открытый блок: членство нужно и внутри чужого блока (сообщение, вложение).
|
||||
|
||||
Нет чата и чужой чат неразличимы: 404 не раскрывает существование.
|
||||
Карточка — из кэша, при промахе — из БД с записью в кэш. Чат, которого
|
||||
нет, не кэшируется. При попадании в кэш соединение не выдаётся: выдача
|
||||
ленивая.
|
||||
"""
|
||||
chat = await chat_cache_repo.get_chat(cache=cache, chat_id=chat_id)
|
||||
if chat is None:
|
||||
chat = await uow.chats.get_chat(chat_id=chat_id)
|
||||
if chat is not None:
|
||||
await chat_cache_repo.put_chat(
|
||||
cache=cache,
|
||||
chat=chat,
|
||||
ttl_seconds=settings.cache.chat_ttl_seconds,
|
||||
)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
raise exceptions.ChatNotFound
|
||||
return chat
|
||||
|
||||
|
||||
class ChatService:
|
||||
"""Чаты; карточка чата кэшируется в Valkey.
|
||||
|
||||
@@ -25,8 +51,8 @@ class ChatService:
|
||||
(design change `membership-cache`, решение 2).
|
||||
"""
|
||||
|
||||
def __init__(self, db_session: AsyncSession, cache: Cache) -> None:
|
||||
self.db_session = db_session
|
||||
def __init__(self, uow: AbstractUnitOfWork, cache: Cache) -> None:
|
||||
self.uow = uow
|
||||
self.cache = cache
|
||||
|
||||
async def create_chat(
|
||||
@@ -36,8 +62,8 @@ class ChatService:
|
||||
title: str,
|
||||
member_ids: Sequence[UUID],
|
||||
) -> dataclasses.ChatFullDTO:
|
||||
"""Чат с участниками — одна транзакция: при ошибке не остаётся ни
|
||||
чата, ни части участников."""
|
||||
"""Чат с участниками — один блок: при ошибке не остаётся ни чата, ни
|
||||
части участников."""
|
||||
log = logger.bind(method="create_chat", members_count=len(member_ids))
|
||||
unique_ids = set(member_ids)
|
||||
if (
|
||||
@@ -46,30 +72,27 @@ class ChatService:
|
||||
):
|
||||
log.info("Rejected chat members: duplicates or caller missing")
|
||||
raise exceptions.InvalidChatMembers
|
||||
# пользователей не удаляют, поэтому проверка до вставки не устареет
|
||||
existing_ids = await user_repo.get_existing_user_ids(
|
||||
db_session=self.db_session,
|
||||
user_ids=unique_ids,
|
||||
)
|
||||
if existing_ids != unique_ids:
|
||||
log.info("Rejected chat members: unknown users")
|
||||
raise exceptions.InvalidChatMembers
|
||||
async with self.uow:
|
||||
# пользователей не удаляют, поэтому проверка до вставки не устареет
|
||||
existing_ids = await self.uow.users.get_existing_user_ids(
|
||||
user_ids=unique_ids,
|
||||
)
|
||||
if existing_ids != unique_ids:
|
||||
log.info("Rejected chat members: unknown users")
|
||||
raise exceptions.InvalidChatMembers
|
||||
|
||||
chat = dataclasses.ChatFullDTO(
|
||||
id=uuid4(),
|
||||
title=title,
|
||||
member_ids=tuple(member_ids),
|
||||
created_at=utcnow(),
|
||||
)
|
||||
await chat_repo.insert_chat(db_session=self.db_session, chat=chat)
|
||||
await chat_repo.insert_chat_members(
|
||||
db_session=self.db_session,
|
||||
chat=chat,
|
||||
)
|
||||
await self.db_session.commit()
|
||||
chat = dataclasses.ChatFullDTO(
|
||||
id=uuid4(),
|
||||
title=title,
|
||||
member_ids=tuple(member_ids),
|
||||
created_at=utcnow(),
|
||||
)
|
||||
await self.uow.chats.insert_chat(chat=chat)
|
||||
await self.uow.chats.insert_chat_members(chat=chat)
|
||||
await self.uow.commit()
|
||||
log.info("Created chat", chat_id=chat.id)
|
||||
# после commit: откат создания не оставит в кэше чата, которого
|
||||
# нет в БД
|
||||
# после блока: откат создания не оставит в кэше чата, которого нет
|
||||
# в БД
|
||||
await chat_cache_repo.put_chat(
|
||||
cache=self.cache,
|
||||
chat=chat,
|
||||
@@ -83,30 +106,14 @@ class ChatService:
|
||||
chat_id: UUID,
|
||||
user_id: UUID,
|
||||
) -> dataclasses.ChatFullDTO:
|
||||
"""Чат, если пользователь в нём состоит; иначе `ChatNotFound`.
|
||||
|
||||
Нет чата и чужой чат неразличимы: 404 не раскрывает существование.
|
||||
Карточка — из кэша, при промахе — из БД с записью в кэш. Чат,
|
||||
которого нет, не кэшируется.
|
||||
"""
|
||||
chat = await chat_cache_repo.get_chat(
|
||||
cache=self.cache,
|
||||
chat_id=chat_id,
|
||||
)
|
||||
if chat is None:
|
||||
chat = await chat_repo.get_chat(
|
||||
db_session=self.db_session,
|
||||
"""Чат для участника; см. `require_member`."""
|
||||
async with self.uow:
|
||||
return await require_member(
|
||||
self.uow,
|
||||
self.cache,
|
||||
chat_id=chat_id,
|
||||
user_id=user_id,
|
||||
)
|
||||
if chat is not None:
|
||||
await chat_cache_repo.put_chat(
|
||||
cache=self.cache,
|
||||
chat=chat,
|
||||
ttl_seconds=settings.cache.chat_ttl_seconds,
|
||||
)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
raise exceptions.ChatNotFound
|
||||
return chat
|
||||
|
||||
async def list_user_chats(
|
||||
self,
|
||||
@@ -117,11 +124,11 @@ class ChatService:
|
||||
) -> dataclasses.ChatPageDTO:
|
||||
scope = user_chats_scope(user_id)
|
||||
after = decode_page_cursor(cursor, scope=scope)
|
||||
rows = await chat_repo.get_user_chats_page(
|
||||
db_session=self.db_session,
|
||||
user_id=user_id,
|
||||
after=after,
|
||||
limit=limit,
|
||||
)
|
||||
async with self.uow:
|
||||
rows = await self.uow.chats.get_user_chats_page(
|
||||
user_id=user_id,
|
||||
after=after,
|
||||
limit=limit,
|
||||
)
|
||||
items, next_cursor = split_page(rows, limit=limit, scope=scope)
|
||||
return dataclasses.ChatPageDTO(items=items, next_cursor=next_cursor)
|
||||
|
||||
@@ -4,14 +4,10 @@ from collections.abc import Sequence
|
||||
from datetime import timedelta
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.config import settings
|
||||
from src.core import exceptions
|
||||
from src.core.repos import attachment as attachment_repo
|
||||
from src.core.repos import idempotency as idempotency_repo
|
||||
from src.core.repos import message as message_repo
|
||||
from src.core.services.chat import ChatService
|
||||
from src.core.ports.uow import AbstractUnitOfWork
|
||||
from src.core.services.chat import require_member
|
||||
from src.core.services.pagination import decode_page_cursor, split_page
|
||||
from src.infra.cache import Cache
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
@@ -53,13 +49,10 @@ def message_request_hash(
|
||||
class MessageService:
|
||||
"""Сообщения; история не кэшируется, членство — по карточке чата."""
|
||||
|
||||
def __init__(self, db_session: AsyncSession, cache: Cache) -> None:
|
||||
self.db_session = db_session
|
||||
def __init__(self, uow: AbstractUnitOfWork, cache: Cache) -> None:
|
||||
self.uow = uow
|
||||
self.cache = cache
|
||||
|
||||
def _chats(self) -> ChatService:
|
||||
return ChatService(db_session=self.db_session, cache=self.cache)
|
||||
|
||||
async def send_message(
|
||||
self,
|
||||
*,
|
||||
@@ -87,79 +80,78 @@ class MessageService:
|
||||
chat_id=chat_id,
|
||||
attachments_count=len(attachment_ids),
|
||||
)
|
||||
# состав чата не меняется, поэтому проверка членства (в том числе
|
||||
# по кэшу) не устареет; составные внешние ключи сообщения и ключа
|
||||
# идемпотентности — страховка на уровне БД. Повтор проходит её
|
||||
# заново, как и проверку сессии в зависимости
|
||||
await self._chats().get_chat_for_member(
|
||||
chat_id=chat_id,
|
||||
user_id=sender_id,
|
||||
)
|
||||
has_failed = False
|
||||
if attachment_ids:
|
||||
has_failed = await self._check_attachments(
|
||||
async with self.uow:
|
||||
# состав чата не меняется, поэтому проверка членства (в том числе
|
||||
# по кэшу) не устареет; составные внешние ключи сообщения и ключа
|
||||
# идемпотентности — страховка на уровне БД. Повтор проходит её
|
||||
# заново, как и проверку сессии в зависимости
|
||||
await require_member(
|
||||
self.uow,
|
||||
self.cache,
|
||||
chat_id=chat_id,
|
||||
attachment_ids=attachment_ids,
|
||||
log=log,
|
||||
)
|
||||
now = utcnow()
|
||||
request_hash = message_request_hash(
|
||||
text=text,
|
||||
attachment_ids=attachment_ids,
|
||||
)
|
||||
message = dataclasses.MessageFullDTO(
|
||||
id=uuid4(),
|
||||
chat_id=chat_id,
|
||||
sender_id=sender_id,
|
||||
text=text,
|
||||
created_at=now,
|
||||
attachment_ids=tuple(attachment_ids),
|
||||
)
|
||||
claimed = await idempotency_repo.claim_key(
|
||||
db_session=self.db_session,
|
||||
user_id=sender_id,
|
||||
chat_id=chat_id,
|
||||
key=idempotency_key,
|
||||
request_hash=request_hash,
|
||||
message_id=message.id,
|
||||
created_at=now,
|
||||
expired_before=now
|
||||
- timedelta(seconds=settings.idempotency.ttl_seconds),
|
||||
)
|
||||
if claimed and has_failed:
|
||||
await self.db_session.rollback()
|
||||
log.info("Rejected message attachments", reason="failed")
|
||||
raise exceptions.AttachmentFailed
|
||||
if claimed:
|
||||
await message_repo.insert_message(
|
||||
db_session=self.db_session,
|
||||
message=message,
|
||||
instance_id=settings.app.instance_id,
|
||||
user_id=sender_id,
|
||||
)
|
||||
has_failed = False
|
||||
if attachment_ids:
|
||||
await message_repo.insert_message_attachments(
|
||||
db_session=self.db_session,
|
||||
message=message,
|
||||
has_failed = await self._check_attachments(
|
||||
chat_id=chat_id,
|
||||
attachment_ids=attachment_ids,
|
||||
log=log,
|
||||
)
|
||||
# отложенная проверка ссылки ключа на сообщение — здесь
|
||||
await self.db_session.commit()
|
||||
log.info(
|
||||
"Created message",
|
||||
message_id=message.id,
|
||||
text_length=len(text),
|
||||
replayed=False,
|
||||
now = utcnow()
|
||||
request_hash = message_request_hash(
|
||||
text=text,
|
||||
attachment_ids=attachment_ids,
|
||||
)
|
||||
return message
|
||||
message = dataclasses.MessageFullDTO(
|
||||
id=uuid4(),
|
||||
chat_id=chat_id,
|
||||
sender_id=sender_id,
|
||||
text=text,
|
||||
created_at=now,
|
||||
attachment_ids=tuple(attachment_ids),
|
||||
)
|
||||
claimed = await self.uow.idempotency.claim_key(
|
||||
user_id=sender_id,
|
||||
chat_id=chat_id,
|
||||
key=idempotency_key,
|
||||
request_hash=request_hash,
|
||||
message_id=message.id,
|
||||
created_at=now,
|
||||
expired_before=now
|
||||
- timedelta(seconds=settings.idempotency.ttl_seconds),
|
||||
)
|
||||
if claimed and has_failed:
|
||||
# исключение внутри блока: новый ключ откатывается при выходе
|
||||
log.info("Rejected message attachments", reason="failed")
|
||||
raise exceptions.AttachmentFailed
|
||||
if claimed:
|
||||
await self.uow.messages.insert_message(
|
||||
message=message,
|
||||
instance_id=settings.app.instance_id,
|
||||
)
|
||||
if attachment_ids:
|
||||
await self.uow.messages.insert_message_attachments(
|
||||
message=message,
|
||||
)
|
||||
# отложенная проверка ссылки ключа на сообщение — здесь
|
||||
await self.uow.commit()
|
||||
log.info(
|
||||
"Created message",
|
||||
message_id=message.id,
|
||||
text_length=len(text),
|
||||
replayed=False,
|
||||
)
|
||||
return message
|
||||
|
||||
saved = await idempotency_repo.get_key_result(
|
||||
db_session=self.db_session,
|
||||
user_id=sender_id,
|
||||
chat_id=chat_id,
|
||||
key=idempotency_key,
|
||||
)
|
||||
# снять блокировку строки ключа до ответа: её ждут повторы того же
|
||||
# ключа, в том числе на других репликах
|
||||
await self.db_session.commit()
|
||||
saved = await self.uow.idempotency.get_key_result(
|
||||
user_id=sender_id,
|
||||
chat_id=chat_id,
|
||||
key=idempotency_key,
|
||||
)
|
||||
# снять блокировку строки ключа до ответа: её ждут повторы того же
|
||||
# ключа, в том числе на других репликах
|
||||
await self.uow.commit()
|
||||
if saved is None:
|
||||
# строку нашёл и заблокировал захват: пропасть она не могла
|
||||
raise RuntimeError("Idempotency key disappeared after claim")
|
||||
@@ -188,8 +180,7 @@ class MessageService:
|
||||
него — тот же итог, что и `failed` чуть позже отправки. Существование
|
||||
держит ещё и внешний ключ связи.
|
||||
"""
|
||||
found = await attachment_repo.get_attachments(
|
||||
db_session=self.db_session,
|
||||
found = await self.uow.attachments.get_attachments(
|
||||
attachment_ids=attachment_ids,
|
||||
)
|
||||
accepted = {
|
||||
@@ -211,17 +202,19 @@ class MessageService:
|
||||
limit: int,
|
||||
cursor: str | None,
|
||||
) -> dataclasses.MessagePageDTO:
|
||||
await self._chats().get_chat_for_member(
|
||||
chat_id=chat_id,
|
||||
user_id=user_id,
|
||||
)
|
||||
scope = chat_messages_scope(chat_id)
|
||||
after = decode_page_cursor(cursor, scope=scope)
|
||||
rows = await message_repo.get_chat_messages_page(
|
||||
db_session=self.db_session,
|
||||
chat_id=chat_id,
|
||||
after=after,
|
||||
limit=limit,
|
||||
)
|
||||
async with self.uow:
|
||||
await require_member(
|
||||
self.uow,
|
||||
self.cache,
|
||||
chat_id=chat_id,
|
||||
user_id=user_id,
|
||||
)
|
||||
after = decode_page_cursor(cursor, scope=scope)
|
||||
rows = await self.uow.messages.get_chat_messages_page(
|
||||
chat_id=chat_id,
|
||||
after=after,
|
||||
limit=limit,
|
||||
)
|
||||
items, next_cursor = split_page(rows, limit=limit, scope=scope)
|
||||
return dataclasses.MessagePageDTO(items=items, next_cursor=next_cursor)
|
||||
|
||||
@@ -3,12 +3,9 @@ import secrets
|
||||
from datetime import timedelta
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.config import settings
|
||||
from src.core import exceptions
|
||||
from src.core.repos import session as session_repo
|
||||
from src.core.repos import user as user_repo
|
||||
from src.core.ports.uow import AbstractUnitOfWork
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.infra.password import verify_password
|
||||
from src.schemas import dataclasses
|
||||
@@ -28,8 +25,8 @@ def hash_token(token: str) -> bytes:
|
||||
|
||||
|
||||
class SessionService:
|
||||
def __init__(self, db_session: AsyncSession) -> None:
|
||||
self.db_session = db_session
|
||||
def __init__(self, uow: AbstractUnitOfWork) -> None:
|
||||
self.uow = uow
|
||||
|
||||
async def login(
|
||||
self,
|
||||
@@ -39,17 +36,16 @@ class SessionService:
|
||||
) -> dataclasses.SessionTokenDTO:
|
||||
"""Вход: проверка пароля и новая сессия.
|
||||
|
||||
Две транзакции: чтение хэша закрывается до KDF, чтобы соединение
|
||||
пула не ждало хэш и очередь лимита (design change `session-auth`,
|
||||
Два блока: чтение хэша заканчивается до KDF, чтобы соединение пула
|
||||
не ждало хэш и очередь лимита (design change `session-auth`,
|
||||
решение 3). Пароли и пользователи не меняются, поэтому между
|
||||
транзакциями проверять нечего.
|
||||
блоками проверять нечего.
|
||||
"""
|
||||
log = logger.bind(method="login")
|
||||
credentials = await user_repo.get_user_credentials(
|
||||
db_session=self.db_session,
|
||||
username=username,
|
||||
)
|
||||
await self.db_session.commit()
|
||||
async with self.uow:
|
||||
credentials = await self.uow.users.get_user_credentials(
|
||||
username=username,
|
||||
)
|
||||
# неизвестный username проверяется против фиктивного хэша: время
|
||||
# ответа то же, что у неверного пароля
|
||||
valid = await verify_password(
|
||||
@@ -63,18 +59,18 @@ class SessionService:
|
||||
|
||||
token = secrets.token_urlsafe(SESSION_TOKEN_BYTES)
|
||||
now = utcnow()
|
||||
session = await session_repo.insert_session(
|
||||
db_session=self.db_session,
|
||||
session=dataclasses.SessionFullDTO(
|
||||
id=uuid4(),
|
||||
user_id=credentials.user.id,
|
||||
token_hash=hash_token(token),
|
||||
expires_at=now
|
||||
+ timedelta(seconds=settings.auth.session_ttl_seconds),
|
||||
created_at=now,
|
||||
),
|
||||
)
|
||||
await self.db_session.commit()
|
||||
async with self.uow:
|
||||
session = await self.uow.sessions.insert_session(
|
||||
session=dataclasses.SessionFullDTO(
|
||||
id=uuid4(),
|
||||
user_id=credentials.user.id,
|
||||
token_hash=hash_token(token),
|
||||
expires_at=now
|
||||
+ timedelta(seconds=settings.auth.session_ttl_seconds),
|
||||
created_at=now,
|
||||
),
|
||||
)
|
||||
await self.uow.commit()
|
||||
log.info(
|
||||
"Created session",
|
||||
user_id=session.user_id,
|
||||
@@ -94,27 +90,26 @@ class SessionService:
|
||||
) -> dataclasses.CurrentSessionDTO:
|
||||
"""Действующая сессия по Bearer-токену; иначе `Unauthenticated`.
|
||||
|
||||
Ошибка БД сюда не превращается: её переводит в 503
|
||||
`get_db_session`, недоступность хранилища не делает токен
|
||||
недействительным.
|
||||
Ошибка БД сюда не превращается: её переводит в 503 единица работы,
|
||||
недоступность хранилища не делает токен недействительным.
|
||||
"""
|
||||
if not token:
|
||||
raise exceptions.Unauthenticated
|
||||
current = await session_repo.get_current_session(
|
||||
db_session=self.db_session,
|
||||
token_hash=hash_token(token),
|
||||
now=utcnow(),
|
||||
)
|
||||
async with self.uow:
|
||||
current = await self.uow.sessions.get_current_session(
|
||||
token_hash=hash_token(token),
|
||||
now=utcnow(),
|
||||
)
|
||||
if current is None:
|
||||
raise exceptions.Unauthenticated
|
||||
return current
|
||||
|
||||
async def revoke(self, *, session_id: UUID) -> None:
|
||||
log = logger.bind(method="revoke", session_id=session_id)
|
||||
deleted = await session_repo.delete_session(
|
||||
db_session=self.db_session,
|
||||
session_id=session_id,
|
||||
)
|
||||
await self.db_session.commit()
|
||||
async with self.uow:
|
||||
deleted = await self.uow.sessions.delete_session(
|
||||
session_id=session_id,
|
||||
)
|
||||
await self.uow.commit()
|
||||
# False — параллельный выход тем же токеном уже удалил сессию
|
||||
log.info("Revoked session", already_revoked=not deleted)
|
||||
|
||||
+15
-17
@@ -1,9 +1,7 @@
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.core import exceptions
|
||||
from src.core.repos import user as user_repo
|
||||
from src.core.ports.uow import AbstractUnitOfWork
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.infra.password import hash_password
|
||||
from src.schemas import dataclasses
|
||||
@@ -13,8 +11,8 @@ logger: AbstractLogger = get_logger().bind(module="user_service")
|
||||
|
||||
|
||||
class UserService:
|
||||
def __init__(self, db_session: AsyncSession) -> None:
|
||||
self.db_session = db_session
|
||||
def __init__(self, uow: AbstractUnitOfWork) -> None:
|
||||
self.uow = uow
|
||||
|
||||
async def register(
|
||||
self,
|
||||
@@ -24,7 +22,7 @@ class UserService:
|
||||
password: str,
|
||||
) -> dataclasses.UserFullDTO:
|
||||
log = logger.bind(method="register")
|
||||
# KDF до обращения к БД: соединение пула не ждёт хэш
|
||||
# KDF до блока: соединение пула не ждёт хэш
|
||||
password_hash = await hash_password(password)
|
||||
user = dataclasses.UserFullDTO(
|
||||
id=uuid4(),
|
||||
@@ -32,16 +30,16 @@ class UserService:
|
||||
display_name=display_name,
|
||||
created_at=utcnow(),
|
||||
)
|
||||
# уникальность держит ограничение БД: гонка регистрации одного
|
||||
# username даёт ровно одну строку, остальным — None
|
||||
created = await user_repo.insert_user(
|
||||
db_session=self.db_session,
|
||||
user=user,
|
||||
password_hash=password_hash,
|
||||
)
|
||||
if created is None:
|
||||
log.info("Username is already taken")
|
||||
raise exceptions.UsernameTaken
|
||||
await self.db_session.commit()
|
||||
async with self.uow:
|
||||
# уникальность держит ограничение БД: гонка регистрации одного
|
||||
# username даёт ровно одну строку, остальным — None
|
||||
created = await self.uow.users.insert_user(
|
||||
user=user,
|
||||
password_hash=password_hash,
|
||||
)
|
||||
if created is None:
|
||||
log.info("Username is already taken")
|
||||
raise exceptions.UsernameTaken
|
||||
await self.uow.commit()
|
||||
log.info("Created user", created_user_id=created.id)
|
||||
return created
|
||||
|
||||
+26
-4
@@ -5,6 +5,7 @@
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from typing import Any
|
||||
|
||||
import asyncpg
|
||||
from sqlalchemy import text
|
||||
@@ -14,6 +15,7 @@ from sqlalchemy.ext.asyncio import (
|
||||
async_sessionmaker,
|
||||
create_async_engine,
|
||||
)
|
||||
from sqlalchemy.util import await_
|
||||
|
||||
from src.config.settings import Database
|
||||
from src.utils.constants import DB_APPLICATION_NAME, DB_CLOSE_TIMEOUT_SECONDS
|
||||
@@ -35,6 +37,24 @@ class BoundedCloseConnection(asyncpg.Connection):
|
||||
await asyncio.wait_for(super().close(timeout=timeout), limit)
|
||||
|
||||
|
||||
def _ping_once(dbapi_connection: Any) -> bool:
|
||||
"""Проверка соединения при выдаче одним обменом `;`.
|
||||
|
||||
Проверка диалекта asyncpg — три обмена (`BEGIN`, `;`, `ROLLBACK`):
|
||||
транзакция там ради pgbouncer в режиме транзакций, которого на стенде нет.
|
||||
Соединение на шаг выдаётся двухшаговой ручке дважды, и именно проверка делает
|
||||
вторую выдачу дорогой (design change `unit-of-work`, решение 7). Разбор обрыва
|
||||
прежний: `_do_ping_w_event` получает ту же ошибку адаптера. Опирается на
|
||||
внутренние имена адаптера, SQLAlchemy закреплён `<2.2`; смену имён ловит
|
||||
`make service_test_db` (`test_ping_*`).
|
||||
"""
|
||||
try:
|
||||
await_(dbapi_connection._connection.fetchrow(";"))
|
||||
except Exception as error:
|
||||
dbapi_connection._handle_exception(error)
|
||||
return True
|
||||
|
||||
|
||||
def create_engine(database: Database) -> AsyncEngine:
|
||||
"""Engine с ограниченным пулом и таймаутами из `[database]`."""
|
||||
server_settings = {
|
||||
@@ -48,7 +68,7 @@ def create_engine(database: Database) -> AsyncEngine:
|
||||
server_settings["idle_in_transaction_session_timeout"] = str(
|
||||
database.idle_in_transaction_timeout_ms,
|
||||
)
|
||||
return create_async_engine(
|
||||
engine = create_async_engine(
|
||||
database.url,
|
||||
pool_size=database.pool_size,
|
||||
max_overflow=database.max_overflow,
|
||||
@@ -56,19 +76,21 @@ def create_engine(database: Database) -> AsyncEngine:
|
||||
# после рестарта Postgres соединения пула мертвы: проверка при
|
||||
# выдаче не даёт первому запросу получить ошибку
|
||||
pool_pre_ping=True,
|
||||
# str() ошибки драйвера уходит в журнал (get_db_session, traceback
|
||||
# str() ошибки драйвера уходит в журнал (session_scope, traceback
|
||||
# 500): без этого в нём были бы параметры SQL — текст сообщений,
|
||||
# с session-auth хэши паролей и токенов (logging.md)
|
||||
hide_parameters=True,
|
||||
# command_timeout asyncpg не задан: зависший сервер он не
|
||||
# ограничивает (см. BoundedCloseConnection). Срок всей работы
|
||||
# запроса с БД ставит asyncio в get_db_session
|
||||
# ограничивает (см. BoundedCloseConnection). Срок блока ставит
|
||||
# asyncio в session_scope
|
||||
connect_args={
|
||||
"timeout": database.connect_timeout_seconds,
|
||||
"connection_class": BoundedCloseConnection,
|
||||
"server_settings": server_settings,
|
||||
},
|
||||
)
|
||||
engine.dialect.do_ping = _ping_once
|
||||
return engine
|
||||
|
||||
|
||||
def create_session_factory(
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
- Postgres остановлен — `ConnectionRefusedError`, его SQLAlchemy не
|
||||
оборачивает; сервер не отвечает на подключение — `TimeoutError`; оба —
|
||||
`OSError`, как и срок запроса из `get_db_session`;
|
||||
`OSError`, как и срок блока из `session_scope`;
|
||||
- пул исчерпан — `sqlalchemy.exc.TimeoutError`;
|
||||
- сработал `statement_timeout` — `DBAPIError` с SQLSTATE `57014`;
|
||||
- соединение оборвано (рестарт, `pg_terminate_backend`) — `DBAPIError`
|
||||
|
||||
+50
-16
@@ -1,8 +1,9 @@
|
||||
"""Короткая сессия БД на один шаг: срок и перевод отказа PostgreSQL в 503.
|
||||
"""Срок и перевод отказа PostgreSQL в 503: блок единицы работы и общий срок
|
||||
JSON-запроса (design change `unit-of-work`, решения 4 и 6).
|
||||
|
||||
Общая для процесса API (`db_session_scope` и `get_db_session` в
|
||||
`src/api/dependencies.py`) и уборщика (`src/cleaner/main.py`): у каждого
|
||||
своя фабрика сессий (design change `upload-consistency`, решение 7).
|
||||
`session_scope` — сессия на один блок, им пользуется только
|
||||
`SqlAlchemyUnitOfWork` (`src/infra/db/uow.py`). `deadline_scope` — срок без
|
||||
сессии вокруг всего запроса, зависимость `request_deadline` роутеров JSON.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
@@ -24,25 +25,58 @@ async def session_scope(
|
||||
*,
|
||||
timeout_seconds: float,
|
||||
) -> AsyncIterator[AsyncSession]:
|
||||
"""Сессия БД на один шаг; commit делает сервис.
|
||||
"""Сессия БД на один блок; фиксирует вызывающий.
|
||||
|
||||
Незакоммиченное при выходе откатывается. Работа с БД внутри
|
||||
ограничена `timeout_seconds`: зависший Postgres не держит шаг
|
||||
бесконечно. Недоступность БД (`is_db_unavailable`) — `warning` и
|
||||
`ServiceUnavailable` (503), а соединение не возвращается в пул: его
|
||||
состояние неизвестно, а откат на зависшем сервере повис бы.
|
||||
Блок, включая откат при выходе, ограничен `timeout_seconds`: блок теперь
|
||||
заканчивается до ответа, и зависший PostgreSQL иначе повесил бы уже готовый
|
||||
ответ. Незафиксированное откатывается и при выходе без фиксации, и при
|
||||
исключении, не связанном с отказом БД; после фиксации откат — без обмена с
|
||||
сервером. Отказ БД (`is_db_unavailable`) — `warning` и `ServiceUnavailable`
|
||||
(503), а соединение не возвращается в пул: его состояние неизвестно, а откат
|
||||
на зависшем сервере повис бы. По той же причине отмена задачи (остановка
|
||||
процесса, общий срок запроса) сбрасывает соединение: `close()` сессии послал
|
||||
бы ROLLBACK.
|
||||
"""
|
||||
async with session_factory() as db_session:
|
||||
try:
|
||||
async with asyncio.timeout(timeout_seconds):
|
||||
yield db_session
|
||||
try:
|
||||
yield db_session
|
||||
except Exception as e:
|
||||
if not is_db_unavailable(e):
|
||||
await db_session.rollback()
|
||||
raise
|
||||
else:
|
||||
await db_session.rollback()
|
||||
except asyncio.CancelledError:
|
||||
await db_session.invalidate()
|
||||
raise
|
||||
except Exception as e:
|
||||
if not is_db_unavailable(e):
|
||||
raise
|
||||
await db_session.invalidate()
|
||||
logger.warning(
|
||||
"Database is unavailable",
|
||||
error_type=type(e).__name__,
|
||||
error=str(e),
|
||||
)
|
||||
_log_unavailable(e)
|
||||
raise ServiceUnavailable from e
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def deadline_scope(*, timeout_seconds: float) -> AsyncIterator[None]:
|
||||
"""Общий срок запроса без сессии: все блоки и очередь хэшей вместе.
|
||||
|
||||
Истечение отменяет задачу: открытый блок сбрасывает своё соединение
|
||||
(`session_scope`), а здесь — та же запись и тот же отказ, что у срока блока.
|
||||
"""
|
||||
try:
|
||||
async with asyncio.timeout(timeout_seconds):
|
||||
yield
|
||||
except TimeoutError as e:
|
||||
_log_unavailable(e)
|
||||
raise ServiceUnavailable from e
|
||||
|
||||
|
||||
def _log_unavailable(error: Exception) -> None:
|
||||
logger.warning(
|
||||
"Database is unavailable",
|
||||
error_type=type(error).__name__,
|
||||
error=str(error),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Единица работы на SQLAlchemy (design change `unit-of-work`, решения 1–4).
|
||||
|
||||
Блок — `session_scope`: срок, откат незафиксированного и перевод отказа
|
||||
PostgreSQL в доменный. Repo создаются на блок поверх его сессии. Соединение пул
|
||||
выдаёт лениво, при первом выражении: блок без обращения к PostgreSQL его не
|
||||
занимает. Импортируют модуль только точки входа процессов;
|
||||
`src/infra/db/__init__.py` его не импортирует: логгер `session_scope` не должен
|
||||
настраиваться в alembic.
|
||||
"""
|
||||
|
||||
from contextlib import AbstractAsyncContextManager
|
||||
from types import TracebackType
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from src.core.ports.uow import AbstractUnitOfWork, Repositories
|
||||
from src.core.repos.attachment import SqlAlchemyAttachmentRepository
|
||||
from src.core.repos.attachment_job import SqlAlchemyAttachmentJobRepository
|
||||
from src.core.repos.attachment_job_replay import (
|
||||
SqlAlchemyAttachmentJobReplayRepository,
|
||||
)
|
||||
from src.core.repos.attachment_variant import (
|
||||
SqlAlchemyAttachmentVariantRepository,
|
||||
)
|
||||
from src.core.repos.chat import SqlAlchemyChatRepository
|
||||
from src.core.repos.idempotency import SqlAlchemyIdempotencyRepository
|
||||
from src.core.repos.message import SqlAlchemyMessageRepository
|
||||
from src.core.repos.session import SqlAlchemySessionRepository
|
||||
from src.core.repos.user import SqlAlchemyUserRepository
|
||||
from src.infra.db.scope import session_scope
|
||||
|
||||
|
||||
class SqlAlchemyUnitOfWork(AbstractUnitOfWork):
|
||||
"""`timeout_seconds` — срок блока, `[database] request_timeout_seconds`."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
session_factory: async_sessionmaker[AsyncSession],
|
||||
*,
|
||||
timeout_seconds: float,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self._session_factory = session_factory
|
||||
self._timeout_seconds = timeout_seconds
|
||||
self._scope: AbstractAsyncContextManager[AsyncSession] | None = None
|
||||
self._session: AsyncSession | None = None
|
||||
|
||||
async def _open(self) -> Repositories:
|
||||
self._scope = session_scope(
|
||||
self._session_factory,
|
||||
timeout_seconds=self._timeout_seconds,
|
||||
)
|
||||
session = await self._scope.__aenter__()
|
||||
self._session = session
|
||||
return Repositories(
|
||||
users=SqlAlchemyUserRepository(session),
|
||||
sessions=SqlAlchemySessionRepository(session),
|
||||
chats=SqlAlchemyChatRepository(session),
|
||||
messages=SqlAlchemyMessageRepository(session),
|
||||
idempotency=SqlAlchemyIdempotencyRepository(session),
|
||||
attachments=SqlAlchemyAttachmentRepository(session),
|
||||
jobs=SqlAlchemyAttachmentJobRepository(session),
|
||||
variants=SqlAlchemyAttachmentVariantRepository(session),
|
||||
job_replays=SqlAlchemyAttachmentJobReplayRepository(session),
|
||||
)
|
||||
|
||||
async def _close(
|
||||
self,
|
||||
exc_type: type[BaseException] | None,
|
||||
exc: BaseException | None,
|
||||
tb: TracebackType | None,
|
||||
) -> bool | None:
|
||||
scope, self._scope, self._session = self._scope, None, None
|
||||
if scope is None:
|
||||
return None
|
||||
return await scope.__aexit__(exc_type, exc, tb)
|
||||
|
||||
async def _commit(self) -> None:
|
||||
await self._current_session().commit()
|
||||
|
||||
async def _rollback(self) -> None:
|
||||
await self._current_session().rollback()
|
||||
|
||||
def _current_session(self) -> AsyncSession:
|
||||
if self._session is None:
|
||||
raise RuntimeError("Unit of work block has no session")
|
||||
return self._session
|
||||
+13
-18
@@ -21,11 +21,9 @@ SIGTERM: текущий шаг доводится до фиксации или
|
||||
import argparse
|
||||
import asyncio
|
||||
import signal
|
||||
from contextlib import AbstractAsyncContextManager, suppress
|
||||
from contextlib import suppress
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.config import settings
|
||||
from src.core import exceptions
|
||||
from src.core.services.attachment_relay import AttachmentRelayService
|
||||
@@ -33,7 +31,7 @@ from src.core.services.attachment_replay import AttachmentReplayService
|
||||
from src.infra import early_stop
|
||||
from src.infra.broker import JobPublisher
|
||||
from src.infra.db import create_engine, create_session_factory
|
||||
from src.infra.db.scope import session_scope
|
||||
from src.infra.db.uow import SqlAlchemyUnitOfWork
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.schemas.enums import AttachmentErrorCode, AttachmentJobReason
|
||||
|
||||
@@ -149,14 +147,13 @@ async def run() -> int:
|
||||
engine = create_engine(settings.database)
|
||||
session_factory = create_session_factory(engine)
|
||||
publisher = JobPublisher(settings.broker, namespace=namespace)
|
||||
|
||||
def db_scope() -> AbstractAsyncContextManager[AsyncSession]:
|
||||
return session_scope(
|
||||
service = AttachmentRelayService(
|
||||
uow=SqlAlchemyUnitOfWork(
|
||||
session_factory,
|
||||
timeout_seconds=settings.database.request_timeout_seconds,
|
||||
)
|
||||
|
||||
service = AttachmentRelayService(db_scope=db_scope, publisher=publisher)
|
||||
),
|
||||
publisher=publisher,
|
||||
)
|
||||
try:
|
||||
logger.info(
|
||||
"Started relay",
|
||||
@@ -206,7 +203,7 @@ async def _serve(
|
||||
stop_requested=stop.is_set,
|
||||
)
|
||||
except exceptions.ServiceUnavailable:
|
||||
# причину уже записали session_scope и издатель
|
||||
# причину уже записали единица работы и издатель
|
||||
logger.warning("Relay pass was interrupted")
|
||||
pause = relay.failure_pause_seconds
|
||||
except Exception as e:
|
||||
@@ -228,14 +225,12 @@ async def run_replay(args: argparse.Namespace) -> int:
|
||||
stop = _install_stop()
|
||||
engine = create_engine(settings.database)
|
||||
session_factory = create_session_factory(engine)
|
||||
|
||||
def db_scope() -> AbstractAsyncContextManager[AsyncSession]:
|
||||
return session_scope(
|
||||
service = AttachmentReplayService(
|
||||
uow=SqlAlchemyUnitOfWork(
|
||||
session_factory,
|
||||
timeout_seconds=settings.database.request_timeout_seconds,
|
||||
)
|
||||
|
||||
service = AttachmentReplayService(db_scope=db_scope)
|
||||
),
|
||||
)
|
||||
exit_code = EXIT_OK
|
||||
try:
|
||||
result = await service.replay_pass(
|
||||
@@ -252,7 +247,7 @@ async def run_replay(args: argparse.Namespace) -> int:
|
||||
elif result.refused:
|
||||
exit_code = EXIT_REFUSED
|
||||
except exceptions.ServiceUnavailable:
|
||||
# причину уже записал session_scope
|
||||
# причину уже записала единица работы
|
||||
logger.warning("Replay pass was interrupted")
|
||||
exit_code = EXIT_FAILED
|
||||
finally:
|
||||
|
||||
+33
-24
@@ -25,9 +25,8 @@ SIGTERM: новые сообщения не принимаются, начаты
|
||||
|
||||
import asyncio
|
||||
import signal
|
||||
from contextlib import AbstractAsyncContextManager, suppress
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from collections.abc import Callable
|
||||
from contextlib import suppress
|
||||
|
||||
from src.config import settings
|
||||
from src.core.services.attachment_processing import (
|
||||
@@ -36,7 +35,7 @@ from src.core.services.attachment_processing import (
|
||||
from src.infra import early_stop
|
||||
from src.infra.broker import JobConsumer, JobDelivery, queue_name
|
||||
from src.infra.db import create_engine, create_session_factory
|
||||
from src.infra.db.scope import session_scope
|
||||
from src.infra.db.uow import SqlAlchemyUnitOfWork
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.infra.render import ImageRenderer
|
||||
from src.infra.s3 import create_object_storage
|
||||
@@ -68,18 +67,21 @@ async def run() -> int:
|
||||
session_factory = create_session_factory(engine)
|
||||
storage = create_object_storage(settings.s3, namespace=namespace)
|
||||
|
||||
def db_scope() -> AbstractAsyncContextManager[AsyncSession]:
|
||||
return session_scope(
|
||||
session_factory,
|
||||
timeout_seconds=settings.database.request_timeout_seconds,
|
||||
renderer = ImageRenderer(worker)
|
||||
|
||||
def make_service() -> AttachmentProcessingService:
|
||||
# единица работы держит открытую сессию, а доставки идут одновременно:
|
||||
# сервис на доставку (design change unit-of-work, решение 3)
|
||||
return AttachmentProcessingService(
|
||||
uow=SqlAlchemyUnitOfWork(
|
||||
session_factory,
|
||||
timeout_seconds=settings.database.request_timeout_seconds,
|
||||
),
|
||||
storage=storage,
|
||||
renderer=renderer,
|
||||
stop=stop,
|
||||
)
|
||||
|
||||
service = AttachmentProcessingService(
|
||||
db_scope=db_scope,
|
||||
storage=storage,
|
||||
renderer=ImageRenderer(worker),
|
||||
stop=stop,
|
||||
)
|
||||
try:
|
||||
if not (
|
||||
settings.s3.access_key_id.get_secret_value()
|
||||
@@ -113,7 +115,7 @@ async def run() -> int:
|
||||
database_name=namespace,
|
||||
database_pool_size=settings.database.pool_size,
|
||||
)
|
||||
await _serve(service, namespace=namespace, stop=stop)
|
||||
await _serve(make_service, namespace=namespace, stop=stop)
|
||||
finally:
|
||||
# одним сроком, а не по очереди: сумма не растёт с числом клиентов (S5)
|
||||
with suppress(Exception):
|
||||
@@ -128,7 +130,7 @@ async def run() -> int:
|
||||
|
||||
|
||||
async def _serve(
|
||||
service: AttachmentProcessingService,
|
||||
make_service: Callable[[], AttachmentProcessingService],
|
||||
*,
|
||||
namespace: str,
|
||||
stop: asyncio.Event,
|
||||
@@ -155,7 +157,9 @@ async def _serve(
|
||||
await _wait_stop(stop, timeout=worker.reconnect_seconds)
|
||||
continue
|
||||
logger.info("Connected to broker", broker_queue=consumer.queue)
|
||||
pump = asyncio.create_task(_pump(consumer, service, slots, tasks))
|
||||
pump = asyncio.create_task(
|
||||
_pump(consumer, make_service, slots, tasks, stop),
|
||||
)
|
||||
stopping = asyncio.create_task(stop.wait())
|
||||
await asyncio.wait(
|
||||
{pump, stopping},
|
||||
@@ -189,31 +193,36 @@ async def _serve(
|
||||
|
||||
async def _pump(
|
||||
consumer: JobConsumer,
|
||||
service: AttachmentProcessingService,
|
||||
make_service: Callable[[], AttachmentProcessingService],
|
||||
slots: asyncio.Semaphore,
|
||||
tasks: set[asyncio.Task[None]],
|
||||
stop: asyncio.Event,
|
||||
) -> None:
|
||||
"""Каждая доставка — своя задача со своим контекстом журнала."""
|
||||
"""Каждая доставка — своя задача со своим контекстом журнала и своим
|
||||
сервисом."""
|
||||
async for delivery in consumer.deliveries():
|
||||
task = asyncio.create_task(_handle(service, delivery, slots))
|
||||
task = asyncio.create_task(
|
||||
_handle(make_service, delivery, slots, stop),
|
||||
)
|
||||
tasks.add(task)
|
||||
task.add_done_callback(tasks.discard)
|
||||
|
||||
|
||||
async def _handle(
|
||||
service: AttachmentProcessingService,
|
||||
make_service: Callable[[], AttachmentProcessingService],
|
||||
delivery: JobDelivery,
|
||||
slots: asyncio.Semaphore,
|
||||
stop: asyncio.Event,
|
||||
) -> None:
|
||||
"""Подтверждение — только после итога сервиса. Отмена при остановке
|
||||
сообщение не подтверждает: брокер вернёт его после закрытия соединения.
|
||||
Сообщение сверх конкуренции ждёт место без взятия; после сигнала остановки
|
||||
попытка не начинается."""
|
||||
async with slots:
|
||||
if service.stop.is_set():
|
||||
if stop.is_set():
|
||||
return
|
||||
try:
|
||||
outcome = await service.handle(
|
||||
outcome = await make_service().handle(
|
||||
body=delivery.body,
|
||||
redelivered=delivery.redelivered,
|
||||
)
|
||||
@@ -221,7 +230,7 @@ async def _handle(
|
||||
logger.error("Job handling failed", exc_info=e)
|
||||
with suppress(TimeoutError):
|
||||
await asyncio.wait_for(
|
||||
service.stop.wait(),
|
||||
stop.wait(),
|
||||
timeout=settings.worker.reconnect_seconds,
|
||||
)
|
||||
outcome = JobOutcome.REQUEUE
|
||||
|
||||
Reference in New Issue
Block a user