forked from VolantMQ/volantmq
/
flowControl.go
80 lines (60 loc) · 1.16 KB
/
flowControl.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
package connection
import (
"errors"
"sync"
"sync/atomic"
"github.com/VolantMQ/vlapi/mqttp"
)
var (
errQuotaExceeded = errors.New("quota exceeded")
)
type flow struct {
inUse sync.Map
counter uint32
quota int32
}
func (s *flow) reAcquire(id mqttp.IDType) error {
if atomicDecNZ(&s.quota) == 0 {
return errQuotaExceeded
}
s.inUse.Store(id, true)
return nil
}
func (s *flow) acquire() (mqttp.IDType, error) {
if atomicDecNZ(&s.quota) == 0 {
return mqttp.IDType(0), errQuotaExceeded
}
var id mqttp.IDType
for count := 0; count <= 0xFFFF; count++ {
s.counter++
id = mqttp.IDType(s.counter)
if id == 0 {
s.counter++
id = mqttp.IDType(s.counter)
}
if _, ok := s.inUse.LoadOrStore(id, true); !ok {
break
}
}
return id, nil
}
func (s *flow) release(id mqttp.IDType) bool {
s.inUse.Delete(id)
return atomic.AddInt32(&s.quota, 1) == 1
}
func (s *flow) quotaAvailable() bool {
return atomic.LoadInt32(&s.quota) > 0
}
func atomicDecNZ(val *int32) int32 {
var prev int32
for {
prev = atomic.LoadInt32(val)
if prev == 0 {
return 0
}
if atomic.CompareAndSwapInt32(val, prev, prev-1) {
break
}
}
return prev
}