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

Add rpc.status to client response context for annotated thrift exceptions #934

Open
wants to merge 3 commits into
base: v1.4.1-hotfix-maintenance
Choose a base branch
from
Open
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
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ lint: check-licence eclint-check
# @[ ! -s deps.log ]

.PHONY: generate
# set GO111MODULE to off to compile ancient tools within the vendor directory
generate: export GO111MODULE = off
generate:
@ls ./node_modules/.bin/uber-licence >/dev/null 2>&1 || npm i uber-licence
@chmod 644 ./codegen/templates/*.tmpl
Expand Down
55 changes: 55 additions & 0 deletions codegen/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ package codegen
import (
"fmt"
"path/filepath"
"strings"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -72,6 +73,7 @@ config:
exposedMethods:
a: method
`

grpcClientYAML = `
name: test
type: grpc
Expand Down Expand Up @@ -666,3 +668,56 @@ config:
assert.Error(t, err)
assert.Equal(t, expectedErr, err.Error())
}

func TestTChannelRPCAnnotations(t *testing.T) {
validator := getExposedMethodValidator()
annotatedTChannelClientYAML := strings.ReplaceAll(tchannelClientYAML, "bar", "baz")
client, errClient := newClientConfig([]byte(annotatedTChannelClientYAML), validator)
assert.NoError(t, errClient)
instance := &ModuleInstance{
YAMLFileName: "YAMLFileName",
JSONFileName: "JSONFileName",
InstanceName: "InstanceName",
PackageInfo: &PackageInfo{
ExportName: "ExportName",
ExportType: "ExportType",
QualifiedInstanceName: "QualifiedInstanceName",
},
}
h := newTestPackageHelper(t)

idlFile := filepath.Join(h.IdlPath(), h.GetModuleIdlSubDir(false), "clients/baz/baz.thrift")
expectedSpec := &ClientSpec{
ModuleSpec: nil,
YAMLFile: instance.YAMLFileName,
JSONFile: instance.JSONFileName,
ClientType: "tchannel",
ImportPackagePath: instance.PackageInfo.ImportPackagePath(),
ImportPackageAlias: instance.PackageInfo.ImportPackageAlias(),
ExportName: instance.PackageInfo.ExportName,
ExportType: instance.PackageInfo.ExportType,
ThriftFile: idlFile,
ClientID: instance.InstanceName,
ClientName: instance.PackageInfo.QualifiedInstanceName,
ExposedMethods: map[string]string{
"a": "method",
},
SidecarRouter: "sidecar",
}

spec, errSpec := client.NewClientSpec(instance, h)
annotatedExceptions := 0
for _, service := range spec.ModuleSpec.Services {
for _, method := range service.Methods {
for _, exception := range method.Exceptions {
if _, ok := exception.Annotations["rpc.code"]; ok {
annotatedExceptions++
}
}
}
}
assert.Equal(t, annotatedExceptions, 15)
spec.ModuleSpec = nil // Not interested in ModuleSpec here
assert.NoError(t, errSpec)
assert.Equal(t, expectedSpec, spec)
}
48 changes: 48 additions & 0 deletions codegen/method.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,33 @@ const (
antHTTPResNoBody = "%s.http.res.body.disallow"
)

const _errorCodeAnnotationKey = "rpc.code"

const queryAnnotationPrefix = "query."
const headerAnnotationPrefix = "headers."

var (
_gRPCCodeNameToYARPCErrorCodeType = map[string]string{
// https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
"CANCELLED": "yarpcerrors.CodeCancelled",
"UNKNOWN": "yarpcerrors.CodeUnknown",
"INVALID_ARGUMENT": "yarpcerrors.CodeInvalidArgument",
"DEADLINE_EXCEEDED": "yarpcerrors.CodeDeadlineExceeded",
"NOT_FOUND": "yarpcerrors.CodeNotFound",
"ALREADY_EXISTS": "yarpcerrors.CodeAlreadyExists",
"PERMISSION_DENIED": "yarpcerrors.CodePermissionDenied",
"RESOURCE_EXHAUSTED": "yarpcerrors.CodeResourceExhausted",
"FAILED_PRECONDITION": "yarpcerrors.CodeFailedPrecondition",
"ABORTED": "yarpcerrors.CodeAborted",
"OUT_OF_RANGE": "yarpcerrors.CodeOutOfRange",
"UNIMPLEMENTED": "yarpcerrors.CodeUnimplemented",
"INTERNAL": "yarpcerrors.CodeInternal",
"UNAVAILABLE": "yarpcerrors.CodeUnavailable",
"DATA_LOSS": "yarpcerrors.CodeDataLoss",
"UNAUTHENTICATED": "yarpcerrors.CodeUnauthenticated",
}
)

// PathSegment represents a part of the http path.
type PathSegment struct {
Type string
Expand Down Expand Up @@ -415,6 +439,18 @@ func (ms *MethodSpec) setExceptions(
)
}

errorCode := ""
if errorCodeString, ok := e.Type.ThriftAnnotations()[_errorCodeAnnotationKey]; ok {
if yarpcCode, ok := _gRPCCodeNameToYARPCErrorCodeType[strings.ToUpper(errorCodeString)]; ok {
errorCode = yarpcCode
}
}
if errorCodeString, ok := e.Annotations[_errorCodeAnnotationKey]; ok {
if yarpcCode, ok := _gRPCCodeNameToYARPCErrorCodeType[strings.ToUpper(errorCodeString)]; ok {
errorCode = yarpcCode
}
}

bodyDisallowed := ms.isBodyDisallowed(e)
if !ms.WantAnnot {
exception := ExceptionSpec{
Expand All @@ -424,6 +460,7 @@ func (ms *MethodSpec) setExceptions(
},
IsBodyDisallowed: bodyDisallowed,
}
exception = addRpcAnnotationToException(exception, errorCode)
ms.Exceptions[i] = exception
ms.ExceptionsIndex[e.Name] = exception
if _, exists := ms.ExceptionsByStatusCode[exception.StatusCode.Code]; !exists {
Expand Down Expand Up @@ -456,6 +493,7 @@ func (ms *MethodSpec) setExceptions(
},
IsBodyDisallowed: bodyDisallowed,
}
exception = addRpcAnnotationToException(exception, errorCode)
ms.Exceptions[i] = exception
ms.ExceptionsIndex[e.Name] = exception
if _, exists := ms.ExceptionsByStatusCode[exception.StatusCode.Code]; !exists {
Expand Down Expand Up @@ -1586,3 +1624,13 @@ func headers(annotation string) []string {
}
return strings.Split(annotation, ",")
}

func addRpcAnnotationToException(exception ExceptionSpec, errorCode string) ExceptionSpec {
if errorCode != "" {
if exception.Annotations == nil {
exception.Annotations = make(compile.Annotations)
}
exception.Annotations[_errorCodeAnnotationKey] = errorCode
}
return exception
}
26 changes: 13 additions & 13 deletions codegen/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,19 +51,19 @@ func (*defaultAssetCollection) Asset(assetName string) ([]byte, error) {
}

var defaultFuncMap = tmpl.FuncMap{
"lower": strings.ToLower,
"title": strings.Title,
"fullTypeName": fullTypeName,
"camel": CamelCase,
"split": strings.Split,
"dec": decrement,
"basePath": filepath.Base,
"pascal": PascalCase,
"isPointerType": IsPointerType,
"unref": Unref,
"lintAcronym": LintAcronym,
"args": args,
"firstIsClientOrEmpty": firstIsClientOrEmpty,
"lower": strings.ToLower,
"title": strings.Title,
"fullTypeName": fullTypeName,
"camel": CamelCase,
"split": strings.Split,
"dec": decrement,
"basePath": filepath.Base,
"pascal": PascalCase,
"isPointerType": IsPointerType,
"unref": Unref,
"lintAcronym": LintAcronym,
"args": args,
"firstIsClientOrEmpty": firstIsClientOrEmpty,
}

func fullTypeName(typeName, packageName string) string {
Expand Down
87 changes: 75 additions & 12 deletions codegen/template_bundle/template_files.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading