Debian Codegraph @

internal/holsterv4/collections/ttlmap.go

raw
1 /*
2 Copyright 2017 Mailgun Technologies Inc
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16 package collections
17
18 import (
19 "fmt"
20 "sync"
21 "time"
22
23 "github.com/vulcand/oxy/v2/internal/holsterv4/clock"
24 )
25
26 type TTLMap struct {
27 // Optionally specifies a callback function to be
28 // executed when an entry has expired
29 OnExpire func(key string, i interface{})
30
31 capacity int
32 elements map[string]*mapElement
33 expiryTimes *PriorityQueue
34 mutex *sync.RWMutex
35 }
36
37 type mapElement struct {
38 key string
39 value interface{}
40 heapEl *PQItem
41 }
42
43 func NewTTLMap(capacity int) *TTLMap {
44 if capacity <= 0 {
45 capacity = 0
46 }
47
48 return &TTLMap{
49 capacity: capacity,
50 elements: make(map[string]*mapElement),
51 expiryTimes: NewPriorityQueue(),
52 mutex: &sync.RWMutex{},
53 }
54 }
55
56 func (m *TTLMap) Set(key string, value interface{}, ttlSeconds int) error {
57 expiryTime, err := m.toEpochSeconds(ttlSeconds)
58 if err != nil {
59 return err
60 }
61 m.mutex.Lock()
62 defer m.mutex.Unlock()
63 return m.set(key, value, expiryTime)
64 }
65
66 func (m *TTLMap) Len() int {
67 m.mutex.RLock()
68 defer m.mutex.RUnlock()
69 return len(m.elements)
70 }
71
72 func (m *TTLMap) Get(key string) (interface{}, bool) {
73 value, mapEl, expired := m.lockNGet(key)
74 if mapEl == nil {
75 return nil, false
76 }
77 if expired {
78 m.lockNDel(mapEl)
79 return nil, false
80 }
81 return value, true
82 }
83
84 func (m *TTLMap) Increment(key string, value int, ttlSeconds int) (int, error) {
85 expiryTime, err := m.toEpochSeconds(ttlSeconds)
86 if err != nil {
87 return 0, err
88 }
89
90 m.mutex.Lock()
91 defer m.mutex.Unlock()
92
93 mapEl, expired := m.get(key)
94 if mapEl == nil || expired {
95 m.set(key, value, expiryTime)
96 return value, nil
97 }
98
99 currentValue, ok := mapEl.value.(int)
100 if !ok {
101 return 0, fmt.Errorf("Expected existing value to be integer, got %T", mapEl.value)
102 }
103
104 currentValue += value
105 m.set(key, currentValue, expiryTime)
106 return currentValue, nil
107 }
108
109 func (m *TTLMap) GetInt(key string) (int, bool, error) {
110 valueI, exists := m.Get(key)
111 if !exists {
112 return 0, false, nil
113 }
114 value, ok := valueI.(int)
115 if !ok {
116 return 0, false, fmt.Errorf("Expected existing value to be integer, got %T", valueI)
117 }
118 return value, true, nil
119 }
120
121 func (m *TTLMap) set(key string, value interface{}, expiryTime int) error {
122 if mapEl, ok := m.elements[key]; ok {
123 mapEl.value = value
124 m.expiryTimes.Update(mapEl.heapEl, expiryTime)
125 return nil
126 }
127
128 if len(m.elements) >= m.capacity {
129 m.freeSpace(1)
130 }
131 heapEl := &PQItem{
132 Priority: expiryTime,
133 }
134 mapEl := &mapElement{
135 key: key,
136 value: value,
137 heapEl: heapEl,
138 }
139 heapEl.Value = mapEl
140 m.elements[key] = mapEl
141 m.expiryTimes.Push(heapEl)
142 return nil
143 }
144
145 func (m *TTLMap) lockNGet(key string) (value interface{}, mapEl *mapElement, expired bool) {
146 m.mutex.RLock()
147 defer m.mutex.RUnlock()
148
149 mapEl, expired = m.get(key)
150 value = nil
151 if mapEl != nil {
152 value = mapEl.value
153 }
154 return value, mapEl, expired
155 }
156
157 func (m *TTLMap) get(key string) (*mapElement, bool) {
158 mapEl, ok := m.elements[key]
159 if !ok {
160 return nil, false
161 }
162 now := int(clock.Now().Unix())
163 expired := mapEl.heapEl.Priority <= now
164 return mapEl, expired
165 }
166
167 func (m *TTLMap) lockNDel(mapEl *mapElement) {
168 m.mutex.Lock()
169 defer m.mutex.Unlock()
170
171 // Map element could have been updated. Now that we have a lock
172 // retrieve it again and check if it is still expired.
173 var ok bool
174 if mapEl, ok = m.elements[mapEl.key]; !ok {
175 return
176 }
177 now := int(clock.Now().Unix())
178 if mapEl.heapEl.Priority > now {
179 return
180 }
181
182 if m.OnExpire != nil {
183 m.OnExpire(mapEl.key, mapEl.value)
184 }
185
186 delete(m.elements, mapEl.key)
187 m.expiryTimes.Remove(mapEl.heapEl)
188 }
189
190 func (m *TTLMap) freeSpace(count int) {
191 removed := m.RemoveExpired(count)
192 if removed >= count {
193 return
194 }
195 m.RemoveLastUsed(count - removed)
196 }
197
198 func (m *TTLMap) RemoveExpired(iterations int) int {
199 removed := 0
200 now := int(clock.Now().Unix())
201 for i := 0; i < iterations; i += 1 {
202 if len(m.elements) == 0 {
203 break
204 }
205 heapEl := m.expiryTimes.Peek()
206 if heapEl.Priority > now {
207 break
208 }
209 m.expiryTimes.Pop()
210 mapEl := heapEl.Value.(*mapElement)
211 delete(m.elements, mapEl.key)
212 removed += 1
213 }
214 return removed
215 }
216
217 func (m *TTLMap) RemoveLastUsed(iterations int) {
218 for i := 0; i < iterations; i += 1 {
219 if len(m.elements) == 0 {
220 return
221 }
222 heapEl := m.expiryTimes.Pop()
223 mapEl := heapEl.Value.(*mapElement)
224 delete(m.elements, mapEl.key)
225 }
226 }
227
228 func (m *TTLMap) toEpochSeconds(ttlSeconds int) (int, error) {
229 if ttlSeconds <= 0 {
230 return 0, fmt.Errorf("ttlSeconds should be >= 0, got %d", ttlSeconds)
231 }
232 return int(clock.Now().Add(time.Second * time.Duration(ttlSeconds)).Unix()), nil
233 }