-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsharedmemorycache.go
More file actions
226 lines (183 loc) · 5.88 KB
/
sharedmemorycache.go
File metadata and controls
226 lines (183 loc) · 5.88 KB
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package maptilecache
import (
"strconv"
"sync"
"time"
)
const MAX_SIZE_BYTES_UNLIMITED = -1
type MemoryMap struct {
Tiles *map[string][]byte
Mutex *sync.RWMutex
}
type TileKeyHistoryItem struct {
MemoryMapKey string
TileKey string
}
type SharedMemoryCache struct {
MemoryMaps map[string]*MemoryMap
TileKeyHistory []TileKeyHistoryItem
MapMutes *sync.RWMutex
HistoryMutex *sync.RWMutex
SizeBytes int
MaxSizeBytes int
EnsureMaxSizeInterval time.Duration
DebugLogger func(string)
InfoLogger func(string)
WarnLogger func(string)
ErrorLogger func(string)
}
type SharedMemoryCacheConfig struct {
MaxSizeBytes int
EnsureMaxSizeInterval time.Duration
DebugLogger func(string)
InfoLogger func(string)
WarnLogger func(string)
ErrorLogger func(string)
}
func NewSharedMemoryCache(config SharedMemoryCacheConfig) *SharedMemoryCache {
m := SharedMemoryCache{
MemoryMaps: make(map[string]*MemoryMap),
TileKeyHistory: []TileKeyHistoryItem{},
MapMutes: &sync.RWMutex{},
HistoryMutex: &sync.RWMutex{},
MaxSizeBytes: config.MaxSizeBytes,
EnsureMaxSizeInterval: config.EnsureMaxSizeInterval,
DebugLogger: config.DebugLogger,
InfoLogger: config.InfoLogger,
WarnLogger: config.WarnLogger,
ErrorLogger: config.ErrorLogger,
}
if m.MaxSizeBytes < 0 {
m.MaxSizeBytes = MAX_SIZE_BYTES_UNLIMITED
m.logWarn("Memory Cache initialized without size limit! Cache can grow excessively!")
} else if m.MaxSizeBytes == 0 {
m.logWarn("Memory Cache initialized with MaxSizeBytes == 0. Cache will not be used...")
}
if m.EnsureMaxSizeInterval <= 0 && m.MaxSizeBytes > 0 {
m.logWarn("Memory Cache MaxByteSize set, but ensure-interval to enforce size limit not set.")
}
if m.EnsureMaxSizeInterval > 0 && m.MaxSizeBytes > 0 {
ticker := time.NewTicker(m.EnsureMaxSizeInterval)
quit := make(chan struct{})
go func() {
for {
select {
case <-ticker.C:
m.EnsureMaxSize()
case <-quit:
ticker.Stop()
return
}
}
}()
}
return &m
}
func (m *SharedMemoryCache) log(message string, logFunc func(string)) {
if logFunc != nil {
logFunc(message)
}
}
func (m *SharedMemoryCache) logDebug(message string) {
m.log(message, m.DebugLogger)
}
func (m *SharedMemoryCache) logInfo(message string) {
m.log(message, m.InfoLogger)
}
func (m *SharedMemoryCache) logWarn(message string) {
m.log(message, m.WarnLogger)
}
func (m *SharedMemoryCache) logError(message string) {
m.log(message, m.ErrorLogger)
}
func (m *SharedMemoryCache) getMemoryMap(mapKey string) (*MemoryMap, bool) {
memoryMap, mapExists := m.MemoryMaps[mapKey]
return memoryMap, mapExists
}
func (m *SharedMemoryCache) addMemoryMapIfNotExists(mapKey string) *MemoryMap {
memoryMap := m.MemoryMaps[mapKey]
if memoryMap == nil {
newMap := make(map[string][]byte)
memoryMap = &MemoryMap{Tiles: &newMap, Mutex: &sync.RWMutex{}}
m.MemoryMaps[mapKey] = memoryMap
m.logDebug("Memory Map with key [" + mapKey + "] did not exist. Created map!")
}
return memoryMap
}
func (mm *MemoryMap) getTile(tileKey string) (*[]byte, bool) {
data, exists := (*mm.Tiles)[tileKey]
return &data, exists
}
func (mm *MemoryMap) addTile(tileKey string, data *[]byte) {
(*mm.Tiles)[tileKey] = *data
}
func (mm *MemoryMap) removeTile(tileKey string) {
delete(*mm.Tiles, tileKey)
}
func (m *SharedMemoryCache) MaxSizeReachedMutex() bool {
m.HistoryMutex.RLock()
defer m.HistoryMutex.RUnlock()
return m.maxSizeReached()
}
func (m *SharedMemoryCache) maxSizeReached() bool {
if m.MaxSizeBytes <= MAX_SIZE_BYTES_UNLIMITED {
return false
}
return len(m.TileKeyHistory) > 0 && m.SizeBytes >= m.MaxSizeBytes
}
func (m *SharedMemoryCache) EnsureMaxSize() {
m.logDebug("EnsureMaxSize() called...")
start := time.Now()
m.HistoryMutex.Lock()
defer m.HistoryMutex.Unlock()
deleteCount := 0
for m.maxSizeReached() {
deleteKeys := m.TileKeyHistory[0]
m.TileKeyHistory = m.TileKeyHistory[1:]
m.MapMutes.RLock()
deleteMemoryMap, deleteMapExisted := m.getMemoryMap(deleteKeys.MemoryMapKey)
m.MapMutes.RUnlock()
if deleteMapExisted {
deleteMemoryMap.Mutex.Lock()
deleteTile, _ := deleteMemoryMap.getTile(deleteKeys.TileKey)
deleteSize := len(*deleteTile)
m.SizeBytes -= deleteSize
deleteMemoryMap.removeTile(deleteKeys.TileKey)
deleteMemoryMap.Mutex.Unlock()
deleteCount++
m.logDebug("MemoryMapWrite would exceed maximum capacity. Deleted tile with key [" + deleteKeys.TileKey + "] from MemoryMap [" + deleteKeys.MemoryMapKey + "], recovered " + strconv.Itoa(deleteSize) + " Bytes.")
} else {
m.logDebug("MemoryMap with key [" + deleteKeys.MemoryMapKey + "] not found. Cannot delete tile to free up space...")
}
}
duration := time.Since(start)
m.logDebug("EnsureMaxSize() finished. Removed " + strconv.Itoa(deleteCount) + " tiles (took " + duration.String() + ").")
}
func (m *SharedMemoryCache) MemoryMapRead(mapKey string, tileKey string) (*[]byte, bool) {
m.MapMutes.RLock()
memoryMap, mapExists := m.getMemoryMap(mapKey)
m.MapMutes.RUnlock()
if !mapExists {
return nil, false
}
memoryMap.Mutex.RLock()
data, exists := memoryMap.getTile(tileKey)
memoryMap.Mutex.RUnlock()
return data, exists
}
func (m *SharedMemoryCache) MemoryMapWrite(mapKey string, tileKey string, data *[]byte) {
m.MapMutes.Lock()
memoryMap := m.addMemoryMapIfNotExists(mapKey)
m.MapMutes.Unlock()
memoryMap.Mutex.Lock()
prevData, _ := memoryMap.getTile(tileKey)
oldDataSize := len(*prevData)
newDataSize := len(*data)
memoryMap.addTile(tileKey, data)
memoryMap.Mutex.Unlock()
m.HistoryMutex.Lock()
m.SizeBytes -= oldDataSize
m.TileKeyHistory = append(m.TileKeyHistory, TileKeyHistoryItem{MemoryMapKey: mapKey, TileKey: tileKey})
m.SizeBytes += newDataSize
m.HistoryMutex.Unlock()
}