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

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