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

Ftr: Generic Implement #291

Merged
merged 15 commits into from
Jan 7, 2020
2 changes: 1 addition & 1 deletion common/constant/default.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const (
const (
DEFAULT_KEY = "default"
PREFIX_DEFAULT_KEY = "default."
DEFAULT_SERVICE_FILTERS = "echo,token,accesslog,tps,execute,pshutdown"
DEFAULT_SERVICE_FILTERS = "echo,token,accesslog,tps,generic-service,execute,pshutdown"
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
DEFAULT_REFERENCE_FILTERS = "cshutdown"
GENERIC_REFERENCE_FILTERS = "generic"
GENERIC = "$invoke"
Expand Down
95 changes: 95 additions & 0 deletions filter/impl/generic_service_filter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package impl
fangyincheng marked this conversation as resolved.
Show resolved Hide resolved

import (
hessian "github.com/apache/dubbo-go-hessian2"
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
"github.com/apache/dubbo-go/common"
"github.com/apache/dubbo-go/common/constant"
"github.com/apache/dubbo-go/common/extension"
"github.com/apache/dubbo-go/common/logger"
"github.com/apache/dubbo-go/filter"
"github.com/apache/dubbo-go/protocol"
invocation2 "github.com/apache/dubbo-go/protocol/invocation"
"github.com/mitchellh/mapstructure"
perrors "github.com/pkg/errors"
"reflect"
"strings"
)

const (
GENERIC_SERVICE = "generic-service"
GENERIC_SERIALIZATION_DEFAULT = "true"
)

func init() {
extension.SetFilter(GENERIC_SERVICE, GetGenericServiceFilter)
}

type GenericServiceFilter struct{}

func (ef *GenericServiceFilter) Invoke(invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
logger.Infof("invoking generic service filter.")
logger.Debugf("generic service filter methodName:%v,args:%v", invocation.MethodName(), len(invocation.Arguments()))
if invocation.MethodName() != constant.GENERIC || len(invocation.Arguments()) != 3 {
return invoker.Invoke(invocation)
}
var (
err error
methodName string
newParams []interface{}
genericKey string
argsType []reflect.Type
oldParams []hessian.Object
)
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
url := invoker.GetUrl()
methodName = invocation.Arguments()[0].(string)
// get service
svc := common.ServiceMap.GetService(url.Protocol, strings.TrimPrefix(url.Path, "/"))
// get method
method := svc.Method()[methodName]
if method == nil {
logger.Errorf("[Generic Service Filter] Don't have this method: %s", methodName)
return &protocol.RPCResult{}
}
argsType = method.ArgsType()
genericKey = invocation.AttachmentsByKey(constant.GENERIC_KEY, GENERIC_SERIALIZATION_DEFAULT)
if genericKey == GENERIC_SERIALIZATION_DEFAULT {
oldParams = invocation.Arguments()[2].([]hessian.Object)
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
} else {
logger.Errorf("[Generic Service Filter] Don't support this generic: %s", genericKey)
return &protocol.RPCResult{}
}
if len(oldParams) != len(argsType) {
logger.Errorf("[Generic Service Filter] method:%s invocation arguments number was wrong", methodName)
return &protocol.RPCResult{}
}
// oldParams convert to newParams
for i := range argsType {
var newParam interface{}
newParam = reflect.New(argsType[i]).Interface()
err = mapstructure.Decode(oldParams[i], newParam)
newParam = reflect.ValueOf(newParam).Elem().Interface()
if err != nil {
logger.Errorf("[Generic Service Filter] decode arguments map to struct wrong: error{%v}", perrors.WithStack(err))
return &protocol.RPCResult{}
}
newParams = append(newParams, newParam)
}
newInvocation := invocation2.NewRPCInvocation(methodName, newParams, invocation.Attachments())
newInvocation.SetReply(invocation.Reply())
return invoker.Invoke(newInvocation)
}

func (ef *GenericServiceFilter) OnResponse(result protocol.Result, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
if invocation.MethodName() == constant.GENERIC && len(invocation.Arguments()) == 3 && result.Result() != nil {
v := reflect.ValueOf(result.Result())
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
result.SetResult(struct2MapAll(v.Interface()))
}
return result
}

func GetGenericServiceFilter() filter.Filter {
return &GenericServiceFilter{}
}
125 changes: 125 additions & 0 deletions filter/impl/generic_service_filter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package impl

import (
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
"context"
"errors"
hessian "github.com/apache/dubbo-go-hessian2"
"github.com/apache/dubbo-go/common"
"github.com/apache/dubbo-go/common/proxy/proxy_factory"
"github.com/apache/dubbo-go/protocol"
"github.com/apache/dubbo-go/protocol/invocation"
"github.com/stretchr/testify/assert"
"reflect"
"testing"
)

type TestStruct struct {
AaAa string
BaBa string `m:"baBa"`
XxYy struct {
xxXx string `m:"xxXx"`
Xx string `m:"xx"`
} `m:"xxYy"`
}

func (c *TestStruct) JavaClassName() string {
return "com.test.testStruct"
}

type TestService struct {
}

func (ts *TestService) MethodOne(ctx context.Context, test1 *TestStruct, test2 []TestStruct,
test3 interface{}, test4 []interface{}, test5 *string) (*TestStruct, error) {
if test1 == nil {
return nil, errors.New("param test1 is nil")
}
if test2 == nil {
return nil, errors.New("param test2 is nil")
}
if test3 == nil {
return nil, errors.New("param test3 is nil")
}
if test4 == nil {
return nil, errors.New("param test4 is nil")
}
if test5 == nil {
return nil, errors.New("param test5 is nil")
}
return &TestStruct{}, nil
}

func (s *TestService) Reference() string {
return "com.test.Path"
}

func TestGenericServiceFilter_Invoke(t *testing.T) {
hessian.RegisterPOJO(&TestStruct{})
methodName := "$invoke"
m := make(map[string]interface{})
m["AaAa"] = "nihao"
x := make(map[string]interface{})
x["xxXX"] = "nihaoxxx"
m["XxYy"] = x
aurguments := []interface{}{
"MethodOne",
nil,
[]hessian.Object{
hessian.Object(m),
hessian.Object(append(make([]map[string]interface{}, 1), m)),
hessian.Object("111"),
hessian.Object(append(make([]map[string]interface{}, 1), m)),
hessian.Object("222")},
}
s := &TestService{}
_, _ = common.ServiceMap.Register("testprotocol", s)
rpcInvocation := invocation.NewRPCInvocation(methodName, aurguments, nil)
filter := GetGenericServiceFilter()
url, _ := common.NewURL(context.Background(), "testprotocol://127.0.0.1:20000/com.test.Path")
result := filter.Invoke(&proxy_factory.ProxyInvoker{BaseInvoker: *protocol.NewBaseInvoker(url)}, rpcInvocation)
assert.NotNil(t, result)
assert.Nil(t, result.Error())
}

func TestGenericServiceFilter_ResponseTestStruct(t *testing.T) {
ts := &TestStruct{
AaAa: "aaa",
BaBa: "bbb",
XxYy: struct {
xxXx string `m:"xxXx"`
Xx string `m:"xx"`
}{},
}
result := &protocol.RPCResult{
Rest: ts,
}
aurguments := []interface{}{
"MethodOne",
nil,
[]hessian.Object{nil},
}
filter := GetGenericServiceFilter()
methodName := "$invoke"
rpcInvocation := invocation.NewRPCInvocation(methodName, aurguments, nil)
r := filter.OnResponse(result, nil, rpcInvocation)
assert.NotNil(t, r.Result())
assert.Equal(t, reflect.ValueOf(r.Result()).Kind(), reflect.Map)
}

func TestGenericServiceFilter_ResponseString(t *testing.T) {
str := "111"
result := &protocol.RPCResult{
Rest: str,
}
aurguments := []interface{}{
"MethodOne",
nil,
[]hessian.Object{nil},
}
filter := GetGenericServiceFilter()
methodName := "$invoke"
rpcInvocation := invocation.NewRPCInvocation(methodName, aurguments, nil)
r := filter.OnResponse(result, nil, rpcInvocation)
assert.NotNil(t, r.Result())
assert.Equal(t, reflect.ValueOf(r.Result()).Kind(), reflect.String)
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ require (
github.com/lestrrat/go-file-rotatelogs v0.0.0-20180223000712-d3151e2a480f // indirect
github.com/lestrrat/go-strftime v0.0.0-20180220042222-ba3bf9c1d042 // indirect
github.com/magiconair/properties v1.8.1
github.com/mitchellh/mapstructure v1.1.2
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd
github.com/nacos-group/nacos-sdk-go v0.0.0-20190723125407-0242d42e3dbb
github.com/pkg/errors v0.8.1
Expand Down