Skip to content

Commit

Permalink
rcmgr: fix JSON marshalling of ResourceManagerStat peer map (#2156)
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoPolo committed Mar 1, 2023
1 parent c1c4a6a commit de33307
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
18 changes: 18 additions & 0 deletions p2p/host/resource-manager/extapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package rcmgr

import (
"bytes"
"encoding/json"
"sort"
"strings"

Expand Down Expand Up @@ -35,6 +36,23 @@ type ResourceManagerStat struct {
Peers map[peer.ID]network.ScopeStat
}

func (s ResourceManagerStat) MarshalJSON() ([]byte, error) {
// we want to marshal the encoded peer id
encodedPeerMap := make(map[string]network.ScopeStat, len(s.Peers))
for p, v := range s.Peers {
encodedPeerMap[p.String()] = v
}

type Alias ResourceManagerStat
return json.Marshal(&struct {
*Alias
Peers map[string]network.ScopeStat `json:",omitempty"`
}{
Alias: (*Alias)(&s),
Peers: encodedPeerMap,
})
}

var _ ResourceManagerState = (*resourceManager)(nil)

func (s *resourceScope) Limit() Limit {
Expand Down
26 changes: 26 additions & 0 deletions p2p/host/resource-manager/extapi_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package rcmgr

import (
"encoding/json"
"testing"

"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/stretchr/testify/require"
)

func TestResourceManagerStatRoundTrip(t *testing.T) {
validPeerID, err := peer.Decode("QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN")
require.NoError(t, err)

n := ResourceManagerStat{
Peers: map[peer.ID]network.ScopeStat{validPeerID: {}},
}
b, err := json.Marshal(n)
require.NoError(t, err)

rt := ResourceManagerStat{}
require.NoError(t, json.Unmarshal(b, &rt))

require.Equal(t, n, rt)
}

0 comments on commit de33307

Please sign in to comment.