-
Notifications
You must be signed in to change notification settings - Fork 47
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
feat: add RPCs returning unknown enum values over REST #856
Draft
vchudnov-g
wants to merge
7
commits into
main
Choose a base branch
from
regapic-parse-error
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
ed34451
Infrastructure to provide REST-specific handlers via hooks
vchudnov-g 5bfe059
Provide an unknown enum
vchudnov-g acba666
Added test for TestRepeatWithUnknownEnum
vchudnov-g 1143406
Add and implement RepeatWithUnknownOptionalEnum RPC
vchudnov-g 1ee9d48
Add test for RepeatWithUnknownOptionalEnum
vchudnov-g ea6a882
Use non-zero value as a sentinel
vchudnov-g 3b54211
Cosmetic fixes.
vchudnov-g File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
// Copyright 2021 Google LLC | ||
// | ||
// 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 | ||
// | ||
// https://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 main | ||
|
||
import ( | ||
"fmt" | ||
"io/ioutil" | ||
"net/http" | ||
"strings" | ||
"testing" | ||
|
||
"github.com/googleapis/gapic-showcase/server/genproto" | ||
genprotopb "github.com/googleapis/gapic-showcase/server/genproto" | ||
"github.com/googleapis/gapic-showcase/util/genrest/resttools" | ||
"google.golang.org/protobuf/encoding/protojson" | ||
) | ||
|
||
// TestRepeatWithUnknownEnum tests both RepeatWithUnknownEnum and RepeatWithUnknownOptionalEnum | ||
func TestRepeatWithUnknownEnum(t *testing.T) { | ||
_, server, err := complianceSuiteTestSetup() | ||
if err != nil { | ||
t.Fatal(err) | ||
} | ||
server.Start() | ||
defer server.Close() | ||
|
||
resttools.JSONMarshaler.Replace(nil) | ||
defer resttools.JSONMarshaler.Restore() | ||
|
||
request := &genprotopb.RepeatRequest{} | ||
|
||
for idx, variant := range []string{"invalidenum", "invalidoptionalenum"} { | ||
errorPrefix := fmt.Sprintf("[%d %q]", idx, variant) | ||
|
||
// First ensure the request would be otherwise successful | ||
responseBody, requestBody := getJSONResponse(t, request, server.URL+"/v1beta1/repeat:body", errorPrefix) | ||
var response genproto.RepeatResponse | ||
if err := protojson.Unmarshal(responseBody, &response); err != nil { | ||
t.Fatalf("%s could not unmarshal valid response body: %s\n response body: %s\n request: %s\n", | ||
errorPrefix, err, string(responseBody), string(requestBody)) | ||
} | ||
|
||
// Then ensure the expected error occurs | ||
responseBody, requestBody = getJSONResponse(t, request, | ||
fmt.Sprintf("%s/v1beta1/repeat:%s", server.URL, variant), errorPrefix) | ||
err = protojson.Unmarshal(responseBody, &response) | ||
if err == nil { | ||
t.Fatalf("%s did not receive an error:\n response body: %s\n request: %s\n", | ||
errorPrefix, string(responseBody), string(requestBody)) | ||
} | ||
if !strings.Contains(err.Error(), "invalid value for enum type") { | ||
t.Fatalf("%s received different error than expected: %s\n response body: %s\n request: %s\n", | ||
errorPrefix, err, string(responseBody), string(requestBody)) | ||
} | ||
} | ||
} | ||
|
||
// getJSONResponse is a helper function for TestRepeatWithUnknownEnum. It issues the REST request to | ||
// the given URI and returns both the response and request JSON bodies. | ||
func getJSONResponse(t *testing.T, request *genprotopb.RepeatRequest, uri, errorPrefix string) (responseBody, requestBody []byte) { | ||
verb := "POST" | ||
requestBody, err := resttools.ToJSON().Marshal(request) | ||
if err != nil { | ||
t.Fatalf("%s error encoding request: %s", errorPrefix, err) | ||
} | ||
|
||
httpRequest, err := http.NewRequest(verb, uri, strings.NewReader(string(requestBody))) | ||
if err != nil { | ||
t.Fatalf("%s error creating request: %s", errorPrefix, err) | ||
} | ||
resttools.PopulateRequestHeaders(httpRequest) | ||
|
||
httpResponse, err := http.DefaultClient.Do(httpRequest) | ||
if err != nil { | ||
t.Fatalf("%s error issuing call: %s", errorPrefix, err) | ||
} | ||
|
||
// Check for successful response. | ||
if got, want := httpResponse.StatusCode, http.StatusOK; got != want { | ||
t.Errorf("%s response code: got %d, want %d\n %s %s\n\n", | ||
errorPrefix, got, want, verb, uri) | ||
} | ||
|
||
responseBody, err = ioutil.ReadAll(httpResponse.Body) | ||
httpResponse.Body.Close() | ||
if err != nil { | ||
t.Fatalf("%s could not read httpResponse body: %s", errorPrefix, err) | ||
} | ||
return responseBody, requestBody | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,6 @@ | ||
# server/genrest | ||
|
||
This directory contains auto-generated files used to implement a REST endpoint | ||
for Showcase services. | ||
This directory contains mostly auto-generated files used to implement a REST | ||
endpoint for Showcase services. The `*_custom.go` files contain manually written | ||
REST-specific handlers, which are useful for helping generators test | ||
REST-specific functionality (such as invalid JSON). |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
// Copyright 2021 Google LLC | ||
// | ||
// 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 | ||
// | ||
// https://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 genrest | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"net/http" | ||
|
||
genprotopb "github.com/googleapis/gapic-showcase/server/genproto" | ||
"github.com/googleapis/gapic-showcase/util/genrest/resttools" | ||
) | ||
|
||
// customRepeatWithUnknownEnum provides REST-specific handling for a RepeatWithUnknownEnum | ||
// request. It returns a JSON response with an unknown enum symbol string in an enum field. | ||
func (backend *RESTBackend) customRepeatWithUnknownEnum(w http.ResponseWriter, r *http.Request, request *genprotopb.RepeatRequest) { | ||
mutator := func(data *genprotopb.ComplianceData, sentinelValue genprotopb.ComplianceData_LifeKingdom) { | ||
data.FKingdom = sentinelValue | ||
} | ||
backend.customRepeatWithUnknownEnumMethod(w, r, request, mutator) | ||
} | ||
|
||
// customRepeatWithUnknownOptionalEnum provides REST-specific handling for a | ||
// RepeatWithUnknownOptionalEnum request. It returns a JSON response with an unknown enum symbol | ||
// string in an enum field. | ||
func (backend *RESTBackend) customRepeatWithUnknownOptionalEnum(w http.ResponseWriter, r *http.Request, request *genprotopb.RepeatRequest) { | ||
mutator := func(data *genprotopb.ComplianceData, sentinelValue genprotopb.ComplianceData_LifeKingdom) { | ||
data.PKingdom = &sentinelValue | ||
} | ||
backend.customRepeatWithUnknownEnumMethod(w, r, request, mutator) | ||
} | ||
|
||
// customRepeatWithUnknownEnumMethod provides REST-specific handling for the RepeatWithUnknown*Enum | ||
// request. It returns a JSON response with an unknown enum symbol string in an enum field. | ||
func (backend *RESTBackend) customRepeatWithUnknownEnumMethod(w http.ResponseWriter, r *http.Request, request *genprotopb.RepeatRequest, mutate enumMutator) { | ||
marshaler := resttools.ToJSON() | ||
|
||
response, err := backend.ComplianceServer.RepeatWithUnknownEnum(context.Background(), request) | ||
if err != nil { | ||
// TODO: Properly handle error. Is StatusInternalServerError (500) the right response? | ||
backend.Error(w, http.StatusInternalServerError, "server error: %s", err.Error()) | ||
return | ||
} | ||
|
||
// Make sure we have at least one sentinel value before serializing properly; we will then | ||
// replace the sentinel value in the JSON with an unknown value. The sentinel value should | ||
// be a non-zero value, since unset non-proto-optional fields will serialize with the zero | ||
// value, which would result in all of these always getting the new, unknown value | ||
sentinelValue := genprotopb.ComplianceData_ANIMALIA | ||
sentinelString := genprotopb.ComplianceData_LifeKingdom_name[int32(sentinelValue)] | ||
if response.Request == nil { | ||
response.Request = &genprotopb.RepeatRequest{} | ||
} | ||
if response.Request.Info == nil { | ||
response.Request.Info = &genprotopb.ComplianceData{} | ||
} | ||
mutate(response.Request.Info, sentinelValue) | ||
|
||
json, err := marshaler.Marshal(response) | ||
if err != nil { | ||
backend.Error(w, http.StatusInternalServerError, "error json-encoding response: %s", err.Error()) | ||
return | ||
} | ||
|
||
// Change the sentinel string to an unknown value. | ||
json = bytes.ReplaceAll(json, []byte(sentinelString), []byte("LIFE_KINGDOM_NEW")) | ||
|
||
w.Write(json) | ||
} | ||
|
||
// enumMutator represents a function that modifies `data` in place using `sentinelValue`. | ||
type enumMutator func(data *genprotopb.ComplianceData, sentinelValue genprotopb.ComplianceData_LifeKingdom) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could these be one request with two fields and maybe a field to toggle behavior? For example, we have the
Echo
RPC which could return either an EchoResponse or an error status depending on what was sent in the request oneof. Might simplify the implementation a bit?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've been thinking about this (and sidetracked by other issues, sorry). We could keep just the previously existing RPCs and add a top-level field to
RepeatRequest
to generate the unknown enum. In fact, I would changeRepeatRequest.server_verify
to be an enum likeserver_behavior
that could beverify
, orgenerate_unknown_enum
, or something else in the future.Not too concerned about that being a breaking change because (a) most generators are not yet using the compliance suite, and (b) the compliance suite is meant to be parsed form this repo and then used to issue requests, without the client code modifying the request.
WDYT?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah that sounds great to me. Thanks for considering this.