feat(messages): make message creation idempotent
This commit is contained in:
+1
-1
@@ -76,7 +76,7 @@ func Run() error {
|
||||
authService := service.NewAuthService(queries, rdb, cfg.Server.SessionTTL, log)
|
||||
userService := service.NewUserService(queries)
|
||||
chatService := service.NewChatService(pool, queries)
|
||||
messageService := service.NewMessageService(queries)
|
||||
messageService := service.NewMessageService(pool, queries)
|
||||
|
||||
router := NewRouter(
|
||||
log,
|
||||
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/google/uuid"
|
||||
@@ -13,6 +14,8 @@ import (
|
||||
"mtusi2026-messenger/internal/service"
|
||||
)
|
||||
|
||||
var idempotencyKeyReq = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
type MessageHandler struct {
|
||||
service *service.MessageService
|
||||
}
|
||||
@@ -37,6 +40,18 @@ func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
if !idempotencyKeyReq.MatchString(key) {
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
dto.ErrorCodeInvalidRequest,
|
||||
"invalid Idempotency-Key",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.CreateMessageRequest
|
||||
if !httpx.DecodeJSONBody(w, r, requestID, &req) {
|
||||
return
|
||||
@@ -53,7 +68,7 @@ func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
message, err := h.service.Create(r.Context(), userID, chatID, req.Text)
|
||||
message, err := h.service.Create(r.Context(), userID, chatID, key, req.Text)
|
||||
switch {
|
||||
case errors.Is(err, service.ErrMessageChatNotFound):
|
||||
httpx.WriteError(
|
||||
@@ -64,6 +79,15 @@ func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
case errors.Is(err, service.ErrIdempotencyKeyConflict):
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusConflict,
|
||||
dto.ErrorCodeConflict,
|
||||
"idempotency key reused with different request",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
case err != nil:
|
||||
httpx.WriteInternalError(w, requestID, err)
|
||||
return
|
||||
|
||||
@@ -2,36 +2,55 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"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")
|
||||
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)
|
||||
GetIdempotentMessage(ctx context.Context, arg db.GetIdempotentMessageParams) (db.GetIdempotentMessageRow, error)
|
||||
IsChatMember(ctx context.Context, arg db.IsChatMemberParams) (bool, error)
|
||||
ListMessagesAfter(ctx context.Context, arg db.ListMessagesAfterParams) ([]db.Message, error)
|
||||
ListMessagesFirstPage(ctx context.Context, arg db.ListMessagesFirstPageParams) ([]db.Message, error)
|
||||
}
|
||||
|
||||
type MessageService struct {
|
||||
q messageQueries
|
||||
pool txBeginner
|
||||
q *db.Queries
|
||||
withTx func(pgx.Tx) messageQueries
|
||||
}
|
||||
|
||||
func NewMessageService(q *db.Queries) *MessageService {
|
||||
return &MessageService{q: q}
|
||||
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,
|
||||
) (model.Message, error) {
|
||||
id, err := uuid.NewV7()
|
||||
@@ -39,7 +58,54 @@ func (s *MessageService) Create(
|
||||
return model.Message{}, err
|
||||
}
|
||||
|
||||
row, err := s.q.CreateMessage(ctx, db.CreateMessageParams{
|
||||
sum := sha256.Sum256([]byte(text))
|
||||
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 {
|
||||
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
|
||||
}
|
||||
|
||||
return model.Message{
|
||||
ID: stored.ID,
|
||||
ChatID: stored.ChatID,
|
||||
SenderID: stored.SenderID,
|
||||
Text: stored.Text,
|
||||
CreatedAt: stored.CreatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
row, err := q.CreateMessage(ctx, db.CreateMessageParams{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
SenderID: userID,
|
||||
@@ -52,6 +118,10 @@ func (s *MessageService) Create(
|
||||
return model.Message{}, err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
|
||||
return model.Message{
|
||||
ID: row.ID,
|
||||
ChatID: row.ChatID,
|
||||
|
||||
Reference in New Issue
Block a user