Files
mtusi2026lab4/src/messenger/attachments/domain/models.py
T
ArtyomandClaude Opus 5.5 76c9673ab3 Add the attachments zone with its domain and use cases
The zone owns the Attachment aggregate, which is staged as pending with
a server-assigned object key and becomes ready only when stored, the
Filename value that refuses empty, blank, overlong names and names with
a path separator or a control character, and the declared image type.

UploadAttachment checks membership first through the ChatMembership
port, then the name and the declared type, reads the body stream only
up to the limit while hashing it, inspects the image through a port,
commits the pending row, writes the object through the ObjectStorage
port and commits the ready row. GetAttachment and OpenAttachment answer
404 to strangers and to a ready row whose object is gone.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 20:43:41 +03:00

79 lines
2.0 KiB
Python

from dataclasses import dataclass, field
from datetime import datetime
from enum import StrEnum
from uuid import UUID
from messenger.attachments.domain.events import AttachmentStored
from messenger.attachments.domain.values import Filename, ImageInfo
from messenger.shared.domain.events import DomainEvent
OBJECT_PREFIX = "attachments/"
class AttachmentStatus(StrEnum):
PENDING = "pending"
READY = "ready"
@dataclass(slots=True)
class Attachment:
id: UUID
chat_id: UUID
owner_id: UUID
filename: Filename
image: ImageInfo
size_bytes: int
sha256: str
object_key: str
status: AttachmentStatus
created_at: datetime
updated_at: datetime
_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,
object_key=f"{OBJECT_PREFIX}{attachment_id}",
status=AttachmentStatus.PENDING,
created_at=now,
updated_at=now,
)
@property
def content_type(self) -> str:
return self.image.kind.value
def store(self, now: datetime) -> None:
self.status = AttachmentStatus.READY
self.updated_at = max(now, self.created_at)
self._events.append(
AttachmentStored(
attachment_id=self.id,
chat_id=self.chat_id,
owner_id=self.owner_id,
size_bytes=self.size_bytes,
)
)
def collect_events(self) -> list[DomainEvent]:
events, self._events = self._events, []
return events