This commit is contained in:
Vladislav Kunetskiy
2026-10-29 23:36:12 +03:00
parent 276dbdad8a
commit 6344754111
383 changed files with 68663 additions and 194 deletions
+90
View File
@@ -0,0 +1,90 @@
package domain
import (
"time"
"github.com/google/uuid"
)
// AttachmentStatus is the lifecycle of an attachment. Only ready attachments
// are exposed to members; pending rows exist while the object is being written,
// failed rows are reserved for later labs.
type AttachmentStatus string
const (
AttachmentPending AttachmentStatus = "pending"
AttachmentReady AttachmentStatus = "ready"
AttachmentFailed AttachmentStatus = "failed"
)
func (s AttachmentStatus) Valid() bool {
switch s {
case AttachmentPending, AttachmentReady, AttachmentFailed:
return true
default:
return false
}
}
// Attachment describes the original object. ObjectKey is internal: it never
// leaves the service and must not be mapped into an API response.
type Attachment struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
Filename string
ContentType string
SizeBytes int64
SHA256 string
Status AttachmentStatus
ErrorCode *string
ObjectKey string
CreatedAt time.Time
UpdatedAt time.Time
}
// AttachmentDraft is a fully validated attachment awaiting persistence.
type AttachmentDraft struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
ObjectKey string
Filename string
ContentType string
SizeBytes int64
SHA256 string
}
// AttachmentState is the minimal projection used while validating message
// attachments in a transaction.
type AttachmentState struct {
ID uuid.UUID
Status AttachmentStatus
}
// AttachmentKey is the minimal projection used by the orphan sweeper.
type AttachmentKey struct {
ID uuid.UUID
ObjectKey string
Status AttachmentStatus
CreatedAt time.Time
}
// PresignRequest is the validated client intent for a direct upload.
type PresignRequest struct {
ChatID uuid.UUID
OwnerID uuid.UUID
Filename string
ContentType string
SizeBytes int64
SHA256 string
}
// PresignResult is returned by the server and never contains credentials.
type PresignResult struct {
AttachmentID uuid.UUID
UploadURL string
ExpiresAt time.Time
SizeBytes int64
SHA256 string
}
+51
View File
@@ -0,0 +1,51 @@
package domain
import (
"fmt"
"slices"
"time"
"github.com/google/uuid"
)
type Chat struct {
ID uuid.UUID
Title string
MemberIDs []uuid.UUID
CreatedAt time.Time
}
func (c Chat) HasMember(userID uuid.UUID) bool {
return slices.Contains(c.MemberIDs, userID)
}
type ChatDraft struct {
Title string
MemberIDs []uuid.UUID
CallerID uuid.UUID
}
func (d ChatDraft) Validate() error {
if err := validateNotBlank("title", d.Title); err != nil {
return err
}
if len(d.MemberIDs) == 0 {
return fmt.Errorf("member_ids must not be empty: %w", ErrValidation)
}
seen := make(map[uuid.UUID]struct{}, len(d.MemberIDs))
for _, id := range d.MemberIDs {
if _, ok := seen[id]; ok {
return fmt.Errorf("member_ids contains duplicates: %w", ErrValidation)
}
seen[id] = struct{}{}
}
if _, ok := seen[d.CallerID]; !ok {
return fmt.Errorf("member_ids must contain the caller: %w", ErrValidation)
}
return nil
}
+17
View File
@@ -0,0 +1,17 @@
package domain
import (
"time"
"github.com/google/uuid"
)
type Cursor struct {
Scope uuid.UUID
CreatedAt time.Time
ID uuid.UUID
}
func (c Cursor) BelongsTo(scope uuid.UUID) bool {
return c.Scope == scope
}
+18
View File
@@ -0,0 +1,18 @@
package domain
import "errors"
var (
ErrNotFound = errors.New("not found")
ErrUsernameTaken = errors.New("username already taken")
ErrUnknownMember = errors.New("member does not exist")
ErrValidation = errors.New("validation failed")
ErrInvalidCursor = errors.New("invalid cursor")
ErrConflict = errors.New("conflict")
ErrIdempotency = errors.New("idempotency key already used with another payload")
ErrUnauthenticated = errors.New("unauthenticated")
ErrUnavailable = errors.New("temporarily unavailable")
ErrTooLarge = errors.New("payload is too large")
ErrUnsupportedMedia = errors.New("unsupported media type")
ErrIncomplete = errors.New("object is not fully uploaded")
)
+70
View File
@@ -0,0 +1,70 @@
package domain
import (
"crypto/sha256"
"fmt"
"strings"
"time"
"github.com/google/uuid"
)
// MaxMessageAttachments is the contract limit for attachment_ids on a message.
const MaxMessageAttachments = 10
type Message struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
AttachmentIDs []uuid.UUID
CreatedAt time.Time
}
// MessageIdempotency is the client Idempotency-Key together with the fingerprint
// of the payload it was first used with. The same key and fingerprint replay the
// stored message; the same key with another payload is a conflict.
type MessageIdempotency struct {
Key string
RequestHash [sha256.Size]byte
}
type MessageDraft struct {
ChatID uuid.UUID
SenderID uuid.UUID
Text string
AttachmentIDs []uuid.UUID
Idempotency MessageIdempotency
}
// Validate enforces the contract rule that a message carries either non-blank
// text or at least one attachment, never neither.
func (d MessageDraft) Validate() error {
if strings.TrimSpace(d.Text) == "" && len(d.AttachmentIDs) == 0 {
return fmt.Errorf("message has neither text nor attachments: %w", ErrValidation)
}
if len(d.AttachmentIDs) > MaxMessageAttachments {
return fmt.Errorf("too many attachments: %w", ErrValidation)
}
seen := make(map[uuid.UUID]struct{}, len(d.AttachmentIDs))
for _, id := range d.AttachmentIDs {
if id == uuid.Nil {
return fmt.Errorf("attachment id is empty: %w", ErrValidation)
}
if _, ok := seen[id]; ok {
return fmt.Errorf("duplicate attachment id %s: %w", id, ErrValidation)
}
seen[id] = struct{}{}
}
if d.Idempotency.Key == "" {
return fmt.Errorf("idempotency key is missing: %w", ErrValidation)
}
return nil
}
+8
View File
@@ -0,0 +1,8 @@
package domain
const DefaultPageLimit = 50
type Page[T any] struct {
Items []T
Next *Cursor
}
+19
View File
@@ -0,0 +1,19 @@
package domain
import (
"time"
"github.com/google/uuid"
)
type Session struct {
Token string
ExpiresAt time.Time
User User
}
type NewSession struct {
TokenHash []byte
UserID uuid.UUID
ExpiresAt time.Time
}
+14
View File
@@ -0,0 +1,14 @@
package domain
import (
"fmt"
"strings"
)
func validateNotBlank(field, value string) error {
if strings.TrimSpace(value) == "" {
return fmt.Errorf("%s consists of whitespace only: %w", field, ErrValidation)
}
return nil
}
+44
View File
@@ -0,0 +1,44 @@
package domain
import (
"fmt"
"time"
"github.com/google/uuid"
)
type User struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
}
type UserDraft struct {
Username string
DisplayName string
Password string
}
func (d UserDraft) Validate() error {
if err := validateNotBlank("display_name", d.DisplayName); err != nil {
return err
}
if length := len([]rune(d.Password)); length < 12 || length > 128 {
return fmt.Errorf("password length must be between 12 and 128 code points: %w", ErrValidation)
}
return nil
}
type NewUser struct {
Username string
DisplayName string
PasswordHash string
}
type UserCredentials struct {
User User
PasswordHash string
}
+121
View File
@@ -0,0 +1,121 @@
package domain_test
import (
"strings"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/domain"
)
// Длины, regex и uniqueItems проверяет сгенерированный слой по contracts/openapi.json.
// Домен закрывает только то, что схема выразить не может.
func TestUserDraftRejectsBlankDisplayName(t *testing.T) {
t.Parallel()
for _, blank := range []string{" ", " ", "\t", "\n", "\u00a0"} {
draft := domain.UserDraft{Username: "alice", DisplayName: blank}
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
}
}
func TestUserDraftAcceptsVisibleName(t *testing.T) {
t.Parallel()
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "very-secret-password"}
assert.NoError(t, draft.Validate())
}
func TestUserDraftRejectsShortPassword(t *testing.T) {
t.Parallel()
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "too-short"}
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
}
func TestUserDraftRejectsTooLongPassword(t *testing.T) {
t.Parallel()
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: strings.Repeat("a", 129)}
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
}
func TestUserDraftAcceptsMinimalPassword(t *testing.T) {
t.Parallel()
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: strings.Repeat("a", 12)}
assert.NoError(t, draft.Validate())
}
func TestChatDraftRequiresCallerAmongMembers(t *testing.T) {
t.Parallel()
caller := uuid.New()
outside := domain.ChatDraft{
Title: "Проект",
MemberIDs: []uuid.UUID{uuid.New(), uuid.New()},
CallerID: caller,
}
require.ErrorIs(t, outside.Validate(), domain.ErrValidation)
inside := domain.ChatDraft{
Title: "Проект",
MemberIDs: []uuid.UUID{uuid.New(), caller},
CallerID: caller,
}
assert.NoError(t, inside.Validate())
}
func TestChatDraftRejectsBlankTitle(t *testing.T) {
t.Parallel()
caller := uuid.New()
draft := domain.ChatDraft{
Title: " ",
MemberIDs: []uuid.UUID{caller},
CallerID: caller,
}
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
}
func TestMessageDraftRejectsBlankText(t *testing.T) {
t.Parallel()
draft := domain.MessageDraft{
ChatID: uuid.New(),
SenderID: uuid.New(),
Text: strings.Repeat(" ", 10),
Idempotency: domain.MessageIdempotency{Key: "key-1"},
}
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
}
func TestMessageDraftRejectsMissingIdempotencyKey(t *testing.T) {
t.Parallel()
draft := domain.MessageDraft{
ChatID: uuid.New(),
SenderID: uuid.New(),
Text: "привет",
}
require.ErrorIs(t, draft.Validate(), domain.ErrValidation,
"с lab3 отправка сообщения невозможна без Idempotency-Key")
}
func TestMessageDraftAcceptsTextWithSurroundingSpaces(t *testing.T) {
t.Parallel()
draft := domain.MessageDraft{
ChatID: uuid.New(),
SenderID: uuid.New(),
Text: " привет ",
Idempotency: domain.MessageIdempotency{Key: "key-1"},
}
assert.NoError(t, draft.Validate(), "контракт запрещает только полностью пробельный текст")
}