Debian Codegraph @

ack_timer.go

raw
1 // SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
2 // SPDX-License-Identifier: MIT
3
4 package sctp
5
6 import (
7 "math"
8 "sync"
9 "time"
10 )
11
12 const (
13 ackInterval time.Duration = 200 * time.Millisecond
14 )
15
16 // ackTimerObserver is the inteface to an ack timer observer.
17 type ackTimerObserver interface {
18 onAckTimeout()
19 }
20
21 type ackTimerState uint8
22
23 const (
24 ackTimerStopped ackTimerState = iota
25 ackTimerStarted
26 ackTimerClosed
27 )
28
29 // ackTimer provides the retnransmission timer conforms with RFC 4960 Sec 6.3.1.
30 type ackTimer struct {
31 timer *time.Timer
32 observer ackTimerObserver
33 mutex sync.Mutex
34 state ackTimerState
35 pending uint8
36 }
37
38 // newAckTimer creates a new acknowledgement timer used to enable delayed ack.
39 func newAckTimer(observer ackTimerObserver) *ackTimer {
40 t := &ackTimer{observer: observer}
41 t.timer = time.AfterFunc(math.MaxInt64, t.timeout)
42 t.timer.Stop()
43
44 return t
45 }
46
47 func (t *ackTimer) timeout() {
48 t.mutex.Lock()
49 if t.pending--; t.pending == 0 && t.state == ackTimerStarted {
50 t.state = ackTimerStopped
51 defer t.observer.onAckTimeout()
52 }
53 t.mutex.Unlock()
54 }
55
56 // start starts the timer.
57 func (t *ackTimer) start() bool {
58 t.mutex.Lock()
59 defer t.mutex.Unlock()
60
61 // this timer is already closed or already running
62 if t.state != ackTimerStopped {
63 return false
64 }
65
66 t.state = ackTimerStarted
67 t.pending++
68 t.timer.Reset(ackInterval)
69
70 return true
71 }
72
73 // stops the timer. this is similar to stop() but subsequent start() call
74 // will fail (the timer is no longer usable).
75 func (t *ackTimer) stop() {
76 t.mutex.Lock()
77 defer t.mutex.Unlock()
78
79 if t.state == ackTimerStarted {
80 if t.timer.Stop() {
81 t.pending--
82 }
83 t.state = ackTimerStopped
84 }
85 }
86
87 // closes the timer. this is similar to stop() but subsequent start() call
88 // will fail (the timer is no longer usable).
89 func (t *ackTimer) close() {
90 t.mutex.Lock()
91 defer t.mutex.Unlock()
92
93 if t.state == ackTimerStarted && t.timer.Stop() {
94 t.pending--
95 }
96 t.state = ackTimerClosed
97 }
98
99 // isRunning tests if the timer is running.
100 // Debug purpose only.
101 func (t *ackTimer) isRunning() bool {
102 t.mutex.Lock()
103 defer t.mutex.Unlock()
104
105 return t.state == ackTimerStarted
106 }