Skip to content

Commit

Permalink
peerstore: pass options to addrbook constructor
Browse files Browse the repository at this point in the history
The constructor starts a goroutine, so we should pass these in the
constructor.
  • Loading branch information
sukunrt committed Dec 6, 2024
1 parent 31b9d3a commit 8c1d7ef
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 8 deletions.
14 changes: 6 additions & 8 deletions p2p/host/peerstore/pstoremem/peerstore.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,28 +26,26 @@ type Option interface{}
// It's the caller's responsibility to call RemovePeer to ensure
// that memory consumption of the peerstore doesn't grow unboundedly.
func NewPeerstore(opts ...Option) (ps *pstoremem, err error) {
ab := NewAddrBook()
defer func() {
if err != nil {
ab.Close()
}
}()

var protoBookOpts []ProtoBookOption
var addrBookOpts []AddrBookOption
for _, opt := range opts {
switch o := opt.(type) {
case ProtoBookOption:
protoBookOpts = append(protoBookOpts, o)
case AddrBookOption:
o(ab)
addrBookOpts = append(addrBookOpts, o)
default:
return nil, fmt.Errorf("unexpected peer store option: %v", o)
}
}
ab := NewAddrBook(addrBookOpts...)

pb, err := NewProtoBook(protoBookOpts...)
if err != nil {
ab.Close()
return nil, err
}

return &pstoremem{
Metrics: pstore.NewMetrics(),
memoryKeyBook: NewKeyBook(),
Expand Down
23 changes: 23 additions & 0 deletions p2p/host/peerstore/pstoremem/peerstore_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package pstoremem

import (
"testing"

"github.com/libp2p/go-libp2p/core/peerstore"
ma "github.com/multiformats/go-multiaddr"
"github.com/stretchr/testify/require"
)

func TestPeerStoreAddrBookOpts(t *testing.T) {
ps, err := NewPeerstore(WithMaxAddresses(1))
require.NoError(t, err)
defer ps.Close()

ps.AddAddr("p1", ma.StringCast("/ip4/1.2.3.4/udp/1/quic-v1"), peerstore.TempAddrTTL)
res := ps.Addrs("p1")
require.NotEmpty(t, res)

ps.AddAddr("p2", ma.StringCast("/ip4/1.2.3.4/udp/1/quic-v1"), peerstore.TempAddrTTL)
res = ps.Addrs("p2")
require.Empty(t, res)
}

0 comments on commit 8c1d7ef

Please sign in to comment.