Commit aed3d0d3 by Carl Bergquist Committed by GitHub

Remotecache: Avoid race condition in Set causing error on insert. (#17082)

* remotecache: avoid race condition in set

since set called the database twice without transactions another
operation could insert a value before the first operation completed.
which would raise an error on insert since the data have been inserted
by the other request.

closes #17079
parent d0ea98f6
......@@ -39,10 +39,14 @@ func (dc *databaseCache) Run(ctx context.Context) error {
}
func (dc *databaseCache) internalRunGC() {
err := dc.SQLStore.WithDbSession(context.Background(), func(session *sqlstore.DBSession) error {
now := getTime().Unix()
sql := `DELETE FROM cache_data WHERE (? - created_at) >= expires AND expires <> 0`
_, err := dc.SQLStore.NewSession().Exec(sql, now)
_, err := session.Exec(sql, now)
return err
})
if err != nil {
dc.log.Error("failed to run garbage collect", "error", err)
}
......@@ -80,14 +84,13 @@ func (dc *databaseCache) Get(key string) (interface{}, error) {
}
func (dc *databaseCache) Set(key string, value interface{}, expire time.Duration) error {
return dc.SQLStore.WithTransactionalDbSession(context.Background(), func(session *sqlstore.DBSession) error {
item := &cachedItem{Val: value}
data, err := encodeGob(item)
if err != nil {
return err
}
session := dc.SQLStore.NewSession()
var cacheHit CacheData
has, err := session.Where("cache_key = ?", key).Get(&cacheHit)
if err != nil {
......@@ -109,15 +112,20 @@ func (dc *databaseCache) Set(key string, value interface{}, expire time.Duration
}
return err
})
}
func (dc *databaseCache) Delete(key string) error {
return dc.SQLStore.WithDbSession(context.Background(), func(session *sqlstore.DBSession) error {
sql := "DELETE FROM cache_data WHERE cache_key=?"
_, err := dc.SQLStore.NewSession().Exec(sql, key)
_, err := session.Exec(sql, key)
return err
})
}
// CacheData is the struct representing the table in the database
type CacheData struct {
CacheKey string
Data []byte
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment