cache.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Package cache is used for completion to not overflow the gateway with redundant search requests.
  2. package cache
  3. import (
  4. "sync"
  5. )
  6. type Cache struct {
  7. items sync.Map
  8. }
  9. func NewCache() *Cache {
  10. return &Cache{items: sync.Map{}}
  11. }
  12. func (c *Cache) Create(query string, value uint) {
  13. c.items.Store(query, value)
  14. }
  15. func (c *Cache) Exists(query string) (ok bool) {
  16. _, ok = c.items.Load(query)
  17. return
  18. }
  19. func (c *Cache) Get(query string) uint {
  20. if i, ok := c.items.Load(query); ok {
  21. return i.(uint)
  22. }
  23. return 0
  24. }
  25. // Invalidate is only needed when a member leaves and the search query reaches
  26. // the search limit.
  27. // "aa", "ab", "ac", ..., "ay" // where length is longer than the limit
  28. // if "ay" leaves, then "az" would not be loaded becaue it would not be
  29. // returned by the search results because of the search limit.
  30. func (c *Cache) Invalidate(name string, limit uint) {
  31. for name != "" {
  32. if c.Exists(name) && c.Get(name) >= limit {
  33. for name != "" {
  34. c.items.Delete(name)
  35. name = name[:len(name)-1]
  36. }
  37. }
  38. name = name[:len(name)-1]
  39. }
  40. }