lab2: fix review round 2 — cache versioning, UUID normalization, cursor validation, ready deps
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
@@ -28,6 +29,29 @@ func cacheKey(chatID, cursor string, limit int) string {
|
||||
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, cursor string, limit int) ([]*domain.Message, string, bool) {
|
||||
raw, err := c.client.Get(ctx, cacheKey(chatID, cursor, limit)).Bytes()
|
||||
if err != nil {
|
||||
@@ -42,11 +66,18 @@ func (c *MessageCache) Get(ctx context.Context, chatID, cursor string, limit int
|
||||
|
||||
func (c *MessageCache) Set(ctx context.Context, chatID, cursor string, limit int, items []*domain.Message, next string) {
|
||||
e := cacheEntry{Items: items, NextCursor: next}
|
||||
raw, _ := json.Marshal(e)
|
||||
_ = c.client.Set(ctx, cacheKey(chatID, cursor, limit), raw, 30*time.Second).Err()
|
||||
raw, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
slog.Warn("marshal cache entry failed", "err", err)
|
||||
return
|
||||
}
|
||||
if err := c.client.Set(ctx, cacheKey(chatID, cursor, limit), raw, 30*time.Second).Err(); err != nil {
|
||||
// Redis недоступен — не падаем, работаем без кэша.
|
||||
slog.Warn("redis set failed", "chat_id", chatID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Invalidate удаляет все ключи для чата через SCAN (безопасно на больших объёмах).
|
||||
// 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()
|
||||
|
||||
Reference in New Issue
Block a user