Repository: googleapis/api-linter
Pull request #648 (2020-10-07 13:50:07)

Add rule for AIP-235 response message name
Part of #612.


Patch:
diff --git a/docs/rules/0235/response-message-name.md b/docs/rules/0235/response-message-name.md
new file mode 100644
index 0000000..fc6a787
--- /dev/null
+++ b/docs/rules/0235/response-message-name.md
@@ -0,0 +1,78 @@
+---
+rule:
+  aip: 235
+  name: [core, '0235', response-message-name]
+  summary: Batch Delete methods must have standardized response message names.
+permalink: /235/response-message-name
+redirect_from:
+  - /0235/response-message-name
+---
+
+# Batch Delete methods: Response message
+
+This rule enforces that all `BatchDelete` RPCs have a response message name of
+`google.protobuf.Empty` or `BatchDelete*Response`, as mandated in [AIP-235][].
+
+## Details
+
+This rule looks at any RPCs whose name starts with `BatchDelete`, and
+complains if the name of the corresponding returned message does not match
+`google.protobuf.Empty` or the name of the RPC with the suffix `Response`
+appended, the latter of which is mandated in [AIP-235][] for soft-delete
+operations.
+
+It also permits a response of `google.longrunning.Operation`; in this case, it
+checks the `response_type` in the `google.longrunning.operation_info`
+annotation and ensures that _it_ is `google.protobuf.Empty` or corresponds to
+the name of the RPC with the suffix `Response` appended, as mandated in
+[AIP-151][].
+
+## Examples
+
+**Incorrect** code for this rule:
+
+```proto
+// Incorrect.
+// Should be `google.protobuf.Empty` or `BatchDeleteBooksResponse`.
+rpc BatchDeleteBooks(BatchDeleteBooksRequest) returns (BooksResponse) {
+  option (google.api.http) = {
+    post: "/v1/{parent=publishers/*}/books:batchDelete"
+    body: "*"
+  };
+}
+```
+
+**Correct** code for this rule:
+
+```proto
+// Correct.
+rpc BatchDeleteBooks(BatchDeleteBooksRequest) returns (google.protobuf.Empty) {
+  option (google.api.http) = {
+    post: "/v1/{parent=publishers/*}/books:batchDelete"
+    body: "*"
+  };
+}
+```
+
+## Disabling
+
+If you need to violate this rule, use a leading comment above the method.
+Remember to also include an [aip.dev/not-precedent][] comment explaining why.
+
+```proto
+// (-- api-linter: core::0235::response-message-name=disabled
+//     aip.dev/not-precedent: We need to do this because reasons. --)
+rpc BatchDeleteBooks(BatchDeleteBooksRequest) returns (BooksResponse) {
+  option (google.api.http) = {
+    post: "/v1/{parent=publishers/*}/books:batchDelete"
+    body: "*"
+  };
+}
+```
+
+If you need to violate this rule for an entire file, place the comment at the
+top of the file.
+
+[aip-151]: https://aip.dev/151
+[aip-235]: https://aip.dev/235
+[aip.dev/not-precedent]: https://aip.dev/not-precedent
diff --git a/rules/aip0235/aip0235.go b/rules/aip0235/aip0235.go
index 84a0b6f..202f306 100644
--- a/rules/aip0235/aip0235.go
+++ b/rules/aip0235/aip0235.go
@@ -39,6 +39,7 @@ func AddRules(r lint.RuleRegistry) error {
 		requestParentReference,
 		requestRequestsBehavior,
 		requestUnknownFields,
+		responseMessageName,
 		responseResourceField,
 	)
 }
diff --git a/rules/aip0235/response_message_name.go b/rules/aip0235/response_message_name.go
new file mode 100644
index 0000000..78035a8
--- /dev/null
+++ b/rules/aip0235/response_message_name.go
@@ -0,0 +1,66 @@
+// Copyright 2020 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 aip0235
+
+import (
+	"fmt"
+
+	"bitbucket.org/creachadair/stringset"
+	"github.com/googleapis/api-linter/lint"
+	"github.com/googleapis/api-linter/locations"
+	"github.com/googleapis/api-linter/rules/internal/utils"
+	"github.com/jhump/protoreflect/desc"
+)
+
+// Batch Delete method should have a properly named response message.
+var responseMessageName = &lint.MethodRule{
+	Name:   lint.NewRuleName(235, "response-message-name"),
+	OnlyIf: isBatchDeleteMethod,
+	LintMethod: func(m *desc.MethodDescriptor) []lint.Problem {
+		got := m.GetOutputType().GetFullyQualifiedName()
+		if got == "google.longrunning.Operation" {
+			got = utils.GetOperationInfo(m).GetResponseType()
+		} else if got != "google.protobuf.Empty" {
+			got = m.GetOutputType().GetName()
+		}
+
+		wantSoftDelete := m.GetName() + "Response"
+		want := stringset.New(
+			"google.protobuf.Empty",
+			wantSoftDelete,
+		)
+
+		// Rule check: Establish that for methods such as `BatchDeleteFoos`, the
+		// response message should be named `BatchDeleteFoosResponse` or
+		// `google.protobuf.Empty`.
+		//
+		// Note: If `got` is empty string, this is an unannotated LRO.
+		// The AIP-151 rule will whine about that, and this rule should not as it
+		// would be confusing.
+		if !want.Contains(got) && got != "" {
+			return []lint.Problem{{
+				Message: fmt.Sprintf(
+					"Batch Delete RPCs should have response message type of `google.protobuf.Empty` or `%s` (for soft-deletes only), not %q.",
+					wantSoftDelete, got,
+				),
+				Suggestion: "google.protobuf.Empty",
+				Descriptor: m,
+				Location:   locations.MethodResponseType(m),
+			}}
+		}
+
+		return nil
+	},
+}


Test patch:
diff --git a/rules/aip0235/response_message_name_test.go b/rules/aip0235/response_message_name_test.go
new file mode 100644
index 0000000..33ba525
--- /dev/null
+++ b/rules/aip0235/response_message_name_test.go
@@ -0,0 +1,122 @@
+// Copyright 2020 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 aip0235
+
+import (
+	"strings"
+	"testing"
+
+	"github.com/googleapis/api-linter/rules/internal/testutils"
+)
+
+type responseMessageNameTest struct {
+	testName         string
+	MethodName       string
+	MethodAnnotation string
+	Response         string
+	problems         testutils.Problems
+}
+
+func (t responseMessageNameTest) ResponseExternal() bool {
+	return strings.Contains(t.Response, ".")
+}
+
+func TestResponseMessageName(t *testing.T) {
+	// Set up the testing permutations.
+	tests := []responseMessageNameTest{
+		{
+			testName:   "Valid-BatchDeleteBooksResponse",
+			MethodName: "BatchDeleteBooks",
+			Response:   "BatchDeleteBooksResponse",
+			problems:   testutils.Problems{},
+		},
+		{
+			testName:   "Valid-Empty",
+			MethodName: "BatchDeleteBooks",
+			Response:   "google.protobuf.Empty",
+			problems:   testutils.Problems{},
+		},
+		{
+			testName:   "Valid-LRO-BatchDeleteBooksResponse",
+			MethodName: "BatchDeleteBooks",
+			Response:   "google.longrunning.Operation",
+			MethodAnnotation: `option (google.longrunning.operation_info) = {
+				response_type: "BatchDeleteBooksResponse"
+			};`,
+			problems: testutils.Problems{},
+		},
+		{
+			testName:   "Valid-LRO-Empty",
+			MethodName: "BatchDeleteBooks",
+			Response:   "google.longrunning.Operation",
+			MethodAnnotation: `option (google.longrunning.operation_info) = {
+				response_type: "google.protobuf.Empty"
+			};`,
+			problems: testutils.Problems{},
+		},
+		{
+			testName:   "Invalid",
+			MethodName: "BatchDeleteBooks",
+			Response:   "BatchDeleteBookResponse",
+			problems: testutils.Problems{{
+				Message:    "`BatchDeleteBooksResponse`",
+				Suggestion: "google.protobuf.Empty",
+			}},
+		},
+		{
+			testName:   "Invalid-LRO",
+			MethodName: "BatchDeleteBooks",
+			Response:   "google.longrunning.Operation",
+			MethodAnnotation: `option (google.longrunning.operation_info) = {
+				response_type: "BatchDeleteBookResponse"
+			};`,
+			problems: testutils.Problems{{
+				Message:    "`BatchDeleteBooksResponse`",
+				Suggestion: "google.protobuf.Empty",
+			}},
+		},
+		{
+			testName:   "Irrelevant",
+			MethodName: "DeleteBook",
+			Response:   "Book",
+			problems:   testutils.Problems{},
+		},
+	}
+
+	// Run each test individually.
+	for _, test := range tests {
+		t.Run(test.testName, func(t *testing.T) {
+			file := testutils.ParseProto3Tmpl(t, `
+				import "google/protobuf/empty.proto";
+				import "google/longrunning/operations.proto";
+
+				service BookService {
+					rpc {{.MethodName}}({{.MethodName}}Request) returns ({{.Response}}) {
+						{{.MethodAnnotation}}
+					}
+				}
+				message {{.MethodName}}Request {}
+				{{ if not .ResponseExternal }}message {{.Response}} {}{{ end }}
+				`, test)
+
+			m := file.GetServices()[0].GetMethods()[0]
+
+			problems := responseMessageName.Lint(file)
+			if diff := test.problems.SetDescriptor(m).Diff(problems); diff != "" {
+				t.Errorf(diff)
+			}
+		})
+	}
+}