github.com/prebid/prebid-server/v2@v2.18.0/stored_requests/caches/memory/maps.go (about)

     1  package memory
     2  
     3  import (
     4  	"encoding/json"
     5  	"sync"
     6  
     7  	"github.com/coocood/freecache"
     8  	"github.com/golang/glog"
     9  )
    10  
    11  // This file contains an interface and some wrapper types for various types of "map-like" structures
    12  // so that we can mix and match them inside the Cache implementation in cache.go.
    13  
    14  // Interface which abstracts the common operations of sync.Map and the freecache.Cache
    15  type mapLike interface {
    16  	Get(id string) (json.RawMessage, bool)
    17  	Set(id string, value json.RawMessage)
    18  	Delete(id string)
    19  }
    20  
    21  // sync.Map wrapper which implements the interface
    22  type pbsSyncMap struct {
    23  	*sync.Map
    24  }
    25  
    26  func (m *pbsSyncMap) Get(id string) (json.RawMessage, bool) {
    27  	val, ok := m.Map.Load(id)
    28  	if ok {
    29  		return val.(json.RawMessage), ok
    30  	} else {
    31  		return nil, ok
    32  	}
    33  }
    34  
    35  func (m *pbsSyncMap) Set(id string, value json.RawMessage) {
    36  	m.Map.Store(id, value)
    37  }
    38  
    39  func (m *pbsSyncMap) Delete(id string) {
    40  	m.Map.Delete(id)
    41  }
    42  
    43  // lruCache wrapper which implements the interface
    44  type pbsLRUCache struct {
    45  	*freecache.Cache
    46  	ttlSeconds int
    47  }
    48  
    49  func (m *pbsLRUCache) Get(id string) (json.RawMessage, bool) {
    50  	val, err := m.Cache.Get([]byte(id))
    51  	if err == nil {
    52  		return val, true
    53  	}
    54  	if err != freecache.ErrNotFound {
    55  		glog.Errorf("unexpected error from freecache: %v", err)
    56  	}
    57  	return val, false
    58  }
    59  
    60  func (m *pbsLRUCache) Set(id string, value json.RawMessage) {
    61  	if err := m.Cache.Set([]byte(id), value, m.ttlSeconds); err != nil {
    62  		glog.Errorf("error saving value in freecache: %v", err)
    63  	}
    64  }
    65  
    66  func (m *pbsLRUCache) Delete(id string) {
    67  	m.Cache.Del([]byte(id))
    68  }