forked from mtusi2026/mtusi2026lab3
feat:level4
This commit is contained in:
+43
-3
@@ -1,8 +1,10 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
@@ -12,6 +14,7 @@ import (
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
var idempotencyKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
type Handler struct {
|
||||
Store *domain.Store
|
||||
@@ -224,12 +227,31 @@ func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
h.bearerAuth(func(w http.ResponseWriter, r *http.Request) {
|
||||
me, _ := userFrom(r)
|
||||
chatID := r.PathValue("chat_id")
|
||||
|
||||
// Idempotency-Key обязателен.
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
if key == "" {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "Idempotency-Key required")
|
||||
return
|
||||
}
|
||||
if !idempotencyKeyRe.MatchString(key) {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid Idempotency-Key")
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := h.Store.GetChat(r.Context(), chatID, me.ID); err != nil {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
return
|
||||
}
|
||||
|
||||
// Читаем тело один раз и хешируем нормализованный JSON.
|
||||
rawBody, err := io.ReadAll(io.LimitReader(r.Body, 64*1024))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "cannot read body")
|
||||
return
|
||||
}
|
||||
var req createMessageReq
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec := json.NewDecoder(bytes.NewReader(rawBody))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&req); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "malformed JSON")
|
||||
@@ -243,13 +265,23 @@ func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "empty message")
|
||||
return
|
||||
}
|
||||
m, err := h.Store.AddMessage(r.Context(), chatID, me.ID, req.Text)
|
||||
bodyHash, err := domain.HashBody(rawBody)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "malformed JSON")
|
||||
return
|
||||
}
|
||||
|
||||
msg, rec, replay, err := h.Store.AddMessageIdempotent(
|
||||
r.Context(), chatID, me.ID, req.Text, key, bodyHash)
|
||||
switch {
|
||||
case err == nil:
|
||||
// ok
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "chat not found")
|
||||
return
|
||||
case errors.Is(err, domain.ErrConflict):
|
||||
writeError(w, r, http.StatusConflict, "conflict", "idempotency key reused with different body")
|
||||
return
|
||||
case errors.Is(err, domain.ErrTimeout):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database timeout")
|
||||
return
|
||||
@@ -257,7 +289,15 @@ func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "database unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, m)
|
||||
|
||||
if replay {
|
||||
// Возвращаем сохранённый 201 и то же Message.
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(rec.StatusCode)
|
||||
_, _ = w.Write(rec.Response)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, msg)
|
||||
})(w, r)
|
||||
}
|
||||
|
||||
|
||||
@@ -33,3 +33,14 @@ func withRequestID(next http.Handler) http.Handler {
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// withInstanceID ставит X-Instance-Id на КАЖДЫЙ ответ (включая ошибки и health).
|
||||
// ID генерируется один раз при старте процесса — стабилен в пределах жизни.
|
||||
func withInstanceID(instanceID 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("X-Instance-Id", instanceID)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+4
-2
@@ -2,7 +2,7 @@ package api
|
||||
|
||||
import "net/http"
|
||||
|
||||
func NewRouter(h *Handler) http.Handler {
|
||||
func NewRouter(h *Handler, instanceID string) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /health/live", h.Live)
|
||||
mux.HandleFunc("GET /health/ready", h.Ready)
|
||||
@@ -15,5 +15,7 @@ func NewRouter(h *Handler) http.Handler {
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}", h.GetChat)
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", h.CreateMessage)
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", h.ListMessages)
|
||||
return withRequestID(mux)
|
||||
|
||||
// Порядок: instanceID снаружи, requestID внутри.
|
||||
return withInstanceID(instanceID)(withRequestID(mux))
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
@@ -15,6 +17,7 @@ type Config struct {
|
||||
SessionTTL time.Duration
|
||||
SessionStore string // "postgres" | "redis"
|
||||
RedisRequired bool
|
||||
InstanceID string
|
||||
}
|
||||
|
||||
func getenv(key, def string) string {
|
||||
@@ -59,6 +62,11 @@ func Load() Config {
|
||||
cacheURL = readSecretFromFile(os.Getenv("CACHE_URL_FILE"))
|
||||
}
|
||||
|
||||
instanceID := os.Getenv("INSTANCE_ID")
|
||||
if instanceID == "" {
|
||||
instanceID = "api-" + randomShortID()
|
||||
}
|
||||
|
||||
store := getenv("SESSION_STORE", "postgres")
|
||||
return Config{
|
||||
Host: getenv("APP_HOST", "0.0.0.0"),
|
||||
@@ -69,5 +77,14 @@ func Load() Config {
|
||||
SessionTTL: time.Duration(ttl) * time.Second,
|
||||
SessionStore: store,
|
||||
RedisRequired: store == "redis",
|
||||
InstanceID: instanceID,
|
||||
}
|
||||
}
|
||||
|
||||
func randomShortID() string {
|
||||
b := make([]byte, 6)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "unknown"
|
||||
}
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// IdempotencyRecord — сохранённый результат POST.
|
||||
type IdempotencyRecord struct {
|
||||
StatusCode int
|
||||
Response json.RawMessage
|
||||
}
|
||||
|
||||
// LookupIdempotency возвращает запись, если ключ уже использован.
|
||||
// Второй аргумент — совпадает ли хеш тела с сохранённым.
|
||||
func (s *Store) LookupIdempotency(ctx context.Context, userID, method, path, key, bodyHash string) (*IdempotencyRecord, bool, error) {
|
||||
var (
|
||||
storedHash string
|
||||
rec IdempotencyRecord
|
||||
)
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT request_hash, status_code, response
|
||||
FROM idempotency_keys
|
||||
WHERE user_id=$1 AND method=$2 AND path=$3 AND key=$4`,
|
||||
userID, method, path, key,
|
||||
).Scan(&storedHash, &rec.StatusCode, &rec.Response)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, classifyDBError(err)
|
||||
}
|
||||
if storedHash != bodyHash {
|
||||
return nil, true, ErrConflict
|
||||
}
|
||||
return &rec, true, nil
|
||||
}
|
||||
|
||||
// SaveIdempotency пишет результат. Конфликт PK означает, что параллельный
|
||||
// запрос успел раньше — вызывающий должен перечитать через LookupIdempotency.
|
||||
func (s *Store) SaveIdempotency(ctx context.Context, userID, method, path, key, bodyHash string, status int, resp json.RawMessage) error {
|
||||
_, err := s.pool.Exec(ctx,
|
||||
`INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, status_code, response)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7)`,
|
||||
userID, method, path, key, bodyHash, status, resp)
|
||||
return classifyDBError(err)
|
||||
}
|
||||
|
||||
// HashBody — стабильный хеш JSON независимо от порядка ключей.
|
||||
func HashBody(raw []byte) (string, error) {
|
||||
var v any
|
||||
if err := json.Unmarshal(raw, &v); err != nil {
|
||||
return "", err
|
||||
}
|
||||
normalized, err := json.Marshal(v) // map keys сортируются
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
sum := sha256.Sum256(normalized)
|
||||
return hex.EncodeToString(sum[:]), nil
|
||||
}
|
||||
|
||||
// CleanupIdempotency — можно звать из фонового тикера (опционально).
|
||||
func (s *Store) CleanupIdempotency(ctx context.Context, olderThan time.Duration) error {
|
||||
_, err := s.pool.Exec(ctx,
|
||||
`DELETE FROM idempotency_keys WHERE created_at < now() - $1::interval`,
|
||||
olderThan.String())
|
||||
return err
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
@@ -443,3 +444,95 @@ func classifyDBError(err error) error {
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// AddMessageIdempotent — атомарно проверяет членство, вставляет сообщение
|
||||
// и сохраняет результат идемпотентности в одной транзакции.
|
||||
// Если ключ уже есть с тем же body — возвращает сохранённый ответ и replay=true.
|
||||
func (s *Store) AddMessageIdempotent(
|
||||
ctx context.Context,
|
||||
chatID, senderID, text, key, bodyHash string,
|
||||
) (msg *Message, rec *IdempotencyRecord, replay bool, err error) {
|
||||
path := "/api/v1/chats/" + chatID + "/messages"
|
||||
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.Serializable})
|
||||
if err != nil {
|
||||
return nil, nil, false, classifyDBError(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
// 1) Членство.
|
||||
var ok bool
|
||||
if err := tx.QueryRow(ctx,
|
||||
`SELECT true FROM chat_members WHERE chat_id=$1 AND user_id=$2`,
|
||||
chatID, senderID,
|
||||
).Scan(&ok); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil, false, ErrNotFound
|
||||
}
|
||||
return nil, nil, false, classifyDBError(err)
|
||||
}
|
||||
|
||||
// 2) Уже был такой ключ?
|
||||
var storedHash string
|
||||
var storedStatus int
|
||||
var storedResp json.RawMessage
|
||||
err = tx.QueryRow(ctx,
|
||||
`SELECT request_hash, status_code, response
|
||||
FROM idempotency_keys
|
||||
WHERE user_id=$1 AND method='POST' AND path=$2 AND key=$3`,
|
||||
senderID, path, key,
|
||||
).Scan(&storedHash, &storedStatus, &storedResp)
|
||||
switch {
|
||||
case err == nil:
|
||||
if storedHash != bodyHash {
|
||||
return nil, nil, false, ErrConflict
|
||||
}
|
||||
return nil, &IdempotencyRecord{StatusCode: storedStatus, Response: storedResp}, true, nil
|
||||
case !errors.Is(err, pgx.ErrNoRows):
|
||||
return nil, nil, false, classifyDBError(err)
|
||||
}
|
||||
|
||||
// 3) Вставка сообщения.
|
||||
var m Message
|
||||
err = tx.QueryRow(ctx,
|
||||
`INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
VALUES ($1,$2,$3,$4)
|
||||
RETURNING id, chat_id, sender_id, text, created_at`,
|
||||
uuid.NewString(), chatID, senderID, text,
|
||||
).Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt)
|
||||
if err != nil {
|
||||
// Гонка на одном ключе в разных репликах: unique violation в idempotency_keys
|
||||
// маловероятен здесь, но serialization failure возможен.
|
||||
return nil, nil, false, classifyDBError(err)
|
||||
}
|
||||
|
||||
// 4) Сохранение ответа.
|
||||
respJSON, _ := json.Marshal(m)
|
||||
_, err = tx.Exec(ctx,
|
||||
`INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, status_code, response)
|
||||
VALUES ($1,'POST',$2,$3,$4,201,$5)`,
|
||||
senderID, path, key, bodyHash, respJSON)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
// Кто-то параллельно успел вставить: перечитываем в этой же tx.
|
||||
if err2 := tx.QueryRow(ctx,
|
||||
`SELECT request_hash, status_code, response
|
||||
FROM idempotency_keys
|
||||
WHERE user_id=$1 AND method='POST' AND path=$2 AND key=$3`,
|
||||
senderID, path, key,
|
||||
).Scan(&storedHash, &storedStatus, &storedResp); err2 == nil {
|
||||
if storedHash != bodyHash {
|
||||
return nil, nil, false, ErrConflict
|
||||
}
|
||||
return nil, &IdempotencyRecord{StatusCode: storedStatus, Response: storedResp}, true, nil
|
||||
}
|
||||
}
|
||||
return nil, nil, false, classifyDBError(err)
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, nil, false, classifyDBError(err)
|
||||
}
|
||||
return &m, nil, false, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user