ack_timer.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package sctp
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. const (
  7. ackInterval time.Duration = 200 * time.Millisecond
  8. )
  9. // ackTimerObserver is the inteface to an ack timer observer.
  10. type ackTimerObserver interface {
  11. onAckTimeout()
  12. }
  13. // ackTimer provides the retnransmission timer conforms with RFC 4960 Sec 6.3.1
  14. type ackTimer struct {
  15. observer ackTimerObserver
  16. interval time.Duration
  17. stopFunc stopAckTimerLoop
  18. closed bool
  19. mutex sync.RWMutex
  20. }
  21. type stopAckTimerLoop func()
  22. // newAckTimer creates a new acknowledgement timer used to enable delayed ack.
  23. func newAckTimer(observer ackTimerObserver) *ackTimer {
  24. return &ackTimer{
  25. observer: observer,
  26. interval: ackInterval,
  27. }
  28. }
  29. // start starts the timer.
  30. func (t *ackTimer) start() bool {
  31. t.mutex.Lock()
  32. defer t.mutex.Unlock()
  33. // this timer is already closed
  34. if t.closed {
  35. return false
  36. }
  37. // this is a noop if the timer is already running
  38. if t.stopFunc != nil {
  39. return false
  40. }
  41. cancelCh := make(chan struct{})
  42. go func() {
  43. timer := time.NewTimer(t.interval)
  44. select {
  45. case <-timer.C:
  46. t.stop()
  47. t.observer.onAckTimeout()
  48. case <-cancelCh:
  49. timer.Stop()
  50. }
  51. }()
  52. t.stopFunc = func() {
  53. close(cancelCh)
  54. }
  55. return true
  56. }
  57. // stops the timer. this is similar to stop() but subsequent start() call
  58. // will fail (the timer is no longer usable)
  59. func (t *ackTimer) stop() {
  60. t.mutex.Lock()
  61. defer t.mutex.Unlock()
  62. if t.stopFunc != nil {
  63. t.stopFunc()
  64. t.stopFunc = nil
  65. }
  66. }
  67. // closes the timer. this is similar to stop() but subsequent start() call
  68. // will fail (the timer is no longer usable)
  69. func (t *ackTimer) close() {
  70. t.mutex.Lock()
  71. defer t.mutex.Unlock()
  72. if t.stopFunc != nil {
  73. t.stopFunc()
  74. t.stopFunc = nil
  75. }
  76. t.closed = true
  77. }
  78. // isRunning tests if the timer is running.
  79. // Debug purpose only
  80. func (t *ackTimer) isRunning() bool {
  81. t.mutex.RLock()
  82. defer t.mutex.RUnlock()
  83. return (t.stopFunc != nil)
  84. }