Skip to content

Commit

Permalink
Satisfy the Stringer interface for Peer and Metadata
Browse files Browse the repository at this point in the history
Effectively allowing to print context containing Peers properly

Also enabling logging of Metadata in an easier way

RELEASE NOTES:

 - peer/peer: implement the Stringer interface for pretty-printing Peers
 - metadata/metadata: implement the Stringer interface for pretty printing metadata

Signed-off-by: Yolan Romailler <anomalroil@users.noreply.github.com>
  • Loading branch information
AnomalRoil committed Apr 17, 2024
1 parent fc8da03 commit bc88d17
Show file tree
Hide file tree
Showing 4 changed files with 185 additions and 0 deletions.
16 changes: 16 additions & 0 deletions metadata/metadata.go
Expand Up @@ -90,6 +90,22 @@ func Pairs(kv ...string) MD {
return md
}

// String implements the Stringer interface for pretty-printing a MD. Ordering of the values is non-deterministic as it ranges over a map.
func (md MD) String() string {
var sb strings.Builder
fmt.Fprintf(&sb, "MD{")
needSep := false
for k, v := range md {
if needSep {
fmt.Fprintf(&sb, ", ")
}
fmt.Fprintf(&sb, "%s=[%s]", k, strings.Join(v, ", "))
needSep = true
}
fmt.Fprintf(&sb, "}")
return sb.String()
}

// Len returns the number of items in md.
func (md MD) Len() int {
return len(md)
Expand Down
21 changes: 21 additions & 0 deletions metadata/metadata_test.go
Expand Up @@ -22,6 +22,7 @@ import (
"context"
"reflect"
"strconv"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -338,6 +339,26 @@ func (s) TestAppendToOutgoingContext_FromKVSlice(t *testing.T) {
}
}

func TestStringerMD(t *testing.T) {
for _, test := range []struct {
md MD
want []string
}{
{MD{}, []string{"MD{}"}},
{MD{"k1": []string{}}, []string{"MD{k1=[]}"}},
{MD{"k1": []string{"v1", "v2"}}, []string{"MD{k1=[v1, v2]}"}},
{MD{"k1": []string{"v1"}}, []string{"MD{k1=[v1]}"}},
{MD{"k1": []string{"v1", "v2"}, "k2": []string{}, "k3": []string{"1", "2", "3"}}, []string{"MD{", "k1=[v1, v2]", "k2=[]", "k3=[1, 2, 3]", "}"}},
} {
strMd := test.md.String()
for _, want := range test.want {
if !strings.Contains(strMd, want) {
t.Fatalf("Metadata string '%s' is missing '%s'", strMd, want)
}
}
}
}

// Old/slow approach to adding metadata to context
func Benchmark_AddingMetadata_ContextManipulationApproach(b *testing.B) {
// TODO: Add in N=1-100 tests once Go1.6 support is removed.
Expand Down
21 changes: 21 additions & 0 deletions peer/peer.go
Expand Up @@ -22,6 +22,7 @@ package peer

import (
"context"
"fmt"
"net"

"google.golang.org/grpc/credentials"
Expand All @@ -39,6 +40,26 @@ type Peer struct {
AuthInfo credentials.AuthInfo
}

// String ensures the Peer types implements the Stringer interface in order to
// allow to print a context with a peerKey value effectively.
func (p *Peer) String() string {
if p == nil {
return "Peer<nil>"
}
ret := "Peer{"
if p.Addr != nil {
ret += fmt.Sprintf("Addr: '%s'", p.Addr.String())
}
if p.AuthInfo != nil {
if len(ret) > 5 {
ret += ", "
}
ret += fmt.Sprintf("AuthInfo: '%s'", p.AuthInfo.AuthType())
}
ret += "}"
return ret
}

type peerKey struct{}

// NewContext creates a new context with peer information attached.
Expand Down
127 changes: 127 additions & 0 deletions peer/peer_test.go
@@ -0,0 +1,127 @@
package peer

import (
"context"
"fmt"
"testing"

"google.golang.org/grpc/credentials"
)

// A struct that implements AuthInfo interface and implements CommonAuthInfo() method.
type testAuthInfo struct {
credentials.CommonAuthInfo
}

func (ta testAuthInfo) AuthType() string {
return "testAuthInfo"
}

func TestPeerSecurityLevel(t *testing.T) {
testCases := []struct {
authLevel credentials.SecurityLevel
testLevel credentials.SecurityLevel
want bool
}{
{
authLevel: credentials.PrivacyAndIntegrity,
testLevel: credentials.PrivacyAndIntegrity,
want: true,
},
{
authLevel: credentials.IntegrityOnly,
testLevel: credentials.PrivacyAndIntegrity,
want: false,
},
{
authLevel: credentials.IntegrityOnly,
testLevel: credentials.NoSecurity,
want: true,
},
{
authLevel: credentials.InvalidSecurityLevel,
testLevel: credentials.IntegrityOnly,
want: true,
},
{
authLevel: credentials.InvalidSecurityLevel,
testLevel: credentials.PrivacyAndIntegrity,
want: true,
},
}
for _, tc := range testCases {
ctx := NewContext(context.Background(), &Peer{AuthInfo: testAuthInfo{credentials.CommonAuthInfo{SecurityLevel: tc.authLevel}}})
p, ok := FromContext(ctx)
if !ok {
t.Fatalf("Unable to get peer from context")
}
err := credentials.CheckSecurityLevel(p.AuthInfo, tc.testLevel)
if tc.want && (err != nil) {
t.Fatalf("CheckSeurityLevel(%s, %s) returned failure but want success", tc.authLevel.String(), tc.testLevel.String())
} else if !tc.want && (err == nil) {
t.Fatalf("CheckSeurityLevel(%s, %s) returned success but want failure", tc.authLevel.String(), tc.testLevel.String())
}
}
}

type addr struct {
ipAddress string
}

func (addr) Network() string { return "" }
func (a *addr) String() string { return a.ipAddress }

func TestPeerStringer(t *testing.T) {
testCases := []struct {
addr *addr
authLevel credentials.SecurityLevel
want string
}{
{
addr: &addr{"example.com:1234"},
authLevel: credentials.PrivacyAndIntegrity,
want: "Peer{Addr: 'example.com:1234', AuthInfo: 'testAuthInfo'}",
},
{
addr: &addr{"1.2.3.4:1234"},
authLevel: -1,
want: "Peer{Addr: '1.2.3.4:1234'}",
},
{
authLevel: credentials.InvalidSecurityLevel,
want: "Peer{AuthInfo: 'testAuthInfo'}",
},
{
authLevel: -1,
want: "Peer{}",
},
}
for _, tc := range testCases {
ctx := NewContext(context.Background(), &Peer{Addr: tc.addr, AuthInfo: testAuthInfo{credentials.CommonAuthInfo{SecurityLevel: tc.authLevel}}})
p, ok := FromContext(ctx)
if tc.authLevel == -1 {
p.AuthInfo = nil
}
if tc.addr == nil {
p.Addr = nil
}
if !ok {
t.Fatalf("Unable to get peer from context")
}
if p.String() != tc.want {
t.Fatalf("Error using peer String(): expected %q, got %q", tc.want, p.String())
}
}
t.Run("test String on nil Peer", func(st *testing.T) {
var test *Peer
if test.String() != "Peer<nil>" {
st.Fatalf("Error using String on nil Peer. Expected 'Peer<nil>', got: '%s'", test.String())
}
})
t.Run("test Stringer on context", func(st *testing.T) {
ctx := NewContext(context.Background(), &Peer{Addr: &addr{"1.2.3.4:1234"}, AuthInfo: testAuthInfo{credentials.CommonAuthInfo{SecurityLevel: credentials.PrivacyAndIntegrity}}})
if fmt.Sprintf("%v", ctx) != "context.Background.WithValue(type peer.peerKey, val Peer{Addr: '1.2.3.4:1234', AuthInfo: 'testAuthInfo'})" {
st.Fatalf("Error printing context with embedded Peer. Got: %v", ctx)
}
})
}

0 comments on commit bc88d17

Please sign in to comment.