status-go/vendor/github.com/pion/sctp/ack_timer.go

101 lines
2.0 KiB
Go
Raw Normal View History

2024-06-05 20:10:03 +00:00
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
2022-03-10 09:44:48 +00:00
package sctp
import (
2024-06-05 20:10:03 +00:00
"math"
2022-03-10 09:44:48 +00:00
"sync"
"time"
)
const (
ackInterval time.Duration = 200 * time.Millisecond
)
// ackTimerObserver is the inteface to an ack timer observer.
type ackTimerObserver interface {
onAckTimeout()
}
2024-06-05 20:10:03 +00:00
type ackTimerState int
const (
ackTimerStopped ackTimerState = iota
ackTimerStarted
ackTimerClosed
)
2022-03-10 09:44:48 +00:00
// ackTimer provides the retnransmission timer conforms with RFC 4960 Sec 6.3.1
type ackTimer struct {
observer ackTimerObserver
mutex sync.RWMutex
2024-06-05 20:10:03 +00:00
state ackTimerState
timer *time.Timer
2022-03-10 09:44:48 +00:00
}
// newAckTimer creates a new acknowledgement timer used to enable delayed ack.
func newAckTimer(observer ackTimerObserver) *ackTimer {
2024-06-05 20:10:03 +00:00
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.state == ackTimerStarted {
t.state = ackTimerStopped
defer t.observer.onAckTimeout()
2022-03-10 09:44:48 +00:00
}
2024-06-05 20:10:03 +00:00
t.mutex.Unlock()
2022-03-10 09:44:48 +00:00
}
// start starts the timer.
func (t *ackTimer) start() bool {
t.mutex.Lock()
defer t.mutex.Unlock()
2024-06-05 20:10:03 +00:00
// this timer is already closed or already running
if t.state != ackTimerStopped {
2022-03-10 09:44:48 +00:00
return false
}
2024-06-05 20:10:03 +00:00
t.state = ackTimerStarted
t.timer.Reset(ackInterval)
2022-03-10 09:44:48 +00:00
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()
2024-06-05 20:10:03 +00:00
if t.state == ackTimerStarted {
t.timer.Stop()
t.state = ackTimerStopped
2022-03-10 09:44:48 +00:00
}
}
// 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()
2024-06-05 20:10:03 +00:00
if t.state == ackTimerStarted {
t.timer.Stop()
2022-03-10 09:44:48 +00:00
}
2024-06-05 20:10:03 +00:00
t.state = ackTimerClosed
2022-03-10 09:44:48 +00:00
}
// isRunning tests if the timer is running.
// Debug purpose only
func (t *ackTimer) isRunning() bool {
t.mutex.RLock()
defer t.mutex.RUnlock()
2024-06-05 20:10:03 +00:00
return t.state == ackTimerStarted
2022-03-10 09:44:48 +00:00
}