feat(messages): make message creation idempotent

This commit is contained in:
kk10
2026-10-17 11:27:34 +03:00
parent 5bab6a83d5
commit dc5e288483
3 changed files with 101 additions and 7 deletions
+25 -1
View File
@@ -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