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"
DEFAULT_REFERENCE_FILTERS = "cshutdown"
GENERIC_REFERENCE_FILTERS = "generic"
GENERIC = "$invoke"
Expand Down
126 changes: 126 additions & 0 deletions filter/impl/generic_service_filter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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
*
* http://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 impl
fangyincheng marked this conversation as resolved.
Show resolved Hide resolved

import (
"reflect"
"strings"
)

import (
hessian "github.com/apache/dubbo-go-hessian2"
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
"github.com/mitchellh/mapstructure"
perrors "github.com/pkg/errors"
)

import (
"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"
)

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 (
ok bool
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, ok = invocation.Arguments()[2].([]hessian.Object)
} else {
logger.Errorf("[Generic Service Filter] Don't support this generic: %s", genericKey)
return &protocol.RPCResult{}
}
if !ok {
logger.Errorf("[Generic Service Filter] wrong serialization")
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
newParams = make([]interface{}, len(oldParams))
for i := range argsType {
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[i] = 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{}
}
148 changes: 148 additions & 0 deletions filter/impl/generic_service_filter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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
*
* http://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 impl

import (
Patrick0308 marked this conversation as resolved.
Show resolved Hide resolved
"context"
"errors"
"reflect"
"testing"
)

import (
hessian "github.com/apache/dubbo-go-hessian2"
"github.com/stretchr/testify/assert"
)

import (
"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"
)

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