Сделать отправку сообщения идемпотентной по Idempotency-Key с общей таблицей ключей и их чисткой

This commit is contained in:
2026-11-02 17:11:04 +03:00
parent 7fa8881eb3
commit 951fd0d517
19 changed files with 856 additions and 40 deletions
+21 -1
View File
@@ -2,6 +2,7 @@ package chat
import (
"net/http"
"regexp"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
@@ -133,12 +134,17 @@ func (h *Handler) send(c *gin.Context, actor uuid.UUID) {
httpx.Error(c, err)
return
}
key, err := idempotencyKey(c)
if err != nil {
httpx.Error(c, err)
return
}
var req createMessageRequest
if err := httpx.DecodeJSON(c, &req); err != nil {
httpx.Error(c, err)
return
}
message, err := h.chats.Send(c.Request.Context(), actor, chatID, req.Text)
message, err := h.chats.Send(c.Request.Context(), actor, chatID, key, req.Text)
if err != nil {
httpx.Error(c, err)
return
@@ -165,6 +171,20 @@ func (h *Handler) history(c *gin.Context, actor uuid.UUID) {
httpx.JSON(c, http.StatusOK, pagination.ToResponse(page, chatID, toMessageResponse))
}
var keyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
// idempotencyKey reads the Idempotency-Key that names one send attempt. It
// is part of this endpoint's input contract, so it is checked here, with
// the path and the body, and before access: the answer to a malformed key
// is the same for any chat. Two headers are ambiguous and rejected.
func idempotencyKey(c *gin.Context) (string, error) {
values := c.Request.Header.Values("Idempotency-Key")
if len(values) != 1 || !keyPattern.MatchString(values[0]) {
return "", apperr.Invalid("Idempotency-Key header is required: one value of 1-128 characters A-Z a-z 0-9 . _ : -")
}
return values[0], nil
}
func chatParam(c *gin.Context) (uuid.UUID, error) {
id, err := ident.Parse(c.Param("chat_id"))
if err != nil {