feat: add shared idempotency and replica identity

This commit is contained in:
2026-10-02 15:59:16 +03:00
parent 32d21ec135
commit da1ab2d216
18 changed files with 630 additions and 90 deletions
+3 -3
View File
@@ -6,9 +6,9 @@ import (
"net/http"
"strings"
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/postgres"
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/session"
"gitea.privcloud.tech/dizi/mtusi2026lab3/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab3/internal/postgres"
"gitea.privcloud.tech/dizi/mtusi2026lab3/internal/session"
)
func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError {
+15 -3
View File
@@ -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
}
+2 -2
View File
@@ -4,7 +4,7 @@ import (
"context"
"time"
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab3/internal/model"
)
type MessengerStore interface {
@@ -15,7 +15,7 @@ type MessengerStore interface {
CreateChat(context.Context, string, []string, string) (model.Chat, error)
ChatForUser(context.Context, string, string) (model.Chat, error)
ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error)
CreateMessage(context.Context, string, string, string) (model.Message, error)
CreateMessage(context.Context, string, string, string, string, time.Duration) (model.Message, bool, error)
ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error)
}
+8
View File
@@ -15,6 +15,7 @@ type metrics struct {
requests *prometheus.CounterVec
duration *prometheus.HistogramVec
inFlight prometheus.Gauge
replays prometheus.Counter
handler http.Handler
}
@@ -40,11 +41,18 @@ func newMetrics() *metrics {
Name: "requests_in_flight",
Help: "HTTP requests currently being served.",
}),
replays: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "messenger",
Subsystem: "http",
Name: "idempotency_replays_total",
Help: "Message requests served from an idempotency record.",
}),
}
registry.MustRegister(
result.requests,
result.duration,
result.inFlight,
result.replays,
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
)
+1 -1
View File
@@ -1,7 +1,7 @@
package messenger
import (
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab3/internal/model"
"github.com/google/uuid"
)
+11
View File
@@ -9,6 +9,7 @@ import (
"mime"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
@@ -17,6 +18,8 @@ import (
const maxRequestBytes = 1 << 20
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
func readJSON(w http.ResponseWriter, r *http.Request, target any) *apiError {
mediaType, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mediaType != "application/json" || (params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
@@ -54,6 +57,14 @@ func validText(value string, maxRunes int) bool {
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= maxRunes
}
func idempotencyKey(r *http.Request) (string, bool) {
values := r.Header.Values("Idempotency-Key")
if len(values) != 1 || !idempotencyKeyPattern.MatchString(values[0]) {
return "", false
}
return values[0], true
}
type pageCursor struct {
Kind string `json:"kind"`
Resource string `json:"resource"`
+19 -5
View File
@@ -13,7 +13,9 @@ type Server struct {
sessions SessionStore
passwords PasswordService
sessionTTL time.Duration
idempotencyTTL time.Duration
requestTTL time.Duration
instanceID string
logger *slog.Logger
swaggerPort string
metrics *metrics
@@ -30,10 +32,21 @@ func (w *statusWriter) WriteHeader(status int) {
w.ResponseWriter.WriteHeader(status)
}
func NewServer(logger *slog.Logger, messages MessengerStore, sessions SessionStore, passwords PasswordService, sessionTTL, requestTTL time.Duration, swaggerPort string) *Server {
func NewServer(
logger *slog.Logger,
messages MessengerStore,
sessions SessionStore,
passwords PasswordService,
sessionTTL time.Duration,
idempotencyTTL time.Duration,
requestTTL time.Duration,
instanceID string,
swaggerPort string,
) *Server {
s := &Server{
messengerStore: messages, sessions: sessions, passwords: passwords,
sessionTTL: sessionTTL, requestTTL: requestTTL, logger: logger, swaggerPort: swaggerPort, metrics: newMetrics(),
sessionTTL: sessionTTL, idempotencyTTL: idempotencyTTL, requestTTL: requestTTL,
instanceID: instanceID, logger: logger, swaggerPort: swaggerPort, metrics: newMetrics(),
}
s.ready.Store(true)
return s
@@ -48,6 +61,7 @@ func (s *Server) Handler() http.Handler {
}
func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Instance-Id", s.instanceID)
requestID, err := newID()
if err != nil {
http.Error(w, "server unavailable", http.StatusServiceUnavailable)
@@ -70,8 +84,8 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
s.logger.Info("request", "request_id", requestID, "method", r.Method, "path", r.URL.Path, "status", wrapped.status, "duration_ms", time.Since(started).Milliseconds())
}()
if s.allowSwaggerOrigin(wrapped, r) && r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
wrapped.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
wrapped.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
wrapped.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
wrapped.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, Idempotency-Key")
wrapped.WriteHeader(http.StatusNoContent)
return
}
@@ -92,7 +106,7 @@ func (s *Server) allowSwaggerOrigin(w http.ResponseWriter, r *http.Request) bool
return false
}
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Expose-Headers", "X-Request-Id")
w.Header().Set("Access-Control-Expose-Headers", "X-Request-Id, X-Instance-Id")
w.Header().Add("Vary", "Origin")
return true
}
+66 -4
View File
@@ -3,6 +3,7 @@ package messenger
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
@@ -11,7 +12,8 @@ import (
"testing"
"time"
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab3/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab3/internal/postgres"
)
var errDependency = errors.New("dependency unavailable")
@@ -22,6 +24,9 @@ type messengerStoreStub struct {
userByIDErr error
credentials model.UserCredentials
credentialsErr error
message model.Message
messageReplay bool
messageErr error
}
func (s messengerStoreStub) Ping(context.Context) error { return s.pingErr }
@@ -43,8 +48,8 @@ func (messengerStoreStub) ChatForUser(context.Context, string, string) (model.Ch
func (messengerStoreStub) ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error) {
return nil, false, nil
}
func (messengerStoreStub) CreateMessage(context.Context, string, string, string) (model.Message, error) {
return model.Message{}, nil
func (s messengerStoreStub) CreateMessage(context.Context, string, string, string, string, time.Duration) (model.Message, bool, error) {
return s.message, s.messageReplay, s.messageErr
}
func (messengerStoreStub) ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error) {
return nil, false, nil
@@ -157,9 +162,66 @@ func TestRegistrationRejectsWhitespacePassword(t *testing.T) {
}
}
func TestInstanceHeaderIsSetOnSuccessAndError(t *testing.T) {
server := newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
for _, response := range []*httptest.ResponseRecorder{
serveRequest(server, http.MethodGet, "/health/live", ""),
serveRequest(server, http.MethodGet, "/api/v1/users/me", ""),
} {
if value := response.Header().Get("X-Instance-Id"); value != "test-instance" {
t.Fatalf("X-Instance-Id = %q, want test-instance", value)
}
}
}
func TestMessageCreationValidatesIdempotencyKey(t *testing.T) {
store := messengerStoreStub{userByID: model.User{ID: "user-id"}}
server := newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{})
tests := []struct {
name string
key string
}{
{name: "missing"},
{name: "invalid", key: "invalid key"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "/api/v1/chats/00000000-0000-0000-0000-000000000001/messages", strings.NewReader(`{"text":"message"}`))
request.Header.Set("Authorization", "Bearer valid-token")
request.Header.Set("Content-Type", "application/json")
if tt.key != "" {
request.Header.Set("Idempotency-Key", tt.key)
}
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
}
})
}
}
func TestMessageCreationReturnsConflictForReusedKeyWithDifferentBody(t *testing.T) {
store := messengerStoreStub{
userByID: model.User{ID: "user-id"},
messageErr: fmt.Errorf("create message: %w", postgres.ErrIdempotencyConflict),
}
server := newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{})
request := httptest.NewRequest(http.MethodPost, "/api/v1/chats/00000000-0000-0000-0000-000000000001/messages", strings.NewReader(`{"text":"different"}`))
request.Header.Set("Authorization", "Bearer valid-token")
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Idempotency-Key", "same-key")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
if response.Code != http.StatusConflict {
t.Fatalf("status = %d, want %d", response.Code, http.StatusConflict)
}
}
func newTestServer(messages MessengerStore, sessions SessionStore, passwords PasswordService) *Server {
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
return NewServer(logger, messages, sessions, passwords, time.Hour, time.Second, "8081")
return NewServer(logger, messages, sessions, passwords, time.Hour, 24*time.Hour, time.Second, "test-instance", "8081")
}
func serveRequest(server *Server, method, path, body string) *httptest.ResponseRecorder {