-
Notifications
You must be signed in to change notification settings - Fork 898
/
timedqueue.go
91 lines (76 loc) · 1.75 KB
/
timedqueue.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
package peers
import (
"sync"
"time"
"github.com/benbjohnson/clock"
"github.com/libp2p/go-libp2p/core/peer"
)
// timedQueue store items for ttl duration and releases it with calling onPop callback. Each item
// is tracked independently
type timedQueue struct {
sync.Mutex
items []item
// ttl is the amount of time each item exist in the timedQueue
ttl time.Duration
clock clock.Clock
after *clock.Timer
// onPop will be called on item peer.ID after it is released
onPop func(peer.ID)
}
type item struct {
peer.ID
createdAt time.Time
}
func newTimedQueue(ttl time.Duration, onPop func(peer.ID)) *timedQueue {
return &timedQueue{
items: make([]item, 0),
clock: clock.New(),
ttl: ttl,
onPop: onPop,
}
}
// releaseExpired will release all expired items
func (q *timedQueue) releaseExpired() {
q.Lock()
defer q.Unlock()
q.releaseUnsafe()
}
func (q *timedQueue) releaseUnsafe() {
if len(q.items) == 0 {
return
}
var i int
for _, next := range q.items {
timeIn := q.clock.Since(next.createdAt)
if timeIn < q.ttl {
// item is not expired yet, create a timer that will call releaseExpired
q.after.Stop()
q.after = q.clock.AfterFunc(q.ttl-timeIn, q.releaseExpired)
break
}
// item is expired
q.onPop(next.ID)
i++
}
if i > 0 {
copy(q.items, q.items[i:])
q.items = q.items[:len(q.items)-i]
}
}
func (q *timedQueue) push(peerID peer.ID) {
q.Lock()
defer q.Unlock()
q.items = append(q.items, item{
ID: peerID,
createdAt: q.clock.Now(),
})
// if it is the first item in queue, create a timer to call releaseExpired after its expiration
if len(q.items) == 1 {
q.after = q.clock.AfterFunc(q.ttl, q.releaseExpired)
}
}
func (q *timedQueue) len() int {
q.Lock()
defer q.Unlock()
return len(q.items)
}