-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
64 lines (57 loc) · 1.17 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
package retroproxy
import (
"fmt"
"sync"
"time"
"go.uber.org/zap"
)
// Cache is an implementation of Storer for an in-memory cache.
type Cache struct {
logger *zap.Logger
tickets map[string]Ticket
mu sync.Mutex
}
func NewCache(logger *zap.Logger) *Cache {
if logger == nil {
logger = zap.NewNop()
}
return &Cache{logger: logger}
}
func (r *Cache) SetTicket(id string, t Ticket) {
r.mu.Lock()
defer r.mu.Unlock()
if r.tickets == nil {
r.tickets = make(map[string]Ticket)
}
r.tickets[id] = t
r.logger.Debug("ticket set",
zap.String("ticket_id", id),
zap.String("ticket", fmt.Sprintf("%+v", t)),
)
}
func (r *Cache) UseTicket(id string) (Ticket, bool) {
r.mu.Lock()
defer r.mu.Unlock()
t, ok := r.tickets[id]
if ok {
delete(r.tickets, id)
r.logger.Debug("ticket used",
zap.String("ticket_id", id),
)
}
return t, ok
}
func (r *Cache) DeleteOldTickets(maxDur time.Duration) {
r.mu.Lock()
defer r.mu.Unlock()
now := time.Now()
for id := range r.tickets {
deadline := r.tickets[id].IssuedAt.Add(maxDur)
if now.After(deadline) {
delete(r.tickets, id)
r.logger.Debug("old ticket deleted",
zap.String("ticket_id", id),
)
}
}
}