forked from mtusi2026/mtusi2026lab5
290 lines
6.8 KiB
Go
290 lines
6.8 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"net/http"
|
|
"sort"
|
|
"strings"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"mtusi2026-messenger/internal/db"
|
|
"mtusi2026-messenger/internal/model"
|
|
"mtusi2026-messenger/internal/postgres"
|
|
)
|
|
|
|
var (
|
|
ErrMessageChatNotFound = errors.New("chat not found")
|
|
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) ([]db.AttachmentStatus, 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)
|
|
}
|
|
|
|
type MessageService struct {
|
|
pool txBeginner
|
|
q *db.Queries
|
|
withTx func(pgx.Tx) messageQueries
|
|
}
|
|
|
|
func NewMessageService(pool *pgxpool.Pool, q *db.Queries) *MessageService {
|
|
return &MessageService{
|
|
pool: pool,
|
|
q: q,
|
|
withTx: func(tx pgx.Tx) messageQueries {
|
|
return q.WithTx(tx)
|
|
},
|
|
}
|
|
}
|
|
|
|
func (s *MessageService) Create(
|
|
ctx context.Context,
|
|
userID uuid.UUID,
|
|
chatID uuid.UUID,
|
|
key string,
|
|
text string,
|
|
attachmentIDs []uuid.UUID,
|
|
) (model.Message, error) {
|
|
id, err := uuid.NewV7()
|
|
if err != nil {
|
|
return model.Message{}, err
|
|
}
|
|
|
|
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 != db.AttachmentStatusReady {
|
|
return model.Message{}, ErrAttachmentNotReady
|
|
}
|
|
}
|
|
}
|
|
|
|
hashInput := text + "|" + normalizeAttachmentIDs(attachmentIDs)
|
|
sum := sha256.Sum256([]byte(hashInput))
|
|
hash := hex.EncodeToString(sum[:])
|
|
path := "/api/v1/chats/" + chatID.String() + "/messages"
|
|
|
|
tx, err := s.pool.Begin(ctx)
|
|
if err != nil {
|
|
return model.Message{}, err
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
|
|
q := s.withTx(tx)
|
|
|
|
inserted, err := q.CreateIdempotencyKey(ctx, db.CreateIdempotencyKeyParams{
|
|
UserID: userID,
|
|
Method: http.MethodPost,
|
|
Path: path,
|
|
Key: key,
|
|
RequestHash: hash,
|
|
MessageID: id,
|
|
})
|
|
if err != nil {
|
|
return model.Message{}, err
|
|
}
|
|
|
|
if inserted == 0 {
|
|
isMember, err := q.IsChatMember(ctx, db.IsChatMemberParams{
|
|
ChatID: chatID,
|
|
UserID: userID,
|
|
})
|
|
if err != nil {
|
|
return model.Message{}, err
|
|
}
|
|
if !isMember {
|
|
return model.Message{}, ErrMessageChatNotFound
|
|
}
|
|
|
|
stored, err := q.GetIdempotentMessage(ctx, db.GetIdempotentMessageParams{
|
|
UserID: userID,
|
|
Method: http.MethodPost,
|
|
Path: path,
|
|
Key: key,
|
|
})
|
|
if err != nil {
|
|
return model.Message{}, err
|
|
}
|
|
if stored.RequestHash != hash {
|
|
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,
|
|
AttachmentIDs: storedAttachmentIDs,
|
|
CreatedAt: stored.CreatedAt,
|
|
}, nil
|
|
}
|
|
|
|
row, err := q.CreateMessage(ctx, db.CreateMessageParams{
|
|
ID: id,
|
|
ChatID: chatID,
|
|
SenderID: userID,
|
|
Text: text,
|
|
})
|
|
if postgres.IsNotFound(err) {
|
|
return model.Message{}, ErrMessageChatNotFound
|
|
}
|
|
if err != nil {
|
|
return model.Message{}, err
|
|
}
|
|
|
|
for i, attachmentID := range attachmentIDs {
|
|
if err := q.CreateMessageAttachment(ctx, db.CreateMessageAttachmentParams{
|
|
MessageID: id,
|
|
AttachmentID: attachmentID,
|
|
Position: 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,
|
|
AttachmentIDs: attachmentIDs,
|
|
CreatedAt: row.CreatedAt,
|
|
}, nil
|
|
}
|
|
|
|
func (s *MessageService) List(
|
|
ctx context.Context,
|
|
userID uuid.UUID,
|
|
chatID uuid.UUID,
|
|
limit int,
|
|
cursor *string,
|
|
) ([]model.Message, *string, error) {
|
|
isMember, err := s.q.IsChatMember(ctx, db.IsChatMemberParams{
|
|
ChatID: chatID,
|
|
UserID: userID,
|
|
})
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
if !isMember {
|
|
return nil, nil, ErrMessageChatNotFound
|
|
}
|
|
|
|
var rows []db.Message
|
|
|
|
if cursor == nil {
|
|
rows, err = s.q.ListMessagesFirstPage(ctx, db.ListMessagesFirstPageParams{
|
|
ChatID: chatID,
|
|
Lim: limit + 1,
|
|
})
|
|
} else {
|
|
decoded, derr := decodeCursor(*cursor, chatID)
|
|
if derr != nil {
|
|
return nil, nil, ErrInvalidCursor
|
|
}
|
|
|
|
rows, err = s.q.ListMessagesAfter(ctx, db.ListMessagesAfterParams{
|
|
ChatID: chatID,
|
|
AfterCreatedAt: decoded.CreatedAt,
|
|
AfterID: decoded.ID,
|
|
Lim: limit + 1,
|
|
})
|
|
}
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
hasMore := len(rows) > limit
|
|
if hasMore {
|
|
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,
|
|
AttachmentIDs: attachmentsByMessage[r.ID],
|
|
CreatedAt: r.CreatedAt,
|
|
})
|
|
}
|
|
|
|
var next *string
|
|
if hasMore {
|
|
last := messages[len(messages)-1]
|
|
c := encodeCursor(Cursor{
|
|
ChatID: chatID,
|
|
CreatedAt: last.CreatedAt,
|
|
ID: last.ID,
|
|
})
|
|
next = &c
|
|
}
|
|
|
|
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, ",")
|
|
}
|