forked from mtusi2026/mtusi2026lab3
feat: add shared idempotency and replica identity
This commit is contained in:
@@ -9,8 +9,8 @@ import (
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/postgres"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab3/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab3/internal/postgres"
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
@@ -202,6 +202,10 @@ func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method == http.MethodGet {
|
||||
return s.listMessages(w, r, user, chatID)
|
||||
}
|
||||
key, valid := idempotencyKey(r)
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
var input struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
@@ -211,13 +215,21 @@ func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if !validText(input.Text, 4000) {
|
||||
return invalidRequest()
|
||||
}
|
||||
message, err := s.messengerStore.CreateMessage(r.Context(), chatID, user.ID, input.Text)
|
||||
message, replay, err := s.messengerStore.CreateMessage(
|
||||
r.Context(), chatID, user.ID, input.Text, key, s.idempotencyTTL,
|
||||
)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
if errors.Is(err, postgres.ErrIdempotencyConflict) {
|
||||
return &apiError{http.StatusConflict, errorCodeConflict, "idempotency key conflicts with previous request"}
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if replay {
|
||||
s.metrics.replays.Inc()
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, message)
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user