diff --git a/p2p/test/resource-manager/echo_test.go b/p2p/test/resource-manager/echo_test.go index d6896fbdef..a16ace6757 100644 --- a/p2p/test/resource-manager/echo_test.go +++ b/p2p/test/resource-manager/echo_test.go @@ -12,7 +12,11 @@ import ( "github.com/stretchr/testify/require" ) -func createEchos(t *testing.T, count int, makeOpts ...func(int) libp2p.Option) []*Echo { +type fataler interface { + Fatal(args ...any) +} + +func createEchos(t fataler, count int, makeOpts ...func(int) libp2p.Option) []*Echo { result := make([]*Echo, 0, count) for i := 0; i < count; i++ { diff --git a/p2p/test/resource-manager/rcmgr_bench_test.go b/p2p/test/resource-manager/rcmgr_bench_test.go new file mode 100644 index 0000000000..7c92749bb8 --- /dev/null +++ b/p2p/test/resource-manager/rcmgr_bench_test.go @@ -0,0 +1,60 @@ +package itest + +import ( + "context" + "log" + "testing" + + rcmgr "github.com/libp2p/go-libp2p/p2p/host/resource-manager" + "github.com/libp2p/go-libp2p/p2p/host/resource-manager/obs" +) + +func BenchmarkMetrics(b *testing.B) { + // this test checks that we can not exceed the inbound conn limit at system level + // we specify: 1 conn per peer, 3 conns total, and we try to create 4 conns + cfg := rcmgr.DefaultLimits.AutoScale() + + b.Run("on", func(b *testing.B) { + b.ReportAllocs() + + tr, err := obs.NewStatsTraceReporter() + if err != nil { + b.Fatal(err) + } + echos := createEchos(b, 2, makeRcmgrOption(b, cfg, rcmgr.WithTraceReporter(&tr))) + defer closeEchos(echos) + defer closeRcmgrs(echos) + + host1 := echos[0] + host2 := echos[1] + + for i := 0; i < b.N; i++ { + stream, err := host1.Host.NewStream(context.Background(), host2.Host.ID(), EchoProtoID) + if err != nil { + log.Fatal(err) + } + stream.Close() + stream.Conn().Close() + } + }) + + b.Run("off", func(b *testing.B) { + b.ReportAllocs() + + echos := createEchos(b, 2, makeRcmgrOption(b, cfg)) + defer closeEchos(echos) + defer closeRcmgrs(echos) + + host1 := echos[0] + host2 := echos[1] + + for i := 0; i < b.N; i++ { + stream, err := host1.Host.NewStream(context.Background(), host2.Host.ID(), EchoProtoID) + if err != nil { + log.Fatal(err) + } + stream.Close() + stream.Conn().Close() + } + }) +} diff --git a/p2p/test/resource-manager/rcmgr_test.go b/p2p/test/resource-manager/rcmgr_test.go index ae546c5af9..7d421a5128 100644 --- a/p2p/test/resource-manager/rcmgr_test.go +++ b/p2p/test/resource-manager/rcmgr_test.go @@ -17,9 +17,13 @@ import ( "github.com/stretchr/testify/require" ) -func makeRcmgrOption(t *testing.T, cfg rcmgr.LimitConfig) func(int) libp2p.Option { +type rcmgrOptionT interface { + require.TestingT + Name() string +} + +func makeRcmgrOption(t rcmgrOptionT, cfg rcmgr.LimitConfig, opts ...rcmgr.Option) func(int) libp2p.Option { return func(i int) libp2p.Option { - var opts []rcmgr.Option if os.Getenv("LIBP2P_TEST_RCMGR_TRACE") == "1" { opts = append(opts, rcmgr.WithTrace(fmt.Sprintf("%s-%d.json.gz", t.Name(), i))) }