Carry over the lab 5 solution
Bring the application, own tests, Dockerfile, toolchain, compose stack,
HAProxy, k6, RustFS and RabbitMQ configuration, migrations, hooks,
scenario scripts and the CI job from the lab 5 solution commit 64d5c67,
keep the lab 5 Makefile targets on top of the unchanged skeleton
targets, and append the lab 5 solution variables to the skeleton
.env.example. The package and the application follow the contract
version 1.6.0, and the image, the throwaway test containers and the
broker vhost description are tagged lab6 so they do not collide with a
lab 5 stand on the same host.
This is the starting point of the lab 6 cycle: lint, own tests and the
offline skeleton check pass before any lab 6 change.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
a0d3947710
commit
5ae3d77152
@@ -0,0 +1,37 @@
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from dishka import make_async_container
|
||||
|
||||
from messenger.attachments.domain.jobs import ReplayResult
|
||||
from messenger.attachments.entrypoints.admin import rendered, run
|
||||
from messenger.attachments.entrypoints.ioc import AdminProvider
|
||||
from messenger.attachments.entrypoints.journal import LOG_FIELDS, subscribe_journal
|
||||
from messenger.shared.application.messagebus import EventBus
|
||||
from messenger.shared.config import PlatformSettings
|
||||
from messenger.shared.entrypoints.ioc import PlatformProvider
|
||||
from messenger.shared.infrastructure.logging import PLATFORM_FIELDS, StructlogLogger
|
||||
|
||||
|
||||
async def serve(argv: list[str]) -> int:
|
||||
platform = PlatformSettings()
|
||||
logger = StructlogLogger(level=platform.log_level, allowed_fields=PLATFORM_FIELDS | LOG_FIELDS)
|
||||
container = make_async_container(PlatformProvider(platform, logger), AdminProvider())
|
||||
bus = await container.get(EventBus)
|
||||
subscribe_journal(bus, logger)
|
||||
bus.start()
|
||||
try:
|
||||
report = await run(container, argv)
|
||||
finally:
|
||||
await bus.stop()
|
||||
await container.close()
|
||||
sys.stdout.write(rendered(report) + "\n")
|
||||
return int(report.get("result") == ReplayResult.NOT_FOUND)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
sys.exit(asyncio.run(serve(sys.argv[1:])))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,5 @@
|
||||
from messenger.shared.application.messagebus import CommandBus
|
||||
|
||||
|
||||
class AttachmentsCommandBus(CommandBus):
|
||||
__slots__ = ()
|
||||
@@ -0,0 +1,49 @@
|
||||
from collections.abc import AsyncIterator
|
||||
from dataclasses import dataclass
|
||||
from datetime import timedelta
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.attachments.domain.jobs import Job
|
||||
from messenger.shared.application.commands import Command
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class UploadAttachment(Command):
|
||||
owner_id: UUID
|
||||
chat_id: UUID
|
||||
filename: str | None
|
||||
content_type: str | None
|
||||
body: AsyncIterator[bytes]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SweepAbandonedUploads(Command):
|
||||
grace: timedelta
|
||||
limit: int
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ProcessJob(Command):
|
||||
job: Job
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PublishOutbox(Command):
|
||||
limit: int
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RecoverExpiredLeases(Command):
|
||||
limit: int
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CleanStaging(Command):
|
||||
limit: int
|
||||
retention: timedelta
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ReplayAttachment(Command):
|
||||
attachment_id: UUID
|
||||
operator: str
|
||||
@@ -0,0 +1,2 @@
|
||||
class ObjectMissingError(Exception):
|
||||
pass
|
||||
@@ -0,0 +1,158 @@
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator
|
||||
from hashlib import sha256
|
||||
|
||||
from messenger.attachments.application.commands import SweepAbandonedUploads, UploadAttachment
|
||||
from messenger.attachments.application.ports import (
|
||||
AttachmentsUnitOfWork,
|
||||
ChatMembership,
|
||||
ImageInspector,
|
||||
ObjectStorage,
|
||||
)
|
||||
from messenger.attachments.domain.errors import ChatNotFound, PayloadTooLarge
|
||||
from messenger.attachments.domain.jobs import Job
|
||||
from messenger.attachments.domain.models import Attachment, AttachmentStatus
|
||||
from messenger.attachments.domain.values import Filename, ImageKind
|
||||
from messenger.shared.application.ports import Clock, IdGenerator, Logger
|
||||
|
||||
|
||||
class UploadSlots(asyncio.Semaphore):
|
||||
pass
|
||||
|
||||
|
||||
async def read_limited(body: AsyncIterator[bytes], limit: int) -> tuple[bytes, str]:
|
||||
chunks: list[bytes] = []
|
||||
digest = sha256()
|
||||
size = 0
|
||||
async for chunk in body:
|
||||
size += len(chunk)
|
||||
if size > limit:
|
||||
raise PayloadTooLarge(f"тело больше {limit} байт")
|
||||
digest.update(chunk)
|
||||
chunks.append(chunk)
|
||||
return b"".join(chunks), digest.hexdigest()
|
||||
|
||||
|
||||
async def drop(
|
||||
uow: AttachmentsUnitOfWork, storage: ObjectStorage, attachment: Attachment, reason: str
|
||||
) -> None:
|
||||
if attachment.staging_key is not None:
|
||||
await storage.delete(attachment.staging_key)
|
||||
attachment.discard(reason)
|
||||
await uow.attachments.remove(attachment)
|
||||
await uow.commit()
|
||||
|
||||
|
||||
class UploadAttachmentHandler:
|
||||
__slots__ = (
|
||||
"_clock",
|
||||
"_ids",
|
||||
"_images",
|
||||
"_limit",
|
||||
"_logger",
|
||||
"_membership",
|
||||
"_pipeline_version",
|
||||
"_slots",
|
||||
"_storage",
|
||||
"_uow",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
uow: AttachmentsUnitOfWork,
|
||||
membership: ChatMembership,
|
||||
images: ImageInspector,
|
||||
storage: ObjectStorage,
|
||||
*,
|
||||
clock: Clock,
|
||||
ids: IdGenerator,
|
||||
limit: int,
|
||||
slots: UploadSlots,
|
||||
logger: Logger,
|
||||
pipeline_version: int = 1,
|
||||
) -> None:
|
||||
self._uow = uow
|
||||
self._membership = membership
|
||||
self._images = images
|
||||
self._storage = storage
|
||||
self._clock = clock
|
||||
self._ids = ids
|
||||
self._limit = limit
|
||||
self._slots = slots
|
||||
self._logger = logger
|
||||
self._pipeline_version = pipeline_version
|
||||
|
||||
async def __call__(self, command: UploadAttachment) -> Attachment:
|
||||
if not await self._membership.is_member(command.chat_id, command.owner_id):
|
||||
raise ChatNotFound("чат не найден")
|
||||
filename = Filename(command.filename or "")
|
||||
declared = ImageKind.declared(command.content_type)
|
||||
async with self._slots:
|
||||
attachment = await self._write(command, filename, declared)
|
||||
now = self._clock.now()
|
||||
attachment.enqueue(now)
|
||||
job = Job(self._ids.new_id(), attachment.id, self._pipeline_version, 1, now)
|
||||
try:
|
||||
async with self._uow.transaction():
|
||||
await self._uow.attachments.save(attachment)
|
||||
await self._uow.jobs.add(job)
|
||||
await self._uow.commit()
|
||||
except Exception:
|
||||
await self._compensate(attachment)
|
||||
raise
|
||||
return attachment
|
||||
|
||||
async def _write(
|
||||
self, command: UploadAttachment, filename: Filename, declared: ImageKind
|
||||
) -> Attachment:
|
||||
data, digest = await read_limited(command.body, self._limit)
|
||||
image = await self._images.inspect(data, declared)
|
||||
attachment = Attachment.stage(
|
||||
attachment_id=self._ids.new_id(),
|
||||
chat_id=command.chat_id,
|
||||
owner_id=command.owner_id,
|
||||
filename=filename,
|
||||
image=image,
|
||||
size_bytes=len(data),
|
||||
sha256=digest,
|
||||
now=self._clock.now(),
|
||||
)
|
||||
async with self._uow.transaction():
|
||||
await self._uow.attachments.add(attachment)
|
||||
await self._uow.commit()
|
||||
await self._storage.put(str(attachment.staging_key), data, attachment.content_type)
|
||||
return attachment
|
||||
|
||||
async def _compensate(self, staged: Attachment) -> None:
|
||||
try:
|
||||
async with self._uow.transaction():
|
||||
current = await self._uow.attachments.lock(staged.id)
|
||||
if current is None:
|
||||
await self._storage.delete(str(staged.staging_key))
|
||||
elif current.status is AttachmentStatus.PENDING:
|
||||
await drop(self._uow, self._storage, current, "compensation")
|
||||
except Exception as error:
|
||||
self._logger.warning(
|
||||
"attachment.compensation_failed",
|
||||
attachment_id=str(staged.id),
|
||||
error=type(error).__name__,
|
||||
)
|
||||
|
||||
|
||||
class SweepAbandonedUploadsHandler:
|
||||
__slots__ = ("_clock", "_storage", "_uow")
|
||||
|
||||
def __init__(self, uow: AttachmentsUnitOfWork, storage: ObjectStorage, clock: Clock) -> None:
|
||||
self._uow = uow
|
||||
self._storage = storage
|
||||
self._clock = clock
|
||||
|
||||
async def __call__(self, command: SweepAbandonedUploads) -> int:
|
||||
before = self._clock.now() - command.grace
|
||||
for swept in range(command.limit):
|
||||
async with self._uow.transaction():
|
||||
abandoned = await self._uow.attachments.next_abandoned(before)
|
||||
if abandoned is None:
|
||||
return swept
|
||||
await drop(self._uow, self._storage, abandoned, "abandoned")
|
||||
return command.limit
|
||||
@@ -0,0 +1,301 @@
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
from hashlib import sha256
|
||||
|
||||
from messenger.attachments.application.commands import (
|
||||
CleanStaging,
|
||||
ProcessJob,
|
||||
PublishOutbox,
|
||||
RecoverExpiredLeases,
|
||||
ReplayAttachment,
|
||||
)
|
||||
from messenger.attachments.application.ports import (
|
||||
AttachmentsUnitOfWork,
|
||||
Faults,
|
||||
Jitter,
|
||||
JobPublisher,
|
||||
ObjectStorage,
|
||||
VariantRenderer,
|
||||
)
|
||||
from messenger.attachments.domain.errors import LeaseLost, UnreadableImage
|
||||
from messenger.attachments.domain.events import AttachmentReplayRequested, JobSettled
|
||||
from messenger.attachments.domain.jobs import (
|
||||
Claim,
|
||||
FailureCode,
|
||||
Job,
|
||||
Lease,
|
||||
Outcome,
|
||||
ReplayResult,
|
||||
RetryPolicy,
|
||||
)
|
||||
from messenger.attachments.domain.models import Attachment, AttachmentStatus, original_key
|
||||
from messenger.attachments.domain.variants import Variant, variant_key
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.application.ports import IdGenerator
|
||||
|
||||
TRANSIENT_ERROR = "transient_error"
|
||||
STALL_AFTER_CLAIM = "stall_after_claim"
|
||||
AFTER_COMMIT_BEFORE_PUBLISH = "after_commit_before_publish"
|
||||
AFTER_PUBLISH_BEFORE_CONFIRM = "after_publish_before_confirm"
|
||||
AFTER_CLAIM = "after_claim_before_side_effect"
|
||||
AFTER_S3_WRITE = "after_s3_write_before_commit"
|
||||
AFTER_COMMIT_BEFORE_ACK = "after_commit_before_ack"
|
||||
RENEWALS = 3
|
||||
|
||||
|
||||
def settled(
|
||||
job: Job,
|
||||
outcome: Outcome,
|
||||
*,
|
||||
error_code: str | None = None,
|
||||
delay_seconds: float | None = None,
|
||||
) -> JobSettled:
|
||||
return JobSettled(
|
||||
job_id=job.id,
|
||||
attachment_id=job.attachment_id,
|
||||
pipeline_version=job.pipeline_version,
|
||||
attempt=job.attempt,
|
||||
outcome=outcome.value,
|
||||
error_code=error_code,
|
||||
delay_seconds=delay_seconds,
|
||||
)
|
||||
|
||||
|
||||
class ProcessJobHandler:
|
||||
__slots__ = ("_faults", "_ids", "_jitter", "_lease", "_policy", "_renderer", "_storage", "_uow")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
uow: AttachmentsUnitOfWork,
|
||||
storage: ObjectStorage,
|
||||
renderer: VariantRenderer,
|
||||
faults: Faults,
|
||||
*,
|
||||
ids: IdGenerator,
|
||||
jitter: Jitter,
|
||||
policy: RetryPolicy,
|
||||
lease: timedelta,
|
||||
) -> None:
|
||||
self._uow = uow
|
||||
self._storage = storage
|
||||
self._renderer = renderer
|
||||
self._faults = faults
|
||||
self._ids = ids
|
||||
self._jitter = jitter
|
||||
self._policy = policy
|
||||
self._lease = lease
|
||||
|
||||
async def __call__(self, command: ProcessJob) -> Outcome:
|
||||
async with self._uow.transaction():
|
||||
claim = await self._uow.jobs.claim(command.job, self._ids.new_id(), self._lease)
|
||||
if claim is None:
|
||||
await self._uow.jobs.note(command.job, Outcome.DUPLICATE)
|
||||
self._uow.record(settled(command.job, Outcome.DUPLICATE))
|
||||
await self._uow.commit()
|
||||
if claim is None:
|
||||
return Outcome.DUPLICATE
|
||||
await self._faults.reach(AFTER_CLAIM)
|
||||
await self._faults.reach(STALL_AFTER_CLAIM)
|
||||
try:
|
||||
variants = await self._held(claim)
|
||||
except LeaseLost:
|
||||
return await self._fenced(claim.lease)
|
||||
except UnreadableImage as error:
|
||||
return await self._fail(claim.lease, FailureCode.INVALID_IMAGE, error)
|
||||
except Unavailable as error:
|
||||
return await self._retry(claim.lease, error)
|
||||
except Exception as error:
|
||||
return await self._fail(claim.lease, FailureCode.PROCESSING_FAILED, error)
|
||||
await self._faults.reach(AFTER_S3_WRITE)
|
||||
outcome = await self._complete(claim.lease, variants)
|
||||
await self._faults.reach(AFTER_COMMIT_BEFORE_ACK)
|
||||
return outcome
|
||||
|
||||
async def _held(self, claim: Claim) -> list[Variant]:
|
||||
await self._renew(claim.lease)
|
||||
work = asyncio.ensure_future(self._produce(claim))
|
||||
try:
|
||||
while not work.done():
|
||||
await asyncio.wait({work}, timeout=self._lease.total_seconds() / RENEWALS)
|
||||
if not work.done():
|
||||
await self._renew(claim.lease)
|
||||
except BaseException:
|
||||
work.cancel()
|
||||
await asyncio.wait({work})
|
||||
raise
|
||||
return work.result()
|
||||
|
||||
async def _renew(self, lease: Lease) -> None:
|
||||
async with self._uow.transaction():
|
||||
held = await self._uow.jobs.renew(lease, self._lease)
|
||||
await self._uow.commit()
|
||||
if not held:
|
||||
raise LeaseLost("аренду задания забрал другой держатель")
|
||||
|
||||
async def _produce(self, claim: Claim) -> list[Variant]:
|
||||
job = claim.lease.job
|
||||
await self._faults.reach(TRANSIENT_ERROR)
|
||||
data = await self._storage.read(claim.source_key)
|
||||
renditions = await self._renderer.render(data, job.pipeline_version)
|
||||
if claim.staged:
|
||||
await self._storage.copy(claim.source_key, original_key(job.attachment_id))
|
||||
variants: list[Variant] = []
|
||||
for rendition in renditions:
|
||||
digest = sha256(rendition.data).hexdigest()
|
||||
key = variant_key(
|
||||
job.attachment_id, job.pipeline_version, rendition.name, digest, rendition.extension
|
||||
)
|
||||
await self._storage.put(key, rendition.data, rendition.content_type)
|
||||
variants.append(
|
||||
Variant(
|
||||
name=rendition.name,
|
||||
content_type=rendition.content_type,
|
||||
size_bytes=len(rendition.data),
|
||||
width=rendition.width,
|
||||
height=rendition.height,
|
||||
sha256=digest,
|
||||
object_key=key,
|
||||
)
|
||||
)
|
||||
return variants
|
||||
|
||||
async def _complete(self, lease: Lease, variants: list[Variant]) -> Outcome:
|
||||
async with self._uow.transaction():
|
||||
outcome = await self._uow.jobs.complete(
|
||||
lease, variants, original_key(lease.job.attachment_id)
|
||||
)
|
||||
self._uow.record(settled(lease.job, outcome))
|
||||
await self._uow.commit()
|
||||
return outcome
|
||||
|
||||
async def _fenced(self, lease: Lease) -> Outcome:
|
||||
async with self._uow.transaction():
|
||||
await self._uow.jobs.note(lease.job, Outcome.FENCED)
|
||||
self._uow.record(settled(lease.job, Outcome.FENCED))
|
||||
await self._uow.commit()
|
||||
return Outcome.FENCED
|
||||
|
||||
async def _retry(self, lease: Lease, error: Exception) -> Outcome:
|
||||
delay = self._policy.delay(lease.job.attempt, self._jitter.spread())
|
||||
if delay is None:
|
||||
return await self._fail(lease, FailureCode.RETRY_EXHAUSTED, error)
|
||||
async with self._uow.transaction():
|
||||
job = await self._uow.jobs.reschedule(
|
||||
lease, delay, Outcome.RESCHEDULED, type(error).__name__
|
||||
)
|
||||
outcome = Outcome.FENCED if job is None else Outcome.RESCHEDULED
|
||||
if job is None:
|
||||
await self._uow.jobs.note(lease.job, outcome)
|
||||
self._uow.record(settled(lease.job, outcome, delay_seconds=delay.total_seconds()))
|
||||
await self._uow.commit()
|
||||
return outcome
|
||||
|
||||
async def _fail(self, lease: Lease, code: FailureCode, error: Exception) -> Outcome:
|
||||
async with self._uow.transaction():
|
||||
done = await self._uow.jobs.fail(lease, code, type(error).__name__)
|
||||
outcome = Outcome.FAILED if done else Outcome.FENCED
|
||||
if not done:
|
||||
await self._uow.jobs.note(lease.job, outcome)
|
||||
self._uow.record(settled(lease.job, outcome, error_code=code.value))
|
||||
await self._uow.commit()
|
||||
return outcome
|
||||
|
||||
|
||||
class PublishOutboxHandler:
|
||||
__slots__ = ("_faults", "_publisher", "_uow")
|
||||
|
||||
def __init__(self, uow: AttachmentsUnitOfWork, publisher: JobPublisher, faults: Faults) -> None:
|
||||
self._uow = uow
|
||||
self._publisher = publisher
|
||||
self._faults = faults
|
||||
|
||||
async def __call__(self, command: PublishOutbox) -> int:
|
||||
failure: Unavailable | None = None
|
||||
published: list[int] = []
|
||||
async with self._uow.transaction():
|
||||
for entry in await self._uow.outbox.pending(command.limit):
|
||||
await self._faults.reach(AFTER_COMMIT_BEFORE_PUBLISH)
|
||||
try:
|
||||
await self._publisher.publish(entry.job_id, entry.body)
|
||||
except Unavailable as error:
|
||||
failure = error
|
||||
break
|
||||
await self._faults.reach(AFTER_PUBLISH_BEFORE_CONFIRM)
|
||||
published.append(entry.id)
|
||||
if published:
|
||||
await self._uow.outbox.published(published)
|
||||
await self._uow.commit()
|
||||
if failure is not None:
|
||||
raise failure
|
||||
return len(published)
|
||||
|
||||
|
||||
class RecoverExpiredLeasesHandler:
|
||||
__slots__ = ("_policy", "_uow")
|
||||
|
||||
def __init__(self, uow: AttachmentsUnitOfWork, policy: RetryPolicy) -> None:
|
||||
self._uow = uow
|
||||
self._policy = policy
|
||||
|
||||
async def __call__(self, command: RecoverExpiredLeases) -> int:
|
||||
async with self._uow.transaction():
|
||||
leases = await self._uow.jobs.expired(command.limit)
|
||||
for lease in leases:
|
||||
if self._policy.exhausted(lease.job.attempt):
|
||||
await self._uow.jobs.fail(
|
||||
lease, FailureCode.RETRY_EXHAUSTED, Outcome.LEASE_EXPIRED.value
|
||||
)
|
||||
outcome = Outcome.FAILED
|
||||
else:
|
||||
await self._uow.jobs.reschedule(
|
||||
lease, timedelta(0), Outcome.LEASE_EXPIRED, Outcome.LEASE_EXPIRED.value
|
||||
)
|
||||
outcome = Outcome.LEASE_EXPIRED
|
||||
self._uow.record(settled(lease.job, outcome))
|
||||
await self._uow.commit()
|
||||
return len(leases)
|
||||
|
||||
|
||||
class CleanStagingHandler:
|
||||
__slots__ = ("_storage", "_uow")
|
||||
|
||||
def __init__(self, uow: AttachmentsUnitOfWork, storage: ObjectStorage) -> None:
|
||||
self._uow = uow
|
||||
self._storage = storage
|
||||
|
||||
async def __call__(self, command: CleanStaging) -> int:
|
||||
async with self._uow.transaction():
|
||||
staged = await self._uow.attachments.staged(command.limit, command.retention)
|
||||
await asyncio.gather(*(self._storage.delete(item.key) for item in staged))
|
||||
await self._uow.attachments.unstage([item.attachment_id for item in staged])
|
||||
await self._uow.commit()
|
||||
return len(staged)
|
||||
|
||||
|
||||
class ReplayAttachmentHandler:
|
||||
__slots__ = ("_uow",)
|
||||
|
||||
def __init__(self, uow: AttachmentsUnitOfWork) -> None:
|
||||
self._uow = uow
|
||||
|
||||
async def __call__(self, command: ReplayAttachment) -> ReplayResult:
|
||||
async with self._uow.transaction():
|
||||
attachment = await self._uow.attachments.lock(command.attachment_id)
|
||||
result = await self._replay(attachment, command.operator)
|
||||
if attachment is not None and result is not ReplayResult.REPLAYED:
|
||||
await self._uow.jobs.note_replay(attachment.id, command.operator, result.value)
|
||||
self._uow.record(
|
||||
AttachmentReplayRequested(command.attachment_id, command.operator, result.value)
|
||||
)
|
||||
await self._uow.commit()
|
||||
return result
|
||||
|
||||
async def _replay(self, attachment: Attachment | None, operator: str) -> ReplayResult:
|
||||
if attachment is None:
|
||||
return ReplayResult.NOT_FOUND
|
||||
if attachment.status is not AttachmentStatus.FAILED:
|
||||
return ReplayResult.NOOP
|
||||
if attachment.staging_key is None:
|
||||
return ReplayResult.EXPIRED
|
||||
job = await self._uow.jobs.replay(attachment, operator)
|
||||
return ReplayResult.NOOP if job is None else ReplayResult.REPLAYED
|
||||
@@ -0,0 +1,155 @@
|
||||
from collections.abc import AsyncIterator, Sequence
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Protocol, runtime_checkable
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.attachments.domain.jobs import Claim, FailedJob, FailureCode, Job, Lease, Outcome
|
||||
from messenger.attachments.domain.models import Attachment
|
||||
from messenger.attachments.domain.values import ImageInfo, ImageKind
|
||||
from messenger.attachments.domain.variants import Variant
|
||||
from messenger.shared.application.ports import UnitOfWork
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ObjectContent:
|
||||
size: int
|
||||
chunks: AsyncIterator[bytes]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Rendition:
|
||||
name: str
|
||||
content_type: str
|
||||
extension: str
|
||||
data: bytes
|
||||
width: int
|
||||
height: int
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class OutboxEntry:
|
||||
id: int
|
||||
job_id: UUID
|
||||
body: bytes
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class StagedObject:
|
||||
attachment_id: UUID
|
||||
key: str
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ObjectStorage(Protocol):
|
||||
async def put(self, key: str, data: bytes, content_type: str) -> None: ...
|
||||
|
||||
async def open(self, key: str) -> ObjectContent: ...
|
||||
|
||||
async def read(self, key: str) -> bytes: ...
|
||||
|
||||
async def copy(self, source: str, target: str) -> None: ...
|
||||
|
||||
async def delete(self, key: str) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ImageInspector(Protocol):
|
||||
async def inspect(self, data: bytes, declared: ImageKind) -> ImageInfo: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class VariantRenderer(Protocol):
|
||||
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class JobPublisher(Protocol):
|
||||
async def publish(self, job_id: UUID, body: bytes) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class Faults(Protocol):
|
||||
async def reach(self, point: str) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class Jitter(Protocol):
|
||||
def spread(self) -> float: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ChatMembership(Protocol):
|
||||
async def is_member(self, chat_id: UUID, user_id: UUID) -> bool: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class AttachmentRepository(Protocol):
|
||||
async def add(self, attachment: Attachment) -> None: ...
|
||||
|
||||
async def save(self, attachment: Attachment) -> None: ...
|
||||
|
||||
async def lock(self, attachment_id: UUID) -> Attachment | None: ...
|
||||
|
||||
async def next_abandoned(self, before: datetime) -> Attachment | None: ...
|
||||
|
||||
async def remove(self, attachment: Attachment) -> None: ...
|
||||
|
||||
async def staged(self, limit: int, retention: timedelta) -> list[StagedObject]: ...
|
||||
|
||||
async def unstage(self, attachment_ids: Sequence[UUID]) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class JobRepository(Protocol):
|
||||
async def add(self, job: Job) -> None: ...
|
||||
|
||||
async def claim(self, job: Job, token: UUID, lease: timedelta) -> Claim | None: ...
|
||||
|
||||
async def complete(
|
||||
self, lease: Lease, variants: Sequence[Variant], original_key: str
|
||||
) -> Outcome: ...
|
||||
|
||||
async def reschedule(
|
||||
self, lease: Lease, delay: timedelta, kind: Outcome, error: str
|
||||
) -> Job | None: ...
|
||||
|
||||
async def renew(self, lease: Lease, duration: timedelta) -> bool: ...
|
||||
|
||||
async def fail(self, lease: Lease, code: FailureCode, error: str) -> bool: ...
|
||||
|
||||
async def note(self, job: Job, kind: Outcome) -> None: ...
|
||||
|
||||
async def expired(self, limit: int) -> list[Lease]: ...
|
||||
|
||||
async def replay(self, attachment: Attachment, operator: str) -> Job | None: ...
|
||||
|
||||
async def note_replay(self, attachment_id: UUID, operator: str, result: str) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class OutboxRepository(Protocol):
|
||||
async def pending(self, limit: int) -> list[OutboxEntry]: ...
|
||||
|
||||
async def published(self, entry_ids: Sequence[int]) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class AttachmentsUnitOfWork(UnitOfWork, Protocol):
|
||||
@property
|
||||
def attachments(self) -> AttachmentRepository: ...
|
||||
|
||||
@property
|
||||
def jobs(self) -> JobRepository: ...
|
||||
|
||||
@property
|
||||
def outbox(self) -> OutboxRepository: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class AttachmentDirectory(Protocol):
|
||||
async def visible(self, attachment_id: UUID) -> Attachment | None: ...
|
||||
|
||||
async def failed_among(self, chat_id: UUID, attachment_ids: Sequence[UUID]) -> bool: ...
|
||||
|
||||
async def failed_jobs(self, limit: int) -> list[FailedJob]: ...
|
||||
@@ -0,0 +1,57 @@
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.attachments.application.errors import ObjectMissingError
|
||||
from messenger.attachments.application.ports import (
|
||||
AttachmentDirectory,
|
||||
ChatMembership,
|
||||
ObjectContent,
|
||||
ObjectStorage,
|
||||
)
|
||||
from messenger.attachments.domain.errors import AttachmentNotFound, AttachmentNotReady
|
||||
from messenger.attachments.domain.models import Attachment
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
ORIGINAL = "original"
|
||||
|
||||
|
||||
class GetAttachment:
|
||||
__slots__ = ("_attachments", "_membership")
|
||||
|
||||
def __init__(self, attachments: AttachmentDirectory, membership: ChatMembership) -> None:
|
||||
self._attachments = attachments
|
||||
self._membership = membership
|
||||
|
||||
async def __call__(self, attachment_id: UUID, user_id: UUID) -> Attachment:
|
||||
attachment = await self._attachments.visible(attachment_id)
|
||||
if attachment is None or not await self._membership.is_member(attachment.chat_id, user_id):
|
||||
raise AttachmentNotFound("вложение не найдено")
|
||||
return attachment
|
||||
|
||||
|
||||
class OpenAttachment:
|
||||
__slots__ = ("_get", "_logger", "_storage")
|
||||
|
||||
def __init__(self, get: GetAttachment, storage: ObjectStorage, logger: Logger) -> None:
|
||||
self._get = get
|
||||
self._storage = storage
|
||||
self._logger = logger
|
||||
|
||||
async def __call__(
|
||||
self, attachment_id: UUID, user_id: UUID, variant: str = ORIGINAL
|
||||
) -> tuple[str, ObjectContent]:
|
||||
attachment = await self._get(attachment_id, user_id)
|
||||
if not attachment.ready:
|
||||
raise AttachmentNotReady("вложение ещё не обработано или обработка не удалась")
|
||||
if variant == ORIGINAL:
|
||||
key, content_type = attachment.original_key, attachment.content_type
|
||||
else:
|
||||
found = attachment.variant(variant)
|
||||
if found is None:
|
||||
raise AttachmentNotFound("у вложения нет такого варианта")
|
||||
key, content_type = found.object_key, found.content_type
|
||||
try:
|
||||
content = await self._storage.open(str(key))
|
||||
except ObjectMissingError as error:
|
||||
self._logger.warning("attachment.object_missing", attachment_id=str(attachment.id))
|
||||
raise AttachmentNotFound("вложение не найдено") from error
|
||||
return content_type, content
|
||||
@@ -0,0 +1,49 @@
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import Field, SecretStr
|
||||
|
||||
from messenger.shared.config import Settings
|
||||
|
||||
UPLOAD_BYTES_MAX = 10_485_760
|
||||
IMAGE_PIXELS_MAX = 40_000_000
|
||||
|
||||
|
||||
class AttachmentsSettings(Settings):
|
||||
s3_endpoint: str = "http://s3:9000"
|
||||
s3_region: str = "us-east-1"
|
||||
s3_bucket: str = Field(default="messenger-attachments", min_length=3)
|
||||
s3_access_key_id: SecretStr = Field(min_length=3)
|
||||
s3_secret_access_key: SecretStr = Field(min_length=8)
|
||||
s3_connect_timeout_seconds: float = Field(default=1.0, gt=0, le=30)
|
||||
s3_read_timeout_seconds: float = Field(default=2.0, gt=0, le=60)
|
||||
s3_max_attempts: int = Field(default=2, ge=1, le=5)
|
||||
max_upload_bytes: int = Field(default=UPLOAD_BYTES_MAX, ge=1, le=UPLOAD_BYTES_MAX)
|
||||
max_image_pixels: int = Field(default=IMAGE_PIXELS_MAX, ge=1, le=IMAGE_PIXELS_MAX)
|
||||
image_check_concurrency: int = Field(default=2, ge=1, le=16)
|
||||
upload_concurrency: int = Field(default=3, ge=1, le=64)
|
||||
upload_grace_seconds: int = Field(default=900, ge=60)
|
||||
upload_sweep_interval_seconds: float = Field(default=30.0, gt=0)
|
||||
upload_sweep_batch: int = Field(default=100, ge=1, le=10_000)
|
||||
|
||||
|
||||
class PipelineSettings(AttachmentsSettings):
|
||||
broker_url: SecretStr = Field(min_length=8)
|
||||
worker_concurrency: int = Field(default=2, ge=1, le=32)
|
||||
job_max_attempts: int = Field(default=5, ge=1, le=20)
|
||||
job_timeout_seconds: float = Field(default=60.0, ge=1, le=290)
|
||||
job_backoff_base_seconds: float = Field(default=2.0, gt=0, le=60)
|
||||
job_backoff_cap_seconds: float = Field(default=60.0, gt=0, le=3600)
|
||||
staging_retention_seconds: int = Field(default=86_400, ge=1)
|
||||
outbox_poll_seconds: float = Field(default=1.0, gt=0, le=10)
|
||||
outbox_batch: int = Field(default=50, ge=1, le=1000)
|
||||
sweep_interval_seconds: float = Field(default=5.0, gt=0, le=300)
|
||||
sweep_batch: int = Field(default=100, ge=1, le=10_000)
|
||||
publish_timeout_seconds: float = Field(default=5.0, gt=0, le=60)
|
||||
shutdown_grace_seconds: float = Field(default=5.0, gt=0, le=9)
|
||||
heartbeat_file: Path | None = None
|
||||
heartbeat_interval_seconds: float = Field(default=5.0, gt=0, le=10)
|
||||
render_timeout_seconds: float = Field(default=30.0, gt=0, le=120)
|
||||
render_memory_mb: int = Field(default=448, ge=0, le=8192)
|
||||
render_tasks_per_child: int = Field(default=100, ge=1, le=10_000)
|
||||
fault_point: str = ""
|
||||
fault_stall_seconds: float = Field(default=15.0, ge=0, le=300)
|
||||
@@ -0,0 +1,45 @@
|
||||
from messenger.shared.domain.errors import DomainError
|
||||
|
||||
|
||||
class AttachmentError(DomainError):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidFilename(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class UnsupportedImage(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class PayloadTooLarge(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class ChatNotFound(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class AttachmentNotFound(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class AttachmentNotReady(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class UploadAborted(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class UnreadableImage(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class ImageTooDemanding(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class LeaseLost(AttachmentError):
|
||||
pass
|
||||
@@ -0,0 +1,41 @@
|
||||
from dataclasses import dataclass, field
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AttachmentQueued(DomainEvent):
|
||||
attachment_id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
size_bytes: int
|
||||
name: str = field(init=False, default="attachment.queued")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AttachmentDiscarded(DomainEvent):
|
||||
attachment_id: UUID
|
||||
chat_id: UUID
|
||||
reason: str
|
||||
name: str = field(init=False, default="attachment.discarded")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class JobSettled(DomainEvent):
|
||||
job_id: UUID
|
||||
attachment_id: UUID
|
||||
pipeline_version: int
|
||||
attempt: int
|
||||
outcome: str
|
||||
error_code: str | None = None
|
||||
delay_seconds: float | None = None
|
||||
name: str = field(init=False, default="job.settled")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AttachmentReplayRequested(DomainEvent):
|
||||
attachment_id: UUID
|
||||
operator: str
|
||||
result: str
|
||||
name: str = field(init=False, default="attachment.replay_requested")
|
||||
@@ -0,0 +1,95 @@
|
||||
from dataclasses import dataclass, replace
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
JOB_TYPE = "attachment.process.v1"
|
||||
SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
class FailureCode(StrEnum):
|
||||
INVALID_IMAGE = "invalid_image"
|
||||
PROCESSING_FAILED = "processing_failed"
|
||||
RETRY_EXHAUSTED = "retry_exhausted"
|
||||
|
||||
|
||||
class ReplayResult(StrEnum):
|
||||
REPLAYED = "replayed"
|
||||
NOOP = "noop"
|
||||
EXPIRED = "expired"
|
||||
NOT_FOUND = "not_found"
|
||||
|
||||
|
||||
class Outcome(StrEnum):
|
||||
DONE = "done"
|
||||
DUPLICATE = "duplicate_noop"
|
||||
FENCED = "fenced"
|
||||
SUPERSEDED = "superseded"
|
||||
RESCHEDULED = "retry_scheduled"
|
||||
LEASE_EXPIRED = "lease_expired"
|
||||
FAILED = "failed"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Job:
|
||||
id: UUID
|
||||
attachment_id: UUID
|
||||
pipeline_version: int
|
||||
attempt: int
|
||||
created_at: datetime
|
||||
|
||||
def payload(self) -> dict[str, Any]:
|
||||
stamp = self.created_at.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
return {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"job_id": str(self.id),
|
||||
"type": JOB_TYPE,
|
||||
"attachment_id": str(self.attachment_id),
|
||||
"pipeline_version": self.pipeline_version,
|
||||
"attempt": self.attempt,
|
||||
"created_at": stamp,
|
||||
}
|
||||
|
||||
def retried(self, attempt: int) -> Job:
|
||||
return replace(self, attempt=attempt)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Lease:
|
||||
job: Job
|
||||
token: UUID
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Claim:
|
||||
lease: Lease
|
||||
source_key: str
|
||||
staged: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class FailedJob:
|
||||
job_id: UUID
|
||||
attachment_id: UUID
|
||||
pipeline_version: int
|
||||
attempt: int
|
||||
error_code: str | None
|
||||
last_error: str | None
|
||||
failed_at: datetime
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RetryPolicy:
|
||||
max_attempts: int
|
||||
base_seconds: float
|
||||
cap_seconds: float
|
||||
|
||||
def exhausted(self, attempt: int) -> bool:
|
||||
return attempt >= self.max_attempts
|
||||
|
||||
def delay(self, attempt: int, spread: float) -> timedelta | None:
|
||||
if self.exhausted(attempt):
|
||||
return None
|
||||
ceiling = min(self.cap_seconds, self.base_seconds * 2 ** (attempt - 1))
|
||||
return timedelta(seconds=ceiling / 2 * (1 + spread))
|
||||
@@ -0,0 +1,103 @@
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.attachments.domain.events import AttachmentDiscarded, AttachmentQueued
|
||||
from messenger.attachments.domain.values import Filename, ImageInfo
|
||||
from messenger.attachments.domain.variants import Variant
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
STAGING_PREFIX = "staging/"
|
||||
ORIGINALS_PREFIX = "originals/"
|
||||
|
||||
|
||||
class AttachmentStatus(StrEnum):
|
||||
PENDING = "pending"
|
||||
QUEUED = "queued"
|
||||
PROCESSING = "processing"
|
||||
READY = "ready"
|
||||
FAILED = "failed"
|
||||
|
||||
|
||||
def original_key(attachment_id: UUID) -> str:
|
||||
return f"{ORIGINALS_PREFIX}{attachment_id}"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Attachment:
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
filename: Filename
|
||||
image: ImageInfo
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: AttachmentStatus
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
staging_key: str | None = None
|
||||
original_key: str | None = None
|
||||
published_version: int = 0
|
||||
error_code: str | None = None
|
||||
variants: tuple[Variant, ...] = ()
|
||||
_events: list[DomainEvent] = field(init=False, default_factory=list, repr=False, compare=False)
|
||||
|
||||
@classmethod
|
||||
def stage(
|
||||
cls,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
chat_id: UUID,
|
||||
owner_id: UUID,
|
||||
filename: Filename,
|
||||
image: ImageInfo,
|
||||
size_bytes: int,
|
||||
sha256: str,
|
||||
now: datetime,
|
||||
) -> Attachment:
|
||||
return cls(
|
||||
id=attachment_id,
|
||||
chat_id=chat_id,
|
||||
owner_id=owner_id,
|
||||
filename=filename,
|
||||
image=image,
|
||||
size_bytes=size_bytes,
|
||||
sha256=sha256,
|
||||
status=AttachmentStatus.PENDING,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
staging_key=f"{STAGING_PREFIX}{attachment_id}",
|
||||
)
|
||||
|
||||
@property
|
||||
def content_type(self) -> str:
|
||||
return self.image.kind.value
|
||||
|
||||
@property
|
||||
def ready(self) -> bool:
|
||||
return self.status is AttachmentStatus.READY
|
||||
|
||||
def variant(self, name: str) -> Variant | None:
|
||||
return next((variant for variant in self.variants if variant.name == name), None)
|
||||
|
||||
def enqueue(self, now: datetime) -> None:
|
||||
self.status = AttachmentStatus.QUEUED
|
||||
self.updated_at = max(now, self.created_at)
|
||||
self._events.append(
|
||||
AttachmentQueued(
|
||||
attachment_id=self.id,
|
||||
chat_id=self.chat_id,
|
||||
owner_id=self.owner_id,
|
||||
size_bytes=self.size_bytes,
|
||||
)
|
||||
)
|
||||
|
||||
def discard(self, reason: str) -> None:
|
||||
self._events.append(
|
||||
AttachmentDiscarded(attachment_id=self.id, chat_id=self.chat_id, reason=reason)
|
||||
)
|
||||
|
||||
def collect_events(self) -> list[DomainEvent]:
|
||||
events, self._events = self._events, []
|
||||
return events
|
||||
@@ -0,0 +1,46 @@
|
||||
import unicodedata
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
|
||||
from messenger.attachments.domain.errors import InvalidFilename, UnsupportedImage
|
||||
|
||||
FILENAME_MAX = 255
|
||||
SEPARATORS = frozenset("/\\")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Filename:
|
||||
value: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.value.strip():
|
||||
raise InvalidFilename("параметр filename обязателен и не может быть пустым")
|
||||
if len(self.value) > FILENAME_MAX:
|
||||
raise InvalidFilename(f"параметр filename длиннее {FILENAME_MAX} символов Unicode")
|
||||
if any(c in SEPARATORS or unicodedata.category(c) == "Cc" for c in self.value):
|
||||
raise InvalidFilename(
|
||||
"параметр filename содержит разделитель пути или управляющий символ"
|
||||
)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.value
|
||||
|
||||
|
||||
class ImageKind(StrEnum):
|
||||
PNG = "image/png"
|
||||
JPEG = "image/jpeg"
|
||||
|
||||
@classmethod
|
||||
def declared(cls, content_type: str | None) -> ImageKind:
|
||||
media = (content_type or "").partition(";")[0].strip().lower()
|
||||
try:
|
||||
return cls(media)
|
||||
except ValueError as error:
|
||||
raise UnsupportedImage("Content-Type должен быть image/png или image/jpeg") from error
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ImageInfo:
|
||||
kind: ImageKind
|
||||
width: int
|
||||
height: int
|
||||
@@ -0,0 +1,35 @@
|
||||
from dataclasses import dataclass
|
||||
from uuid import UUID
|
||||
|
||||
THUMBNAIL = "thumbnail"
|
||||
CROP = "crop"
|
||||
OPTIMIZED = "optimized"
|
||||
THUMBNAIL_BOX = 256
|
||||
CROP_SIDE = 128
|
||||
OPTIMIZED_BOX = 1280
|
||||
VARIANTS_PREFIX = "variants/"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Variant:
|
||||
name: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
width: int
|
||||
height: int
|
||||
sha256: str
|
||||
object_key: str
|
||||
|
||||
|
||||
def fit(width: int, height: int, box: int) -> tuple[int, int]:
|
||||
if max(width, height) <= box:
|
||||
return width, height
|
||||
if width >= height:
|
||||
return box, max(1, height * box // width)
|
||||
return max(1, width * box // height), box
|
||||
|
||||
|
||||
def variant_key(
|
||||
attachment_id: UUID, pipeline_version: int, name: str, sha256: str, extension: str
|
||||
) -> str:
|
||||
return f"{VARIANTS_PREFIX}{attachment_id}/{pipeline_version}/{name}-{sha256[:16]}.{extension}"
|
||||
@@ -0,0 +1,50 @@
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from dataclasses import asdict
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from dishka import AsyncContainer
|
||||
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import ReplayAttachment
|
||||
from messenger.attachments.application.ports import AttachmentDirectory
|
||||
from messenger.attachments.domain.jobs import ReplayResult
|
||||
|
||||
REGISTRY_LIMIT = 20
|
||||
|
||||
|
||||
def parser() -> argparse.ArgumentParser:
|
||||
root = argparse.ArgumentParser(
|
||||
prog="python -m messenger.admin", description="Реестр failed-заданий и явный replay"
|
||||
)
|
||||
commands = root.add_subparsers(dest="command", required=True)
|
||||
failed = commands.add_parser("failed", help="последние задания в failed")
|
||||
failed.add_argument("--limit", type=int, default=REGISTRY_LIMIT)
|
||||
replay = commands.add_parser("replay", help="вернуть failed-вложение в очередь")
|
||||
replay.add_argument("--attachment-id", type=UUID, required=True)
|
||||
replay.add_argument("--operator", default=os.environ.get("OPERATOR", "cli"))
|
||||
return root
|
||||
|
||||
|
||||
async def run(container: AsyncContainer, argv: list[str]) -> dict[str, Any]:
|
||||
args = parser().parse_args(argv)
|
||||
async with container() as scope:
|
||||
if args.command == "failed":
|
||||
directory = await scope.get(AttachmentDirectory)
|
||||
return {"failed": [asdict(job) for job in await directory.failed_jobs(args.limit)]}
|
||||
bus = await scope.get(AttachmentsCommandBus)
|
||||
result: ReplayResult = await bus.execute(
|
||||
ReplayAttachment(args.attachment_id, args.operator)
|
||||
)
|
||||
return {"result": result.value, "attachment_id": args.attachment_id, "operator": args.operator}
|
||||
|
||||
|
||||
def plain(value: object) -> str:
|
||||
return value.isoformat() if isinstance(value, datetime) else str(value)
|
||||
|
||||
|
||||
def rendered(report: dict[str, Any]) -> str:
|
||||
return json.dumps(report, default=plain, ensure_ascii=False)
|
||||
@@ -0,0 +1,20 @@
|
||||
from messenger.attachments.domain.errors import (
|
||||
AttachmentNotFound,
|
||||
AttachmentNotReady,
|
||||
ChatNotFound,
|
||||
InvalidFilename,
|
||||
PayloadTooLarge,
|
||||
UnsupportedImage,
|
||||
UploadAborted,
|
||||
)
|
||||
from messenger.shared.domain.errors import DomainError
|
||||
|
||||
ERROR_CODES: dict[type[DomainError], tuple[str, int]] = {
|
||||
InvalidFilename: ("invalid_request", 400),
|
||||
UploadAborted: ("invalid_request", 400),
|
||||
ChatNotFound: ("not_found", 404),
|
||||
AttachmentNotFound: ("not_found", 404),
|
||||
AttachmentNotReady: ("conflict", 409),
|
||||
PayloadTooLarge: ("payload_too_large", 413),
|
||||
UnsupportedImage: ("unsupported_media_type", 415),
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import asyncio
|
||||
from collections.abc import Awaitable, Callable
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
|
||||
class Heartbeat:
|
||||
__slots__ = ("_interval", "_logger", "_path", "_probe", "_task")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
path: Path | None,
|
||||
probe: Callable[[], Awaitable[bool]],
|
||||
interval: float,
|
||||
logger: Logger,
|
||||
) -> None:
|
||||
self._path = path
|
||||
self._probe = probe
|
||||
self._interval = interval
|
||||
self._logger = logger
|
||||
self._task: asyncio.Task[None] | None = None
|
||||
|
||||
def start(self) -> None:
|
||||
if self._path is not None:
|
||||
self._task = asyncio.create_task(self._run(self._path))
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._task is None:
|
||||
return
|
||||
self._task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await self._task
|
||||
self._task = None
|
||||
|
||||
async def _run(self, path: Path) -> None:
|
||||
while True:
|
||||
try:
|
||||
if await self._probe():
|
||||
await asyncio.to_thread(path.touch)
|
||||
except Exception as error:
|
||||
self._logger.warning("heartbeat.failed", error=type(error).__name__)
|
||||
await asyncio.sleep(self._interval)
|
||||
@@ -0,0 +1,77 @@
|
||||
import re
|
||||
from collections.abc import AsyncIterator
|
||||
from typing import Annotated
|
||||
from uuid import UUID
|
||||
|
||||
from dishka.integrations.fastapi import FromDishka, inject
|
||||
from fastapi import APIRouter, Query, Request, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import UploadAttachment
|
||||
from messenger.attachments.application.queries import GetAttachment, OpenAttachment
|
||||
from messenger.attachments.domain.errors import UploadAborted
|
||||
from messenger.attachments.entrypoints.schemas import AttachmentOut, VariantName
|
||||
from messenger.shared.entrypoints.actor import Actor
|
||||
|
||||
UPLOAD_PATH = re.compile(r"/api/v1/chats/[^/]+/attachments/?")
|
||||
CONTENT_HEADERS = {"X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store"}
|
||||
|
||||
uploads_router = APIRouter(prefix="/api/v1/chats/{chat_id}/attachments", tags=["attachments"])
|
||||
attachments_router = APIRouter(prefix="/api/v1/attachments", tags=["attachments"])
|
||||
|
||||
|
||||
async def body_of(request: Request) -> AsyncIterator[bytes]:
|
||||
try:
|
||||
async for chunk in request.stream():
|
||||
yield chunk
|
||||
except ClientDisconnect as error:
|
||||
raise UploadAborted("клиент оборвал загрузку до конца тела") from error
|
||||
|
||||
|
||||
@uploads_router.post("", status_code=status.HTTP_202_ACCEPTED)
|
||||
@inject
|
||||
async def upload_attachment(
|
||||
chat_id: UUID,
|
||||
actor: Actor,
|
||||
request: Request,
|
||||
bus: FromDishka[AttachmentsCommandBus],
|
||||
filename: Annotated[str | None, Query()] = None,
|
||||
) -> AttachmentOut:
|
||||
attachment = await bus.execute(
|
||||
UploadAttachment(
|
||||
owner_id=actor,
|
||||
chat_id=chat_id,
|
||||
filename=filename,
|
||||
content_type=request.headers.get("content-type"),
|
||||
body=body_of(request),
|
||||
)
|
||||
)
|
||||
return AttachmentOut.of(attachment)
|
||||
|
||||
|
||||
@attachments_router.get("/{attachment_id}")
|
||||
@inject
|
||||
async def read_attachment(
|
||||
attachment_id: UUID,
|
||||
actor: Actor,
|
||||
query: FromDishka[GetAttachment],
|
||||
) -> AttachmentOut:
|
||||
return AttachmentOut.of(await query(attachment_id, actor))
|
||||
|
||||
|
||||
@attachments_router.get("/{attachment_id}/content")
|
||||
@inject
|
||||
async def download_attachment(
|
||||
attachment_id: UUID,
|
||||
actor: Actor,
|
||||
query: FromDishka[OpenAttachment],
|
||||
variant: Annotated[VariantName, Query()] = "original",
|
||||
) -> StreamingResponse:
|
||||
content_type, content = await query(attachment_id, actor, variant)
|
||||
return StreamingResponse(
|
||||
content.chunks,
|
||||
media_type=content_type,
|
||||
headers={**CONTENT_HEADERS, "Content-Length": str(content.size)},
|
||||
)
|
||||
@@ -0,0 +1,268 @@
|
||||
from collections.abc import AsyncIterator, Iterator
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import timedelta
|
||||
|
||||
from dishka import Provider, Scope, provide
|
||||
from faststream.rabbit import RabbitBroker
|
||||
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import (
|
||||
CleanStaging,
|
||||
ProcessJob,
|
||||
PublishOutbox,
|
||||
RecoverExpiredLeases,
|
||||
ReplayAttachment,
|
||||
SweepAbandonedUploads,
|
||||
UploadAttachment,
|
||||
)
|
||||
from messenger.attachments.application.handlers import (
|
||||
SweepAbandonedUploadsHandler,
|
||||
UploadAttachmentHandler,
|
||||
UploadSlots,
|
||||
)
|
||||
from messenger.attachments.application.pipeline import (
|
||||
CleanStagingHandler,
|
||||
ProcessJobHandler,
|
||||
PublishOutboxHandler,
|
||||
RecoverExpiredLeasesHandler,
|
||||
ReplayAttachmentHandler,
|
||||
)
|
||||
from messenger.attachments.application.ports import (
|
||||
AttachmentDirectory,
|
||||
AttachmentsUnitOfWork,
|
||||
ChatMembership,
|
||||
Faults,
|
||||
ImageInspector,
|
||||
Jitter,
|
||||
JobPublisher,
|
||||
ObjectStorage,
|
||||
VariantRenderer,
|
||||
)
|
||||
from messenger.attachments.application.queries import GetAttachment, OpenAttachment
|
||||
from messenger.attachments.config import AttachmentsSettings, PipelineSettings
|
||||
from messenger.attachments.domain.jobs import RetryPolicy
|
||||
from messenger.attachments.infrastructure.faults import EnvironmentFaults
|
||||
from messenger.attachments.infrastructure.images import (
|
||||
PillowImageInspector,
|
||||
ProcessVariantRenderer,
|
||||
RenderLimits,
|
||||
)
|
||||
from messenger.attachments.infrastructure.jitter import RandomJitter
|
||||
from messenger.attachments.infrastructure.postgres import (
|
||||
PostgresAttachmentDirectory,
|
||||
PostgresAttachmentsUnitOfWork,
|
||||
)
|
||||
from messenger.attachments.infrastructure.rabbitmq import RabbitJobPublisher
|
||||
from messenger.attachments.infrastructure.s3 import S3ObjectStorage, s3_client
|
||||
from messenger.shared.application.commands import Command
|
||||
from messenger.shared.application.messagebus import CommandHandler
|
||||
from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator, Logger
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def object_storage(settings: AttachmentsSettings) -> AsyncIterator[ObjectStorage]:
|
||||
async with s3_client(
|
||||
endpoint=settings.s3_endpoint,
|
||||
region=settings.s3_region,
|
||||
access_key_id=settings.s3_access_key_id.get_secret_value(),
|
||||
secret_access_key=settings.s3_secret_access_key.get_secret_value(),
|
||||
connect_timeout=settings.s3_connect_timeout_seconds,
|
||||
read_timeout=settings.s3_read_timeout_seconds,
|
||||
max_attempts=settings.s3_max_attempts,
|
||||
) as client:
|
||||
yield S3ObjectStorage(client, settings.s3_bucket)
|
||||
|
||||
|
||||
class AttachmentsProvider(Provider):
|
||||
def __init__(self, settings: AttachmentsSettings) -> None:
|
||||
super().__init__()
|
||||
self._settings = settings
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def settings(self) -> AttachmentsSettings:
|
||||
return self._settings
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
async def storage(self, settings: AttachmentsSettings) -> AsyncIterator[ObjectStorage]:
|
||||
async with object_storage(settings) as storage:
|
||||
yield storage
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def images(self, settings: AttachmentsSettings) -> ImageInspector:
|
||||
return PillowImageInspector(settings.max_image_pixels, settings.image_check_concurrency)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def slots(self, settings: AttachmentsSettings) -> UploadSlots:
|
||||
return UploadSlots(settings.upload_concurrency)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def directory(self, database: Database) -> AttachmentDirectory:
|
||||
return PostgresAttachmentDirectory(database)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def unit_of_work(self, database: Database) -> AttachmentsUnitOfWork:
|
||||
return PostgresAttachmentsUnitOfWork(database)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def attachment(
|
||||
self, directory: AttachmentDirectory, membership: ChatMembership
|
||||
) -> GetAttachment:
|
||||
return GetAttachment(directory, membership)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def content(
|
||||
self, attachment: GetAttachment, storage: ObjectStorage, logger: Logger
|
||||
) -> OpenAttachment:
|
||||
return OpenAttachment(attachment, storage, logger)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def command_bus(
|
||||
self,
|
||||
uow: AttachmentsUnitOfWork,
|
||||
membership: ChatMembership,
|
||||
images: ImageInspector,
|
||||
storage: ObjectStorage,
|
||||
publisher: EventPublisher,
|
||||
clock: Clock,
|
||||
ids: IdGenerator,
|
||||
settings: AttachmentsSettings,
|
||||
slots: UploadSlots,
|
||||
logger: Logger,
|
||||
) -> AttachmentsCommandBus:
|
||||
upload = UploadAttachmentHandler(
|
||||
uow,
|
||||
membership,
|
||||
images,
|
||||
storage,
|
||||
clock=clock,
|
||||
ids=ids,
|
||||
limit=settings.max_upload_bytes,
|
||||
slots=slots,
|
||||
logger=logger,
|
||||
)
|
||||
handlers: dict[type[Command], CommandHandler] = {
|
||||
UploadAttachment: upload,
|
||||
SweepAbandonedUploads: SweepAbandonedUploadsHandler(uow, storage, clock),
|
||||
}
|
||||
return AttachmentsCommandBus(handlers, uow, publisher)
|
||||
|
||||
|
||||
class PipelineProvider(Provider):
|
||||
def __init__(self, settings: PipelineSettings) -> None:
|
||||
super().__init__()
|
||||
self._settings = settings
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def settings(self) -> PipelineSettings:
|
||||
return self._settings
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
async def storage(self, settings: PipelineSettings) -> AsyncIterator[ObjectStorage]:
|
||||
async with object_storage(settings) as storage:
|
||||
yield storage
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def policy(self, settings: PipelineSettings) -> RetryPolicy:
|
||||
return RetryPolicy(
|
||||
settings.job_max_attempts,
|
||||
settings.job_backoff_base_seconds,
|
||||
settings.job_backoff_cap_seconds,
|
||||
)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def faults(self, settings: PipelineSettings, logger: Logger) -> Faults:
|
||||
return EnvironmentFaults(settings.fault_point, logger, settings.fault_stall_seconds)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def unit_of_work(self, database: Database) -> AttachmentsUnitOfWork:
|
||||
return PostgresAttachmentsUnitOfWork(database)
|
||||
|
||||
|
||||
class WorkerProvider(Provider):
|
||||
@provide(scope=Scope.APP)
|
||||
def renderer(self, settings: PipelineSettings) -> Iterator[VariantRenderer]:
|
||||
renderer = ProcessVariantRenderer(
|
||||
RenderLimits(settings.max_upload_bytes, settings.max_image_pixels),
|
||||
concurrency=settings.worker_concurrency,
|
||||
timeout=settings.render_timeout_seconds,
|
||||
memory_bytes=settings.render_memory_mb << 20,
|
||||
tasks_per_child=settings.render_tasks_per_child,
|
||||
)
|
||||
yield renderer
|
||||
renderer.close()
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def jitter(self) -> Jitter:
|
||||
return RandomJitter()
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def command_bus(
|
||||
self,
|
||||
uow: AttachmentsUnitOfWork,
|
||||
storage: ObjectStorage,
|
||||
renderer: VariantRenderer,
|
||||
faults: Faults,
|
||||
publisher: EventPublisher,
|
||||
ids: IdGenerator,
|
||||
jitter: Jitter,
|
||||
policy: RetryPolicy,
|
||||
settings: PipelineSettings,
|
||||
) -> AttachmentsCommandBus:
|
||||
process = ProcessJobHandler(
|
||||
uow,
|
||||
storage,
|
||||
renderer,
|
||||
faults,
|
||||
ids=ids,
|
||||
jitter=jitter,
|
||||
policy=policy,
|
||||
lease=timedelta(seconds=settings.job_timeout_seconds),
|
||||
)
|
||||
return AttachmentsCommandBus({ProcessJob: process}, uow, publisher)
|
||||
|
||||
|
||||
class RelayProvider(Provider):
|
||||
def __init__(self, broker: RabbitBroker) -> None:
|
||||
super().__init__()
|
||||
self._broker = broker
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def publisher(self, settings: PipelineSettings) -> JobPublisher:
|
||||
return RabbitJobPublisher(self._broker, settings.publish_timeout_seconds)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def command_bus(
|
||||
self,
|
||||
uow: AttachmentsUnitOfWork,
|
||||
storage: ObjectStorage,
|
||||
jobs: JobPublisher,
|
||||
faults: Faults,
|
||||
publisher: EventPublisher,
|
||||
policy: RetryPolicy,
|
||||
) -> AttachmentsCommandBus:
|
||||
handlers: dict[type[Command], CommandHandler] = {
|
||||
PublishOutbox: PublishOutboxHandler(uow, jobs, faults),
|
||||
RecoverExpiredLeases: RecoverExpiredLeasesHandler(uow, policy),
|
||||
CleanStaging: CleanStagingHandler(uow, storage),
|
||||
}
|
||||
return AttachmentsCommandBus(handlers, uow, publisher)
|
||||
|
||||
|
||||
class AdminProvider(Provider):
|
||||
@provide(scope=Scope.APP)
|
||||
def directory(self, database: Database) -> AttachmentDirectory:
|
||||
return PostgresAttachmentDirectory(database)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def unit_of_work(self, database: Database) -> AttachmentsUnitOfWork:
|
||||
return PostgresAttachmentsUnitOfWork(database)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def command_bus(
|
||||
self, uow: AttachmentsUnitOfWork, publisher: EventPublisher
|
||||
) -> AttachmentsCommandBus:
|
||||
handlers: dict[type[Command], CommandHandler] = {
|
||||
ReplayAttachment: ReplayAttachmentHandler(uow)
|
||||
}
|
||||
return AttachmentsCommandBus(handlers, uow, publisher)
|
||||
@@ -0,0 +1,78 @@
|
||||
from messenger.attachments.domain.events import (
|
||||
AttachmentDiscarded,
|
||||
AttachmentQueued,
|
||||
AttachmentReplayRequested,
|
||||
JobSettled,
|
||||
)
|
||||
from messenger.shared.application.messagebus import EventBus
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
LOG_FIELDS = frozenset(
|
||||
{
|
||||
"attachment_id",
|
||||
"chat_id",
|
||||
"actor_id",
|
||||
"size_bytes",
|
||||
"count",
|
||||
"job_id",
|
||||
"attempt",
|
||||
"pipeline_version",
|
||||
"outcome",
|
||||
"error_code",
|
||||
"delay_seconds",
|
||||
"operator",
|
||||
"result",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class AttachmentsJournal:
|
||||
__slots__ = ("_logger",)
|
||||
|
||||
def __init__(self, logger: Logger) -> None:
|
||||
self._logger = logger
|
||||
|
||||
async def on_attachment_queued(self, event: AttachmentQueued) -> None:
|
||||
self._logger.info(
|
||||
"audit.attachment_queued",
|
||||
attachment_id=str(event.attachment_id),
|
||||
chat_id=str(event.chat_id),
|
||||
actor_id=str(event.owner_id),
|
||||
size_bytes=event.size_bytes,
|
||||
)
|
||||
|
||||
async def on_attachment_discarded(self, event: AttachmentDiscarded) -> None:
|
||||
self._logger.info(
|
||||
"audit.attachment_discarded",
|
||||
attachment_id=str(event.attachment_id),
|
||||
chat_id=str(event.chat_id),
|
||||
reason=event.reason,
|
||||
)
|
||||
|
||||
async def on_job_settled(self, event: JobSettled) -> None:
|
||||
self._logger.info(
|
||||
"audit.job_settled",
|
||||
job_id=str(event.job_id),
|
||||
attachment_id=str(event.attachment_id),
|
||||
pipeline_version=event.pipeline_version,
|
||||
attempt=event.attempt,
|
||||
outcome=event.outcome,
|
||||
error_code=event.error_code,
|
||||
delay_seconds=event.delay_seconds,
|
||||
)
|
||||
|
||||
async def on_replay_requested(self, event: AttachmentReplayRequested) -> None:
|
||||
self._logger.info(
|
||||
"audit.attachment_replay",
|
||||
attachment_id=str(event.attachment_id),
|
||||
operator=event.operator,
|
||||
result=event.result,
|
||||
)
|
||||
|
||||
|
||||
def subscribe_journal(bus: EventBus, logger: Logger) -> None:
|
||||
journal = AttachmentsJournal(logger)
|
||||
bus.subscribe(AttachmentQueued, journal.on_attachment_queued)
|
||||
bus.subscribe(AttachmentDiscarded, journal.on_attachment_discarded)
|
||||
bus.subscribe(JobSettled, journal.on_job_settled)
|
||||
bus.subscribe(AttachmentReplayRequested, journal.on_replay_requested)
|
||||
@@ -0,0 +1,73 @@
|
||||
import asyncio
|
||||
from collections.abc import Sequence
|
||||
from contextlib import suppress
|
||||
from datetime import timedelta
|
||||
|
||||
from dishka import AsyncContainer
|
||||
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import (
|
||||
CleanStaging,
|
||||
PublishOutbox,
|
||||
RecoverExpiredLeases,
|
||||
)
|
||||
from messenger.attachments.config import PipelineSettings
|
||||
from messenger.shared.application.commands import Command
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
|
||||
class Relay:
|
||||
__slots__ = ("_container", "_logger", "_settings", "_tasks")
|
||||
|
||||
def __init__(
|
||||
self, container: AsyncContainer, settings: PipelineSettings, logger: Logger
|
||||
) -> None:
|
||||
self._container = container
|
||||
self._settings = settings
|
||||
self._logger = logger
|
||||
self._tasks: list[asyncio.Task[None]] = []
|
||||
|
||||
def start(self) -> None:
|
||||
settings = self._settings
|
||||
loops: tuple[tuple[float, Sequence[Command]], ...] = (
|
||||
(settings.outbox_poll_seconds, (PublishOutbox(settings.outbox_batch),)),
|
||||
(
|
||||
settings.sweep_interval_seconds,
|
||||
(
|
||||
RecoverExpiredLeases(settings.sweep_batch),
|
||||
CleanStaging(
|
||||
settings.sweep_batch, timedelta(seconds=settings.staging_retention_seconds)
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
self._tasks = [asyncio.create_task(self._every(*loop)) for loop in loops]
|
||||
|
||||
async def stop(self) -> None:
|
||||
for task in self._tasks:
|
||||
task.cancel()
|
||||
for task in self._tasks:
|
||||
with suppress(asyncio.CancelledError):
|
||||
await task
|
||||
self._tasks = []
|
||||
|
||||
async def run(self, command: Command) -> int:
|
||||
async with self._container() as scope:
|
||||
bus = await scope.get(AttachmentsCommandBus)
|
||||
return await bus.execute(command)
|
||||
|
||||
async def _every(self, interval: float, commands: Sequence[Command]) -> None:
|
||||
while True:
|
||||
for command in commands:
|
||||
try:
|
||||
done = await self.run(command)
|
||||
except Exception as error:
|
||||
self._logger.warning(
|
||||
"relay.pass_failed",
|
||||
reason=type(command).__name__,
|
||||
error=type(error).__name__,
|
||||
)
|
||||
continue
|
||||
if done:
|
||||
self._logger.info("relay.pass", reason=type(command).__name__, count=done)
|
||||
await asyncio.sleep(interval)
|
||||
@@ -0,0 +1,84 @@
|
||||
from datetime import datetime
|
||||
from typing import Annotated, Literal
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import AwareDatetime, BaseModel, ConfigDict, Field
|
||||
|
||||
from messenger.attachments.domain.jobs import Job
|
||||
from messenger.attachments.domain.models import Attachment
|
||||
from messenger.attachments.domain.variants import Variant
|
||||
|
||||
type VariantName = Literal["original", "thumbnail", "crop", "optimized"]
|
||||
|
||||
|
||||
class VariantOut(BaseModel):
|
||||
name: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
width: int
|
||||
height: int
|
||||
sha256: str
|
||||
|
||||
@classmethod
|
||||
def of(cls, variant: Variant) -> VariantOut:
|
||||
return cls(
|
||||
name=variant.name,
|
||||
content_type=variant.content_type,
|
||||
size_bytes=variant.size_bytes,
|
||||
width=variant.width,
|
||||
height=variant.height,
|
||||
sha256=variant.sha256,
|
||||
)
|
||||
|
||||
|
||||
class AttachmentOut(BaseModel):
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: str
|
||||
variants: list[VariantOut]
|
||||
error_code: str | None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
@classmethod
|
||||
def of(cls, attachment: Attachment) -> AttachmentOut:
|
||||
return cls(
|
||||
id=attachment.id,
|
||||
chat_id=attachment.chat_id,
|
||||
owner_id=attachment.owner_id,
|
||||
filename=attachment.filename.value,
|
||||
content_type=attachment.content_type,
|
||||
size_bytes=attachment.size_bytes,
|
||||
sha256=attachment.sha256,
|
||||
status=attachment.status.value,
|
||||
variants=[VariantOut.of(variant) for variant in attachment.variants],
|
||||
error_code=attachment.error_code,
|
||||
created_at=attachment.created_at,
|
||||
updated_at=attachment.updated_at,
|
||||
)
|
||||
|
||||
|
||||
class JobMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", frozen=True)
|
||||
|
||||
schema_version: Literal[1]
|
||||
job_id: UUID
|
||||
type: Literal["attachment.process.v1"]
|
||||
attachment_id: UUID
|
||||
pipeline_version: Annotated[int, Field(ge=1)]
|
||||
attempt: Annotated[int, Field(ge=1)]
|
||||
created_at: AwareDatetime
|
||||
traceparent: Annotated[
|
||||
str | None, Field(pattern=r"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$")
|
||||
] = None
|
||||
tracestate: Annotated[str | None, Field(max_length=512)] = None
|
||||
|
||||
def job(self) -> Job:
|
||||
return Job(
|
||||
self.job_id, self.attachment_id, self.pipeline_version, self.attempt, self.created_at
|
||||
)
|
||||
@@ -0,0 +1,53 @@
|
||||
import asyncio
|
||||
from contextlib import suppress
|
||||
from datetime import timedelta
|
||||
|
||||
from dishka import AsyncContainer
|
||||
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import SweepAbandonedUploads
|
||||
from messenger.attachments.config import AttachmentsSettings
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
|
||||
class UploadSweeper:
|
||||
__slots__ = ("_command", "_container", "_interval", "_logger", "_task")
|
||||
|
||||
def __init__(
|
||||
self, container: AsyncContainer, settings: AttachmentsSettings, logger: Logger
|
||||
) -> None:
|
||||
self._container = container
|
||||
self._logger = logger
|
||||
self._interval = settings.upload_sweep_interval_seconds
|
||||
self._command = SweepAbandonedUploads(
|
||||
grace=timedelta(seconds=settings.upload_grace_seconds),
|
||||
limit=settings.upload_sweep_batch,
|
||||
)
|
||||
self._task: asyncio.Task[None] | None = None
|
||||
|
||||
def start(self) -> None:
|
||||
self._task = asyncio.create_task(self._run())
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._task is None:
|
||||
return
|
||||
self._task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await self._task
|
||||
self._task = None
|
||||
|
||||
async def sweep(self) -> int:
|
||||
async with self._container() as scope:
|
||||
bus = await scope.get(AttachmentsCommandBus)
|
||||
return await bus.execute(self._command)
|
||||
|
||||
async def _run(self) -> None:
|
||||
while True:
|
||||
await asyncio.sleep(self._interval)
|
||||
try:
|
||||
swept = await self.sweep()
|
||||
except Exception as error:
|
||||
self._logger.warning("attachments.sweep_failed", error=type(error).__name__)
|
||||
continue
|
||||
if swept:
|
||||
self._logger.info("attachments.swept", count=swept)
|
||||
@@ -0,0 +1,50 @@
|
||||
import asyncio
|
||||
|
||||
from dishka import FromDishka
|
||||
from faststream import AckPolicy
|
||||
from faststream.rabbit import Channel, QueueType, RabbitBroker, RabbitQueue
|
||||
from faststream.rabbit.annotations import RabbitMessage
|
||||
from pydantic import ValidationError
|
||||
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import ProcessJob
|
||||
from messenger.attachments.entrypoints.schemas import JobMessage
|
||||
from messenger.attachments.infrastructure.rabbitmq import QUEUE
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
REQUEUE_DELAY_SECONDS = 1.0
|
||||
JOBS = RabbitQueue(QUEUE, queue_type=QueueType.QUORUM, declare=False)
|
||||
|
||||
|
||||
async def raw(message: RabbitMessage) -> bytes:
|
||||
return message.body
|
||||
|
||||
|
||||
async def handle_job(
|
||||
message: RabbitMessage,
|
||||
bus: FromDishka[AttachmentsCommandBus],
|
||||
logger: FromDishka[Logger],
|
||||
) -> None:
|
||||
try:
|
||||
job = JobMessage.model_validate_json(message.body).job()
|
||||
except ValidationError:
|
||||
logger.warning("job.rejected", reason="message does not match jobs.schema.json")
|
||||
await message.reject(requeue=False)
|
||||
return
|
||||
try:
|
||||
await bus.execute(ProcessJob(job))
|
||||
except Exception as error:
|
||||
logger.warning("job.requeued", job_id=str(job.id), error=type(error).__name__)
|
||||
await asyncio.sleep(REQUEUE_DELAY_SECONDS)
|
||||
await message.nack(requeue=True)
|
||||
return
|
||||
await message.ack()
|
||||
|
||||
|
||||
def subscribe(broker: RabbitBroker, concurrency: int) -> None:
|
||||
broker.subscriber(
|
||||
JOBS,
|
||||
channel=Channel(prefetch_count=concurrency),
|
||||
ack_policy=AckPolicy.MANUAL,
|
||||
decoder=raw,
|
||||
)(handle_job)
|
||||
@@ -0,0 +1,32 @@
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
|
||||
from messenger.attachments.application.pipeline import STALL_AFTER_CLAIM, TRANSIENT_ERROR
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
CRASH_EXIT_CODE = 137
|
||||
|
||||
|
||||
class EnvironmentFaults:
|
||||
__slots__ = ("_logger", "_point", "_stall_seconds")
|
||||
|
||||
def __init__(self, point: str, logger: Logger, stall_seconds: float = 0.0) -> None:
|
||||
self._point = point
|
||||
self._logger = logger
|
||||
self._stall_seconds = stall_seconds
|
||||
|
||||
async def reach(self, point: str) -> None:
|
||||
if not self._point or point != self._point:
|
||||
return
|
||||
self._logger.warning("fault.injected", reason=point)
|
||||
if point == TRANSIENT_ERROR:
|
||||
raise Unavailable("внедрённая временная ошибка")
|
||||
if point == STALL_AFTER_CLAIM:
|
||||
self._point = ""
|
||||
await asyncio.sleep(self._stall_seconds)
|
||||
return
|
||||
sys.stdout.flush()
|
||||
sys.stderr.flush()
|
||||
os._exit(CRASH_EXIT_CODE)
|
||||
@@ -0,0 +1,206 @@
|
||||
import asyncio
|
||||
import resource
|
||||
import sys
|
||||
import warnings
|
||||
from collections.abc import Callable
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from concurrent.futures.process import BrokenProcessPool
|
||||
from dataclasses import dataclass
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from messenger.attachments.application.ports import Rendition
|
||||
from messenger.attachments.domain.errors import (
|
||||
ImageTooDemanding,
|
||||
PayloadTooLarge,
|
||||
UnreadableImage,
|
||||
UnsupportedImage,
|
||||
)
|
||||
from messenger.attachments.domain.values import ImageInfo, ImageKind
|
||||
from messenger.attachments.domain.variants import (
|
||||
CROP,
|
||||
CROP_SIDE,
|
||||
OPTIMIZED,
|
||||
OPTIMIZED_BOX,
|
||||
THUMBNAIL,
|
||||
THUMBNAIL_BOX,
|
||||
fit,
|
||||
)
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
|
||||
KINDS = {"PNG": ImageKind.PNG, "JPEG": ImageKind.JPEG}
|
||||
BOMBS = (Image.DecompressionBombError, Image.DecompressionBombWarning)
|
||||
JPEG_SCALE = 8
|
||||
WIDE_MODES = frozenset({"I", "I;16", "I;16B", "I;16L", "I;16N"})
|
||||
ALPHA_MODES = frozenset({"LA", "La", "PA", "RGBa"})
|
||||
JPEG = {"quality": 85, "optimize": True}
|
||||
WEBP = {"quality": 80, "method": 4}
|
||||
ENCODINGS = {"JPEG": (ImageKind.JPEG.value, "jpg"), "WEBP": ("image/webp", "webp")}
|
||||
REDUCING_GAP = 3.0
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RenderLimits:
|
||||
max_bytes: int
|
||||
max_pixels: int
|
||||
|
||||
|
||||
class PillowImageInspector:
|
||||
__slots__ = ("_max_pixels", "_slots")
|
||||
|
||||
def __init__(self, max_pixels: int, concurrency: int) -> None:
|
||||
self._max_pixels = max_pixels
|
||||
self._slots = asyncio.Semaphore(concurrency)
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
|
||||
async def inspect(self, data: bytes, declared: ImageKind) -> ImageInfo:
|
||||
async with self._slots:
|
||||
return await asyncio.to_thread(self._inspect, data, declared)
|
||||
|
||||
def _inspect(self, data: bytes, declared: ImageKind) -> ImageInfo:
|
||||
try:
|
||||
image = Image.open(BytesIO(data), formats=tuple(KINDS))
|
||||
except BOMBS as error:
|
||||
raise PayloadTooLarge("изображение больше допустимого числа пикселей") from error
|
||||
except Exception as error:
|
||||
raise UnsupportedImage("содержимое не является изображением PNG или JPEG") from error
|
||||
with image:
|
||||
kind = KINDS[str(image.format)]
|
||||
width, height = image.size
|
||||
if kind is not declared:
|
||||
raise UnsupportedImage("содержимое не совпадает с заявленным Content-Type")
|
||||
if width * height > self._max_pixels:
|
||||
raise PayloadTooLarge("изображение больше допустимого числа пикселей")
|
||||
try:
|
||||
if kind is ImageKind.JPEG:
|
||||
image.draft("RGB", (width // JPEG_SCALE or 1, height // JPEG_SCALE or 1))
|
||||
image.load()
|
||||
else:
|
||||
image.verify()
|
||||
except Exception as error:
|
||||
raise UnsupportedImage("изображение повреждено или обрезано") from error
|
||||
return ImageInfo(kind, width, height)
|
||||
|
||||
|
||||
def flatten(image: Image.Image) -> Image.Image:
|
||||
if image.mode in WIDE_MODES:
|
||||
image = image.convert("I").point(lambda value: value / 256, "L")
|
||||
if image.mode == "P":
|
||||
image = image.convert("RGBA" if "transparency" in image.info else "RGB")
|
||||
if image.mode in ALPHA_MODES:
|
||||
image = image.convert("RGBA")
|
||||
if image.mode == "RGBA":
|
||||
background = Image.new("RGB", image.size, "white")
|
||||
background.paste(image, mask=image.getchannel("A"))
|
||||
return background
|
||||
return image if image.mode == "RGB" else image.convert("RGB")
|
||||
|
||||
|
||||
def scaled(image: Image.Image, size: tuple[int, int]) -> Image.Image:
|
||||
if size == image.size:
|
||||
return image
|
||||
return image.resize(size, Image.Resampling.LANCZOS, reducing_gap=REDUCING_GAP)
|
||||
|
||||
|
||||
def encoded(name: str, image: Image.Image, kind: str, **options: object) -> Rendition:
|
||||
buffer = BytesIO()
|
||||
image.save(buffer, kind, **options)
|
||||
content_type, extension = ENCODINGS[kind]
|
||||
return Rendition(name, content_type, extension, buffer.getvalue(), *image.size)
|
||||
|
||||
|
||||
def decoded(data: bytes, max_pixels: int) -> tuple[Image.Image, int, int]:
|
||||
try:
|
||||
image = Image.open(BytesIO(data), formats=tuple(KINDS))
|
||||
width, height = image.size
|
||||
if width * height > max_pixels:
|
||||
raise UnreadableImage("изображение больше допустимого числа пикселей")
|
||||
image.draft(None, fit(width, height, OPTIMIZED_BOX))
|
||||
stored = image.size
|
||||
ImageOps.exif_transpose(image, in_place=True)
|
||||
if image.size != stored:
|
||||
width, height = height, width
|
||||
return flatten(image), width, height
|
||||
except UnreadableImage, MemoryError:
|
||||
raise
|
||||
except Exception as error:
|
||||
raise UnreadableImage("изображение не декодируется") from error
|
||||
|
||||
|
||||
def render_variants(data: bytes, limits: RenderLimits) -> list[Rendition]:
|
||||
if len(data) > limits.max_bytes:
|
||||
raise ImageTooDemanding("оригинал больше допустимого размера")
|
||||
upright, width, height = decoded(data, limits.max_pixels)
|
||||
square = ImageOps.fit(upright, (CROP_SIDE, CROP_SIDE), Image.Resampling.LANCZOS)
|
||||
return [
|
||||
encoded(THUMBNAIL, scaled(upright, fit(width, height, THUMBNAIL_BOX)), "JPEG", **JPEG),
|
||||
encoded(CROP, square, "JPEG", **JPEG),
|
||||
encoded(OPTIMIZED, scaled(upright, fit(width, height, OPTIMIZED_BOX)), "WEBP", **WEBP),
|
||||
]
|
||||
|
||||
|
||||
def limit_memory(limit_bytes: int) -> None:
|
||||
if limit_bytes and sys.platform == "linux":
|
||||
resource.setrlimit(resource.RLIMIT_AS, (limit_bytes, limit_bytes))
|
||||
|
||||
|
||||
type Render = Callable[[bytes, RenderLimits], list[Rendition]]
|
||||
|
||||
|
||||
class ProcessVariantRenderer:
|
||||
__slots__ = ("_idle", "_limits", "_memory", "_render", "_tasks", "_timeout")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
limits: RenderLimits,
|
||||
*,
|
||||
concurrency: int,
|
||||
timeout: float,
|
||||
memory_bytes: int,
|
||||
tasks_per_child: int,
|
||||
render: Render = render_variants,
|
||||
) -> None:
|
||||
self._limits = limits
|
||||
self._timeout = timeout
|
||||
self._memory = memory_bytes
|
||||
self._tasks = tasks_per_child
|
||||
self._render = render
|
||||
self._idle: asyncio.Queue[ProcessPoolExecutor] = asyncio.Queue()
|
||||
for _ in range(concurrency):
|
||||
self._idle.put_nowait(self._spawn())
|
||||
|
||||
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]:
|
||||
pool = await self._idle.get()
|
||||
try:
|
||||
future = asyncio.wrap_future(pool.submit(self._render, data, self._limits))
|
||||
return await asyncio.wait_for(future, self._timeout)
|
||||
except TimeoutError as error:
|
||||
pool = self._replace(pool)
|
||||
raise ImageTooDemanding("рендер дольше допустимого времени") from error
|
||||
except MemoryError as error:
|
||||
raise ImageTooDemanding("рендер больше допустимой памяти") from error
|
||||
except BrokenProcessPool as error:
|
||||
pool = self._replace(pool)
|
||||
raise Unavailable("процесс рендера завершился аварийно") from error
|
||||
except asyncio.CancelledError:
|
||||
pool = self._replace(pool)
|
||||
raise
|
||||
finally:
|
||||
self._idle.put_nowait(pool)
|
||||
|
||||
def close(self) -> None:
|
||||
while not self._idle.empty():
|
||||
self._idle.get_nowait().kill_workers()
|
||||
|
||||
def _replace(self, pool: ProcessPoolExecutor) -> ProcessPoolExecutor:
|
||||
pool.kill_workers()
|
||||
return self._spawn()
|
||||
|
||||
def _spawn(self) -> ProcessPoolExecutor:
|
||||
return ProcessPoolExecutor(
|
||||
1,
|
||||
max_tasks_per_child=self._tasks,
|
||||
initializer=limit_memory,
|
||||
initargs=(self._memory,),
|
||||
)
|
||||
@@ -0,0 +1,10 @@
|
||||
from secrets import SystemRandom
|
||||
|
||||
SOURCE = SystemRandom()
|
||||
|
||||
|
||||
class RandomJitter:
|
||||
__slots__ = ()
|
||||
|
||||
def spread(self) -> float:
|
||||
return SOURCE.random()
|
||||
@@ -0,0 +1,461 @@
|
||||
import json
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime, timedelta
|
||||
from uuid import UUID
|
||||
|
||||
from asyncpg import ForeignKeyViolationError, Record
|
||||
|
||||
from messenger.attachments.application.ports import OutboxEntry, StagedObject
|
||||
from messenger.attachments.domain.errors import ChatNotFound
|
||||
from messenger.attachments.domain.jobs import Claim, FailedJob, FailureCode, Job, Lease, Outcome
|
||||
from messenger.attachments.domain.models import Attachment, AttachmentStatus
|
||||
from messenger.attachments.domain.values import Filename, ImageInfo, ImageKind
|
||||
from messenger.attachments.domain.variants import Variant
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.infrastructure.postgres import (
|
||||
Connection,
|
||||
Database,
|
||||
EventSource,
|
||||
PostgresUnitOfWork,
|
||||
)
|
||||
|
||||
INSERT = """
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
width, height, staging_key, status, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
|
||||
"""
|
||||
MARK = "UPDATE attachments SET status = $2, updated_at = $3 WHERE id = $1 AND status = 'pending'"
|
||||
COLUMNS = """
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.width,
|
||||
a.height, a.status, a.staging_key, a.original_key, a.published_version, a.error_code,
|
||||
a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
"""
|
||||
VISIBLE = """
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.width,
|
||||
a.height, a.status, a.staging_key, a.original_key, a.published_version, a.error_code,
|
||||
a.created_at, a.updated_at,
|
||||
(SELECT coalesce(jsonb_agg(jsonb_build_array(v.name, v.content_type, v.size_bytes, v.width,
|
||||
v.height, v.sha256, v.object_key)
|
||||
ORDER BY v.name), '[]')
|
||||
FROM attachment_variants v
|
||||
WHERE v.attachment_id = a.id AND v.pipeline_version = a.published_version) AS variants
|
||||
FROM attachments a
|
||||
WHERE a.id = $1 AND a.status <> 'pending'
|
||||
"""
|
||||
FAILED_AMONG = """
|
||||
SELECT EXISTS (SELECT 1 FROM attachments
|
||||
WHERE id = ANY($1::uuid[]) AND chat_id = $2 AND status = 'failed')
|
||||
"""
|
||||
LOCK = COLUMNS + "WHERE a.id = $1 FOR UPDATE"
|
||||
ABANDONED = (
|
||||
COLUMNS
|
||||
+ """WHERE a.status = 'pending' AND a.created_at < $1
|
||||
ORDER BY a.created_at LIMIT 1 FOR UPDATE SKIP LOCKED"""
|
||||
)
|
||||
REMOVE = "DELETE FROM attachments WHERE id = $1 AND status = 'pending'"
|
||||
STAGED = """
|
||||
SELECT id, staging_key FROM attachments
|
||||
WHERE staging_key IS NOT NULL
|
||||
AND (status = 'ready' OR (status = 'failed' AND updated_at < now() - make_interval(secs => $2)))
|
||||
ORDER BY updated_at LIMIT $1 FOR UPDATE SKIP LOCKED
|
||||
"""
|
||||
FAILED_JOBS = """
|
||||
SELECT j.job_id, j.attachment_id, j.pipeline_version, j.attempt, a.error_code, j.last_error,
|
||||
j.updated_at AS failed_at
|
||||
FROM jobs j JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.status = 'failed'
|
||||
ORDER BY j.updated_at DESC LIMIT $1
|
||||
"""
|
||||
UNSTAGE = "UPDATE attachments SET staging_key = NULL WHERE id = ANY($1::uuid[])"
|
||||
|
||||
ADD_JOB = """
|
||||
WITH job AS (
|
||||
INSERT INTO jobs (job_id, attachment_id, pipeline_version, status, attempt,
|
||||
created_at, updated_at)
|
||||
VALUES ($1, $2, $3, 'queued', $4, $5, $5)
|
||||
RETURNING job_id
|
||||
), box AS (
|
||||
INSERT INTO outbox (job_id, payload, available_at)
|
||||
SELECT job_id, $6::jsonb, now() FROM job
|
||||
)
|
||||
INSERT INTO job_events (job_id, attachment_id, kind, attempt)
|
||||
SELECT job_id, $2, 'enqueued', $4 FROM job
|
||||
"""
|
||||
CLAIM = """
|
||||
WITH claimed AS (
|
||||
UPDATE jobs
|
||||
SET status = 'processing', lease_token = $4, claims = claims + 1, updated_at = now(),
|
||||
lease_until = now() + make_interval(secs => $5)
|
||||
WHERE job_id = $1 AND attachment_id = $2 AND pipeline_version = $3
|
||||
AND ((status = 'queued' AND coalesce(next_attempt_at, '-infinity') <= now())
|
||||
OR (status = 'processing' AND lease_until < now()))
|
||||
RETURNING job_id, attachment_id, attempt, created_at
|
||||
), moved AS (
|
||||
UPDATE attachments a SET status = 'processing', updated_at = greatest(now(), a.created_at)
|
||||
FROM claimed c WHERE a.id = c.attachment_id AND a.status = 'queued'
|
||||
), audit AS (
|
||||
INSERT INTO job_events (job_id, attachment_id, kind, attempt)
|
||||
SELECT job_id, attachment_id, 'claimed', attempt FROM claimed
|
||||
)
|
||||
SELECT c.attempt, c.created_at, a.staging_key, a.original_key
|
||||
FROM claimed c JOIN attachments a ON a.id = c.attachment_id
|
||||
"""
|
||||
FINISH = """
|
||||
UPDATE jobs SET status = 'done', lease_token = NULL, lease_until = NULL, next_attempt_at = NULL,
|
||||
last_error = NULL, updated_at = now()
|
||||
WHERE job_id = $1 AND status = 'processing' AND lease_token = $2
|
||||
"""
|
||||
ADD_VARIANTS = """
|
||||
INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type,
|
||||
size_bytes, width, height, sha256, created_at)
|
||||
SELECT $1, $2, v.name, v.object_key, v.content_type, v.size_bytes, v.width, v.height, v.sha256,
|
||||
now()
|
||||
FROM unnest($3::text[], $4::text[], $5::text[], $6::bigint[], $7::int[], $8::int[], $9::text[])
|
||||
AS v (name, object_key, content_type, size_bytes, width, height, sha256)
|
||||
ON CONFLICT DO NOTHING
|
||||
"""
|
||||
PUBLISH = """
|
||||
UPDATE attachments
|
||||
SET status = 'ready', published_version = $2, error_code = NULL, original_key = $3,
|
||||
updated_at = greatest(now(), created_at)
|
||||
WHERE id = $1 AND published_version < $2
|
||||
"""
|
||||
SUPERSEDE = "UPDATE jobs SET status = 'superseded', updated_at = now() WHERE job_id = $1"
|
||||
RESCHEDULE = """
|
||||
WITH job AS (
|
||||
UPDATE jobs
|
||||
SET status = 'queued', attempt = attempt + 1, lease_token = NULL, lease_until = NULL,
|
||||
next_attempt_at = now() + make_interval(secs => $3), last_error = $4, updated_at = now()
|
||||
WHERE job_id = $1 AND status = 'processing' AND lease_token = $2
|
||||
RETURNING job_id, attachment_id, attempt, next_attempt_at
|
||||
), moved AS (
|
||||
UPDATE attachments a SET status = 'queued', updated_at = greatest(now(), a.created_at)
|
||||
FROM job WHERE a.id = job.attachment_id AND a.status = 'processing'
|
||||
), audit AS (
|
||||
INSERT INTO job_events (job_id, attachment_id, kind, attempt, detail)
|
||||
SELECT job_id, attachment_id, $5, attempt,
|
||||
jsonb_build_object('error', $4::text, 'next_attempt_at', next_attempt_at,
|
||||
'delay_seconds', $3::float8)
|
||||
FROM job
|
||||
)
|
||||
SELECT attempt, next_attempt_at FROM job
|
||||
"""
|
||||
RENEW = """
|
||||
UPDATE jobs SET lease_until = now() + make_interval(secs => $3), updated_at = now()
|
||||
WHERE job_id = $1 AND lease_token = $2 AND status = 'processing'
|
||||
"""
|
||||
ENQUEUE = "INSERT INTO outbox (job_id, payload, available_at) VALUES ($1, $2::jsonb, $3)"
|
||||
FAIL = """
|
||||
WITH job AS (
|
||||
UPDATE jobs SET status = 'failed', lease_token = NULL, lease_until = NULL, last_error = $4,
|
||||
updated_at = now()
|
||||
WHERE job_id = $1 AND status = 'processing' AND lease_token = $2
|
||||
RETURNING job_id, attachment_id, attempt
|
||||
), moved AS (
|
||||
UPDATE attachments a SET status = 'failed', error_code = $3,
|
||||
updated_at = greatest(now(), a.created_at)
|
||||
FROM job WHERE a.id = job.attachment_id AND a.status IN ('queued', 'processing')
|
||||
), audit AS (
|
||||
INSERT INTO job_events (job_id, attachment_id, kind, attempt, detail)
|
||||
SELECT job_id, attachment_id, 'failed', attempt,
|
||||
jsonb_build_object('error_code', $3::text, 'error', $4::text)
|
||||
FROM job
|
||||
)
|
||||
SELECT attempt FROM job
|
||||
"""
|
||||
NOTE = "INSERT INTO job_events (job_id, attachment_id, kind, attempt) VALUES ($1, $2, $3, $4)"
|
||||
EXPIRED = """
|
||||
SELECT job_id, attachment_id, pipeline_version, attempt, created_at, lease_token FROM jobs
|
||||
WHERE status = 'processing' AND lease_until < now()
|
||||
ORDER BY lease_until LIMIT $1 FOR UPDATE SKIP LOCKED
|
||||
"""
|
||||
REPLAY = """
|
||||
WITH job AS (
|
||||
UPDATE jobs
|
||||
SET status = 'queued', attempt = 1, lease_token = NULL, lease_until = NULL,
|
||||
next_attempt_at = NULL, last_error = NULL, updated_at = now()
|
||||
WHERE job_id = (SELECT job_id FROM jobs WHERE attachment_id = $1 AND status = 'failed'
|
||||
ORDER BY pipeline_version DESC LIMIT 1)
|
||||
RETURNING job_id, attachment_id, pipeline_version, created_at, updated_at
|
||||
), moved AS (
|
||||
UPDATE attachments a SET status = 'queued', error_code = NULL,
|
||||
updated_at = greatest(now(), a.created_at)
|
||||
FROM job WHERE a.id = job.attachment_id AND a.status = 'failed'
|
||||
), audit AS (
|
||||
INSERT INTO job_events (job_id, attachment_id, kind, attempt, detail)
|
||||
SELECT job_id, attachment_id, 'replayed', 1,
|
||||
jsonb_build_object('operator', $2::text, 'error_code', $3::text)
|
||||
FROM job
|
||||
)
|
||||
SELECT job_id, pipeline_version, created_at, updated_at FROM job
|
||||
"""
|
||||
NOTE_REPLAY = """
|
||||
INSERT INTO job_events (job_id, attachment_id, kind, attempt, detail)
|
||||
SELECT job_id, attachment_id, 'replay_noop', attempt,
|
||||
jsonb_build_object('operator', $2::text, 'result', $3::text)
|
||||
FROM jobs WHERE attachment_id = $1
|
||||
ORDER BY pipeline_version DESC LIMIT 1
|
||||
"""
|
||||
PENDING = """
|
||||
SELECT id, job_id, payload::text AS body FROM outbox
|
||||
WHERE published_at IS NULL AND available_at <= now()
|
||||
ORDER BY available_at, id LIMIT $1 FOR UPDATE SKIP LOCKED
|
||||
"""
|
||||
PUBLISHED = "UPDATE outbox SET published_at = now() WHERE id = ANY($1::bigint[])"
|
||||
|
||||
|
||||
def attachment_of(row: Record, variants: tuple[Variant, ...] = ()) -> Attachment:
|
||||
return Attachment(
|
||||
id=row["id"],
|
||||
chat_id=row["chat_id"],
|
||||
owner_id=row["owner_id"],
|
||||
filename=Filename(row["filename"]),
|
||||
image=ImageInfo(ImageKind(row["content_type"]), row["width"], row["height"]),
|
||||
size_bytes=row["size_bytes"],
|
||||
sha256=row["sha256"],
|
||||
status=AttachmentStatus(row["status"]),
|
||||
created_at=row["created_at"],
|
||||
updated_at=row["updated_at"],
|
||||
staging_key=row["staging_key"],
|
||||
original_key=row["original_key"],
|
||||
published_version=row["published_version"],
|
||||
error_code=row["error_code"],
|
||||
variants=variants,
|
||||
)
|
||||
|
||||
|
||||
def payload(job: Job) -> str:
|
||||
return json.dumps(job.payload(), separators=(",", ":"))
|
||||
|
||||
|
||||
class PostgresAttachmentRepository:
|
||||
__slots__ = ("_connection", "_seen")
|
||||
|
||||
def __init__(self, connection: Connection, seen: list[EventSource]) -> None:
|
||||
self._connection = connection
|
||||
self._seen = seen
|
||||
|
||||
async def add(self, attachment: Attachment) -> None:
|
||||
try:
|
||||
await self._connection.execute(
|
||||
INSERT,
|
||||
attachment.id,
|
||||
attachment.chat_id,
|
||||
attachment.owner_id,
|
||||
attachment.filename.value,
|
||||
attachment.content_type,
|
||||
attachment.size_bytes,
|
||||
attachment.sha256,
|
||||
attachment.image.width,
|
||||
attachment.image.height,
|
||||
attachment.staging_key,
|
||||
attachment.status.value,
|
||||
attachment.created_at,
|
||||
attachment.updated_at,
|
||||
)
|
||||
except ForeignKeyViolationError as error:
|
||||
raise ChatNotFound("чат не найден") from error
|
||||
self._seen.append(attachment)
|
||||
|
||||
async def save(self, attachment: Attachment) -> None:
|
||||
done = await self._connection.execute(
|
||||
MARK, attachment.id, attachment.status.value, attachment.updated_at
|
||||
)
|
||||
if done == "UPDATE 0":
|
||||
raise Unavailable("намерение загрузки уже снято уборкой")
|
||||
self._seen.append(attachment)
|
||||
|
||||
async def lock(self, attachment_id: UUID) -> Attachment | None:
|
||||
row = await self._connection.fetchrow(LOCK, attachment_id)
|
||||
return None if row is None else attachment_of(row)
|
||||
|
||||
async def next_abandoned(self, before: datetime) -> Attachment | None:
|
||||
row = await self._connection.fetchrow(ABANDONED, before)
|
||||
return None if row is None else attachment_of(row)
|
||||
|
||||
async def remove(self, attachment: Attachment) -> None:
|
||||
await self._connection.execute(REMOVE, attachment.id)
|
||||
self._seen.append(attachment)
|
||||
|
||||
async def staged(self, limit: int, retention: timedelta) -> list[StagedObject]:
|
||||
rows = await self._connection.fetch(STAGED, limit, retention.total_seconds())
|
||||
return [StagedObject(row["id"], row["staging_key"]) for row in rows]
|
||||
|
||||
async def unstage(self, attachment_ids: Sequence[UUID]) -> None:
|
||||
if attachment_ids:
|
||||
await self._connection.execute(UNSTAGE, list(attachment_ids))
|
||||
|
||||
|
||||
class PostgresJobRepository:
|
||||
__slots__ = ("_connection",)
|
||||
|
||||
def __init__(self, connection: Connection) -> None:
|
||||
self._connection = connection
|
||||
|
||||
async def add(self, job: Job) -> None:
|
||||
await self._connection.execute(
|
||||
ADD_JOB,
|
||||
job.id,
|
||||
job.attachment_id,
|
||||
job.pipeline_version,
|
||||
job.attempt,
|
||||
job.created_at,
|
||||
payload(job),
|
||||
)
|
||||
|
||||
async def claim(self, job: Job, token: UUID, lease: timedelta) -> Claim | None:
|
||||
row = await self._connection.fetchrow(
|
||||
CLAIM,
|
||||
job.id,
|
||||
job.attachment_id,
|
||||
job.pipeline_version,
|
||||
token,
|
||||
lease.total_seconds(),
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
claimed = Job(
|
||||
job.id, job.attachment_id, job.pipeline_version, row["attempt"], row["created_at"]
|
||||
)
|
||||
staged = row["staging_key"] is not None
|
||||
source = row["staging_key"] if staged else row["original_key"]
|
||||
return Claim(Lease(claimed, token), source, staged)
|
||||
|
||||
async def complete(
|
||||
self, lease: Lease, variants: Sequence[Variant], original_key: str
|
||||
) -> Outcome:
|
||||
job = lease.job
|
||||
if await self._connection.execute(FINISH, job.id, lease.token) == "UPDATE 0":
|
||||
await self.note(job, Outcome.FENCED)
|
||||
return Outcome.FENCED
|
||||
await self._connection.execute(
|
||||
ADD_VARIANTS,
|
||||
job.attachment_id,
|
||||
job.pipeline_version,
|
||||
[v.name for v in variants],
|
||||
[v.object_key for v in variants],
|
||||
[v.content_type for v in variants],
|
||||
[v.size_bytes for v in variants],
|
||||
[v.width for v in variants],
|
||||
[v.height for v in variants],
|
||||
[v.sha256 for v in variants],
|
||||
)
|
||||
published = await self._connection.execute(
|
||||
PUBLISH, job.attachment_id, job.pipeline_version, original_key
|
||||
)
|
||||
outcome = Outcome.SUPERSEDED if published == "UPDATE 0" else Outcome.DONE
|
||||
if outcome is Outcome.SUPERSEDED:
|
||||
await self._connection.execute(SUPERSEDE, job.id)
|
||||
await self.note(job, outcome)
|
||||
return outcome
|
||||
|
||||
async def reschedule(
|
||||
self, lease: Lease, delay: timedelta, kind: Outcome, error: str
|
||||
) -> Job | None:
|
||||
row = await self._connection.fetchrow(
|
||||
RESCHEDULE, lease.job.id, lease.token, delay.total_seconds(), error, kind.value
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
job = lease.job.retried(row["attempt"])
|
||||
await self._connection.execute(ENQUEUE, job.id, payload(job), row["next_attempt_at"])
|
||||
return job
|
||||
|
||||
async def renew(self, lease: Lease, duration: timedelta) -> bool:
|
||||
done = await self._connection.execute(
|
||||
RENEW, lease.job.id, lease.token, duration.total_seconds()
|
||||
)
|
||||
return done == "UPDATE 1"
|
||||
|
||||
async def fail(self, lease: Lease, code: FailureCode, error: str) -> bool:
|
||||
attempt = await self._connection.fetchval(
|
||||
FAIL, lease.job.id, lease.token, code.value, error
|
||||
)
|
||||
return attempt is not None
|
||||
|
||||
async def note(self, job: Job, kind: Outcome) -> None:
|
||||
await self._connection.execute(NOTE, job.id, job.attachment_id, kind.value, job.attempt)
|
||||
|
||||
async def expired(self, limit: int) -> list[Lease]:
|
||||
rows = await self._connection.fetch(EXPIRED, limit)
|
||||
return [
|
||||
Lease(
|
||||
Job(
|
||||
row["job_id"],
|
||||
row["attachment_id"],
|
||||
row["pipeline_version"],
|
||||
row["attempt"],
|
||||
row["created_at"],
|
||||
),
|
||||
row["lease_token"],
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
|
||||
async def replay(self, attachment: Attachment, operator: str) -> Job | None:
|
||||
row = await self._connection.fetchrow(
|
||||
REPLAY, attachment.id, operator, attachment.error_code
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
job = Job(row["job_id"], attachment.id, row["pipeline_version"], 1, row["created_at"])
|
||||
await self._connection.execute(ENQUEUE, job.id, payload(job), row["updated_at"])
|
||||
return job
|
||||
|
||||
async def note_replay(self, attachment_id: UUID, operator: str, result: str) -> None:
|
||||
await self._connection.execute(NOTE_REPLAY, attachment_id, operator, result)
|
||||
|
||||
|
||||
class PostgresOutboxRepository:
|
||||
__slots__ = ("_connection",)
|
||||
|
||||
def __init__(self, connection: Connection) -> None:
|
||||
self._connection = connection
|
||||
|
||||
async def pending(self, limit: int) -> list[OutboxEntry]:
|
||||
rows = await self._connection.fetch(PENDING, limit)
|
||||
return [OutboxEntry(row["id"], row["job_id"], row["body"].encode()) for row in rows]
|
||||
|
||||
async def published(self, entry_ids: Sequence[int]) -> None:
|
||||
await self._connection.execute(PUBLISHED, list(entry_ids))
|
||||
|
||||
|
||||
class PostgresAttachmentsUnitOfWork(PostgresUnitOfWork):
|
||||
__slots__ = ()
|
||||
|
||||
@property
|
||||
def attachments(self) -> PostgresAttachmentRepository:
|
||||
return PostgresAttachmentRepository(self.connection, self.seen)
|
||||
|
||||
@property
|
||||
def jobs(self) -> PostgresJobRepository:
|
||||
return PostgresJobRepository(self.connection)
|
||||
|
||||
@property
|
||||
def outbox(self) -> PostgresOutboxRepository:
|
||||
return PostgresOutboxRepository(self.connection)
|
||||
|
||||
|
||||
def variants_of(raw: str) -> tuple[Variant, ...]:
|
||||
return tuple(Variant(*item) for item in json.loads(raw))
|
||||
|
||||
|
||||
class PostgresAttachmentDirectory:
|
||||
__slots__ = ("_database",)
|
||||
|
||||
def __init__(self, database: Database) -> None:
|
||||
self._database = database
|
||||
|
||||
async def visible(self, attachment_id: UUID) -> Attachment | None:
|
||||
async with self._database.connection() as connection:
|
||||
row = await connection.fetchrow(VISIBLE, attachment_id)
|
||||
return None if row is None else attachment_of(row, variants_of(row["variants"]))
|
||||
|
||||
async def failed_among(self, chat_id: UUID, attachment_ids: Sequence[UUID]) -> bool:
|
||||
async with self._database.connection() as connection:
|
||||
return bool(await connection.fetchval(FAILED_AMONG, list(attachment_ids), chat_id))
|
||||
|
||||
async def failed_jobs(self, limit: int) -> list[FailedJob]:
|
||||
async with self._database.connection() as connection:
|
||||
return [FailedJob(**row) for row in await connection.fetch(FAILED_JOBS, limit)]
|
||||
@@ -0,0 +1,37 @@
|
||||
from uuid import UUID
|
||||
|
||||
from faststream.rabbit import RabbitBroker, RabbitExchange
|
||||
from pamqp.commands import Basic
|
||||
|
||||
from messenger.attachments.domain.jobs import JOB_TYPE
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
|
||||
EXCHANGE = RabbitExchange("attachments", declare=False)
|
||||
QUEUE = "attachments.process"
|
||||
DEAD_LETTERS = "attachments.process.dlq"
|
||||
|
||||
|
||||
class RabbitJobPublisher:
|
||||
__slots__ = ("_broker", "_timeout")
|
||||
|
||||
def __init__(self, broker: RabbitBroker, timeout: float) -> None:
|
||||
self._broker = broker
|
||||
self._timeout = timeout
|
||||
|
||||
async def publish(self, job_id: UUID, body: bytes) -> None:
|
||||
try:
|
||||
confirmation = await self._broker.publish(
|
||||
body,
|
||||
exchange=EXCHANGE,
|
||||
routing_key=JOB_TYPE,
|
||||
mandatory=True,
|
||||
persist=True,
|
||||
message_id=str(job_id),
|
||||
message_type=JOB_TYPE,
|
||||
content_type="application/json",
|
||||
timeout=self._timeout,
|
||||
)
|
||||
except Exception as error:
|
||||
raise Unavailable("брокер не принял задание") from error
|
||||
if not isinstance(confirmation, Basic.Ack):
|
||||
raise Unavailable("брокер не подтвердил задание")
|
||||
@@ -0,0 +1,104 @@
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any
|
||||
|
||||
from aiobotocore.session import get_session
|
||||
from botocore.config import Config
|
||||
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.shared.application.errors import Unavailable
|
||||
|
||||
CHUNK_BYTES = 64 * 1024
|
||||
MISSING = frozenset({"NoSuchKey", "404", "NotFound"})
|
||||
FAILURES = (BotoCoreError, ClientError, OSError, TimeoutError)
|
||||
|
||||
|
||||
def missing(error: Exception) -> bool:
|
||||
return isinstance(error, ClientError) and error.response.get("Error", {}).get("Code") in MISSING
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def s3_client(
|
||||
*,
|
||||
endpoint: str,
|
||||
region: str,
|
||||
access_key_id: str,
|
||||
secret_access_key: str,
|
||||
connect_timeout: float,
|
||||
read_timeout: float,
|
||||
max_attempts: int,
|
||||
) -> AsyncIterator[Any]:
|
||||
config = Config(
|
||||
region_name=region,
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
connect_timeout=connect_timeout,
|
||||
read_timeout=read_timeout,
|
||||
retries={"mode": "standard", "max_attempts": max_attempts},
|
||||
max_pool_connections=32,
|
||||
request_checksum_calculation="when_required",
|
||||
response_checksum_validation="when_required",
|
||||
)
|
||||
async with get_session().create_client(
|
||||
"s3",
|
||||
endpoint_url=endpoint,
|
||||
aws_access_key_id=access_key_id,
|
||||
aws_secret_access_key=secret_access_key,
|
||||
config=config,
|
||||
) as client:
|
||||
client.meta.events.unregister("before-call.s3", add_expect_header)
|
||||
yield client
|
||||
|
||||
|
||||
class S3ObjectStorage:
|
||||
__slots__ = ("_bucket", "_client")
|
||||
|
||||
def __init__(self, client: Any, bucket: str) -> None:
|
||||
self._client = client
|
||||
self._bucket = bucket
|
||||
|
||||
async def put(self, key: str, data: bytes, content_type: str) -> None:
|
||||
try:
|
||||
await self._client.put_object(
|
||||
Bucket=self._bucket, Key=key, Body=data, ContentType=content_type
|
||||
)
|
||||
except FAILURES as error:
|
||||
raise Unavailable("S3 недоступно") from error
|
||||
|
||||
async def open(self, key: str) -> ObjectContent:
|
||||
try:
|
||||
response = await self._client.get_object(Bucket=self._bucket, Key=key)
|
||||
except FAILURES as error:
|
||||
if missing(error):
|
||||
raise ObjectMissingError(key) from error
|
||||
raise Unavailable("S3 недоступно") from error
|
||||
return ObjectContent(size=response["ContentLength"], chunks=self._chunks(response["Body"]))
|
||||
|
||||
async def read(self, key: str) -> bytes:
|
||||
content = await self.open(key)
|
||||
try:
|
||||
return b"".join([chunk async for chunk in content.chunks])
|
||||
except Exception as error:
|
||||
raise Unavailable("S3 оборвал чтение объекта") from error
|
||||
|
||||
async def copy(self, source: str, target: str) -> None:
|
||||
try:
|
||||
await self._client.copy_object(
|
||||
Bucket=self._bucket, Key=target, CopySource={"Bucket": self._bucket, "Key": source}
|
||||
)
|
||||
except FAILURES as error:
|
||||
raise Unavailable("S3 недоступно") from error
|
||||
|
||||
async def delete(self, key: str) -> None:
|
||||
try:
|
||||
await self._client.delete_object(Bucket=self._bucket, Key=key)
|
||||
except FAILURES as error:
|
||||
raise Unavailable("S3 недоступно") from error
|
||||
|
||||
async def _chunks(self, body: Any) -> AsyncIterator[bytes]:
|
||||
async with body as stream:
|
||||
async for chunk in stream.iter_chunks(CHUNK_BYTES):
|
||||
yield chunk
|
||||
@@ -0,0 +1,66 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
from gunicorn.arbiter import Arbiter
|
||||
from gunicorn.glogging import Logger as GunicornBaseLogger
|
||||
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
|
||||
|
||||
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO")
|
||||
SHUTDOWN_SECONDS = int(os.environ.get("SHUTDOWN_TIMEOUT_SECONDS", "5"))
|
||||
DRAIN_SECONDS = float(os.environ.get("DRAIN_SECONDS", "2"))
|
||||
|
||||
|
||||
class StructlogGunicornLogger(GunicornBaseLogger):
|
||||
def setup(self, cfg: object) -> None:
|
||||
configure(LOG_LEVEL, LOG_FIELDS)
|
||||
|
||||
def access(self, resp: object, req: object, environ: object, request_time: object) -> None:
|
||||
return
|
||||
|
||||
|
||||
class DrainingServer(Server):
|
||||
async def main_loop(self) -> None:
|
||||
await super().main_loop()
|
||||
if not self.force_exit:
|
||||
DRAINING.set()
|
||||
logging.getLogger("uvicorn.error").info("Draining for %.1f s", DRAIN_SECONDS)
|
||||
await asyncio.sleep(DRAIN_SECONDS)
|
||||
|
||||
|
||||
class MessengerWorker(UvicornWorker):
|
||||
CONFIG_KWARGS: dict[str, Any] = {
|
||||
"access_log": False,
|
||||
"server_header": False,
|
||||
"date_header": False,
|
||||
"timeout_graceful_shutdown": max(1, int(SHUTDOWN_SECONDS - DRAIN_SECONDS)),
|
||||
}
|
||||
|
||||
async def _serve(self) -> None:
|
||||
self.config.app = self.wsgi
|
||||
server = DrainingServer(config=self.config)
|
||||
self._install_sigquit_handler()
|
||||
await server.serve(sockets=self.sockets)
|
||||
if not server.started:
|
||||
sys.exit(Arbiter.WORKER_BOOT_ERROR)
|
||||
|
||||
|
||||
bind = f"{os.environ.get('HOST', '0.0.0.0')}:{os.environ.get('PORT', '8080')}"
|
||||
workers = int(os.environ.get("WEB_CONCURRENCY", "2"))
|
||||
worker_class = "messenger.gunicorn_conf.MessengerWorker"
|
||||
logger_class = StructlogGunicornLogger
|
||||
loglevel = LOG_LEVEL.lower()
|
||||
accesslog = None
|
||||
errorlog = "-"
|
||||
timeout = int(float(os.environ.get("REQUEST_TIMEOUT_SECONDS", "8")) + 5)
|
||||
graceful_timeout = SHUTDOWN_SECONDS
|
||||
keepalive = 5
|
||||
preload_app = False
|
||||
control_socket_disable = True
|
||||
@@ -0,0 +1,5 @@
|
||||
from messenger.shared.application.messagebus import CommandBus
|
||||
|
||||
|
||||
class IdentityCommandBus(CommandBus):
|
||||
__slots__ = ()
|
||||
@@ -0,0 +1,22 @@
|
||||
from dataclasses import dataclass, field
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.identity.domain.models import Session
|
||||
from messenger.shared.application.commands import Command
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RegisterUser(Command):
|
||||
username: str
|
||||
display_name: str
|
||||
password: str = field(repr=False)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class OpenSession(Command):
|
||||
user_id: UUID
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CloseSession(Command):
|
||||
session: Session
|
||||
@@ -0,0 +1,76 @@
|
||||
from datetime import timedelta
|
||||
|
||||
from messenger.identity.application.commands import CloseSession, OpenSession, RegisterUser
|
||||
from messenger.identity.application.ports import (
|
||||
IdentityUnitOfWork,
|
||||
PasswordHasher,
|
||||
SessionDirectory,
|
||||
)
|
||||
from messenger.identity.domain.events import SessionClosed, SessionOpened
|
||||
from messenger.identity.domain.models import Session, User
|
||||
from messenger.identity.domain.values import DisplayName, Password, Username
|
||||
from messenger.shared.application.ports import Clock, IdGenerator
|
||||
|
||||
|
||||
class RegisterUserHandler:
|
||||
__slots__ = ("_clock", "_hasher", "_ids", "_uow")
|
||||
|
||||
def __init__(
|
||||
self, uow: IdentityUnitOfWork, clock: Clock, ids: IdGenerator, hasher: PasswordHasher
|
||||
) -> None:
|
||||
self._uow = uow
|
||||
self._clock = clock
|
||||
self._ids = ids
|
||||
self._hasher = hasher
|
||||
|
||||
async def __call__(self, command: RegisterUser) -> User:
|
||||
username = Username(command.username)
|
||||
display_name = DisplayName(command.display_name)
|
||||
password = Password(command.password)
|
||||
password_hash = await self._hasher.hash(password.value)
|
||||
user, event = User.register(
|
||||
user_id=self._ids.new_id(),
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
password_hash=password_hash,
|
||||
registered_at=self._clock.now(),
|
||||
)
|
||||
async with self._uow.transaction():
|
||||
await self._uow.users.add(user)
|
||||
self._uow.record(event)
|
||||
await self._uow.commit()
|
||||
return user
|
||||
|
||||
|
||||
class OpenSessionHandler:
|
||||
__slots__ = ("_clock", "_ttl", "_uow")
|
||||
|
||||
def __init__(self, uow: IdentityUnitOfWork, clock: Clock, ttl: timedelta) -> None:
|
||||
self._uow = uow
|
||||
self._clock = clock
|
||||
self._ttl = ttl
|
||||
|
||||
async def __call__(self, command: OpenSession) -> tuple[str, Session]:
|
||||
token, session = Session.issue(
|
||||
user_id=command.user_id, issued_at=self._clock.now(), ttl=self._ttl
|
||||
)
|
||||
async with self._uow.transaction():
|
||||
await self._uow.sessions.add(session)
|
||||
self._uow.record(SessionOpened(user_id=session.user_id, expires_at=session.expires_at))
|
||||
await self._uow.commit()
|
||||
return token, session
|
||||
|
||||
|
||||
class CloseSessionHandler:
|
||||
__slots__ = ("_sessions", "_uow")
|
||||
|
||||
def __init__(self, uow: IdentityUnitOfWork, sessions: SessionDirectory) -> None:
|
||||
self._uow = uow
|
||||
self._sessions = sessions
|
||||
|
||||
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()
|
||||
@@ -0,0 +1,48 @@
|
||||
from datetime import datetime
|
||||
from typing import Protocol, runtime_checkable
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.identity.domain.models import Session, User
|
||||
from messenger.shared.application.ports import UnitOfWork
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class UserRepository(Protocol):
|
||||
async def add(self, user: User) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class SessionRepository(Protocol):
|
||||
async def add(self, session: Session) -> None: ...
|
||||
|
||||
async def remove(self, token_hash: bytes) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class IdentityUnitOfWork(UnitOfWork, Protocol):
|
||||
@property
|
||||
def users(self) -> UserRepository: ...
|
||||
|
||||
@property
|
||||
def sessions(self) -> SessionRepository: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class UserDirectory(Protocol):
|
||||
async def find(self, user_id: UUID) -> User | None: ...
|
||||
|
||||
async def find_by_username(self, username: str) -> User | None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class SessionDirectory(Protocol):
|
||||
async def find(self, token_hash: bytes, now: datetime) -> Session | None: ...
|
||||
|
||||
async def invalidate(self, session: Session) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class PasswordHasher(Protocol):
|
||||
async def hash(self, password: str) -> str: ...
|
||||
|
||||
async def verify(self, password_hash: str | None, password: str) -> bool: ...
|
||||
@@ -0,0 +1,43 @@
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.identity.application.ports import PasswordHasher, SessionDirectory, UserDirectory
|
||||
from messenger.identity.domain.errors import ActorNotIdentified
|
||||
from messenger.identity.domain.models import Session, User, token_digest
|
||||
from messenger.shared.application.ports import Clock
|
||||
|
||||
|
||||
class GetCurrentUser:
|
||||
__slots__ = ("_directory",)
|
||||
|
||||
def __init__(self, directory: UserDirectory) -> None:
|
||||
self._directory = directory
|
||||
|
||||
async def __call__(self, user_id: UUID) -> User:
|
||||
user = await self._directory.find(user_id)
|
||||
if user is None:
|
||||
raise ActorNotIdentified("идентификация не подтверждена")
|
||||
return user
|
||||
|
||||
|
||||
class VerifyCredentials:
|
||||
__slots__ = ("_directory", "_hasher")
|
||||
|
||||
def __init__(self, directory: UserDirectory, hasher: PasswordHasher) -> None:
|
||||
self._directory = directory
|
||||
self._hasher = hasher
|
||||
|
||||
async def __call__(self, username: str, password: str) -> User | None:
|
||||
user = await self._directory.find_by_username(username)
|
||||
valid = await self._hasher.verify(user.password_hash if user else None, password)
|
||||
return user if valid else None
|
||||
|
||||
|
||||
class Authenticate:
|
||||
__slots__ = ("_clock", "_sessions")
|
||||
|
||||
def __init__(self, sessions: SessionDirectory, clock: Clock) -> None:
|
||||
self._sessions = sessions
|
||||
self._clock = clock
|
||||
|
||||
async def __call__(self, token: str) -> Session | None:
|
||||
return await self._sessions.find(token_digest(token), self._clock.now())
|
||||
@@ -0,0 +1,12 @@
|
||||
from pydantic import Field, SecretStr
|
||||
|
||||
from messenger.shared.config import Settings
|
||||
|
||||
|
||||
class IdentitySettings(Settings):
|
||||
session_ttl_seconds: int = Field(default=3600, ge=1, le=30 * 24 * 3600)
|
||||
password_hash_concurrency: int = Field(default=2, ge=1, le=64)
|
||||
cache_url: SecretStr | None = None
|
||||
session_cache_ttl_seconds: int = Field(default=300, ge=1, le=24 * 3600)
|
||||
cache_timeout_seconds: float = Field(default=0.2, gt=0, le=5)
|
||||
cache_cooldown_seconds: float = Field(default=1.0, ge=0, le=60)
|
||||
@@ -0,0 +1,17 @@
|
||||
from messenger.shared.domain.errors import DomainError
|
||||
|
||||
|
||||
class IdentityError(DomainError):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidUserData(IdentityError):
|
||||
pass
|
||||
|
||||
|
||||
class UsernameAlreadyTaken(IdentityError):
|
||||
pass
|
||||
|
||||
|
||||
class ActorNotIdentified(IdentityError):
|
||||
pass
|
||||
@@ -0,0 +1,25 @@
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class UserRegistered(DomainEvent):
|
||||
user_id: UUID
|
||||
registered_at: datetime
|
||||
name: str = field(init=False, default="user.registered")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SessionOpened(DomainEvent):
|
||||
user_id: UUID
|
||||
expires_at: datetime
|
||||
name: str = field(init=False, default="session.opened")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SessionClosed(DomainEvent):
|
||||
user_id: UUID
|
||||
name: str = field(init=False, default="session.closed")
|
||||
@@ -0,0 +1,62 @@
|
||||
import secrets
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta
|
||||
from hashlib import sha256
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.identity.domain.events import UserRegistered
|
||||
from messenger.identity.domain.values import DisplayName, Username
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
TOKEN_BYTES = 32
|
||||
|
||||
|
||||
def token_digest(token: str) -> bytes:
|
||||
return sha256(token.encode()).digest()
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class User:
|
||||
id: UUID
|
||||
username: Username
|
||||
display_name: DisplayName
|
||||
created_at: datetime
|
||||
password_hash: str = field(repr=False)
|
||||
|
||||
@classmethod
|
||||
def register(
|
||||
cls,
|
||||
*,
|
||||
user_id: UUID,
|
||||
username: Username,
|
||||
display_name: DisplayName,
|
||||
password_hash: str,
|
||||
registered_at: datetime,
|
||||
) -> tuple[User, DomainEvent]:
|
||||
user = cls(
|
||||
id=user_id,
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
created_at=registered_at,
|
||||
password_hash=password_hash,
|
||||
)
|
||||
return user, UserRegistered(user_id=user.id, registered_at=registered_at)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Session:
|
||||
token_hash: bytes = field(repr=False)
|
||||
user_id: UUID
|
||||
created_at: datetime
|
||||
expires_at: datetime
|
||||
|
||||
@classmethod
|
||||
def issue(cls, *, user_id: UUID, issued_at: datetime, ttl: timedelta) -> tuple[str, Session]:
|
||||
token = secrets.token_urlsafe(TOKEN_BYTES)
|
||||
session = cls(
|
||||
token_hash=token_digest(token),
|
||||
user_id=user_id,
|
||||
created_at=issued_at,
|
||||
expires_at=issued_at + ttl,
|
||||
)
|
||||
return token, session
|
||||
@@ -0,0 +1,54 @@
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from messenger.identity.domain.errors import InvalidUserData
|
||||
|
||||
USERNAME_PATTERN = re.compile(r"\A[a-z0-9_]{3,32}\Z")
|
||||
DISPLAY_NAME_MAX = 100
|
||||
PASSWORD_MIN = 12
|
||||
PASSWORD_MAX = 128
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Username:
|
||||
value: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.value, str):
|
||||
raise InvalidUserData("поле username должно быть строкой")
|
||||
if USERNAME_PATTERN.match(self.value) is None:
|
||||
raise InvalidUserData("поле username должно соответствовать [a-z0-9_]{3,32}")
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.value
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DisplayName:
|
||||
value: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.value, str):
|
||||
raise InvalidUserData("поле display_name должно быть строкой")
|
||||
if not self.value.strip():
|
||||
raise InvalidUserData("поле display_name не может быть пустым или состоять из пробелов")
|
||||
if len(self.value) > DISPLAY_NAME_MAX:
|
||||
raise InvalidUserData(f"поле display_name длиннее {DISPLAY_NAME_MAX} символов Unicode")
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.value
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Password:
|
||||
value: str = field(repr=False)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.value, str):
|
||||
raise InvalidUserData("поле password должно быть строкой")
|
||||
if not self.value.strip():
|
||||
raise InvalidUserData("поле password не может состоять из пробелов")
|
||||
if not PASSWORD_MIN <= len(self.value) <= PASSWORD_MAX:
|
||||
raise InvalidUserData(
|
||||
f"поле password: от {PASSWORD_MIN} до {PASSWORD_MAX} символов Unicode"
|
||||
)
|
||||
@@ -0,0 +1,98 @@
|
||||
import re
|
||||
from base64 import b64decode
|
||||
from binascii import Error as Base64Error
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Depends, Request
|
||||
from starlette.types import Scope
|
||||
|
||||
from messenger.identity.application.queries import Authenticate, VerifyCredentials
|
||||
from messenger.identity.domain.models import Session, User
|
||||
from messenger.shared.entrypoints.errors import Unauthenticated
|
||||
from messenger.shared.entrypoints.pipeline import Rejection, header
|
||||
|
||||
LOGIN_PATH = "/api/v1/auth/sessions"
|
||||
PROTECTED_PREFIX = "/api/v1/"
|
||||
PUBLIC_ROUTES = frozenset({("POST", "/api/v1/users")})
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
AUTHORIZATION = b"authorization"
|
||||
TOKEN = re.compile(r"[A-Za-z0-9\-._~+/]{1,512}=*")
|
||||
|
||||
|
||||
def normalized(path: str) -> str:
|
||||
return path.rstrip("/") or "/"
|
||||
|
||||
|
||||
def challenge_for(path: str) -> str:
|
||||
return BASIC_CHALLENGE if normalized(path) == LOGIN_PATH else BEARER_CHALLENGE
|
||||
|
||||
|
||||
def basic_credentials(value: str) -> tuple[str, str] | None:
|
||||
scheme, _, encoded = value.partition(" ")
|
||||
if scheme.lower() != "basic":
|
||||
return None
|
||||
try:
|
||||
decoded = b64decode(encoded.strip(), validate=True).decode("utf-8")
|
||||
except Base64Error, UnicodeDecodeError:
|
||||
return None
|
||||
username, separator, password = decoded.partition(":")
|
||||
if not separator or not username.isascii():
|
||||
return None
|
||||
return username, password
|
||||
|
||||
|
||||
def bearer_token(value: str) -> str | None:
|
||||
scheme, _, token = value.partition(" ")
|
||||
token = token.strip()
|
||||
if scheme.lower() != "bearer" or TOKEN.fullmatch(token) is None:
|
||||
return None
|
||||
return token
|
||||
|
||||
|
||||
def rejection(path: str) -> Rejection:
|
||||
return Rejection(401, "unauthorized", (("www-authenticate", challenge_for(path)),))
|
||||
|
||||
|
||||
async def guard(scope: Scope) -> Rejection | None:
|
||||
method, path = scope["method"], normalized(scope["path"])
|
||||
if not path.startswith(PROTECTED_PREFIX) or (method, path) in PUBLIC_ROUTES:
|
||||
return None
|
||||
container = scope["app"].state.dishka_container
|
||||
state = scope.setdefault("state", {})
|
||||
raw = header(scope, AUTHORIZATION)
|
||||
if (method, path) == ("POST", LOGIN_PATH):
|
||||
credentials = basic_credentials(raw)
|
||||
verify = await container.get(VerifyCredentials)
|
||||
user = await verify(*credentials) if credentials else None
|
||||
if user is None:
|
||||
return rejection(path)
|
||||
state["user"] = user
|
||||
state["actor"] = user.id
|
||||
return None
|
||||
token = bearer_token(raw)
|
||||
authenticate = await container.get(Authenticate)
|
||||
session = await authenticate(token) if token else None
|
||||
if session is None:
|
||||
return rejection(path)
|
||||
state["session"] = session
|
||||
state["actor"] = session.user_id
|
||||
return None
|
||||
|
||||
|
||||
async def verified_user(request: Request) -> User:
|
||||
user = getattr(request.state, "user", None)
|
||||
if not isinstance(user, User):
|
||||
raise Unauthenticated("учётные данные не подтверждены")
|
||||
return user
|
||||
|
||||
|
||||
async def current_session(request: Request) -> Session:
|
||||
session = getattr(request.state, "session", None)
|
||||
if not isinstance(session, Session):
|
||||
raise Unauthenticated("сессия не подтверждена")
|
||||
return session
|
||||
|
||||
|
||||
type VerifiedUser = Annotated[User, Depends(verified_user)]
|
||||
type CurrentSession = Annotated[Session, Depends(current_session)]
|
||||
@@ -0,0 +1,12 @@
|
||||
from messenger.identity.domain.errors import (
|
||||
ActorNotIdentified,
|
||||
InvalidUserData,
|
||||
UsernameAlreadyTaken,
|
||||
)
|
||||
from messenger.shared.domain.errors import DomainError
|
||||
|
||||
ERROR_CODES: dict[type[DomainError], tuple[str, int]] = {
|
||||
InvalidUserData: ("invalid_request", 400),
|
||||
UsernameAlreadyTaken: ("conflict", 409),
|
||||
ActorNotIdentified: ("unauthorized", 401),
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
from dishka.integrations.fastapi import FromDishka, inject
|
||||
from fastapi import APIRouter, Request, Response, status
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
|
||||
from messenger.identity.application.bus import IdentityCommandBus
|
||||
from messenger.identity.application.commands import CloseSession, OpenSession, RegisterUser
|
||||
from messenger.identity.application.queries import GetCurrentUser
|
||||
from messenger.identity.entrypoints.authentication import CurrentSession, VerifiedUser
|
||||
from messenger.identity.entrypoints.schemas import CreateUserRequest, SessionOut, UserOut
|
||||
from messenger.shared.entrypoints.actor import Actor
|
||||
|
||||
router = APIRouter(prefix="/api/v1/users", tags=["users"])
|
||||
sessions_router = APIRouter(prefix="/api/v1/auth/sessions", tags=["sessions"])
|
||||
|
||||
|
||||
@router.post("", status_code=status.HTTP_201_CREATED)
|
||||
@inject
|
||||
async def create_user(
|
||||
body: CreateUserRequest,
|
||||
bus: FromDishka[IdentityCommandBus],
|
||||
) -> UserOut:
|
||||
user = await bus.execute(
|
||||
RegisterUser(username=body.username, display_name=body.display_name, password=body.password)
|
||||
)
|
||||
return UserOut.of(user)
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
@inject
|
||||
async def current_user(
|
||||
actor: Actor,
|
||||
query: FromDishka[GetCurrentUser],
|
||||
) -> UserOut:
|
||||
return UserOut.of(await query(actor))
|
||||
|
||||
|
||||
@sessions_router.post("", status_code=status.HTTP_201_CREATED)
|
||||
@inject
|
||||
async def open_session(
|
||||
request: Request,
|
||||
user: VerifiedUser,
|
||||
bus: FromDishka[IdentityCommandBus],
|
||||
) -> SessionOut:
|
||||
if await request.body():
|
||||
raise RequestValidationError([])
|
||||
token, session = await bus.execute(OpenSession(user_id=user.id))
|
||||
return SessionOut.of(token, session, user)
|
||||
|
||||
|
||||
@sessions_router.delete("/current", status_code=status.HTTP_204_NO_CONTENT)
|
||||
@inject
|
||||
async def close_session(
|
||||
session: CurrentSession,
|
||||
bus: FromDishka[IdentityCommandBus],
|
||||
) -> Response:
|
||||
await bus.execute(CloseSession(session=session))
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -0,0 +1,112 @@
|
||||
from collections.abc import AsyncIterator
|
||||
from datetime import timedelta
|
||||
|
||||
from dishka import Provider, Scope, provide
|
||||
from redis.asyncio import Redis
|
||||
from redis.asyncio.retry import Retry
|
||||
from redis.backoff import NoBackoff
|
||||
|
||||
from messenger.identity.application.bus import IdentityCommandBus
|
||||
from messenger.identity.application.commands import CloseSession, OpenSession, RegisterUser
|
||||
from messenger.identity.application.handlers import (
|
||||
CloseSessionHandler,
|
||||
OpenSessionHandler,
|
||||
RegisterUserHandler,
|
||||
)
|
||||
from messenger.identity.application.ports import (
|
||||
IdentityUnitOfWork,
|
||||
PasswordHasher,
|
||||
SessionDirectory,
|
||||
UserDirectory,
|
||||
)
|
||||
from messenger.identity.application.queries import Authenticate, GetCurrentUser, VerifyCredentials
|
||||
from messenger.identity.config import IdentitySettings
|
||||
from messenger.identity.infrastructure.argon2 import Argon2PasswordHasher
|
||||
from messenger.identity.infrastructure.postgres import (
|
||||
PostgresIdentityUnitOfWork,
|
||||
PostgresSessionDirectory,
|
||||
PostgresUserDirectory,
|
||||
)
|
||||
from messenger.identity.infrastructure.valkey import CachedSessionDirectory
|
||||
from messenger.shared.application.commands import Command
|
||||
from messenger.shared.application.messagebus import CommandHandler
|
||||
from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator, Logger
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
|
||||
|
||||
class IdentityProvider(Provider):
|
||||
def __init__(self, settings: IdentitySettings) -> None:
|
||||
super().__init__()
|
||||
self._settings = settings
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def settings(self) -> IdentitySettings:
|
||||
return self._settings
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def hasher(self, settings: IdentitySettings) -> PasswordHasher:
|
||||
return Argon2PasswordHasher(settings.password_hash_concurrency)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def users(self, database: Database) -> UserDirectory:
|
||||
return PostgresUserDirectory(database)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
async def sessions(
|
||||
self, database: Database, settings: IdentitySettings, logger: Logger
|
||||
) -> AsyncIterator[SessionDirectory]:
|
||||
origin = PostgresSessionDirectory(database)
|
||||
if settings.cache_url is None:
|
||||
yield origin
|
||||
return
|
||||
client = Redis.from_url(
|
||||
settings.cache_url.get_secret_value(),
|
||||
socket_connect_timeout=settings.cache_timeout_seconds,
|
||||
socket_timeout=settings.cache_timeout_seconds,
|
||||
retry=Retry(NoBackoff(), 1),
|
||||
)
|
||||
try:
|
||||
yield CachedSessionDirectory(
|
||||
origin,
|
||||
client,
|
||||
logger,
|
||||
limit=timedelta(seconds=settings.session_cache_ttl_seconds),
|
||||
cooldown=settings.cache_cooldown_seconds,
|
||||
)
|
||||
finally:
|
||||
await client.aclose()
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def verify(self, users: UserDirectory, hasher: PasswordHasher) -> VerifyCredentials:
|
||||
return VerifyCredentials(users, hasher)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def authenticate(self, sessions: SessionDirectory, clock: Clock) -> Authenticate:
|
||||
return Authenticate(sessions, clock)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def unit_of_work(self, database: Database) -> IdentityUnitOfWork:
|
||||
return PostgresIdentityUnitOfWork(database)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def current_user(self, users: UserDirectory) -> GetCurrentUser:
|
||||
return GetCurrentUser(users)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def command_bus(
|
||||
self,
|
||||
uow: IdentityUnitOfWork,
|
||||
publisher: EventPublisher,
|
||||
clock: Clock,
|
||||
ids: IdGenerator,
|
||||
hasher: PasswordHasher,
|
||||
sessions: SessionDirectory,
|
||||
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),
|
||||
}
|
||||
return IdentityCommandBus(handlers, uow, publisher)
|
||||
@@ -0,0 +1,20 @@
|
||||
from messenger.identity.domain.events import SessionClosed, SessionOpened, UserRegistered
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
LOG_FIELDS = frozenset({"actor_id"})
|
||||
|
||||
|
||||
class IdentityJournal:
|
||||
__slots__ = ("_logger",)
|
||||
|
||||
def __init__(self, logger: Logger) -> None:
|
||||
self._logger = logger
|
||||
|
||||
async def on_user_registered(self, event: UserRegistered) -> None:
|
||||
self._logger.info("audit.user_registered", actor_id=str(event.user_id))
|
||||
|
||||
async def on_session_opened(self, event: SessionOpened) -> None:
|
||||
self._logger.info("audit.session_opened", actor_id=str(event.user_id))
|
||||
|
||||
async def on_session_closed(self, event: SessionClosed) -> None:
|
||||
self._logger.info("audit.session_closed", actor_id=str(event.user_id))
|
||||
@@ -0,0 +1,42 @@
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
from messenger.identity.domain.models import Session, User
|
||||
|
||||
|
||||
class CreateUserRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
username: str
|
||||
display_name: str
|
||||
password: str
|
||||
|
||||
|
||||
class UserOut(BaseModel):
|
||||
id: UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
|
||||
@classmethod
|
||||
def of(cls, user: User) -> UserOut:
|
||||
return cls(
|
||||
id=user.id,
|
||||
username=user.username.value,
|
||||
display_name=user.display_name.value,
|
||||
created_at=user.created_at,
|
||||
)
|
||||
|
||||
|
||||
class SessionOut(BaseModel):
|
||||
token: str
|
||||
token_type: Literal["Bearer"] = "Bearer"
|
||||
expires_at: datetime
|
||||
user: UserOut
|
||||
|
||||
@classmethod
|
||||
def of(cls, token: str, session: Session, user: User) -> SessionOut:
|
||||
return cls(token=token, expires_at=session.expires_at, user=UserOut.of(user))
|
||||
@@ -0,0 +1,35 @@
|
||||
import asyncio
|
||||
import secrets
|
||||
|
||||
from argon2 import PasswordHasher, Type
|
||||
from argon2.exceptions import InvalidHashError, VerificationError
|
||||
|
||||
TIME_COST = 2
|
||||
MEMORY_COST_KIB = 19_456
|
||||
PARALLELISM = 1
|
||||
|
||||
|
||||
class Argon2PasswordHasher:
|
||||
__slots__ = ("_dummy", "_hasher", "_slots")
|
||||
|
||||
def __init__(self, concurrency: int) -> None:
|
||||
self._hasher = PasswordHasher(
|
||||
time_cost=TIME_COST,
|
||||
memory_cost=MEMORY_COST_KIB,
|
||||
parallelism=PARALLELISM,
|
||||
type=Type.ID,
|
||||
)
|
||||
self._slots = asyncio.Semaphore(concurrency)
|
||||
self._dummy = self._hasher.hash(secrets.token_urlsafe(16))
|
||||
|
||||
async def hash(self, password: str) -> str:
|
||||
async with self._slots:
|
||||
return await asyncio.to_thread(self._hasher.hash, password)
|
||||
|
||||
async def verify(self, password_hash: str | None, password: str) -> bool:
|
||||
async with self._slots:
|
||||
try:
|
||||
await asyncio.to_thread(self._hasher.verify, password_hash or self._dummy, password)
|
||||
except VerificationError, InvalidHashError:
|
||||
return False
|
||||
return password_hash is not None
|
||||
@@ -0,0 +1,124 @@
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from asyncpg import Record
|
||||
|
||||
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
|
||||
"""
|
||||
|
||||
|
||||
def user_of(row: Record | 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"],
|
||||
)
|
||||
|
||||
|
||||
class PostgresUserRepository:
|
||||
__slots__ = ("_connection",)
|
||||
|
||||
def __init__(self, connection: Connection) -> None:
|
||||
self._connection = connection
|
||||
|
||||
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,
|
||||
)
|
||||
if inserted is None:
|
||||
raise UsernameAlreadyTaken("username уже занят")
|
||||
|
||||
|
||||
class PostgresSessionRepository:
|
||||
__slots__ = ("_connection",)
|
||||
|
||||
def __init__(self, connection: Connection) -> None:
|
||||
self._connection = connection
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
async def remove(self, token_hash: bytes) -> None:
|
||||
await self._connection.execute(DELETE_SESSION, token_hash)
|
||||
|
||||
|
||||
class PostgresIdentityUnitOfWork(PostgresUnitOfWork):
|
||||
__slots__ = ()
|
||||
|
||||
@property
|
||||
def users(self) -> PostgresUserRepository:
|
||||
return PostgresUserRepository(self.connection)
|
||||
|
||||
@property
|
||||
def sessions(self) -> PostgresSessionRepository:
|
||||
return PostgresSessionRepository(self.connection)
|
||||
|
||||
|
||||
class PostgresUserDirectory:
|
||||
__slots__ = ("_database",)
|
||||
|
||||
def __init__(self, database: Database) -> None:
|
||||
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 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))
|
||||
|
||||
|
||||
class PostgresSessionDirectory:
|
||||
__slots__ = ("_database",)
|
||||
|
||||
def __init__(self, database: Database) -> None:
|
||||
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
|
||||
@@ -0,0 +1,102 @@
|
||||
import time
|
||||
from collections.abc import Awaitable
|
||||
from datetime import datetime, timedelta
|
||||
from uuid import UUID
|
||||
|
||||
from redis.asyncio import Redis
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from messenger.identity.application.ports import SessionDirectory
|
||||
from messenger.identity.domain.models import Session
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
REVOKED = "-"
|
||||
FAILURES = (RedisError, OSError)
|
||||
|
||||
|
||||
def key_of(token_hash: bytes) -> str:
|
||||
return f"session:{token_hash.hex()}"
|
||||
|
||||
|
||||
def milliseconds(moment: datetime) -> int:
|
||||
return int(moment.timestamp() * 1000)
|
||||
|
||||
|
||||
def encode(session: Session) -> str:
|
||||
return f"{session.user_id} {session.created_at.isoformat()} {session.expires_at.isoformat()}"
|
||||
|
||||
|
||||
def decode(token_hash: bytes, value: str) -> Session:
|
||||
user_id, created_at, expires_at = value.split(" ")
|
||||
return Session(
|
||||
token_hash=token_hash,
|
||||
user_id=UUID(user_id),
|
||||
created_at=datetime.fromisoformat(created_at),
|
||||
expires_at=datetime.fromisoformat(expires_at),
|
||||
)
|
||||
|
||||
|
||||
class CachedSessionDirectory:
|
||||
__slots__ = ("_client", "_cooldown", "_limit", "_logger", "_origin", "_resume_at")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
origin: SessionDirectory,
|
||||
client: Redis,
|
||||
logger: Logger,
|
||||
*,
|
||||
limit: timedelta,
|
||||
cooldown: float,
|
||||
) -> None:
|
||||
self._origin = origin
|
||||
self._client = client
|
||||
self._logger = logger
|
||||
self._limit = limit
|
||||
self._cooldown = cooldown
|
||||
self._resume_at = 0.0
|
||||
|
||||
async def find(self, token_hash: bytes, now: datetime) -> Session | None:
|
||||
key = key_of(token_hash)
|
||||
cached = await self._read(key)
|
||||
if cached == REVOKED:
|
||||
return None
|
||||
if cached is not None:
|
||||
session = decode(token_hash, cached)
|
||||
return session if session.expires_at > now else None
|
||||
session = await self._origin.find(token_hash, now)
|
||||
if session is not None and self._closed():
|
||||
until = milliseconds(min(session.expires_at, now + self._limit))
|
||||
await self._quietly(self._client.set(key, encode(session), pxat=until, nx=True))
|
||||
return session
|
||||
|
||||
async def invalidate(self, session: Session) -> None:
|
||||
if not self._closed():
|
||||
raise Unavailable("кэш сессий недоступен")
|
||||
try:
|
||||
await self._client.set(
|
||||
key_of(session.token_hash), REVOKED, pxat=milliseconds(session.expires_at)
|
||||
)
|
||||
except FAILURES as error:
|
||||
self._trip(error)
|
||||
raise Unavailable("кэш сессий недоступен") from error
|
||||
|
||||
async def _read(self, key: str) -> str | None:
|
||||
if not self._closed():
|
||||
return None
|
||||
value = await self._quietly(self._client.get(key))
|
||||
return value.decode() if isinstance(value, bytes) else value
|
||||
|
||||
async def _quietly[ResultT](self, call: Awaitable[ResultT]) -> ResultT | None:
|
||||
try:
|
||||
return await call
|
||||
except FAILURES as error:
|
||||
self._trip(error)
|
||||
return None
|
||||
|
||||
def _closed(self) -> bool:
|
||||
return time.monotonic() >= self._resume_at
|
||||
|
||||
def _trip(self, error: Exception) -> None:
|
||||
self._resume_at = time.monotonic() + self._cooldown
|
||||
self._logger.warning("cache.bypassed", error=type(error).__name__, limit=self._cooldown)
|
||||
@@ -0,0 +1,162 @@
|
||||
from collections.abc import AsyncIterator, Sequence
|
||||
from contextlib import asynccontextmanager
|
||||
from uuid import UUID
|
||||
|
||||
from dishka import Provider, Scope, make_async_container, provide
|
||||
from dishka.integrations.fastapi import FastapiProvider, setup_dishka
|
||||
from fastapi import FastAPI
|
||||
|
||||
from messenger.attachments.application.ports import AttachmentDirectory, ChatMembership
|
||||
from messenger.attachments.config import AttachmentsSettings
|
||||
from messenger.attachments.entrypoints.errors import ERROR_CODES as ATTACHMENT_ERRORS
|
||||
from messenger.attachments.entrypoints.http import UPLOAD_PATH, attachments_router, uploads_router
|
||||
from messenger.attachments.entrypoints.ioc import AttachmentsProvider
|
||||
from messenger.attachments.entrypoints.journal import LOG_FIELDS as ATTACHMENT_FIELDS
|
||||
from messenger.attachments.entrypoints.journal import subscribe_journal
|
||||
from messenger.attachments.entrypoints.sweeper import UploadSweeper
|
||||
from messenger.identity.config import IdentitySettings
|
||||
from messenger.identity.domain.events import SessionClosed, SessionOpened, UserRegistered
|
||||
from messenger.identity.entrypoints.authentication import challenge_for, guard
|
||||
from messenger.identity.entrypoints.errors import ERROR_CODES as IDENTITY_ERRORS
|
||||
from messenger.identity.entrypoints.http import router as users_router
|
||||
from messenger.identity.entrypoints.http import sessions_router
|
||||
from messenger.identity.entrypoints.ioc import IdentityProvider
|
||||
from messenger.identity.entrypoints.journal import LOG_FIELDS as IDENTITY_FIELDS
|
||||
from messenger.identity.entrypoints.journal import IdentityJournal
|
||||
from messenger.messaging.application.ports import AttachmentStates, ChatDirectory
|
||||
from messenger.messaging.config import MessagingSettings
|
||||
from messenger.messaging.domain.events import ChatCreated, MessagePosted
|
||||
from messenger.messaging.entrypoints.errors import ERROR_CODES as MESSAGING_ERRORS
|
||||
from messenger.messaging.entrypoints.http import chats_router, messages_router
|
||||
from messenger.messaging.entrypoints.ioc import MessagingProvider
|
||||
from messenger.messaging.entrypoints.journal import LOG_FIELDS as MESSAGING_FIELDS
|
||||
from messenger.messaging.entrypoints.journal import MessagingJournal
|
||||
from messenger.shared.application.messagebus import EventBus
|
||||
from messenger.shared.application.ports import Logger
|
||||
from messenger.shared.config import PlatformSettings
|
||||
from messenger.shared.entrypoints import errors, health
|
||||
from messenger.shared.entrypoints.config import TransportSettings
|
||||
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"})
|
||||
|
||||
LOG_FIELDS = (
|
||||
PLATFORM_FIELDS | TRANSPORT_FIELDS | IDENTITY_FIELDS | MESSAGING_FIELDS | ATTACHMENT_FIELDS
|
||||
)
|
||||
ERROR_CODES = {**IDENTITY_ERRORS, **MESSAGING_ERRORS, **ATTACHMENT_ERRORS}
|
||||
|
||||
|
||||
class MessagingMembership:
|
||||
__slots__ = ("_chats",)
|
||||
|
||||
def __init__(self, chats: ChatDirectory) -> None:
|
||||
self._chats = chats
|
||||
|
||||
async def is_member(self, chat_id: UUID, user_id: UUID) -> bool:
|
||||
return await self._chats.chat_for_member(chat_id, user_id) is not None
|
||||
|
||||
|
||||
class AttachmentGate:
|
||||
__slots__ = ("_attachments",)
|
||||
|
||||
def __init__(self, attachments: AttachmentDirectory) -> None:
|
||||
self._attachments = attachments
|
||||
|
||||
async def unusable(self, chat_id: UUID, attachment_ids: Sequence[UUID]) -> bool:
|
||||
return await self._attachments.failed_among(chat_id, attachment_ids)
|
||||
|
||||
|
||||
class ZoneLinks(Provider):
|
||||
@provide(scope=Scope.APP)
|
||||
def membership(self, chats: ChatDirectory) -> ChatMembership:
|
||||
return MessagingMembership(chats)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def attachment_states(self, attachments: AttachmentDirectory) -> AttachmentStates:
|
||||
return AttachmentGate(attachments)
|
||||
|
||||
|
||||
def wire_events(bus: EventBus, logger: Logger) -> None:
|
||||
identity = IdentityJournal(logger)
|
||||
bus.subscribe(UserRegistered, identity.on_user_registered)
|
||||
bus.subscribe(SessionOpened, identity.on_session_opened)
|
||||
bus.subscribe(SessionClosed, identity.on_session_closed)
|
||||
|
||||
messaging = MessagingJournal(logger)
|
||||
bus.subscribe(ChatCreated, messaging.on_chat_created)
|
||||
bus.subscribe(MessagePosted, messaging.on_message_posted)
|
||||
|
||||
subscribe_journal(bus, logger)
|
||||
|
||||
|
||||
def create_app(
|
||||
*,
|
||||
platform: PlatformSettings | None = None,
|
||||
transport: TransportSettings | None = None,
|
||||
identity: IdentitySettings | None = None,
|
||||
messaging: MessagingSettings | None = None,
|
||||
attachments: AttachmentsSettings | None = None,
|
||||
overrides: Sequence[Provider] = (),
|
||||
) -> FastAPI:
|
||||
platform = platform or PlatformSettings()
|
||||
transport = transport or TransportSettings()
|
||||
identity = identity or IdentitySettings()
|
||||
messaging = messaging or MessagingSettings()
|
||||
attachments = attachments or AttachmentsSettings()
|
||||
logger = StructlogLogger(level=platform.log_level, allowed_fields=LOG_FIELDS)
|
||||
container = make_async_container(
|
||||
PlatformProvider(platform, logger),
|
||||
IdentityProvider(identity),
|
||||
MessagingProvider(messaging),
|
||||
AttachmentsProvider(attachments),
|
||||
ZoneLinks(),
|
||||
FastapiProvider(),
|
||||
*overrides,
|
||||
)
|
||||
sweeper = UploadSweeper(container, attachments, logger)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
||||
bus = await container.get(EventBus)
|
||||
wire_events(bus, logger)
|
||||
bus.start()
|
||||
sweeper.start()
|
||||
logger.info("service.started")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
await sweeper.stop()
|
||||
await bus.stop()
|
||||
await container.close()
|
||||
logger.info("service.stopped")
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUSI Messenger",
|
||||
version="1.6.0",
|
||||
lifespan=lifespan,
|
||||
docs_url="/docs" if transport.docs else None,
|
||||
redoc_url=None,
|
||||
openapi_url="/openapi.json" if transport.docs else None,
|
||||
)
|
||||
app.add_middleware(
|
||||
RequestPipeline,
|
||||
logger=logger,
|
||||
max_bytes=transport.max_body_bytes,
|
||||
timeout=transport.request_timeout_seconds,
|
||||
guard=guard,
|
||||
instance=platform.instance_id,
|
||||
limits=((UPLOAD_PATH, attachments.max_upload_bytes),),
|
||||
)
|
||||
errors.install(app, logger, ERROR_CODES, challenge_for, platform.instance_id)
|
||||
app.include_router(health.router)
|
||||
app.include_router(users_router)
|
||||
app.include_router(sessions_router)
|
||||
app.include_router(chats_router)
|
||||
app.include_router(messages_router)
|
||||
app.include_router(uploads_router)
|
||||
app.include_router(attachments_router)
|
||||
setup_dishka(container, app)
|
||||
app.state.sweeper = sweeper
|
||||
return app
|
||||
@@ -0,0 +1,5 @@
|
||||
from messenger.shared.application.messagebus import CommandBus
|
||||
|
||||
|
||||
class MessagingCommandBus(CommandBus):
|
||||
__slots__ = ()
|
||||
@@ -0,0 +1,22 @@
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.shared.application.commands import Command
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CreateChat(Command):
|
||||
creator_id: UUID
|
||||
title: str
|
||||
member_ids: Sequence[UUID]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PostMessage(Command):
|
||||
sender_id: UUID
|
||||
chat_id: UUID
|
||||
text: str
|
||||
key: str
|
||||
fingerprint: bytes
|
||||
attachment_ids: tuple[UUID, ...] = ()
|
||||
@@ -0,0 +1,73 @@
|
||||
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.shared.application.ports import Clock, IdGenerator
|
||||
|
||||
|
||||
class CreateChatHandler:
|
||||
__slots__ = ("_clock", "_ids", "_uow")
|
||||
|
||||
def __init__(self, uow: MessagingUnitOfWork, clock: Clock, ids: IdGenerator) -> None:
|
||||
self._uow = uow
|
||||
self._clock = clock
|
||||
self._ids = ids
|
||||
|
||||
async def __call__(self, command: CreateChat) -> Chat:
|
||||
chat = Chat.create(
|
||||
chat_id=self._ids.new_id(),
|
||||
title=command.title,
|
||||
member_ids=command.member_ids,
|
||||
creator_id=command.creator_id,
|
||||
created_at=self._clock.now(),
|
||||
)
|
||||
async with self._uow.transaction():
|
||||
await self._uow.chats.add(chat)
|
||||
await self._uow.commit()
|
||||
return chat
|
||||
|
||||
|
||||
class PostMessageHandler:
|
||||
__slots__ = ("_attachments", "_clock", "_ids", "_ttl", "_uow")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
uow: MessagingUnitOfWork,
|
||||
attachments: AttachmentStates,
|
||||
clock: Clock,
|
||||
ids: IdGenerator,
|
||||
ttl: timedelta,
|
||||
) -> None:
|
||||
self._uow = uow
|
||||
self._attachments = attachments
|
||||
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()
|
||||
return message
|
||||
@@ -0,0 +1,52 @@
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime
|
||||
from typing import Protocol, runtime_checkable
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.messaging.domain.keys import HistoryKey
|
||||
from messenger.messaging.domain.models import Chat, Message, Receipt
|
||||
from messenger.shared.application.ports import UnitOfWork
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class CursorCodec(Protocol):
|
||||
def encode(self, scope: str, key: HistoryKey) -> str: ...
|
||||
|
||||
def decode(self, scope: str, raw: str) -> HistoryKey: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
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
|
||||
) -> Receipt | None: ...
|
||||
|
||||
async def append(self, receipt: Receipt) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class MessagingUnitOfWork(UnitOfWork, Protocol):
|
||||
@property
|
||||
def chats(self) -> ChatRepository: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class AttachmentStates(Protocol):
|
||||
async def unusable(self, chat_id: UUID, attachment_ids: Sequence[UUID]) -> bool: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ChatDirectory(Protocol):
|
||||
async def chat_for_member(self, chat_id: UUID, user_id: UUID) -> Chat | None: ...
|
||||
|
||||
async def chats_of(
|
||||
self, user_id: UUID, *, after: HistoryKey | None, limit: int
|
||||
) -> tuple[list[Chat], bool]: ...
|
||||
|
||||
async def history(
|
||||
self, chat_id: UUID, *, after: HistoryKey | None, limit: int
|
||||
) -> tuple[list[Message], bool]: ...
|
||||
@@ -0,0 +1,73 @@
|
||||
from dataclasses import dataclass
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.messaging.application.ports import ChatDirectory, CursorCodec
|
||||
from messenger.messaging.domain.errors import ChatNotFound
|
||||
from messenger.messaging.domain.keys import HistoryKey
|
||||
from messenger.messaging.domain.models import Chat, Message
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Page[ItemT]:
|
||||
items: list[ItemT]
|
||||
next_cursor: str | None
|
||||
|
||||
|
||||
def chats_scope(user_id: UUID) -> str:
|
||||
return f"chats:{user_id}"
|
||||
|
||||
|
||||
def messages_scope(chat_id: UUID) -> str:
|
||||
return f"messages:{chat_id}"
|
||||
|
||||
|
||||
class GetChat:
|
||||
__slots__ = ("_chats",)
|
||||
|
||||
def __init__(self, chats: ChatDirectory) -> None:
|
||||
self._chats = chats
|
||||
|
||||
async def __call__(self, chat_id: UUID, user_id: UUID) -> Chat:
|
||||
chat = await self._chats.chat_for_member(chat_id, user_id)
|
||||
if chat is None:
|
||||
raise ChatNotFound("чат не найден")
|
||||
return chat
|
||||
|
||||
|
||||
class ListChats:
|
||||
__slots__ = ("_chats", "_cursors")
|
||||
|
||||
def __init__(self, chats: ChatDirectory, cursors: CursorCodec) -> None:
|
||||
self._chats = chats
|
||||
self._cursors = cursors
|
||||
|
||||
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
|
||||
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)
|
||||
|
||||
|
||||
class ReadHistory:
|
||||
__slots__ = ("_chats", "_cursors")
|
||||
|
||||
def __init__(self, chats: ChatDirectory, cursors: CursorCodec) -> None:
|
||||
self._chats = chats
|
||||
self._cursors = cursors
|
||||
|
||||
async def __call__(
|
||||
self,
|
||||
chat_id: UUID,
|
||||
user_id: UUID,
|
||||
*,
|
||||
limit: int,
|
||||
cursor: str | None,
|
||||
) -> Page[Message]:
|
||||
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
|
||||
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)
|
||||
@@ -0,0 +1,8 @@
|
||||
from pydantic import Field, SecretStr
|
||||
|
||||
from messenger.shared.config import Settings
|
||||
|
||||
|
||||
class MessagingSettings(Settings):
|
||||
cursor_secret: SecretStr = Field(min_length=16)
|
||||
idempotency_ttl_seconds: int = Field(default=86_400, ge=1)
|
||||
@@ -0,0 +1,37 @@
|
||||
from messenger.shared.domain.errors import DomainError
|
||||
|
||||
|
||||
class MessagingError(DomainError):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidChatData(MessagingError):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidMessageText(MessagingError):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidPageRequest(MessagingError):
|
||||
pass
|
||||
|
||||
|
||||
class ChatNotFound(MessagingError):
|
||||
pass
|
||||
|
||||
|
||||
class IdempotencyConflict(MessagingError):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidAttachmentList(MessagingError):
|
||||
pass
|
||||
|
||||
|
||||
class UnknownAttachment(MessagingError):
|
||||
pass
|
||||
|
||||
|
||||
class AttachmentUnavailable(MessagingError):
|
||||
pass
|
||||
@@ -0,0 +1,24 @@
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ChatCreated(DomainEvent):
|
||||
chat_id: UUID
|
||||
creator_id: UUID
|
||||
member_count: int
|
||||
created_at: datetime
|
||||
name: str = field(init=False, default="chat.created")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class MessagePosted(DomainEvent):
|
||||
message_id: UUID
|
||||
chat_id: UUID
|
||||
sender_id: UUID
|
||||
text_length: int
|
||||
created_at: datetime
|
||||
name: str = field(init=False, default="message.posted")
|
||||
@@ -0,0 +1,3 @@
|
||||
from datetime import datetime
|
||||
|
||||
type HistoryKey = tuple[datetime, int]
|
||||
@@ -0,0 +1,177 @@
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.messaging.domain.errors import (
|
||||
ChatNotFound,
|
||||
IdempotencyConflict,
|
||||
InvalidAttachmentList,
|
||||
InvalidChatData,
|
||||
InvalidMessageText,
|
||||
)
|
||||
from messenger.messaging.domain.events import ChatCreated, MessagePosted
|
||||
from messenger.messaging.domain.keys import HistoryKey
|
||||
from messenger.messaging.domain.values import (
|
||||
CHAT_MEMBERS_MAX,
|
||||
MESSAGE_ATTACHMENTS_MAX,
|
||||
ChatTitle,
|
||||
MessageText,
|
||||
)
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
TICK = timedelta(microseconds=1)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Message:
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
sender_id: UUID
|
||||
text: MessageText
|
||||
created_at: datetime
|
||||
attachment_ids: tuple[UUID, ...] = ()
|
||||
|
||||
@property
|
||||
def key(self) -> HistoryKey:
|
||||
return (self.created_at, self.id.int)
|
||||
|
||||
|
||||
def attachment_list(text: MessageText, attachment_ids: Sequence[UUID]) -> tuple[UUID, ...]:
|
||||
if len(attachment_ids) > MESSAGE_ATTACHMENTS_MAX:
|
||||
raise InvalidAttachmentList(
|
||||
f"поле attachment_ids содержит больше {MESSAGE_ATTACHMENTS_MAX} вложений"
|
||||
)
|
||||
if len(set(attachment_ids)) != len(attachment_ids):
|
||||
raise InvalidAttachmentList("поле attachment_ids содержит дубликаты")
|
||||
if not text.value and not attachment_ids:
|
||||
raise InvalidMessageText("пустой text допустим только с вложением")
|
||||
return tuple(attachment_ids)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Receipt:
|
||||
key: str
|
||||
fingerprint: bytes
|
||||
message: Message
|
||||
|
||||
def replay(self, fingerprint: bytes) -> Message:
|
||||
if fingerprint != self.fingerprint:
|
||||
raise IdempotencyConflict("ключ идемпотентности уже использован с другим телом")
|
||||
return self.message
|
||||
|
||||
|
||||
class Chat:
|
||||
__slots__ = (
|
||||
"_events",
|
||||
"_members",
|
||||
"created_at",
|
||||
"id",
|
||||
"last_message_at",
|
||||
"member_ids",
|
||||
"title",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
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
|
||||
def create(
|
||||
cls,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
title: str,
|
||||
member_ids: Sequence[UUID],
|
||||
creator_id: UUID,
|
||||
created_at: datetime,
|
||||
) -> Chat:
|
||||
if not member_ids:
|
||||
raise InvalidChatData("поле member_ids не может быть пустым")
|
||||
if len(member_ids) > CHAT_MEMBERS_MAX:
|
||||
raise InvalidChatData(f"поле member_ids содержит больше {CHAT_MEMBERS_MAX} участников")
|
||||
unique = set(member_ids)
|
||||
if len(unique) != len(member_ids):
|
||||
raise InvalidChatData("поле member_ids содержит дубликаты")
|
||||
if creator_id not in unique:
|
||||
raise InvalidChatData("создатель чата обязан входить в список member_ids")
|
||||
chat = cls(
|
||||
chat_id=chat_id,
|
||||
title=ChatTitle(title),
|
||||
member_ids=member_ids,
|
||||
created_at=created_at,
|
||||
)
|
||||
chat.record(
|
||||
ChatCreated(
|
||||
chat_id=chat.id,
|
||||
creator_id=creator_id,
|
||||
member_count=len(unique),
|
||||
created_at=created_at,
|
||||
)
|
||||
)
|
||||
return chat
|
||||
|
||||
@property
|
||||
def key(self) -> HistoryKey:
|
||||
return (self.created_at, self.id.int)
|
||||
|
||||
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
|
||||
@@ -0,0 +1,40 @@
|
||||
from dataclasses import dataclass
|
||||
|
||||
from messenger.messaging.domain.errors import InvalidChatData, InvalidMessageText
|
||||
|
||||
CHAT_TITLE_MAX = 100
|
||||
MESSAGE_TEXT_MAX = 4000
|
||||
CHAT_MEMBERS_MAX = 100
|
||||
MESSAGE_ATTACHMENTS_MAX = 10
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ChatTitle:
|
||||
value: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.value, str):
|
||||
raise InvalidChatData("поле title должно быть строкой")
|
||||
if not self.value.strip():
|
||||
raise InvalidChatData("поле title не может быть пустым или состоять из пробелов")
|
||||
if len(self.value) > CHAT_TITLE_MAX:
|
||||
raise InvalidChatData(f"поле title длиннее {CHAT_TITLE_MAX} символов Unicode")
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.value
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class MessageText:
|
||||
value: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.value, str):
|
||||
raise InvalidMessageText("поле text должно быть строкой")
|
||||
if self.value and not self.value.strip():
|
||||
raise InvalidMessageText("поле text не может состоять из пробелов")
|
||||
if len(self.value) > MESSAGE_TEXT_MAX:
|
||||
raise InvalidMessageText(f"поле text длиннее {MESSAGE_TEXT_MAX} символов Unicode")
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.value
|
||||
@@ -0,0 +1,22 @@
|
||||
from messenger.messaging.domain.errors import (
|
||||
AttachmentUnavailable,
|
||||
ChatNotFound,
|
||||
IdempotencyConflict,
|
||||
InvalidAttachmentList,
|
||||
InvalidChatData,
|
||||
InvalidMessageText,
|
||||
InvalidPageRequest,
|
||||
UnknownAttachment,
|
||||
)
|
||||
from messenger.shared.domain.errors import DomainError
|
||||
|
||||
ERROR_CODES: dict[type[DomainError], tuple[str, int]] = {
|
||||
InvalidChatData: ("invalid_request", 400),
|
||||
InvalidMessageText: ("invalid_request", 400),
|
||||
InvalidPageRequest: ("invalid_request", 400),
|
||||
InvalidAttachmentList: ("invalid_request", 400),
|
||||
ChatNotFound: ("not_found", 404),
|
||||
UnknownAttachment: ("not_found", 404),
|
||||
IdempotencyConflict: ("conflict", 409),
|
||||
AttachmentUnavailable: ("conflict", 409),
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
from typing import Annotated
|
||||
from uuid import UUID
|
||||
|
||||
from dishka.integrations.fastapi import FromDishka, inject
|
||||
from fastapi import APIRouter, Query, status
|
||||
|
||||
from messenger.messaging.application.bus import MessagingCommandBus
|
||||
from messenger.messaging.application.commands import CreateChat, PostMessage
|
||||
from messenger.messaging.application.queries import GetChat, ListChats, ReadHistory
|
||||
from messenger.messaging.entrypoints.schemas import (
|
||||
ChatOut,
|
||||
CreateChatRequest,
|
||||
CreateMessageRequest,
|
||||
IdempotencyKey,
|
||||
MessageOut,
|
||||
PageOut,
|
||||
PageQuery,
|
||||
)
|
||||
from messenger.shared.entrypoints.actor import Actor
|
||||
|
||||
chats_router = APIRouter(prefix="/api/v1/chats", tags=["chats"])
|
||||
messages_router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["messages"])
|
||||
|
||||
|
||||
@chats_router.post("", status_code=status.HTTP_201_CREATED)
|
||||
@inject
|
||||
async def create_chat(
|
||||
actor: Actor,
|
||||
body: CreateChatRequest,
|
||||
bus: FromDishka[MessagingCommandBus],
|
||||
) -> ChatOut:
|
||||
chat = await bus.execute(
|
||||
CreateChat(creator_id=actor, title=body.title, member_ids=body.member_ids)
|
||||
)
|
||||
return ChatOut.of(chat)
|
||||
|
||||
|
||||
@chats_router.get("")
|
||||
@inject
|
||||
async def list_chats(
|
||||
actor: Actor,
|
||||
page: Annotated[PageQuery, Query()],
|
||||
query: FromDishka[ListChats],
|
||||
) -> PageOut[ChatOut]:
|
||||
chats = await query(actor, limit=page.limit, cursor=page.cursor)
|
||||
return PageOut[ChatOut].of(chats, ChatOut.of)
|
||||
|
||||
|
||||
@chats_router.get("/{chat_id}")
|
||||
@inject
|
||||
async def read_chat(
|
||||
chat_id: UUID,
|
||||
actor: Actor,
|
||||
query: FromDishka[GetChat],
|
||||
) -> ChatOut:
|
||||
return ChatOut.of(await query(chat_id, actor))
|
||||
|
||||
|
||||
@messages_router.post("", status_code=status.HTTP_201_CREATED)
|
||||
@inject
|
||||
async def post_message(
|
||||
chat_id: UUID,
|
||||
actor: Actor,
|
||||
body: CreateMessageRequest,
|
||||
key: IdempotencyKey,
|
||||
bus: FromDishka[MessagingCommandBus],
|
||||
) -> MessageOut:
|
||||
message = await bus.execute(
|
||||
PostMessage(
|
||||
sender_id=actor,
|
||||
chat_id=chat_id,
|
||||
text=body.text,
|
||||
key=key,
|
||||
fingerprint=body.fingerprint(),
|
||||
attachment_ids=tuple(body.attachment_ids),
|
||||
)
|
||||
)
|
||||
return MessageOut.of(message)
|
||||
|
||||
|
||||
@messages_router.get("")
|
||||
@inject
|
||||
async def read_history(
|
||||
chat_id: UUID,
|
||||
actor: Actor,
|
||||
page: Annotated[PageQuery, Query()],
|
||||
query: FromDishka[ReadHistory],
|
||||
) -> PageOut[MessageOut]:
|
||||
messages = await query(chat_id, actor, limit=page.limit, cursor=page.cursor)
|
||||
return PageOut[MessageOut].of(messages, MessageOut.of)
|
||||
@@ -0,0 +1,75 @@
|
||||
from datetime import timedelta
|
||||
|
||||
from dishka import Provider, Scope, provide
|
||||
|
||||
from messenger.messaging.application.bus import MessagingCommandBus
|
||||
from messenger.messaging.application.commands import CreateChat, PostMessage
|
||||
from messenger.messaging.application.handlers import CreateChatHandler, PostMessageHandler
|
||||
from messenger.messaging.application.ports import (
|
||||
AttachmentStates,
|
||||
ChatDirectory,
|
||||
CursorCodec,
|
||||
MessagingUnitOfWork,
|
||||
)
|
||||
from messenger.messaging.application.queries import GetChat, ListChats, ReadHistory
|
||||
from messenger.messaging.config import MessagingSettings
|
||||
from messenger.messaging.infrastructure.cursor import SignedCursorCodec
|
||||
from messenger.messaging.infrastructure.postgres import (
|
||||
PostgresChatDirectory,
|
||||
PostgresMessagingUnitOfWork,
|
||||
)
|
||||
from messenger.shared.application.commands import Command
|
||||
from messenger.shared.application.messagebus import CommandHandler
|
||||
from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
|
||||
|
||||
class MessagingProvider(Provider):
|
||||
def __init__(self, settings: MessagingSettings) -> None:
|
||||
super().__init__()
|
||||
self._settings = settings
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def settings(self) -> MessagingSettings:
|
||||
return self._settings
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def directory(self, database: Database) -> ChatDirectory:
|
||||
return PostgresChatDirectory(database)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def cursors(self, settings: MessagingSettings) -> CursorCodec:
|
||||
return SignedCursorCodec(settings.cursor_secret.get_secret_value().encode())
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def unit_of_work(self, database: Database) -> MessagingUnitOfWork:
|
||||
return PostgresMessagingUnitOfWork(database)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def chat(self, directory: ChatDirectory) -> GetChat:
|
||||
return GetChat(directory)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def chat_list(self, directory: ChatDirectory, cursors: CursorCodec) -> ListChats:
|
||||
return ListChats(directory, cursors)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def history(self, directory: ChatDirectory, cursors: CursorCodec) -> ReadHistory:
|
||||
return ReadHistory(directory, cursors)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def command_bus(
|
||||
self,
|
||||
uow: MessagingUnitOfWork,
|
||||
attachments: AttachmentStates,
|
||||
publisher: EventPublisher,
|
||||
clock: Clock,
|
||||
ids: IdGenerator,
|
||||
settings: MessagingSettings,
|
||||
) -> MessagingCommandBus:
|
||||
ttl = timedelta(seconds=settings.idempotency_ttl_seconds)
|
||||
handlers: dict[type[Command], CommandHandler] = {
|
||||
CreateChat: CreateChatHandler(uow, clock, ids),
|
||||
PostMessage: PostMessageHandler(uow, attachments, clock, ids, ttl),
|
||||
}
|
||||
return MessagingCommandBus(handlers, uow, publisher)
|
||||
@@ -0,0 +1,27 @@
|
||||
from messenger.messaging.domain.events import ChatCreated, MessagePosted
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
LOG_FIELDS = frozenset({"chat_id", "message_id", "count"})
|
||||
|
||||
|
||||
class MessagingJournal:
|
||||
__slots__ = ("_logger",)
|
||||
|
||||
def __init__(self, logger: Logger) -> None:
|
||||
self._logger = logger
|
||||
|
||||
async def on_chat_created(self, event: ChatCreated) -> None:
|
||||
self._logger.info(
|
||||
"audit.chat_created",
|
||||
chat_id=str(event.chat_id),
|
||||
actor_id=str(event.creator_id),
|
||||
count=event.member_count,
|
||||
)
|
||||
|
||||
async def on_message_posted(self, event: MessagePosted) -> None:
|
||||
self._logger.info(
|
||||
"audit.message_posted",
|
||||
chat_id=str(event.chat_id),
|
||||
actor_id=str(event.sender_id),
|
||||
message_id=str(event.message_id),
|
||||
)
|
||||
@@ -0,0 +1,85 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime
|
||||
from hashlib import sha256
|
||||
from typing import Annotated, Self
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Header
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from messenger.messaging.application.queries import Page
|
||||
from messenger.messaging.domain.models import Chat, Message
|
||||
|
||||
STRICT = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
type IdempotencyKey = Annotated[
|
||||
str,
|
||||
Header(alias="Idempotency-Key", min_length=1, max_length=128, pattern=r"^[A-Za-z0-9._:-]+$"),
|
||||
]
|
||||
|
||||
|
||||
class CreateChatRequest(BaseModel):
|
||||
model_config = STRICT
|
||||
|
||||
title: str
|
||||
member_ids: list[Annotated[UUID, Field(strict=False)]]
|
||||
|
||||
|
||||
class CreateMessageRequest(BaseModel):
|
||||
model_config = STRICT
|
||||
|
||||
text: str
|
||||
attachment_ids: list[Annotated[UUID, Field(strict=False)]] = Field(default_factory=list)
|
||||
|
||||
def fingerprint(self) -> bytes:
|
||||
return sha256(self.model_dump_json().encode()).digest()
|
||||
|
||||
|
||||
class PageQuery(BaseModel):
|
||||
limit: int = Field(default=50, ge=1, le=100)
|
||||
cursor: str | None = None
|
||||
|
||||
|
||||
class ChatOut(BaseModel):
|
||||
id: UUID
|
||||
title: str
|
||||
member_ids: tuple[UUID, ...]
|
||||
created_at: datetime
|
||||
|
||||
@classmethod
|
||||
def of(cls, chat: Chat) -> ChatOut:
|
||||
return cls(
|
||||
id=chat.id,
|
||||
title=chat.title.value,
|
||||
member_ids=chat.member_ids,
|
||||
created_at=chat.created_at,
|
||||
)
|
||||
|
||||
|
||||
class MessageOut(BaseModel):
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
sender_id: UUID
|
||||
text: str
|
||||
created_at: datetime
|
||||
attachment_ids: tuple[UUID, ...]
|
||||
|
||||
@classmethod
|
||||
def of(cls, message: Message) -> MessageOut:
|
||||
return cls(
|
||||
id=message.id,
|
||||
chat_id=message.chat_id,
|
||||
sender_id=message.sender_id,
|
||||
text=message.text.value,
|
||||
created_at=message.created_at,
|
||||
attachment_ids=message.attachment_ids,
|
||||
)
|
||||
|
||||
|
||||
class PageOut[ItemT](BaseModel):
|
||||
items: list[ItemT]
|
||||
next_cursor: str | None
|
||||
|
||||
@classmethod
|
||||
def of[SourceT](cls, page: Page[SourceT], view: Callable[[SourceT], ItemT]) -> Self:
|
||||
return cls(items=[view(item) for item in page.items], next_cursor=page.next_cursor)
|
||||
@@ -0,0 +1,59 @@
|
||||
import hmac
|
||||
from base64 import urlsafe_b64decode, urlsafe_b64encode
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from hashlib import sha256
|
||||
|
||||
from messenger.messaging.domain.errors import InvalidPageRequest
|
||||
from messenger.messaging.domain.keys import HistoryKey
|
||||
|
||||
VERSION = "1"
|
||||
SIGNATURE_BYTES = 12
|
||||
EPOCH = datetime(1970, 1, 1, tzinfo=UTC)
|
||||
PARTS = 4
|
||||
|
||||
|
||||
def _encode_part(value: bytes) -> str:
|
||||
return urlsafe_b64encode(value).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def _decode_part(value: str) -> bytes:
|
||||
padding = "=" * (-len(value) % 4)
|
||||
try:
|
||||
return urlsafe_b64decode(value + padding)
|
||||
except (ValueError, TypeError) as error:
|
||||
raise InvalidPageRequest("параметр cursor повреждён") from error
|
||||
|
||||
|
||||
class SignedCursorCodec:
|
||||
__slots__ = ("_secret",)
|
||||
|
||||
def __init__(self, secret: bytes) -> None:
|
||||
self._secret = secret
|
||||
|
||||
def encode(self, scope: str, key: HistoryKey) -> str:
|
||||
moment, identifier = key
|
||||
micros = (moment - EPOCH) // timedelta(microseconds=1)
|
||||
body = f"{VERSION}.{micros}.{identifier:032x}"
|
||||
return f"{body}.{_encode_part(self._sign(scope, body))}"
|
||||
|
||||
def decode(self, scope: str, raw: str) -> HistoryKey:
|
||||
parts = raw.split(".")
|
||||
if len(parts) != PARTS or parts[0] != VERSION:
|
||||
raise InvalidPageRequest("параметр cursor не распознан")
|
||||
body = ".".join(parts[:3])
|
||||
if not hmac.compare_digest(self._sign(scope, body), _decode_part(parts[3])):
|
||||
raise InvalidPageRequest("параметр cursor недействителен для этого запроса")
|
||||
try:
|
||||
micros = int(parts[1])
|
||||
identifier = int(parts[2], 16)
|
||||
except ValueError as error:
|
||||
raise InvalidPageRequest("параметр cursor повреждён") from error
|
||||
try:
|
||||
moment = EPOCH + timedelta(microseconds=micros)
|
||||
except (OverflowError, ValueError) as error:
|
||||
raise InvalidPageRequest("параметр cursor повреждён") from error
|
||||
return (moment, identifier)
|
||||
|
||||
def _sign(self, scope: str, body: str) -> bytes:
|
||||
payload = f"{scope}|{body}".encode()
|
||||
return hmac.new(self._secret, payload, sha256).digest()[:SIGNATURE_BYTES]
|
||||
@@ -0,0 +1,219 @@
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from asyncpg import ForeignKeyViolationError, Record
|
||||
|
||||
from messenger.messaging.domain.errors import 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.infrastructure.postgres import (
|
||||
Connection,
|
||||
Database,
|
||||
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
|
||||
"""
|
||||
|
||||
|
||||
def chat_of(row: Record) -> 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:
|
||||
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"]),
|
||||
)
|
||||
|
||||
|
||||
def page[ItemT](rows: Sequence[ItemT], limit: int) -> tuple[list[ItemT], bool]:
|
||||
return list(rows[:limit]), len(rows) > limit
|
||||
|
||||
|
||||
class PostgresChatRepository:
|
||||
__slots__ = ("_connection", "_seen")
|
||||
|
||||
def __init__(self, connection: Connection, seen: list[EventSource]) -> None:
|
||||
self._connection = connection
|
||||
self._seen = seen
|
||||
|
||||
async def add(self, chat: Chat) -> None:
|
||||
await self._connection.execute(INSERT_CHAT, chat.id, chat.title.value, chat.created_at)
|
||||
try:
|
||||
await self._connection.execute(
|
||||
INSERT_MEMBERS, chat.id, list(chat.member_ids), chat.created_at
|
||||
)
|
||||
except ForeignKeyViolationError as error:
|
||||
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
|
||||
) -> 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),
|
||||
)
|
||||
except ForeignKeyViolationError as error:
|
||||
if getattr(error, "constraint_name", None) != ATTACHMENT_FKEY:
|
||||
raise
|
||||
raise UnknownAttachment("вложение не найдено в этом чате") from error
|
||||
|
||||
|
||||
class PostgresMessagingUnitOfWork(PostgresUnitOfWork):
|
||||
__slots__ = ()
|
||||
|
||||
@property
|
||||
def chats(self) -> PostgresChatRepository:
|
||||
return PostgresChatRepository(self.connection, self.seen)
|
||||
|
||||
|
||||
class PostgresChatDirectory:
|
||||
__slots__ = ("_database",)
|
||||
|
||||
def __init__(self, database: Database) -> None:
|
||||
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)
|
||||
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
|
||||
)
|
||||
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
|
||||
)
|
||||
return page([message_of(row) for row in rows], limit)
|
||||
@@ -0,0 +1,70 @@
|
||||
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()
|
||||
@@ -0,0 +1,46 @@
|
||||
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);
|
||||
@@ -0,0 +1,10 @@
|
||||
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)
|
||||
);
|
||||
@@ -0,0 +1,37 @@
|
||||
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);
|
||||
@@ -0,0 +1,70 @@
|
||||
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);
|
||||
@@ -0,0 +1 @@
|
||||
CREATE INDEX jobs_failed_idx ON jobs (updated_at DESC) WHERE status = 'failed';
|
||||
@@ -0,0 +1,66 @@
|
||||
import asyncio
|
||||
import signal
|
||||
|
||||
from dishka import make_async_container
|
||||
from faststream.rabbit import Channel, RabbitBroker
|
||||
|
||||
from messenger.attachments.config import PipelineSettings
|
||||
from messenger.attachments.entrypoints.heartbeat import Heartbeat
|
||||
from messenger.attachments.entrypoints.ioc import PipelineProvider, RelayProvider
|
||||
from messenger.attachments.entrypoints.journal import LOG_FIELDS, subscribe_journal
|
||||
from messenger.attachments.entrypoints.relay import Relay
|
||||
from messenger.shared.application.messagebus import EventBus
|
||||
from messenger.shared.config import PlatformSettings
|
||||
from messenger.shared.entrypoints.ioc import PlatformProvider
|
||||
from messenger.shared.infrastructure.logging import PLATFORM_FIELDS, StructlogLogger
|
||||
|
||||
PING_TIMEOUT_SECONDS = 2.0
|
||||
|
||||
|
||||
async def serve() -> None:
|
||||
platform = PlatformSettings()
|
||||
pipeline = PipelineSettings()
|
||||
logger = StructlogLogger(level=platform.log_level, allowed_fields=PLATFORM_FIELDS | LOG_FIELDS)
|
||||
broker = RabbitBroker(
|
||||
pipeline.broker_url.get_secret_value(),
|
||||
default_channel=Channel(publisher_confirms=True, on_return_raises=True),
|
||||
logger=None,
|
||||
)
|
||||
container = make_async_container(
|
||||
PlatformProvider(platform, logger), PipelineProvider(pipeline), RelayProvider(broker)
|
||||
)
|
||||
stop = asyncio.Event()
|
||||
loop = asyncio.get_running_loop()
|
||||
for signum in (signal.SIGTERM, signal.SIGINT):
|
||||
loop.add_signal_handler(signum, stop.set)
|
||||
await broker.connect()
|
||||
bus = await container.get(EventBus)
|
||||
subscribe_journal(bus, logger)
|
||||
bus.start()
|
||||
relay = Relay(container, pipeline, logger)
|
||||
heartbeat = Heartbeat(
|
||||
pipeline.heartbeat_file,
|
||||
lambda: broker.ping(PING_TIMEOUT_SECONDS),
|
||||
pipeline.heartbeat_interval_seconds,
|
||||
logger,
|
||||
)
|
||||
relay.start()
|
||||
heartbeat.start()
|
||||
logger.info("relay.started")
|
||||
try:
|
||||
await stop.wait()
|
||||
finally:
|
||||
await heartbeat.stop()
|
||||
await relay.stop()
|
||||
await bus.stop()
|
||||
await broker.stop()
|
||||
await container.close()
|
||||
logger.info("relay.stopped")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
asyncio.run(serve())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,2 @@
|
||||
class Command:
|
||||
pass
|
||||
@@ -0,0 +1,2 @@
|
||||
class Unavailable(Exception):
|
||||
pass
|
||||
@@ -0,0 +1,124 @@
|
||||
import asyncio
|
||||
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
||||
from contextlib import suppress
|
||||
from typing import Any
|
||||
|
||||
from messenger.shared.application.commands import Command
|
||||
from messenger.shared.application.ports import EventPublisher, Logger, UnitOfWork
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
type CommandHandler = Callable[[Any], Awaitable[Any]]
|
||||
type EventHandler[EventT: DomainEvent] = Callable[[EventT], Awaitable[None]]
|
||||
|
||||
|
||||
class CommandBus:
|
||||
__slots__ = ("_handlers", "_publisher", "_uow")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
handlers: Mapping[type[Command], CommandHandler],
|
||||
uow: UnitOfWork,
|
||||
publisher: EventPublisher,
|
||||
) -> None:
|
||||
self._handlers = handlers
|
||||
self._uow = uow
|
||||
self._publisher = publisher
|
||||
|
||||
async def execute(self, command: Command) -> Any:
|
||||
handler = self._handlers.get(type(command))
|
||||
if handler is None:
|
||||
raise LookupError(f"нет обработчика для команды {type(command).__name__}")
|
||||
try:
|
||||
return await handler(command)
|
||||
finally:
|
||||
events = self._uow.collect_new_events()
|
||||
if events:
|
||||
await self._publisher.publish(events)
|
||||
|
||||
|
||||
class EventBus:
|
||||
__slots__ = ("_deferred", "_dropped", "_logger", "_projections", "_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:
|
||||
self._queue.put_nowait(event)
|
||||
except asyncio.QueueFull:
|
||||
self._dropped += 1
|
||||
self._logger.warning(
|
||||
"event.dropped", event_name=event.name, dropped_total=self._dropped
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
@property
|
||||
def dropped(self) -> int:
|
||||
return self._dropped
|
||||
|
||||
@property
|
||||
def pending(self) -> int:
|
||||
return self._queue.qsize()
|
||||
|
||||
def start(self) -> None:
|
||||
if self._worker is None:
|
||||
self._worker = asyncio.create_task(self._drain())
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._worker is None:
|
||||
return
|
||||
await self._queue.join()
|
||||
self._worker.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await self._worker
|
||||
self._worker = None
|
||||
|
||||
async def _drain(self) -> None:
|
||||
while True:
|
||||
event = await self._queue.get()
|
||||
try:
|
||||
await self._run(self._deferred.get(type(event), []), event, "subscriber")
|
||||
finally:
|
||||
self._queue.task_done()
|
||||
|
||||
async def _run(self, handlers: Sequence[Any], event: DomainEvent, kind: str) -> None:
|
||||
for handler in handlers:
|
||||
try:
|
||||
await handler(event)
|
||||
except Exception as error:
|
||||
self._logger.error(
|
||||
"event.handler_failed",
|
||||
event_name=event.name,
|
||||
reason=kind,
|
||||
error=type(error).__name__,
|
||||
)
|
||||
|
||||
|
||||
class InMemoryEventPublisher:
|
||||
__slots__ = ("_bus",)
|
||||
|
||||
def __init__(self, bus: EventBus) -> None:
|
||||
self._bus = bus
|
||||
|
||||
async def publish(self, events: Sequence[DomainEvent]) -> None:
|
||||
for event in events:
|
||||
await self._bus.emit(event)
|
||||
@@ -0,0 +1,42 @@
|
||||
from collections.abc import Sequence
|
||||
from contextlib import AbstractAsyncContextManager
|
||||
from datetime import datetime
|
||||
from typing import Any, Protocol, runtime_checkable
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class Clock(Protocol):
|
||||
def now(self) -> datetime: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class IdGenerator(Protocol):
|
||||
def new_id(self) -> UUID: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class Logger(Protocol):
|
||||
def info(self, event: str, /, **fields: Any) -> None: ...
|
||||
|
||||
def warning(self, event: str, /, **fields: Any) -> None: ...
|
||||
|
||||
def error(self, event: str, /, **fields: Any) -> None: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class UnitOfWork(Protocol):
|
||||
def transaction(self) -> AbstractAsyncContextManager[None]: ...
|
||||
|
||||
async def commit(self) -> None: ...
|
||||
|
||||
def record(self, event: DomainEvent) -> None: ...
|
||||
|
||||
def collect_new_events(self) -> list[DomainEvent]: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class EventPublisher(Protocol):
|
||||
async def publish(self, events: Sequence[DomainEvent]) -> None: ...
|
||||
@@ -0,0 +1,49 @@
|
||||
import os
|
||||
import socket
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pydantic import Field, SecretStr
|
||||
from pydantic.fields import FieldInfo
|
||||
from pydantic_settings import BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict
|
||||
|
||||
CONFIG = SettingsConfigDict(extra="ignore", frozen=True)
|
||||
|
||||
|
||||
class FileVariables(PydanticBaseSettingsSource):
|
||||
def get_field_value(self, field: FieldInfo, field_name: str) -> tuple[Any, str, bool]:
|
||||
path = os.environ.get(f"{field_name.upper()}_FILE")
|
||||
return (Path(path).read_text().strip() if path else None), field_name, False
|
||||
|
||||
def __call__(self) -> dict[str, Any]:
|
||||
found = {
|
||||
name: self.get_field_value(field, name)[0]
|
||||
for name, field in self.settings_cls.model_fields.items()
|
||||
}
|
||||
return {name: value for name, value in found.items() if value is not None}
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = CONFIG
|
||||
|
||||
@classmethod
|
||||
def settings_customise_sources(
|
||||
cls,
|
||||
settings_cls: type[BaseSettings],
|
||||
init_settings: PydanticBaseSettingsSource,
|
||||
env_settings: PydanticBaseSettingsSource,
|
||||
dotenv_settings: PydanticBaseSettingsSource,
|
||||
file_secret_settings: PydanticBaseSettingsSource,
|
||||
) -> tuple[PydanticBaseSettingsSource, ...]:
|
||||
return init_settings, env_settings, FileVariables(settings_cls)
|
||||
|
||||
|
||||
class PlatformSettings(Settings):
|
||||
log_level: str = "INFO"
|
||||
instance_id: str = Field(default_factory=socket.gethostname, min_length=1)
|
||||
event_queue_max: int = Field(default=10_000, ge=16)
|
||||
database_url: SecretStr
|
||||
db_pool_max_size: int = Field(default=8, ge=1, le=50)
|
||||
db_connect_timeout_seconds: float = Field(default=1.0, gt=0, le=30)
|
||||
db_acquire_timeout_seconds: float = Field(default=1.0, gt=0, le=30)
|
||||
db_command_timeout_seconds: float = Field(default=2.0, gt=0, le=60)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user