diff --git a/db/migrations/00003_attachments.sql b/db/migrations/00003_attachments.sql new file mode 100644 index 0000000..e777337 --- /dev/null +++ b/db/migrations/00003_attachments.sql @@ -0,0 +1,32 @@ +-- +goose Up +CREATE TABLE attachments ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + owner_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT, + s3_key text NOT NULL UNIQUE, + filename text NOT NULL, + content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')), + size_bytes bigint NOT NULL CHECK (size_bytes > 0 AND size_bytes <= 10485760), + sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'), + status text NOT NULL DEFAULT 'ready' CHECK (status = 'ready'), + error_code text, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); + +CREATE INDEX idx_attachments_chat_id ON attachments (chat_id, created_at); +CREATE INDEX idx_attachments_owner_id ON attachments (owner_id); + +CREATE TABLE message_attachments ( + message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE, + attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE RESTRICT, + position int NOT NULL CHECK (position >= 0 AND position < 10), + PRIMARY KEY (message_id, attachment_id), + UNIQUE (message_id, position) +); + +CREATE INDEX idx_message_attachments_attachment_id ON message_attachments (attachment_id); + +-- +goose Down +DROP TABLE message_attachments; +DROP TABLE attachments; diff --git a/db/queries/attachments.sql b/db/queries/attachments.sql new file mode 100644 index 0000000..5b9495b --- /dev/null +++ b/db/queries/attachments.sql @@ -0,0 +1,59 @@ +-- name: CreateAttachment :one +INSERT INTO attachments ( + id, + chat_id, + owner_id, + s3_key, + filename, + content_type, + size_bytes, + sha256, + status, + error_code +) +SELECT + sqlc.arg(id)::uuid, + sqlc.arg(chat_id)::uuid, + sqlc.arg(owner_id)::uuid, + sqlc.arg(s3_key)::text, + sqlc.arg(filename)::text, + sqlc.arg(content_type)::text, + sqlc.arg(size_bytes)::bigint, + sqlc.arg(sha256)::text, + sqlc.arg(status)::text, + sqlc.arg(error_code)::text +WHERE EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = sqlc.arg(chat_id) + AND user_id = sqlc.arg(owner_id) +) +RETURNING *; + +-- name: CreateMessageAttachment :exec +INSERT INTO message_attachments ( + message_id, + attachment_id, + position +) VALUES ( + sqlc.arg(message_id), + sqlc.arg(attachment_id), + sqlc.arg(position) +); + +-- name: ListAttachmentsByIDs :many +SELECT status +FROM attachments +WHERE chat_id = sqlc.arg(chat_id)::uuid + AND id = ANY(sqlc.arg(ids)::uuid[]); + +-- name: ListMessageAttachmentIDs :many +SELECT attachment_id +FROM message_attachments +WHERE message_id = sqlc.arg(message_id)::uuid +ORDER BY position; + +-- name: ListMessageAttachmentsByMessageIDs :many +SELECT message_id, attachment_id +FROM message_attachments +WHERE message_id = ANY(sqlc.arg(message_ids)::uuid[]) +ORDER BY message_id, position; diff --git a/internal/db/attachments.sql.go b/internal/db/attachments.sql.go new file mode 100644 index 0000000..85ebc97 --- /dev/null +++ b/internal/db/attachments.sql.go @@ -0,0 +1,202 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: attachments.sql + +package db + +import ( + "context" + + "github.com/google/uuid" +) + +const createAttachment = `-- name: CreateAttachment :one +INSERT INTO attachments ( + id, + chat_id, + owner_id, + s3_key, + filename, + content_type, + size_bytes, + sha256, + status, + error_code +) +SELECT + $1::uuid, + $2::uuid, + $3::uuid, + $4::text, + $5::text, + $6::text, + $7::bigint, + $8::text, + $9::text, + $10::text +WHERE EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = $2 + AND user_id = $3 +) +RETURNING id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at +` + +type CreateAttachmentParams struct { + ID uuid.UUID + ChatID uuid.UUID + OwnerID uuid.UUID + S3Key string + Filename string + ContentType string + SizeBytes int64 + Sha256 string + Status string + ErrorCode string +} + +func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentParams) (Attachment, error) { + row := q.db.QueryRow(ctx, createAttachment, + arg.ID, + arg.ChatID, + arg.OwnerID, + arg.S3Key, + arg.Filename, + arg.ContentType, + arg.SizeBytes, + arg.Sha256, + arg.Status, + arg.ErrorCode, + ) + var i Attachment + err := row.Scan( + &i.ID, + &i.ChatID, + &i.OwnerID, + &i.S3Key, + &i.Filename, + &i.ContentType, + &i.SizeBytes, + &i.Sha256, + &i.Status, + &i.ErrorCode, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const createMessageAttachment = `-- name: CreateMessageAttachment :exec +INSERT INTO message_attachments ( + message_id, + attachment_id, + position +) VALUES ( + $1, + $2, + $3 +) +` + +type CreateMessageAttachmentParams struct { + MessageID uuid.UUID + AttachmentID uuid.UUID + Position int32 +} + +func (q *Queries) CreateMessageAttachment(ctx context.Context, arg CreateMessageAttachmentParams) error { + _, err := q.db.Exec(ctx, createMessageAttachment, arg.MessageID, arg.AttachmentID, arg.Position) + return err +} + +const listAttachmentsByIDs = `-- name: ListAttachmentsByIDs :many +SELECT status +FROM attachments +WHERE chat_id = $1::uuid + AND id = ANY($2::uuid[]) +` + +type ListAttachmentsByIDsParams struct { + ChatID uuid.UUID + Ids []uuid.UUID +} + +func (q *Queries) ListAttachmentsByIDs(ctx context.Context, arg ListAttachmentsByIDsParams) ([]string, error) { + rows, err := q.db.Query(ctx, listAttachmentsByIDs, arg.ChatID, arg.Ids) + if err != nil { + return nil, err + } + defer rows.Close() + items := []string{} + for rows.Next() { + var status string + if err := rows.Scan(&status); err != nil { + return nil, err + } + items = append(items, status) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listMessageAttachmentIDs = `-- name: ListMessageAttachmentIDs :many +SELECT attachment_id +FROM message_attachments +WHERE message_id = $1::uuid +ORDER BY position +` + +func (q *Queries) ListMessageAttachmentIDs(ctx context.Context, messageID uuid.UUID) ([]uuid.UUID, error) { + rows, err := q.db.Query(ctx, listMessageAttachmentIDs, messageID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []uuid.UUID{} + for rows.Next() { + var attachment_id uuid.UUID + if err := rows.Scan(&attachment_id); err != nil { + return nil, err + } + items = append(items, attachment_id) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listMessageAttachmentsByMessageIDs = `-- name: ListMessageAttachmentsByMessageIDs :many +SELECT message_id, attachment_id +FROM message_attachments +WHERE message_id = ANY($1::uuid[]) +ORDER BY message_id, position +` + +type ListMessageAttachmentsByMessageIDsRow struct { + MessageID uuid.UUID + AttachmentID uuid.UUID +} + +func (q *Queries) ListMessageAttachmentsByMessageIDs(ctx context.Context, messageIds []uuid.UUID) ([]ListMessageAttachmentsByMessageIDsRow, error) { + rows, err := q.db.Query(ctx, listMessageAttachmentsByMessageIDs, messageIds) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListMessageAttachmentsByMessageIDsRow{} + for rows.Next() { + var i ListMessageAttachmentsByMessageIDsRow + if err := rows.Scan(&i.MessageID, &i.AttachmentID); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/db/models.go b/internal/db/models.go index caaeefd..c02477d 100644 --- a/internal/db/models.go +++ b/internal/db/models.go @@ -10,6 +10,21 @@ import ( "github.com/google/uuid" ) +type Attachment struct { + ID uuid.UUID + ChatID uuid.UUID + OwnerID uuid.UUID + S3Key string + Filename string + ContentType string + SizeBytes int64 + Sha256 string + Status string + ErrorCode *string + CreatedAt time.Time + UpdatedAt time.Time +} + type Chat struct { ID uuid.UUID Title string @@ -39,6 +54,12 @@ type Message struct { CreatedAt time.Time } +type MessageAttachment struct { + MessageID uuid.UUID + AttachmentID uuid.UUID + Position int32 +} + type Session struct { TokenHash string UserID uuid.UUID diff --git a/internal/dto/message.go b/internal/dto/message.go index 32658c5..00902c7 100644 --- a/internal/dto/message.go +++ b/internal/dto/message.go @@ -10,15 +10,17 @@ import ( ) type CreateMessageRequest struct { - Text string `json:"text"` + Text string `json:"text"` + AttachmentIDs []string `json:"attachment_ids"` } type MessageResponse struct { - ID uuid.UUID `json:"id"` - ChatID uuid.UUID `json:"chat_id"` - SenderID uuid.UUID `json:"sender_id"` - Text string `json:"text"` - CreatedAt time.Time `json:"created_at"` + ID uuid.UUID `json:"id"` + ChatID uuid.UUID `json:"chat_id"` + SenderID uuid.UUID `json:"sender_id"` + Text string `json:"text"` + AttachmentIDs []uuid.UUID `json:"attachment_ids"` + CreatedAt time.Time `json:"created_at"` } type MessagePageResponse struct { @@ -27,21 +29,36 @@ type MessagePageResponse struct { } func (r CreateMessageRequest) Validate() bool { - if strings.TrimSpace(r.Text) == "" || - strings.ContainsRune(r.Text, 0) || - utf8.RuneCountInString(r.Text) > 4000 { + if strings.ContainsRune(r.Text, 0) || utf8.RuneCountInString(r.Text) > 4000 { + return false + } + if len(r.AttachmentIDs) > 10 { return false } - return true + seen := make(map[string]struct{}, len(r.AttachmentIDs)) + for _, id := range r.AttachmentIDs { + if _, ok := seen[id]; ok { + return false + } + seen[id] = struct{}{} + } + + hasText := strings.TrimSpace(r.Text) != "" + hasAttachment := len(r.AttachmentIDs) > 0 + + return hasText || hasAttachment } func ToMessageResponse(m model.Message) MessageResponse { + ids := make([]uuid.UUID, len(m.AttachmentIDs)) + copy(ids, m.AttachmentIDs) return MessageResponse{ - ID: m.ID, - ChatID: m.ChatID, - SenderID: m.SenderID, - Text: m.Text, - CreatedAt: m.CreatedAt, + ID: m.ID, + ChatID: m.ChatID, + SenderID: m.SenderID, + Text: m.Text, + AttachmentIDs: ids, + CreatedAt: m.CreatedAt, } } diff --git a/internal/handler/message.go b/internal/handler/message.go index c71366a..bd926ba 100644 --- a/internal/handler/message.go +++ b/internal/handler/message.go @@ -68,7 +68,23 @@ func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) { return } - message, err := h.service.Create(r.Context(), userID, chatID, key, req.Text) + attachmentIDs := make([]uuid.UUID, 0, len(req.AttachmentIDs)) + for _, s := range req.AttachmentIDs { + id, err := uuid.Parse(s) + if err != nil { + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid attachment_id", + requestID, + ) + return + } + attachmentIDs = append(attachmentIDs, id) + } + + message, err := h.service.Create(r.Context(), userID, chatID, key, req.Text, attachmentIDs) switch { case errors.Is(err, service.ErrMessageChatNotFound): httpx.WriteError( @@ -79,6 +95,24 @@ func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) { requestID, ) return + case errors.Is(err, service.ErrAttachmentNotFound): + httpx.WriteError( + w, + http.StatusNotFound, + dto.ErrorCodeNotFound, + "attachment not found", + requestID, + ) + return + case errors.Is(err, service.ErrAttachmentNotReady): + httpx.WriteError( + w, + http.StatusConflict, + dto.ErrorCodeConflict, + "attachment not ready", + requestID, + ) + return case errors.Is(err, service.ErrIdempotencyKeyConflict): httpx.WriteError( w, diff --git a/internal/model/message.go b/internal/model/message.go index 5c2cf5f..8db0c61 100644 --- a/internal/model/message.go +++ b/internal/model/message.go @@ -7,9 +7,10 @@ import ( ) type Message struct { - ID uuid.UUID - ChatID uuid.UUID - SenderID uuid.UUID - Text string - CreatedAt time.Time + ID uuid.UUID + ChatID uuid.UUID + SenderID uuid.UUID + Text string + AttachmentIDs []uuid.UUID + CreatedAt time.Time } diff --git a/internal/service/message.go b/internal/service/message.go index ae0c471..7a723e8 100644 --- a/internal/service/message.go +++ b/internal/service/message.go @@ -6,6 +6,8 @@ import ( "encoding/hex" "errors" "net/http" + "sort" + "strings" "github.com/google/uuid" "github.com/jackc/pgx/v5" @@ -18,14 +20,20 @@ import ( var ( ErrMessageChatNotFound = errors.New("chat not found") + ErrAttachmentNotFound = errors.New("attachment not found") + ErrAttachmentNotReady = errors.New("attachment not ready") ErrIdempotencyKeyConflict = errors.New("idempotency key reused with different request") ) type messageQueries interface { CreateIdempotencyKey(ctx context.Context, arg db.CreateIdempotencyKeyParams) (int64, error) CreateMessage(ctx context.Context, arg db.CreateMessageParams) (db.Message, error) + CreateMessageAttachment(ctx context.Context, arg db.CreateMessageAttachmentParams) error GetIdempotentMessage(ctx context.Context, arg db.GetIdempotentMessageParams) (db.GetIdempotentMessageRow, error) IsChatMember(ctx context.Context, arg db.IsChatMemberParams) (bool, error) + ListAttachmentsByIDs(ctx context.Context, arg db.ListAttachmentsByIDsParams) ([]string, error) + ListMessageAttachmentIDs(ctx context.Context, messageID uuid.UUID) ([]uuid.UUID, error) + ListMessageAttachmentsByMessageIDs(ctx context.Context, messageIDs []uuid.UUID) ([]db.ListMessageAttachmentsByMessageIDsRow, error) ListMessagesAfter(ctx context.Context, arg db.ListMessagesAfterParams) ([]db.Message, error) ListMessagesFirstPage(ctx context.Context, arg db.ListMessagesFirstPageParams) ([]db.Message, error) } @@ -52,13 +60,33 @@ func (s *MessageService) Create( chatID uuid.UUID, key string, text string, + attachmentIDs []uuid.UUID, ) (model.Message, error) { id, err := uuid.NewV7() if err != nil { return model.Message{}, err } - sum := sha256.Sum256([]byte(text)) + if len(attachmentIDs) > 0 { + statuses, err := s.q.ListAttachmentsByIDs(ctx, db.ListAttachmentsByIDsParams{ + ChatID: chatID, + Ids: attachmentIDs, + }) + if err != nil { + return model.Message{}, err + } + if len(statuses) != len(attachmentIDs) { + return model.Message{}, ErrAttachmentNotFound + } + for _, status := range statuses { + if status != "ready" { + return model.Message{}, ErrAttachmentNotReady + } + } + } + + hashInput := text + "|" + normalizeAttachmentIDs(attachmentIDs) + sum := sha256.Sum256([]byte(hashInput)) hash := hex.EncodeToString(sum[:]) path := "/api/v1/chats/" + chatID.String() + "/messages" @@ -107,12 +135,18 @@ func (s *MessageService) Create( return model.Message{}, ErrIdempotencyKeyConflict } + storedAttachmentIDs, err := q.ListMessageAttachmentIDs(ctx, stored.ID) + if err != nil { + return model.Message{}, err + } + return model.Message{ - ID: stored.ID, - ChatID: stored.ChatID, - SenderID: stored.SenderID, - Text: stored.Text, - CreatedAt: stored.CreatedAt, + ID: stored.ID, + ChatID: stored.ChatID, + SenderID: stored.SenderID, + Text: stored.Text, + AttachmentIDs: storedAttachmentIDs, + CreatedAt: stored.CreatedAt, }, nil } @@ -129,16 +163,27 @@ func (s *MessageService) Create( return model.Message{}, err } + for i, attachmentID := range attachmentIDs { + if err := q.CreateMessageAttachment(ctx, db.CreateMessageAttachmentParams{ + MessageID: id, + AttachmentID: attachmentID, + Position: int32(i), + }); err != nil { + return model.Message{}, err + } + } + if err := tx.Commit(ctx); err != nil { return model.Message{}, err } return model.Message{ - ID: row.ID, - ChatID: row.ChatID, - SenderID: row.SenderID, - Text: row.Text, - CreatedAt: row.CreatedAt, + ID: row.ID, + ChatID: row.ChatID, + SenderID: row.SenderID, + Text: row.Text, + AttachmentIDs: attachmentIDs, + CreatedAt: row.CreatedAt, }, nil } @@ -189,14 +234,31 @@ func (s *MessageService) List( rows = rows[:limit] } + attachmentsByMessage := make(map[uuid.UUID][]uuid.UUID, len(rows)) + if len(rows) > 0 { + messageIDs := make([]uuid.UUID, len(rows)) + for i, r := range rows { + messageIDs[i] = r.ID + } + + links, err := s.q.ListMessageAttachmentsByMessageIDs(ctx, messageIDs) + if err != nil { + return nil, nil, err + } + for _, l := range links { + attachmentsByMessage[l.MessageID] = append(attachmentsByMessage[l.MessageID], l.AttachmentID) + } + } + messages := make([]model.Message, 0, len(rows)) for _, r := range rows { messages = append(messages, model.Message{ - ID: r.ID, - ChatID: r.ChatID, - SenderID: r.SenderID, - Text: r.Text, - CreatedAt: r.CreatedAt, + ID: r.ID, + ChatID: r.ChatID, + SenderID: r.SenderID, + Text: r.Text, + AttachmentIDs: attachmentsByMessage[r.ID], + CreatedAt: r.CreatedAt, }) } @@ -213,3 +275,17 @@ func (s *MessageService) List( return messages, next, nil } + +func normalizeAttachmentIDs(ids []uuid.UUID) string { + if len(ids) == 0 { + return "" + } + + parts := make([]string, len(ids)) + for i, id := range ids { + parts[i] = id.String() + } + sort.Strings(parts) + + return strings.Join(parts, ",") +}