fixed read-after-write after failed cache invalidation and API restart

This commit is contained in:
Нурлыгаянова Екатерина
2026-10-29 15:18:44 +03:00
parent 5021df4ea8
commit ee87d17cb9
13 changed files with 510 additions and 78 deletions
+104 -24
View File
@@ -35,8 +35,17 @@ type Source interface {
HistoryPage(ctx context.Context, chatID, cursor string, limit int) (domain.Page[domain.Message], error)
}
// Outbox хранит долг инвалидации в источнике истины, чтобы он пережил
// рестарт API. Без него отложенная инвалидация живёт только в памяти.
type Outbox interface {
AddPendingInvalidation(ctx context.Context, chatID string) (int64, error)
PendingInvalidations(ctx context.Context) (map[string]int64, error)
ResolvePendingInvalidation(ctx context.Context, chatID string, gen int64) error
}
type Options struct {
Mode string
Outbox Outbox
PageTTL time.Duration
LockTTL time.Duration
FillDelay time.Duration
@@ -45,6 +54,14 @@ type Options struct {
var _ store.MessageStore = (*Messages)(nil)
// pendingEntry — несброшенная версия чата. seq меняется при каждом новом
// сбое: повтор снимает запись, только если seq не изменился с его снимка.
// gen — поколение строки в Outbox (0 — не записана).
type pendingEntry struct {
seq uint64
gen int64
}
type Messages struct {
src Source
rdb *redis.Client
@@ -53,9 +70,13 @@ type Messages struct {
log *slog.Logger
downUntil atomic.Int64
// loaded: долг инвалидации из Outbox прочитан. До этого любой чат может
// иметь устаревшую версию, поэтому все чтения идут мимо кэша.
loaded atomic.Bool
mu sync.Mutex
pending map[string]struct{}
pending map[string]pendingEntry
seq uint64
stop chan struct{}
done chan struct{}
}
@@ -85,10 +106,11 @@ func New(src Source, rdb *redis.Client, opt Options) *Messages {
rdb: rdb,
opt: opt,
log: opt.Logger,
pending: make(map[string]struct{}),
pending: make(map[string]pendingEntry),
stop: make(chan struct{}),
done: make(chan struct{}),
}
m.loaded.Store(opt.Outbox == nil || opt.Mode != ModeSafe)
go m.retryLoop()
return m
}
@@ -136,7 +158,7 @@ func (m *Messages) AddMessage(ctx context.Context, callerID, chatID, text string
case ModeSafe:
if err := m.rdb.Del(ictx, verKey(chatID)).Err(); err != nil {
m.markDown(err)
m.addPending(chatID)
m.addPending(ictx, chatID)
}
}
return msg, nil
@@ -285,15 +307,39 @@ func (m *Messages) fill(ctx context.Context, key, chatID, cursor string, limit i
return page, nil
}
func (m *Messages) addPending(chatID string) {
// addPending вызывается до ответа 201: после него чат читается мимо кэша,
// пока версия не будет сброшена, в том числе после рестарта API.
func (m *Messages) addPending(ctx context.Context, chatID string) {
m.markPending(chatID, 0)
if m.opt.Outbox == nil {
m.log.Warn("history cache invalidation deferred", slog.String("chat_id", chatID))
return
}
gen, err := m.opt.Outbox.AddPendingInvalidation(ctx, chatID)
if err != nil {
m.log.Error("history cache invalidation deferred in memory only, lost on restart",
slog.String("chat_id", chatID), slog.Any("err", err))
return
}
m.markPending(chatID, gen)
m.log.Warn("history cache invalidation deferred",
slog.String("chat_id", chatID), slog.Int64("gen", gen))
}
// markPending всегда выдаёт новый seq, чтобы повтор, начатый раньше, не снял
// запись. gen не уменьшается.
func (m *Messages) markPending(chatID string, gen int64) {
m.mu.Lock()
m.pending[chatID] = struct{}{}
m.seq++
e := m.pending[chatID]
e.seq = m.seq
e.gen = max(e.gen, gen)
m.pending[chatID] = e
m.mu.Unlock()
m.log.Warn("history cache invalidation deferred", slog.String("chat_id", chatID))
}
func (m *Messages) bypass(chatID string) bool {
if m.isDown() {
if m.isDown() || !m.loaded.Load() {
return true
}
m.mu.Lock()
@@ -302,36 +348,70 @@ func (m *Messages) bypass(chatID string) bool {
return ok
}
func (m *Messages) loadPending() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
rows, err := m.opt.Outbox.PendingInvalidations(ctx)
if err != nil {
m.log.Warn("history cache: pending invalidations not loaded, bypassing", slog.Any("err", err))
return
}
for id, gen := range rows {
m.markPending(id, gen)
}
m.loaded.Store(true)
if len(rows) > 0 {
m.log.Info("history cache: pending invalidations loaded", slog.Int("chats", len(rows)))
}
}
func (m *Messages) retryLoop() {
defer close(m.done)
t := time.NewTicker(retryInterval)
defer t.Stop()
for {
if !m.loaded.Load() {
m.loadPending()
}
m.retryPending()
select {
case <-m.stop:
return
case <-t.C:
}
m.mu.Lock()
chats := make([]string, 0, len(m.pending))
for id := range m.pending {
chats = append(chats, id)
}
m.mu.Unlock()
for _, id := range chats {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
err := m.rdb.Del(ctx, verKey(id)).Err()
cancel()
if err != nil {
break
}
m.mu.Lock()
delete(m.pending, id)
m.mu.Unlock()
}
}
}
func (m *Messages) retryPending() {
m.mu.Lock()
chats := make(map[string]pendingEntry, len(m.pending))
for id, e := range m.pending {
chats[id] = e
}
m.mu.Unlock()
for id, e := range chats {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
err := m.rdb.Del(ctx, verKey(id)).Err()
if err == nil && e.gen > 0 {
err = m.opt.Outbox.ResolvePendingInvalidation(ctx, id, e.gen)
}
cancel()
if err != nil {
return
}
m.resolved(id, e)
}
}
// resolved снимает запись, если после снимка e не было нового сбоя.
func (m *Messages) resolved(chatID string, e pendingEntry) {
m.mu.Lock()
if m.pending[chatID].seq == e.seq {
delete(m.pending, chatID)
}
m.mu.Unlock()
}
func (m *Messages) isDown() bool {
return time.Now().UnixNano() < m.downUntil.Load()
}