-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathretransmission.go
86 lines (76 loc) · 1.68 KB
/
retransmission.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
package accter
import (
"sync"
"time"
)
type RetransmissionHandler interface {
IsRetransmission(key string) bool
AddToCache(key string) error
RemoveFromCache(key string)
CleanCycle() error
SetCleanCycleSeconds(sec int)
SetObjectLifetimeSeconds(sec int)
}
type Retransmissions struct {
sync.RWMutex
retransmissions map[string]time.Time
CleanCycleSeconds int
EntryLifetimeSeconds int
}
func CreateLocalRetransmissionHandler() RetransmissionHandler {
var r = &Retransmissions{
retransmissions: make(map[string]time.Time),
EntryLifetimeSeconds: 300,
CleanCycleSeconds: 10,
}
r.CleanCycle()
return r
}
func (r *Retransmissions) SetCleanCycleSeconds(sec int) {
r.Lock()
defer r.Unlock()
r.CleanCycleSeconds = sec
}
func (r *Retransmissions) SetObjectLifetimeSeconds(sec int) {
r.Lock()
defer r.Unlock()
r.EntryLifetimeSeconds = sec
}
func (r *Retransmissions) IsRetransmission(key string) bool {
r.RLock()
defer r.RUnlock()
if _, ok := r.retransmissions[key]; ok {
return true
}
return false
}
func (r *Retransmissions) AddToCache(key string) error {
r.Lock()
defer r.Unlock()
r.retransmissions[key] = time.Now()
return nil
}
func (r *Retransmissions) RemoveFromCache(key string) {
r.Lock()
defer r.Unlock()
delete(r.retransmissions, key)
}
func (r *Retransmissions) CleanCycle() error {
go func() {
for {
time.Sleep(time.Duration(r.CleanCycleSeconds) * time.Second)
r.RLock()
rts := make(map[string]time.Time)
for k, v := range r.retransmissions {
rts[k] = v
}
r.RUnlock()
for k := range rts {
if time.Since(rts[k]) > time.Duration(r.EntryLifetimeSeconds)*time.Second {
r.RemoveFromCache(k)
}
}
}
}()
return nil
}