feat: API replicas over HAProxy (3)

This commit is contained in:
2026-11-06 03:26:54 +03:00
parent de2f63b926
commit ec111aadfb
32 changed files with 396 additions and 147 deletions
+1 -1
View File
@@ -42,7 +42,7 @@ func (h *Handler) fail(w http.ResponseWriter, r *http.Request, err error) {
case errors.Is(err, domain.ErrNotFound):
writeError(w, http.StatusNotFound, "not_found", "resource not found")
case errors.Is(err, domain.ErrConflict):
writeError(w, http.StatusConflict, "conflict", "username is already taken")
writeError(w, http.StatusConflict, "conflict", err.Error())
case errors.Is(err, domain.ErrUnavailable):
h.log.Error("dependency unavailable", "request_id", w.Header().Get(headerRequestID),
"method", r.Method, "path", r.URL.Path, "err", err)
+4 -1
View File
@@ -57,7 +57,7 @@ func newStack(t *testing.T, dbURL, redisURL string, ttl time.Duration) *httptest
chats := service.NewChatService(store)
messages := service.NewMessageService(chats, store)
h := handler.New(users, auth, chats, messages, []handler.Pinger{store.Ping, sessions.Ping}, slog.New(slog.DiscardHandler))
srv := httptest.NewServer(router.New(h))
srv := httptest.NewServer(router.New(h, "test"))
t.Cleanup(srv.Close)
return srv
}
@@ -81,6 +81,9 @@ func request(t *testing.T, srv *httptest.Server, method, path, token, body strin
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
if method == http.MethodPost && strings.HasSuffix(path, "/messages") {
req.Header.Set("Idempotency-Key", uuid.New().String())
}
resp, err := srv.Client().Do(req)
if err != nil {
t.Fatal(err)
+4 -1
View File
@@ -2,8 +2,11 @@ package handler
import (
"context"
"fmt"
"net/http"
"time"
"messenger/internal/domain"
)
const readyTimeout = time.Second
@@ -17,7 +20,7 @@ func (h *Handler) Ready(w http.ResponseWriter, r *http.Request) {
defer cancel()
for _, dep := range h.deps {
if err := dep(ctx); err != nil {
h.fail(w, r, err)
h.fail(w, r, fmt.Errorf("%w: %v", domain.ErrUnavailable, err))
return
}
}
+14 -2
View File
@@ -1,6 +1,13 @@
package handler
import "net/http"
import (
"net/http"
"regexp"
)
const headerIdempotencyKey = "Idempotency-Key"
var idempotencyKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
func (h *Handler) SendMessage(w http.ResponseWriter, r *http.Request) {
chatID, err := chatIDParam(r)
@@ -8,6 +15,11 @@ func (h *Handler) SendMessage(w http.ResponseWriter, r *http.Request) {
h.fail(w, r, err)
return
}
key := r.Header.Get(headerIdempotencyKey)
if !idempotencyKeyRe.MatchString(key) {
h.fail(w, r, badRequest("Idempotency-Key header must match [A-Za-z0-9._:-]{1,128}"))
return
}
var req createMessageRequest
if err := decodeJSON(w, r, &req); err != nil {
h.fail(w, r, err)
@@ -17,7 +29,7 @@ func (h *Handler) SendMessage(w http.ResponseWriter, r *http.Request) {
h.fail(w, r, badRequest("text is required"))
return
}
msg, err := h.messages.Send(r.Context(), actor(r), chatID, *req.Text)
msg, err := h.messages.Send(r.Context(), actor(r), chatID, key, *req.Text)
if err != nil {
h.fail(w, r, err)
return
+10
View File
@@ -17,11 +17,21 @@ import (
const (
headerRequestID = "X-Request-Id"
headerInstanceID = "X-Instance-Id"
headerWWWAuthenticate = "WWW-Authenticate"
bearerChallenge = `Bearer realm="messenger"`
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
)
func InstanceID(id string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(headerInstanceID, id)
next.ServeHTTP(w, r)
})
}
}
func RequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(headerRequestID, uuid.New().String())