-
Notifications
You must be signed in to change notification settings - Fork 1
/
payloads_buffer.go
169 lines (101 loc) · 2.37 KB
/
payloads_buffer.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package state
import (
"sync"
"sync/atomic"
proto "github.com/mcc-github/blockchain-protos-go/gossip"
"github.com/mcc-github/blockchain/common/metrics"
"github.com/mcc-github/blockchain/gossip/util"
)
type PayloadsBuffer interface {
Push(payload *proto.Payload)
Next() uint64
Pop() *proto.Payload
Size() int
Ready() chan struct{}
Close()
}
type PayloadsBufferImpl struct {
next uint64
buf map[uint64]*proto.Payload
readyChan chan struct{}
mutex sync.RWMutex
logger util.Logger
}
func NewPayloadsBuffer(next uint64) PayloadsBuffer {
return &PayloadsBufferImpl{
buf: make(map[uint64]*proto.Payload),
readyChan: make(chan struct{}, 1),
next: next,
logger: util.GetLogger(util.StateLogger, ""),
}
}
func (b *PayloadsBufferImpl) Ready() chan struct{} {
return b.readyChan
}
func (b *PayloadsBufferImpl) Push(payload *proto.Payload) {
b.mutex.Lock()
defer b.mutex.Unlock()
seqNum := payload.SeqNum
if seqNum < b.next || b.buf[seqNum] != nil {
logger.Debugf("Payload with sequence number = %d has been already processed", payload.SeqNum)
return
}
b.buf[seqNum] = payload
if seqNum == b.next && len(b.readyChan) == 0 {
b.readyChan <- struct{}{}
}
}
func (b *PayloadsBufferImpl) Next() uint64 {
return atomic.LoadUint64(&b.next)
}
func (b *PayloadsBufferImpl) Pop() *proto.Payload {
b.mutex.Lock()
defer b.mutex.Unlock()
result := b.buf[b.Next()]
if result != nil {
delete(b.buf, b.Next())
atomic.AddUint64(&b.next, 1)
b.drainReadChannel()
}
return result
}
func (b *PayloadsBufferImpl) drainReadChannel() {
if len(b.buf) == 0 {
for {
if len(b.readyChan) > 0 {
<-b.readyChan
} else {
break
}
}
}
}
func (b *PayloadsBufferImpl) Size() int {
b.mutex.RLock()
defer b.mutex.RUnlock()
return len(b.buf)
}
func (b *PayloadsBufferImpl) Close() {
close(b.readyChan)
}
type metricsBuffer struct {
PayloadsBuffer
sizeMetrics metrics.Gauge
chainID string
}
func (mb *metricsBuffer) Push(payload *proto.Payload) {
mb.PayloadsBuffer.Push(payload)
mb.reportSize()
}
func (mb *metricsBuffer) Pop() *proto.Payload {
pl := mb.PayloadsBuffer.Pop()
mb.reportSize()
return pl
}
func (mb *metricsBuffer) reportSize() {
mb.sizeMetrics.With("channel", mb.chainID).Set(float64(mb.Size()))
}