You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
107 lines
2.2 KiB
107 lines
2.2 KiB
package cache
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
badger "github.com/dgraph-io/badger/v2"
|
|
// log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
type Reader interface {
|
|
Get(key string) (*string, error)
|
|
}
|
|
|
|
type Writer interface {
|
|
Set(key string, value string) error
|
|
SetWithTTL(key string, value string, ttl int) error
|
|
}
|
|
|
|
type Cache interface {
|
|
Reader
|
|
Writer
|
|
Close()
|
|
}
|
|
|
|
type bCache struct {
|
|
db *badger.DB
|
|
// logger *log.Entry
|
|
}
|
|
|
|
func NewCache(db *badger.DB) Cache {
|
|
return &bCache{
|
|
db: db,
|
|
}
|
|
}
|
|
|
|
func (cache bCache) close() {
|
|
cache.db.Close()
|
|
}
|
|
|
|
// Get gets a cache entry by key
|
|
func (cache bCache) Get(key string) (*string, error) {
|
|
var result []byte
|
|
if err := cache.db.View(func(txn *badger.Txn) error {
|
|
item, err := txn.Get([]byte(key))
|
|
if err != nil {
|
|
if err.Error() != "Key not found" {
|
|
return nil
|
|
}
|
|
}
|
|
if err == nil || (item != nil && !item.IsDeletedOrExpired()) {
|
|
if err := item.Value(func(val []byte) error {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
result = append([]byte{}, val...)
|
|
return nil
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}); err != nil {
|
|
return nil, err
|
|
}
|
|
r := string(result)
|
|
return &r, nil
|
|
}
|
|
|
|
// SetWithTTL sets a cache entry
|
|
func (cache bCache) Set(key string, value string) error {
|
|
if err := cache.db.Update(func(txn *badger.Txn) error {
|
|
err := txn.Set([]byte(key), []byte(value))
|
|
return err
|
|
}); err != nil {
|
|
// cache.logger.WithFields(log.Fields{"module": "cache"}).Errorln(err.Error())
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// SetWithTTL sets a cache entry with defined ttl
|
|
func (cache bCache) SetWithTTL(key string, value string, ttl int) error {
|
|
if err := cache.db.Update(func(txn *badger.Txn) error {
|
|
e := badger.NewEntry([]byte(key), []byte(value)).WithTTL(time.Duration(ttl) * time.Second)
|
|
err := txn.SetEntry(e)
|
|
return err
|
|
}); err != nil {
|
|
// cache.logger.WithFields(log.Fields{"module": "cache"}).Errorln(err.Error())
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (cache bCache) Close() {
|
|
cache.close()
|
|
}
|
|
|
|
func Bootstrap() (Cache, error) {
|
|
db, err := badger.Open(badger.DefaultOptions("").WithInMemory(true))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("Unable to open badger db: %s", err.Error())
|
|
}
|
|
|
|
cache := NewCache(db)
|
|
return cache, err
|
|
}
|