github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/network/p2p/logging/internal/peerIdCache.go (about)

     1  package internal
     2  
     3  import (
     4  	"fmt"
     5  
     6  	lru "github.com/hashicorp/golang-lru"
     7  	"github.com/libp2p/go-libp2p/core/peer"
     8  )
     9  
    10  type PeerIdCache struct {
    11  	// TODO: Note that we use lru.Cache as there is an inherent import cycle when using the HeroCache.
    12  	//	 Moving forward we should consider moving the HeroCache to a separate repository and transition
    13  	// 	to using it here.
    14  	// 	This PeerIdCache is used extensively across the codebase, so any minor import cycle will cause
    15  	// 	a lot of trouble.
    16  	peerCache *lru.Cache
    17  }
    18  
    19  func NewPeerIdCache(size int) (*PeerIdCache, error) {
    20  	c, err := lru.New(size)
    21  	if err != nil {
    22  		return nil, fmt.Errorf("failed to create peer id cache: %w", err)
    23  	}
    24  	return &PeerIdCache{
    25  		peerCache: c,
    26  	}, nil
    27  }
    28  
    29  // PeerIdString returns the base58 encoded peer id string, it looks up the peer id in a cache to avoid
    30  // expensive base58 encoding, and caches the result for future use in case of a cache miss.
    31  // It is safe to call this method concurrently.
    32  func (p *PeerIdCache) PeerIdString(pid peer.ID) string {
    33  	pidStr, ok := p.peerCache.Get(pid)
    34  	if ok {
    35  		return pidStr.(string)
    36  	}
    37  
    38  	pidStr0 := pid.String()
    39  	p.peerCache.Add(pid, pidStr0)
    40  	return pidStr0
    41  }
    42  
    43  // Size returns the number of entries in the cache; it is mainly used for testing.
    44  func (p *PeerIdCache) Size() int {
    45  	return p.peerCache.Len()
    46  }
    47  
    48  // ByPeerId returns the base58 encoded peer id string by directly looking up the peer id in the cache. It is only
    49  // used for testing and since this is an internal package, it is not exposed to the outside world.
    50  func (p *PeerIdCache) ByPeerId(pid peer.ID) (string, bool) {
    51  	pidStr, ok := p.peerCache.Get(pid)
    52  	if ok {
    53  		return pidStr.(string), true
    54  	}
    55  	return "", false
    56  }