Skip to content

Commit f78ffc0

Browse files
authored
les: create utilities as common package (#20509)
* les: move execqueue into utilities package execqueue is a util for executing queued functions in a serial order which is used by both les server and les client. Move it to common package. * les: move randselect to utilities package weighted_random_selector is a helpful tool for randomly select items maintained in a set but based on the item weight. It's used anywhere is LES package, mainly by les client but will be used in les server with very high chance. So move it into a common package as the second step for les separation. * les: rename to utils
1 parent 32d31c3 commit f78ffc0

7 files changed

Lines changed: 90 additions & 90 deletions

File tree

‎les/distributor.go‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
"time"
2323

2424
"github.com/ethereum/go-ethereum/common/mclock"
25+
"github.com/ethereum/go-ethereum/les/utils"
2526
)
2627

2728
// requestDistributor implements a mechanism that distributes requests to
@@ -194,7 +195,7 @@ func (d *requestDistributor) nextRequest() (distPeer, *distReq, time.Duration) {
194195
elem := d.reqQueue.Front()
195196
var (
196197
bestWait time.Duration
197-
sel *weightedRandomSelect
198+
sel *utils.WeightedRandomSelect
198199
)
199200

200201
d.peerLock.RLock()
@@ -219,9 +220,9 @@ func (d *requestDistributor) nextRequest() (distPeer, *distReq, time.Duration) {
219220
wait, bufRemain := peer.waitBefore(cost)
220221
if wait == 0 {
221222
if sel == nil {
222-
sel = newWeightedRandomSelect()
223+
sel = utils.NewWeightedRandomSelect()
223224
}
224-
sel.update(selectPeerItem{peer: peer, req: req, weight: int64(bufRemain*1000000) + 1})
225+
sel.Update(selectPeerItem{peer: peer, req: req, weight: int64(bufRemain*1000000) + 1})
225226
} else {
226227
if bestWait == 0 || wait < bestWait {
227228
bestWait = wait
@@ -239,7 +240,7 @@ func (d *requestDistributor) nextRequest() (distPeer, *distReq, time.Duration) {
239240
}
240241

241242
if sel != nil {
242-
c := sel.choose().(selectPeerItem)
243+
c := sel.Choose().(selectPeerItem)
243244
return c.peer, c.req, 0
244245
}
245246
return nil, nil, bestWait

‎les/peer.go‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import (
3232
"github.com/ethereum/go-ethereum/core/types"
3333
"github.com/ethereum/go-ethereum/eth"
3434
"github.com/ethereum/go-ethereum/les/flowcontrol"
35+
"github.com/ethereum/go-ethereum/les/utils"
3536
"github.com/ethereum/go-ethereum/light"
3637
"github.com/ethereum/go-ethereum/p2p"
3738
"github.com/ethereum/go-ethereum/p2p/enode"
@@ -135,7 +136,7 @@ type peerCommons struct {
135136
headInfo blockInfo // Latest block information.
136137

137138
// Background task queue for caching peer tasks and executing in order.
138-
sendQueue *execQueue
139+
sendQueue *utils.ExecQueue
139140

140141
// Flow control agreement.
141142
fcParams flowcontrol.ServerParams // The config for token bucket.
@@ -153,13 +154,13 @@ func (p *peerCommons) isFrozen() bool {
153154

154155
// canQueue returns an indicator whether the peer can queue a operation.
155156
func (p *peerCommons) canQueue() bool {
156-
return p.sendQueue.canQueue() && !p.isFrozen()
157+
return p.sendQueue.CanQueue() && !p.isFrozen()
157158
}
158159

159160
// queueSend caches a peer operation in the background task queue.
160161
// Please ensure to check `canQueue` before call this function
161162
func (p *peerCommons) queueSend(f func()) bool {
162-
return p.sendQueue.queue(f)
163+
return p.sendQueue.Queue(f)
163164
}
164165

165166
// mustQueueSend starts a for loop and retry the caching if failed.
@@ -337,7 +338,7 @@ func (p *peerCommons) handshake(td *big.Int, head common.Hash, headNum uint64, g
337338
// close closes the channel and notifies all background routines to exit.
338339
func (p *peerCommons) close() {
339340
close(p.closeCh)
340-
p.sendQueue.quit()
341+
p.sendQueue.Quit()
341342
}
342343

343344
// serverPeer represents each node to which the client is connected.
@@ -375,7 +376,7 @@ func newServerPeer(version int, network uint64, trusted bool, p *p2p.Peer, rw p2
375376
id: peerIdToString(p.ID()),
376377
version: version,
377378
network: network,
378-
sendQueue: newExecQueue(100),
379+
sendQueue: utils.NewExecQueue(100),
379380
closeCh: make(chan struct{}),
380381
},
381382
trusted: trusted,
@@ -407,7 +408,7 @@ func (p *serverPeer) rejectUpdate(size uint64) bool {
407408
// frozen.
408409
func (p *serverPeer) freeze() {
409410
if atomic.CompareAndSwapUint32(&p.frozen, 0, 1) {
410-
p.sendQueue.clear()
411+
p.sendQueue.Clear()
411412
}
412413
}
413414

@@ -652,7 +653,7 @@ func newClientPeer(version int, network uint64, p *p2p.Peer, rw p2p.MsgReadWrite
652653
id: peerIdToString(p.ID()),
653654
version: version,
654655
network: network,
655-
sendQueue: newExecQueue(100),
656+
sendQueue: utils.NewExecQueue(100),
656657
closeCh: make(chan struct{}),
657658
},
658659
errCh: make(chan error, 1),

‎les/serverpool.go‎

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import (
3030
"github.com/ethereum/go-ethereum/common/mclock"
3131
"github.com/ethereum/go-ethereum/crypto"
3232
"github.com/ethereum/go-ethereum/ethdb"
33+
"github.com/ethereum/go-ethereum/les/utils"
3334
"github.com/ethereum/go-ethereum/log"
3435
"github.com/ethereum/go-ethereum/p2p"
3536
"github.com/ethereum/go-ethereum/p2p/discv5"
@@ -129,7 +130,7 @@ type serverPool struct {
129130
adjustStats chan poolStatAdjust
130131

131132
knownQueue, newQueue poolEntryQueue
132-
knownSelect, newSelect *weightedRandomSelect
133+
knownSelect, newSelect *utils.WeightedRandomSelect
133134
knownSelected, newSelected int
134135
fastDiscover bool
135136
connCh chan *connReq
@@ -152,8 +153,8 @@ func newServerPool(db ethdb.Database, ulcServers []string) *serverPool {
152153
disconnCh: make(chan *disconnReq),
153154
registerCh: make(chan *registerReq),
154155
closeCh: make(chan struct{}),
155-
knownSelect: newWeightedRandomSelect(),
156-
newSelect: newWeightedRandomSelect(),
156+
knownSelect: utils.NewWeightedRandomSelect(),
157+
newSelect: utils.NewWeightedRandomSelect(),
157158
fastDiscover: true,
158159
trustedNodes: parseTrustedNodes(ulcServers),
159160
}
@@ -402,8 +403,8 @@ func (pool *serverPool) eventLoop() {
402403
entry.lastConnected = addr
403404
entry.addr = make(map[string]*poolEntryAddress)
404405
entry.addr[addr.strKey()] = addr
405-
entry.addrSelect = *newWeightedRandomSelect()
406-
entry.addrSelect.update(addr)
406+
entry.addrSelect = *utils.NewWeightedRandomSelect()
407+
entry.addrSelect.Update(addr)
407408
req.result <- entry
408409
}
409410

@@ -459,7 +460,7 @@ func (pool *serverPool) findOrNewNode(node *enode.Node) *poolEntry {
459460
entry = &poolEntry{
460461
node: node,
461462
addr: make(map[string]*poolEntryAddress),
462-
addrSelect: *newWeightedRandomSelect(),
463+
addrSelect: *utils.NewWeightedRandomSelect(),
463464
shortRetry: shortRetryCnt,
464465
}
465466
pool.entries[node.ID()] = entry
@@ -477,7 +478,7 @@ func (pool *serverPool) findOrNewNode(node *enode.Node) *poolEntry {
477478
entry.addr[addr.strKey()] = addr
478479
}
479480
addr.lastSeen = now
480-
entry.addrSelect.update(addr)
481+
entry.addrSelect.Update(addr)
481482
if !entry.known {
482483
pool.newQueue.setLatest(entry)
483484
}
@@ -505,7 +506,7 @@ func (pool *serverPool) loadNodes() {
505506
pool.entries[e.node.ID()] = e
506507
if pool.trustedNodes[e.node.ID()] == nil {
507508
pool.knownQueue.setLatest(e)
508-
pool.knownSelect.update((*knownEntry)(e))
509+
pool.knownSelect.Update((*knownEntry)(e))
509510
}
510511
}
511512
}
@@ -556,8 +557,8 @@ func (pool *serverPool) saveNodes() {
556557
// Note that it is called by the new/known queues from which the entry has already
557558
// been removed so removing it from the queues is not necessary.
558559
func (pool *serverPool) removeEntry(entry *poolEntry) {
559-
pool.newSelect.remove((*discoveredEntry)(entry))
560-
pool.knownSelect.remove((*knownEntry)(entry))
560+
pool.newSelect.Remove((*discoveredEntry)(entry))
561+
pool.knownSelect.Remove((*knownEntry)(entry))
561562
entry.removed = true
562563
delete(pool.entries, entry.node.ID())
563564
}
@@ -586,8 +587,8 @@ func (pool *serverPool) setRetryDial(entry *poolEntry) {
586587
// updateCheckDial is called when an entry can potentially be dialed again. It updates
587588
// its selection weights and checks if new dials can/should be made.
588589
func (pool *serverPool) updateCheckDial(entry *poolEntry) {
589-
pool.newSelect.update((*discoveredEntry)(entry))
590-
pool.knownSelect.update((*knownEntry)(entry))
590+
pool.newSelect.Update((*discoveredEntry)(entry))
591+
pool.knownSelect.Update((*knownEntry)(entry))
591592
pool.checkDial()
592593
}
593594

@@ -596,15 +597,15 @@ func (pool *serverPool) updateCheckDial(entry *poolEntry) {
596597
func (pool *serverPool) checkDial() {
597598
fillWithKnownSelects := !pool.fastDiscover
598599
for pool.knownSelected < targetKnownSelect {
599-
entry := pool.knownSelect.choose()
600+
entry := pool.knownSelect.Choose()
600601
if entry == nil {
601602
fillWithKnownSelects = false
602603
break
603604
}
604605
pool.dial((*poolEntry)(entry.(*knownEntry)), true)
605606
}
606607
for pool.knownSelected+pool.newSelected < targetServerCount {
607-
entry := pool.newSelect.choose()
608+
entry := pool.newSelect.Choose()
608609
if entry == nil {
609610
break
610611
}
@@ -615,7 +616,7 @@ func (pool *serverPool) checkDial() {
615616
// is over, we probably won't find more in the near future so select more
616617
// known entries if possible
617618
for pool.knownSelected < targetServerCount {
618-
entry := pool.knownSelect.choose()
619+
entry := pool.knownSelect.Choose()
619620
if entry == nil {
620621
break
621622
}
@@ -636,7 +637,7 @@ func (pool *serverPool) dial(entry *poolEntry, knownSelected bool) {
636637
} else {
637638
pool.newSelected++
638639
}
639-
addr := entry.addrSelect.choose().(*poolEntryAddress)
640+
addr := entry.addrSelect.Choose().(*poolEntryAddress)
640641
log.Debug("Dialing new peer", "lesaddr", entry.node.ID().String()+"@"+addr.strKey(), "set", len(entry.addr), "known", knownSelected)
641642
entry.dialed = addr
642643
go func() {
@@ -684,7 +685,7 @@ type poolEntry struct {
684685
addr map[string]*poolEntryAddress
685686
node *enode.Node
686687
lastConnected, dialed *poolEntryAddress
687-
addrSelect weightedRandomSelect
688+
addrSelect utils.WeightedRandomSelect
688689

689690
lastDiscovered mclock.AbsTime
690691
known, knownSelected, trusted bool
@@ -734,8 +735,8 @@ func (e *poolEntry) DecodeRLP(s *rlp.Stream) error {
734735
e.node = enode.NewV4(pubkey, entry.IP, int(entry.Port), int(entry.Port))
735736
e.addr = make(map[string]*poolEntryAddress)
736737
e.addr[addr.strKey()] = addr
737-
e.addrSelect = *newWeightedRandomSelect()
738-
e.addrSelect.update(addr)
738+
e.addrSelect = *utils.NewWeightedRandomSelect()
739+
e.addrSelect.Update(addr)
739740
e.lastConnected = addr
740741
e.connectStats = entry.CStat
741742
e.delayStats = entry.DStat
Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -14,35 +14,35 @@
1414
// You should have received a copy of the GNU Lesser General Public License
1515
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
1616

17-
package les
17+
package utils
1818

1919
import "sync"
2020

21-
// execQueue implements a queue that executes function calls in a single thread,
21+
// ExecQueue implements a queue that executes function calls in a single thread,
2222
// in the same order as they have been queued.
23-
type execQueue struct {
23+
type ExecQueue struct {
2424
mu sync.Mutex
2525
cond *sync.Cond
2626
funcs []func()
2727
closeWait chan struct{}
2828
}
2929

30-
// newExecQueue creates a new execution queue.
31-
func newExecQueue(capacity int) *execQueue {
32-
q := &execQueue{funcs: make([]func(), 0, capacity)}
30+
// NewExecQueue creates a new execution Queue.
31+
func NewExecQueue(capacity int) *ExecQueue {
32+
q := &ExecQueue{funcs: make([]func(), 0, capacity)}
3333
q.cond = sync.NewCond(&q.mu)
3434
go q.loop()
3535
return q
3636
}
3737

38-
func (q *execQueue) loop() {
38+
func (q *ExecQueue) loop() {
3939
for f := q.waitNext(false); f != nil; f = q.waitNext(true) {
4040
f()
4141
}
4242
close(q.closeWait)
4343
}
4444

45-
func (q *execQueue) waitNext(drop bool) (f func()) {
45+
func (q *ExecQueue) waitNext(drop bool) (f func()) {
4646
q.mu.Lock()
4747
if drop && len(q.funcs) > 0 {
4848
// Remove the function that just executed. We do this here instead of when
@@ -60,20 +60,20 @@ func (q *execQueue) waitNext(drop bool) (f func()) {
6060
return f
6161
}
6262

63-
func (q *execQueue) isClosed() bool {
63+
func (q *ExecQueue) isClosed() bool {
6464
return q.closeWait != nil
6565
}
6666

67-
// canQueue returns true if more function calls can be added to the execution queue.
68-
func (q *execQueue) canQueue() bool {
67+
// CanQueue returns true if more function calls can be added to the execution Queue.
68+
func (q *ExecQueue) CanQueue() bool {
6969
q.mu.Lock()
7070
ok := !q.isClosed() && len(q.funcs) < cap(q.funcs)
7171
q.mu.Unlock()
7272
return ok
7373
}
7474

75-
// queue adds a function call to the execution queue. Returns true if successful.
76-
func (q *execQueue) queue(f func()) bool {
75+
// Queue adds a function call to the execution Queue. Returns true if successful.
76+
func (q *ExecQueue) Queue(f func()) bool {
7777
q.mu.Lock()
7878
ok := !q.isClosed() && len(q.funcs) < cap(q.funcs)
7979
if ok {
@@ -84,16 +84,17 @@ func (q *execQueue) queue(f func()) bool {
8484
return ok
8585
}
8686

87-
// clear drops all queued functions
88-
func (q *execQueue) clear() {
87+
// Clear drops all queued functions.
88+
func (q *ExecQueue) Clear() {
8989
q.mu.Lock()
9090
q.funcs = q.funcs[:0]
9191
q.mu.Unlock()
9292
}
9393

94-
// quit stops the exec queue.
95-
// quit waits for the current execution to finish before returning.
96-
func (q *execQueue) quit() {
94+
// Quit stops the exec Queue.
95+
//
96+
// Quit waits for the current execution to finish before returning.
97+
func (q *ExecQueue) Quit() {
9798
q.mu.Lock()
9899
if !q.isClosed() {
99100
q.closeWait = make(chan struct{})
Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,21 +14,19 @@
1414
// You should have received a copy of the GNU Lesser General Public License
1515
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
1616

17-
package les
17+
package utils
1818

19-
import (
20-
"testing"
21-
)
19+
import "testing"
2220

2321
func TestExecQueue(t *testing.T) {
2422
var (
2523
N = 10000
26-
q = newExecQueue(N)
24+
q = NewExecQueue(N)
2725
counter int
2826
execd = make(chan int)
2927
testexit = make(chan struct{})
3028
)
31-
defer q.quit()
29+
defer q.Quit()
3230
defer close(testexit)
3331

3432
check := func(state string, wantOK bool) {
@@ -40,11 +38,11 @@ func TestExecQueue(t *testing.T) {
4038
case <-testexit:
4139
}
4240
}
43-
if q.canQueue() != wantOK {
44-
t.Fatalf("canQueue() == %t for %s", !wantOK, state)
41+
if q.CanQueue() != wantOK {
42+
t.Fatalf("CanQueue() == %t for %s", !wantOK, state)
4543
}
46-
if q.queue(qf) != wantOK {
47-
t.Fatalf("canQueue() == %t for %s", !wantOK, state)
44+
if q.Queue(qf) != wantOK {
45+
t.Fatalf("Queue() == %t for %s", !wantOK, state)
4846
}
4947
}
5048

@@ -57,6 +55,6 @@ func TestExecQueue(t *testing.T) {
5755
t.Fatal("execution out of order")
5856
}
5957
}
60-
q.quit()
58+
q.Quit()
6159
check("closed queue", false)
6260
}

0 commit comments

Comments
 (0)