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

Generate unbound methods #1652

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions protoc-gen-grpc-gateway/descriptor/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ type Registry struct {
// warnOnUnboundMethods causes the registry to emit warning logs if an RPC method
// has no HttpRule annotation.
warnOnUnboundMethods bool

// generateUnboundMethods causes the registry to generate proxy methods even for
// RPC methods that have no HttpRule annotation.
generateUnboundMethods bool
}

type repeatedFieldSeparator struct {
Expand Down Expand Up @@ -533,6 +537,11 @@ func (r *Registry) SetWarnOnUnboundMethods(warn bool) {
r.warnOnUnboundMethods = warn
}

// SetGenerateUnboundMethods sets generateUnboundMethods
func (r *Registry) SetGenerateUnboundMethods(generate bool) {
r.generateUnboundMethods = generate
}

// sanitizePackageName replaces unallowed character in package name
// with allowed character.
func sanitizePackageName(pkgName string) string {
Expand Down
29 changes: 25 additions & 4 deletions protoc-gen-grpc-gateway/descriptor/services.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,20 @@ func (r *Registry) loadServices(file *File) error {
optsList = append(optsList, opts)
}
if len(optsList) == 0 {
logFn := glog.V(1).Infof
if r.warnOnUnboundMethods {
logFn = glog.Warningf
if r.generateUnboundMethods {
defaultOpts, err := defaultAPIOptions(svc, md)
if err != nil {
glog.Errorf("Failed to generate default HttpRule from %s.%s: %v", svc.GetName(), md.GetName(), err)
return err
}
optsList = append(optsList, defaultOpts)
} else {
logFn := glog.V(1).Infof
if r.warnOnUnboundMethods {
logFn = glog.Warningf
}
logFn("No HttpRule found for method: %s.%s", svc.GetName(), md.GetName())
}
logFn("No HttpRule found for method: %s.%s", svc.GetName(), md.GetName())
}
meth, err := r.newMethod(svc, md, optsList)
if err != nil {
Expand Down Expand Up @@ -205,6 +214,18 @@ func extractAPIOptions(meth *descriptor.MethodDescriptorProto) (*options.HttpRul
return opts, nil
}

func defaultAPIOptions(svc *Service, md *descriptor.MethodDescriptorProto) (*options.HttpRule, error) {
// FQSN prefixes the service's full name with a '.', e.g.: '.example.ExampleService'
fqsn := strings.TrimPrefix(svc.FQSN(), ".")
rule := &options.HttpRule{
Pattern: &options.HttpRule_Post{
Post: fmt.Sprintf("/%s/%s", fqsn, md.GetName()),
},
Body: "*",
}
johanbrandhorst marked this conversation as resolved.
Show resolved Hide resolved
return rule, nil
}

func (r *Registry) newParam(meth *Method, path string) (Parameter, error) {
msg := meth.RequestType
fields, err := r.resolveFieldPath(msg, path, true)
Expand Down
73 changes: 72 additions & 1 deletion protoc-gen-grpc-gateway/descriptor/services_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ func compilePath(t *testing.T, path string) httprule.Template {
}

func testExtractServices(t *testing.T, input []*descriptor.FileDescriptorProto, target string, wantSvcs []*Service) {
reg := NewRegistry()
testExtractServicesWithRegistry(t, NewRegistry(), input, target, wantSvcs)
}

func testExtractServicesWithRegistry(t *testing.T, reg *Registry, input []*descriptor.FileDescriptorProto, target string, wantSvcs []*Service) {
for _, file := range input {
reg.loadFile(file)
}
Expand Down Expand Up @@ -278,6 +281,74 @@ func TestExtractServicesWithoutAnnotation(t *testing.T) {
testExtractServices(t, []*descriptor.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services)
}

func TestExtractServicesGenerateUnboundMethods(t *testing.T) {
src := `
name: "path/to/example.proto",
package: "example"
message_type <
name: "StringMessage"
field <
name: "string"
number: 1
label: LABEL_OPTIONAL
type: TYPE_STRING
>
>
service <
name: "ExampleService"
method <
name: "Echo"
input_type: "StringMessage"
output_type: "StringMessage"
>
>
`
var fd descriptor.FileDescriptorProto
if err := proto.UnmarshalText(src, &fd); err != nil {
t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err)
}
msg := &Message{
DescriptorProto: fd.MessageType[0],
Fields: []*Field{
{
FieldDescriptorProto: fd.MessageType[0].Field[0],
},
},
}
file := &File{
FileDescriptorProto: &fd,
GoPkg: GoPackage{
Path: "path/to/example.pb",
Name: "example_pb",
},
Messages: []*Message{msg},
Services: []*Service{
{
ServiceDescriptorProto: fd.Service[0],
Methods: []*Method{
{
MethodDescriptorProto: fd.Service[0].Method[0],
RequestType: msg,
ResponseType: msg,
Bindings: []*Binding{
{
PathTmpl: compilePath(t, "/example.ExampleService/Echo"),
HTTPMethod: "POST",
Body: &Body{FieldPath: nil},
},
},
},
},
},
},
}

crossLinkFixture(file)
reg := NewRegistry()
reg.SetGenerateUnboundMethods(true)
testExtractServicesWithRegistry(t, reg, []*descriptor.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services)
}

func TestExtractServicesCrossPackage(t *testing.T) {
srcs := []string{
`
Expand Down
7 changes: 7 additions & 0 deletions protoc-gen-grpc-gateway/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ var (
allowColonFinalSegments = flag.Bool("allow_colon_final_segments", false, "determines whether colons are permitted in the final segment of a path")
versionFlag = flag.Bool("version", false, "print the current version")
warnOnUnboundMethods = flag.Bool("warn_on_unbound_methods", false, "emit a warning message if an RPC method has no HttpRule annotation")
generateUnboundMethods = flag.Bool("generate_unbound_methods", false, "generate proxy methods even for RPC methods that have no HttpRule annotation")
)

// Variables set by goreleaser at build time
Expand Down Expand Up @@ -97,7 +98,13 @@ func main() {
reg.SetAllowDeleteBody(*allowDeleteBody)
reg.SetAllowRepeatedFieldsInBody(*allowRepeatedFieldsInBody)
reg.SetAllowColonFinalSegments(*allowColonFinalSegments)

if *warnOnUnboundMethods && *generateUnboundMethods {
glog.Warningf("Option warn_on_unbound_methods has no effect when generate_unbound_methods is used.")
}

reg.SetWarnOnUnboundMethods(*warnOnUnboundMethods)
reg.SetGenerateUnboundMethods(*generateUnboundMethods)
if err := reg.SetRepeatedPathParamSeparator(*repeatedPathParamSeparator); err != nil {
emitError(err)
return
Expand Down