-
Notifications
You must be signed in to change notification settings - Fork 79
/
ack_timer.go
104 lines (86 loc) · 2.11 KB
/
ack_timer.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
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package sctp
import (
"math"
"sync"
"time"
)
const (
ackInterval time.Duration = 200 * time.Millisecond
)
// ackTimerObserver is the inteface to an ack timer observer.
type ackTimerObserver interface {
onAckTimeout()
}
type ackTimerState uint8
const (
ackTimerStopped ackTimerState = iota
ackTimerStarted
ackTimerClosed
)
// ackTimer provides the retnransmission timer conforms with RFC 4960 Sec 6.3.1
type ackTimer struct {
timer *time.Timer
observer ackTimerObserver
mutex sync.Mutex
state ackTimerState
pending uint8
}
// newAckTimer creates a new acknowledgement timer used to enable delayed ack.
func newAckTimer(observer ackTimerObserver) *ackTimer {
t := &ackTimer{observer: observer}
t.timer = time.AfterFunc(math.MaxInt64, t.timeout)
t.timer.Stop()
return t
}
func (t *ackTimer) timeout() {
t.mutex.Lock()
if t.pending--; t.pending == 0 && t.state == ackTimerStarted {
t.state = ackTimerStopped
defer t.observer.onAckTimeout()
}
t.mutex.Unlock()
}
// start starts the timer.
func (t *ackTimer) start() bool {
t.mutex.Lock()
defer t.mutex.Unlock()
// this timer is already closed or already running
if t.state != ackTimerStopped {
return false
}
t.state = ackTimerStarted
t.pending++
t.timer.Reset(ackInterval)
return true
}
// stops the timer. this is similar to stop() but subsequent start() call
// will fail (the timer is no longer usable)
func (t *ackTimer) stop() {
t.mutex.Lock()
defer t.mutex.Unlock()
if t.state == ackTimerStarted {
if t.timer.Stop() {
t.pending--
}
t.state = ackTimerStopped
}
}
// closes the timer. this is similar to stop() but subsequent start() call
// will fail (the timer is no longer usable)
func (t *ackTimer) close() {
t.mutex.Lock()
defer t.mutex.Unlock()
if t.state == ackTimerStarted && t.timer.Stop() {
t.pending--
}
t.state = ackTimerClosed
}
// isRunning tests if the timer is running.
// Debug purpose only
func (t *ackTimer) isRunning() bool {
t.mutex.Lock()
defer t.mutex.Unlock()
return t.state == ackTimerStarted
}