Skip to content

Commit

Permalink
feat(gengapic): rest-numeric-enums option enables enum-encoding sys p…
Browse files Browse the repository at this point in the history
…aram (#1022)

For REGAPIC API calls, when the `rest-numeric-enums` plugin option is provided, include the new system parameter variant of `$alt=json` that enables proto-json encoding of enums in server responses as integers - `enum-encoding=int`.  The default is false. Includes the bazel attribute as well.

Also updates the README with option documentation.

Requested in http://b/232457394.
  • Loading branch information
noahdietz authored Jul 27, 2022
1 parent 8340671 commit 6bbbf6f
Show file tree
Hide file tree
Showing 8 changed files with 57 additions and 10 deletions.
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,14 @@ The configuration supported by the plugin option includes:
* `api-service-config`: the path the service YAML file.
* This is used for service-level client documentation.

* `transport`: the desired transport(s) to generate, delimited by `+` e.g. `grpc+rest`.
* Acceptable values are `grpc` and `rest`.
* Defaults to `grpc`.

* `rest-numeric-enums`: enables requesting response enums be encoded as numbers.
* Not enabled by default.
* Only effective when `rest` is included as a `transport` to be generated.

Bazel
-----

Expand Down Expand Up @@ -148,6 +156,15 @@ following attributes:

* `metadata`: if `True`, [GapicMetadata](https://github.com/googleapis/googleapis/blob/master/gapic/metadata/gapic_metadata.proto) will be generated in JSON form. The default is `False`.

* `transport`: the desired transport(s) to generate, delimited by `+` e.g. `grpc+rest`.
* Acceptable values are `grpc` and `rest`.
* Defaults to `grpc`.

* `rest_numeric_enums`: if `True`, enables generation of system parameter requesting
response enums be encoded as numbers.
* Default is `False`.
* Only effective when `rest` is included as a `transport` to be generated.

Docker Wrapper
--------------
The generator can also be executed via a Docker container. The image containes `protoc`, the microgenerator
Expand Down
21 changes: 13 additions & 8 deletions internal/gengapic/genrest.go
Original file line number Diff line number Diff line change
Expand Up @@ -380,9 +380,6 @@ func (g *generator) getLeafs(msg *descriptor.DescriptorProto, excludedFields ...
func (g *generator) generateQueryString(m *descriptor.MethodDescriptorProto) {
p := g.printf
queryParams := g.queryParams(m)
if len(queryParams) == 0 {
return
}

// We want to iterate over fields in a deterministic order
// to prevent spurious deltas when regenerating gapics.
Expand All @@ -392,8 +389,13 @@ func (g *generator) generateQueryString(m *descriptor.MethodDescriptorProto) {
}
sort.Strings(fields)

g.imports[pbinfo.ImportSpec{Path: "net/url"}] = true
p("params := url.Values{}")
if g.opts.restNumericEnum || len(fields) > 0 {
g.imports[pbinfo.ImportSpec{Path: "net/url"}] = true
p("params := url.Values{}")
}
if g.opts.restNumericEnum {
p(`params.Add("$alt", "json;enum-encoding=int")`)
}
for _, path := range fields {
field := queryParams[path]
required := isRequired(field)
Expand Down Expand Up @@ -438,9 +440,12 @@ func (g *generator) generateQueryString(m *descriptor.MethodDescriptorProto) {
p(" %s", paramAdd)
p("}")
}
p("")
p("baseUrl.RawQuery = params.Encode()")
p("")

if g.opts.restNumericEnum || len(fields) > 0 {
p("")
p("baseUrl.RawQuery = params.Encode()")
p("")
}
}

func (g *generator) generateBaseURL(info *httpInfo, ret string) {
Expand Down
2 changes: 1 addition & 1 deletion internal/gengapic/genrest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -698,7 +698,7 @@ func TestGenRestMethod(t *testing.T) {
{
name: "unary_rpc",
method: unaryRPC,
options: &options{},
options: &options{restNumericEnum: true},
imports: map[pbinfo.ImportSpec]bool{
{Path: "bytes"}: true,
{Path: "fmt"}: true,
Expand Down
4 changes: 4 additions & 0 deletions internal/gengapic/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ type options struct {
transports []transport
metadata bool
diregapic bool
restNumericEnum bool
pkgOverrides map[string]string
}

Expand Down Expand Up @@ -87,6 +88,9 @@ func parseOptions(parameter *string) (*options, error) {
case "diregapic":
opts.diregapic = true
continue
case "rest-numeric-enums":
opts.restNumericEnum = true
continue
}

e := strings.IndexByte(s, '=')
Expand Down
13 changes: 12 additions & 1 deletion internal/gengapic/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,17 @@ func TestParseOptions(t *testing.T) {
},
expectErr: false,
},
{
param: "transport=rest,rest-numeric-enums,go-gapic-package=path;pkg",
expectedOpts: &options{
transports: []transport{rest},
pkgPath: "path",
pkgName: "pkg",
outDir: "path",
restNumericEnum: true,
},
expectErr: false,
},
{
param: "transport=tcp,go-gapic-package=path;pkg",
expectErr: true,
Expand Down Expand Up @@ -131,7 +142,7 @@ func TestParseOptions(t *testing.T) {
}

if !reflect.DeepEqual(opts, tst.expectedOpts) {
t.Errorf("parseOptions(%s) = %v, expected %v", tst.param, opts, tst.expectedOpts)
t.Errorf("parseOptions(%s) = %+v, expected %+v", tst.param, opts, tst.expectedOpts)
continue
}
}
Expand Down
5 changes: 5 additions & 0 deletions internal/gengapic/testdata/rest_UnaryRPC.want
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ func (c *fooRESTClient) UnaryRPC(ctx context.Context, req *foopb.Foo, opts ...ga
}
baseUrl.Path += fmt.Sprintf("/v1/foo")

params := url.Values{}
params.Add("$alt", "json;enum-encoding=int")

baseUrl.RawQuery = params.Encode()

// Build HTTP headers from client and context metadata.
routingHeaders := ""
routingHeadersMap := make(map[string]string)
Expand Down
4 changes: 4 additions & 0 deletions rules_go_gapic/go_gapic.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ def go_gapic_library(
metadata = False,
transport = "grpc",
diregapic = False,
rest_numeric_enums = False,
**kwargs):

file_args = {}
Expand All @@ -117,6 +118,9 @@ def go_gapic_library(
if diregapic:
plugin_args.append("diregapic")

if rest_numeric_enums:
plugin_args.append("rest-numeric-enums")

srcjar_name = name+"_srcjar"
raw_srcjar_name = srcjar_name+"_raw"
output_suffix = ".srcjar"
Expand Down
1 change: 1 addition & 0 deletions showcase/showcase.bash
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ protoc \
--go_out=plugins=grpc:./gen \
--go_gapic_out ./gen \
--go_gapic_opt 'transport=rest+grpc' \
--go_gapic_opt 'rest-numeric-enums' \
--go_gapic_opt 'go-gapic-package=github.com/googleapis/gapic-showcase/client;client' \
--go_gapic_opt 'grpc-service-config=showcase_grpc_service_config.json' \
--go_gapic_opt 'api-service-config=showcase_v1beta1.yaml' \
Expand Down

0 comments on commit 6bbbf6f

Please sign in to comment.