github.com/ethersphere/bee/v2@v2.2.0/pkg/topology/kademlia/internal/waitnext/waitnext.go (about) 1 // Copyright 2021 The Swarm Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package metrics provides service for collecting various metrics about peers. 6 // It is intended to be used with the kademlia where the metrics are collected. 7 package waitnext 8 9 import ( 10 "sync" 11 "time" 12 13 "github.com/ethersphere/bee/v2/pkg/swarm" 14 ) 15 16 type next struct { 17 tryAfter time.Time 18 failedAttempts int 19 } 20 21 type WaitNext struct { 22 next map[string]*next 23 sync.Mutex 24 } 25 26 func New() *WaitNext { 27 return &WaitNext{ 28 next: make(map[string]*next), 29 } 30 } 31 32 func (r *WaitNext) Set(addr swarm.Address, tryAfter time.Time, attempts int) { 33 34 r.Lock() 35 defer r.Unlock() 36 37 r.next[addr.ByteString()] = &next{tryAfter: tryAfter, failedAttempts: attempts} 38 } 39 40 func (r *WaitNext) SetTryAfter(addr swarm.Address, tryAfter time.Time) { 41 42 r.Lock() 43 defer r.Unlock() 44 45 if info, ok := r.next[addr.ByteString()]; ok { 46 info.tryAfter = tryAfter 47 } else { 48 r.next[addr.ByteString()] = &next{tryAfter: tryAfter} 49 } 50 } 51 52 func (r *WaitNext) Waiting(addr swarm.Address) bool { 53 54 r.Lock() 55 defer r.Unlock() 56 57 info, ok := r.next[addr.ByteString()] 58 return ok && time.Now().Before(info.tryAfter) 59 } 60 61 func (r *WaitNext) Attempts(addr swarm.Address) int { 62 63 r.Lock() 64 defer r.Unlock() 65 66 if info, ok := r.next[addr.ByteString()]; ok { 67 return info.failedAttempts 68 } 69 70 return 0 71 } 72 73 func (r *WaitNext) Remove(addr swarm.Address) { 74 75 r.Lock() 76 defer r.Unlock() 77 78 delete(r.next, addr.ByteString()) 79 }