func (cm *BasicConnMgr) GetInfo() CMInfo {
	cm.lastTrimMu.RLock()
	lastTrim := cm.lastTrim
	cm.lastTrimMu.RUnlock()
	return CMInfo{
		HighWater:   cm.cfg.highWater,
		LowWater:    cm.cfg.lowWater,
		LastTrim:    lastTrim,
		GracePeriod: cm.cfg.gracePeriod,
		ConnCount:   int(atomic.LoadInt32(&cm.connCount)),
	}
}
GetInfo returns the configuration and status data for this connection manager.
package connmgr
import (
	"context"
	"sort"
	"sync"
	"sync/atomic"
	"time"
	"github.com/libp2p/go-libp2p-core/connmgr"
	"github.com/libp2p/go-libp2p-core/network"
	"github.com/libp2p/go-libp2p-core/peer"
	logging "github.com/ipfs/go-log"
	ma "github.com/multiformats/go-multiaddr"
)
var SilencePeriod = 10 * time.Second
var log = logging.Logger("connmgr")
type BasicConnMgr struct {
	*decayer
	cfg      *BasicConnManagerConfig
	segments segments
	plk       sync.RWMutex
	protected map[peer.ID]map[string]struct{}
	trimRunningCh chan struct{}
	trimTrigger   chan chan<- struct{}
	connCount     int32
	lastTrimMu sync.RWMutex
	lastTrim   time.Time
	ctx    context.Context
	cancel func()
}
var (
	_ connmgr.ConnManager = (*BasicConnMgr)(nil)
	_ connmgr.Decayer     = (*BasicConnMgr)(nil)
)
type segment struct {
	sync.Mutex
	peers map[peer.ID]*peerInfo
}
type segments [256]*segment
func (ss *segments) get(p peer.ID) *segment {
	return ss[byte(p[len(p)-1])]
}
func (ss *segments) countPeers() (count int) {
	for _, seg := range ss {
		seg.Lock()
		count += len(seg.peers)
		seg.Unlock()
	}
	return count
}
func (s *segment) tagInfoFor(p peer.ID) *peerInfo {
	pi, ok := s.peers[p]
	if ok {
		return pi
	}
	pi = &peerInfo{
		id:        p,
		firstSeen: time.Now(),  
		temp:      true,
		tags:      make(map[string]int),
		decaying:  make(map[*decayingTag]*connmgr.DecayingValue),
		conns:     make(map[network.Conn]time.Time),
	}
	s.peers[p] = pi
	return pi
}
func NewConnManager(low, hi int, grace time.Duration, opts ...Option) *BasicConnMgr {
	ctx, cancel := context.WithCancel(context.Background())
	cfg := &BasicConnManagerConfig{
		highWater:     hi,
		lowWater:      low,
		gracePeriod:   grace,
		silencePeriod: SilencePeriod,
	}
	for _, o := range opts {
		_ = o(cfg)
	}
	if cfg.decayer == nil {
		cfg.decayer = (&DecayerCfg{}).WithDefaults()
	}
	cm := &BasicConnMgr{
		cfg:           cfg,
		trimRunningCh: make(chan struct{}, 1),
		trimTrigger:   make(chan chan<- struct{}),
		protected:     make(map[peer.ID]map[string]struct{}, 16),
		ctx:           ctx,
		cancel:        cancel,
		segments: func() (ret segments) {
			for i := range ret {
				ret[i] = &segment{
					peers: make(map[peer.ID]*peerInfo),
				}
			}
			return ret
		}(),
	}
	decay, _ := NewDecayer(cfg.decayer, cm)
	cm.decayer = decay
	go cm.background()
	return cm
}
func (cm *BasicConnMgr) Close() error {
	if err := cm.decayer.Close(); err != nil {
		return err
	}
	cm.cancel()
	return nil
}
func (cm *BasicConnMgr) Protect(id peer.ID, tag string) {
	cm.plk.Lock()
	defer cm.plk.Unlock()
	tags, ok := cm.protected[id]
	if !ok {
		tags = make(map[string]struct{}, 2)
		cm.protected[id] = tags
	}
	tags[tag] = struct{}{}
}
func (cm *BasicConnMgr) Unprotect(id peer.ID, tag string) (protected bool) {
	cm.plk.Lock()
	defer cm.plk.Unlock()
	tags, ok := cm.protected[id]
	if !ok {
		return false
	}
	if delete(tags, tag); len(tags) == 0 {
		delete(cm.protected, id)
		return false
	}
	return true
}
func (cm *BasicConnMgr) IsProtected(id peer.ID, tag string) (protected bool) {
	cm.plk.Lock()
	defer cm.plk.Unlock()
	tags, ok := cm.protected[id]
	if !ok {
		return false
	}
	if tag == "" {
		return true
	}
	_, protected = tags[tag]
	return protected
}
type peerInfo struct {
	id       peer.ID
	tags     map[string]int                           
	decaying map[*decayingTag]*connmgr.DecayingValue  
	value int   
	temp  bool  
	conns map[network.Conn]time.Time  
	firstSeen time.Time  
}
func (cm *BasicConnMgr) TrimOpenConns(ctx context.Context) {
	ch := make(chan struct{})
	select {
	case cm.trimTrigger <- ch:
	case <-cm.ctx.Done():
	case <-ctx.Done():
	}
	select {
	case <-ch:
	case <-cm.ctx.Done():
	case <-ctx.Done():
	}
}
func (cm *BasicConnMgr) background() {
	interval := cm.cfg.gracePeriod / 2
	if interval < cm.cfg.silencePeriod {
		interval = cm.cfg.silencePeriod
	}
	if interval < 10*time.Second {
		interval = 10 * time.Second
	}
	ticker := time.NewTicker(interval)
	defer ticker.Stop()
	for {
		var waiting chan<- struct{}
		select {
		case <-ticker.C:
			if atomic.LoadInt32(&cm.connCount) < int32(cm.cfg.highWater) {
				continue
			}
		case waiting = <-cm.trimTrigger:
		case <-cm.ctx.Done():
			return
		}
		cm.trim()
		if waiting != nil {
			close(waiting)
		}
		for {
			select {
			case waiting = <-cm.trimTrigger:
				if waiting != nil {
					close(waiting)
				}
				continue
			default:
			}
			break
		}
	}
}
func (cm *BasicConnMgr) trim() {
	cm.lastTrimMu.RLock()
	lastTrim := cm.lastTrim
	cm.lastTrimMu.RUnlock()
	if time.Since(lastTrim) < cm.cfg.silencePeriod {
		return
	}
	for _, c := range cm.getConnsToClose() {
		log.Info("closing conn: ", c.RemotePeer())
		c.Close()
	}
	cm.lastTrimMu.Lock()
	cm.lastTrim = time.Now()
	cm.lastTrimMu.Unlock()
}
func (cm *BasicConnMgr) getConnsToClose() []network.Conn {
	if cm.cfg.lowWater == 0 || cm.cfg.highWater == 0 {
		return nil
	}
	nconns := int(atomic.LoadInt32(&cm.connCount))
	if nconns <= cm.cfg.lowWater {
		log.Info("open connection count below limit")
		return nil
	}
	npeers := cm.segments.countPeers()
	candidates := make([]*peerInfo, 0, npeers)
	ncandidates := 0
	gracePeriodStart := time.Now().Add(-cm.cfg.gracePeriod)
	cm.plk.RLock()
	for _, s := range cm.segments {
		s.Lock()
		for id, inf := range s.peers {
			if _, ok := cm.protected[id]; ok {
				continue
			}
			if inf.firstSeen.After(gracePeriodStart) {
				continue
			}
			candidates = append(candidates, inf)
			ncandidates += len(inf.conns)
		}
		s.Unlock()
	}
	cm.plk.RUnlock()
	if ncandidates < cm.cfg.lowWater {
		log.Info("open connection count above limit but too many are in the grace period")
		return nil
	}
	sort.Slice(candidates, func(i, j int) bool {
		left, right := candidates[i], candidates[j]
		if left.temp != right.temp {
			return left.temp
		}
		return left.value < right.value
	})
	target := ncandidates - cm.cfg.lowWater
	selected := make([]network.Conn, 0, target+10)
	for _, inf := range candidates {
		if target <= 0 {
			break
		}
		s := cm.segments.get(inf.id)
		s.Lock()
		if len(inf.conns) == 0 && inf.temp {
			delete(s.peers, inf.id)
		} else {
			for c := range inf.conns {
				selected = append(selected, c)
			}
		}
		target -= len(inf.conns)
		s.Unlock()
	}
	return selected
}
func (cm *BasicConnMgr) GetTagInfo(p peer.ID) *connmgr.TagInfo {
	s := cm.segments.get(p)
	s.Lock()
	defer s.Unlock()
	pi, ok := s.peers[p]
	if !ok {
		return nil
	}
	out := &connmgr.TagInfo{
		FirstSeen: pi.firstSeen,
		Value:     pi.value,
		Tags:      make(map[string]int),
		Conns:     make(map[string]time.Time),
	}
	for t, v := range pi.tags {
		out.Tags[t] = v
	}
	for t, v := range pi.decaying {
		out.Tags[t.name] = v.Value
	}
	for c, t := range pi.conns {
		out.Conns[c.RemoteMultiaddr().String()] = t
	}
	return out
}
func (cm *BasicConnMgr) TagPeer(p peer.ID, tag string, val int) {
	s := cm.segments.get(p)
	s.Lock()
	defer s.Unlock()
	pi := s.tagInfoFor(p)
	pi.value += val - pi.tags[tag]
	pi.tags[tag] = val
}
func (cm *BasicConnMgr) UntagPeer(p peer.ID, tag string) {
	s := cm.segments.get(p)
	s.Lock()
	defer s.Unlock()
	pi, ok := s.peers[p]
	if !ok {
		log.Info("tried to remove tag from untracked peer: ", p)
		return
	}
	pi.value -= pi.tags[tag]
	delete(pi.tags, tag)
}
func (cm *BasicConnMgr) UpsertTag(p peer.ID, tag string, upsert func(int) int) {
	s := cm.segments.get(p)
	s.Lock()
	defer s.Unlock()
	pi := s.tagInfoFor(p)
	oldval := pi.tags[tag]
	newval := upsert(oldval)
	pi.value += newval - oldval
	pi.tags[tag] = newval
}
type CMInfo struct {
	LowWater int
	HighWater int
	LastTrim time.Time
	GracePeriod time.Duration
	ConnCount int
}