forked from mtusi2026/mtusi2026lab2
fixed read-after-write after failed cache invalidation and API restart
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// AddPendingInvalidation фиксирует, что версия кэша чата не сброшена.
|
||||
// Возвращает поколение записи для последующего compare-and-delete.
|
||||
func (m *Messages) AddPendingInvalidation(ctx context.Context, chatID string) (int64, error) {
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var gen int64
|
||||
err := m.pool.QueryRow(ctx, `
|
||||
INSERT INTO cache_invalidations (chat_id) VALUES ($1)
|
||||
ON CONFLICT (chat_id) DO UPDATE
|
||||
SET gen = nextval('cache_invalidations_gen_seq'), updated_at = now()
|
||||
RETURNING gen`,
|
||||
chatID,
|
||||
).Scan(&gen)
|
||||
if err != nil {
|
||||
return 0, mapErr(err)
|
||||
}
|
||||
return gen, nil
|
||||
}
|
||||
|
||||
func (m *Messages) PendingInvalidations(ctx context.Context) (map[string]int64, error) {
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := m.pool.Query(ctx, `SELECT chat_id::text, gen FROM cache_invalidations`)
|
||||
if err != nil {
|
||||
return nil, mapErr(err)
|
||||
}
|
||||
out := map[string]int64{}
|
||||
var (
|
||||
id string
|
||||
gen int64
|
||||
)
|
||||
_, err = pgx.ForEachRow(rows, []any{&id, &gen}, func() error {
|
||||
out[id] = gen
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, mapErr(err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ResolvePendingInvalidation удаляет запись, только если с момента чтения
|
||||
// не случилось нового сбоя (gen не изменился).
|
||||
func (m *Messages) ResolvePendingInvalidation(ctx context.Context, chatID string, gen int64) error {
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := m.pool.Exec(ctx,
|
||||
`DELETE FROM cache_invalidations WHERE chat_id = $1 AND gen = $2`,
|
||||
chatID, gen,
|
||||
)
|
||||
return mapErr(err)
|
||||
}
|
||||
Reference in New Issue
Block a user