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:
@@ -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()
|
||||
}
|
||||
Reference in New Issue
Block a user