lab3: балансировка, идемпотентность, отказ реплики, трек 1

- X-Instance-Id, обязательный Idempotency-Key (PostgreSQL, одна транзакция)
- HAProxy + 2..N реплик API, readiness/drain по SIGTERM, однократные миграции
- скрипты stop-one/restore/restart/rolling-update/collect-evidence
- трек 1: параметризованный стенд, cmd/bench, оркестратор и анализ
- workflow реального прогона Docker-стенда на GitHub Actions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-23 17:24:54 +03:00
co-authored by Claude Opus 5.5
parent 0ab3a341aa
commit 2e7a80be92
68 changed files with 4747 additions and 17 deletions
+159
View File
@@ -0,0 +1,159 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/charawein/mtusi2026lab3/internal/domain"
"github.com/charawein/mtusi2026lab3/internal/repository"
)
type ChatRepository struct {
pool *pgxpool.Pool
}
func NewChatRepository(pool *pgxpool.Pool) *ChatRepository {
return &ChatRepository{pool: pool}
}
func (r *ChatRepository) Create(ctx context.Context, chat *domain.Chat) error {
tx, err := r.pool.Begin(ctx)
if err != nil {
return fmt.Errorf("begin tx: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
const insertChat = `INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)`
if _, err := tx.Exec(ctx, insertChat, chat.ID, chat.Title, chat.CreatedAt); err != nil {
return fmt.Errorf("insert chat: %w", err)
}
const insertMember = `INSERT INTO chat_members (chat_id, user_id) VALUES ($1::uuid, $2::uuid)`
for _, uid := range chat.MemberIDs {
if _, err := tx.Exec(ctx, insertMember, chat.ID, uid); err != nil {
return fmt.Errorf("insert member %s: %w", uid, err)
}
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("commit tx: %w", err)
}
return nil
}
func (r *ChatRepository) GetByID(ctx context.Context, id string) (*domain.Chat, error) {
const q = `SELECT id, title, created_at FROM chats WHERE id = $1::uuid`
var c domain.Chat
err := r.pool.QueryRow(ctx, q, id).Scan(&c.ID, &c.Title, &c.CreatedAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, repository.ErrNotFound
}
return nil, fmt.Errorf("select chat: %w", err)
}
const qMembers = `SELECT user_id FROM chat_members WHERE chat_id = $1::uuid ORDER BY user_id`
rows, err := r.pool.Query(ctx, qMembers, id)
if err != nil {
return nil, fmt.Errorf("select members: %w", err)
}
defer rows.Close()
c.MemberIDs = []string{}
for rows.Next() {
var uid string
if err := rows.Scan(&uid); err != nil {
return nil, fmt.Errorf("scan member: %w", err)
}
c.MemberIDs = append(c.MemberIDs, uid)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate members: %w", err)
}
return &c, nil
}
func (r *ChatRepository) IsMember(ctx context.Context, chatID, userID string) (bool, error) {
const q = `SELECT 1 FROM chat_members WHERE chat_id = $1::uuid AND user_id = $2::uuid`
var one int
err := r.pool.QueryRow(ctx, q, chatID, userID).Scan(&one)
if err == nil {
return true, nil
}
if !errors.Is(err, pgx.ErrNoRows) {
return false, fmt.Errorf("check membership: %w", err)
}
const qChat = `SELECT 1 FROM chats WHERE id = $1::uuid`
err = r.pool.QueryRow(ctx, qChat, chatID).Scan(&one)
if err == nil {
return false, nil
}
if errors.Is(err, pgx.ErrNoRows) {
return false, repository.ErrNotFound
}
return false, fmt.Errorf("check chat exists: %w", err)
}
func (r *ChatRepository) ListByMember(ctx context.Context, userID string, cursor time.Time, cursorID string, limit int) ([]*domain.Chat, error) {
const qChats = `
SELECT c.id, c.title, c.created_at
FROM chats c
JOIN chat_members m ON m.chat_id = c.id
WHERE m.user_id = $1::uuid
AND (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
ORDER BY c.created_at, c.id
LIMIT $4
`
rows, err := r.pool.Query(ctx, qChats, userID, cursor, cursorID, limit)
if err != nil {
return nil, fmt.Errorf("list chats: %w", err)
}
defer rows.Close()
chats := []*domain.Chat{}
var chatIDs []string
for rows.Next() {
var c domain.Chat
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
return nil, fmt.Errorf("scan chat: %w", err)
}
c.MemberIDs = []string{}
chats = append(chats, &c)
chatIDs = append(chatIDs, c.ID)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate chats: %w", err)
}
if len(chats) == 0 {
return chats, nil
}
const qMembers = `SELECT chat_id, user_id FROM chat_members WHERE chat_id = ANY($1::uuid[]) ORDER BY chat_id, user_id`
memberRows, err := r.pool.Query(ctx, qMembers, chatIDs)
if err != nil {
return nil, fmt.Errorf("list members: %w", err)
}
defer memberRows.Close()
byChat := make(map[string][]string)
for memberRows.Next() {
var chatID, uid string
if err := memberRows.Scan(&chatID, &uid); err != nil {
return nil, fmt.Errorf("scan member: %w", err)
}
byChat[chatID] = append(byChat[chatID], uid)
}
if err := memberRows.Err(); err != nil {
return nil, fmt.Errorf("iterate members: %w", err)
}
for _, c := range chats {
if members, ok := byChat[c.ID]; ok {
c.MemberIDs = members
}
}
return chats, nil
}
+135
View File
@@ -0,0 +1,135 @@
package postgres
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/charawein/mtusi2026lab3/internal/domain"
"github.com/charawein/mtusi2026lab3/internal/repository"
)
type MessageRepository struct {
pool *pgxpool.Pool
}
func NewMessageRepository(pool *pgxpool.Pool) *MessageRepository {
return &MessageRepository{pool: pool}
}
func (r *MessageRepository) Create(ctx context.Context, msg *domain.Message) error {
const q = `
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
`
if _, err := r.pool.Exec(ctx, q, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil {
return fmt.Errorf("insert message: %w", err)
}
return nil
}
// CreateIdempotent вставляет сообщение и ключ в одной транзакции.
// Конкурентные запросы с одним ключом сериализуются уникальным индексом
// idempotency_keys: второй INSERT ждёт завершения первой транзакции, после
// COMMIT получает конфликт (DO NOTHING), откатывает своё сообщение и читает
// уже сохранённое. Если первая транзакция откатилась (транзиентная ошибка),
// вторая просто продолжает — неуспешный результат не фиксируется.
func (r *MessageRepository) CreateIdempotent(ctx context.Context, msg *domain.Message, key, requestHash string, ttl time.Duration) (*domain.Message, bool, error) {
tx, err := r.pool.Begin(ctx)
if err != nil {
return nil, false, fmt.Errorf("begin tx: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
// Ключ старше TTL больше не защищает от повтора — освобождаем его.
const deleteExpired = `
DELETE FROM idempotency_keys
WHERE user_id = $1::uuid AND chat_id = $2::uuid AND key = $3
AND created_at < now() - make_interval(secs => $4)
`
if _, err := tx.Exec(ctx, deleteExpired, msg.SenderID, msg.ChatID, key, ttl.Seconds()); err != nil {
return nil, false, fmt.Errorf("delete expired key: %w", err)
}
const insertMsg = `
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
`
if _, err := tx.Exec(ctx, insertMsg, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil {
return nil, false, fmt.Errorf("insert message: %w", err)
}
const insertKey = `
INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id)
VALUES ($1::uuid, $2::uuid, $3, $4, $5::uuid)
ON CONFLICT (user_id, chat_id, key) DO NOTHING
`
tag, err := tx.Exec(ctx, insertKey, msg.SenderID, msg.ChatID, key, requestHash, msg.ID)
if err != nil {
return nil, false, fmt.Errorf("insert idempotency key: %w", err)
}
if tag.RowsAffected() == 1 {
if err := tx.Commit(ctx); err != nil {
return nil, false, fmt.Errorf("commit tx: %w", err)
}
return msg, true, nil
}
// Ключ уже занят подтверждённой записью: наше сообщение не сохраняем.
_ = tx.Rollback(ctx)
const selectStored = `
SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at
FROM idempotency_keys k
JOIN messages m ON m.id = k.message_id
WHERE k.user_id = $1::uuid AND k.chat_id = $2::uuid AND k.key = $3
`
var storedHash string
var m domain.Message
err = r.pool.QueryRow(ctx, selectStored, msg.SenderID, msg.ChatID, key).
Scan(&storedHash, &m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt)
if err != nil {
return nil, false, fmt.Errorf("select stored message: %w", err)
}
if storedHash != requestHash {
return nil, false, repository.ErrConflict
}
return &m, false, nil
}
// DeleteExpiredKeys удаляет ключи старше TTL. Безопасно выполнять с любой реплики.
func (r *MessageRepository) DeleteExpiredKeys(ctx context.Context, ttl time.Duration) (int64, error) {
const q = `DELETE FROM idempotency_keys WHERE created_at < now() - make_interval(secs => $1)`
tag, err := r.pool.Exec(ctx, q, ttl.Seconds())
if err != nil {
return 0, fmt.Errorf("delete expired keys: %w", err)
}
return tag.RowsAffected(), nil
}
func (r *MessageRepository) ListByChat(ctx context.Context, chatID string, cursor time.Time, cursorID string, limit int) ([]*domain.Message, error) {
const q = `
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1::uuid
AND (created_at, id) > ($2::timestamptz, $3::uuid)
ORDER BY created_at, id
LIMIT $4
`
rows, err := r.pool.Query(ctx, q, chatID, cursor, cursorID, limit)
if err != nil {
return nil, fmt.Errorf("list messages: %w", err)
}
defer rows.Close()
msgs := []*domain.Message{}
for rows.Next() {
var m domain.Message
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
return nil, fmt.Errorf("scan message: %w", err)
}
msgs = append(msgs, &m)
}
return msgs, rows.Err()
}
+39
View File
@@ -0,0 +1,39 @@
package postgres
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
// NewPool создаёт пул соединений с PostgreSQL.
// Параметры ограничены, чтобы не перегрузить БД.
func NewPool(ctx context.Context, dsn string, maxConns int32) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, fmt.Errorf("parse dsn: %w", err)
}
cfg.MaxConns = maxConns
cfg.MinConns = min(2, maxConns)
cfg.MaxConnIdleTime = 5 * time.Minute
cfg.MaxConnLifetime = 30 * time.Minute
cfg.HealthCheckPeriod = 30 * time.Second
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, fmt.Errorf("create pool: %w", err)
}
// Проверяем, что соединение работает.
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if err := pool.Ping(pingCtx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping: %w", err)
}
return pool, nil
}
+77
View File
@@ -0,0 +1,77 @@
package postgres
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/charawein/mtusi2026lab3/internal/domain"
"github.com/charawein/mtusi2026lab3/internal/repository"
)
type UserRepository struct {
pool *pgxpool.Pool
}
func NewUserRepository(pool *pgxpool.Pool) *UserRepository {
return &UserRepository{pool: pool}
}
func (r *UserRepository) Create(ctx context.Context, user *domain.User, passwordHash string) error {
const q = `
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ($1::uuid, $2, $3, $4, $5)
`
_, err := r.pool.Exec(ctx, q, user.ID, user.Username, user.DisplayName, passwordHash, user.CreatedAt)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return repository.ErrConflict
}
return fmt.Errorf("insert user: %w", err)
}
return nil
}
func (r *UserRepository) GetByID(ctx context.Context, id string) (*domain.User, error) {
const q = `SELECT id, username, display_name, created_at FROM users WHERE id = $1::uuid`
var u domain.User
err := r.pool.QueryRow(ctx, q, id).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, repository.ErrNotFound
}
return nil, fmt.Errorf("select user by id: %w", err)
}
return &u, nil
}
func (r *UserRepository) GetByUsername(ctx context.Context, username string) (*domain.User, error) {
const q = `SELECT id, username, display_name, created_at FROM users WHERE username = $1`
var u domain.User
err := r.pool.QueryRow(ctx, q, username).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, repository.ErrNotFound
}
return nil, fmt.Errorf("select user by username: %w", err)
}
return &u, nil
}
func (r *UserRepository) GetPasswordHash(ctx context.Context, userID string) (string, error) {
const q = `SELECT password_hash FROM users WHERE id = $1::uuid`
var hash string
err := r.pool.QueryRow(ctx, q, userID).Scan(&hash)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return "", repository.ErrNotFound
}
return "", fmt.Errorf("select password hash: %w", err)
}
return hash, nil
}
+111
View File
@@ -0,0 +1,111 @@
package redis
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"time"
"github.com/redis/go-redis/v9"
"github.com/charawein/mtusi2026lab3/internal/domain"
)
// Режимы инвалидации кэша истории (CACHE_INVALIDATION):
// - "scan" (поведение lab2): ключ без версии; запись делает INCR версии и
// удаляет ключи чата через SCAN — O(размер keyspace) запросов к Redis на запись;
// - "version": версия чата входит в ключ; запись делает только INCR, старые
// ключи становятся недостижимыми и истекают по TTL. O(1) на запись.
const (
InvalidationScan = "scan"
InvalidationVersion = "version"
)
type MessageCache struct {
client *redis.Client
versionedKeys bool
}
func NewMessageCache(client *redis.Client, mode string) *MessageCache {
return &MessageCache{client: client, versionedKeys: mode != InvalidationScan}
}
type cacheEntry struct {
Items []*domain.Message `json:"items"`
NextCursor string `json:"next_cursor"`
}
func (c *MessageCache) cacheKey(chatID string, version int64, cursor string, limit int) string {
if c.versionedKeys {
return fmt.Sprintf("messages:%s:v%d:%s:%d", chatID, version, cursor, limit)
}
return fmt.Sprintf("messages:%s:%s:%d", chatID, cursor, limit)
}
func versionKey(chatID string) string {
return "chat_version:" + chatID
}
// GetVersion возвращает текущую версию чата. 0, если ключа нет.
func (c *MessageCache) GetVersion(ctx context.Context, chatID string) int64 {
v, err := c.client.Get(ctx, versionKey(chatID)).Int64()
if err != nil {
return 0
}
return v
}
// IncrVersion увеличивает версию чата. Используется в Send для инвалидации.
func (c *MessageCache) IncrVersion(ctx context.Context, chatID string) int64 {
v, err := c.client.Incr(ctx, versionKey(chatID)).Result()
if err != nil {
slog.Warn("redis incr version failed", "chat_id", chatID, "err", err)
return 0
}
return v
}
func (c *MessageCache) Get(ctx context.Context, chatID string, version int64, cursor string, limit int) ([]*domain.Message, string, bool) {
raw, err := c.client.Get(ctx, c.cacheKey(chatID, version, cursor, limit)).Bytes()
if err != nil {
return nil, "", false
}
var e cacheEntry
if err := json.Unmarshal(raw, &e); err != nil {
return nil, "", false
}
return e.Items, e.NextCursor, true
}
func (c *MessageCache) Set(ctx context.Context, chatID string, version int64, cursor string, limit int, items []*domain.Message, next string) {
e := cacheEntry{Items: items, NextCursor: next}
raw, err := json.Marshal(e)
if err != nil {
slog.Warn("marshal cache entry failed", "err", err)
return
}
if err := c.client.Set(ctx, c.cacheKey(chatID, version, cursor, limit), raw, 30*time.Second).Err(); err != nil {
// Redis недоступен — не падаем, работаем без кэша.
slog.Warn("redis set failed", "chat_id", chatID, "err", err)
}
}
// OnWrite вызывается после успешной записи сообщения, до ответа клиенту.
// Ошибки Redis игнорируются — при недоступности кэш устареет по TTL.
func (c *MessageCache) OnWrite(ctx context.Context, chatID string) {
c.IncrVersion(ctx, chatID)
if !c.versionedKeys {
_ = c.Invalidate(ctx, chatID)
}
}
// Invalidate удаляет все ключи messages:{chatID}:* через SCAN.
func (c *MessageCache) Invalidate(ctx context.Context, chatID string) error {
pattern := fmt.Sprintf("messages:%s:*", chatID)
iter := c.client.Scan(ctx, 0, pattern, 100).Iterator()
for iter.Next(ctx) {
_ = c.client.Del(ctx, iter.Val()).Err()
}
return iter.Err()
}
+73
View File
@@ -0,0 +1,73 @@
package redis
import (
"context"
"errors"
"fmt"
"time"
"github.com/redis/go-redis/v9"
"github.com/charawein/mtusi2026lab3/internal/domain"
"github.com/charawein/mtusi2026lab3/internal/repository"
)
type SessionRepository struct {
client *redis.Client
}
func NewSessionRepository(client *redis.Client) *SessionRepository {
return &SessionRepository{client: client}
}
func (r *SessionRepository) Create(ctx context.Context, s *domain.Session) error {
key := "session:" + s.Token
ttl := time.Until(s.ExpiresAt)
if ttl <= 0 {
return fmt.Errorf("session already expired")
}
if err := r.client.Set(ctx, key, s.UserID, ttl).Err(); err != nil {
return fmt.Errorf("set session: %w", err)
}
return nil
}
func (r *SessionRepository) GetByToken(ctx context.Context, token string) (*domain.Session, error) {
key := "session:" + token
userID, err := r.client.Get(ctx, key).Result()
if err != nil {
if errors.Is(err, redis.Nil) {
return nil, repository.ErrNotFound
}
return nil, fmt.Errorf("get session: %w", err)
}
ttl, err := r.client.TTL(ctx, key).Result()
if err != nil {
return nil, fmt.Errorf("ttl: %w", err)
}
return &domain.Session{
Token: token,
UserID: userID,
ExpiresAt: time.Now().UTC().Add(ttl),
}, nil
}
func (r *SessionRepository) Delete(ctx context.Context, token string) error {
return r.client.Del(ctx, "session:"+token).Err()
}
func (r *SessionRepository) DeleteExpired(ctx context.Context) error {
return nil
}
func NewClient(ctx context.Context, url string) (*redis.Client, error) {
opts, err := redis.ParseURL(url)
if err != nil {
return nil, fmt.Errorf("parse redis url: %w", err)
}
client := redis.NewClient(opts)
if err := client.Ping(ctx).Err(); err != nil {
return nil, fmt.Errorf("ping redis: %w", err)
}
return client, nil
}
+55
View File
@@ -0,0 +1,55 @@
package repository
import (
"context"
"time"
"github.com/charawein/mtusi2026lab3/internal/domain"
)
var ErrNotFound = errNotFound{}
type errNotFound struct{}
func (errNotFound) Error() string { return "not found" }
var ErrConflict = errConflict{}
type errConflict struct{}
func (errConflict) Error() string { return "conflict" }
// UserRepository
type UserRepository interface {
Create(ctx context.Context, user *domain.User, passwordHash string) error
GetByID(ctx context.Context, id string) (*domain.User, error)
GetByUsername(ctx context.Context, username string) (*domain.User, error)
GetPasswordHash(ctx context.Context, userID string) (string, error)
}
// ChatRepository
type ChatRepository interface {
Create(ctx context.Context, chat *domain.Chat) error
GetByID(ctx context.Context, id string) (*domain.Chat, error)
IsMember(ctx context.Context, chatID, userID string) (bool, error)
ListByMember(ctx context.Context, userID string, cursor time.Time, cursorID string, limit int) ([]*domain.Chat, error)
}
// MessageRepository
type MessageRepository interface {
Create(ctx context.Context, msg *domain.Message) error
// CreateIdempotent атомарно создаёт сообщение и запись ключа идемпотентности.
// Если ключ уже есть с тем же requestHash — возвращает ранее созданное сообщение
// и created=false; с другим requestHash — ErrConflict.
CreateIdempotent(ctx context.Context, msg *domain.Message, key, requestHash string, ttl time.Duration) (stored *domain.Message, created bool, err error)
DeleteExpiredKeys(ctx context.Context, ttl time.Duration) (int64, error)
ListByChat(ctx context.Context, chatID string, cursor time.Time, cursorID string, limit int) ([]*domain.Message, error)
}
// SessionRepository
type SessionRepository interface {
Create(ctx context.Context, s *domain.Session) error
GetByToken(ctx context.Context, token string) (*domain.Session, error)
Delete(ctx context.Context, token string) error
DeleteExpired(ctx context.Context) error
}