forked from mtusi2026/mtusi2026lab5
Forward the lab 4 foundation and migrate the lab 5 pipeline to SQLAlchemy
This commit is contained in:
@@ -47,3 +47,14 @@ class CleanStaging(Command):
|
||||
class ReplayAttachment(Command):
|
||||
attachment_id: UUID
|
||||
operator: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ReconcileStorage(Command):
|
||||
apply: bool
|
||||
grace: timedelta
|
||||
skew: timedelta
|
||||
deep: bool = False
|
||||
page_size: int = 1000
|
||||
deep_concurrency: int = 8
|
||||
samples: int = 20
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from collections.abc import AsyncIterator, Sequence
|
||||
from contextlib import AbstractAsyncContextManager
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Protocol, runtime_checkable
|
||||
@@ -40,6 +41,13 @@ class StagedObject:
|
||||
key: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class StoredObject:
|
||||
key: str
|
||||
size: int
|
||||
modified: datetime
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ObjectStorage(Protocol):
|
||||
async def put(self, key: str, data: bytes, content_type: str) -> None: ...
|
||||
@@ -52,6 +60,10 @@ class ObjectStorage(Protocol):
|
||||
|
||||
async def delete(self, key: str) -> None: ...
|
||||
|
||||
def listing(self, prefix: str, page_size: int) -> AsyncIterator[Sequence[StoredObject]]: ...
|
||||
|
||||
async def stat(self, key: str) -> StoredObject | None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ImageInspector(Protocol):
|
||||
@@ -95,6 +107,14 @@ class AttachmentRepository(Protocol):
|
||||
|
||||
async def remove(self, attachment: Attachment) -> None: ...
|
||||
|
||||
async def page_after(self, key: str, limit: int) -> Sequence[Attachment]: ...
|
||||
|
||||
async def by_key(self, key: str) -> Attachment | None: ...
|
||||
|
||||
async def claim(self, attachment_id: UUID) -> Attachment | None: ...
|
||||
|
||||
async def mark(self, attachment: Attachment) -> None: ...
|
||||
|
||||
async def staged(self, limit: int, retention: timedelta) -> list[StagedObject]: ...
|
||||
|
||||
async def unstage(self, attachment_ids: Sequence[UUID]) -> None: ...
|
||||
@@ -153,3 +173,8 @@ class AttachmentDirectory(Protocol):
|
||||
async def failed_among(self, chat_id: UUID, attachment_ids: Sequence[UUID]) -> bool: ...
|
||||
|
||||
async def failed_jobs(self, limit: int) -> list[FailedJob]: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class SingleRun(Protocol):
|
||||
def hold(self) -> AbstractAsyncContextManager[bool]: ...
|
||||
|
||||
@@ -49,6 +49,9 @@ class OpenAttachment:
|
||||
if found is None:
|
||||
raise AttachmentNotFound("у вложения нет такого варианта")
|
||||
key, content_type = found.object_key, found.content_type
|
||||
if attachment.quarantine is not None:
|
||||
self._logger.warning("attachment.quarantined", attachment_id=str(attachment.id))
|
||||
raise AttachmentNotFound("вложение не найдено")
|
||||
try:
|
||||
content = await self._storage.open(str(key))
|
||||
except ObjectMissingError as error:
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
import asyncio
|
||||
from collections import Counter
|
||||
from collections.abc import AsyncIterator, Awaitable, Callable, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from hashlib import sha256
|
||||
from time import monotonic
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.attachments.application.commands import ReconcileStorage
|
||||
from messenger.attachments.application.errors import ObjectMissingError
|
||||
from messenger.attachments.application.handlers import drop
|
||||
from messenger.attachments.application.ports import (
|
||||
AttachmentsUnitOfWork,
|
||||
ObjectStorage,
|
||||
SingleRun,
|
||||
StoredObject,
|
||||
)
|
||||
from messenger.attachments.domain.models import (
|
||||
OBJECT_PREFIX,
|
||||
Attachment,
|
||||
AttachmentStatus,
|
||||
Quarantine,
|
||||
)
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.application.ports import Clock, EventPublisher, Logger
|
||||
|
||||
type UnitOfWorkFactory = Callable[[], AttachmentsUnitOfWork]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Reconciliation:
|
||||
apply: bool
|
||||
skipped: bool = False
|
||||
objects: int = 0
|
||||
rows: int = 0
|
||||
found: Counter[str] = field(default_factory=Counter)
|
||||
fixed: Counter[str] = field(default_factory=Counter)
|
||||
rechecked: Counter[str] = field(default_factory=Counter)
|
||||
requests: Counter[str] = field(default_factory=Counter)
|
||||
waited: dict[str, float] = field(default_factory=dict)
|
||||
samples: dict[str, list[str]] = field(default_factory=dict)
|
||||
hashed_bytes: int = 0
|
||||
errors: int = 0
|
||||
seconds: float = 0.0
|
||||
|
||||
|
||||
class StorageReconciler:
|
||||
__slots__ = ("_clock", "_logger", "_publisher", "_single", "_storage", "_uow")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
uow: UnitOfWorkFactory,
|
||||
storage: ObjectStorage,
|
||||
single: SingleRun,
|
||||
clock: Clock,
|
||||
*,
|
||||
logger: Logger,
|
||||
publisher: EventPublisher,
|
||||
) -> None:
|
||||
self._uow = uow
|
||||
self._storage = storage
|
||||
self._single = single
|
||||
self._clock = clock
|
||||
self._logger = logger
|
||||
self._publisher = publisher
|
||||
|
||||
async def __call__(self, command: ReconcileStorage) -> Reconciliation:
|
||||
report = Reconciliation(apply=command.apply)
|
||||
started = monotonic()
|
||||
async with self._single.hold() as held:
|
||||
report.skipped = not held
|
||||
if held:
|
||||
before = self._clock.now() - command.grace - command.skew
|
||||
await Pass(
|
||||
self._uow,
|
||||
self._storage,
|
||||
command,
|
||||
before=before,
|
||||
report=report,
|
||||
logger=self._logger,
|
||||
publisher=self._publisher,
|
||||
).run()
|
||||
report.seconds = round(monotonic() - started, 3)
|
||||
return report
|
||||
|
||||
|
||||
class Pass:
|
||||
__slots__ = (
|
||||
"_before",
|
||||
"_command",
|
||||
"_logger",
|
||||
"_publisher",
|
||||
"_report",
|
||||
"_slots",
|
||||
"_storage",
|
||||
"_uow",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
uow: UnitOfWorkFactory,
|
||||
storage: ObjectStorage,
|
||||
command: ReconcileStorage,
|
||||
*,
|
||||
before: datetime,
|
||||
report: Reconciliation,
|
||||
logger: Logger,
|
||||
publisher: EventPublisher,
|
||||
) -> None:
|
||||
self._uow = uow
|
||||
self._storage = storage
|
||||
self._command = command
|
||||
self._before = before
|
||||
self._report = report
|
||||
self._logger = logger
|
||||
self._publisher = publisher
|
||||
self._slots = asyncio.Semaphore(command.deep_concurrency)
|
||||
|
||||
async def run(self) -> None:
|
||||
objects = aiter(self._objects())
|
||||
item = await anext(objects, None)
|
||||
try:
|
||||
async with asyncio.TaskGroup() as checks:
|
||||
async for row in self._rows():
|
||||
while item is not None and item.key < row.object_key:
|
||||
await self._orphan(item)
|
||||
item = await anext(objects, None)
|
||||
matched = item if item is not None and item.key == row.object_key else None
|
||||
await self._row(row, matched, checks)
|
||||
if matched is not None:
|
||||
item = await anext(objects, None)
|
||||
while item is not None:
|
||||
await self._orphan(item)
|
||||
item = await anext(objects, None)
|
||||
except* Unavailable as failed:
|
||||
error = failed.exceptions[0]
|
||||
raise error from error.__cause__
|
||||
|
||||
async def _timed[ResultT](self, name: str, step: Awaitable[ResultT]) -> ResultT:
|
||||
started = monotonic()
|
||||
try:
|
||||
return await step
|
||||
finally:
|
||||
spent = self._report.waited.get(name, 0.0) + monotonic() - started
|
||||
self._report.waited[name] = spent
|
||||
|
||||
async def _objects(self) -> AsyncIterator[StoredObject]:
|
||||
pages = aiter(self._storage.listing(OBJECT_PREFIX, self._command.page_size))
|
||||
while (page := await self._timed("s3_list", anext(pages, None))) is not None:
|
||||
self._report.requests["s3_list"] += 1
|
||||
self._report.objects += len(page)
|
||||
for item in page:
|
||||
yield item
|
||||
|
||||
async def _rows(self) -> AsyncIterator[Attachment]:
|
||||
after, size = "", self._command.page_size
|
||||
while True:
|
||||
page = await self._timed("sql", self._page(after, size + 1))
|
||||
self._report.requests["sql"] += 1
|
||||
rows = page[:size]
|
||||
self._report.rows += len(rows)
|
||||
for row in rows:
|
||||
yield row
|
||||
if len(page) <= size:
|
||||
return
|
||||
after = rows[-1].object_key
|
||||
|
||||
async def _page(self, after: str, size: int) -> Sequence[Attachment]:
|
||||
uow = self._uow()
|
||||
async with uow.transaction():
|
||||
return await uow.attachments.page_after(after, size)
|
||||
|
||||
def _found(self, name: str, subject: str) -> None:
|
||||
self._report.found[name] += 1
|
||||
sample = self._report.samples.setdefault(name, [])
|
||||
if len(sample) < self._command.samples:
|
||||
sample.append(subject)
|
||||
|
||||
async def _safely(self, name: str, action: Awaitable[bool], subject: UUID | None) -> None:
|
||||
attachment_id = None if subject is None else str(subject)
|
||||
try:
|
||||
done = await action
|
||||
except Exception as error:
|
||||
self._report.errors += 1
|
||||
self._logger.warning(
|
||||
"reconcile.action_failed",
|
||||
reason=name,
|
||||
attachment_id=attachment_id,
|
||||
error=type(error).__name__,
|
||||
)
|
||||
return
|
||||
(self._report.fixed if done else self._report.rechecked)[name] += 1
|
||||
event = "reconcile.fixed" if done else "reconcile.rechecked"
|
||||
self._logger.info(event, reason=name, attachment_id=attachment_id)
|
||||
|
||||
async def _orphan(self, item: StoredObject) -> None:
|
||||
if item.modified >= self._before:
|
||||
self._found("orphan_fresh", item.key)
|
||||
return
|
||||
self._found("orphan_stale", item.key)
|
||||
if self._command.apply:
|
||||
await self._safely("orphan_stale", self._delete_orphan(item), None)
|
||||
|
||||
async def _delete_orphan(self, item: StoredObject) -> bool:
|
||||
uow = self._uow()
|
||||
async with uow.transaction():
|
||||
owner = await uow.attachments.by_key(item.key)
|
||||
self._report.requests["sql"] += 1
|
||||
if owner is not None:
|
||||
return False
|
||||
self._report.requests["s3_delete"] += 1
|
||||
await self._storage.delete(item.key)
|
||||
return True
|
||||
|
||||
async def _row(
|
||||
self, row: Attachment, item: StoredObject | None, checks: asyncio.TaskGroup
|
||||
) -> None:
|
||||
if row.status is AttachmentStatus.PENDING:
|
||||
await self._pending(row)
|
||||
elif item is None:
|
||||
await self._broken(row, Quarantine.MISSING)
|
||||
elif item.size != row.size_bytes:
|
||||
await self._broken(row, Quarantine.SIZE_MISMATCH)
|
||||
elif self._command.deep or row.quarantine is not None:
|
||||
await self._slots.acquire()
|
||||
checks.create_task(self._verify(row))
|
||||
|
||||
async def _verify(self, row: Attachment) -> None:
|
||||
try:
|
||||
digest = await self._digest(row.object_key)
|
||||
except Exception as error:
|
||||
self._report.errors += 1
|
||||
self._logger.warning(
|
||||
"reconcile.hash_failed", attachment_id=str(row.id), error=type(error).__name__
|
||||
)
|
||||
return
|
||||
finally:
|
||||
self._slots.release()
|
||||
if digest is None:
|
||||
await self._broken(row, Quarantine.MISSING)
|
||||
elif digest != row.sha256:
|
||||
await self._broken(row, Quarantine.SHA_MISMATCH)
|
||||
else:
|
||||
await self._healthy(row)
|
||||
|
||||
async def _digest(self, key: str) -> str | None:
|
||||
self._report.requests["s3_get"] += 1
|
||||
try:
|
||||
content = await self._storage.open(key)
|
||||
except ObjectMissingError:
|
||||
return None
|
||||
digest = sha256()
|
||||
async for chunk in content.chunks:
|
||||
digest.update(chunk)
|
||||
self._report.hashed_bytes += len(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
async def _broken(self, row: Attachment, reason: Quarantine) -> None:
|
||||
if row.quarantine is not None:
|
||||
self._found("quarantined", str(row.id))
|
||||
return
|
||||
self._found(reason.value, str(row.id))
|
||||
if self._command.apply:
|
||||
await self._safely(reason.value, self._isolate(row, reason), row.id)
|
||||
|
||||
async def _isolate(self, row: Attachment, reason: Quarantine) -> bool:
|
||||
if reason is not Quarantine.SHA_MISMATCH:
|
||||
self._report.requests["s3_head"] += 1
|
||||
found = await self._storage.stat(row.object_key)
|
||||
if found is not None and found.size == row.size_bytes:
|
||||
return False
|
||||
row.isolate(reason)
|
||||
await self._mark(row)
|
||||
return True
|
||||
|
||||
async def _healthy(self, row: Attachment) -> None:
|
||||
if row.quarantine is None:
|
||||
return
|
||||
self._found("healed", str(row.id))
|
||||
if self._command.apply:
|
||||
await self._safely("healed", self._release(row), row.id)
|
||||
|
||||
async def _release(self, row: Attachment) -> bool:
|
||||
row.release()
|
||||
await self._mark(row)
|
||||
return True
|
||||
|
||||
async def _mark(self, row: Attachment) -> None:
|
||||
uow = self._uow()
|
||||
async with uow.transaction():
|
||||
await uow.attachments.mark(row)
|
||||
await uow.commit()
|
||||
self._report.requests["sql"] += 1
|
||||
|
||||
async def _pending(self, row: Attachment) -> None:
|
||||
if row.created_at >= self._before:
|
||||
self._found("pending_fresh", str(row.id))
|
||||
return
|
||||
self._found("pending_stale", str(row.id))
|
||||
if self._command.apply:
|
||||
await self._safely("pending_stale", self._drop(row), row.id)
|
||||
|
||||
async def _drop(self, row: Attachment) -> bool:
|
||||
uow = self._uow()
|
||||
async with uow.transaction():
|
||||
current = await uow.attachments.claim(row.id)
|
||||
self._report.requests["sql"] += 1
|
||||
if (
|
||||
current is None
|
||||
or current.status is not AttachmentStatus.PENDING
|
||||
or current.created_at >= self._before
|
||||
):
|
||||
return False
|
||||
self._report.requests["s3_delete"] += 1
|
||||
await drop(uow, self._storage, current, "reconcile")
|
||||
await self._publisher.publish(uow.collect_new_events())
|
||||
return True
|
||||
@@ -8,6 +8,7 @@ from messenger.attachments.domain.values import Filename, ImageInfo
|
||||
from messenger.attachments.domain.variants import Variant
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
OBJECT_PREFIX = "attachments/"
|
||||
STAGING_PREFIX = "staging/"
|
||||
ORIGINALS_PREFIX = "originals/"
|
||||
|
||||
@@ -24,6 +25,12 @@ def original_key(attachment_id: UUID) -> str:
|
||||
return f"{ORIGINALS_PREFIX}{attachment_id}"
|
||||
|
||||
|
||||
class Quarantine(StrEnum):
|
||||
MISSING = "missing"
|
||||
SIZE_MISMATCH = "size_mismatch"
|
||||
SHA_MISMATCH = "sha_mismatch"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Attachment:
|
||||
id: UUID
|
||||
@@ -41,6 +48,7 @@ class Attachment:
|
||||
published_version: int = 0
|
||||
error_code: str | None = None
|
||||
variants: tuple[Variant, ...] = ()
|
||||
quarantine: Quarantine | None = None
|
||||
_events: list[DomainEvent] = field(init=False, default_factory=list, repr=False, compare=False)
|
||||
|
||||
@classmethod
|
||||
@@ -70,6 +78,10 @@ class Attachment:
|
||||
staging_key=f"{STAGING_PREFIX}{attachment_id}",
|
||||
)
|
||||
|
||||
@property
|
||||
def object_key(self) -> str:
|
||||
return self.original_key or self.staging_key or f"{OBJECT_PREFIX}{self.id}"
|
||||
|
||||
@property
|
||||
def content_type(self) -> str:
|
||||
return self.image.kind.value
|
||||
@@ -98,6 +110,13 @@ class Attachment:
|
||||
AttachmentDiscarded(attachment_id=self.id, chat_id=self.chat_id, reason=reason)
|
||||
)
|
||||
|
||||
def isolate(self, reason: Quarantine) -> None:
|
||||
if self.status is AttachmentStatus.READY:
|
||||
self.quarantine = reason
|
||||
|
||||
def release(self) -> None:
|
||||
self.quarantine = None
|
||||
|
||||
def collect_events(self) -> list[DomainEvent]:
|
||||
events, self._events = self._events, []
|
||||
return events
|
||||
|
||||
@@ -74,7 +74,7 @@ async def object_storage(settings: AttachmentsSettings) -> AsyncIterator[ObjectS
|
||||
yield S3ObjectStorage(client, settings.s3_bucket)
|
||||
|
||||
|
||||
class AttachmentsProvider(Provider):
|
||||
class AttachmentStorageProvider(Provider):
|
||||
def __init__(self, settings: AttachmentsSettings) -> None:
|
||||
super().__init__()
|
||||
self._settings = settings
|
||||
@@ -88,6 +88,8 @@ class AttachmentsProvider(Provider):
|
||||
async with object_storage(settings) as storage:
|
||||
yield storage
|
||||
|
||||
|
||||
class AttachmentsProvider(AttachmentStorageProvider):
|
||||
@provide(scope=Scope.APP)
|
||||
def images(self, settings: AttachmentsSettings) -> ImageInspector:
|
||||
return PillowImageInspector(settings.max_image_pixels, settings.image_check_concurrency)
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import resource
|
||||
import sys
|
||||
from collections.abc import Callable, Sequence
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
|
||||
from dishka import Scope, make_async_container, provide
|
||||
|
||||
from messenger.attachments.application.commands import ReconcileStorage
|
||||
from messenger.attachments.application.ports import ObjectStorage
|
||||
from messenger.attachments.application.reconcile import Reconciliation, StorageReconciler
|
||||
from messenger.attachments.config import AttachmentsSettings
|
||||
from messenger.attachments.domain.events import AttachmentDiscarded
|
||||
from messenger.attachments.entrypoints.ioc import AttachmentStorageProvider
|
||||
from messenger.attachments.entrypoints.journal import LOG_FIELDS, AttachmentsJournal
|
||||
from messenger.attachments.infrastructure.postgres import (
|
||||
PostgresAttachmentsUnitOfWork,
|
||||
PostgresSingleRun,
|
||||
)
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.application.messagebus import EventBus
|
||||
from messenger.shared.application.ports import Clock, EventPublisher, Logger
|
||||
from messenger.shared.config import PlatformSettings
|
||||
from messenger.shared.entrypoints.ioc import PlatformProvider
|
||||
from messenger.shared.infrastructure.logging import PLATFORM_FIELDS, StructlogLogger
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
|
||||
LOCK_KEY = 20_260_004
|
||||
CLASSES = (
|
||||
"orphan_stale",
|
||||
"orphan_fresh",
|
||||
"missing",
|
||||
"size_mismatch",
|
||||
"sha_mismatch",
|
||||
"pending_stale",
|
||||
"pending_fresh",
|
||||
"quarantined",
|
||||
"healed",
|
||||
)
|
||||
FIXABLE = ("orphan_stale", "missing", "size_mismatch", "sha_mismatch", "pending_stale", "healed")
|
||||
REQUESTS = ("s3_list", "s3_head", "s3_get", "s3_delete", "sql")
|
||||
|
||||
|
||||
def bounded(low: int, high: int | None = None) -> Callable[[str], int]:
|
||||
def parse(text: str) -> int:
|
||||
value = int(text)
|
||||
if value < low or (high is not None and value > high):
|
||||
raise argparse.ArgumentTypeError(f"ожидается {low}..{high or '∞'}")
|
||||
return value
|
||||
|
||||
return parse
|
||||
|
||||
|
||||
def command_of(argv: Sequence[str] | None = None) -> ReconcileStorage:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="python -m messenger.attachments.entrypoints.reconcile",
|
||||
description="Сверка метаданных вложений в PostgreSQL с объектами bucket S3",
|
||||
)
|
||||
mode = parser.add_mutually_exclusive_group()
|
||||
mode.add_argument("--dry-run", dest="apply", action="store_false", help="только отчёт")
|
||||
mode.add_argument("--apply", dest="apply", action="store_true", help="исправить найденное")
|
||||
parser.add_argument("--grace", type=bounded(60), default=3600, help="секунды, ≥ 60")
|
||||
parser.add_argument("--skew", type=bounded(0), default=60, help="запас на часы, секунды")
|
||||
parser.add_argument("--deep", action="store_true", help="сверить SHA-256 каждого объекта")
|
||||
parser.add_argument("--page-size", type=bounded(1, 1000), default=1000)
|
||||
parser.add_argument("--deep-concurrency", type=bounded(1, 48), default=8)
|
||||
parser.add_argument("--samples", type=bounded(0, 1000), default=20)
|
||||
args = parser.parse_args(argv)
|
||||
return ReconcileStorage(
|
||||
apply=args.apply,
|
||||
grace=timedelta(seconds=args.grace),
|
||||
skew=timedelta(seconds=args.skew),
|
||||
deep=args.deep,
|
||||
page_size=args.page_size,
|
||||
deep_concurrency=args.deep_concurrency,
|
||||
samples=args.samples,
|
||||
)
|
||||
|
||||
|
||||
class ReconcileProvider(AttachmentStorageProvider):
|
||||
@provide(scope=Scope.APP)
|
||||
def reconciler(
|
||||
self,
|
||||
database: Database,
|
||||
storage: ObjectStorage,
|
||||
clock: Clock,
|
||||
logger: Logger,
|
||||
publisher: EventPublisher,
|
||||
) -> StorageReconciler:
|
||||
return StorageReconciler(
|
||||
lambda: PostgresAttachmentsUnitOfWork(database),
|
||||
storage,
|
||||
PostgresSingleRun(database, LOCK_KEY),
|
||||
clock,
|
||||
logger=logger,
|
||||
publisher=publisher,
|
||||
)
|
||||
|
||||
|
||||
async def reconcile(
|
||||
command: ReconcileStorage,
|
||||
platform: PlatformSettings,
|
||||
settings: AttachmentsSettings,
|
||||
logger: Logger,
|
||||
) -> Reconciliation:
|
||||
container = make_async_container(
|
||||
PlatformProvider(platform, logger), ReconcileProvider(settings)
|
||||
)
|
||||
bus = await container.get(EventBus)
|
||||
bus.subscribe(AttachmentDiscarded, AttachmentsJournal(logger).on_attachment_discarded)
|
||||
bus.start()
|
||||
try:
|
||||
reconciler = await container.get(StorageReconciler)
|
||||
return await reconciler(command)
|
||||
finally:
|
||||
await bus.stop()
|
||||
await container.close()
|
||||
|
||||
|
||||
def failure(error: BaseException) -> str:
|
||||
if isinstance(error, BaseExceptionGroup):
|
||||
return failure(error.exceptions[0])
|
||||
if isinstance(error, Unavailable) and error.__cause__ is not None:
|
||||
return type(error.__cause__).__name__
|
||||
return type(error).__name__
|
||||
|
||||
|
||||
def report_of(command: ReconcileStorage, result: Reconciliation) -> dict[str, Any]:
|
||||
usage = resource.getrusage(resource.RUSAGE_SELF)
|
||||
return {
|
||||
"mode": "apply" if command.apply else "dry-run",
|
||||
"skipped": result.skipped,
|
||||
"grace_seconds": int(command.grace.total_seconds()),
|
||||
"skew_seconds": int(command.skew.total_seconds()),
|
||||
"deep": command.deep,
|
||||
"page_size": command.page_size,
|
||||
"scanned": {"objects": result.objects, "rows": result.rows},
|
||||
"found": {name: result.found[name] for name in CLASSES},
|
||||
"fixed": {name: result.fixed[name] for name in FIXABLE},
|
||||
"rechecked": dict(result.rechecked),
|
||||
"errors": result.errors,
|
||||
"samples": result.samples,
|
||||
"cost": {
|
||||
"seconds": result.seconds,
|
||||
"requests": {name: result.requests[name] for name in REQUESTS},
|
||||
"waited_seconds": {name: round(spent, 3) for name, spent in result.waited.items()},
|
||||
"hashed_bytes": result.hashed_bytes,
|
||||
"cpu_seconds": round(usage.ru_utime + usage.ru_stime, 3),
|
||||
"max_rss_mib": round(usage.ru_maxrss / 1024, 1),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> None:
|
||||
command = command_of(argv)
|
||||
platform = PlatformSettings(db_pool_max_size=command.deep_concurrency + 2)
|
||||
settings = AttachmentsSettings()
|
||||
logger = StructlogLogger(
|
||||
level=platform.log_level, allowed_fields=PLATFORM_FIELDS | LOG_FIELDS, stream=sys.stderr
|
||||
)
|
||||
try:
|
||||
result = asyncio.run(reconcile(command, platform, settings, logger))
|
||||
except Exception as error:
|
||||
logger.error("reconcile.failed", error=failure(error))
|
||||
raise SystemExit(1) from None
|
||||
sys.stdout.write(json.dumps(report_of(command, result), ensure_ascii=False, indent=2) + "\n")
|
||||
raise SystemExit(1 if result.errors else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,4 @@
|
||||
from collections.abc import AsyncIterator
|
||||
from collections.abc import AsyncIterator, Sequence
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any
|
||||
|
||||
@@ -8,7 +8,7 @@ from botocore.exceptions import BotoCoreError, ClientError
|
||||
from botocore.handlers import add_expect_header
|
||||
|
||||
from messenger.attachments.application.errors import ObjectMissingError
|
||||
from messenger.attachments.application.ports import ObjectContent
|
||||
from messenger.attachments.application.ports import ObjectContent, StoredObject
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
|
||||
CHUNK_BYTES = 64 * 1024
|
||||
@@ -98,6 +98,28 @@ class S3ObjectStorage:
|
||||
except FAILURES as error:
|
||||
raise Unavailable("S3 недоступно") from error
|
||||
|
||||
async def listing(self, prefix: str, page_size: int) -> AsyncIterator[Sequence[StoredObject]]:
|
||||
pages = self._client.get_paginator("list_objects_v2").paginate(
|
||||
Bucket=self._bucket, Prefix=prefix, PaginationConfig={"PageSize": page_size}
|
||||
)
|
||||
try:
|
||||
async for page in pages:
|
||||
yield [
|
||||
StoredObject(item["Key"], item["Size"], item["LastModified"])
|
||||
for item in page.get("Contents", ())
|
||||
]
|
||||
except FAILURES as error:
|
||||
raise Unavailable("S3 недоступно") from error
|
||||
|
||||
async def stat(self, key: str) -> StoredObject | None:
|
||||
try:
|
||||
head = await self._client.head_object(Bucket=self._bucket, Key=key)
|
||||
except FAILURES as error:
|
||||
if missing(error):
|
||||
return None
|
||||
raise Unavailable("S3 недоступно") from error
|
||||
return StoredObject(key, head["ContentLength"], head["LastModified"])
|
||||
|
||||
async def _chunks(self, body: Any) -> AsyncIterator[bytes]:
|
||||
async with body as stream:
|
||||
async for chunk in stream.iter_chunks(CHUNK_BYTES):
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from typing import Any
|
||||
@@ -10,12 +9,13 @@ from uvicorn.server import Server
|
||||
from uvicorn_worker import UvicornWorker
|
||||
|
||||
from messenger.main import LOG_FIELDS
|
||||
from messenger.shared.entrypoints.health import DRAINING
|
||||
from messenger.shared.infrastructure.logging import configure
|
||||
from messenger.shared.infrastructure.logging import StructlogLogger, configure
|
||||
from messenger.shared.infrastructure.readiness import DRAINING
|
||||
|
||||
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO")
|
||||
SHUTDOWN_SECONDS = int(os.environ.get("SHUTDOWN_TIMEOUT_SECONDS", "5"))
|
||||
SHUTDOWN_SECONDS = int(os.environ.get("SHUTDOWN_TIMEOUT_SECONDS", "6"))
|
||||
DRAIN_SECONDS = float(os.environ.get("DRAIN_SECONDS", "2"))
|
||||
LOGGER = StructlogLogger(level=LOG_LEVEL, allowed_fields=LOG_FIELDS)
|
||||
|
||||
|
||||
class StructlogGunicornLogger(GunicornBaseLogger):
|
||||
@@ -31,7 +31,7 @@ class DrainingServer(Server):
|
||||
await super().main_loop()
|
||||
if not self.force_exit:
|
||||
DRAINING.set()
|
||||
logging.getLogger("uvicorn.error").info("Draining for %.1f s", DRAIN_SECONDS)
|
||||
LOGGER.info("service.draining", limit=DRAIN_SECONDS)
|
||||
await asyncio.sleep(DRAIN_SECONDS)
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ class MessengerWorker(UvicornWorker):
|
||||
"access_log": False,
|
||||
"server_header": False,
|
||||
"date_header": False,
|
||||
"timeout_graceful_shutdown": max(1, int(SHUTDOWN_SECONDS - DRAIN_SECONDS)),
|
||||
"timeout_graceful_shutdown": max(1, int(SHUTDOWN_SECONDS - DRAIN_SECONDS) - 1),
|
||||
}
|
||||
|
||||
async def _serve(self) -> None:
|
||||
|
||||
@@ -4,7 +4,7 @@ from messenger.identity.application.commands import CloseSession, OpenSession, R
|
||||
from messenger.identity.application.ports import (
|
||||
IdentityUnitOfWork,
|
||||
PasswordHasher,
|
||||
SessionDirectory,
|
||||
SessionRevocations,
|
||||
)
|
||||
from messenger.identity.domain.events import SessionClosed, SessionOpened
|
||||
from messenger.identity.domain.models import Session, User
|
||||
@@ -62,15 +62,19 @@ class OpenSessionHandler:
|
||||
|
||||
|
||||
class CloseSessionHandler:
|
||||
__slots__ = ("_sessions", "_uow")
|
||||
__slots__ = ("_revocations", "_uow")
|
||||
|
||||
def __init__(self, uow: IdentityUnitOfWork, sessions: SessionDirectory) -> None:
|
||||
def __init__(self, uow: IdentityUnitOfWork, revocations: SessionRevocations) -> None:
|
||||
self._uow = uow
|
||||
self._sessions = sessions
|
||||
self._revocations = revocations
|
||||
|
||||
async def __call__(self, command: CloseSession) -> None:
|
||||
await self._sessions.invalidate(command.session)
|
||||
async with self._uow.transaction():
|
||||
await self._uow.sessions.remove(command.session.token_hash)
|
||||
self._uow.record(SessionClosed(user_id=command.session.user_id))
|
||||
await self._uow.commit()
|
||||
await self._revocations.revoke(command.session)
|
||||
try:
|
||||
async with self._uow.transaction():
|
||||
await self._uow.sessions.remove(command.session.token_hash)
|
||||
self._uow.record(SessionClosed(user_id=command.session.user_id))
|
||||
await self._uow.commit()
|
||||
except BaseException:
|
||||
await self._revocations.restore(command.session)
|
||||
raise
|
||||
|
||||
@@ -38,7 +38,12 @@ class UserDirectory(Protocol):
|
||||
class SessionDirectory(Protocol):
|
||||
async def find(self, token_hash: bytes, now: datetime) -> Session | None: ...
|
||||
|
||||
async def invalidate(self, session: Session) -> None: ...
|
||||
|
||||
@runtime_checkable
|
||||
class SessionRevocations(Protocol):
|
||||
async def revoke(self, session: Session) -> None: ...
|
||||
|
||||
async def restore(self, session: Session) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
|
||||
@@ -17,6 +17,7 @@ from messenger.identity.application.ports import (
|
||||
IdentityUnitOfWork,
|
||||
PasswordHasher,
|
||||
SessionDirectory,
|
||||
SessionRevocations,
|
||||
UserDirectory,
|
||||
)
|
||||
from messenger.identity.application.queries import Authenticate, GetCurrentUser, VerifyCredentials
|
||||
@@ -27,7 +28,7 @@ from messenger.identity.infrastructure.postgres import (
|
||||
PostgresSessionDirectory,
|
||||
PostgresUserDirectory,
|
||||
)
|
||||
from messenger.identity.infrastructure.valkey import CachedSessionDirectory
|
||||
from messenger.identity.infrastructure.valkey import CachedSessionDirectory, NoRevocations
|
||||
from messenger.shared.application.commands import Command
|
||||
from messenger.shared.application.messagebus import CommandHandler
|
||||
from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator, Logger
|
||||
@@ -76,6 +77,10 @@ class IdentityProvider(Provider):
|
||||
finally:
|
||||
await client.aclose()
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def revocations(self, sessions: SessionDirectory) -> SessionRevocations:
|
||||
return sessions if isinstance(sessions, CachedSessionDirectory) else NoRevocations()
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def verify(self, users: UserDirectory, hasher: PasswordHasher) -> VerifyCredentials:
|
||||
return VerifyCredentials(users, hasher)
|
||||
@@ -100,13 +105,13 @@ class IdentityProvider(Provider):
|
||||
clock: Clock,
|
||||
ids: IdGenerator,
|
||||
hasher: PasswordHasher,
|
||||
sessions: SessionDirectory,
|
||||
revocations: SessionRevocations,
|
||||
settings: IdentitySettings,
|
||||
) -> IdentityCommandBus:
|
||||
ttl = timedelta(seconds=settings.session_ttl_seconds)
|
||||
handlers: dict[type[Command], CommandHandler] = {
|
||||
RegisterUser: RegisterUserHandler(uow, clock, ids, hasher),
|
||||
OpenSession: OpenSessionHandler(uow, clock, ttl),
|
||||
CloseSession: CloseSessionHandler(uow, sessions),
|
||||
CloseSession: CloseSessionHandler(uow, revocations),
|
||||
}
|
||||
return IdentityCommandBus(handlers, uow, publisher)
|
||||
|
||||
@@ -1,85 +1,126 @@
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from asyncpg import Record
|
||||
from sqlalchemy import (
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
LargeBinary,
|
||||
UniqueConstraint,
|
||||
delete,
|
||||
literal,
|
||||
select,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from messenger.identity.domain.errors import UsernameAlreadyTaken
|
||||
from messenger.identity.domain.models import Session, User
|
||||
from messenger.identity.domain.values import DisplayName, Username
|
||||
from messenger.shared.infrastructure.postgres import Connection, Database, PostgresUnitOfWork
|
||||
|
||||
INSERT_USER = """
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (username) DO NOTHING
|
||||
RETURNING true
|
||||
"""
|
||||
USER_BY_ID = """
|
||||
SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = $1
|
||||
"""
|
||||
USER_BY_USERNAME = """
|
||||
SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1
|
||||
"""
|
||||
INSERT_SESSION = """
|
||||
WITH expired AS (DELETE FROM sessions WHERE user_id = $2 AND expires_at <= $3)
|
||||
INSERT INTO sessions (token_hash, user_id, created_at, expires_at) VALUES ($1, $2, $3, $4)
|
||||
"""
|
||||
DELETE_SESSION = "DELETE FROM sessions WHERE token_hash = $1"
|
||||
ACTIVE_SESSION = """
|
||||
SELECT token_hash, user_id, created_at, expires_at
|
||||
FROM sessions
|
||||
WHERE token_hash = $1 AND expires_at > $2
|
||||
"""
|
||||
from messenger.shared.infrastructure.postgres import (
|
||||
Base,
|
||||
Database,
|
||||
DatabaseSession,
|
||||
PostgresUnitOfWork,
|
||||
)
|
||||
|
||||
|
||||
def user_of(row: Record | None) -> User | None:
|
||||
class UserRow(Base):
|
||||
__tablename__ = "users"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("username", name="users_username_key"),
|
||||
CheckConstraint("username ~ '^[a-z0-9_]{3,32}$'", name="users_username_format"),
|
||||
CheckConstraint(
|
||||
"char_length(display_name) BETWEEN 1 AND 100", name="users_display_name_check"
|
||||
),
|
||||
CheckConstraint("password_hash LIKE '$argon2id$%'", name="users_password_hash_check"),
|
||||
)
|
||||
|
||||
id: Mapped[UUID] = mapped_column(primary_key=True)
|
||||
username: Mapped[str]
|
||||
display_name: Mapped[str]
|
||||
password_hash: Mapped[str]
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class SessionRow(Base):
|
||||
__tablename__ = "sessions"
|
||||
__table_args__ = (
|
||||
CheckConstraint("octet_length(token_hash) = 32", name="sessions_token_hash_check"),
|
||||
CheckConstraint("expires_at > created_at", name="sessions_check"),
|
||||
Index("sessions_user_idx", "user_id"),
|
||||
)
|
||||
|
||||
token_hash: Mapped[bytes] = mapped_column(LargeBinary, primary_key=True)
|
||||
user_id: Mapped[UUID] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
def user_of(row: UserRow | None) -> User | None:
|
||||
if row is None:
|
||||
return None
|
||||
return User(
|
||||
id=row["id"],
|
||||
username=Username(row["username"]),
|
||||
display_name=DisplayName(row["display_name"]),
|
||||
created_at=row["created_at"],
|
||||
password_hash=row["password_hash"],
|
||||
id=row.id,
|
||||
username=Username(row.username),
|
||||
display_name=DisplayName(row.display_name),
|
||||
created_at=row.created_at,
|
||||
password_hash=row.password_hash,
|
||||
)
|
||||
|
||||
|
||||
class PostgresUserRepository:
|
||||
__slots__ = ("_connection",)
|
||||
__slots__ = ("_session",)
|
||||
|
||||
def __init__(self, connection: Connection) -> None:
|
||||
self._connection = connection
|
||||
def __init__(self, session: DatabaseSession) -> None:
|
||||
self._session = session
|
||||
|
||||
async def add(self, user: User) -> None:
|
||||
inserted = await self._connection.fetchval(
|
||||
INSERT_USER,
|
||||
user.id,
|
||||
user.username.value,
|
||||
user.display_name.value,
|
||||
user.password_hash,
|
||||
user.created_at,
|
||||
statement = (
|
||||
insert(UserRow)
|
||||
.values(
|
||||
id=user.id,
|
||||
username=user.username.value,
|
||||
display_name=user.display_name.value,
|
||||
password_hash=user.password_hash,
|
||||
created_at=user.created_at,
|
||||
)
|
||||
.on_conflict_do_nothing(index_elements=["username"])
|
||||
.returning(literal(True))
|
||||
)
|
||||
inserted = (await self._session.execute(statement)).scalar_one_or_none()
|
||||
if inserted is None:
|
||||
raise UsernameAlreadyTaken("username уже занят")
|
||||
|
||||
|
||||
class PostgresSessionRepository:
|
||||
__slots__ = ("_connection",)
|
||||
__slots__ = ("_session",)
|
||||
|
||||
def __init__(self, connection: Connection) -> None:
|
||||
self._connection = connection
|
||||
def __init__(self, session: DatabaseSession) -> None:
|
||||
self._session = session
|
||||
|
||||
async def add(self, session: Session) -> None:
|
||||
await self._connection.execute(
|
||||
INSERT_SESSION,
|
||||
session.token_hash,
|
||||
session.user_id,
|
||||
session.created_at,
|
||||
session.expires_at,
|
||||
expired = (
|
||||
delete(SessionRow)
|
||||
.where(
|
||||
SessionRow.user_id == session.user_id, SessionRow.expires_at <= session.created_at
|
||||
)
|
||||
.cte("expired")
|
||||
)
|
||||
await self._session.execute(
|
||||
insert(SessionRow)
|
||||
.values(
|
||||
token_hash=session.token_hash,
|
||||
user_id=session.user_id,
|
||||
created_at=session.created_at,
|
||||
expires_at=session.expires_at,
|
||||
)
|
||||
.add_cte(expired)
|
||||
)
|
||||
|
||||
async def remove(self, token_hash: bytes) -> None:
|
||||
await self._connection.execute(DELETE_SESSION, token_hash)
|
||||
await self._session.execute(delete(SessionRow).where(SessionRow.token_hash == token_hash))
|
||||
|
||||
|
||||
class PostgresIdentityUnitOfWork(PostgresUnitOfWork):
|
||||
@@ -87,11 +128,11 @@ class PostgresIdentityUnitOfWork(PostgresUnitOfWork):
|
||||
|
||||
@property
|
||||
def users(self) -> PostgresUserRepository:
|
||||
return PostgresUserRepository(self.connection)
|
||||
return PostgresUserRepository(self.session)
|
||||
|
||||
@property
|
||||
def sessions(self) -> PostgresSessionRepository:
|
||||
return PostgresSessionRepository(self.connection)
|
||||
return PostgresSessionRepository(self.session)
|
||||
|
||||
|
||||
class PostgresUserDirectory:
|
||||
@@ -101,12 +142,18 @@ class PostgresUserDirectory:
|
||||
self._database = database
|
||||
|
||||
async def find(self, user_id: UUID) -> User | None:
|
||||
async with self._database.connection() as connection:
|
||||
return user_of(await connection.fetchrow(USER_BY_ID, user_id))
|
||||
async with self._database.session() as session:
|
||||
row = (
|
||||
await session.execute(select(UserRow).where(UserRow.id == user_id))
|
||||
).scalar_one_or_none()
|
||||
return user_of(row)
|
||||
|
||||
async def find_by_username(self, username: str) -> User | None:
|
||||
async with self._database.connection() as connection:
|
||||
return user_of(await connection.fetchrow(USER_BY_USERNAME, username))
|
||||
async with self._database.session() as session:
|
||||
row = (
|
||||
await session.execute(select(UserRow).where(UserRow.username == username))
|
||||
).scalar_one_or_none()
|
||||
return user_of(row)
|
||||
|
||||
|
||||
class PostgresSessionDirectory:
|
||||
@@ -116,9 +163,20 @@ class PostgresSessionDirectory:
|
||||
self._database = database
|
||||
|
||||
async def find(self, token_hash: bytes, now: datetime) -> Session | None:
|
||||
async with self._database.connection() as connection:
|
||||
row = await connection.fetchrow(ACTIVE_SESSION, token_hash, now)
|
||||
return None if row is None else Session(**dict(row))
|
||||
|
||||
async def invalidate(self, session: Session) -> None:
|
||||
return None
|
||||
async with self._database.session() as session:
|
||||
row = (
|
||||
await session.execute(
|
||||
select(SessionRow).where(
|
||||
SessionRow.token_hash == token_hash,
|
||||
SessionRow.expires_at > now,
|
||||
)
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
if row is None:
|
||||
return None
|
||||
return Session(
|
||||
token_hash=row.token_hash,
|
||||
user_id=row.user_id,
|
||||
created_at=row.created_at,
|
||||
expires_at=row.expires_at,
|
||||
)
|
||||
|
||||
@@ -37,6 +37,14 @@ def decode(token_hash: bytes, value: str) -> Session:
|
||||
)
|
||||
|
||||
|
||||
class NoRevocations:
|
||||
async def revoke(self, session: Session) -> None:
|
||||
return None
|
||||
|
||||
async def restore(self, session: Session) -> None:
|
||||
return None
|
||||
|
||||
|
||||
class CachedSessionDirectory:
|
||||
__slots__ = ("_client", "_cooldown", "_limit", "_logger", "_origin", "_resume_at")
|
||||
|
||||
@@ -70,7 +78,7 @@ class CachedSessionDirectory:
|
||||
await self._quietly(self._client.set(key, encode(session), pxat=until, nx=True))
|
||||
return session
|
||||
|
||||
async def invalidate(self, session: Session) -> None:
|
||||
async def revoke(self, session: Session) -> None:
|
||||
if not self._closed():
|
||||
raise Unavailable("кэш сессий недоступен")
|
||||
try:
|
||||
@@ -81,6 +89,9 @@ class CachedSessionDirectory:
|
||||
self._trip(error)
|
||||
raise Unavailable("кэш сессий недоступен") from error
|
||||
|
||||
async def restore(self, session: Session) -> None:
|
||||
await self._quietly(self._client.delete(key_of(session.token_hash)))
|
||||
|
||||
async def _read(self, key: str) -> str | None:
|
||||
if not self._closed():
|
||||
return None
|
||||
|
||||
@@ -40,7 +40,7 @@ from messenger.shared.entrypoints.ioc import PlatformProvider
|
||||
from messenger.shared.entrypoints.pipeline import RequestPipeline
|
||||
from messenger.shared.infrastructure.logging import PLATFORM_FIELDS, StructlogLogger
|
||||
|
||||
TRANSPORT_FIELDS = frozenset({"dropped_total", "queue", "instance"})
|
||||
TRANSPORT_FIELDS = frozenset({"dropped_total"})
|
||||
|
||||
LOG_FIELDS = (
|
||||
PLATFORM_FIELDS | TRANSPORT_FIELDS | IDENTITY_FIELDS | MESSAGING_FIELDS | ATTACHMENT_FIELDS
|
||||
@@ -148,6 +148,7 @@ def create_app(
|
||||
guard=guard,
|
||||
instance=platform.instance_id,
|
||||
limits=((UPLOAD_PATH, attachments.max_upload_bytes),),
|
||||
min_rate=transport.min_transfer_rate_bytes,
|
||||
)
|
||||
errors.install(app, logger, ERROR_CODES, challenge_for, platform.instance_id)
|
||||
app.include_router(health.router)
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
from datetime import timedelta
|
||||
|
||||
from messenger.messaging.application.commands import CreateChat, PostMessage
|
||||
from messenger.messaging.application.ports import AttachmentStates, MessagingUnitOfWork
|
||||
from messenger.messaging.domain.errors import AttachmentUnavailable, ChatNotFound
|
||||
from messenger.messaging.domain.models import Chat, Message, Receipt
|
||||
from messenger.messaging.application.ports import ChatDirectory, MessageLog, MessagingUnitOfWork
|
||||
from messenger.messaging.domain.errors import (
|
||||
ChatNotFound,
|
||||
InvalidAttachmentList,
|
||||
InvalidMessageText,
|
||||
)
|
||||
from messenger.messaging.domain.models import Chat, Message, attachment_list
|
||||
from messenger.messaging.domain.values import MessageText
|
||||
from messenger.shared.application.ports import Clock, IdGenerator
|
||||
|
||||
|
||||
@@ -30,44 +35,41 @@ class CreateChatHandler:
|
||||
|
||||
|
||||
class PostMessageHandler:
|
||||
__slots__ = ("_attachments", "_clock", "_ids", "_ttl", "_uow")
|
||||
__slots__ = ("_chats", "_clock", "_ids", "_log", "_ttl", "_uow")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
uow: MessagingUnitOfWork,
|
||||
attachments: AttachmentStates,
|
||||
log: MessageLog,
|
||||
chats: ChatDirectory,
|
||||
clock: Clock,
|
||||
ids: IdGenerator,
|
||||
*,
|
||||
ttl: timedelta,
|
||||
) -> None:
|
||||
self._uow = uow
|
||||
self._attachments = attachments
|
||||
self._log = log
|
||||
self._chats = chats
|
||||
self._clock = clock
|
||||
self._ids = ids
|
||||
self._ttl = ttl
|
||||
|
||||
async def __call__(self, command: PostMessage) -> Message:
|
||||
async with self._uow.transaction():
|
||||
chat = await self._uow.chats.get(command.chat_id)
|
||||
if chat is None:
|
||||
raise ChatNotFound("чат не найден")
|
||||
now = self._clock.now()
|
||||
message = chat.post(
|
||||
message_id=self._ids.new_id(),
|
||||
sender_id=command.sender_id,
|
||||
text=command.text,
|
||||
now=now,
|
||||
attachment_ids=command.attachment_ids,
|
||||
)
|
||||
known = await self._uow.chats.receipt(
|
||||
chat.id, command.sender_id, command.key, now - self._ttl
|
||||
)
|
||||
if known is not None:
|
||||
return known.replay(command.fingerprint)
|
||||
if message.attachment_ids and await self._attachments.unusable(
|
||||
chat.id, message.attachment_ids
|
||||
):
|
||||
raise AttachmentUnavailable("вложение не обработано и не может быть отправлено")
|
||||
await self._uow.chats.append(Receipt(command.key, command.fingerprint, message))
|
||||
await self._uow.commit()
|
||||
try:
|
||||
text = MessageText(command.text)
|
||||
attachments = attachment_list(text, command.attachment_ids)
|
||||
except InvalidMessageText, InvalidAttachmentList:
|
||||
if await self._chats.chat_for_member(command.chat_id, command.sender_id) is None:
|
||||
raise ChatNotFound("чат не найден") from None
|
||||
raise
|
||||
now = self._clock.now()
|
||||
draft = Message(
|
||||
self._ids.new_id(), command.chat_id, command.sender_id, text, now, attachments
|
||||
)
|
||||
receipt = await self._log.post(draft, command.key, command.fingerprint, now - self._ttl)
|
||||
if receipt is None:
|
||||
raise ChatNotFound("чат не найден")
|
||||
message = receipt.replay(command.fingerprint)
|
||||
if message.id == draft.id:
|
||||
self._uow.record(message.posted())
|
||||
return message
|
||||
|
||||
@@ -19,14 +19,13 @@ class CursorCodec(Protocol):
|
||||
class ChatRepository(Protocol):
|
||||
async def add(self, chat: Chat) -> None: ...
|
||||
|
||||
async def get(self, chat_id: UUID) -> Chat | None: ...
|
||||
|
||||
async def receipt(
|
||||
self, chat_id: UUID, sender_id: UUID, key: str, since: datetime
|
||||
@runtime_checkable
|
||||
class MessageLog(Protocol):
|
||||
async def post(
|
||||
self, message: Message, key: str, fingerprint: bytes, since: datetime
|
||||
) -> Receipt | None: ...
|
||||
|
||||
async def append(self, receipt: Receipt) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class MessagingUnitOfWork(UnitOfWork, Protocol):
|
||||
|
||||
@@ -43,7 +43,7 @@ class ListChats:
|
||||
|
||||
async def __call__(self, user_id: UUID, *, limit: int, cursor: str | None) -> Page[Chat]:
|
||||
scope = chats_scope(user_id)
|
||||
after: HistoryKey | None = self._cursors.decode(scope, cursor) if cursor else None
|
||||
after: HistoryKey | None = None if cursor is None else self._cursors.decode(scope, cursor)
|
||||
items, has_more = await self._chats.chats_of(user_id, after=after, limit=limit)
|
||||
next_cursor = self._cursors.encode(scope, items[-1].key) if has_more and items else None
|
||||
return Page(items=items, next_cursor=next_cursor)
|
||||
@@ -67,7 +67,7 @@ class ReadHistory:
|
||||
if await self._chats.chat_for_member(chat_id, user_id) is None:
|
||||
raise ChatNotFound("чат не найден")
|
||||
scope = messages_scope(chat_id)
|
||||
after: HistoryKey | None = self._cursors.decode(scope, cursor) if cursor else None
|
||||
after: HistoryKey | None = None if cursor is None else self._cursors.decode(scope, cursor)
|
||||
items, has_more = await self._chats.history(chat_id, after=after, limit=limit)
|
||||
next_cursor = self._cursors.encode(scope, items[-1].key) if has_more and items else None
|
||||
return Page(items=items, next_cursor=next_cursor)
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.messaging.domain.errors import (
|
||||
ChatNotFound,
|
||||
IdempotencyConflict,
|
||||
InvalidAttachmentList,
|
||||
InvalidChatData,
|
||||
@@ -20,8 +19,6 @@ from messenger.messaging.domain.values import (
|
||||
)
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
TICK = timedelta(microseconds=1)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Message:
|
||||
@@ -36,6 +33,15 @@ class Message:
|
||||
def key(self) -> HistoryKey:
|
||||
return (self.created_at, self.id.int)
|
||||
|
||||
def posted(self) -> MessagePosted:
|
||||
return MessagePosted(
|
||||
message_id=self.id,
|
||||
chat_id=self.chat_id,
|
||||
sender_id=self.sender_id,
|
||||
text_length=len(self.text.value),
|
||||
created_at=self.created_at,
|
||||
)
|
||||
|
||||
|
||||
def attachment_list(text: MessageText, attachment_ids: Sequence[UUID]) -> tuple[UUID, ...]:
|
||||
if len(attachment_ids) > MESSAGE_ATTACHMENTS_MAX:
|
||||
@@ -62,15 +68,7 @@ class Receipt:
|
||||
|
||||
|
||||
class Chat:
|
||||
__slots__ = (
|
||||
"_events",
|
||||
"_members",
|
||||
"created_at",
|
||||
"id",
|
||||
"last_message_at",
|
||||
"member_ids",
|
||||
"title",
|
||||
)
|
||||
__slots__ = ("_events", "created_at", "id", "member_ids", "title")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -79,14 +77,11 @@ class Chat:
|
||||
title: ChatTitle,
|
||||
member_ids: Sequence[UUID],
|
||||
created_at: datetime,
|
||||
last_message_at: datetime | None = None,
|
||||
) -> None:
|
||||
self.id = chat_id
|
||||
self.title = title
|
||||
self.member_ids: tuple[UUID, ...] = tuple(member_ids)
|
||||
self.created_at = created_at
|
||||
self.last_message_at = last_message_at
|
||||
self._members: frozenset[UUID] = frozenset(member_ids)
|
||||
self._events: list[DomainEvent] = []
|
||||
|
||||
@classmethod
|
||||
@@ -131,47 +126,6 @@ class Chat:
|
||||
def record(self, event: DomainEvent) -> None:
|
||||
self._events.append(event)
|
||||
|
||||
def is_member(self, user_id: UUID) -> bool:
|
||||
return user_id in self._members
|
||||
|
||||
def require_member(self, user_id: UUID) -> None:
|
||||
if not self.is_member(user_id):
|
||||
raise ChatNotFound("чат не найден")
|
||||
|
||||
def post(
|
||||
self,
|
||||
*,
|
||||
message_id: UUID,
|
||||
sender_id: UUID,
|
||||
text: str,
|
||||
now: datetime,
|
||||
attachment_ids: Sequence[UUID] = (),
|
||||
) -> Message:
|
||||
self.require_member(sender_id)
|
||||
body = MessageText(text)
|
||||
attachments = attachment_list(body, attachment_ids)
|
||||
last = self.last_message_at
|
||||
created_at = now if last is None or now > last else last + TICK
|
||||
message = Message(
|
||||
id=message_id,
|
||||
chat_id=self.id,
|
||||
sender_id=sender_id,
|
||||
text=body,
|
||||
created_at=created_at,
|
||||
attachment_ids=attachments,
|
||||
)
|
||||
self.last_message_at = created_at
|
||||
self.record(
|
||||
MessagePosted(
|
||||
message_id=message.id,
|
||||
chat_id=self.id,
|
||||
sender_id=sender_id,
|
||||
text_length=len(message.text.value),
|
||||
created_at=created_at,
|
||||
)
|
||||
)
|
||||
return message
|
||||
|
||||
def collect_events(self) -> list[DomainEvent]:
|
||||
events, self._events = self._events, []
|
||||
return events
|
||||
|
||||
@@ -9,6 +9,7 @@ from messenger.messaging.application.ports import (
|
||||
AttachmentStates,
|
||||
ChatDirectory,
|
||||
CursorCodec,
|
||||
MessageLog,
|
||||
MessagingUnitOfWork,
|
||||
)
|
||||
from messenger.messaging.application.queries import GetChat, ListChats, ReadHistory
|
||||
@@ -16,6 +17,7 @@ from messenger.messaging.config import MessagingSettings
|
||||
from messenger.messaging.infrastructure.cursor import SignedCursorCodec
|
||||
from messenger.messaging.infrastructure.postgres import (
|
||||
PostgresChatDirectory,
|
||||
PostgresMessageLog,
|
||||
PostgresMessagingUnitOfWork,
|
||||
)
|
||||
from messenger.shared.application.commands import Command
|
||||
@@ -37,6 +39,10 @@ class MessagingProvider(Provider):
|
||||
def directory(self, database: Database) -> ChatDirectory:
|
||||
return PostgresChatDirectory(database)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def log(self, database: Database, attachments: AttachmentStates) -> MessageLog:
|
||||
return PostgresMessageLog(database, attachments)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def cursors(self, settings: MessagingSettings) -> CursorCodec:
|
||||
return SignedCursorCodec(settings.cursor_secret.get_secret_value().encode())
|
||||
@@ -61,7 +67,8 @@ class MessagingProvider(Provider):
|
||||
def command_bus(
|
||||
self,
|
||||
uow: MessagingUnitOfWork,
|
||||
attachments: AttachmentStates,
|
||||
log: MessageLog,
|
||||
directory: ChatDirectory,
|
||||
publisher: EventPublisher,
|
||||
clock: Clock,
|
||||
ids: IdGenerator,
|
||||
@@ -70,6 +77,6 @@ class MessagingProvider(Provider):
|
||||
ttl = timedelta(seconds=settings.idempotency_ttl_seconds)
|
||||
handlers: dict[type[Command], CommandHandler] = {
|
||||
CreateChat: CreateChatHandler(uow, clock, ids),
|
||||
PostMessage: PostMessageHandler(uow, attachments, clock, ids, ttl),
|
||||
PostMessage: PostMessageHandler(uow, log, directory, clock, ids, ttl=ttl),
|
||||
}
|
||||
return MessagingCommandBus(handlers, uow, publisher)
|
||||
|
||||
@@ -37,7 +37,7 @@ class CreateMessageRequest(BaseModel):
|
||||
|
||||
class PageQuery(BaseModel):
|
||||
limit: int = Field(default=50, ge=1, le=100)
|
||||
cursor: str | None = None
|
||||
cursor: str | None = Field(default=None, min_length=1)
|
||||
|
||||
|
||||
class ChatOut(BaseModel):
|
||||
|
||||
@@ -1,122 +1,266 @@
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime
|
||||
from dataclasses import replace
|
||||
from datetime import datetime, timedelta
|
||||
from typing import cast
|
||||
from uuid import UUID
|
||||
|
||||
from asyncpg import ForeignKeyViolationError, Record
|
||||
from sqlalchemy import (
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
ForeignKeyConstraint,
|
||||
Index,
|
||||
LargeBinary,
|
||||
RowMapping,
|
||||
Select,
|
||||
SmallInteger,
|
||||
Table,
|
||||
UniqueConstraint,
|
||||
bindparam,
|
||||
column,
|
||||
func,
|
||||
insert,
|
||||
lambda_stmt,
|
||||
literal,
|
||||
select,
|
||||
true,
|
||||
tuple_,
|
||||
update,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import ARRAY
|
||||
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy.sql.elements import Label
|
||||
|
||||
from messenger.messaging.domain.errors import InvalidChatData, UnknownAttachment
|
||||
from messenger.messaging.application.ports import AttachmentStates
|
||||
from messenger.messaging.domain.errors import (
|
||||
AttachmentUnavailable,
|
||||
InvalidChatData,
|
||||
UnknownAttachment,
|
||||
)
|
||||
from messenger.messaging.domain.keys import HistoryKey
|
||||
from messenger.messaging.domain.models import Chat, Message, Receipt
|
||||
from messenger.messaging.domain.values import ChatTitle, MessageText
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.infrastructure.postgres import (
|
||||
Connection,
|
||||
Base,
|
||||
Database,
|
||||
DatabaseSession,
|
||||
EventSource,
|
||||
PostgresUnitOfWork,
|
||||
)
|
||||
|
||||
INSERT_CHAT = "INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)"
|
||||
INSERT_MEMBERS = """
|
||||
INSERT INTO chat_members (chat_id, user_id, position, chat_created_at)
|
||||
SELECT $1, member.user_id, member.position, $3
|
||||
FROM unnest($2::uuid[]) WITH ORDINALITY AS member (user_id, position)
|
||||
"""
|
||||
LOCK_CHAT = """
|
||||
SELECT c.id, c.title, c.created_at, c.last_message_at,
|
||||
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids
|
||||
FROM chats c
|
||||
WHERE c.id = $1
|
||||
FOR UPDATE
|
||||
"""
|
||||
ATTACHMENT_FKEY = "message_attachments_attachment_fkey"
|
||||
RECEIPT = """
|
||||
SELECT k.fingerprint, m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
||||
WHERE a.message_id = m.id ORDER BY a.position) AS attachment_ids
|
||||
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.chat_id = $1 AND k.user_id = $2 AND k.key = $3 AND k.created_at > $4
|
||||
"""
|
||||
APPEND_MESSAGE = """
|
||||
WITH message AS (
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING id, chat_id, sender_id, created_at
|
||||
), links AS (
|
||||
INSERT INTO message_attachments (message_id, position, chat_id, attachment_id)
|
||||
SELECT message.id, link.position - 1, message.chat_id, link.attachment_id
|
||||
FROM message, unnest($8::uuid[]) WITH ORDINALITY AS link (attachment_id, position)
|
||||
), receipt AS (
|
||||
INSERT INTO idempotency_keys (chat_id, user_id, key, fingerprint, message_id, created_at)
|
||||
SELECT chat_id, sender_id, $6, $7, id, created_at FROM message
|
||||
ON CONFLICT (chat_id, user_id, key) DO UPDATE
|
||||
SET fingerprint = EXCLUDED.fingerprint,
|
||||
message_id = EXCLUDED.message_id,
|
||||
created_at = EXCLUDED.created_at
|
||||
)
|
||||
UPDATE chats SET last_message_at = message.created_at
|
||||
FROM message
|
||||
WHERE chats.id = message.chat_id
|
||||
"""
|
||||
CHAT_OF_MEMBER = """
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids
|
||||
FROM chat_members m JOIN chats c ON c.id = m.chat_id
|
||||
WHERE m.chat_id = $1 AND m.user_id = $2
|
||||
"""
|
||||
CHATS_FIRST = """
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids
|
||||
FROM chat_members m JOIN chats c ON c.id = m.chat_id
|
||||
WHERE m.user_id = $1
|
||||
ORDER BY m.chat_created_at, m.chat_id
|
||||
LIMIT $2
|
||||
"""
|
||||
CHATS_AFTER = """
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids
|
||||
FROM chat_members m JOIN chats c ON c.id = m.chat_id
|
||||
WHERE m.user_id = $1 AND (m.chat_created_at, m.chat_id) > ($2, $3)
|
||||
ORDER BY m.chat_created_at, m.chat_id
|
||||
LIMIT $4
|
||||
"""
|
||||
HISTORY_FIRST = """
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
||||
WHERE a.message_id = m.id ORDER BY a.position) AS attachment_ids
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $2
|
||||
"""
|
||||
HISTORY_AFTER = """
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
||||
WHERE a.message_id = m.id ORDER BY a.position) AS attachment_ids
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1 AND (m.created_at, m.id) > ($2, $3)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $4
|
||||
"""
|
||||
FOREIGN_KEY_VIOLATED = "23503"
|
||||
|
||||
|
||||
def chat_of(row: Record) -> Chat:
|
||||
class ChatRow(Base):
|
||||
__tablename__ = "chats"
|
||||
__table_args__ = (
|
||||
CheckConstraint("char_length(title) BETWEEN 1 AND 100", name="chats_title_check"),
|
||||
)
|
||||
|
||||
id: Mapped[UUID] = mapped_column(primary_key=True)
|
||||
title: Mapped[str]
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
last_message_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class ChatMemberRow(Base):
|
||||
__tablename__ = "chat_members"
|
||||
__table_args__ = (
|
||||
CheckConstraint("position BETWEEN 1 AND 100", name="chat_members_position_check"),
|
||||
Index("chat_members_user_idx", "user_id", "chat_created_at", "chat_id"),
|
||||
)
|
||||
|
||||
chat_id: Mapped[UUID] = mapped_column(
|
||||
ForeignKey("chats.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
user_id: Mapped[UUID] = mapped_column(ForeignKey("users.id"), primary_key=True)
|
||||
position: Mapped[int] = mapped_column(SmallInteger)
|
||||
chat_created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class MessageRow(Base):
|
||||
__tablename__ = "messages"
|
||||
__table_args__ = (
|
||||
CheckConstraint("char_length(text) <= 4000", name="messages_text_check"),
|
||||
ForeignKeyConstraint(
|
||||
["chat_id", "sender_id"], ["chat_members.chat_id", "chat_members.user_id"]
|
||||
),
|
||||
Index("messages_history_idx", "chat_id", "created_at", "id"),
|
||||
)
|
||||
|
||||
id: Mapped[UUID] = mapped_column(primary_key=True)
|
||||
chat_id: Mapped[UUID]
|
||||
sender_id: Mapped[UUID]
|
||||
text: Mapped[str]
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class IdempotencyKeyRow(Base):
|
||||
__tablename__ = "idempotency_keys"
|
||||
__table_args__ = (
|
||||
CheckConstraint("key ~ '^[A-Za-z0-9._:-]{1,128}$'", name="idempotency_keys_key_check"),
|
||||
CheckConstraint(
|
||||
"octet_length(fingerprint) = 32", name="idempotency_keys_fingerprint_check"
|
||||
),
|
||||
ForeignKeyConstraint(
|
||||
["chat_id", "user_id"], ["chat_members.chat_id", "chat_members.user_id"]
|
||||
),
|
||||
)
|
||||
|
||||
chat_id: Mapped[UUID] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[UUID] = mapped_column(primary_key=True)
|
||||
key: Mapped[str] = mapped_column(primary_key=True)
|
||||
fingerprint: Mapped[bytes] = mapped_column(LargeBinary)
|
||||
message_id: Mapped[UUID] = mapped_column(ForeignKey("messages.id", ondelete="CASCADE"))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class MessageAttachmentRow(Base):
|
||||
__tablename__ = "message_attachments"
|
||||
__table_args__ = (
|
||||
CheckConstraint("position BETWEEN 0 AND 9", name="message_attachments_position_check"),
|
||||
UniqueConstraint("message_id", "attachment_id"),
|
||||
ForeignKeyConstraint(
|
||||
["attachment_id", "chat_id"],
|
||||
["attachments.id", "attachments.chat_id"],
|
||||
name="message_attachments_attachment_fkey",
|
||||
ondelete="RESTRICT",
|
||||
),
|
||||
Index("message_attachments_attachment_idx", "attachment_id"),
|
||||
)
|
||||
|
||||
message_id: Mapped[UUID] = mapped_column(
|
||||
ForeignKey("messages.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
position: Mapped[int] = mapped_column(SmallInteger, primary_key=True)
|
||||
chat_id: Mapped[UUID]
|
||||
attachment_id: Mapped[UUID]
|
||||
|
||||
|
||||
def post_message() -> Select:
|
||||
chats, members = cast(Table, ChatRow.__table__), cast(Table, ChatMemberRow.__table__)
|
||||
keys, messages = cast(Table, IdempotencyKeyRow.__table__), cast(Table, MessageRow.__table__)
|
||||
sender = bindparam("sender_id", type_=PGUUID)
|
||||
chat_id = bindparam("chat_id", type_=PGUUID)
|
||||
message_id = bindparam("message_id", type_=PGUUID)
|
||||
chat = (
|
||||
select(
|
||||
chats.c.id,
|
||||
func.greatest(
|
||||
bindparam("stamp", type_=DateTime(timezone=True)),
|
||||
chats.c.last_message_at + timedelta(microseconds=1),
|
||||
).label("stamp"),
|
||||
)
|
||||
.join(members, (members.c.chat_id == chats.c.id) & (members.c.user_id == sender))
|
||||
.where(chats.c.id == chat_id)
|
||||
.with_for_update(of=chats)
|
||||
.cte("chat")
|
||||
)
|
||||
receipt_insert = pg_insert(keys).from_select(
|
||||
["chat_id", "user_id", "key", "fingerprint", "message_id", "created_at"],
|
||||
select(
|
||||
chat.c.id,
|
||||
sender,
|
||||
bindparam("key"),
|
||||
bindparam("fingerprint", type_=LargeBinary),
|
||||
message_id,
|
||||
chat.c.stamp,
|
||||
),
|
||||
)
|
||||
receipt = (
|
||||
receipt_insert.on_conflict_do_update(
|
||||
index_elements=[keys.c.chat_id, keys.c.user_id, keys.c.key],
|
||||
set_={
|
||||
name: receipt_insert.excluded[name]
|
||||
for name in ("fingerprint", "message_id", "created_at")
|
||||
},
|
||||
where=keys.c.created_at <= bindparam("since", type_=DateTime(timezone=True)),
|
||||
)
|
||||
.returning(keys.c.created_at)
|
||||
.cte("receipt")
|
||||
)
|
||||
message = (
|
||||
insert(messages)
|
||||
.from_select(
|
||||
["id", "chat_id", "sender_id", "text", "created_at"],
|
||||
select(message_id, chat_id, sender, bindparam("text"), receipt.c.created_at),
|
||||
)
|
||||
.returning(messages.c.chat_id, messages.c.created_at)
|
||||
.cte("message")
|
||||
)
|
||||
attachments = (
|
||||
func.unnest(bindparam("attachment_ids", type_=ARRAY(PGUUID)))
|
||||
.table_valued(column("attachment_id", PGUUID), with_ordinality="position")
|
||||
.render_derived(name="attachment")
|
||||
)
|
||||
links = (
|
||||
insert(cast(Table, MessageAttachmentRow.__table__))
|
||||
.from_select(
|
||||
["message_id", "position", "chat_id", "attachment_id"],
|
||||
select(
|
||||
message_id, attachments.c.position - 1, chat_id, attachments.c.attachment_id
|
||||
).select_from(message.join(attachments, true())),
|
||||
)
|
||||
.cte("links")
|
||||
)
|
||||
touched = (
|
||||
update(chats)
|
||||
.where(chats.c.id == message.c.chat_id)
|
||||
.values(last_message_at=message.c.created_at)
|
||||
.cte("touched")
|
||||
)
|
||||
return select(
|
||||
select(chat.c.id).exists().label("member"),
|
||||
select(message.c.created_at).scalar_subquery().label("created_at"),
|
||||
).add_cte(links, touched)
|
||||
|
||||
|
||||
POST_MESSAGE = lambda_stmt(post_message, enable_tracking=False)
|
||||
|
||||
|
||||
def member_ids() -> Label[Sequence[UUID]]:
|
||||
return func.array(
|
||||
select(ChatMemberRow.user_id)
|
||||
.where(ChatMemberRow.chat_id == ChatRow.id)
|
||||
.order_by(ChatMemberRow.position)
|
||||
.correlate(ChatRow)
|
||||
.scalar_subquery(),
|
||||
type_=ARRAY(PGUUID(as_uuid=True)),
|
||||
).label("member_ids")
|
||||
|
||||
|
||||
def attachment_ids() -> Label[Sequence[UUID]]:
|
||||
return func.array(
|
||||
select(MessageAttachmentRow.attachment_id)
|
||||
.where(MessageAttachmentRow.message_id == MessageRow.id)
|
||||
.order_by(MessageAttachmentRow.position)
|
||||
.correlate(MessageRow)
|
||||
.scalar_subquery(),
|
||||
type_=ARRAY(PGUUID(as_uuid=True)),
|
||||
).label("attachment_ids")
|
||||
|
||||
|
||||
def chat_of(row: RowMapping) -> Chat:
|
||||
return Chat(
|
||||
chat_id=row["id"],
|
||||
title=ChatTitle(row["title"]),
|
||||
member_ids=row["member_ids"],
|
||||
created_at=row["created_at"],
|
||||
last_message_at=row.get("last_message_at"),
|
||||
)
|
||||
|
||||
|
||||
def message_of(row: Record) -> Message:
|
||||
def message_of(row: RowMapping) -> Message:
|
||||
return Message(
|
||||
id=row["id"],
|
||||
chat_id=row["chat_id"],
|
||||
sender_id=row["sender_id"],
|
||||
text=MessageText(row["text"]),
|
||||
created_at=row["created_at"],
|
||||
attachment_ids=tuple(row["attachment_ids"]),
|
||||
created_at=row["created_at"],
|
||||
)
|
||||
|
||||
|
||||
@@ -125,54 +269,110 @@ def page[ItemT](rows: Sequence[ItemT], limit: int) -> tuple[list[ItemT], bool]:
|
||||
|
||||
|
||||
class PostgresChatRepository:
|
||||
__slots__ = ("_connection", "_seen")
|
||||
__slots__ = ("_seen", "_session")
|
||||
|
||||
def __init__(self, connection: Connection, seen: list[EventSource]) -> None:
|
||||
self._connection = connection
|
||||
def __init__(self, session: DatabaseSession, seen: list[EventSource]) -> None:
|
||||
self._session = session
|
||||
self._seen = seen
|
||||
|
||||
async def add(self, chat: Chat) -> None:
|
||||
await self._connection.execute(INSERT_CHAT, chat.id, chat.title.value, chat.created_at)
|
||||
await self._session.execute(
|
||||
insert(ChatRow).values(id=chat.id, title=chat.title.value, created_at=chat.created_at)
|
||||
)
|
||||
try:
|
||||
await self._connection.execute(
|
||||
INSERT_MEMBERS, chat.id, list(chat.member_ids), chat.created_at
|
||||
await self._session.execute(
|
||||
insert(ChatMemberRow),
|
||||
[
|
||||
{
|
||||
"chat_id": chat.id,
|
||||
"user_id": member_id,
|
||||
"position": position,
|
||||
"chat_created_at": chat.created_at,
|
||||
}
|
||||
for position, member_id in enumerate(chat.member_ids, 1)
|
||||
],
|
||||
)
|
||||
except ForeignKeyViolationError as error:
|
||||
except IntegrityError as error:
|
||||
if getattr(error.orig, "sqlstate", None) != FOREIGN_KEY_VIOLATED:
|
||||
raise
|
||||
raise InvalidChatData("поле member_ids содержит неизвестного пользователя") from error
|
||||
self._seen.append(chat)
|
||||
|
||||
async def get(self, chat_id: UUID) -> Chat | None:
|
||||
row = await self._connection.fetchrow(LOCK_CHAT, chat_id)
|
||||
if row is None:
|
||||
return None
|
||||
chat = chat_of(row)
|
||||
self._seen.append(chat)
|
||||
return chat
|
||||
|
||||
async def receipt(
|
||||
self, chat_id: UUID, sender_id: UUID, key: str, since: datetime
|
||||
class PostgresMessageLog:
|
||||
__slots__ = ("_attachments", "_database")
|
||||
|
||||
def __init__(self, database: Database, attachments: AttachmentStates) -> None:
|
||||
self._database = database
|
||||
self._attachments = attachments
|
||||
|
||||
async def post(
|
||||
self, message: Message, key: str, fingerprint: bytes, since: datetime
|
||||
) -> Receipt | None:
|
||||
row = await self._connection.fetchrow(RECEIPT, chat_id, sender_id, key, since)
|
||||
return None if row is None else Receipt(key, row["fingerprint"], message_of(row))
|
||||
|
||||
async def append(self, receipt: Receipt) -> None:
|
||||
message = receipt.message
|
||||
try:
|
||||
await self._connection.execute(
|
||||
APPEND_MESSAGE,
|
||||
message.id,
|
||||
message.chat_id,
|
||||
message.sender_id,
|
||||
message.text.value,
|
||||
message.created_at,
|
||||
receipt.key,
|
||||
receipt.fingerprint,
|
||||
list(message.attachment_ids),
|
||||
chat_id, sender_id = message.chat_id, message.sender_id
|
||||
async with self._database.session() as session:
|
||||
try:
|
||||
row = (
|
||||
(
|
||||
await session.execute(
|
||||
POST_MESSAGE,
|
||||
{
|
||||
"message_id": message.id,
|
||||
"chat_id": chat_id,
|
||||
"sender_id": sender_id,
|
||||
"text": message.text.value,
|
||||
"stamp": message.created_at,
|
||||
"key": key,
|
||||
"fingerprint": fingerprint,
|
||||
"since": since,
|
||||
"attachment_ids": list(message.attachment_ids),
|
||||
},
|
||||
)
|
||||
)
|
||||
.mappings()
|
||||
.first()
|
||||
)
|
||||
except IntegrityError as error:
|
||||
cause = getattr(error.orig, "__cause__", None)
|
||||
if getattr(cause, "constraint_name", None) != "message_attachments_attachment_fkey":
|
||||
raise
|
||||
raise UnknownAttachment("вложение не найдено в этом чате") from error
|
||||
if row is None or not row["member"]:
|
||||
return None
|
||||
if row["created_at"] is not None:
|
||||
if message.attachment_ids and await self._attachments.unusable(
|
||||
chat_id, message.attachment_ids
|
||||
):
|
||||
raise AttachmentUnavailable("вложение не обработано и не может быть отправлено")
|
||||
await session.commit()
|
||||
return Receipt(key, fingerprint, replace(message, created_at=row["created_at"]))
|
||||
known = (
|
||||
(
|
||||
await session.execute(
|
||||
select(
|
||||
IdempotencyKeyRow.fingerprint,
|
||||
MessageRow.id,
|
||||
MessageRow.chat_id,
|
||||
MessageRow.sender_id,
|
||||
MessageRow.text,
|
||||
MessageRow.created_at,
|
||||
attachment_ids(),
|
||||
)
|
||||
.join(MessageRow, MessageRow.id == IdempotencyKeyRow.message_id)
|
||||
.where(
|
||||
IdempotencyKeyRow.chat_id == chat_id,
|
||||
IdempotencyKeyRow.user_id == sender_id,
|
||||
IdempotencyKeyRow.key == key,
|
||||
IdempotencyKeyRow.created_at > since,
|
||||
)
|
||||
)
|
||||
)
|
||||
.mappings()
|
||||
.first()
|
||||
)
|
||||
except ForeignKeyViolationError as error:
|
||||
if getattr(error, "constraint_name", None) != ATTACHMENT_FKEY:
|
||||
raise
|
||||
raise UnknownAttachment("вложение не найдено в этом чате") from error
|
||||
if known is None:
|
||||
raise Unavailable("ключ идемпотентности занят незавершённой записью")
|
||||
return Receipt(key, known["fingerprint"], message_of(known))
|
||||
|
||||
|
||||
class PostgresMessagingUnitOfWork(PostgresUnitOfWork):
|
||||
@@ -180,7 +380,7 @@ class PostgresMessagingUnitOfWork(PostgresUnitOfWork):
|
||||
|
||||
@property
|
||||
def chats(self) -> PostgresChatRepository:
|
||||
return PostgresChatRepository(self.connection, self.seen)
|
||||
return PostgresChatRepository(self.session, self.seen)
|
||||
|
||||
|
||||
class PostgresChatDirectory:
|
||||
@@ -190,30 +390,62 @@ class PostgresChatDirectory:
|
||||
self._database = database
|
||||
|
||||
async def chat_for_member(self, chat_id: UUID, user_id: UUID) -> Chat | None:
|
||||
async with self._database.connection() as connection:
|
||||
row = await connection.fetchrow(CHAT_OF_MEMBER, chat_id, user_id)
|
||||
async with self._database.session() as session:
|
||||
row = (
|
||||
(
|
||||
await session.execute(
|
||||
select(ChatRow.id, ChatRow.title, ChatRow.created_at, member_ids())
|
||||
.select_from(ChatMemberRow)
|
||||
.join(ChatRow, ChatRow.id == ChatMemberRow.chat_id)
|
||||
.where(ChatMemberRow.chat_id == chat_id, ChatMemberRow.user_id == user_id)
|
||||
)
|
||||
)
|
||||
.mappings()
|
||||
.first()
|
||||
)
|
||||
return None if row is None else chat_of(row)
|
||||
|
||||
async def chats_of(
|
||||
self, user_id: UUID, *, after: HistoryKey | None, limit: int
|
||||
) -> tuple[list[Chat], bool]:
|
||||
async with self._database.connection() as connection:
|
||||
if after is None:
|
||||
rows = await connection.fetch(CHATS_FIRST, user_id, limit + 1)
|
||||
else:
|
||||
rows = await connection.fetch(
|
||||
CHATS_AFTER, user_id, after[0], UUID(int=after[1]), limit + 1
|
||||
)
|
||||
statement = (
|
||||
select(ChatRow.id, ChatRow.title, ChatRow.created_at, member_ids())
|
||||
.select_from(ChatMemberRow)
|
||||
.join(ChatRow, ChatRow.id == ChatMemberRow.chat_id)
|
||||
.where(ChatMemberRow.user_id == user_id)
|
||||
.order_by(ChatMemberRow.chat_created_at, ChatMemberRow.chat_id)
|
||||
.limit(limit + 1)
|
||||
)
|
||||
if after is not None:
|
||||
statement = statement.where(
|
||||
tuple_(ChatMemberRow.chat_created_at, ChatMemberRow.chat_id)
|
||||
> tuple_(literal(after[0]), literal(UUID(int=after[1])))
|
||||
)
|
||||
async with self._database.session() as session:
|
||||
rows = (await session.execute(statement)).mappings().all()
|
||||
return page([chat_of(row) for row in rows], limit)
|
||||
|
||||
async def history(
|
||||
self, chat_id: UUID, *, after: HistoryKey | None, limit: int
|
||||
) -> tuple[list[Message], bool]:
|
||||
async with self._database.connection() as connection:
|
||||
if after is None:
|
||||
rows = await connection.fetch(HISTORY_FIRST, chat_id, limit + 1)
|
||||
else:
|
||||
rows = await connection.fetch(
|
||||
HISTORY_AFTER, chat_id, after[0], UUID(int=after[1]), limit + 1
|
||||
)
|
||||
statement = (
|
||||
select(
|
||||
MessageRow.id,
|
||||
MessageRow.chat_id,
|
||||
MessageRow.sender_id,
|
||||
MessageRow.text,
|
||||
MessageRow.created_at,
|
||||
attachment_ids(),
|
||||
)
|
||||
.where(MessageRow.chat_id == chat_id)
|
||||
.order_by(MessageRow.created_at, MessageRow.id)
|
||||
.limit(limit + 1)
|
||||
)
|
||||
if after is not None:
|
||||
statement = statement.where(
|
||||
tuple_(MessageRow.created_at, MessageRow.id)
|
||||
> tuple_(literal(after[0]), literal(UUID(int=after[1])))
|
||||
)
|
||||
async with self._database.session() as session:
|
||||
rows = (await session.execute(statement)).mappings().all()
|
||||
return page([message_of(row) for row in rows], limit)
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
from importlib import resources
|
||||
|
||||
import asyncpg
|
||||
|
||||
from messenger.shared.config import PlatformSettings
|
||||
from messenger.shared.infrastructure.logging import PLATFORM_FIELDS, StructlogLogger
|
||||
|
||||
LOCK_KEY = 20_260_002
|
||||
JOURNAL = """
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
checksum text NOT NULL,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)
|
||||
"""
|
||||
|
||||
|
||||
class MigrationChangedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def migrations() -> list[tuple[str, str]]:
|
||||
folder = resources.files("messenger") / "migrations"
|
||||
found = (item for item in folder.iterdir() if item.name.endswith(".sql"))
|
||||
return sorted((item.name.removesuffix(".sql"), item.read_text()) for item in found)
|
||||
|
||||
|
||||
async def migrate(dsn: str) -> list[str]:
|
||||
connection = await asyncpg.connect(dsn, timeout=10)
|
||||
try:
|
||||
await connection.execute("SELECT pg_advisory_lock($1)", LOCK_KEY)
|
||||
await connection.execute(JOURNAL)
|
||||
applied = dict(await connection.fetch("SELECT version, checksum FROM schema_migrations"))
|
||||
done: list[str] = []
|
||||
for version, sql in migrations():
|
||||
checksum = hashlib.sha256(sql.encode()).hexdigest()
|
||||
if version in applied:
|
||||
if applied[version] != checksum:
|
||||
raise MigrationChangedError(version)
|
||||
continue
|
||||
async with connection.transaction():
|
||||
await connection.execute(sql)
|
||||
await connection.execute(
|
||||
"INSERT INTO schema_migrations (version, checksum) VALUES ($1, $2)",
|
||||
version,
|
||||
checksum,
|
||||
)
|
||||
done.append(version)
|
||||
return done
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
settings = PlatformSettings()
|
||||
logger = StructlogLogger(level=settings.log_level, allowed_fields=PLATFORM_FIELDS | {"version"})
|
||||
try:
|
||||
done = asyncio.run(migrate(settings.database_url.get_secret_value()))
|
||||
except MigrationChangedError as error:
|
||||
logger.error("migration.changed", version=str(error))
|
||||
raise SystemExit(1) from None
|
||||
for version in done:
|
||||
logger.info("migration.applied", version=version)
|
||||
logger.info("migration.completed", reason="up to date" if not done else "applied")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,46 +0,0 @@
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL CONSTRAINT users_username_key UNIQUE
|
||||
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
password_hash text NOT NULL CHECK (password_hash LIKE '$argon2id$%'),
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
token_hash bytea PRIMARY KEY CHECK (octet_length(token_hash) = 32),
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL,
|
||||
expires_at timestamptz NOT NULL,
|
||||
CHECK (expires_at > created_at)
|
||||
);
|
||||
|
||||
CREATE INDEX sessions_user_idx ON sessions (user_id);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||
created_at timestamptz NOT NULL,
|
||||
last_message_at timestamptz
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
position smallint NOT NULL CHECK (position BETWEEN 1 AND 100),
|
||||
chat_created_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_created_at, chat_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL,
|
||||
sender_id uuid NOT NULL,
|
||||
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
created_at timestamptz NOT NULL,
|
||||
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id);
|
||||
@@ -1,10 +0,0 @@
|
||||
CREATE TABLE idempotency_keys (
|
||||
chat_id uuid NOT NULL,
|
||||
user_id uuid NOT NULL,
|
||||
key text NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'),
|
||||
fingerprint bytea NOT NULL CHECK (octet_length(fingerprint) = 32),
|
||||
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id, key),
|
||||
FOREIGN KEY (chat_id, user_id) REFERENCES chat_members (chat_id, user_id)
|
||||
);
|
||||
@@ -1,37 +0,0 @@
|
||||
ALTER TABLE messages
|
||||
DROP CONSTRAINT messages_text_check,
|
||||
ADD CONSTRAINT messages_text_check CHECK (char_length(text) <= 4000);
|
||||
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL,
|
||||
owner_id uuid NOT NULL,
|
||||
filename text NOT NULL CHECK (char_length(filename) BETWEEN 1 AND 255),
|
||||
content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'),
|
||||
width integer NOT NULL CHECK (width > 0),
|
||||
height integer NOT NULL CHECK (height > 0),
|
||||
object_key text COLLATE "C" NOT NULL CONSTRAINT attachments_object_key_key UNIQUE,
|
||||
status text NOT NULL CHECK (status IN ('pending', 'ready')),
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL,
|
||||
CONSTRAINT attachments_chat_key UNIQUE (id, chat_id),
|
||||
CONSTRAINT attachments_owner_fkey FOREIGN KEY (chat_id, owner_id)
|
||||
REFERENCES chat_members (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX attachments_pending_idx ON attachments (created_at) WHERE status = 'pending';
|
||||
|
||||
CREATE TABLE message_attachments (
|
||||
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
|
||||
position smallint NOT NULL CHECK (position BETWEEN 0 AND 9),
|
||||
chat_id uuid NOT NULL,
|
||||
attachment_id uuid NOT NULL,
|
||||
PRIMARY KEY (message_id, position),
|
||||
UNIQUE (message_id, attachment_id),
|
||||
CONSTRAINT message_attachments_attachment_fkey FOREIGN KEY (attachment_id, chat_id)
|
||||
REFERENCES attachments (id, chat_id) ON DELETE RESTRICT
|
||||
);
|
||||
|
||||
CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id);
|
||||
@@ -1,70 +0,0 @@
|
||||
ALTER TABLE attachments
|
||||
DROP CONSTRAINT attachments_status_check,
|
||||
ADD CONSTRAINT attachments_status_check
|
||||
CHECK (status IN ('pending', 'queued', 'processing', 'ready', 'failed')),
|
||||
ADD COLUMN staging_key text COLLATE "C" CONSTRAINT attachments_staging_key_key UNIQUE,
|
||||
ADD COLUMN original_key text COLLATE "C" CONSTRAINT attachments_original_key_key UNIQUE,
|
||||
ADD COLUMN published_version integer NOT NULL DEFAULT 0 CHECK (published_version >= 0),
|
||||
ADD COLUMN error_code text
|
||||
CHECK (error_code IN ('invalid_image', 'processing_failed', 'retry_exhausted')),
|
||||
ALTER COLUMN object_key DROP NOT NULL;
|
||||
|
||||
UPDATE attachments SET original_key = object_key, published_version = 1 WHERE status = 'ready';
|
||||
UPDATE attachments SET staging_key = object_key WHERE status = 'pending';
|
||||
|
||||
CREATE INDEX attachments_staged_idx ON attachments (updated_at) WHERE staging_key IS NOT NULL;
|
||||
|
||||
CREATE TABLE attachment_variants (
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id),
|
||||
pipeline_version integer NOT NULL CHECK (pipeline_version >= 1),
|
||||
name text NOT NULL CHECK (name IN ('thumbnail', 'crop', 'optimized')),
|
||||
object_key text COLLATE "C" NOT NULL CONSTRAINT attachment_variants_object_key_key UNIQUE,
|
||||
content_type text NOT NULL CHECK (content_type IN ('image/jpeg', 'image/png', 'image/webp')),
|
||||
size_bytes bigint NOT NULL CHECK (size_bytes >= 1),
|
||||
width integer NOT NULL CHECK (width >= 1),
|
||||
height integer NOT NULL CHECK (height >= 1),
|
||||
sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'),
|
||||
created_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (attachment_id, pipeline_version, name)
|
||||
);
|
||||
|
||||
CREATE TABLE jobs (
|
||||
job_id uuid PRIMARY KEY,
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id),
|
||||
pipeline_version integer NOT NULL CHECK (pipeline_version >= 1),
|
||||
status text NOT NULL CHECK (status IN ('queued', 'processing', 'done', 'failed', 'superseded')),
|
||||
attempt integer NOT NULL CHECK (attempt >= 1),
|
||||
claims integer NOT NULL DEFAULT 0 CHECK (claims >= 0),
|
||||
lease_token uuid,
|
||||
lease_until timestamptz,
|
||||
next_attempt_at timestamptz,
|
||||
last_error text,
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL,
|
||||
CONSTRAINT jobs_effect_key UNIQUE (attachment_id, pipeline_version)
|
||||
);
|
||||
|
||||
CREATE INDEX jobs_lease_idx ON jobs (lease_until) WHERE status = 'processing';
|
||||
|
||||
CREATE TABLE outbox (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
job_id uuid NOT NULL REFERENCES jobs (job_id),
|
||||
payload jsonb NOT NULL,
|
||||
available_at timestamptz NOT NULL,
|
||||
published_at timestamptz
|
||||
);
|
||||
|
||||
CREATE INDEX outbox_pending_idx ON outbox (available_at, id) WHERE published_at IS NULL;
|
||||
CREATE INDEX outbox_job_idx ON outbox (job_id);
|
||||
|
||||
CREATE TABLE job_events (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
job_id uuid NOT NULL,
|
||||
attachment_id uuid NOT NULL,
|
||||
kind text NOT NULL,
|
||||
attempt integer,
|
||||
detail jsonb NOT NULL DEFAULT '{}',
|
||||
at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX job_events_attachment_idx ON job_events (attachment_id, id);
|
||||
@@ -1 +0,0 @@
|
||||
CREATE INDEX jobs_failed_idx ON jobs (updated_at DESC) WHERE status = 'failed';
|
||||
@@ -37,28 +37,21 @@ class CommandBus:
|
||||
|
||||
|
||||
class EventBus:
|
||||
__slots__ = ("_deferred", "_dropped", "_logger", "_projections", "_queue", "_worker")
|
||||
__slots__ = ("_deferred", "_dropped", "_logger", "_queue", "_worker")
|
||||
|
||||
def __init__(self, logger: Logger, *, max_queue: int = 10_000) -> None:
|
||||
self._logger = logger
|
||||
self._queue: asyncio.Queue[DomainEvent] = asyncio.Queue(maxsize=max_queue)
|
||||
self._projections: dict[type[DomainEvent], list[Any]] = {}
|
||||
self._deferred: dict[type[DomainEvent], list[Any]] = {}
|
||||
self._worker: asyncio.Task[None] | None = None
|
||||
self._dropped = 0
|
||||
|
||||
def project[EventT: DomainEvent](
|
||||
self, event_type: type[EventT], handler: EventHandler[EventT]
|
||||
) -> None:
|
||||
self._projections.setdefault(event_type, []).append(handler)
|
||||
|
||||
def subscribe[EventT: DomainEvent](
|
||||
self, event_type: type[EventT], handler: EventHandler[EventT]
|
||||
) -> None:
|
||||
self._deferred.setdefault(event_type, []).append(handler)
|
||||
|
||||
async def emit(self, event: DomainEvent) -> bool:
|
||||
await self._run(self._projections.get(type(event), []), event, "projection")
|
||||
if not self._deferred.get(type(event)):
|
||||
return True
|
||||
try:
|
||||
@@ -96,11 +89,11 @@ class EventBus:
|
||||
while True:
|
||||
event = await self._queue.get()
|
||||
try:
|
||||
await self._run(self._deferred.get(type(event), []), event, "subscriber")
|
||||
await self._run(self._deferred.get(type(event), []), event)
|
||||
finally:
|
||||
self._queue.task_done()
|
||||
|
||||
async def _run(self, handlers: Sequence[Any], event: DomainEvent, kind: str) -> None:
|
||||
async def _run(self, handlers: Sequence[Any], event: DomainEvent) -> None:
|
||||
for handler in handlers:
|
||||
try:
|
||||
await handler(event)
|
||||
@@ -108,7 +101,6 @@ class EventBus:
|
||||
self._logger.error(
|
||||
"event.handler_failed",
|
||||
event_name=event.name,
|
||||
reason=kind,
|
||||
error=type(error).__name__,
|
||||
)
|
||||
|
||||
|
||||
@@ -26,6 +26,11 @@ class Logger(Protocol):
|
||||
def error(self, event: str, /, **fields: Any) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class Readiness(Protocol):
|
||||
async def check(self) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class UnitOfWork(Protocol):
|
||||
def transaction(self) -> AbstractAsyncContextManager[None]: ...
|
||||
|
||||
@@ -9,7 +9,7 @@ from messenger.shared.entrypoints.errors import Unauthenticated
|
||||
async def current_actor(request: Request) -> UUID:
|
||||
actor = getattr(request.state, "actor", None)
|
||||
if not isinstance(actor, UUID):
|
||||
raise Unauthenticated("заголовок идентификации обязателен и должен быть действительным")
|
||||
raise Unauthenticated("сессия не подтверждена")
|
||||
return actor
|
||||
|
||||
|
||||
|
||||
@@ -7,4 +7,4 @@ class TransportSettings(Settings):
|
||||
docs: bool = False
|
||||
max_body_bytes: int = Field(default=1_048_576, ge=4_096)
|
||||
request_timeout_seconds: float = Field(default=8.0, gt=0, le=300)
|
||||
shutdown_timeout_seconds: int = Field(default=5, ge=1, le=10)
|
||||
min_transfer_rate_bytes: int = Field(default=131_072, ge=1_024)
|
||||
|
||||
@@ -46,7 +46,7 @@ class Unauthenticated(Exception):
|
||||
|
||||
def classify(error: DomainError, codes: ErrorCodes) -> tuple[str, int]:
|
||||
for kind in type(error).__mro__:
|
||||
known = codes.get(kind) # type: ignore[arg-type]
|
||||
known = codes.get(kind)
|
||||
if known is not None:
|
||||
return known
|
||||
return "internal_error", status.HTTP_500_INTERNAL_SERVER_ERROR
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
from threading import Event
|
||||
|
||||
from dishka.integrations.fastapi import FromDishka, inject
|
||||
from fastapi import APIRouter
|
||||
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.application.ports import Readiness
|
||||
from messenger.shared.entrypoints.schemas import HealthOut
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
DRAINING = Event()
|
||||
|
||||
|
||||
@router.get("/health/live")
|
||||
@@ -18,8 +14,6 @@ async def live() -> HealthOut:
|
||||
|
||||
@router.get("/health/ready")
|
||||
@inject
|
||||
async def ready(database: FromDishka[Database]) -> HealthOut:
|
||||
if DRAINING.is_set():
|
||||
raise Unavailable("Реплика выходит из ротации")
|
||||
await database.ping()
|
||||
async def ready(readiness: FromDishka[Readiness]) -> HealthOut:
|
||||
await readiness.check()
|
||||
return HealthOut()
|
||||
|
||||
@@ -3,11 +3,12 @@ from collections.abc import AsyncIterator
|
||||
from dishka import Provider, Scope, provide
|
||||
|
||||
from messenger.shared.application.messagebus import EventBus, InMemoryEventPublisher
|
||||
from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator, Logger
|
||||
from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator, Logger, Readiness
|
||||
from messenger.shared.config import PlatformSettings
|
||||
from messenger.shared.infrastructure.clock import MonotonicUtcClock
|
||||
from messenger.shared.infrastructure.ids import Uuid7Generator
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
from messenger.shared.infrastructure.readiness import DatabaseReadiness
|
||||
|
||||
|
||||
class PlatformProvider(Provider):
|
||||
@@ -45,6 +46,10 @@ class PlatformProvider(Provider):
|
||||
yield database
|
||||
await database.close()
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def readiness(self, database: Database) -> Readiness:
|
||||
return DatabaseReadiness(database)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def event_bus(self, logger: Logger, settings: PlatformSettings) -> EventBus:
|
||||
return EventBus(logger, max_queue=settings.event_queue_max)
|
||||
|
||||
@@ -5,6 +5,7 @@ from collections.abc import Awaitable, Callable
|
||||
from dataclasses import dataclass
|
||||
from uuid import uuid4
|
||||
|
||||
from starlette.exceptions import HTTPException
|
||||
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
||||
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
@@ -57,8 +58,44 @@ async def send_error(
|
||||
await send({"type": "http.response.body", "body": body})
|
||||
|
||||
|
||||
class Pace:
|
||||
__slots__ = ("_deadline", "_moved", "_opened", "_rate", "_timeout")
|
||||
|
||||
def __init__(self, deadline: asyncio.Timeout, timeout: float, rate: float) -> None:
|
||||
self._deadline = deadline
|
||||
self._timeout = timeout
|
||||
self._rate = rate
|
||||
self._opened = asyncio.get_running_loop().time()
|
||||
self._moved = 0
|
||||
|
||||
def around(self, receive: Receive, send: Send) -> tuple[Receive, Send]:
|
||||
async def paced_receive() -> Message:
|
||||
return self._count(await receive())
|
||||
|
||||
async def paced_send(message: Message) -> None:
|
||||
await send(self._count(message))
|
||||
|
||||
return paced_receive, paced_send
|
||||
|
||||
def _count(self, message: Message) -> Message:
|
||||
if size := len(message.get("body", b"")):
|
||||
self._moved += size
|
||||
moved = min(asyncio.get_running_loop().time(), self._opened + self._moved / self._rate)
|
||||
self._deadline.reschedule(moved + self._timeout)
|
||||
return message
|
||||
|
||||
|
||||
class RequestPipeline:
|
||||
__slots__ = ("_app", "_guard", "_instance", "_limits", "_logger", "_max_bytes", "_timeout")
|
||||
__slots__ = (
|
||||
"_app",
|
||||
"_guard",
|
||||
"_instance",
|
||||
"_limits",
|
||||
"_logger",
|
||||
"_max_bytes",
|
||||
"_min_rate",
|
||||
"_timeout",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -69,12 +106,14 @@ class RequestPipeline:
|
||||
guard: Guard,
|
||||
instance: str,
|
||||
limits: BodyLimits = (),
|
||||
min_rate: float = 131_072,
|
||||
) -> None:
|
||||
self._app = app
|
||||
self._logger = logger
|
||||
self._max_bytes = max_bytes
|
||||
self._limits = limits
|
||||
self._timeout = timeout
|
||||
self._min_rate = min_rate
|
||||
self._guard = guard
|
||||
self._instance = instance.encode()
|
||||
|
||||
@@ -85,9 +124,7 @@ class RequestPipeline:
|
||||
|
||||
incoming = header(scope, HEADER_BYTES)
|
||||
request_id = incoming[:MAX_REQUEST_ID] if incoming else uuid4().hex
|
||||
state = scope.setdefault("state", {})
|
||||
state["request_id"] = request_id
|
||||
state["actor"] = None
|
||||
scope.setdefault("state", {}).update(request_id=request_id, actor=None)
|
||||
started = time.perf_counter()
|
||||
status_holder = [500]
|
||||
answered = [False]
|
||||
@@ -106,18 +143,23 @@ class RequestPipeline:
|
||||
message = {**message, "headers": headers}
|
||||
await send(message)
|
||||
|
||||
declared = header(scope, b"content-length")
|
||||
if declared.isdigit() and int(declared) > self._limit(scope["path"]):
|
||||
await send_error(wrapped_send, 413, "payload_too_large", request_id)
|
||||
self._log(scope, status_holder[0], request_id, started)
|
||||
return
|
||||
limit = self._limit(scope["path"])
|
||||
received = [0]
|
||||
|
||||
async def limited_receive() -> Message:
|
||||
message = await receive()
|
||||
received[0] += len(message.get("body", b""))
|
||||
if received[0] > limit:
|
||||
raise HTTPException(413)
|
||||
return message
|
||||
|
||||
rejection: Rejection | None = None
|
||||
try:
|
||||
async with asyncio.timeout(self._timeout):
|
||||
rejection = await self._guard(scope)
|
||||
async with asyncio.timeout(self._timeout) as deadline:
|
||||
rejection = await self._guard(scope) or self._oversized(scope, limit)
|
||||
if rejection is None:
|
||||
await self._app(scope, receive, wrapped_send)
|
||||
pace = Pace(deadline, self._timeout, self._min_rate)
|
||||
await self._app(scope, *pace.around(limited_receive, wrapped_send))
|
||||
except Unavailable as error:
|
||||
self._logger.warning(
|
||||
"dependency.unavailable",
|
||||
@@ -126,18 +168,21 @@ class RequestPipeline:
|
||||
request_id=request_id,
|
||||
)
|
||||
rejection = Rejection(503, "unavailable")
|
||||
except TimeoutError:
|
||||
except (TimeoutError, asyncio.CancelledError) as error:
|
||||
cancelled = isinstance(error, asyncio.CancelledError)
|
||||
self._logger.warning(
|
||||
"request.timeout",
|
||||
"request.cancelled" if cancelled else "request.timeout",
|
||||
method=scope["method"],
|
||||
route=self._route(scope),
|
||||
request_id=request_id,
|
||||
limit=self._timeout,
|
||||
limit=None if cancelled else self._timeout,
|
||||
duration_ms=round((time.perf_counter() - started) * 1000, 3),
|
||||
)
|
||||
if not answered[0]:
|
||||
await send_error(wrapped_send, 503, "unavailable", request_id)
|
||||
self._log(scope, status_holder[0], request_id, started)
|
||||
if cancelled:
|
||||
raise
|
||||
return
|
||||
except Exception:
|
||||
self._logger.error(
|
||||
@@ -160,6 +205,12 @@ class RequestPipeline:
|
||||
return limit
|
||||
return self._max_bytes
|
||||
|
||||
def _oversized(self, scope: Scope, limit: int) -> Rejection | None:
|
||||
declared = header(scope, b"content-length")
|
||||
if declared.isdigit() and int(declared) > limit:
|
||||
return Rejection(413, "payload_too_large")
|
||||
return None
|
||||
|
||||
def _route(self, scope: Scope) -> str:
|
||||
route = scope.get("route")
|
||||
return getattr(route, "path", scope["path"])
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import logging
|
||||
import sys
|
||||
from typing import Any
|
||||
from typing import Any, TextIO
|
||||
|
||||
import orjson
|
||||
import structlog
|
||||
@@ -51,7 +51,11 @@ def field_filter(allowed: frozenset[str]) -> Processor:
|
||||
return drop_unlisted_fields
|
||||
|
||||
|
||||
def configure(level: str = "INFO", allowed_fields: frozenset[str] = PLATFORM_FIELDS) -> None:
|
||||
def configure(
|
||||
level: str = "INFO",
|
||||
allowed_fields: frozenset[str] = PLATFORM_FIELDS,
|
||||
stream: TextIO | None = None,
|
||||
) -> None:
|
||||
shared = [
|
||||
structlog.contextvars.merge_contextvars,
|
||||
structlog.processors.add_log_level,
|
||||
@@ -63,7 +67,7 @@ def configure(level: str = "INFO", allowed_fields: frozenset[str] = PLATFORM_FIE
|
||||
wrapper_class=structlog.stdlib.BoundLogger,
|
||||
cache_logger_on_first_use=False,
|
||||
)
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler = logging.StreamHandler(stream or sys.stdout)
|
||||
handler.setFormatter(
|
||||
structlog.stdlib.ProcessorFormatter(
|
||||
foreign_pre_chain=shared,
|
||||
@@ -99,8 +103,9 @@ class StructlogLogger:
|
||||
name: str = "messenger",
|
||||
level: str = "INFO",
|
||||
allowed_fields: frozenset[str] = PLATFORM_FIELDS,
|
||||
stream: TextIO | None = None,
|
||||
) -> None:
|
||||
configure(level, allowed_fields)
|
||||
configure(level, allowed_fields, stream)
|
||||
self._logger = structlog.get_logger(name)
|
||||
|
||||
def info(self, event: str, /, **fields: Any) -> None:
|
||||
|
||||
@@ -1,32 +1,45 @@
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any, Protocol
|
||||
from typing import ClassVar, Protocol
|
||||
|
||||
import asyncpg
|
||||
from sqlalchemy import Text, make_url, select
|
||||
from sqlalchemy.exc import DBAPIError, IntegrityError, InterfaceError, OperationalError
|
||||
from sqlalchemy.exc import TimeoutError as PoolTimeout
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
FAILURES = (
|
||||
OSError,
|
||||
asyncpg.InterfaceError,
|
||||
asyncpg.PostgresConnectionError,
|
||||
asyncpg.exceptions.OperatorInterventionError,
|
||||
asyncpg.exceptions.InsufficientResourcesError,
|
||||
asyncpg.exceptions.LockNotAvailableError,
|
||||
)
|
||||
FAILURES = (OSError, InterfaceError, OperationalError, PoolTimeout, TimeoutError)
|
||||
|
||||
PING_TIMEOUT_SECONDS = 0.4
|
||||
|
||||
type Connection = asyncpg.Connection
|
||||
type DatabaseSession = AsyncSession
|
||||
|
||||
|
||||
class EventSource(Protocol):
|
||||
def collect_events(self) -> list[DomainEvent]: ...
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
type_annotation_map: ClassVar = {str: Text}
|
||||
|
||||
|
||||
def unavailable(error: BaseException) -> bool:
|
||||
if isinstance(error, IntegrityError):
|
||||
return False
|
||||
if isinstance(error, FAILURES):
|
||||
return True
|
||||
if isinstance(error, DBAPIError) and error.connection_invalidated:
|
||||
return True
|
||||
state = getattr(error.orig if isinstance(error, DBAPIError) else error, "sqlstate", None)
|
||||
return isinstance(state, str) and (state.startswith(("08", "53", "57")) or state == "55P03")
|
||||
|
||||
|
||||
class Database:
|
||||
__slots__ = ("_acquire_timeout", "_pool")
|
||||
__slots__ = ("_engine", "_sessions")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -37,63 +50,71 @@ class Database:
|
||||
acquire_timeout: float,
|
||||
command_timeout: float,
|
||||
) -> None:
|
||||
self._acquire_timeout = acquire_timeout
|
||||
self._pool = asyncpg.create_pool(
|
||||
dsn,
|
||||
min_size=0,
|
||||
max_size=max_size,
|
||||
timeout=connect_timeout,
|
||||
command_timeout=command_timeout,
|
||||
max_inactive_connection_lifetime=60,
|
||||
server_settings={
|
||||
"statement_timeout": str(int(command_timeout * 1000)),
|
||||
"lock_timeout": str(int(command_timeout * 1000)),
|
||||
"idle_in_transaction_session_timeout": "10000",
|
||||
self._engine = create_async_engine(
|
||||
make_url(dsn).set(drivername="postgresql+asyncpg"),
|
||||
pool_size=max_size,
|
||||
max_overflow=0,
|
||||
pool_timeout=acquire_timeout,
|
||||
pool_recycle=60,
|
||||
pool_pre_ping=True,
|
||||
hide_parameters=True,
|
||||
connect_args={
|
||||
"timeout": connect_timeout,
|
||||
"command_timeout": command_timeout,
|
||||
"server_settings": {
|
||||
"statement_timeout": str(int(command_timeout * 1000)),
|
||||
"lock_timeout": str(int(command_timeout * 1000)),
|
||||
"idle_in_transaction_session_timeout": "10000",
|
||||
},
|
||||
},
|
||||
)
|
||||
self._sessions = async_sessionmaker(self._engine, expire_on_commit=False)
|
||||
|
||||
async def open(self) -> None:
|
||||
await self._pool
|
||||
pass
|
||||
|
||||
async def close(self) -> None:
|
||||
await self._pool.close()
|
||||
await self._engine.dispose()
|
||||
|
||||
@asynccontextmanager
|
||||
async def connection(self, wait: float | None = None) -> AsyncIterator[Connection]:
|
||||
async def session(self) -> AsyncIterator[DatabaseSession]:
|
||||
try:
|
||||
async with self._pool.acquire(timeout=wait or self._acquire_timeout) as connection:
|
||||
yield connection
|
||||
except FAILURES as error:
|
||||
async with self._sessions() as session:
|
||||
yield session
|
||||
except Exception as error:
|
||||
if not unavailable(error):
|
||||
raise
|
||||
raise Unavailable("PostgreSQL недоступен") from error
|
||||
|
||||
async def ping(self) -> None:
|
||||
async with self.connection(PING_TIMEOUT_SECONDS) as connection:
|
||||
await connection.fetchval("SELECT 1", timeout=PING_TIMEOUT_SECONDS)
|
||||
try:
|
||||
async with asyncio.timeout(PING_TIMEOUT_SECONDS):
|
||||
async with self.session() as session:
|
||||
await session.execute(select(1))
|
||||
except TimeoutError as error:
|
||||
raise Unavailable("PostgreSQL недоступен") from error
|
||||
|
||||
|
||||
class PostgresUnitOfWork:
|
||||
__slots__ = ("_committed", "_connection", "_database", "_events", "_transaction", "seen")
|
||||
__slots__ = ("_committed", "_database", "_events", "_session", "seen")
|
||||
|
||||
def __init__(self, database: Database) -> None:
|
||||
self._database = database
|
||||
self._connection: Connection | None = None
|
||||
self._transaction: Any = None
|
||||
self._session: DatabaseSession | None = None
|
||||
self._committed = False
|
||||
self._events: list[DomainEvent] = []
|
||||
self.seen: list[EventSource] = []
|
||||
|
||||
@property
|
||||
def connection(self) -> Connection:
|
||||
if self._connection is None:
|
||||
def session(self) -> DatabaseSession:
|
||||
if self._session is None:
|
||||
raise RuntimeError("репозиторий используется вне транзакции")
|
||||
return self._connection
|
||||
return self._session
|
||||
|
||||
@asynccontextmanager
|
||||
async def transaction(self) -> AsyncIterator[None]:
|
||||
async with self._database.connection() as connection:
|
||||
self._connection = connection
|
||||
self._transaction = connection.transaction()
|
||||
await self._transaction.start()
|
||||
async with self._database.session() as session:
|
||||
self._session = session
|
||||
self._committed = False
|
||||
mark = len(self._events)
|
||||
try:
|
||||
@@ -101,12 +122,11 @@ class PostgresUnitOfWork:
|
||||
finally:
|
||||
if not self._committed:
|
||||
del self._events[mark:]
|
||||
await self._transaction.rollback()
|
||||
self.seen.clear()
|
||||
self._connection = None
|
||||
self._session = None
|
||||
|
||||
async def commit(self) -> None:
|
||||
await self._transaction.commit()
|
||||
await self.session.commit()
|
||||
self._committed = True
|
||||
for source in self.seen:
|
||||
self._events.extend(source.collect_events())
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
from threading import Event
|
||||
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
|
||||
DRAINING = Event()
|
||||
|
||||
|
||||
class DatabaseReadiness:
|
||||
__slots__ = ("_database", "_draining")
|
||||
|
||||
def __init__(self, database: Database, draining: Event = DRAINING) -> None:
|
||||
self._database = database
|
||||
self._draining = draining
|
||||
|
||||
async def check(self) -> None:
|
||||
if self._draining.is_set():
|
||||
raise Unavailable("Реплика выходит из ротации")
|
||||
await self._database.ping()
|
||||
Reference in New Issue
Block a user