-
Notifications
You must be signed in to change notification settings - Fork 2
/
cache.go
147 lines (113 loc) · 2.35 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
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
package main
import (
"sort"
"time"
"github.com/rs/xid"
)
type Cache struct {
messageTTL time.Duration
messages map[string]map[string]*CacheObject
semaphore chan bool
}
type CacheObject struct {
message string
addDate int64
}
func newCache(TTL time.Duration) *Cache {
return &Cache{
messageTTL: TTL,
messages: make(map[string]map[string]*CacheObject),
semaphore: make(chan bool, 1),
}
}
func (c *Cache) put(
authToken string,
message string,
) {
logger.Debugf(
"caching message %s for %s",
message,
authToken,
)
c.semaphore <- true
messageCacheID := xid.New().String()
messageCache := make(map[string]*CacheObject)
if len(c.messages[authToken]) == 0 {
messageCache[messageCacheID] = &CacheObject{
message,
time.Now().UnixNano(),
}
c.messages[authToken] = messageCache
} else {
messageCache = c.messages[authToken]
messageCache[messageCacheID] = &CacheObject{
message,
time.Now().UnixNano(),
}
}
c.messages[authToken] = messageCache
<-c.semaphore
go func() {
ttlTimer := time.NewTimer(c.messageTTL)
defer ttlTimer.Stop()
<-ttlTimer.C
logger.Debugf(
"message %s for %s TTL expired, it will be evicted",
message,
c.messageTTL,
)
c.semaphore <- true
switch len(c.messages[authToken]) {
case 0:
logger.Debugf(
"messages for %s was already evicted, nothing to delete",
authToken,
)
<-c.semaphore
return
case 1:
delete(c.messages, authToken)
<-c.semaphore
logger.Debugf(
"message cache for %s was purged",
authToken,
)
return
default:
delete(c.messages[authToken], messageCacheID)
<-c.semaphore
}
logger.Debugf(
"message %s successfully deleted by TTL expiration",
message,
)
}()
defer func() {
logger.Debugf(
"message %s successfuly cached",
message,
)
}()
}
func (c *Cache) pop(
authToken string,
) []*CacheObject {
var cachedMessages []*CacheObject
if len(c.messages[authToken]) == 0 {
logger.Debugf(
"no cached messages was found for %s",
authToken,
)
return cachedMessages
}
c.semaphore <- true
for _, message := range c.messages[authToken] {
cachedMessages = append(cachedMessages, message)
}
delete(c.messages, authToken)
<-c.semaphore
sort.Slice(cachedMessages, func(i, j int) bool {
return cachedMessages[i].addDate <= cachedMessages[j].addDate
})
return cachedMessages
}