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

     1  package memory
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"sync"
     7  
     8  	"github.com/coocood/freecache"
     9  	"github.com/golang/glog"
    10  	"github.com/prebid/prebid-server/v2/stored_requests"
    11  )
    12  
    13  // NewCache returns an in-memory Cache which evicts items if:
    14  //
    15  // 1. They haven't been used within the TTL.
    16  // 2. The cache is too large. This will cause the least recently used items to be evicted.
    17  //
    18  // For no TTL, use ttlSeconds <= 0
    19  func NewCache(size int, ttl int, dataType string) stored_requests.CacheJSON {
    20  	if ttl > 0 && size <= 0 {
    21  		// a positive ttl indicates "LRU" cache type, while unlimited size indicates an "unbounded" cache type
    22  		glog.Fatalf("unbounded in-memory %s cache with TTL not allowed. Config validation should have caught this. Failing fast because something is buggy.", dataType)
    23  	}
    24  	if size > 0 {
    25  		glog.Infof("Using a Stored %s in-memory cache. Max size: %d bytes. TTL: %d seconds.", dataType, size, ttl)
    26  		return &cache{
    27  			dataType: dataType,
    28  			cache: &pbsLRUCache{
    29  				Cache:      freecache.NewCache(size),
    30  				ttlSeconds: ttl,
    31  			},
    32  		}
    33  	} else {
    34  		glog.Infof("Using an unbounded Stored %s in-memory cache.", dataType)
    35  		return &cache{
    36  			dataType: dataType,
    37  			cache:    &pbsSyncMap{&sync.Map{}},
    38  		}
    39  	}
    40  }
    41  
    42  type cache struct {
    43  	dataType string
    44  	cache    mapLike
    45  }
    46  
    47  func (c *cache) Get(ctx context.Context, ids []string) (data map[string]json.RawMessage) {
    48  	data = make(map[string]json.RawMessage, len(ids))
    49  	for _, id := range ids {
    50  		if val, ok := c.cache.Get(id); ok {
    51  			data[id] = val
    52  		}
    53  	}
    54  	return
    55  }
    56  
    57  func (c *cache) Save(ctx context.Context, data map[string]json.RawMessage) {
    58  	for id, data := range data {
    59  		c.cache.Set(id, data)
    60  	}
    61  }
    62  
    63  func (c *cache) Invalidate(ctx context.Context, ids []string) {
    64  	for _, id := range ids {
    65  		c.cache.Delete(id)
    66  	}
    67  }