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.

cache_twoqueue.go 4.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package cache
  5. import (
  6. "strconv"
  7. "sync"
  8. "time"
  9. "code.gitea.io/gitea/modules/json"
  10. mc "gitea.com/go-chi/cache"
  11. lru "github.com/hashicorp/golang-lru"
  12. )
  13. // TwoQueueCache represents a LRU 2Q cache adapter implementation
  14. type TwoQueueCache struct {
  15. lock sync.Mutex
  16. cache *lru.TwoQueueCache
  17. interval int
  18. }
  19. // TwoQueueCacheConfig describes the configuration for TwoQueueCache
  20. type TwoQueueCacheConfig struct {
  21. Size int `ini:"SIZE" json:"size"`
  22. RecentRatio float64 `ini:"RECENT_RATIO" json:"recent_ratio"`
  23. GhostRatio float64 `ini:"GHOST_RATIO" json:"ghost_ratio"`
  24. }
  25. // MemoryItem represents a memory cache item.
  26. type MemoryItem struct {
  27. Val interface{}
  28. Created int64
  29. Timeout int64
  30. }
  31. func (item *MemoryItem) hasExpired() bool {
  32. return item.Timeout > 0 &&
  33. (time.Now().Unix()-item.Created) >= item.Timeout
  34. }
  35. var _ mc.Cache = &TwoQueueCache{}
  36. // Put puts value into cache with key and expire time.
  37. func (c *TwoQueueCache) Put(key string, val interface{}, timeout int64) error {
  38. item := &MemoryItem{
  39. Val: val,
  40. Created: time.Now().Unix(),
  41. Timeout: timeout,
  42. }
  43. c.lock.Lock()
  44. defer c.lock.Unlock()
  45. c.cache.Add(key, item)
  46. return nil
  47. }
  48. // Get gets cached value by given key.
  49. func (c *TwoQueueCache) Get(key string) interface{} {
  50. c.lock.Lock()
  51. defer c.lock.Unlock()
  52. cached, ok := c.cache.Get(key)
  53. if !ok {
  54. return nil
  55. }
  56. item, ok := cached.(*MemoryItem)
  57. if !ok || item.hasExpired() {
  58. c.cache.Remove(key)
  59. return nil
  60. }
  61. return item.Val
  62. }
  63. // Delete deletes cached value by given key.
  64. func (c *TwoQueueCache) Delete(key string) error {
  65. c.lock.Lock()
  66. defer c.lock.Unlock()
  67. c.cache.Remove(key)
  68. return nil
  69. }
  70. // Incr increases cached int-type value by given key as a counter.
  71. func (c *TwoQueueCache) Incr(key string) error {
  72. c.lock.Lock()
  73. defer c.lock.Unlock()
  74. cached, ok := c.cache.Get(key)
  75. if !ok {
  76. return nil
  77. }
  78. item, ok := cached.(*MemoryItem)
  79. if !ok || item.hasExpired() {
  80. c.cache.Remove(key)
  81. return nil
  82. }
  83. var err error
  84. item.Val, err = mc.Incr(item.Val)
  85. return err
  86. }
  87. // Decr decreases cached int-type value by given key as a counter.
  88. func (c *TwoQueueCache) Decr(key string) error {
  89. c.lock.Lock()
  90. defer c.lock.Unlock()
  91. cached, ok := c.cache.Get(key)
  92. if !ok {
  93. return nil
  94. }
  95. item, ok := cached.(*MemoryItem)
  96. if !ok || item.hasExpired() {
  97. c.cache.Remove(key)
  98. return nil
  99. }
  100. var err error
  101. item.Val, err = mc.Decr(item.Val)
  102. return err
  103. }
  104. // IsExist returns true if cached value exists.
  105. func (c *TwoQueueCache) IsExist(key string) bool {
  106. c.lock.Lock()
  107. defer c.lock.Unlock()
  108. cached, ok := c.cache.Peek(key)
  109. if !ok {
  110. return false
  111. }
  112. item, ok := cached.(*MemoryItem)
  113. if !ok || item.hasExpired() {
  114. c.cache.Remove(key)
  115. return false
  116. }
  117. return true
  118. }
  119. // Flush deletes all cached data.
  120. func (c *TwoQueueCache) Flush() error {
  121. c.lock.Lock()
  122. defer c.lock.Unlock()
  123. c.cache.Purge()
  124. return nil
  125. }
  126. func (c *TwoQueueCache) checkAndInvalidate(key interface{}) {
  127. c.lock.Lock()
  128. defer c.lock.Unlock()
  129. cached, ok := c.cache.Peek(key)
  130. if !ok {
  131. return
  132. }
  133. item, ok := cached.(*MemoryItem)
  134. if !ok || item.hasExpired() {
  135. c.cache.Remove(item)
  136. }
  137. }
  138. func (c *TwoQueueCache) startGC() {
  139. if c.interval < 0 {
  140. return
  141. }
  142. for _, key := range c.cache.Keys() {
  143. c.checkAndInvalidate(key)
  144. }
  145. time.AfterFunc(time.Duration(c.interval)*time.Second, c.startGC)
  146. }
  147. // StartAndGC starts GC routine based on config string settings.
  148. func (c *TwoQueueCache) StartAndGC(opts mc.Options) error {
  149. var err error
  150. size := 50000
  151. if opts.AdapterConfig != "" {
  152. size, err = strconv.Atoi(opts.AdapterConfig)
  153. }
  154. if err != nil {
  155. if !json.Valid([]byte(opts.AdapterConfig)) {
  156. return err
  157. }
  158. cfg := &TwoQueueCacheConfig{
  159. Size: 50000,
  160. RecentRatio: lru.Default2QRecentRatio,
  161. GhostRatio: lru.Default2QGhostEntries,
  162. }
  163. _ = json.Unmarshal([]byte(opts.AdapterConfig), cfg)
  164. c.cache, err = lru.New2QParams(cfg.Size, cfg.RecentRatio, cfg.GhostRatio)
  165. } else {
  166. c.cache, err = lru.New2Q(size)
  167. }
  168. c.interval = opts.Interval
  169. if c.interval > 0 {
  170. go c.startGC()
  171. }
  172. return err
  173. }
  174. // Ping tests if the cache is alive.
  175. func (c *TwoQueueCache) Ping() error {
  176. return mc.GenericPing(c)
  177. }
  178. func init() {
  179. mc.Register("twoqueue", &TwoQueueCache{})
  180. }