summaryrefslogtreecommitdiffstats
path: root/modules/cache/cache_twoqueue.go
blob: 275b73f068f29f157b857a26ca6b71045bc6cc91 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// Copyright 2021 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package cache

import (
	"strconv"
	"sync"
	"time"

	"code.gitea.io/gitea/modules/json"

	mc "gitea.com/go-chi/cache"
	lru "github.com/hashicorp/golang-lru"
)

// TwoQueueCache represents a LRU 2Q cache adapter implementation
type TwoQueueCache struct {
	lock     sync.Mutex
	cache    *lru.TwoQueueCache
	interval int
}

// TwoQueueCacheConfig describes the configuration for TwoQueueCache
type TwoQueueCacheConfig struct {
	Size        int     `ini:"SIZE" json:"size"`
	RecentRatio float64 `ini:"RECENT_RATIO" json:"recent_ratio"`
	GhostRatio  float64 `ini:"GHOST_RATIO" json:"ghost_ratio"`
}

// MemoryItem represents a memory cache item.
type MemoryItem struct {
	Val     interface{}
	Created int64
	Timeout int64
}

func (item *MemoryItem) hasExpired() bool {
	return item.Timeout > 0 &&
		(time.Now().Unix()-item.Created) >= item.Timeout
}

var _ mc.Cache = &TwoQueueCache{}

// Put puts value into cache with key and expire time.
func (c *TwoQueueCache) Put(key string, val interface{}, timeout int64) error {
	item := &MemoryItem{
		Val:     val,
		Created: time.Now().Unix(),
		Timeout: timeout,
	}
	c.lock.Lock()
	defer c.lock.Unlock()
	c.cache.Add(key, item)
	return nil
}

// Get gets cached value by given key.
func (c *TwoQueueCache) Get(key string) interface{} {
	c.lock.Lock()
	defer c.lock.Unlock()
	cached, ok := c.cache.Get(key)
	if !ok {
		return nil
	}
	item, ok := cached.(*MemoryItem)

	if !ok || item.hasExpired() {
		c.cache.Remove(key)
		return nil
	}

	return item.Val
}

// Delete deletes cached value by given key.
func (c *TwoQueueCache) Delete(key string) error {
	c.lock.Lock()
	defer c.lock.Unlock()
	c.cache.Remove(key)
	return nil
}

// Incr increases cached int-type value by given key as a counter.
func (c *TwoQueueCache) Incr(key string) error {
	c.lock.Lock()
	defer c.lock.Unlock()
	cached, ok := c.cache.Get(key)
	if !ok {
		return nil
	}
	item, ok := cached.(*MemoryItem)

	if !ok || item.hasExpired() {
		c.cache.Remove(key)
		return nil
	}

	var err error
	item.Val, err = mc.Incr(item.Val)
	return err
}

// Decr decreases cached int-type value by given key as a counter.
func (c *TwoQueueCache) Decr(key string) error {
	c.lock.Lock()
	defer c.lock.Unlock()
	cached, ok := c.cache.Get(key)
	if !ok {
		return nil
	}
	item, ok := cached.(*MemoryItem)

	if !ok || item.hasExpired() {
		c.cache.Remove(key)
		return nil
	}

	var err error
	item.Val, err = mc.Decr(item.Val)
	return err
}

// IsExist returns true if cached value exists.
func (c *TwoQueueCache) IsExist(key string) bool {
	c.lock.Lock()
	defer c.lock.Unlock()
	cached, ok := c.cache.Peek(key)
	if !ok {
		return false
	}
	item, ok := cached.(*MemoryItem)
	if !ok || item.hasExpired() {
		c.cache.Remove(key)
		return false
	}

	return true
}

// Flush deletes all cached data.
func (c *TwoQueueCache) Flush() error {
	c.lock.Lock()
	defer c.lock.Unlock()
	c.cache.Purge()
	return nil
}

func (c *TwoQueueCache) checkAndInvalidate(key interface{}) {
	c.lock.Lock()
	defer c.lock.Unlock()
	cached, ok := c.cache.Peek(key)
	if !ok {
		return
	}
	item, ok := cached.(*MemoryItem)
	if !ok || item.hasExpired() {
		c.cache.Remove(item)
	}
}

func (c *TwoQueueCache) startGC() {
	if c.interval < 0 {
		return
	}
	for _, key := range c.cache.Keys() {
		c.checkAndInvalidate(key)
	}
	time.AfterFunc(time.Duration(c.interval)*time.Second, c.startGC)
}

// StartAndGC starts GC routine based on config string settings.
func (c *TwoQueueCache) StartAndGC(opts mc.Options) error {
	var err error
	size := 50000
	if opts.AdapterConfig != "" {
		size, err = strconv.Atoi(opts.AdapterConfig)
	}
	if err != nil {
		if !json.Valid([]byte(opts.AdapterConfig)) {
			return err
		}

		cfg := &TwoQueueCacheConfig{
			Size:        50000,
			RecentRatio: lru.Default2QRecentRatio,
			GhostRatio:  lru.Default2QGhostEntries,
		}
		_ = json.Unmarshal([]byte(opts.AdapterConfig), cfg)
		c.cache, err = lru.New2QParams(cfg.Size, cfg.RecentRatio, cfg.GhostRatio)
	} else {
		c.cache, err = lru.New2Q(size)
	}
	c.interval = opts.Interval
	if c.interval > 0 {
		go c.startGC()
	}
	return err
}

func init() {
	mc.Register("twoqueue", &TwoQueueCache{})
}