-
Notifications
You must be signed in to change notification settings - Fork 2
/
cache.go
88 lines (76 loc) · 2.01 KB
/
cache.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
// -*- Go -*-
/* ------------------------------------------------ */
/* Golang source */
/* Author: Alexei Panov <[email protected]> */
/* ------------------------------------------------ */
package main
import (
"time"
"github.com/go-pg/pg"
log "github.com/sirupsen/logrus"
)
// Cache is a type for store flooder information
type Cache struct {
FlooderID int
UserID int
Timestamp time.Time
}
func cacheUpdate() {
var (
caches []Cache
err error
)
for {
time.Sleep(options.CacheUpdatePeriod)
if err = db.Model(&caches).Select(); err != nil {
log.Errorf("Unable to get caches: %s", err)
continue
}
for _, cache := range caches {
if time.Since(cache.Timestamp) >= options.CacheDuration {
if err = cache.Remove(); err != nil {
log.Errorf("Unable to remove cache record: %s", err)
}
}
}
}
}
func cacheGet(flooderID, userID int) (exists bool, duration time.Duration, err error) {
var caches []Cache
if err = db.Model(&caches).Where("flooder_id = ? AND user_id = ?", flooderID, userID).Select(); err != nil && err == pg.ErrNoRows {
return false, 0, nil
} else if err != nil {
return
}
exists = false
for _, cache := range caches {
exists = true
d := time.Since(cache.Timestamp)
if d < duration || duration == 0 {
duration = d
}
if d >= options.CacheDuration {
if err = cache.Remove(); err != nil {
log.Errorf("Unable to delete cache record in cacheGet: %s", err)
}
}
}
return
}
func cacheSet(flooderID, userID int) (err error) {
cache := Cache{
FlooderID: flooderID,
UserID: userID,
Timestamp: time.Now(),
}
err = db.Insert(&cache)
return
}
// Remove function for remove cache flooder record from database
func (c *Cache) Remove() (err error) {
if _, err = db.Model(&[]Cache{}).Where("flooder_id = ? AND user_id = ? AND timestamp = ?", c.FlooderID, c.UserID, c.Timestamp).Delete(); err != nil {
return
}
log.Debugf("Cache record with flooder ID=%d and user ID=%d removed", c.FlooderID, c.UserID)
return
}