-
Notifications
You must be signed in to change notification settings - Fork 0
/
retransmission_queue.go
75 lines (66 loc) · 1.44 KB
/
retransmission_queue.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
package spectral
import (
"sync"
"time"
)
const (
retransmissionAttempts = 3
retransmissionDelay = time.Second * 3
)
type retransmissionEntry struct {
payload []byte
timestamp time.Time
attempts int
nack bool
}
type retransmissionQueue struct {
entries map[uint32]*retransmissionEntry
mu sync.Mutex
}
func newRetransmissionQueue() *retransmissionQueue {
return &retransmissionQueue{
entries: make(map[uint32]*retransmissionEntry),
}
}
func (r *retransmissionQueue) add(sequenceID uint32, p []byte) {
r.mu.Lock()
r.entries[sequenceID] = &retransmissionEntry{payload: p, timestamp: time.Now()}
r.mu.Unlock()
}
func (r *retransmissionQueue) nack(sequenceID uint32) {
r.mu.Lock()
if entry, ok := r.entries[sequenceID]; ok {
entry.nack = true
}
r.mu.Unlock()
}
func (r *retransmissionQueue) remove(sequenceID uint32) (e *retransmissionEntry) {
r.mu.Lock()
entry, ok := r.entries[sequenceID]
if ok {
e = entry
delete(r.entries, sequenceID)
}
r.mu.Unlock()
return
}
func (r *retransmissionQueue) shift() (p []byte) {
r.mu.Lock()
if len(r.entries) > 0 {
now := time.Now()
for sequenceID, entry := range r.entries {
if entry.nack || now.Sub(entry.timestamp) >= retransmissionDelay {
entry.timestamp = now
entry.nack = false
entry.attempts++
if entry.attempts >= retransmissionAttempts {
delete(r.entries, sequenceID)
}
p = entry.payload
break
}
}
}
r.mu.Unlock()
return
}