Skip to content

Commit 5cf9fca

Browse files
authored
[common-go] Support rate limiting by enum key (#16899)
1 parent 95feb1a commit 5cf9fca

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

components/common-go/grpc/ratelimit.go

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package grpc
66

77
import (
88
"context"
9+
"strconv"
910
"strings"
1011
"time"
1112

@@ -110,12 +111,16 @@ func getFieldValue(msg protoreflect.Message, path []string) (val string, ok bool
110111
return getFieldValue(child, path[1:])
111112
}
112113

113-
if field.Kind() != protoreflect.StringKind {
114-
// we only support string fields
114+
switch field.Kind() {
115+
case protoreflect.StringKind:
116+
return msg.Get(field).String(), true
117+
case protoreflect.EnumKind:
118+
enumNum := msg.Get(field).Enum()
119+
return strconv.Itoa(int(enumNum)), true
120+
default:
121+
// we only support string and enum fields
115122
return "", false
116123
}
117-
118-
return msg.Get(field).String(), true
119124
}
120125

121126
// RatelimitingInterceptor limits how often a gRPC function may be called. If the limit has been

components/common-go/grpc/ratelimit_test.go

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,15 @@
55
package grpc
66

77
import (
8+
"strconv"
89
"strings"
910
"testing"
1011

1112
"github.com/google/go-cmp/cmp"
1213
"google.golang.org/protobuf/proto"
1314
"google.golang.org/protobuf/types/known/apipb"
1415
"google.golang.org/protobuf/types/known/sourcecontextpb"
16+
"google.golang.org/protobuf/types/known/typepb"
1517
)
1618

1719
func TestGetFieldValue(t *testing.T) {
@@ -32,11 +34,23 @@ func TestGetFieldValue(t *testing.T) {
3234
Expectation: Expectation{Found: true, Val: "bar"},
3335
},
3436
{
35-
Name: "empty field",
37+
Name: "empty string field",
3638
Message: &apipb.Api{},
3739
Path: "name",
3840
Expectation: Expectation{Found: true},
3941
},
42+
{
43+
Name: "enum field",
44+
Message: &apipb.Api{Syntax: typepb.Syntax_SYNTAX_PROTO3},
45+
Path: "syntax",
46+
Expectation: Expectation{Found: true, Val: strconv.Itoa(int(typepb.Syntax_SYNTAX_PROTO3))},
47+
},
48+
{
49+
Name: "empty enum field",
50+
Message: &apipb.Api{},
51+
Path: "syntax",
52+
Expectation: Expectation{Found: true, Val: "0"},
53+
},
4054
{
4155
Name: "non-existent field",
4256
Message: &apipb.Api{},

0 commit comments

Comments
 (0)