-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathmemcache.go
320 lines (281 loc) · 9.42 KB
/
memcache.go
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package common
import (
"bytes"
"context"
"crypto/md5"
"crypto/tls"
"encoding/gob"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"net"
"strconv"
"strings"
"github.com/sqlitebrowser/dbhub.io/common/config"
"github.com/sqlitebrowser/dbhub.io/common/database"
"github.com/bradfitz/gomemcache/memcache"
)
var (
// Connection handles
memCache *memcache.Client
)
// CacheData caches data in Memcached
func CacheData(cacheKey string, cacheData interface{}, cacheSeconds int) error {
// Encode the data
var encodedData bytes.Buffer
enc := gob.NewEncoder(&encodedData)
err := enc.Encode(cacheData)
if err != nil {
return err
}
// Send the data to memcached
cachedData := memcache.Item{Key: cacheKey, Value: encodedData.Bytes(), Expiration: int32(cacheSeconds)}
err = memCache.Set(&cachedData)
if err != nil {
return err
}
return nil
}
// ClearCache removes all items currently cached by Memcached, so it's like a newly started server
func ClearCache() (err error) {
err = memCache.FlushAll()
log.Println("Memcached cleared")
return
}
// ConnectCache connects to the Memcached server
func ConnectCache() (err error) {
memCache = memcache.New(config.Conf.Memcache.Server)
if config.Conf.Environment.Environment == "production" {
z := strings.Split(config.Conf.Memcache.Server, ":")
serverName := z[0]
memCache.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
var td tls.Dialer
td.Config = &tls.Config{
// This REQUIRES the memcached server to be configured with the full cert chain, not just it's own cert
ServerName: serverName,
}
return td.DialContext(context.Background(), network, addr)
}
}
// Test the memcached connection
cacheTest := memcache.Item{Key: "connecttext", Value: []byte("1"), Expiration: 10}
err = memCache.Set(&cacheTest)
if err != nil {
return fmt.Errorf("%s: couldn't connect to memcached server: %s", config.Conf.Live.Nodename, err)
}
// Log successful connection message for Memcached
log.Printf("%v: connected to Memcached: %v", config.Conf.Live.Nodename, config.Conf.Memcache.Server)
return nil
}
// DeleteCacheItem deletes the cached item with the given key if it exists
func DeleteCacheItem(cacheKey string) error {
err := memCache.Delete(cacheKey)
// We don't care about cache misses
if errors.Is(err, memcache.ErrCacheMiss) {
return nil
}
return err
}
// GetCachedData retrieves cached data from Memcached
func GetCachedData(cacheKey string, cacheData interface{}) (bool, error) {
cacheItem, err := memCache.Get(cacheKey)
if err != nil {
if err == memcache.ErrCacheMiss {
return false, nil
}
return false, err
}
// If a value was retrieved, return it
if cacheItem != nil {
// Decode the serialised data
var decBuf bytes.Buffer
io.Copy(&decBuf, bytes.NewReader(cacheItem.Value))
dec := gob.NewDecoder(&decBuf)
dec.Decode(cacheData)
return true, nil
}
return false, nil
}
// GetViewCount retrieves the view count in Memcached for a database
func GetViewCount(dbOwner string, dbName string) (count int, err error) {
// Generate the cache key
cacheString := fmt.Sprintf("viewcount-%s-/-%s", dbOwner, dbName)
tempArr := md5.Sum([]byte(cacheString))
cacheKey := hex.EncodeToString(tempArr[:])
// Retrieve the view count
data, err := memCache.Get(cacheKey)
if err != nil {
if err != memcache.ErrCacheMiss {
// A real error occurred
return -1, err
}
// There isn't a cached value for the database
return -1, nil
}
// Convert the string value to int, and return it
count, err = strconv.Atoi(string(data.Value))
if err != nil {
return -1, err
}
return count, nil
}
// IncrementViewCount increments the view counter in Memcached for a database
func IncrementViewCount(dbOwner string, dbName string) error {
// Generate the cache key
cacheString := fmt.Sprintf("viewcount-%s-/-%s", dbOwner, dbName)
tempArr := md5.Sum([]byte(cacheString))
cacheKey := hex.EncodeToString(tempArr[:])
// Attempt to directly increment the counter
_, err := memCache.Increment(cacheKey, 1)
if err != nil {
if err != memcache.ErrCacheMiss {
// A real error occurred
return err
}
// The cached value didn't exist, so we check if it has an entry in PostgreSQL already
// NOTE: This function returns 0 if there's no existing entry, so we can just increment whatever it gives us
cnt, err := database.ViewCount(dbOwner, dbName)
if err != nil {
return err
}
// It doesn't so we create a new memcached entry for it
cachedData := memcache.Item{
Key: cacheKey,
Value: []byte(fmt.Sprintf("%d", cnt+1)),
Expiration: int32(config.Conf.Memcache.DefaultCacheTime),
}
err = memCache.Set(&cachedData)
if err != nil {
return err
}
}
return nil
}
// InvalidateCacheEntry invalidate Memcache data for a database entry or entries
func InvalidateCacheEntry(loggedInUser string, dbOwner string, dbName string, commitID string) error {
// If commitID is "", that means "for all commits". Otherwise, just invalidate the data for the requested one
var commitList []string
if commitID == "" {
// Get the list of all commits for the given database
var err error
l, err := database.GetCommitList(dbOwner, dbName) // Get the full commit list
if err != nil {
return err
}
for i := range l {
commitList = append(commitList, i)
}
commitList = append(commitList, "") // Add "" on the end, to indicate all entries
} else {
// Only one cached commit needs invalidation
commitList = append(commitList, commitID)
}
// Loop around, invalidating the now outdated entries
for _, c := range commitList {
// Invalidate the download page data, for private database versions
cacheKey := MetadataCacheKey("dwndb-meta", dbOwner, dbOwner, dbName, c)
err := memCache.Delete(cacheKey)
if err != nil {
if err != memcache.ErrCacheMiss {
// Cache miss is not an error we care about
return err
}
}
// Invalidate the download page data for public database versions
cacheKey = MetadataCacheKey("dwndb-meta", "", dbOwner, dbName, c)
err = memCache.Delete(cacheKey)
if err != nil {
if err != memcache.ErrCacheMiss {
// Cache miss is not an error we care about
return err
}
}
}
return nil
}
// MemcacheHandle returns the Memcached handle
func MemcacheHandle() *memcache.Client {
return memCache
}
// MetadataCacheKey generates a predictable cache key for metadata information
func MetadataCacheKey(prefix string, loggedInUser string, dbOwner string, dbName string, commitID string) string {
// The following schema of the cache string makes sure that the information is stored separately for all users.
// Users who are not logged in all have the same empty user name and this way get the same cache key.
cacheString := fmt.Sprintf("%s/%s/%s/%s/%s/%s", prefix, loggedInUser, strings.ToLower(dbOwner), "/", dbName, commitID)
tempArr := md5.Sum([]byte(cacheString))
return hex.EncodeToString(tempArr[:])
}
// SetUserStatusUpdates increments the view counter in Memcached for a database
func SetUserStatusUpdates(userName string, numUpdates int) error {
// Generate the cache key
cacheString := fmt.Sprintf("status-updates-%s", userName)
tempArr := md5.Sum([]byte(cacheString))
cacheKey := hex.EncodeToString(tempArr[:])
// Create a memcached entry with the new user status updates count
cachedData := memcache.Item{
Key: cacheKey,
Value: []byte(fmt.Sprintf("%d", numUpdates)),
Expiration: int32(config.Conf.Memcache.DefaultCacheTime),
}
err := memCache.Set(&cachedData)
if err != nil {
return err
}
return nil
}
// TableRowsCacheKey generates a predictable cache key for SQLite row data. ONLY for standard databases
func TableRowsCacheKey(prefix string, loggedInUser string, dbOwner string, dbName string, commitID string, dbTable string, rows int) string {
var cacheString string
if strings.ToLower(loggedInUser) == strings.ToLower(dbOwner) {
cacheString = fmt.Sprintf("%s/%s/%s/%s/%s/%s/%d", prefix, strings.ToLower(dbOwner), "/", dbName, commitID,
dbTable, rows)
} else {
// Requests for other users databases are cached separately from users own database requests
cacheString = fmt.Sprintf("%s/pub/%s/%s/%s/%s/%s/%d", prefix, strings.ToLower(dbOwner), "/", dbName,
commitID, dbTable, rows)
}
tempArr := md5.Sum([]byte(cacheString))
return hex.EncodeToString(tempArr[:])
}
// UserStatusUpdates returns the number of status updates outstanding for a user
func UserStatusUpdates(userName string) (numUpdates int, err error) {
// Generate the cache key
cacheString := fmt.Sprintf("status-updates-%s", userName)
tempArr := md5.Sum([]byte(cacheString))
cacheKey := hex.EncodeToString(tempArr[:])
// Retrieve the status updates counter
data, err := memCache.Get(cacheKey)
if err != nil {
if err != memcache.ErrCacheMiss {
// A real error occurred
return 0, err
}
// There isn't a cached value for the user, so retrieve the list from PG and create an initial value
lst, err := database.StatusUpdates(userName)
if err != nil {
return 0, err
}
for _, i := range lst {
numUpdates += len(i)
}
// Set the initial number of updates
cachedData := memcache.Item{
Key: cacheKey,
Value: []byte(fmt.Sprintf("%d", numUpdates)),
Expiration: int32(config.Conf.Memcache.DefaultCacheTime),
}
err = memCache.Set(&cachedData)
if err != nil {
return 0, err
}
return numUpdates, nil
}
// Convert the string value to int, and return it
numUpdates, err = strconv.Atoi(string(data.Value))
if err != nil {
return 0, err
}
return numUpdates, nil
}