лаба 4 на оценку 5

This commit is contained in:
2026-10-30 12:27:49 +03:00
parent 7860d81fa1
commit f9444a3965
59 changed files with 4696 additions and 90 deletions
+33
View File
@@ -0,0 +1,33 @@
package health
import (
"context"
"fmt"
)
type Checker interface {
Ping(ctx context.Context) error
}
type MultiChecker struct {
checkers []Checker
}
func NewMultiChecker(checkers ...Checker) *MultiChecker {
filtered := make([]Checker, 0, len(checkers))
for _, checker := range checkers {
if checker != nil {
filtered = append(filtered, checker)
}
}
return &MultiChecker{checkers: filtered}
}
func (checker *MultiChecker) Ping(ctx context.Context) error {
for index, dependency := range checker.checkers {
if err := dependency.Ping(ctx); err != nil {
return fmt.Errorf("dependency %d: %w", index, err)
}
}
return nil
}
+83 -1
View File
@@ -166,6 +166,15 @@ func (r *MemoryRepository) CreateMessageIdempotently(
if _, err := r.legacy.GetChatByID(write.ChatID, write.ActorID); err != nil {
return domain.Message{}, err
}
for _, attachmentID := range write.AttachmentIDs {
attachment, err := r.legacy.GetAttachmentByID(attachmentID)
if err != nil || attachment.ChatID != write.ChatID {
return domain.Message{}, ErrNotFound
}
if attachment.Status != domain.AttachmentStatusReady {
return domain.Message{}, application.ErrAttachmentNotReady
}
}
if stored, exists := r.idempotencyByScope[scope]; exists {
if stored.expiresAt.After(now) {
@@ -177,7 +186,12 @@ func (r *MemoryRepository) CreateMessageIdempotently(
delete(r.idempotencyByScope, scope)
}
message, err := r.legacy.CreateMessage(write.ChatID, write.ActorID, write.Text)
message, err := r.legacy.CreateMessage(
write.ChatID,
write.ActorID,
write.Text,
write.AttachmentIDs,
)
if err != nil {
return domain.Message{}, err
}
@@ -277,6 +291,74 @@ func (r *MemoryRepository) DeleteSession(
return nil
}
func (r *MemoryRepository) CreateAttachment(
ctx context.Context,
attachment domain.Attachment,
) (domain.Attachment, error) {
if err := ctx.Err(); err != nil {
return domain.Attachment{}, err
}
if err := r.legacy.PutAttachment(attachment); err != nil {
return domain.Attachment{}, err
}
return attachment, nil
}
func (r *MemoryRepository) MarkAttachmentReady(
ctx context.Context,
attachmentID string,
updatedAt time.Time,
) (domain.Attachment, error) {
if err := ctx.Err(); err != nil {
return domain.Attachment{}, err
}
return r.legacy.UpdateAttachmentStatus(
attachmentID,
domain.AttachmentStatusReady,
nil,
updatedAt,
)
}
func (r *MemoryRepository) MarkAttachmentFailed(
ctx context.Context,
attachmentID string,
errorCode string,
updatedAt time.Time,
) error {
if err := ctx.Err(); err != nil {
return err
}
_, err := r.legacy.UpdateAttachmentStatus(
attachmentID,
domain.AttachmentStatusFailed,
&errorCode,
updatedAt,
)
return err
}
func (r *MemoryRepository) GetAttachment(
ctx context.Context,
attachmentID string,
callerID string,
) (domain.Attachment, error) {
if err := ctx.Err(); err != nil {
return domain.Attachment{}, err
}
attachment, err := r.legacy.GetAttachmentByID(attachmentID)
if err != nil {
return domain.Attachment{}, err
}
if _, err = r.legacy.GetChatByID(attachment.ChatID, callerID); err != nil {
return domain.Attachment{}, err
}
if attachment.Variants == nil {
attachment.Variants = make([]domain.AttachmentVariant, 0)
}
return attachment, nil
}
func memoryTokenHashKey(tokenHash []byte) ([32]byte, error) {
var key [32]byte
+90 -6
View File
@@ -20,6 +20,8 @@ type MemoryStore struct {
chatsByID map[string]domain.Chat //key = chat UUID
messagesByChatID map[string][]domain.Message // key = chat UUID, value = слайс сообщений
attachmentsByID map[string]domain.Attachment
}
func NewMemoryStore() *MemoryStore {
@@ -28,6 +30,7 @@ func NewMemoryStore() *MemoryStore {
usersByUsername: make(map[string]string),
chatsByID: make(map[string]domain.Chat),
messagesByChatID: make(map[string][]domain.Message),
attachmentsByID: make(map[string]domain.Attachment),
}
}
@@ -177,12 +180,86 @@ func (s *MemoryStore) GetChatsForUser(
return items, end < len(chats), nil
}
// PutAttachment stores metadata for adapter and application tests. Binary
// content intentionally does not belong to this in-memory metadata store.
func (s *MemoryStore) PutAttachment(attachment domain.Attachment) error {
s.mu.Lock()
defer s.mu.Unlock()
if _, exists := s.attachmentsByID[attachment.ID]; exists {
return ErrConflict
}
chat, exists := s.chatsByID[attachment.ChatID]
if !exists {
return ErrNotFound
}
ownerIsMember := false
for _, memberID := range chat.MemberIDs {
if memberID == attachment.OwnerID {
ownerIsMember = true
break
}
}
if !ownerIsMember {
return ErrNotFound
}
s.attachmentsByID[attachment.ID] = attachment
return nil
}
func (s *MemoryStore) GetAttachmentByID(
attachmentID string,
) (domain.Attachment, error) {
s.mu.RLock()
defer s.mu.RUnlock()
attachment, exists := s.attachmentsByID[attachmentID]
if !exists {
return domain.Attachment{}, ErrNotFound
}
return attachment, nil
}
func (s *MemoryStore) UpdateAttachmentStatus(
attachmentID string,
status domain.AttachmentStatus,
errorCode *string,
updatedAt time.Time,
) (domain.Attachment, error) {
s.mu.Lock()
defer s.mu.Unlock()
attachment, exists := s.attachmentsByID[attachmentID]
if !exists {
return domain.Attachment{}, ErrNotFound
}
if attachment.Status != domain.AttachmentStatusPending {
return domain.Attachment{}, ErrConflict
}
attachment.Status = status
attachment.ErrorCode = errorCode
attachment.UpdatedAt = updatedAt
if attachment.Variants == nil {
attachment.Variants = make([]domain.AttachmentVariant, 0)
}
s.attachmentsByID[attachmentID] = attachment
return attachment, nil
}
// ---Сообщения---
func (s *MemoryStore) CreateMessage(
chatID, senderID, text string,
attachmentLists ...[]string,
) (domain.Message, error) {
messageID := uuid.NewString()
attachmentIDs := make([]string, 0)
if len(attachmentLists) > 0 {
attachmentIDs = append(attachmentIDs, attachmentLists[0]...)
}
s.mu.Lock()
defer s.mu.Unlock()
@@ -216,11 +293,12 @@ func (s *MemoryStore) CreateMessage(
}
message := domain.Message{
ID: messageID,
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: createdAt,
ID: messageID,
ChatID: chatID,
SenderID: senderID,
Text: text,
AttachmentIDs: attachmentIDs,
CreatedAt: createdAt,
}
s.messagesByChatID[chatID] = append(messages, message)
@@ -282,6 +360,12 @@ func (s *MemoryStore) GetMessages(
// копируем только возвращаемую страницу, а не всю историю, изменяя внутренний срез
items := make([]domain.Message, end-start)
copy(items, messages[start:end])
for index, message := range messages[start:end] {
message.AttachmentIDs = append(
make([]string, 0, len(message.AttachmentIDs)),
message.AttachmentIDs...,
)
items[index] = message
}
return items, end < len(messages), nil
}
+201
View File
@@ -0,0 +1,201 @@
package objectstore
import (
"bytes"
"context"
"fmt"
"io"
"net/url"
"strings"
"time"
"mtusi2026lab4/internal/application"
minio "github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
type MinIOStore struct {
client *minio.Client
bucket string
operationTimeout time.Duration
}
type StoredObject struct {
Key string
SizeBytes int64
LastModified time.Time
}
func NewMinIOStore(
endpoint string,
region string,
bucket string,
accessKeyID string,
secretAccessKey string,
operationTimeout time.Duration,
) (*MinIOStore, error) {
parsedEndpoint, err := url.Parse(endpoint)
if err != nil || parsedEndpoint.Host == "" {
return nil, fmt.Errorf("S3 endpoint must be an absolute HTTP(S) URL")
}
if parsedEndpoint.Scheme != "http" && parsedEndpoint.Scheme != "https" {
return nil, fmt.Errorf("S3 endpoint scheme must be http or https")
}
if parsedEndpoint.Path != "" && parsedEndpoint.Path != "/" {
return nil, fmt.Errorf("S3 endpoint must not contain a path")
}
if parsedEndpoint.RawQuery != "" || parsedEndpoint.Fragment != "" || parsedEndpoint.User != nil {
return nil, fmt.Errorf("S3 endpoint must not contain credentials, query or fragment")
}
if strings.TrimSpace(bucket) == "" || strings.TrimSpace(accessKeyID) == "" ||
strings.TrimSpace(secretAccessKey) == "" {
return nil, fmt.Errorf("S3 bucket and credentials are required")
}
if operationTimeout <= 0 {
return nil, fmt.Errorf("S3 operation timeout must be positive")
}
client, err := minio.New(parsedEndpoint.Host, &minio.Options{
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
Secure: parsedEndpoint.Scheme == "https",
Region: region,
})
if err != nil {
return nil, fmt.Errorf("create MinIO client: %w", err)
}
return &MinIOStore{client: client, bucket: bucket, operationTimeout: operationTimeout}, nil
}
func (store *MinIOStore) Put(ctx context.Context, object application.ObjectPut) error {
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
defer cancel()
upload, err := store.client.PutObject(
operationContext,
store.bucket,
object.Key,
object.Body,
object.SizeBytes,
minio.PutObjectOptions{ContentType: object.ContentType},
)
if err != nil {
return fmt.Errorf("put MinIO object: %w", err)
}
if upload.Size != object.SizeBytes {
return fmt.Errorf("put MinIO object: stored %d bytes, want %d", upload.Size, object.SizeBytes)
}
return nil
}
func (store *MinIOStore) Get(
ctx context.Context,
key string,
) (application.ObjectContent, error) {
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
stat, err := store.client.StatObject(
operationContext,
store.bucket,
key,
minio.StatObjectOptions{},
)
if err != nil {
cancel()
return application.ObjectContent{}, fmt.Errorf("stat MinIO object: %w", err)
}
object, err := store.client.GetObject(
operationContext,
store.bucket,
key,
minio.GetObjectOptions{},
)
if err != nil {
cancel()
return application.ObjectContent{}, fmt.Errorf("get MinIO object: %w", err)
}
firstByte := make([]byte, 1)
readCount, readError := object.Read(firstByte)
if readError != nil && readCount == 0 {
_ = object.Close()
cancel()
return application.ObjectContent{}, fmt.Errorf("read MinIO object: %w", readError)
}
if readCount != 1 {
_ = object.Close()
cancel()
return application.ObjectContent{}, fmt.Errorf("read MinIO object: expected non-empty object")
}
return application.ObjectContent{
Body: &cancelingReadCloser{
Reader: io.MultiReader(bytes.NewReader(firstByte), object),
Closer: object,
cancel: cancel,
},
SizeBytes: stat.Size,
}, nil
}
func (store *MinIOStore) List(
ctx context.Context,
prefix string,
) ([]StoredObject, error) {
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
defer cancel()
objects := make([]StoredObject, 0)
for object := range store.client.ListObjects(
operationContext,
store.bucket,
minio.ListObjectsOptions{Prefix: prefix, Recursive: true},
) {
if object.Err != nil {
return nil, fmt.Errorf("list MinIO objects: %w", object.Err)
}
objects = append(objects, StoredObject{
Key: object.Key,
SizeBytes: object.Size,
LastModified: object.LastModified.UTC(),
})
}
return objects, nil
}
func (store *MinIOStore) Delete(ctx context.Context, key string) error {
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
defer cancel()
if err := store.client.RemoveObject(
operationContext,
store.bucket,
key,
minio.RemoveObjectOptions{},
); err != nil {
return fmt.Errorf("delete MinIO object: %w", err)
}
return nil
}
func (store *MinIOStore) Ping(ctx context.Context) error {
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
defer cancel()
exists, err := store.client.BucketExists(operationContext, store.bucket)
if err != nil {
return fmt.Errorf("check MinIO bucket: %w", err)
}
if !exists {
return fmt.Errorf("MinIO bucket %q does not exist", store.bucket)
}
return nil
}
type cancelingReadCloser struct {
io.Reader
io.Closer
cancel context.CancelFunc
}
func (reader *cancelingReadCloser) Close() error {
err := reader.Closer.Close()
reader.cancel()
return err
}
var _ application.ObjectStore = (*MinIOStore)(nil)
@@ -0,0 +1,37 @@
package objectstore
import (
"testing"
"time"
)
func TestNewMinIOStoreValidatesConfiguration(t *testing.T) {
testCases := []struct {
name string
endpoint string
bucket string
accessKey string
secretKey string
timeout time.Duration
wantError bool
}{
{name: "valid HTTP", endpoint: "http://minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second},
{name: "valid HTTPS", endpoint: "https://s3.example.test", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second},
{name: "relative endpoint", endpoint: "minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true},
{name: "endpoint path", endpoint: "http://minio:9000/path", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true},
{name: "embedded credentials", endpoint: "http://user:pass@minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true},
{name: "empty bucket", endpoint: "http://minio:9000", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true},
{name: "empty credentials", endpoint: "http://minio:9000", bucket: "attachments", timeout: time.Second, wantError: true},
{name: "invalid timeout", endpoint: "http://minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", wantError: true},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
_, err := NewMinIOStore(testCase.endpoint, "us-east-1", testCase.bucket,
testCase.accessKey, testCase.secretKey, testCase.timeout)
if (err != nil) != testCase.wantError {
t.Fatalf("NewMinIOStore() error = %v, wantError %v", err, testCase.wantError)
}
})
}
}
+306
View File
@@ -0,0 +1,306 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"mtusi2026lab4/internal/domain"
"mtusi2026lab4/internal/reconcile"
"github.com/jackc/pgx/v5"
)
func (s *PostgreSQLStore) CreateAttachment(
ctx context.Context,
attachment domain.Attachment,
) (domain.Attachment, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
err := s.pool.QueryRow(
queryContext,
`
INSERT INTO attachments (
id, chat_id, owner_id, object_key, filename, content_type,
size_bytes, sha256, width, height, status, error_code,
created_at, updated_at
)
VALUES (
$1, $2, $3, $4, $5, $6,
$7, decode($8, 'hex'), $9, $10, $11, $12,
$13, $14
)
RETURNING created_at, updated_at
`,
attachment.ID,
attachment.ChatID,
attachment.OwnerID,
attachment.ObjectKey,
attachment.Filename,
attachment.ContentType,
attachment.SizeBytes,
attachment.SHA256,
attachment.Width,
attachment.Height,
attachment.Status,
attachment.ErrorCode,
attachment.CreatedAt,
attachment.UpdatedAt,
).Scan(&attachment.CreatedAt, &attachment.UpdatedAt)
if err != nil {
return domain.Attachment{}, fmt.Errorf("insert attachment metadata: %w", err)
}
if attachment.Variants == nil {
attachment.Variants = make([]domain.AttachmentVariant, 0)
}
return attachment, nil
}
func (s *PostgreSQLStore) MarkAttachmentReady(
ctx context.Context,
attachmentID string,
updatedAt time.Time,
) (domain.Attachment, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var attachment domain.Attachment
var sha256Bytes []byte
err := s.pool.QueryRow(
queryContext,
`
UPDATE attachments
SET status = 'ready', error_code = NULL, updated_at = $2
WHERE id = $1 AND status = 'pending'
RETURNING
id::text, chat_id::text, owner_id::text, object_key,
filename, content_type, size_bytes, sha256, width, height,
status, error_code, created_at, updated_at
`,
attachmentID,
updatedAt,
).Scan(
&attachment.ID,
&attachment.ChatID,
&attachment.OwnerID,
&attachment.ObjectKey,
&attachment.Filename,
&attachment.ContentType,
&attachment.SizeBytes,
&sha256Bytes,
&attachment.Width,
&attachment.Height,
&attachment.Status,
&attachment.ErrorCode,
&attachment.CreatedAt,
&attachment.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.Attachment{}, ErrConflict
}
if err != nil {
return domain.Attachment{}, fmt.Errorf("mark attachment ready: %w", err)
}
attachment.SHA256 = fmt.Sprintf("%x", sha256Bytes)
attachment.Variants = make([]domain.AttachmentVariant, 0)
return attachment, nil
}
func (s *PostgreSQLStore) MarkAttachmentFailed(
ctx context.Context,
attachmentID string,
errorCode string,
updatedAt time.Time,
) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
commandTag, err := s.pool.Exec(
queryContext,
`
UPDATE attachments
SET status = 'failed', error_code = $2, updated_at = $3
WHERE id = $1 AND status = 'pending'
`,
attachmentID,
errorCode,
updatedAt,
)
if err != nil {
return fmt.Errorf("mark attachment failed: %w", err)
}
if commandTag.RowsAffected() != 1 {
return ErrConflict
}
return nil
}
func (s *PostgreSQLStore) GetAttachment(
ctx context.Context,
attachmentID string,
callerID string,
) (domain.Attachment, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var attachment domain.Attachment
var sha256Bytes []byte
err := s.pool.QueryRow(
queryContext,
`
SELECT
a.id::text, a.chat_id::text, a.owner_id::text, a.object_key,
a.filename, a.content_type, a.size_bytes, a.sha256,
a.width, a.height, a.status, a.error_code,
a.created_at, a.updated_at
FROM attachments AS a
JOIN chat_members AS cm
ON cm.chat_id = a.chat_id AND cm.user_id = $2
WHERE a.id = $1
`,
attachmentID,
callerID,
).Scan(
&attachment.ID,
&attachment.ChatID,
&attachment.OwnerID,
&attachment.ObjectKey,
&attachment.Filename,
&attachment.ContentType,
&attachment.SizeBytes,
&sha256Bytes,
&attachment.Width,
&attachment.Height,
&attachment.Status,
&attachment.ErrorCode,
&attachment.CreatedAt,
&attachment.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.Attachment{}, ErrNotFound
}
if err != nil {
return domain.Attachment{}, fmt.Errorf("get attachment metadata: %w", err)
}
attachment.SHA256 = fmt.Sprintf("%x", sha256Bytes)
attachment.Variants = make([]domain.AttachmentVariant, 0)
return attachment, nil
}
func (s *PostgreSQLStore) ListAttachmentInventory(
ctx context.Context,
) ([]reconcile.AttachmentRecord, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
rows, err := s.pool.Query(
queryContext,
`
SELECT
a.id::text,
a.object_key,
a.status,
a.updated_at,
EXISTS (
SELECT 1
FROM message_attachments AS ma
WHERE ma.attachment_id = a.id
) AS referenced
FROM attachments AS a
ORDER BY a.id
`,
)
if err != nil {
return nil, fmt.Errorf("query attachment inventory: %w", err)
}
defer rows.Close()
records := make([]reconcile.AttachmentRecord, 0)
for rows.Next() {
var record reconcile.AttachmentRecord
if err = rows.Scan(
&record.ID,
&record.ObjectKey,
&record.Status,
&record.UpdatedAt,
&record.Referenced,
); err != nil {
return nil, fmt.Errorf("scan attachment inventory: %w", err)
}
records = append(records, record)
}
if err = rows.Err(); err != nil {
return nil, fmt.Errorf("iterate attachment inventory: %w", err)
}
return records, nil
}
func (s *PostgreSQLStore) MarkAttachmentFailedIfUnreferenced(
ctx context.Context,
attachmentID string,
expectedStatus domain.AttachmentStatus,
updatedBefore time.Time,
errorCode string,
updatedAt time.Time,
) (bool, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
transaction, err := s.pool.BeginTx(queryContext, pgx.TxOptions{})
if err != nil {
return false, fmt.Errorf("begin attachment reconciliation transaction: %w", err)
}
defer func() { _ = transaction.Rollback(queryContext) }()
var lockedAttachmentID string
err = transaction.QueryRow(
queryContext,
`
SELECT id::text
FROM attachments
WHERE id = $1
FOR UPDATE
`,
attachmentID,
).Scan(&lockedAttachmentID)
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("lock attachment during reconciliation: %w", err)
}
// This is deliberately a second statement. Under READ COMMITTED it gets a
// fresh snapshot after the row lock was acquired, so a message transaction
// that linked this attachment while we waited is visible to NOT EXISTS.
commandTag, err := transaction.Exec(
queryContext,
`
UPDATE attachments AS a
SET status = 'failed', error_code = $4, updated_at = $5
WHERE a.id = $1
AND a.status = $2
AND a.updated_at <= $3
AND NOT EXISTS (
SELECT 1
FROM message_attachments AS ma
WHERE ma.attachment_id = a.id
)
`,
attachmentID,
expectedStatus,
updatedBefore,
errorCode,
updatedAt,
)
if err != nil {
return false, fmt.Errorf("mark attachment failed during reconciliation: %w", err)
}
if err = transaction.Commit(queryContext); err != nil {
return false, fmt.Errorf("commit attachment reconciliation: %w", err)
}
return commandTag.RowsAffected() == 1, nil
}
var _ reconcile.MetadataStore = (*PostgreSQLStore)(nil)
+109 -7
View File
@@ -48,6 +48,59 @@ func (s *PostgreSQLStore) CreateMessageIdempotently(
return domain.Message{}, ErrNotFound
}
attachmentUUIDs := make([]uuid.UUID, len(write.AttachmentIDs))
for index, attachmentID := range write.AttachmentIDs {
parsedID, parseErr := uuid.Parse(attachmentID)
if parseErr != nil {
return domain.Message{}, fmt.Errorf("parse validated attachment id: %w", parseErr)
}
attachmentUUIDs[index] = parsedID
}
if len(attachmentUUIDs) > 0 {
rows, queryError := transaction.Query(
queryContext,
`
SELECT id::text, status
FROM attachments
WHERE chat_id = $1
AND id = ANY($2::uuid[])
ORDER BY id
FOR UPDATE
`,
write.ChatID,
attachmentUUIDs,
)
if queryError != nil {
return domain.Message{}, fmt.Errorf("lock message attachments: %w", queryError)
}
availableCount := 0
readyCount := 0
for rows.Next() {
var attachmentID string
var status domain.AttachmentStatus
if queryError = rows.Scan(&attachmentID, &status); queryError != nil {
rows.Close()
return domain.Message{}, fmt.Errorf("scan locked message attachment: %w", queryError)
}
availableCount++
if status == domain.AttachmentStatusReady {
readyCount++
}
}
queryError = rows.Err()
rows.Close()
if queryError != nil {
return domain.Message{}, fmt.Errorf("iterate locked message attachments: %w", queryError)
}
if availableCount != len(attachmentUUIDs) {
return domain.Message{}, ErrNotFound
}
if readyCount != len(attachmentUUIDs) {
return domain.Message{}, application.ErrAttachmentNotReady
}
}
_, err = transaction.Exec(
queryContext,
`
@@ -68,10 +121,11 @@ func (s *PostgreSQLStore) CreateMessageIdempotently(
}
message := domain.Message{
ID: uuid.NewString(),
ChatID: write.ChatID,
SenderID: write.ActorID,
Text: write.Text,
ID: uuid.NewString(),
ChatID: write.ChatID,
SenderID: write.ActorID,
Text: write.Text,
AttachmentIDs: append([]string(nil), write.AttachmentIDs...),
}
var storedHash []byte
@@ -141,7 +195,15 @@ func (s *PostgreSQLStore) CreateMessageIdempotently(
chat_id::text,
sender_id::text,
text,
created_at
created_at,
COALESCE(
ARRAY(
SELECT attachment_id::text
FROM message_attachments
WHERE message_id = messages.id
ORDER BY position
), ARRAY[]::text[]
)
FROM messages
WHERE id = $1
`,
@@ -152,6 +214,7 @@ func (s *PostgreSQLStore) CreateMessageIdempotently(
&message.SenderID,
&message.Text,
&message.CreatedAt,
&message.AttachmentIDs,
)
if err != nil {
return domain.Message{}, fmt.Errorf("read idempotent message: %w", err)
@@ -187,6 +250,28 @@ func (s *PostgreSQLStore) CreateMessageIdempotently(
return domain.Message{}, fmt.Errorf("insert message: %w", err)
}
if len(attachmentUUIDs) > 0 {
_, err = transaction.Exec(
queryContext,
`
INSERT INTO message_attachments (
message_id,
chat_id,
attachment_id,
position
)
SELECT $1, $2, attachment_id, (ordinality - 1)::smallint
FROM unnest($3::uuid[]) WITH ORDINALITY AS input(attachment_id, ordinality)
`,
message.ID,
message.ChatID,
attachmentUUIDs,
)
if err != nil {
return domain.Message{}, fmt.Errorf("link message attachments: %w", err)
}
}
if err = transaction.Commit(queryContext); err != nil {
return domain.Message{}, fmt.Errorf("commit idempotent message: %w", err)
}
@@ -241,7 +326,15 @@ func (s *PostgreSQLStore) GetMessages(
chat_id::text,
sender_id::text,
text,
created_at
created_at,
COALESCE(
ARRAY(
SELECT attachment_id::text
FROM message_attachments
WHERE message_id = messages.id
ORDER BY position
), ARRAY[]::text[]
)
FROM messages
WHERE chat_id = $1
ORDER BY
@@ -261,7 +354,15 @@ func (s *PostgreSQLStore) GetMessages(
chat_id::text,
sender_id::text,
text,
created_at
created_at,
COALESCE(
ARRAY(
SELECT attachment_id::text
FROM message_attachments
WHERE message_id = messages.id
ORDER BY position
), ARRAY[]::text[]
)
FROM messages
WHERE chat_id = $1
AND (created_at, id) > ($2, $3)
@@ -296,6 +397,7 @@ func (s *PostgreSQLStore) GetMessages(
&message.SenderID,
&message.Text,
&message.CreatedAt,
&message.AttachmentIDs,
); err != nil {
return nil, false, fmt.Errorf(
"scan message page: %w",
@@ -0,0 +1,65 @@
package application
import (
"context"
"fmt"
"io"
"mtusi2026lab4/internal/domain"
)
type AttachmentDownload struct {
Body io.ReadCloser
ContentType string
Filename string
SizeBytes int64
}
func (s *Service) GetAttachment(
ctx context.Context,
attachmentID string,
actorID string,
) (domain.Attachment, error) {
return s.repository.GetAttachment(ctx, attachmentID, actorID)
}
func (s *Service) DownloadAttachment(
ctx context.Context,
attachmentID string,
actorID string,
variant string,
) (AttachmentDownload, error) {
attachment, err := s.repository.GetAttachment(ctx, attachmentID, actorID)
if err != nil {
return AttachmentDownload{}, err
}
if attachment.Status != domain.AttachmentStatusReady {
return AttachmentDownload{}, ErrAttachmentNotReady
}
if variant == "" {
variant = "original"
}
if variant != "original" {
return AttachmentDownload{}, domain.ErrNotFound
}
if s.objectStore == nil {
return AttachmentDownload{}, ErrStorageUnavailable
}
object, err := s.objectStore.Get(ctx, attachment.ObjectKey)
if err != nil {
return AttachmentDownload{}, fmt.Errorf("%w: get object", ErrStorageUnavailable)
}
if object.Body == nil || object.SizeBytes != attachment.SizeBytes {
if object.Body != nil {
_ = object.Body.Close()
}
return AttachmentDownload{}, fmt.Errorf("%w: object metadata mismatch", ErrStorageUnavailable)
}
return AttachmentDownload{
Body: object.Body,
ContentType: attachment.ContentType,
Filename: attachment.Filename,
SizeBytes: attachment.SizeBytes,
}, nil
}
+246
View File
@@ -0,0 +1,246 @@
package application
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"os"
"mtusi2026lab4/internal/domain"
"github.com/google/uuid"
)
const attachmentPutFailedCode = "object_store_put_failed"
const attachmentFinalizeFailedCode = "metadata_finalize_failed"
func (s *Service) UploadAttachment(
ctx context.Context,
command UploadAttachmentCommand,
) (domain.Attachment, error) {
if s.objectStore == nil {
return domain.Attachment{}, ErrStorageUnavailable
}
if command.Body == nil {
return domain.Attachment{}, fmt.Errorf("%w: attachment body is required", ErrInvalidInput)
}
if err := domain.ValidateAttachmentFilename(command.Filename); err != nil {
return domain.Attachment{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
if err := domain.ValidateAttachmentContentType(command.DeclaredContentType); err != nil {
return domain.Attachment{}, fmt.Errorf("%w: %v", ErrUnsupportedMediaType, err)
}
if _, err := s.repository.GetChatByID(ctx, command.ChatID, command.ActorID); err != nil {
return domain.Attachment{}, err
}
if err := acquireAttachmentSlot(ctx, s.attachmentUploadSlots); err != nil {
return domain.Attachment{}, fmt.Errorf("%w: wait for upload capacity", ErrStorageUnavailable)
}
defer releaseAttachmentSlot(s.attachmentUploadSlots)
stagedFile, err := os.CreateTemp("", "mtusi-attachment-*")
if err != nil {
return domain.Attachment{}, fmt.Errorf("create bounded upload staging file: %w", err)
}
stagedPath := stagedFile.Name()
defer func() {
_ = stagedFile.Close()
_ = os.Remove(stagedPath)
}()
hasher := sha256.New()
limitedBody := io.LimitReader(command.Body, domain.MaxAttachmentSizeBytes+1)
sizeBytes, err := io.Copy(io.MultiWriter(stagedFile, hasher), limitedBody)
if err != nil {
return domain.Attachment{}, fmt.Errorf("%w: read attachment body", ErrInvalidInput)
}
if sizeBytes > domain.MaxAttachmentSizeBytes {
return domain.Attachment{}, ErrPayloadTooLarge
}
if _, err = stagedFile.Seek(0, io.SeekStart); err != nil {
return domain.Attachment{}, fmt.Errorf("rewind staged attachment: %w", err)
}
imageConfig, format, err := image.DecodeConfig(stagedFile)
if err != nil {
return domain.Attachment{}, fmt.Errorf("%w: decode image header", ErrInvalidImage)
}
actualContentType, supported := contentTypeForImageFormat(format)
if !supported || actualContentType != command.DeclaredContentType {
return domain.Attachment{}, ErrUnsupportedMediaType
}
if imageConfig.Width < 1 || imageConfig.Height < 1 {
return domain.Attachment{}, ErrInvalidImage
}
if int64(imageConfig.Width) > int64(domain.MaxAttachmentPixels)/int64(imageConfig.Height) {
return domain.Attachment{}, ErrPayloadTooLarge
}
sha256Hex := hex.EncodeToString(hasher.Sum(nil))
if err = domain.ValidateReadyAttachmentMetadata(
command.Filename,
actualContentType,
sizeBytes,
sha256Hex,
imageConfig.Width,
imageConfig.Height,
); err != nil {
return domain.Attachment{}, fmt.Errorf("%w: %v", ErrInvalidImage, err)
}
if _, err = stagedFile.Seek(0, io.SeekStart); err != nil {
return domain.Attachment{}, fmt.Errorf("rewind staged attachment for validation: %w", err)
}
if err = s.validateCompleteImage(ctx, stagedFile); err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return domain.Attachment{}, fmt.Errorf("%w: wait for image decoder", ErrStorageUnavailable)
}
return domain.Attachment{}, fmt.Errorf("%w: decode complete image", ErrInvalidImage)
}
now := s.now().UTC()
attachmentID := uuid.NewString()
attachment := domain.Attachment{
ID: attachmentID,
ChatID: command.ChatID,
OwnerID: command.ActorID,
Filename: command.Filename,
ObjectKey: "attachments/" + command.ChatID + "/" + attachmentID + "/original",
ContentType: actualContentType,
SizeBytes: sizeBytes,
SHA256: sha256Hex,
Width: imageConfig.Width,
Height: imageConfig.Height,
Status: domain.AttachmentStatusPending,
Variants: make([]domain.AttachmentVariant, 0),
CreatedAt: now,
UpdatedAt: now,
}
attachment, err = s.repository.CreateAttachment(ctx, attachment)
if err != nil {
return domain.Attachment{}, err
}
if _, err = stagedFile.Seek(0, io.SeekStart); err != nil {
s.cleanupFailedAttachment(ctx, attachment, attachmentFinalizeFailedCode, false)
return domain.Attachment{}, fmt.Errorf("rewind staged attachment for storage: %w", err)
}
err = s.objectStore.Put(ctx, ObjectPut{
Key: attachment.ObjectKey,
ContentType: attachment.ContentType,
SizeBytes: attachment.SizeBytes,
Body: stagedFile,
})
if err != nil {
s.cleanupFailedAttachment(ctx, attachment, attachmentPutFailedCode, true)
return domain.Attachment{}, fmt.Errorf("%w: put object", ErrStorageUnavailable)
}
readyAttachment, err := s.repository.MarkAttachmentReady(ctx, attachment.ID, s.now().UTC())
if err != nil {
// The UPDATE may already have committed even when its response was lost.
// Deleting the object here could turn durable ready metadata into a
// permanently broken attachment. A best-effort read may recover a 201;
// otherwise both sides are preserved for the grace-period reconciler.
if resolved, ok := s.resolveAmbiguousAttachmentFinalize(ctx, attachment); ok {
return resolved, nil
}
return domain.Attachment{}, fmt.Errorf("finalize attachment metadata: %w", err)
}
if readyAttachment.Variants == nil {
readyAttachment.Variants = make([]domain.AttachmentVariant, 0)
}
return readyAttachment, nil
}
func acquireAttachmentSlot(ctx context.Context, slots chan struct{}) error {
select {
case slots <- struct{}{}:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func releaseAttachmentSlot(slots chan struct{}) {
<-slots
}
func (s *Service) validateCompleteImage(ctx context.Context, body io.Reader) error {
if err := acquireAttachmentSlot(ctx, s.attachmentDecodeSlots); err != nil {
return err
}
defer releaseAttachmentSlot(s.attachmentDecodeSlots)
_, _, err := image.Decode(body)
return err
}
func (s *Service) resolveAmbiguousAttachmentFinalize(
requestContext context.Context,
attachment domain.Attachment,
) (domain.Attachment, bool) {
resolveContext, cancel := context.WithTimeout(
context.WithoutCancel(requestContext),
s.attachmentCleanupTimeout,
)
defer cancel()
stored, err := s.repository.GetAttachment(
resolveContext,
attachment.ID,
attachment.OwnerID,
)
if err != nil || stored.Status != domain.AttachmentStatusReady {
return domain.Attachment{}, false
}
if stored.Variants == nil {
stored.Variants = make([]domain.AttachmentVariant, 0)
}
return stored, true
}
func contentTypeForImageFormat(format string) (string, bool) {
switch format {
case "png":
return "image/png", true
case "jpeg":
return "image/jpeg", true
default:
return "", false
}
}
func (s *Service) cleanupFailedAttachment(
requestContext context.Context,
attachment domain.Attachment,
errorCode string,
deleteObject bool,
) {
metadataContext, metadataCancel := context.WithTimeout(
context.WithoutCancel(requestContext),
s.attachmentCleanupTimeout,
)
_ = s.repository.MarkAttachmentFailed(
metadataContext,
attachment.ID,
errorCode,
s.now().UTC(),
)
metadataCancel()
if !deleteObject {
return
}
deleteContext, deleteCancel := context.WithTimeout(
context.WithoutCancel(requestContext),
s.attachmentCleanupTimeout,
)
defer deleteCancel()
_ = s.objectStore.Delete(deleteContext, attachment.ObjectKey)
}
+524
View File
@@ -0,0 +1,524 @@
package application_test
import (
"bytes"
"context"
"encoding/binary"
"errors"
"hash/crc32"
"image"
"image/color"
"image/jpeg"
"image/png"
"io"
"strings"
"sync"
"testing"
"time"
"mtusi2026lab4/internal/adapter/memory"
. "mtusi2026lab4/internal/application"
"mtusi2026lab4/internal/domain"
)
type fakeObjectStore struct {
mu sync.Mutex
objects map[string][]byte
putError error
blockDelete bool
putCalls int
deleteCalls int
lastPutKey string
}
type alwaysFailReader struct{}
func (alwaysFailReader) Read([]byte) (int, error) {
return 0, errors.New("injected interrupted upload")
}
type finalizeFailureRepository struct {
Repository
}
func (repository *finalizeFailureRepository) MarkAttachmentReady(
context.Context,
string,
time.Time,
) (domain.Attachment, error) {
return domain.Attachment{}, errors.New("injected metadata finalize failure")
}
type commitThenDisconnectRepository struct {
Repository
hideReadback bool
}
func (repository *commitThenDisconnectRepository) MarkAttachmentReady(
ctx context.Context,
attachmentID string,
updatedAt time.Time,
) (domain.Attachment, error) {
if _, err := repository.Repository.MarkAttachmentReady(ctx, attachmentID, updatedAt); err != nil {
return domain.Attachment{}, err
}
return domain.Attachment{}, errors.New("injected connection loss after commit")
}
func (repository *commitThenDisconnectRepository) GetAttachment(
ctx context.Context,
attachmentID string,
actorID string,
) (domain.Attachment, error) {
if repository.hideReadback {
return domain.Attachment{}, errors.New("injected database outage during readback")
}
return repository.Repository.GetAttachment(ctx, attachmentID, actorID)
}
func newFakeObjectStore() *fakeObjectStore {
return &fakeObjectStore{objects: make(map[string][]byte)}
}
func (store *fakeObjectStore) Put(_ context.Context, object ObjectPut) error {
store.mu.Lock()
defer store.mu.Unlock()
store.putCalls++
store.lastPutKey = object.Key
if store.putError != nil {
return store.putError
}
payload, err := io.ReadAll(object.Body)
if err != nil {
return err
}
if int64(len(payload)) != object.SizeBytes {
return errors.New("declared object size differs")
}
store.objects[object.Key] = payload
return nil
}
func (store *fakeObjectStore) Get(_ context.Context, key string) (ObjectContent, error) {
store.mu.Lock()
defer store.mu.Unlock()
payload, exists := store.objects[key]
if !exists {
return ObjectContent{}, errors.New("object not found")
}
copyOfPayload := append([]byte(nil), payload...)
return ObjectContent{
Body: io.NopCloser(bytes.NewReader(copyOfPayload)),
SizeBytes: int64(len(copyOfPayload)),
}, nil
}
func (store *fakeObjectStore) Delete(ctx context.Context, key string) error {
store.mu.Lock()
store.deleteCalls++
blockDelete := store.blockDelete
store.mu.Unlock()
if blockDelete {
<-ctx.Done()
return ctx.Err()
}
store.mu.Lock()
defer store.mu.Unlock()
delete(store.objects, key)
return nil
}
func newAttachmentService(
t *testing.T,
objectStore ObjectStore,
) (*Service, *memory.MemoryStore, string, string) {
t.Helper()
legacyStore := memory.NewMemoryStore()
repository := memory.NewMemoryRepository(legacyStore)
user, err := repository.CreateUser(context.Background(), "uploader", "Uploader", "hash")
if err != nil {
t.Fatal(err)
}
chat, err := repository.CreateChat(context.Background(), "Images", []string{user.ID})
if err != nil {
t.Fatal(err)
}
codec, err := NewCursorCodec("attachment-test-key-with-more-than-thirty-two-bytes")
if err != nil {
t.Fatal(err)
}
service, err := NewService(repository, codec, time.Hour, WithObjectStore(objectStore))
if err != nil {
t.Fatal(err)
}
return service, legacyStore, user.ID, chat.ID
}
func encodeTestImage(t *testing.T, contentType string) []byte {
t.Helper()
var payload bytes.Buffer
img := image.NewRGBA(image.Rect(0, 0, 2, 2))
img.Set(0, 0, color.RGBA{R: 255, A: 255})
var err error
if contentType == "image/png" {
err = png.Encode(&payload, img)
} else {
err = jpeg.Encode(&payload, img, nil)
}
if err != nil {
t.Fatal(err)
}
return payload.Bytes()
}
func corruptPNGAfterPrefix(t *testing.T) []byte {
t.Helper()
img := image.NewNRGBA(image.Rect(0, 0, 512, 512))
state := uint32(0x12345678)
for index := range img.Pix {
state ^= state << 13
state ^= state >> 17
state ^= state << 5
img.Pix[index] = byte(state)
}
var payload bytes.Buffer
if err := png.Encode(&payload, img); err != nil {
t.Fatal(err)
}
corrupted := payload.Bytes()
if len(corrupted) <= 70_000 {
t.Fatalf("test PNG is unexpectedly small: %d", len(corrupted))
}
corrupted[70_000] ^= 0xff
return corrupted
}
func jpegWithoutScanData(t *testing.T) []byte {
t.Helper()
payload := encodeTestImage(t, "image/jpeg")
sos := bytes.Index(payload, []byte{0xff, 0xda})
if sos < 0 || sos+4 > len(payload) {
t.Fatal("encoded JPEG has no SOS marker")
}
segmentLength := int(binary.BigEndian.Uint16(payload[sos+2 : sos+4]))
endOfHeader := sos + 2 + segmentLength
if endOfHeader > len(payload) {
t.Fatal("invalid SOS segment length in test JPEG")
}
return append([]byte(nil), payload[:endOfHeader]...)
}
func TestUploadAttachmentStoresValidatedImage(t *testing.T) {
objectStore := newFakeObjectStore()
service, metadataStore, actorID, chatID := newAttachmentService(t, objectStore)
payload := encodeTestImage(t, "image/png")
attachment, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: actorID,
ChatID: chatID,
Filename: "кот.png",
DeclaredContentType: "image/png",
Body: bytes.NewReader(payload),
})
if err != nil {
t.Fatal(err)
}
if attachment.Status != domain.AttachmentStatusReady {
t.Fatalf("status = %q, want ready", attachment.Status)
}
if attachment.ObjectKey == "" || strings.Contains(attachment.ObjectKey, attachment.Filename) {
t.Fatalf("object key must be server-generated: %q", attachment.ObjectKey)
}
if attachment.Width != 2 || attachment.Height != 2 || len(attachment.SHA256) != 64 {
t.Fatalf("unexpected image metadata: %+v", attachment)
}
if !bytes.Equal(objectStore.objects[attachment.ObjectKey], payload) {
t.Fatal("stored object differs from uploaded bytes")
}
stored, err := metadataStore.GetAttachmentByID(attachment.ID)
if err != nil || stored.Status != domain.AttachmentStatusReady {
t.Fatalf("ready metadata was not persisted: %+v, %v", stored, err)
}
}
func TestUploadAttachmentRejectsInvalidInputBeforeStorage(t *testing.T) {
testCases := []struct {
name string
filename string
declaredType string
payload []byte
wantError error
}{
{name: "unsafe filename", filename: "../image.png", declaredType: "image/png", payload: encodeTestImage(t, "image/png"), wantError: ErrInvalidInput},
{name: "unsupported declared type", filename: "image.gif", declaredType: "image/gif", payload: []byte("GIF89a"), wantError: ErrUnsupportedMediaType},
{name: "MIME substitution", filename: "image.jpg", declaredType: "image/jpeg", payload: encodeTestImage(t, "image/png"), wantError: ErrUnsupportedMediaType},
{name: "corrupt image", filename: "image.png", declaredType: "image/png", payload: []byte("not a png"), wantError: ErrInvalidImage},
{name: "PNG header without image data", filename: "truncated.png", declaredType: "image/png", payload: pngConfigurationOnly(1, 1), wantError: ErrInvalidImage},
{name: "PNG corruption after 64 KiB", filename: "corrupted.png", declaredType: "image/png", payload: corruptPNGAfterPrefix(t), wantError: ErrInvalidImage},
{name: "JPEG without scan data", filename: "truncated.jpg", declaredType: "image/jpeg", payload: jpegWithoutScanData(t), wantError: ErrInvalidImage},
{name: "too large", filename: "image.png", declaredType: "image/png", payload: bytes.Repeat([]byte{0}, domain.MaxAttachmentSizeBytes+1), wantError: ErrPayloadTooLarge},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
objectStore := newFakeObjectStore()
service, _, actorID, chatID := newAttachmentService(t, objectStore)
_, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: actorID,
ChatID: chatID,
Filename: testCase.filename,
DeclaredContentType: testCase.declaredType,
Body: bytes.NewReader(testCase.payload),
})
if !errors.Is(err, testCase.wantError) {
t.Fatalf("error = %v, want %v", err, testCase.wantError)
}
if objectStore.putCalls != 0 {
t.Fatalf("invalid upload reached object storage %d times", objectStore.putCalls)
}
})
}
}
func TestUploadAttachmentCompensatesObjectStoreFailure(t *testing.T) {
objectStore := newFakeObjectStore()
objectStore.putError = errors.New("injected put failure")
service, metadataStore, actorID, chatID := newAttachmentService(t, objectStore)
_, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: actorID,
ChatID: chatID,
Filename: "image.jpg",
DeclaredContentType: "image/jpeg",
Body: bytes.NewReader(encodeTestImage(t, "image/jpeg")),
})
if !errors.Is(err, ErrStorageUnavailable) {
t.Fatalf("error = %v, want ErrStorageUnavailable", err)
}
if objectStore.deleteCalls != 1 {
t.Fatalf("compensating deletes = %d, want 1", objectStore.deleteCalls)
}
objectStore.mu.Lock()
keyParts := strings.Split(objectStore.lastPutKey, "/")
objectStore.mu.Unlock()
if len(keyParts) != 4 {
t.Fatalf("unexpected generated object key: %q", objectStore.lastPutKey)
}
failedAttachment, lookupErr := metadataStore.GetAttachmentByID(keyParts[2])
if lookupErr != nil {
t.Fatal(lookupErr)
}
if failedAttachment.Status != domain.AttachmentStatusFailed || failedAttachment.ErrorCode == nil {
t.Fatalf("failed upload metadata was not finalized: %+v", failedAttachment)
}
}
func TestUploadAttachmentMarksFailedBeforeBlockedObjectCleanup(t *testing.T) {
objectStore := newFakeObjectStore()
objectStore.putError = errors.New("injected put failure")
objectStore.blockDelete = true
service, metadataStore, actorID, chatID := newAttachmentService(t, objectStore)
startedAt := time.Now()
_, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: actorID, ChatID: chatID, Filename: "blocked-cleanup.png",
DeclaredContentType: "image/png", Body: bytes.NewReader(encodeTestImage(t, "image/png")),
})
if !errors.Is(err, ErrStorageUnavailable) {
t.Fatalf("error = %v, want ErrStorageUnavailable", err)
}
if elapsed := time.Since(startedAt); elapsed > 2*time.Second {
t.Fatalf("bounded cleanup took %s", elapsed)
}
keyParts := strings.Split(objectStore.lastPutKey, "/")
failed, lookupErr := metadataStore.GetAttachmentByID(keyParts[2])
if lookupErr != nil {
t.Fatal(lookupErr)
}
if failed.Status != domain.AttachmentStatusFailed || failed.ErrorCode == nil {
t.Fatalf("blocked object cleanup consumed DB cleanup context: %+v", failed)
}
}
func TestUploadAttachmentRejectsInterruptedBodyBeforeMetadata(t *testing.T) {
objectStore := newFakeObjectStore()
service, metadataStore, actorID, chatID := newAttachmentService(t, objectStore)
payload := encodeTestImage(t, "image/png")
_, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: actorID,
ChatID: chatID,
Filename: "interrupted.png",
DeclaredContentType: "image/png",
Body: io.MultiReader(bytes.NewReader(payload[:8]), alwaysFailReader{}),
})
if !errors.Is(err, ErrInvalidInput) {
t.Fatalf("error = %v, want ErrInvalidInput", err)
}
if objectStore.putCalls != 0 {
t.Fatal("interrupted upload reached object storage")
}
if _, lookupErr := metadataStore.GetAttachmentByID("missing"); !errors.Is(lookupErr, domain.ErrNotFound) {
t.Fatalf("unexpected metadata lookup result: %v", lookupErr)
}
}
func TestUploadAttachmentPreservesObjectOnMetadataFinalizeFailure(t *testing.T) {
legacyStore := memory.NewMemoryStore()
repository := memory.NewMemoryRepository(legacyStore)
user, err := repository.CreateUser(context.Background(), "finalize", "Finalize", "hash")
if err != nil {
t.Fatal(err)
}
chat, err := repository.CreateChat(context.Background(), "Finalize", []string{user.ID})
if err != nil {
t.Fatal(err)
}
codec, err := NewCursorCodec("finalize-test-key-with-more-than-thirty-two-bytes")
if err != nil {
t.Fatal(err)
}
objectStore := newFakeObjectStore()
service, err := NewService(
&finalizeFailureRepository{Repository: repository},
codec,
time.Hour,
WithObjectStore(objectStore),
)
if err != nil {
t.Fatal(err)
}
_, err = service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: user.ID,
ChatID: chat.ID,
Filename: "finalize.png",
DeclaredContentType: "image/png",
Body: bytes.NewReader(encodeTestImage(t, "image/png")),
})
if err == nil {
t.Fatal("metadata finalize failure was hidden")
}
if objectStore.deleteCalls != 0 || len(objectStore.objects) != 1 {
t.Fatalf("ambiguous object must be preserved: deletes=%d objects=%d", objectStore.deleteCalls, len(objectStore.objects))
}
keyParts := strings.Split(objectStore.lastPutKey, "/")
pending, lookupErr := legacyStore.GetAttachmentByID(keyParts[2])
if lookupErr != nil {
t.Fatal(lookupErr)
}
if pending.Status != domain.AttachmentStatusPending || pending.ErrorCode != nil {
t.Fatalf("ambiguous metadata must remain reconcilable: %+v", pending)
}
}
func TestUploadAttachmentRecoversWhenCommitResponseIsLost(t *testing.T) {
legacyStore := memory.NewMemoryStore()
baseRepository := memory.NewMemoryRepository(legacyStore)
user, err := baseRepository.CreateUser(context.Background(), "commit-lost", "Commit Lost", "hash")
if err != nil {
t.Fatal(err)
}
chat, err := baseRepository.CreateChat(context.Background(), "Commit Lost", []string{user.ID})
if err != nil {
t.Fatal(err)
}
codec, err := NewCursorCodec("commit-lost-test-key-with-more-than-thirty-two-bytes")
if err != nil {
t.Fatal(err)
}
objectStore := newFakeObjectStore()
repository := &commitThenDisconnectRepository{Repository: baseRepository}
service, err := NewService(repository, codec, time.Hour, WithObjectStore(objectStore))
if err != nil {
t.Fatal(err)
}
attachment, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: user.ID, ChatID: chat.ID, Filename: "commit.png",
DeclaredContentType: "image/png", Body: bytes.NewReader(encodeTestImage(t, "image/png")),
})
if err != nil {
t.Fatalf("committed ready attachment was not recovered: %v", err)
}
if attachment.Status != domain.AttachmentStatusReady || len(objectStore.objects) != 1 || objectStore.deleteCalls != 0 {
t.Fatalf("lost commit response damaged attachment: attachment=%+v deletes=%d objects=%d",
attachment, objectStore.deleteCalls, len(objectStore.objects))
}
}
func TestUploadAttachmentNeverDeletesObjectAfterAmbiguousCommit(t *testing.T) {
legacyStore := memory.NewMemoryStore()
baseRepository := memory.NewMemoryRepository(legacyStore)
user, err := baseRepository.CreateUser(context.Background(), "commit-outage", "Commit Outage", "hash")
if err != nil {
t.Fatal(err)
}
chat, err := baseRepository.CreateChat(context.Background(), "Commit Outage", []string{user.ID})
if err != nil {
t.Fatal(err)
}
codec, err := NewCursorCodec("commit-outage-test-key-with-more-than-thirty-two-bytes")
if err != nil {
t.Fatal(err)
}
objectStore := newFakeObjectStore()
repository := &commitThenDisconnectRepository{Repository: baseRepository, hideReadback: true}
service, err := NewService(repository, codec, time.Hour, WithObjectStore(objectStore))
if err != nil {
t.Fatal(err)
}
_, err = service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: user.ID, ChatID: chat.ID, Filename: "commit.png",
DeclaredContentType: "image/png", Body: bytes.NewReader(encodeTestImage(t, "image/png")),
})
if err == nil {
t.Fatal("database outage after commit was hidden")
}
keyParts := strings.Split(objectStore.lastPutKey, "/")
stored, lookupErr := legacyStore.GetAttachmentByID(keyParts[2])
if lookupErr != nil {
t.Fatal(lookupErr)
}
if stored.Status != domain.AttachmentStatusReady || len(objectStore.objects) != 1 || objectStore.deleteCalls != 0 {
t.Fatalf("committed ready metadata lost its original: metadata=%+v deletes=%d objects=%d",
stored, objectStore.deleteCalls, len(objectStore.objects))
}
}
func TestUploadAttachmentRejectsPixelLimitBeforeFullDecode(t *testing.T) {
objectStore := newFakeObjectStore()
service, _, actorID, chatID := newAttachmentService(t, objectStore)
_, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: actorID,
ChatID: chatID,
Filename: "huge.png",
DeclaredContentType: "image/png",
Body: bytes.NewReader(pngConfigurationOnly(10_000, 4_001)),
})
if !errors.Is(err, ErrPayloadTooLarge) {
t.Fatalf("error = %v, want ErrPayloadTooLarge", err)
}
if objectStore.putCalls != 0 {
t.Fatalf("oversized decoded image reached object storage %d times", objectStore.putCalls)
}
}
func pngConfigurationOnly(width uint32, height uint32) []byte {
payload := make([]byte, 33)
copy(payload[0:8], []byte{137, 80, 78, 71, 13, 10, 26, 10})
binary.BigEndian.PutUint32(payload[8:12], 13)
copy(payload[12:16], "IHDR")
binary.BigEndian.PutUint32(payload[16:20], width)
binary.BigEndian.PutUint32(payload[20:24], height)
payload[24] = 8
payload[25] = 6
payload[26] = 0
payload[27] = 0
payload[28] = 0
binary.BigEndian.PutUint32(payload[29:33], crc32.ChecksumIEEE(payload[12:29]))
return payload
}
+11
View File
@@ -1,5 +1,7 @@
package application
import "io"
type CreateUserCommand struct {
Username string
DisplayName string
@@ -21,7 +23,16 @@ type SendMessageCommand struct {
ActorID string
ChatID string
Text string
AttachmentIDs []string
Method string
CanonicalPath string
IdempotencyKey string
}
type UploadAttachmentCommand struct {
ActorID string
ChatID string
Filename string
DeclaredContentType string
Body io.Reader
}
+30 -4
View File
@@ -1,7 +1,9 @@
package application
import (
"encoding/base64"
"errors"
"strings"
"testing"
"time"
@@ -47,11 +49,13 @@ func TestCursorCodecRejectsTamperingAndWrongScope(t *testing.T) {
t.Fatal(err)
}
replacement := "A"
if token[len(token)-1:] == replacement {
replacement = "B"
parts := strings.Split(token, ".")
signature, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
t.Fatal(err)
}
tampered := token[:len(token)-1] + replacement
signature[0] ^= 1
tampered := parts[0] + "." + base64.RawURLEncoding.EncodeToString(signature)
if _, err = codec.DecodeChat(tampered, "9fa3f49c-e62e-4209-8414-d6d5f69805bf"); !errors.Is(err, ErrInvalidCursor) {
t.Fatalf("tampered cursor: got %v, want ErrInvalidCursor", err)
}
@@ -68,3 +72,25 @@ func TestCursorCodecRequiresStrongSharedKey(t *testing.T) {
t.Fatal("expected short cursor signing key to be rejected")
}
}
func TestCursorCodecRejectsSignedInvalidFieldTypesBeforeSQL(t *testing.T) {
codec, err := NewCursorCodec(cursorTestKey)
if err != nil {
t.Fatal(err)
}
chatID := "9fa3f49c-e62e-4209-8414-d6d5f69805bf"
validMessageID := "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf"
testCases := []cursorPayload{
{Version: cursorVersion, Kind: "message", CreatedAt: "not-a-time", ID: validMessageID, ScopeID: chatID},
{Version: cursorVersion, Kind: "message", CreatedAt: time.Now().UTC().Format(time.RFC3339Nano), ID: "not-a-uuid", ScopeID: chatID},
}
for _, payload := range testCases {
token, encodeErr := codec.encode(payload)
if encodeErr != nil {
t.Fatal(encodeErr)
}
if _, decodeErr := codec.DecodeMessage(token, chatID); !errors.Is(decodeErr, ErrInvalidCursor) {
t.Fatalf("invalid signed cursor returned %v, want ErrInvalidCursor", decodeErr)
}
}
}
+10 -5
View File
@@ -3,9 +3,14 @@ package application
import "errors"
var (
ErrInvalidCursor = errors.New("invalid cursor")
ErrInvalidCredentials = errors.New("invalid credentials")
ErrInvalidInput = errors.New("invalid input")
ErrCredentialState = errors.New("invalid stored credential state")
ErrIdempotencyConflict = errors.New("idempotency key is already used for another request")
ErrInvalidCursor = errors.New("invalid cursor")
ErrInvalidCredentials = errors.New("invalid credentials")
ErrInvalidInput = errors.New("invalid input")
ErrCredentialState = errors.New("invalid stored credential state")
ErrIdempotencyConflict = errors.New("idempotency key is already used for another request")
ErrAttachmentNotReady = errors.New("attachment is not ready")
ErrPayloadTooLarge = errors.New("payload too large")
ErrUnsupportedMediaType = errors.New("unsupported media type")
ErrInvalidImage = errors.New("invalid image")
ErrStorageUnavailable = errors.New("object storage unavailable")
)
+13 -2
View File
@@ -7,6 +7,8 @@ import (
"fmt"
"mtusi2026lab4/internal/domain"
"github.com/google/uuid"
)
type canonicalMessageRequest struct {
@@ -15,13 +17,21 @@ type canonicalMessageRequest struct {
}
func (s *Service) SendMessage(ctx context.Context, command SendMessageCommand) (domain.Message, error) {
if err := domain.ValidateMessageText(command.Text); err != nil {
attachmentIDs := append([]string(nil), command.AttachmentIDs...)
if attachmentIDs == nil {
attachmentIDs = make([]string, 0)
}
if err := domain.ValidateMessageInput(command.Text, attachmentIDs); err != nil {
return domain.Message{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
for index, attachmentID := range attachmentIDs {
attachmentIDs[index] = uuid.MustParse(attachmentID).String()
}
canonicalBody, err := json.Marshal(canonicalMessageRequest{
Text: command.Text,
AttachmentIDs: make([]string, 0),
AttachmentIDs: attachmentIDs,
})
if err != nil {
return domain.Message{}, fmt.Errorf("canonicalize message request: %w", err)
@@ -31,6 +41,7 @@ func (s *Service) SendMessage(ctx context.Context, command SendMessageCommand) (
ActorID: command.ActorID,
ChatID: command.ChatID,
Text: command.Text,
AttachmentIDs: attachmentIDs,
Method: command.Method,
CanonicalPath: command.CanonicalPath,
Key: command.IdempotencyKey,
+28
View File
@@ -2,6 +2,7 @@ package application
import (
"context"
"io"
"time"
"mtusi2026lab4/internal/domain"
@@ -28,6 +29,7 @@ type IdempotentMessageWrite struct {
ActorID string
ChatID string
Text string
AttachmentIDs []string
Method string
CanonicalPath string
Key string
@@ -40,9 +42,35 @@ type MessageRepository interface {
GetMessages(ctx context.Context, chatID, callerID string, limit int, cursor *domain.MessageCursor) ([]domain.Message, bool, error)
}
type AttachmentRepository interface {
CreateAttachment(ctx context.Context, attachment domain.Attachment) (domain.Attachment, error)
MarkAttachmentReady(ctx context.Context, attachmentID string, updatedAt time.Time) (domain.Attachment, error)
MarkAttachmentFailed(ctx context.Context, attachmentID, errorCode string, updatedAt time.Time) error
GetAttachment(ctx context.Context, attachmentID, callerID string) (domain.Attachment, error)
}
type Repository interface {
UserRepository
SessionRepository
ChatRepository
MessageRepository
AttachmentRepository
}
type ObjectPut struct {
Key string
ContentType string
SizeBytes int64
Body io.Reader
}
type ObjectContent struct {
Body io.ReadCloser
SizeBytes int64
}
type ObjectStore interface {
Put(ctx context.Context, object ObjectPut) error
Get(ctx context.Context, key string) (ObjectContent, error)
Delete(ctx context.Context, key string) error
}
+30 -10
View File
@@ -6,15 +6,22 @@ import (
)
const MinimumIdempotencyTTL = 24 * time.Hour
const defaultAttachmentCleanupTimeout = time.Second
const defaultAttachmentUploadConcurrency = 4
const defaultAttachmentDecodeConcurrency = 1
type ServiceOption func(*Service) error
type Service struct {
repository Repository
cursors *CursorCodec
sessionTTL time.Duration
idempotencyTTL time.Duration
now func() time.Time
repository Repository
cursors *CursorCodec
sessionTTL time.Duration
idempotencyTTL time.Duration
now func() time.Time
objectStore ObjectStore
attachmentCleanupTimeout time.Duration
attachmentUploadSlots chan struct{}
attachmentDecodeSlots chan struct{}
}
func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Duration, options ...ServiceOption) (*Service, error) {
@@ -28,11 +35,14 @@ func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Dur
return nil, fmt.Errorf("session TTL must be positive")
}
service := &Service{
repository: repository,
cursors: cursors,
sessionTTL: sessionTTL,
idempotencyTTL: MinimumIdempotencyTTL,
now: func() time.Time { return time.Now().UTC() },
repository: repository,
cursors: cursors,
sessionTTL: sessionTTL,
idempotencyTTL: MinimumIdempotencyTTL,
now: func() time.Time { return time.Now().UTC() },
attachmentCleanupTimeout: defaultAttachmentCleanupTimeout,
attachmentUploadSlots: make(chan struct{}, defaultAttachmentUploadConcurrency),
attachmentDecodeSlots: make(chan struct{}, defaultAttachmentDecodeConcurrency),
}
for _, option := range options {
if err := option(service); err != nil {
@@ -51,3 +61,13 @@ func WithIdempotencyTTL(ttl time.Duration) ServiceOption {
return nil
}
}
func WithObjectStore(objectStore ObjectStore) ServiceOption {
return func(service *Service) error {
if objectStore == nil {
return fmt.Errorf("object store is required")
}
service.objectStore = objectStore
return nil
}
}
+31
View File
@@ -35,6 +35,13 @@ type Config struct {
RedisOperationTimeout time.Duration
RedisPoolSize int
S3Endpoint string
S3Region string
S3Bucket string
S3AccessKeyID string
S3SecretAccessKey string
S3OperationTimeout time.Duration
ReadinessTimeout time.Duration
ShutdownDrainDelay time.Duration
ShutdownTimeout time.Duration
@@ -82,6 +89,24 @@ func Load() (Config, error) {
return Config{}, err
}
s3AccessKeyID, err := requiredValueOrFile(
"S3_ACCESS_KEY_ID",
"S3_ACCESS_KEY_ID_FILE",
)
if err != nil {
return Config{}, err
}
s3SecretAccessKey, err := requiredValueOrFile(
"S3_SECRET_ACCESS_KEY",
"S3_SECRET_ACCESS_KEY_FILE",
)
if err != nil {
return Config{}, err
}
s3OperationTimeout, err := durationFromEnv("S3_OPERATION_TIMEOUT", 5*time.Second)
if err != nil {
return Config{}, err
}
databaseMaxConns, err := int32FromEnv("DB_MAX_CONNS", 10, 1)
if err != nil {
return Config{}, err
@@ -223,6 +248,12 @@ func Load() (Config, error) {
RedisOperationTimeout: redisOperationTimeout,
RedisPoolSize: int(redisPoolSize),
S3Endpoint: envOrDefault("S3_ENDPOINT", "http://minio:9000"),
S3Region: envOrDefault("S3_REGION", "us-east-1"),
S3Bucket: envOrDefault("S3_BUCKET", "messenger-attachments"),
S3AccessKeyID: s3AccessKeyID,
S3SecretAccessKey: s3SecretAccessKey,
S3OperationTimeout: s3OperationTimeout,
ReadinessTimeout: readinessTimeout,
ShutdownDrainDelay: shutdownDrainDelay,
ShutdownTimeout: shutdownTimeout,
+119
View File
@@ -0,0 +1,119 @@
package domain
import (
"encoding/hex"
"fmt"
"strings"
"time"
"unicode"
"unicode/utf8"
)
const (
MaxAttachmentFilenameCodePoints = 255
MaxAttachmentSizeBytes = 10 * 1024 * 1024
MaxAttachmentPixels = 40_000_000
)
type AttachmentVariant struct {
Name string
ContentType string
SizeBytes int64
Width int
Height int
SHA256 string
}
type AttachmentStatus string
const (
AttachmentStatusPending AttachmentStatus = "pending"
AttachmentStatusReady AttachmentStatus = "ready"
AttachmentStatusFailed AttachmentStatus = "failed"
)
// Attachment contains metadata only. ObjectKey points to bytes in the
// private object store and must never be derived from Filename.
type Attachment struct {
ID string
ChatID string
OwnerID string
Filename string
ObjectKey string
ContentType string
SizeBytes int64
SHA256 string
Width int
Height int
Status AttachmentStatus
Variants []AttachmentVariant
ErrorCode *string
CreatedAt time.Time
UpdatedAt time.Time
}
func ValidateAttachmentFilename(filename string) error {
if !utf8.ValidString(filename) {
return fmt.Errorf("filename must be valid UTF-8")
}
filenameLength := utf8.RuneCountInString(filename)
if filenameLength < 1 || filenameLength > MaxAttachmentFilenameCodePoints {
return fmt.Errorf("filename length must be between 1 and %d code points", MaxAttachmentFilenameCodePoints)
}
if strings.TrimSpace(filename) == "" || filename == "." || filename == ".." {
return fmt.Errorf("filename is unsafe")
}
if strings.ContainsAny(filename, `/\\`) {
return fmt.Errorf("filename must not contain path separators")
}
for _, character := range filename {
if unicode.IsControl(character) {
return fmt.Errorf("filename must not contain control characters")
}
}
return nil
}
func ValidateAttachmentContentType(contentType string) error {
if contentType != "image/png" && contentType != "image/jpeg" {
return fmt.Errorf("content type must be image/png or image/jpeg")
}
return nil
}
// ValidateReadyAttachmentMetadata checks the bounded metadata produced after
// the upload stream has been identified, decoded and hashed. It deliberately
// does not trust an HTTP Content-Type header.
func ValidateReadyAttachmentMetadata(
filename string,
contentType string,
sizeBytes int64,
sha256Hex string,
width int,
height int,
) error {
if err := ValidateAttachmentFilename(filename); err != nil {
return err
}
if err := ValidateAttachmentContentType(contentType); err != nil {
return err
}
if sizeBytes < 1 || sizeBytes > MaxAttachmentSizeBytes {
return fmt.Errorf("attachment size must be between 1 and %d bytes", MaxAttachmentSizeBytes)
}
if width < 1 || height < 1 {
return fmt.Errorf("image dimensions must be positive and contain at most %d pixels", MaxAttachmentPixels)
}
if int64(width) > int64(MaxAttachmentPixels)/int64(height) {
return fmt.Errorf("image dimensions must be positive and contain at most %d pixels", MaxAttachmentPixels)
}
if len(sha256Hex) != 64 || sha256Hex != strings.ToLower(sha256Hex) {
return fmt.Errorf("sha256 must contain 64 lowercase hexadecimal characters")
}
decodedHash, err := hex.DecodeString(sha256Hex)
if err != nil || len(decodedHash) != 32 {
return fmt.Errorf("sha256 must contain 64 lowercase hexadecimal characters")
}
return nil
}
+59
View File
@@ -0,0 +1,59 @@
package domain
import (
"math"
"strings"
"testing"
)
func TestValidateReadyAttachmentMetadata(t *testing.T) {
validHash := strings.Repeat("ab", 32)
testCases := []struct {
name string
filename string
contentType string
sizeBytes int64
sha256 string
width int
height int
wantError bool
}{
{name: "png", filename: "кот.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1},
{name: "jpeg at limits", filename: strings.Repeat("界", 255), contentType: "image/jpeg", sizeBytes: MaxAttachmentSizeBytes, sha256: validHash, width: 8_000, height: 5_000},
{name: "empty filename", filename: "", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "blank filename", filename: " ", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "dot segment", filename: "..", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "forward slash", filename: "folder/image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "backslash", filename: `folder\\image.png`, contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "control character", filename: "image\n.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "C1 control character", filename: "image\u0085.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "invalid UTF-8", filename: string([]byte{'x', 0xff, '.', 'p', 'n', 'g'}), contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "filename too long", filename: strings.Repeat("a", 256), contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "unsupported MIME", filename: "image.gif", contentType: "image/gif", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "empty file", filename: "image.png", contentType: "image/png", sizeBytes: 0, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "file too large", filename: "image.png", contentType: "image/png", sizeBytes: MaxAttachmentSizeBytes + 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "zero width", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 0, height: 1, wantError: true},
{name: "too many pixels", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 8_001, height: 5_000, wantError: true},
{name: "dimension multiplication cannot overflow", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: math.MaxInt, height: math.MaxInt, wantError: true},
{name: "short hash", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: "ab", width: 1, height: 1, wantError: true},
{name: "uppercase hash", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: strings.ToUpper(validHash), width: 1, height: 1, wantError: true},
{name: "non-hex hash", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: strings.Repeat("zz", 32), width: 1, height: 1, wantError: true},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
err := ValidateReadyAttachmentMetadata(
testCase.filename,
testCase.contentType,
testCase.sizeBytes,
testCase.sha256,
testCase.width,
testCase.height,
)
if (err != nil) != testCase.wantError {
t.Fatalf("ValidateReadyAttachmentMetadata() error = %v, wantError %v", err, testCase.wantError)
}
})
}
}
+6 -5
View File
@@ -3,11 +3,12 @@ package domain
import "time"
type Message struct {
ID string
ChatID string
SenderID string
Text string
CreatedAt time.Time
ID string
ChatID string
SenderID string
Text string
AttachmentIDs []string
CreatedAt time.Time
}
type MessageCursor struct {
+70
View File
@@ -0,0 +1,70 @@
package domain
import (
"strings"
"testing"
)
func TestValidateMessageInput(t *testing.T) {
validAttachment := "11111111-1111-4111-8111-111111111111"
testCases := []struct {
name string
text string
attachmentIDs []string
wantError bool
}{
{name: "text only", text: "hello"},
{name: "attachment only", attachmentIDs: []string{validAttachment}},
{name: "whitespace with attachment", text: " ", attachmentIDs: []string{validAttachment}},
{name: "empty", wantError: true},
{name: "whitespace only", text: " ", wantError: true},
{name: "text too long", text: strings.Repeat("界", 4001), wantError: true},
{name: "invalid attachment uuid", text: "hello", attachmentIDs: []string{"not-a-uuid"}, wantError: true},
{
name: "duplicate attachment uuid ignores case",
text: "hello",
attachmentIDs: []string{
"AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA",
"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
},
wantError: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
err := ValidateMessageInput(testCase.text, testCase.attachmentIDs)
if (err != nil) != testCase.wantError {
t.Fatalf("ValidateMessageInput() error = %v, wantError %v", err, testCase.wantError)
}
})
}
}
func TestValidateMessageInputAttachmentLimit(t *testing.T) {
attachmentIDs := []string{
"00000000-0000-4000-8000-000000000001",
"00000000-0000-4000-8000-000000000002",
"00000000-0000-4000-8000-000000000003",
"00000000-0000-4000-8000-000000000004",
"00000000-0000-4000-8000-000000000005",
"00000000-0000-4000-8000-000000000006",
"00000000-0000-4000-8000-000000000007",
"00000000-0000-4000-8000-000000000008",
"00000000-0000-4000-8000-000000000009",
"00000000-0000-4000-8000-000000000010",
}
if err := ValidateMessageInput("", attachmentIDs); err != nil {
t.Fatalf("10 attachments must be accepted: %v", err)
}
attachmentIDs = append(
attachmentIDs,
"00000000-0000-4000-8000-000000000011",
)
if err := ValidateMessageInput("hello", attachmentIDs); err == nil {
t.Fatal("11 attachments must be rejected")
}
}
+29 -5
View File
@@ -9,6 +9,8 @@ import (
"github.com/google/uuid"
)
const MaxMessageAttachments = 10
var usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
func ValidateUser(username, displayName string) error {
@@ -65,13 +67,35 @@ func ValidateChatInput(title string, memberIDs []string, callerID string) error
return nil
}
func ValidateMessageText(text string) error {
func ValidateMessageInput(text string, attachmentIDs []string) error {
textRunes := utf8.RuneCountInString(text)
if textRunes < 1 || textRunes > 4000 {
return fmt.Errorf("message text length must be between 1 and 4000 code points")
if textRunes > 4000 {
return fmt.Errorf("message text length must be at most 4000 code points")
}
if strings.TrimSpace(text) == "" {
return fmt.Errorf("message text cannot be only whitespace")
if len(attachmentIDs) > MaxMessageAttachments {
return fmt.Errorf("attachment_ids must contain at most %d items", MaxMessageAttachments)
}
seen := make(map[string]struct{}, len(attachmentIDs))
for _, attachmentID := range attachmentIDs {
parsedID, err := uuid.Parse(attachmentID)
if err != nil {
return fmt.Errorf("invalid attachment uuid: %s", attachmentID)
}
canonicalID := parsedID.String()
if _, exists := seen[canonicalID]; exists {
return fmt.Errorf("duplicate attachment_id: %s", attachmentID)
}
seen[canonicalID] = struct{}{}
}
if strings.TrimSpace(text) == "" && len(attachmentIDs) == 0 {
return fmt.Errorf("message must contain non-blank text or at least one attachment")
}
return nil
}
// ValidateMessageText remains for callers that create text-only messages.
func ValidateMessageText(text string) error {
return ValidateMessageInput(text, nil)
}
+229
View File
@@ -0,0 +1,229 @@
package reconcile
import (
"context"
"fmt"
"sort"
"time"
"mtusi2026lab4/internal/adapter/objectstore"
"mtusi2026lab4/internal/domain"
)
const (
IssueOrphanObject = "orphan_object"
IssueMissingObject = "missing_object"
IssueStalePending = "stale_pending"
IssueFailedObject = "failed_object"
IssueReferencedMissing = "referenced_missing_object"
)
type AttachmentRecord struct {
ID string
ObjectKey string
Status domain.AttachmentStatus
UpdatedAt time.Time
Referenced bool
}
type MetadataStore interface {
ListAttachmentInventory(ctx context.Context) ([]AttachmentRecord, error)
MarkAttachmentFailedIfUnreferenced(
ctx context.Context,
attachmentID string,
expectedStatus domain.AttachmentStatus,
updatedBefore time.Time,
errorCode string,
updatedAt time.Time,
) (bool, error)
}
type ObjectInventory interface {
List(ctx context.Context, prefix string) ([]objectstore.StoredObject, error)
Delete(ctx context.Context, key string) error
}
type Issue struct {
Kind string `json:"kind"`
AttachmentID string `json:"attachment_id,omitempty"`
ObjectKey string `json:"object_key"`
Protected bool `json:"protected,omitempty"`
Action string `json:"action"`
}
type Result struct {
DryRun bool `json:"dry_run"`
GracePeriod time.Duration `json:"-"`
GracePeriodSeconds int64 `json:"grace_period_seconds"`
ScannedAttachments int `json:"scanned_attachments"`
ScannedObjects int `json:"scanned_objects"`
Issues []Issue `json:"issues"`
DeletedObjects int `json:"deleted_objects"`
FailedAttachments int `json:"failed_attachments"`
Duration time.Duration `json:"-"`
DurationMillis int64 `json:"duration_ms"`
}
type Reconciler struct {
metadata MetadataStore
objects ObjectInventory
now func() time.Time
}
func New(metadata MetadataStore, objects ObjectInventory) (*Reconciler, error) {
if metadata == nil || objects == nil {
return nil, fmt.Errorf("metadata and object stores are required")
}
return &Reconciler{
metadata: metadata,
objects: objects,
now: func() time.Time { return time.Now().UTC() },
}, nil
}
func (r *Reconciler) Run(
ctx context.Context,
gracePeriod time.Duration,
apply bool,
) (Result, error) {
if gracePeriod <= 0 {
return Result{}, fmt.Errorf("grace period must be positive")
}
startedAt := r.now().UTC()
cutoff := startedAt.Add(-gracePeriod)
result := Result{
DryRun: !apply,
GracePeriod: gracePeriod,
GracePeriodSeconds: int64(gracePeriod / time.Second),
Issues: make([]Issue, 0),
}
attachments, err := r.metadata.ListAttachmentInventory(ctx)
if err != nil {
return Result{}, fmt.Errorf("list attachment metadata: %w", err)
}
objects, err := r.objects.List(ctx, "attachments/")
if err != nil {
return Result{}, fmt.Errorf("list attachment objects: %w", err)
}
result.ScannedAttachments = len(attachments)
result.ScannedObjects = len(objects)
attachmentsByKey := make(map[string]AttachmentRecord, len(attachments))
for _, attachment := range attachments {
attachmentsByKey[attachment.ObjectKey] = attachment
}
objectsByKey := make(map[string]objectstore.StoredObject, len(objects))
for _, object := range objects {
objectsByKey[object.Key] = object
if _, exists := attachmentsByKey[object.Key]; exists {
continue
}
if object.LastModified.IsZero() || object.LastModified.After(cutoff) {
continue
}
issue := Issue{Kind: IssueOrphanObject, ObjectKey: object.Key, Action: "would_delete"}
if apply {
if err = r.objects.Delete(ctx, object.Key); err != nil {
return result, fmt.Errorf("delete orphan object %q: %w", object.Key, err)
}
issue.Action = "deleted"
result.DeletedObjects++
}
result.Issues = append(result.Issues, issue)
}
for _, attachment := range attachments {
if attachment.UpdatedAt.After(cutoff) {
continue
}
_, objectExists := objectsByKey[attachment.ObjectKey]
switch {
case attachment.Status == domain.AttachmentStatusReady && !objectExists:
issue := Issue{
Kind: IssueMissingObject,
AttachmentID: attachment.ID,
ObjectKey: attachment.ObjectKey,
Protected: attachment.Referenced,
Action: "would_mark_failed",
}
if attachment.Referenced {
issue.Kind = IssueReferencedMissing
issue.Action = "manual_repair_required"
} else if apply {
changed, markError := r.metadata.MarkAttachmentFailedIfUnreferenced(
ctx, attachment.ID, attachment.Status, cutoff,
"reconciler_missing_object", startedAt,
)
if markError != nil {
return result, fmt.Errorf("mark missing attachment %q failed: %w", attachment.ID, markError)
}
if changed {
issue.Action = "marked_failed"
result.FailedAttachments++
} else {
issue.Action = "skipped_concurrent_change"
}
}
result.Issues = append(result.Issues, issue)
case attachment.Status == domain.AttachmentStatusPending:
issue := Issue{
Kind: IssueStalePending, AttachmentID: attachment.ID,
ObjectKey: attachment.ObjectKey, Protected: attachment.Referenced,
Action: "would_mark_failed",
}
if attachment.Referenced {
issue.Action = "manual_repair_required"
} else if apply {
changed, markError := r.metadata.MarkAttachmentFailedIfUnreferenced(
ctx, attachment.ID, attachment.Status, cutoff,
"reconciler_stale_pending", startedAt,
)
if markError != nil {
return result, fmt.Errorf("mark stale attachment %q failed: %w", attachment.ID, markError)
}
if changed {
issue.Action = "marked_failed"
result.FailedAttachments++
if objectExists {
if err = r.objects.Delete(ctx, attachment.ObjectKey); err != nil {
return result, fmt.Errorf("delete stale pending object %q: %w", attachment.ObjectKey, err)
}
result.DeletedObjects++
}
} else {
issue.Action = "skipped_concurrent_change"
}
}
result.Issues = append(result.Issues, issue)
case attachment.Status == domain.AttachmentStatusFailed && objectExists:
issue := Issue{
Kind: IssueFailedObject, AttachmentID: attachment.ID,
ObjectKey: attachment.ObjectKey, Protected: attachment.Referenced,
Action: "would_delete",
}
if attachment.Referenced {
issue.Action = "manual_repair_required"
} else if apply {
if err = r.objects.Delete(ctx, attachment.ObjectKey); err != nil {
return result, fmt.Errorf("delete failed attachment object %q: %w", attachment.ObjectKey, err)
}
issue.Action = "deleted"
result.DeletedObjects++
}
result.Issues = append(result.Issues, issue)
}
}
sort.Slice(result.Issues, func(i, j int) bool {
if result.Issues[i].ObjectKey == result.Issues[j].ObjectKey {
return result.Issues[i].Kind < result.Issues[j].Kind
}
return result.Issues[i].ObjectKey < result.Issues[j].ObjectKey
})
result.Duration = r.now().UTC().Sub(startedAt)
result.DurationMillis = result.Duration.Milliseconds()
return result, nil
}
+209
View File
@@ -0,0 +1,209 @@
package reconcile
import (
"context"
"errors"
"testing"
"time"
"mtusi2026lab4/internal/adapter/objectstore"
"mtusi2026lab4/internal/domain"
)
type fakeMetadataStore struct {
records []AttachmentRecord
markError error
skipMark bool
}
func (store *fakeMetadataStore) ListAttachmentInventory(
context.Context,
) ([]AttachmentRecord, error) {
return append([]AttachmentRecord(nil), store.records...), nil
}
func (store *fakeMetadataStore) MarkAttachmentFailedIfUnreferenced(
_ context.Context,
attachmentID string,
expectedStatus domain.AttachmentStatus,
updatedBefore time.Time,
errorCode string,
updatedAt time.Time,
) (bool, error) {
if store.markError != nil {
return false, store.markError
}
if store.skipMark {
return false, nil
}
for index := range store.records {
record := &store.records[index]
if record.ID != attachmentID || record.Status != expectedStatus ||
record.UpdatedAt.After(updatedBefore) || record.Referenced {
continue
}
record.Status = domain.AttachmentStatusFailed
record.UpdatedAt = updatedAt
_ = errorCode
return true, nil
}
return false, nil
}
func TestReconcilerDoesNotDeleteAfterConcurrentMetadataChange(t *testing.T) {
old := time.Now().UTC().Add(-2 * time.Hour)
metadata := &fakeMetadataStore{
records: []AttachmentRecord{{
ID: "pending-race", ObjectKey: "attachments/pending-race",
Status: domain.AttachmentStatusPending, UpdatedAt: old,
}},
skipMark: true,
}
objects := &fakeObjectInventory{objects: map[string]objectstore.StoredObject{
"attachments/pending-race": {Key: "attachments/pending-race", LastModified: old},
}}
reconciler, err := New(metadata, objects)
if err != nil {
t.Fatal(err)
}
result, err := reconciler.Run(context.Background(), time.Hour, true)
if err != nil {
t.Fatal(err)
}
if result.DeletedObjects != 0 || result.FailedAttachments != 0 {
t.Fatalf("concurrent metadata change must suppress deletion: %+v", result)
}
if _, exists := objects.objects["attachments/pending-race"]; !exists {
t.Fatal("reconciler deleted an object after losing the metadata race")
}
if len(result.Issues) != 1 || result.Issues[0].Action != "skipped_concurrent_change" {
t.Fatalf("unexpected race result: %+v", result.Issues)
}
}
type fakeObjectInventory struct {
objects map[string]objectstore.StoredObject
deleteError error
}
func (store *fakeObjectInventory) List(
context.Context,
string,
) ([]objectstore.StoredObject, error) {
objects := make([]objectstore.StoredObject, 0, len(store.objects))
for _, object := range store.objects {
objects = append(objects, object)
}
return objects, nil
}
func (store *fakeObjectInventory) Delete(_ context.Context, key string) error {
if store.deleteError != nil {
return store.deleteError
}
delete(store.objects, key)
return nil
}
func TestReconcilerDryRunApplyAndRepeat(t *testing.T) {
now := time.Now().UTC()
old := now.Add(-2 * time.Hour)
fresh := now.Add(-5 * time.Minute)
metadata := &fakeMetadataStore{records: []AttachmentRecord{
{ID: "ready-present", ObjectKey: "attachments/ready-present", Status: domain.AttachmentStatusReady, UpdatedAt: old},
{ID: "ready-missing", ObjectKey: "attachments/ready-missing", Status: domain.AttachmentStatusReady, UpdatedAt: old},
{ID: "ready-used-missing", ObjectKey: "attachments/ready-used-missing", Status: domain.AttachmentStatusReady, UpdatedAt: old, Referenced: true},
{ID: "pending-old", ObjectKey: "attachments/pending-old", Status: domain.AttachmentStatusPending, UpdatedAt: old},
{ID: "failed-old", ObjectKey: "attachments/failed-old", Status: domain.AttachmentStatusFailed, UpdatedAt: old},
{ID: "pending-fresh", ObjectKey: "attachments/pending-fresh", Status: domain.AttachmentStatusPending, UpdatedAt: fresh},
}}
objects := &fakeObjectInventory{objects: map[string]objectstore.StoredObject{
"attachments/ready-present": {Key: "attachments/ready-present", LastModified: old},
"attachments/pending-old": {Key: "attachments/pending-old", LastModified: old},
"attachments/failed-old": {Key: "attachments/failed-old", LastModified: old},
"attachments/orphan-old": {Key: "attachments/orphan-old", LastModified: old},
"attachments/orphan-fresh": {Key: "attachments/orphan-fresh", LastModified: fresh},
}}
reconciler, err := New(metadata, objects)
if err != nil {
t.Fatal(err)
}
dryRun, err := reconciler.Run(context.Background(), time.Hour, false)
if err != nil {
t.Fatal(err)
}
if !dryRun.DryRun || len(dryRun.Issues) != 5 ||
dryRun.DeletedObjects != 0 || dryRun.FailedAttachments != 0 {
t.Fatalf("unexpected dry-run result: %+v", dryRun)
}
if len(objects.objects) != 5 {
t.Fatal("dry-run changed object storage")
}
for _, record := range metadata.records {
if record.ID == "ready-missing" && record.Status != domain.AttachmentStatusReady {
t.Fatal("dry-run changed metadata")
}
}
applied, err := reconciler.Run(context.Background(), time.Hour, true)
if err != nil {
t.Fatal(err)
}
if applied.DeletedObjects != 3 || applied.FailedAttachments != 2 {
t.Fatalf("unexpected apply result: %+v", applied)
}
if _, exists := objects.objects["attachments/orphan-old"]; exists {
t.Fatal("old orphan was not deleted")
}
if _, exists := objects.objects["attachments/orphan-fresh"]; !exists {
t.Fatal("fresh orphan must be protected by grace period")
}
if _, exists := objects.objects["attachments/ready-present"]; !exists {
t.Fatal("healthy object was deleted")
}
for _, issue := range applied.Issues {
if issue.AttachmentID == "ready-used-missing" &&
(!issue.Protected || issue.Action != "manual_repair_required") {
t.Fatalf("referenced attachment was not protected: %+v", issue)
}
}
repeated, err := reconciler.Run(context.Background(), time.Hour, true)
if err != nil {
t.Fatal(err)
}
if repeated.DeletedObjects != 0 || repeated.FailedAttachments != 0 {
t.Fatalf("repeat must be mutation-idempotent: %+v", repeated)
}
if len(repeated.Issues) != 1 || !repeated.Issues[0].Protected {
t.Fatalf("repeat should retain only protected manual issue: %+v", repeated)
}
}
func TestReconcilerReportsMutationFailures(t *testing.T) {
old := time.Now().UTC().Add(-2 * time.Hour)
metadata := &fakeMetadataStore{records: []AttachmentRecord{
{ID: "missing", ObjectKey: "attachments/missing", Status: domain.AttachmentStatusReady, UpdatedAt: old},
}}
metadata.markError = errors.New("injected database failure")
objects := &fakeObjectInventory{objects: make(map[string]objectstore.StoredObject)}
reconciler, err := New(metadata, objects)
if err != nil {
t.Fatal(err)
}
if _, err = reconciler.Run(context.Background(), time.Hour, true); err == nil {
t.Fatal("injected database mutation failure was hidden")
}
metadata.records = nil
metadata.markError = nil
objects.objects["attachments/orphan"] = objectstore.StoredObject{
Key: "attachments/orphan", LastModified: old,
}
objects.deleteError = errors.New("injected object-store failure")
if _, err = reconciler.Run(context.Background(), time.Hour, true); err == nil {
t.Fatal("injected object-store mutation failure was hidden")
}
}
+59
View File
@@ -0,0 +1,59 @@
package dto
import (
"time"
"mtusi2026lab4/internal/domain"
)
type AttachmentVariantResponse struct {
Name string `json:"name"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
Width int `json:"width"`
Height int `json:"height"`
SHA256 string `json:"sha256"`
}
type AttachmentResponse struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status domain.AttachmentStatus `json:"status"`
Variants []AttachmentVariantResponse `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func AttachmentFromDomain(attachment domain.Attachment) AttachmentResponse {
variants := make([]AttachmentVariantResponse, 0, len(attachment.Variants))
for _, variant := range attachment.Variants {
variants = append(variants, AttachmentVariantResponse{
Name: variant.Name,
ContentType: variant.ContentType,
SizeBytes: variant.SizeBytes,
Width: variant.Width,
Height: variant.Height,
SHA256: variant.SHA256,
})
}
return AttachmentResponse{
ID: attachment.ID,
ChatID: attachment.ChatID,
OwnerID: attachment.OwnerID,
Filename: attachment.Filename,
ContentType: attachment.ContentType,
SizeBytes: attachment.SizeBytes,
SHA256: attachment.SHA256,
Status: attachment.Status,
Variants: variants,
ErrorCode: attachment.ErrorCode,
CreatedAt: attachment.CreatedAt,
UpdatedAt: attachment.UpdatedAt,
}
}
+14 -7
View File
@@ -7,15 +7,17 @@ import (
)
type CreateMessageRequest struct {
Text string `json:"text"`
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
type MessageResponse struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt time.Time `json:"created_at"`
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
CreatedAt time.Time `json:"created_at"`
}
type MessagePageResponse struct {
@@ -24,9 +26,14 @@ type MessagePageResponse struct {
}
func MessageFromDomain(message domain.Message) MessageResponse {
attachmentIDs := append([]string(nil), message.AttachmentIDs...)
if attachmentIDs == nil {
attachmentIDs = make([]string, 0)
}
return MessageResponse{
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
Text: message.Text, CreatedAt: message.CreatedAt,
Text: message.Text, AttachmentIDs: attachmentIDs, CreatedAt: message.CreatedAt,
}
}
@@ -44,6 +44,7 @@ func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
ActorID: currentUser.ID,
ChatID: chatID,
Text: request.Text,
AttachmentIDs: request.AttachmentIDs,
Method: http.MethodPost,
CanonicalPath: "/api/v1/chats/" + chatID + "/messages",
IdempotencyKey: idempotencyKey,
@@ -53,6 +54,11 @@ func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
"Idempotency-Key is already used for another request", requestID)
return
}
if errors.Is(err, application.ErrAttachmentNotReady) {
response.WriteError(w, http.StatusConflict, response.CodeConflict,
"attachment is not ready", requestID)
return
}
if errors.Is(err, application.ErrInvalidInput) {
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "), requestID)
@@ -0,0 +1,94 @@
package handlers
import (
"errors"
"io"
"mime"
"net/http"
"strconv"
"mtusi2026lab4/internal/application"
"mtusi2026lab4/internal/domain"
"mtusi2026lab4/internal/transport/http/dto"
"mtusi2026lab4/internal/transport/http/middleware"
"mtusi2026lab4/internal/transport/http/response"
"github.com/google/uuid"
)
func (h *Handler) GetAttachment(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
currentUser := middleware.GetCurrentUser(r.Context())
attachmentID, ok := parseAttachmentID(w, r, requestID)
if !ok {
return
}
attachment, err := h.service.GetAttachment(r.Context(), attachmentID, currentUser.ID)
if errors.Is(err, domain.ErrNotFound) {
response.WriteError(w, http.StatusNotFound, response.CodeNotFound,
"attachment not found", requestID)
return
}
if err != nil {
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
"service is temporarily unavailable", requestID)
return
}
response.WriteJSON(w, http.StatusOK, dto.AttachmentFromDomain(attachment), requestID)
}
func (h *Handler) DownloadAttachment(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
currentUser := middleware.GetCurrentUser(r.Context())
attachmentID, ok := parseAttachmentID(w, r, requestID)
if !ok {
return
}
download, err := h.service.DownloadAttachment(
r.Context(), attachmentID, currentUser.ID, r.URL.Query().Get("variant"),
)
switch {
case errors.Is(err, domain.ErrNotFound):
response.WriteError(w, http.StatusNotFound, response.CodeNotFound,
"attachment or variant not found", requestID)
return
case errors.Is(err, application.ErrAttachmentNotReady):
response.WriteError(w, http.StatusConflict, response.CodeConflict,
"attachment is not ready", requestID)
return
case errors.Is(err, application.ErrStorageUnavailable):
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
"object storage is temporarily unavailable", requestID)
return
case err != nil:
response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError,
"unexpected internal error", requestID)
return
}
defer download.Body.Close()
w.Header().Set("Content-Type", download.ContentType)
w.Header().Set("Content-Length", strconv.FormatInt(download.SizeBytes, 10))
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Content-Disposition", mime.FormatMediaType(
"attachment", map[string]string{"filename": download.Filename},
))
w.WriteHeader(http.StatusOK)
_, _ = io.Copy(w, download.Body)
}
func parseAttachmentID(
w http.ResponseWriter,
r *http.Request,
requestID string,
) (string, bool) {
parsedID, err := uuid.Parse(r.PathValue("attachment_id"))
if err != nil {
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
"invalid attachment_id uuid", requestID)
return "", false
}
return parsedID.String(), true
}
@@ -0,0 +1,97 @@
package handlers
import (
"errors"
"mime"
"net/http"
"strings"
"mtusi2026lab4/internal/application"
"mtusi2026lab4/internal/domain"
"mtusi2026lab4/internal/transport/http/dto"
"mtusi2026lab4/internal/transport/http/middleware"
"mtusi2026lab4/internal/transport/http/response"
"github.com/google/uuid"
)
func (h *Handler) UploadAttachment(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
currentUser := middleware.GetCurrentUser(r.Context())
parsedChatID, err := uuid.Parse(r.PathValue("chat_id"))
if err != nil {
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
"invalid chat_id uuid", requestID)
return
}
filename := r.URL.Query().Get("filename")
if filename == "" {
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
"filename query parameter is required", requestID)
return
}
contentType, parameters, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || len(parameters) != 0 ||
(contentType != "image/png" && contentType != "image/jpeg") {
response.WriteError(w, http.StatusUnsupportedMediaType,
response.CodeUnsupportedMediaType,
"Content-Type must be image/png or image/jpeg", requestID)
return
}
if r.ContentLength > domain.MaxAttachmentSizeBytes {
response.WriteError(w, http.StatusRequestEntityTooLarge,
response.CodePayloadTooLarge,
"attachment exceeds 10 MiB", requestID)
return
}
if r.Body == nil {
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
"attachment body is required", requestID)
return
}
defer r.Body.Close()
attachment, err := h.service.UploadAttachment(
r.Context(),
application.UploadAttachmentCommand{
ActorID: currentUser.ID,
ChatID: parsedChatID.String(),
Filename: filename,
DeclaredContentType: contentType,
Body: r.Body,
},
)
switch {
case errors.Is(err, application.ErrPayloadTooLarge):
response.WriteError(w, http.StatusRequestEntityTooLarge,
response.CodePayloadTooLarge,
"attachment exceeds 10 MiB or 40 million pixels", requestID)
return
case errors.Is(err, application.ErrUnsupportedMediaType), errors.Is(err, application.ErrInvalidImage):
response.WriteError(w, http.StatusUnsupportedMediaType,
response.CodeUnsupportedMediaType,
"body is not a valid PNG/JPEG matching the declared Content-Type", requestID)
return
case errors.Is(err, application.ErrInvalidInput):
message := strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": ")
response.WriteError(w, http.StatusBadRequest,
response.CodeInvalidRequest, message, requestID)
return
case errors.Is(err, domain.ErrNotFound):
response.WriteError(w, http.StatusNotFound,
response.CodeNotFound, "chat not found", requestID)
return
case errors.Is(err, application.ErrStorageUnavailable):
response.WriteError(w, http.StatusServiceUnavailable,
response.CodeUnavailable, "object storage is temporarily unavailable", requestID)
return
case err != nil:
response.WriteError(w, http.StatusServiceUnavailable,
response.CodeUnavailable, "service is temporarily unavailable", requestID)
return
}
response.WriteJSON(w, http.StatusCreated, dto.AttachmentFromDomain(attachment), requestID)
}