Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

peer and metadata: Implement the Stringer interface for Peer and Metadata #7137

Merged
merged 9 commits into from May 6, 2024
14 changes: 14 additions & 0 deletions metadata/metadata.go
Expand Up @@ -90,6 +90,20 @@ 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.
AnomalRoil marked this conversation as resolved.
Show resolved Hide resolved
func (md MD) String() string {
var sb strings.Builder
fmt.Fprintf(&sb, "MD{")
arvindbr8 marked this conversation as resolved.
Show resolved Hide resolved
for k, v := range md {
if sb.Len() > 3 {
fmt.Fprintf(&sb, ", ")
}
arvindbr8 marked this conversation as resolved.
Show resolved Hide resolved
fmt.Fprintf(&sb, "%s=[%s]", k, strings.Join(v, ", "))
}
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
arvindbr8 marked this conversation as resolved.
Show resolved Hide resolved
}{
{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()
AnomalRoil marked this conversation as resolved.
Show resolved Hide resolved
for _, want := range test.want {
if !strings.Contains(strMd, want) {
t.Fatalf("Metadata string '%s' is missing '%s'", strMd, want)
AnomalRoil marked this conversation as resolved.
Show resolved Hide resolved
AnomalRoil marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
}

// 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
25 changes: 25 additions & 0 deletions peer/peer.go
Expand Up @@ -22,7 +22,9 @@ package peer

import (
"context"
"fmt"
"net"
"strings"

"google.golang.org/grpc/credentials"
)
Expand All @@ -39,6 +41,29 @@ 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>"
}
arvindbr8 marked this conversation as resolved.
Show resolved Hide resolved
sb := &strings.Builder{}
sb.WriteString("Peer{")
if p.Addr != nil {
arvindbr8 marked this conversation as resolved.
Show resolved Hide resolved
fmt.Fprintf(sb, "Addr: '%s', ", p.Addr.String())
} else {
fmt.Fprintf(sb, "Addr: <nil>, ")
}
if p.AuthInfo != nil {
AnomalRoil marked this conversation as resolved.
Show resolved Hide resolved
fmt.Fprintf(sb, "AuthInfo: '%s'", p.AuthInfo.AuthType())
} else {
fmt.Fprintf(sb, "AuthInfo: <nil>")
}
sb.WriteString("}")

return sb.String()
}

type peerKey struct{}

// NewContext creates a new context with peer information attached.
Expand Down
145 changes: 145 additions & 0 deletions peer/peer_test.go
@@ -0,0 +1,145 @@
/*
*
* Copyright 2024 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

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) {
AnomalRoil marked this conversation as resolved.
Show resolved Hide resolved
testCases := []struct {
AnomalRoil marked this conversation as resolved.
Show resolved Hide resolved
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}}})
AnomalRoil marked this conversation as resolved.
Show resolved Hide resolved
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', AuthInfo: <nil>}",
},
{
authLevel: credentials.InvalidSecurityLevel,
want: "Peer{Addr: <nil>, AuthInfo: 'testAuthInfo'}",
},
{
authLevel: -1,
want: "Peer{Addr: <nil>, AuthInfo: <nil>}",
},
}
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())
}
}
AnomalRoil marked this conversation as resolved.
Show resolved Hide resolved
t.Run("test String on nil Peer", func(st *testing.T) {
AnomalRoil marked this conversation as resolved.
Show resolved Hide resolved
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) {
AnomalRoil marked this conversation as resolved.
Show resolved Hide resolved
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)
}
})
}