forked from mtusi2026/mtusi2026lab3
Добавить две реплики API за HAProxy и проверку отказа одной из них.
Общие сессии и ключ идемпотентности позволяют продолжать чтение и запись, когда одна реплика остановлена.
This commit is contained in:
@@ -222,6 +222,11 @@ func (a *API) createMessage(w http.ResponseWriter, r *http.Request, rawID string
|
||||
if _, err := a.store.ChatFor(r.Context(), id, user.ID); a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
idemKey := r.Header.Get("Idempotency-Key")
|
||||
if !idemKeyRe.MatchString(idemKey) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Нужен заголовок Idempotency-Key", 0)
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
@@ -232,7 +237,8 @@ func (a *API) createMessage(w http.ResponseWriter, r *http.Request, rawID string
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный текст сообщения", 0)
|
||||
return
|
||||
}
|
||||
msg, err := a.store.AddMessage(r.Context(), id, user.ID, body.Text)
|
||||
// Отпечаток — разобранный текст, а не сырые байты: порядок ключей JSON и \u-экранирование не создают другое сообщение.
|
||||
msg, err := a.store.AddMessage(r.Context(), id, user.ID, body.Text, idemKey, body.Text)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
@@ -288,6 +294,8 @@ func (a *API) writeStoreErr(w http.ResponseWriter, r *http.Request, err error) b
|
||||
switch {
|
||||
case errors.Is(err, store.ErrUnavailable), errors.Is(err, session.ErrUnavailable):
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", 1)
|
||||
case errors.Is(err, store.ErrIdempotencyMismatch):
|
||||
a.fail(w, r, http.StatusConflict, "conflict", "Этот ключ уже использован для другого сообщения", 0)
|
||||
case errors.Is(err, store.ErrConflict):
|
||||
a.fail(w, r, http.StatusConflict, "conflict", "Имя пользователя уже занято", 0)
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
|
||||
@@ -22,6 +22,7 @@ var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
var uuidRe = regexp.MustCompile(`(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
|
||||
var limitRe = regexp.MustCompile(`^[0-9]{1,3}$`)
|
||||
var requestIDRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,64}$`)
|
||||
var idemKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
type errorEnvelope struct {
|
||||
Error errorObject `json:"error"`
|
||||
|
||||
@@ -20,19 +20,23 @@ type API struct {
|
||||
hasher password.Params
|
||||
dummyHash string
|
||||
sessionTTL time.Duration
|
||||
instanceID string
|
||||
log *slog.Logger
|
||||
shutting atomic.Bool
|
||||
}
|
||||
|
||||
// New связывает HTTP с хранилищем и сессиями.
|
||||
// dummyHash нужен, чтобы несуществующий username тратил столько же KDF, сколько существующий.
|
||||
func New(st store.Repository, sessions session.Store, hasher password.Params, sessionTTL time.Duration, log *slog.Logger) *API {
|
||||
func New(st store.Repository, sessions session.Store, hasher password.Params, sessionTTL time.Duration, instanceID string, log *slog.Logger) *API {
|
||||
if log == nil {
|
||||
log = slog.Default()
|
||||
}
|
||||
if sessionTTL <= 0 {
|
||||
sessionTTL = time.Hour
|
||||
}
|
||||
if instanceID == "" {
|
||||
instanceID = "api"
|
||||
}
|
||||
dummy, err := hasher.Hash("dummy-password-not-a-login")
|
||||
if err != nil {
|
||||
// Параметры KDF проверяются на старте. Пустая строка заставит Verify сразу вернуть false.
|
||||
@@ -44,6 +48,7 @@ func New(st store.Repository, sessions session.Store, hasher password.Params, se
|
||||
hasher: hasher,
|
||||
dummyHash: dummy,
|
||||
sessionTTL: sessionTTL,
|
||||
instanceID: instanceID,
|
||||
log: log,
|
||||
}
|
||||
}
|
||||
@@ -61,6 +66,7 @@ func (a *API) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
id := requestID(r)
|
||||
sw.Header().Set("X-Request-Id", id)
|
||||
sw.Header().Set("X-Instance-Id", a.instanceID)
|
||||
r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, id))
|
||||
|
||||
defer func() {
|
||||
|
||||
+131
-3
@@ -10,8 +10,10 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -38,7 +40,7 @@ func newServerTTL(t *testing.T, ttl time.Duration) *labServer {
|
||||
t.Helper()
|
||||
st := store.New()
|
||||
sess := session.NewMemory()
|
||||
application := New(st, sess, password.Params{Time: 1, Memory: 8, Threads: 1}, ttl, slog.New(slog.NewJSONHandler(io.Discard, nil)))
|
||||
application := New(st, sess, password.Params{Time: 1, Memory: 8, Threads: 1}, ttl, "test-instance", slog.New(slog.NewJSONHandler(io.Discard, nil)))
|
||||
srv := httptest.NewServer(application)
|
||||
t.Cleanup(srv.Close)
|
||||
return &labServer{URL: srv.URL, tokens: map[string]string{}, api: application, store: st, sess: sess}
|
||||
@@ -54,7 +56,13 @@ func (e *labServer) bearer(user string) string {
|
||||
return "unknown-session-token"
|
||||
}
|
||||
|
||||
func do(t *testing.T, env *labServer, method, url, user string, body any, raw []byte, contentType string) (int, http.Header, []byte) {
|
||||
var keySeq atomic.Uint64
|
||||
|
||||
func nextIdemKey() string {
|
||||
return "k" + strconv.FormatUint(keySeq.Add(1), 36)
|
||||
}
|
||||
|
||||
func do(t *testing.T, env *labServer, method, url, user string, body any, raw []byte, contentType string, extra ...map[string]string) (int, http.Header, []byte) {
|
||||
t.Helper()
|
||||
var rdr io.Reader
|
||||
if raw != nil {
|
||||
@@ -79,6 +87,14 @@ func do(t *testing.T, env *labServer, method, url, user string, body any, raw []
|
||||
if tok := env.bearer(user); tok != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
if len(extra) > 0 {
|
||||
for k, v := range extra[0] {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
}
|
||||
if method == http.MethodPost && strings.Contains(url, "/messages") && req.Header.Get("Idempotency-Key") == "" {
|
||||
req.Header.Set("Idempotency-Key", nextIdemKey())
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -91,6 +107,9 @@ func do(t *testing.T, env *labServer, method, url, user string, body any, raw []
|
||||
if resp.Header.Get("X-Request-Id") == "" {
|
||||
t.Fatalf("%s %s: missing X-Request-Id", method, url)
|
||||
}
|
||||
if resp.Header.Get("X-Instance-Id") != "test-instance" {
|
||||
t.Fatalf("%s %s: X-Instance-Id = %q", method, url, resp.Header.Get("X-Instance-Id"))
|
||||
}
|
||||
if resp.StatusCode >= 400 {
|
||||
var env errorEnvelope
|
||||
if err := json.Unmarshal(data, &env); err != nil {
|
||||
@@ -402,6 +421,7 @@ func TestConcurrentHundredMessages(t *testing.T) {
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+env.tokens[user])
|
||||
req.Header.Set("Idempotency-Key", user+"-"+strconv.Itoa(j))
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
@@ -559,7 +579,7 @@ func (downStore) User(context.Context, string) (store.User, error) {
|
||||
func TestDependencyDownDoesNotTrustAnonymous(t *testing.T) {
|
||||
env := newServer(t)
|
||||
alice := createUser(t, env, "alice", "Алиса")
|
||||
broken := New(downStore{env.store}, downSessions{env.sess}, password.Params{Time: 1, Memory: 8, Threads: 1}, time.Hour, slog.New(slog.NewJSONHandler(io.Discard, nil)))
|
||||
broken := New(downStore{env.store}, downSessions{env.sess}, password.Params{Time: 1, Memory: 8, Threads: 1}, time.Hour, "test-instance", slog.New(slog.NewJSONHandler(io.Discard, nil)))
|
||||
srv := httptest.NewServer(broken)
|
||||
defer srv.Close()
|
||||
|
||||
@@ -604,6 +624,114 @@ func TestDependencyDownDoesNotTrustAnonymous(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdempotencyReplayConflictAndRace(t *testing.T) {
|
||||
env := newServer(t)
|
||||
alice := createUser(t, env, "alice", "Алиса")
|
||||
bob := createUser(t, env, "bob", "Боб")
|
||||
chat := createChat(t, env, alice.ID, "ключ", alice.ID, bob.ID)
|
||||
path := env.URL + "/api/v1/chats/" + chat.ID + "/messages"
|
||||
key := "same-key-1"
|
||||
|
||||
status, _, body := do(t, env, http.MethodPost, path, alice.ID, map[string]string{"text": "одно"}, nil, "", map[string]string{"Idempotency-Key": key})
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("first: %d %s", status, body)
|
||||
}
|
||||
var first messageJSON
|
||||
if err := json.Unmarshal(body, &first); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
status, _, body = do(t, env, http.MethodPost, path, alice.ID, nil, []byte(`{"text":"одно"}`), "application/json", map[string]string{"Idempotency-Key": key})
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("replay: %d %s", status, body)
|
||||
}
|
||||
var replay messageJSON
|
||||
if err := json.Unmarshal(body, &replay); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if replay != first {
|
||||
t.Fatalf("replay changed message: %+v vs %+v", replay, first)
|
||||
}
|
||||
status, _, _ = do(t, env, http.MethodPost, path, alice.ID, map[string]string{"text": "другое"}, nil, "", map[string]string{"Idempotency-Key": key})
|
||||
if status != http.StatusConflict {
|
||||
t.Fatalf("mismatch: %d", status)
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost, path, strings.NewReader(`{"text":"без ключа"}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+env.tokens[alice.ID])
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("missing key: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
status, _, body = do(t, env, http.MethodPost, path, bob.ID, map[string]string{"text": "одно"}, nil, "", map[string]string{"Idempotency-Key": key})
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("other user: %d %s", status, body)
|
||||
}
|
||||
var other messageJSON
|
||||
if err := json.Unmarshal(body, &other); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if other.ID == first.ID {
|
||||
t.Fatal("same key for another user reused the message")
|
||||
}
|
||||
|
||||
raceKey := "race-key"
|
||||
var wg sync.WaitGroup
|
||||
ids := make(chan string, 16)
|
||||
errs := make(chan error, 16)
|
||||
for i := 0; i < 16; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
req, err := http.NewRequest(http.MethodPost, path, strings.NewReader(`{"text":"гонка"}`))
|
||||
if err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+env.tokens[alice.ID])
|
||||
req.Header.Set("Idempotency-Key", raceKey)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
errs <- &statusErr{resp.StatusCode, raw}
|
||||
return
|
||||
}
|
||||
var msg messageJSON
|
||||
if err := json.Unmarshal(raw, &msg); err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
ids <- msg.ID
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(ids)
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seen := map[string]struct{}{}
|
||||
for id := range ids {
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
if len(seen) != 1 {
|
||||
t.Fatalf("concurrent same key created %d messages", len(seen))
|
||||
}
|
||||
}
|
||||
|
||||
type statusErr struct {
|
||||
code int
|
||||
body []byte
|
||||
|
||||
@@ -21,6 +21,8 @@ type Config struct {
|
||||
Argon2Time uint32
|
||||
Argon2Memory uint32
|
||||
Argon2Threads uint8
|
||||
InstanceID string
|
||||
IdempotencyTTL time.Duration
|
||||
}
|
||||
|
||||
// Addr — адрес прослушивания. В контейнере это 0.0.0.0:8080,
|
||||
@@ -93,6 +95,16 @@ func Load() (Config, error) {
|
||||
c.Argon2Time = uint32(argonTime)
|
||||
c.Argon2Memory = uint32(argonMemory)
|
||||
c.Argon2Threads = uint8(argonThreads)
|
||||
|
||||
c.InstanceID = getenv("INSTANCE_ID", "")
|
||||
idemTTL, err := nonNeg("IDEMPOTENCY_TTL_SECONDS", 86400)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if idemTTL < 86400 || idemTTL > 7*24*3600 {
|
||||
return Config{}, fmt.Errorf("IDEMPOTENCY_TTL_SECONDS must be 86400..604800")
|
||||
}
|
||||
c.IdempotencyTTL = time.Duration(idemTTL) * time.Second
|
||||
return c, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -13,15 +13,29 @@ import (
|
||||
"messenger/migrations"
|
||||
)
|
||||
|
||||
// Создаёт schema_migrations и выполняет ещё не записанные файлы.
|
||||
// Повторный запуск не исполняет уже применённый SQL и не дублирует строки.
|
||||
// advisoryLock сериализует миграции между процессами. Номер постоянный для этого приложения.
|
||||
const advisoryLock int64 = 748392016
|
||||
|
||||
// Apply создаёт schema_migrations и выполняет ещё не записанные файлы.
|
||||
// Замок держится на одном соединении: пул сам по себе не привязывает блокировку к сессии.
|
||||
func Apply(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
_, err := pool.Exec(ctx, `
|
||||
conn, err := pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Release()
|
||||
if _, err := conn.Exec(ctx, `SELECT pg_advisory_lock($1)`, advisoryLock); err != nil {
|
||||
return fmt.Errorf("advisory lock: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
_, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock($1)`, advisoryLock)
|
||||
}()
|
||||
|
||||
if _, err := conn.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)`)
|
||||
if err != nil {
|
||||
)`); err != nil {
|
||||
return fmt.Errorf("schema_migrations: %w", err)
|
||||
}
|
||||
entries, err := fs.ReadDir(migrations.FS, ".")
|
||||
@@ -38,7 +52,7 @@ func Apply(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
sort.Strings(names)
|
||||
for _, name := range names {
|
||||
var applied bool
|
||||
if err := pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = $1)`, name).Scan(&applied); err != nil {
|
||||
if err := conn.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = $1)`, name).Scan(&applied); err != nil {
|
||||
return err
|
||||
}
|
||||
if applied {
|
||||
@@ -48,7 +62,7 @@ func Apply(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tx, err := pool.Begin(ctx)
|
||||
tx, err := conn.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
+98
-28
@@ -14,7 +14,8 @@ import (
|
||||
// PG — источник истины для пользователей, чатов и сообщений.
|
||||
// Запросы только с параметрами. Пул ограничен, у сессии соединения есть statement_timeout.
|
||||
type PG struct {
|
||||
pool *pgxpool.Pool
|
||||
pool *pgxpool.Pool
|
||||
idemTTL time.Duration
|
||||
}
|
||||
|
||||
func Open(ctx context.Context, databaseURL string, maxConns int32) (*PG, error) {
|
||||
@@ -45,7 +46,14 @@ func Open(ctx context.Context, databaseURL string, maxConns int32) (*PG, error)
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &PG{pool: pool}, nil
|
||||
return &PG{pool: pool, idemTTL: 24 * time.Hour}, nil
|
||||
}
|
||||
|
||||
// SetIdempotencyTTL задаёт, сколько хранить результат POST сообщения.
|
||||
func (p *PG) SetIdempotencyTTL(ttl time.Duration) {
|
||||
if ttl > 0 {
|
||||
p.idemTTL = ttl
|
||||
}
|
||||
}
|
||||
|
||||
func (p *PG) Close() { p.pool.Close() }
|
||||
@@ -214,37 +222,72 @@ func (p *PG) ListChats(ctx context.Context, userID string, cur *Cursor, limit in
|
||||
return items, hasMore, nil
|
||||
}
|
||||
|
||||
func (p *PG) AddMessage(ctx context.Context, chatID, senderID, text string) (Message, error) {
|
||||
func (p *PG) AddMessage(ctx context.Context, chatID, senderID, text, idemKey, fingerprint string) (Message, error) {
|
||||
if idemKey == "" || fingerprint == "" {
|
||||
return Message{}, ErrInvalid
|
||||
}
|
||||
var last error
|
||||
for attempt := 0; attempt < 5; attempt++ {
|
||||
msg, retry, err := p.addMessageOnce(ctx, chatID, senderID, text, idemKey, fingerprint)
|
||||
if !retry {
|
||||
return msg, err
|
||||
}
|
||||
last = err
|
||||
}
|
||||
if last == nil {
|
||||
last = ErrUnavailable
|
||||
}
|
||||
return Message{}, ErrUnavailable
|
||||
}
|
||||
|
||||
// addMessageOnce пишет сообщение и ключ одной транзакцией.
|
||||
// retry=true значит, что параллельная реплика заняла тот же ключ раньше: свою вставку откатываем и читаем её результат.
|
||||
func (p *PG) addMessageOnce(ctx context.Context, chatID, senderID, text, idemKey, fingerprint string) (Message, bool, error) {
|
||||
tx, err := p.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
return Message{}, false, mapDB(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
// Блокировка строки чата сериализует writers одного чата.
|
||||
var exists string
|
||||
err = tx.QueryRow(ctx, `SELECT id::text FROM chats WHERE id = $1 FOR UPDATE`, chatID).Scan(&exists)
|
||||
if err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
}
|
||||
var member int
|
||||
if err := tx.QueryRow(ctx, `
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, senderID).Scan(&member); err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
return Message{}, false, mapDB(err)
|
||||
}
|
||||
var last time.Time
|
||||
|
||||
var storedFP, messageID string
|
||||
var expires time.Time
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT created_at FROM messages WHERE chat_id = $1
|
||||
ORDER BY created_at DESC LIMIT 1`, chatID).Scan(&last)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
last = time.Time{}
|
||||
} else if err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
SELECT fingerprint, message_id::text, expires_at
|
||||
FROM message_idempotency
|
||||
WHERE user_id = $1 AND chat_id = $2 AND idem_key = $3
|
||||
FOR UPDATE`, senderID, chatID, idemKey).Scan(&storedFP, &messageID, &expires)
|
||||
if err == nil {
|
||||
if expires.After(time.Now()) {
|
||||
if storedFP != fingerprint {
|
||||
return Message{}, false, ErrIdempotencyMismatch
|
||||
}
|
||||
msg, err := scanMessage(tx.QueryRow(ctx, `
|
||||
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
||||
FROM messages WHERE id = $1`, messageID))
|
||||
if err != nil {
|
||||
return Message{}, false, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return Message{}, false, mapDB(err)
|
||||
}
|
||||
return msg, false, nil
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
DELETE FROM message_idempotency
|
||||
WHERE user_id = $1 AND chat_id = $2 AND idem_key = $3`, senderID, chatID, idemKey); err != nil {
|
||||
return Message{}, false, mapDB(err)
|
||||
}
|
||||
} else if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return Message{}, false, mapDB(err)
|
||||
}
|
||||
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
if !last.IsZero() && !now.After(last.UTC()) {
|
||||
now = last.UTC().Add(time.Microsecond)
|
||||
}
|
||||
m := Message{
|
||||
ID: newID(),
|
||||
ChatID: chatID,
|
||||
@@ -255,12 +298,31 @@ func (p *PG) AddMessage(ctx context.Context, chatID, senderID, text string) (Mes
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`, m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt); err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
return Message{}, retryable(err), mapDB(err)
|
||||
}
|
||||
recorded := time.Now().UTC().Truncate(time.Microsecond)
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO message_idempotency
|
||||
(user_id, chat_id, idem_key, fingerprint, message_id, created_at, expires_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
|
||||
senderID, chatID, idemKey, fingerprint, m.ID, recorded, recorded.Add(p.idemTTL)); err != nil {
|
||||
return Message{}, retryable(err), mapDB(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
return Message{}, retryable(err), mapDB(err)
|
||||
}
|
||||
return m, nil
|
||||
return m, false, nil
|
||||
}
|
||||
|
||||
func retryable(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
switch pgErr.Code {
|
||||
case "23505", "40001", "40P01":
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *PG) ListMessages(ctx context.Context, chatID, userID string, cur *Cursor, limit int) ([]Message, bool, error) {
|
||||
@@ -302,11 +364,10 @@ func (p *PG) ListMessages(ctx context.Context, chatID, userID string, cur *Curso
|
||||
defer rows.Close()
|
||||
items := make([]Message, 0)
|
||||
for rows.Next() {
|
||||
var m Message
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return nil, false, mapDB(err)
|
||||
m, err := scanMessage(rows)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
m.CreatedAt = m.CreatedAt.UTC()
|
||||
items = append(items, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
@@ -350,6 +411,15 @@ func (p *PG) memberIDs(ctx context.Context, q queryer, chatIDs []string) (map[st
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func scanMessage(row pgx.Row) (Message, error) {
|
||||
var m Message
|
||||
if err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
}
|
||||
m.CreatedAt = m.CreatedAt.UTC()
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func scanUser(row pgx.Row) (User, error) {
|
||||
var u User
|
||||
err := row.Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
|
||||
@@ -121,6 +121,58 @@ func TestIntegrationChatRollback(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationIdempotencyRace(t *testing.T) {
|
||||
pg := openIntegration(t)
|
||||
ctx := context.Background()
|
||||
u, err := pg.CreateUser(ctx, "idm_"+newID()[:8], "Ключ", "hash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chat, err := pg.CreateChat(ctx, "идемпотентность", []string{u.ID}, u.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const n = 16
|
||||
var wg sync.WaitGroup
|
||||
ids := make(chan string, n)
|
||||
errs := make(chan error, n)
|
||||
for i := 0; i < n; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
msg, err := pg.AddMessage(ctx, chat.ID, u.ID, "одно", "key-1", "одно")
|
||||
if err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
ids <- msg.ID
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(ids)
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seen := map[string]struct{}{}
|
||||
for id := range ids {
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
if len(seen) != 1 {
|
||||
t.Fatalf("concurrent key created %d messages", len(seen))
|
||||
}
|
||||
if _, err := pg.AddMessage(ctx, chat.ID, u.ID, "другое", "key-1", "другое"); !errors.Is(err, ErrIdempotencyMismatch) {
|
||||
t.Fatalf("mismatch: %v", err)
|
||||
}
|
||||
var count int
|
||||
if err := pg.Pool().QueryRow(ctx, `SELECT count(*) FROM messages WHERE chat_id = $1`, chat.ID).Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("messages = %d, want 1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresUnreachable(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
+46
-7
@@ -10,11 +10,12 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrInvalid = errors.New("invalid")
|
||||
ErrBadCursor = errors.New("bad cursor")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrIdempotencyMismatch = errors.New("idempotency mismatch")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrInvalid = errors.New("invalid")
|
||||
ErrBadCursor = errors.New("bad cursor")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
)
|
||||
|
||||
// User — публичная карточка. Хеш пароля в неё не входит.
|
||||
@@ -57,7 +58,10 @@ type Repository interface {
|
||||
CreateChat(ctx context.Context, title string, memberIDs []string, caller string) (Chat, error)
|
||||
ChatFor(ctx context.Context, chatID, userID string) (Chat, error)
|
||||
ListChats(ctx context.Context, userID string, cur *Cursor, limit int) ([]Chat, bool, error)
|
||||
AddMessage(ctx context.Context, chatID, senderID, text string) (Message, error)
|
||||
// AddMessage создаёт сообщение или возвращает уже записанное для того же ключа.
|
||||
// fingerprint — каноническое тело (текст). Другой fingerprint при живом ключе даёт ErrIdempotencyMismatch.
|
||||
// Ключ живёт idempotencyTTL. Область: отправитель + чат + ключ (метод POST и путь чата).
|
||||
AddMessage(ctx context.Context, chatID, senderID, text, idemKey, fingerprint string) (Message, error)
|
||||
ListMessages(ctx context.Context, chatID, userID string, cur *Cursor, limit int) ([]Message, bool, error)
|
||||
}
|
||||
|
||||
@@ -66,6 +70,12 @@ type chatRec struct {
|
||||
members map[string]struct{}
|
||||
}
|
||||
|
||||
type idemRec struct {
|
||||
fingerprint string
|
||||
messageID string
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
// Memory сериализует записи мьютексом. Это двойник контракта для тестов без PostgreSQL.
|
||||
type Memory struct {
|
||||
mu sync.RWMutex
|
||||
@@ -76,6 +86,8 @@ type Memory struct {
|
||||
chatOrder []string
|
||||
messages map[string][]Message
|
||||
msgIndex map[string]map[string]int
|
||||
idem map[string]idemRec
|
||||
idemTTL time.Duration
|
||||
last time.Time
|
||||
}
|
||||
|
||||
@@ -87,9 +99,21 @@ func New() *Memory {
|
||||
chats: make(map[string]*chatRec),
|
||||
messages: make(map[string][]Message),
|
||||
msgIndex: make(map[string]map[string]int),
|
||||
idem: make(map[string]idemRec),
|
||||
idemTTL: 24 * time.Hour,
|
||||
}
|
||||
}
|
||||
|
||||
// SetIdempotencyTTL меняет срок ключа. Нужен тестам; в PostgreSQL тот же смысл у IDEMPOTENCY_TTL_SECONDS.
|
||||
func (s *Memory) SetIdempotencyTTL(d time.Duration) {
|
||||
if d <= 0 {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.idemTTL = d
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Memory) Ping(ctx context.Context) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return ErrUnavailable
|
||||
@@ -218,10 +242,13 @@ func (s *Memory) ListChats(ctx context.Context, userID string, cur *Cursor, limi
|
||||
return append([]Chat(nil), filtered[start:end]...), end < len(filtered), nil
|
||||
}
|
||||
|
||||
func (s *Memory) AddMessage(ctx context.Context, chatID, senderID, text string) (Message, error) {
|
||||
func (s *Memory) AddMessage(ctx context.Context, chatID, senderID, text, idemKey, fingerprint string) (Message, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Message{}, ErrUnavailable
|
||||
}
|
||||
if idemKey == "" || fingerprint == "" {
|
||||
return Message{}, ErrInvalid
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
rec, ok := s.chats[chatID]
|
||||
@@ -231,6 +258,17 @@ func (s *Memory) AddMessage(ctx context.Context, chatID, senderID, text string)
|
||||
if _, member := rec.members[senderID]; !member {
|
||||
return Message{}, ErrNotFound
|
||||
}
|
||||
slot := senderID + "\x00" + chatID + "\x00" + idemKey
|
||||
if prev, ok := s.idem[slot]; ok && prev.expires.After(time.Now()) {
|
||||
if prev.fingerprint != fingerprint {
|
||||
return Message{}, ErrIdempotencyMismatch
|
||||
}
|
||||
idx, ok := s.msgIndex[chatID][prev.messageID]
|
||||
if !ok {
|
||||
return Message{}, ErrNotFound
|
||||
}
|
||||
return s.messages[chatID][idx], nil
|
||||
}
|
||||
m := Message{
|
||||
ID: newID(),
|
||||
ChatID: chatID,
|
||||
@@ -241,6 +279,7 @@ func (s *Memory) AddMessage(ctx context.Context, chatID, senderID, text string)
|
||||
idx := len(s.messages[chatID])
|
||||
s.messages[chatID] = append(s.messages[chatID], m)
|
||||
s.msgIndex[chatID][m.ID] = idx
|
||||
s.idem[slot] = idemRec{fingerprint: fingerprint, messageID: m.ID, expires: time.Now().Add(s.idemTTL)}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user