1 Star 0 Fork 27

陈先乐 / erpc

forked from andeyalee / erpc 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
router.go 28.94 KB
一键复制 编辑 原始数据 按行查看 历史
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
// Copyright 2015-2019 HenryLee. All Rights Reserved.
//
// 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
//
// 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 erpc
import (
"path"
"reflect"
"runtime"
"strings"
"sync"
"unsafe"
"github.com/henrylee2cn/goutil"
"github.com/henrylee2cn/goutil/errors"
)
var (
typeOfCallCtx = reflect.TypeOf((*CallCtx)(nil)).Elem()
typeOfPushCtx = reflect.TypeOf((*PushCtx)(nil)).Elem()
)
// ServiceMethodMapper mapper service method from prefix, recvName and funcName.
// NOTE:
// @prefix is optional;
// @name is required.
type ServiceMethodMapper func(prefix, name string) (serviceMethod string)
// SetServiceMethodMapper customizes your own service method mapper.
func SetServiceMethodMapper(mapper ServiceMethodMapper) {
globalServiceMethodMapper = mapper
}
// HTTPServiceMethodMapper like most RPC services service method mapper.
// Such as: user/get
// It is the default mapper.
// The mapping rule of struct(func) name to service methods:
// `AaBb` -> `/aa_bb`
// `ABcXYz` -> `/abc_xyz`
// `Aa__Bb` -> `/aa_bb`
// `aa__bb` -> `/aa_bb`
// `ABC__XYZ` -> `/abc_xyz`
// `Aa_Bb` -> `/aa/bb`
// `aa_bb` -> `/aa/bb`
// `ABC_XYZ` -> `/abc/xyz`
//
func HTTPServiceMethodMapper(prefix, name string) string {
return path.Join("/", prefix, toServiceMethods(name, '/', true))
}
// RPCServiceMethodMapper like most RPC services service method mapper.
// Such as: User.Get
// The mapping rule of struct(func) name to service methods:
// `AaBb` -> `AaBb`
// `ABcXYz` -> `ABcXYz`
// `Aa__Bb` -> `Aa_Bb`
// `aa__bb` -> `aa_bb`
// `ABC__XYZ` -> `ABC_XYZ`
// `Aa_Bb` -> `Aa.Bb`
// `aa_bb` -> `aa.bb`
// `ABC_XYZ` -> `ABC.XYZ`
//
func RPCServiceMethodMapper(prefix, name string) string {
p := prefix + "." + toServiceMethods(name, '.', false)
return strings.Trim(p, ".")
}
// toServiceMethods maps struct(func) name to service methods.
func toServiceMethods(name string, sep rune, toSnake bool) string {
var a = []rune{}
var last rune
for _, r := range name {
if last == '_' {
if r == '_' {
last = '\x00'
continue
} else {
a[len(a)-1] = sep
}
}
if last == '\x00' && r == '_' {
continue
}
a = append(a, r)
last = r
}
name = string(a)
if toSnake {
name = goutil.SnakeString(name)
name = strings.Replace(name, "__", "_", -1)
name = strings.Replace(name, string(sep)+"_", string(sep), -1)
}
return name
}
/**
* Router the router of call or push handlers.
*
* 1. Call-Controller-Struct API template
*
* type Aaa struct {
* erpc.CallCtx
* }
* func (x *Aaa) XxZz(arg *<T>) (<T>, *erpc.Status) {
* ...
* return r, nil
* }
*
* - register it to root router:
*
* // register the call route: /aaa/xx_zz
* peer.RouteCall(new(Aaa))
*
* // or register the call route: /xx_zz
* peer.RouteCallFunc((*Aaa).XxZz)
*
* 2. Call-Handler-Function API template
*
* func XxZz(ctx erpc.CallCtx, arg *<T>) (<T>, *erpc.Status) {
* ...
* return r, nil
* }
*
* - register it to root router:
*
* // register the call route: /xx_zz
* peer.RouteCallFunc(XxZz)
*
* 3. Push-Controller-Struct API template
*
* type Bbb struct {
* erpc.PushCtx
* }
* func (b *Bbb) YyZz(arg *<T>) *erpc.Status {
* ...
* return nil
* }
*
* - register it to root router:
*
* // register the push route: /bbb/yy_zz
* peer.RoutePush(new(Bbb))
*
* // or register the push route: /yy_zz
* peer.RoutePushFunc((*Bbb).YyZz)
*
* 4. Push-Handler-Function API template
*
* // YyZz register the route: /yy_zz
* func YyZz(ctx erpc.PushCtx, arg *<T>) *erpc.Status {
* ...
* return nil
* }
*
* - register it to root router:
*
* // register the push route: /yy_zz
* peer.RoutePushFunc(YyZz)
*
* 5. Unknown-Call-Handler-Function API template
*
* func XxxUnknownCall (ctx erpc.UnknownCallCtx) (interface{}, *erpc.Status) {
* ...
* return r, nil
* }
*
* - register it to root router:
*
* // register the unknown call route: /*
* peer.SetUnknownCall(XxxUnknownCall)
*
* 6. Unknown-Push-Handler-Function API template
*
* func XxxUnknownPush(ctx erpc.UnknownPushCtx) *erpc.Status {
* ...
* return nil
* }
*
* - register it to root router:
*
* // register the unknown push route: /*
* peer.SetUnknownPush(XxxUnknownPush)
*
* 7. The default mapping rule(HTTPServiceMethodMapper) of struct(func) name to service methods:
*
* - `AaBb` -> `/aa_bb`
* - `ABcXYz` -> `/abc_xyz`
* - `Aa__Bb` -> `/aa_bb`
* - `aa__bb` -> `/aa_bb`
* - `ABC__XYZ` -> `/abc_xyz`
* - `Aa_Bb` -> `/aa/bb`
* - `aa_bb` -> `/aa/bb`
* - `ABC_XYZ` -> `/abc/xyz`
*
* 8. The mapping rule(RPCServiceMethodMapper) of struct(func) name to service methods:
*
* - `AaBb` -> `AaBb`
* - `ABcXYz` -> `ABcXYz`
* - `Aa__Bb` -> `Aa_Bb`
* - `aa__bb` -> `aa_bb`
* - `ABC__XYZ` -> `ABC_XYZ`
* - `Aa_Bb` -> `Aa.Bb`
* - `aa_bb` -> `aa.bb`
* - `ABC_XYZ` -> `ABC.XYZ`
**/
type (
// Router the router of call or push handlers.
Router struct {
subRouter *SubRouter
}
// SubRouter without the SetUnknownCall and SetUnknownPush methods
SubRouter struct {
root *Router
callHandlers map[string]*Handler
pushHandlers map[string]*Handler
unknownCall **Handler
unknownPush **Handler
// only for register router
prefix string
pluginContainer *PluginContainer
}
// Handler call or push handler type info
Handler struct {
name string
argElem reflect.Type
reply reflect.Type // only for call handler doc
handleFunc func(*handlerCtx, reflect.Value)
unknownHandleFunc func(*handlerCtx)
pluginContainer *PluginContainer
routerTypeName string
isUnknown bool
}
// HandlersMaker makes []*Handler
HandlersMaker func(string, interface{}, *PluginContainer) ([]*Handler, error)
)
var globalServiceMethodMapper = HTTPServiceMethodMapper
const (
pnPush = "PUSH"
pnCall = "CALL"
pnUnknownPush = "UNKNOWN_PUSH"
pnUnknownCall = "UNKNOWN_CALL"
)
// newRouter creates root router.
func newRouter(pluginContainer *PluginContainer) *Router {
rootGroup := globalServiceMethodMapper("", "")
root := &Router{
subRouter: &SubRouter{
callHandlers: make(map[string]*Handler),
pushHandlers: make(map[string]*Handler),
unknownCall: new(*Handler),
unknownPush: new(*Handler),
prefix: rootGroup,
pluginContainer: pluginContainer,
},
}
root.subRouter.root = root
return root
}
// Root returns the root router.
func (r *SubRouter) Root() *Router {
return r.root
}
// ToRouter converts to the router which is added the SetUnknownCall and SetUnknownPush methods.
func (r *SubRouter) ToRouter() *Router {
return &Router{subRouter: r}
}
// SubRoute adds handler group.
func (r *Router) SubRoute(prefix string, plugin ...Plugin) *SubRouter {
return r.subRouter.SubRoute(prefix, plugin...)
}
// SubRoute adds handler group.
func (r *SubRouter) SubRoute(prefix string, plugin ...Plugin) *SubRouter {
pluginContainer := r.pluginContainer.cloneAndAppendMiddle(plugin...)
warnInvalidHandlerHooks(plugin)
return &SubRouter{
root: r.root,
callHandlers: r.callHandlers,
pushHandlers: r.pushHandlers,
unknownCall: r.unknownCall,
unknownPush: r.unknownPush,
prefix: globalServiceMethodMapper(r.prefix, prefix),
pluginContainer: pluginContainer,
}
}
// RouteCall registers CALL handlers, and returns the paths.
func (r *Router) RouteCall(callCtrlStruct interface{}, plugin ...Plugin) []string {
return r.subRouter.RouteCall(callCtrlStruct, plugin...)
}
// RouteCall registers CALL handlers, and returns the paths.
func (r *SubRouter) RouteCall(callCtrlStruct interface{}, plugin ...Plugin) []string {
return r.reg(pnCall, makeCallHandlersFromStruct, callCtrlStruct, plugin)
}
// RouteCallFunc registers CALL handler, and returns the path.
func (r *Router) RouteCallFunc(callHandleFunc interface{}, plugin ...Plugin) string {
return r.subRouter.RouteCallFunc(callHandleFunc, plugin...)
}
// RouteCallFunc registers CALL handler, and returns the path.
func (r *SubRouter) RouteCallFunc(callHandleFunc interface{}, plugin ...Plugin) string {
return r.reg(pnCall, makeCallHandlersFromFunc, callHandleFunc, plugin)[0]
}
// RoutePush registers PUSH handlers, and returns the paths.
func (r *Router) RoutePush(pushCtrlStruct interface{}, plugin ...Plugin) []string {
return r.subRouter.RoutePush(pushCtrlStruct, plugin...)
}
// RoutePush registers PUSH handlers, and returns the paths.
func (r *SubRouter) RoutePush(pushCtrlStruct interface{}, plugin ...Plugin) []string {
return r.reg(pnPush, makePushHandlersFromStruct, pushCtrlStruct, plugin)
}
// RoutePushFunc registers PUSH handler, and returns the path.
func (r *Router) RoutePushFunc(pushHandleFunc interface{}, plugin ...Plugin) string {
return r.subRouter.RoutePushFunc(pushHandleFunc, plugin...)
}
// RoutePushFunc registers PUSH handler, and returns the path.
func (r *SubRouter) RoutePushFunc(pushHandleFunc interface{}, plugin ...Plugin) string {
return r.reg(pnPush, makePushHandlersFromFunc, pushHandleFunc, plugin)[0]
}
func (r *SubRouter) reg(
routerTypeName string,
handlerMaker func(string, interface{}, *PluginContainer) ([]*Handler, error),
ctrlStruct interface{},
plugins []Plugin,
) []string {
pluginContainer := r.pluginContainer.cloneAndAppendMiddle(plugins...)
warnInvalidHandlerHooks(plugins)
handlers, err := handlerMaker(
r.prefix,
ctrlStruct,
pluginContainer,
)
if err != nil {
Fatalf("%v", err)
}
var names []string
var hadHandlers map[string]*Handler
if routerTypeName == pnCall {
hadHandlers = r.callHandlers
} else {
hadHandlers = r.pushHandlers
}
for _, h := range handlers {
if _, ok := hadHandlers[h.name]; ok {
Fatalf("there is a handler conflict: %s", h.name)
}
h.routerTypeName = routerTypeName
hadHandlers[h.name] = h
pluginContainer.postReg(h)
Printf("register %s handler: %s", routerTypeName, h.name)
names = append(names, h.name)
}
return names
}
// SetUnknownCall sets the default handler,
// which is called when no handler for CALL is found.
func (r *Router) SetUnknownCall(fn func(UnknownCallCtx) (interface{}, *Status), plugin ...Plugin) {
pluginContainer := r.subRouter.pluginContainer.cloneAndAppendMiddle(plugin...)
warnInvalidHandlerHooks(plugin)
var h = &Handler{
name: pnUnknownCall,
isUnknown: true,
argElem: reflect.TypeOf([]byte{}),
pluginContainer: pluginContainer,
unknownHandleFunc: func(ctx *handlerCtx) {
body, stat := fn(ctx)
if !stat.OK() {
ctx.stat = stat
ctx.output.SetStatus(stat)
} else {
ctx.output.SetBody(body)
}
},
}
if *r.subRouter.unknownCall == nil {
Printf("set %s handler", h.name)
} else {
Warnf("covered %s handler", h.name)
}
r.subRouter.unknownCall = &h
}
// SetUnknownPush sets the default handler,
// which is called when no handler for PUSH is found.
func (r *Router) SetUnknownPush(fn func(UnknownPushCtx) *Status, plugin ...Plugin) {
pluginContainer := r.subRouter.pluginContainer.cloneAndAppendMiddle(plugin...)
warnInvalidHandlerHooks(plugin)
var h = &Handler{
name: pnUnknownPush,
isUnknown: true,
argElem: reflect.TypeOf([]byte{}),
pluginContainer: pluginContainer,
unknownHandleFunc: func(ctx *handlerCtx) {
ctx.stat = fn(ctx)
},
}
if *r.subRouter.unknownPush == nil {
Printf("set %s handler", h.name)
} else {
Warnf("covered %s handler", h.name)
}
r.subRouter.unknownPush = &h
}
func (r *SubRouter) getCall(uriPath string) (*Handler, bool) {
t, ok := r.callHandlers[uriPath]
if ok {
return t, true
}
if unknown := *r.unknownCall; unknown != nil {
return unknown, true
}
return nil, false
}
func (r *SubRouter) getPush(uriPath string) (*Handler, bool) {
t, ok := r.pushHandlers[uriPath]
if ok {
return t, true
}
if unknown := *r.unknownPush; unknown != nil {
return unknown, true
}
return nil, false
}
// NOTE: callCtrlStruct needs to implement CallCtx interface.
func makeCallHandlersFromStruct(prefix string, callCtrlStruct interface{}, pluginContainer *PluginContainer) ([]*Handler, error) {
var (
ctype = reflect.TypeOf(callCtrlStruct)
handlers = make([]*Handler, 0, 1)
)
if ctype.Kind() != reflect.Ptr {
return nil, errors.Errorf("call-handler: the type is not struct point: %s", ctype.String())
}
var ctypeElem = ctype.Elem()
if ctypeElem.Kind() != reflect.Struct {
return nil, errors.Errorf("call-handler: the type is not struct point: %s", ctype.String())
}
iType, ok := ctypeElem.FieldByName("CallCtx")
if !ok || !iType.Anonymous {
return nil, errors.Errorf("call-handler: the struct do not have anonymous field erpc.CallCtx: %s", ctype.String())
}
var callCtxOffset = iType.Offset
if pluginContainer == nil {
pluginContainer = newPluginContainer()
}
type CallCtrlValue struct {
ctrl reflect.Value
ctxPtr *CallCtx
}
var pool = &sync.Pool{
New: func() interface{} {
ctrl := reflect.New(ctypeElem)
return &CallCtrlValue{
ctrl: ctrl,
ctxPtr: (*CallCtx)(unsafe.Pointer(uintptr(unsafe.Pointer(ctrl.Pointer())) + callCtxOffset)),
}
},
}
for m := 0; m < ctype.NumMethod(); m++ {
method := ctype.Method(m)
mtype := method.Type
mname := method.Name
// Method must be exported.
if method.PkgPath != "" {
continue
}
// Method needs two ins: receiver, *<T>.
if mtype.NumIn() != 2 {
if isBelongToCallCtx(mname) {
continue
}
return nil, errors.Errorf("call-handler: %s.%s needs one in argument, but have %d", ctype.String(), mname, mtype.NumIn())
}
// Receiver need be a struct pointer.
structType := mtype.In(0)
if structType.Kind() != reflect.Ptr || structType.Elem().Kind() != reflect.Struct {
if isBelongToCallCtx(mname) {
continue
}
return nil, errors.Errorf("call-handler: %s.%s receiver need be a struct pointer: %s", ctype.String(), mname, structType)
}
// First arg need be exported or builtin, and need be a pointer.
argType := mtype.In(1)
if !goutil.IsExportedOrBuiltinType(argType) {
if isBelongToCallCtx(mname) {
continue
}
return nil, errors.Errorf("call-handler: %s.%s arg type not exported: %s", ctype.String(), mname, argType)
}
if argType.Kind() != reflect.Ptr {
if isBelongToCallCtx(mname) {
continue
}
return nil, errors.Errorf("call-handler: %s.%s arg type need be a pointer: %s", ctype.String(), mname, argType)
}
// Method needs two outs: reply, *Status.
if mtype.NumOut() != 2 {
if isBelongToCallCtx(mname) {
continue
}
return nil, errors.Errorf("call-handler: %s.%s needs two out arguments, but have %d", ctype.String(), mname, mtype.NumOut())
}
// Reply type must be exported.
replyType := mtype.Out(0)
if !goutil.IsExportedOrBuiltinType(replyType) {
if isBelongToCallCtx(mname) {
continue
}
return nil, errors.Errorf("call-handler: %s.%s first reply type not exported: %s", ctype.String(), mname, replyType)
}
// The return type of the method must be *Status.
if returnType := mtype.Out(1); !isStatusType(returnType.String()) {
if isBelongToCallCtx(mname) {
continue
}
return nil, errors.Errorf("call-handler: %s.%s second out argument %s is not *erpc.Status", ctype.String(), mname, returnType)
}
var methodFunc = method.Func
var handleFunc = func(ctx *handlerCtx, argValue reflect.Value) {
obj := pool.Get().(*CallCtrlValue)
*obj.ctxPtr = ctx
rets := methodFunc.Call([]reflect.Value{obj.ctrl, argValue})
stat := (*Status)(unsafe.Pointer(rets[1].Pointer()))
if !stat.OK() {
ctx.stat = stat
ctx.output.SetStatus(stat)
} else {
ctx.output.SetBody(rets[0].Interface())
}
pool.Put(obj)
}
handlers = append(handlers, &Handler{
handleFunc: handleFunc,
argElem: argType.Elem(),
reply: replyType,
pluginContainer: pluginContainer,
name: globalServiceMethodMapper(
globalServiceMethodMapper(prefix, ctrlStructName(ctype)),
mname,
),
})
}
return handlers, nil
}
func makeCallHandlersFromFunc(prefix string, callHandleFunc interface{}, pluginContainer *PluginContainer) ([]*Handler, error) {
var (
ctype = reflect.TypeOf(callHandleFunc)
cValue = reflect.ValueOf(callHandleFunc)
typeString = objectName(cValue)
)
if ctype.Kind() != reflect.Func {
return nil, errors.Errorf("call-handler: the type is not function: %s", typeString)
}
// needs two outs: reply, *Status.
if ctype.NumOut() != 2 {
return nil, errors.Errorf("call-handler: %s needs two out arguments, but have %d", typeString, ctype.NumOut())
}
// Reply type must be exported.
replyType := ctype.Out(0)
if !goutil.IsExportedOrBuiltinType(replyType) {
return nil, errors.Errorf("call-handler: %s first reply type not exported: %s", typeString, replyType)
}
// The return type of the method must be *Status.
if returnType := ctype.Out(1); !isStatusType(returnType.String()) {
return nil, errors.Errorf("call-handler: %s second out argument %s is not *erpc.Status", typeString, returnType)
}
// needs two ins: CallCtx, *<T>.
if ctype.NumIn() != 2 {
return nil, errors.Errorf("call-handler: %s needs two in argument, but have %d", typeString, ctype.NumIn())
}
// First arg need be exported or builtin, and need be a pointer.
argType := ctype.In(1)
if !goutil.IsExportedOrBuiltinType(argType) {
return nil, errors.Errorf("call-handler: %s arg type not exported: %s", typeString, argType)
}
if argType.Kind() != reflect.Ptr {
return nil, errors.Errorf("call-handler: %s arg type need be a pointer: %s", typeString, argType)
}
// first agr need be a CallCtx (struct pointer or CallCtx).
ctxType := ctype.In(0)
var handleFunc func(*handlerCtx, reflect.Value)
switch ctxType.Kind() {
default:
return nil, errors.Errorf("call-handler: %s's first arg must be erpc.CallCtx type or struct pointer: %s", typeString, ctxType)
case reflect.Interface:
iface := reflect.TypeOf((*CallCtx)(nil)).Elem()
if !ctxType.Implements(iface) ||
!iface.Implements(reflect.New(ctxType).Type().Elem()) {
return nil, errors.Errorf("call-handler: %s's first arg must be erpc.CallCtx type or struct pointer: %s", typeString, ctxType)
}
handleFunc = func(ctx *handlerCtx, argValue reflect.Value) {
rets := cValue.Call([]reflect.Value{reflect.ValueOf(ctx), argValue})
stat := (*Status)(unsafe.Pointer(rets[1].Pointer()))
if !stat.OK() {
ctx.stat = stat
ctx.output.SetStatus(stat)
} else {
ctx.output.SetBody(rets[0].Interface())
}
}
case reflect.Ptr:
var ctxTypeElem = ctxType.Elem()
if ctxTypeElem.Kind() != reflect.Struct {
return nil, errors.Errorf("call-handler: %s's first arg must be erpc.CallCtx type or struct pointer: %s", typeString, ctxType)
}
iType, ok := ctxTypeElem.FieldByName("CallCtx")
if !ok || !iType.Anonymous {
return nil, errors.Errorf("call-handler: %s's first arg do not have anonymous field erpc.CallCtx: %s", typeString, ctxType)
}
type CallCtrlValue struct {
ctrl reflect.Value
ctxPtr *CallCtx
}
var callCtxOffset = iType.Offset
var pool = &sync.Pool{
New: func() interface{} {
ctrl := reflect.New(ctxTypeElem)
return &CallCtrlValue{
ctrl: ctrl,
ctxPtr: (*CallCtx)(unsafe.Pointer(uintptr(unsafe.Pointer(ctrl.Pointer())) + callCtxOffset)),
}
},
}
handleFunc = func(ctx *handlerCtx, argValue reflect.Value) {
obj := pool.Get().(*CallCtrlValue)
*obj.ctxPtr = ctx
rets := cValue.Call([]reflect.Value{obj.ctrl, argValue})
stat := (*Status)(unsafe.Pointer(rets[1].Pointer()))
if !stat.OK() {
ctx.stat = stat
ctx.output.SetStatus(stat)
} else {
ctx.output.SetBody(rets[0].Interface())
}
pool.Put(obj)
}
}
if pluginContainer == nil {
pluginContainer = newPluginContainer()
}
return []*Handler{&Handler{
name: globalServiceMethodMapper(prefix, handlerFuncName(cValue)),
handleFunc: handleFunc,
argElem: argType.Elem(),
reply: replyType,
pluginContainer: pluginContainer,
}}, nil
}
// NOTE: pushCtrlStruct needs to implement PushCtx interface.
func makePushHandlersFromStruct(prefix string, pushCtrlStruct interface{}, pluginContainer *PluginContainer) ([]*Handler, error) {
var (
ctype = reflect.TypeOf(pushCtrlStruct)
handlers = make([]*Handler, 0, 1)
)
if ctype.Kind() != reflect.Ptr {
return nil, errors.Errorf("push-handler: the type is not struct point: %s", ctype.String())
}
var ctypeElem = ctype.Elem()
if ctypeElem.Kind() != reflect.Struct {
return nil, errors.Errorf("push-handler: the type is not struct point: %s", ctype.String())
}
iType, ok := ctypeElem.FieldByName("PushCtx")
if !ok || !iType.Anonymous {
return nil, errors.Errorf("push-handler: the struct do not have anonymous field erpc.PushCtx: %s", ctype.String())
}
var pushCtxOffset = iType.Offset
if pluginContainer == nil {
pluginContainer = newPluginContainer()
}
type PushCtrlValue struct {
ctrl reflect.Value
ctxPtr *PushCtx
}
var pool = &sync.Pool{
New: func() interface{} {
ctrl := reflect.New(ctypeElem)
return &PushCtrlValue{
ctrl: ctrl,
ctxPtr: (*PushCtx)(unsafe.Pointer(uintptr(unsafe.Pointer(ctrl.Pointer())) + pushCtxOffset)),
}
},
}
for m := 0; m < ctype.NumMethod(); m++ {
method := ctype.Method(m)
mtype := method.Type
mname := method.Name
// Method must be exported.
if method.PkgPath != "" {
continue
}
// Method needs two ins: receiver, *<T>.
if mtype.NumIn() != 2 {
if isBelongToCallCtx(mname) {
continue
}
return nil, errors.Errorf("push-handler: %s.%s needs one in argument, but have %d", ctype.String(), mname, mtype.NumIn())
}
// Receiver need be a struct pointer.
structType := mtype.In(0)
if structType.Kind() != reflect.Ptr || structType.Elem().Kind() != reflect.Struct {
if isBelongToCallCtx(mname) {
continue
}
return nil, errors.Errorf("push-handler: %s.%s receiver need be a struct pointer: %s", ctype.String(), mname, structType)
}
// First arg need be exported or builtin, and need be a pointer.
argType := mtype.In(1)
if !goutil.IsExportedOrBuiltinType(argType) {
if isBelongToCallCtx(mname) {
continue
}
return nil, errors.Errorf("push-handler: %s.%s arg type not exported: %s", ctype.String(), mname, argType)
}
if argType.Kind() != reflect.Ptr {
if isBelongToCallCtx(mname) {
continue
}
return nil, errors.Errorf("push-handler: %s.%s arg type need be a pointer: %s", ctype.String(), mname, argType)
}
// Method needs one out: *Status.
if mtype.NumOut() != 1 {
if isBelongToCallCtx(mname) {
continue
}
return nil, errors.Errorf("push-handler: %s.%s needs one out arguments, but have %d", ctype.String(), mname, mtype.NumOut())
}
// The return type of the method must be *Status.
if returnType := mtype.Out(0); !isStatusType(returnType.String()) {
if isBelongToCallCtx(mname) {
continue
}
return nil, errors.Errorf("push-handler: %s.%s out argument %s is not *erpc.Status", ctype.String(), mname, returnType)
}
var methodFunc = method.Func
var handleFunc = func(ctx *handlerCtx, argValue reflect.Value) {
obj := pool.Get().(*PushCtrlValue)
*obj.ctxPtr = ctx
rets := methodFunc.Call([]reflect.Value{obj.ctrl, argValue})
ctx.stat = (*Status)(unsafe.Pointer(rets[0].Pointer()))
pool.Put(obj)
}
handlers = append(handlers, &Handler{
handleFunc: handleFunc,
argElem: argType.Elem(),
pluginContainer: pluginContainer,
name: globalServiceMethodMapper(
globalServiceMethodMapper(prefix, ctrlStructName(ctype)),
mname,
),
})
}
return handlers, nil
}
func makePushHandlersFromFunc(prefix string, pushHandleFunc interface{}, pluginContainer *PluginContainer) ([]*Handler, error) {
var (
ctype = reflect.TypeOf(pushHandleFunc)
cValue = reflect.ValueOf(pushHandleFunc)
typeString = objectName(cValue)
)
if ctype.Kind() != reflect.Func {
return nil, errors.Errorf("push-handler: the type is not function: %s", typeString)
}
// needs one out: *Status.
if ctype.NumOut() != 1 {
return nil, errors.Errorf("push-handler: %s needs one out arguments, but have %d", typeString, ctype.NumOut())
}
// The return type of the method must be *Status.
if returnType := ctype.Out(0); !isStatusType(returnType.String()) {
return nil, errors.Errorf("push-handler: %s out argument %s is not *erpc.Status", typeString, returnType)
}
// needs two ins: PushCtx, *<T>.
if ctype.NumIn() != 2 {
return nil, errors.Errorf("push-handler: %s needs two in argument, but have %d", typeString, ctype.NumIn())
}
// First arg need be exported or builtin, and need be a pointer.
argType := ctype.In(1)
if !goutil.IsExportedOrBuiltinType(argType) {
return nil, errors.Errorf("push-handler: %s arg type not exported: %s", typeString, argType)
}
if argType.Kind() != reflect.Ptr {
return nil, errors.Errorf("push-handler: %s arg type need be a pointer: %s", typeString, argType)
}
// first agr need be a PushCtx (struct pointer or PushCtx).
ctxType := ctype.In(0)
var handleFunc func(*handlerCtx, reflect.Value)
switch ctxType.Kind() {
default:
return nil, errors.Errorf("push-handler: %s's first arg must be erpc.PushCtx type or struct pointer: %s", typeString, ctxType)
case reflect.Interface:
iface := reflect.TypeOf((*PushCtx)(nil)).Elem()
if !ctxType.Implements(iface) ||
!iface.Implements(reflect.New(ctxType).Type().Elem()) {
return nil, errors.Errorf("push-handler: %s's first arg need implement erpc.PushCtx: %s", typeString, ctxType)
}
handleFunc = func(ctx *handlerCtx, argValue reflect.Value) {
rets := cValue.Call([]reflect.Value{reflect.ValueOf(ctx), argValue})
ctx.stat = (*Status)(unsafe.Pointer(rets[0].Pointer()))
}
case reflect.Ptr:
var ctxTypeElem = ctxType.Elem()
if ctxTypeElem.Kind() != reflect.Struct {
return nil, errors.Errorf("push-handler: %s's first arg must be erpc.PushCtx type or struct pointer: %s", typeString, ctxType)
}
iType, ok := ctxTypeElem.FieldByName("PushCtx")
if !ok || !iType.Anonymous {
return nil, errors.Errorf("push-handler: %s's first arg do not have anonymous field erpc.PushCtx: %s", typeString, ctxType)
}
type PushCtrlValue struct {
ctrl reflect.Value
ctxPtr *PushCtx
}
var pushCtxOffset = iType.Offset
var pool = &sync.Pool{
New: func() interface{} {
ctrl := reflect.New(ctxTypeElem)
return &PushCtrlValue{
ctrl: ctrl,
ctxPtr: (*PushCtx)(unsafe.Pointer(uintptr(unsafe.Pointer(ctrl.Pointer())) + pushCtxOffset)),
}
},
}
handleFunc = func(ctx *handlerCtx, argValue reflect.Value) {
obj := pool.Get().(*PushCtrlValue)
*obj.ctxPtr = ctx
rets := cValue.Call([]reflect.Value{obj.ctrl, argValue})
ctx.stat = (*Status)(unsafe.Pointer(rets[0].Pointer()))
pool.Put(obj)
}
}
if pluginContainer == nil {
pluginContainer = newPluginContainer()
}
return []*Handler{&Handler{
name: globalServiceMethodMapper(prefix, handlerFuncName(cValue)),
handleFunc: handleFunc,
argElem: argType.Elem(),
pluginContainer: pluginContainer,
}}, nil
}
func isBelongToCallCtx(name string) bool {
for m := 0; m < typeOfCallCtx.NumMethod(); m++ {
if name == typeOfCallCtx.Method(m).Name {
return true
}
}
return false
}
func isBelongToPushCtx(name string) bool {
for m := 0; m < typeOfPushCtx.NumMethod(); m++ {
if name == typeOfPushCtx.Method(m).Name {
return true
}
}
return false
}
func isStatusType(s string) bool {
return strings.HasPrefix(s, "*") && strings.HasSuffix(s, ".Status")
}
func ctrlStructName(ctype reflect.Type) string {
split := strings.Split(ctype.String(), ".")
return split[len(split)-1]
}
func handlerFuncName(v reflect.Value) string {
str := objectName(v)
split := strings.Split(str, ".")
return split[len(split)-1]
}
func objectName(v reflect.Value) string {
t := v.Type()
if t.Kind() == reflect.Func {
return runtime.FuncForPC(v.Pointer()).Name()
}
return t.String()
}
// Name returns the handler name.
func (h *Handler) Name() string {
return h.name
}
// ArgElemType returns the handler arg elem type.
func (h *Handler) ArgElemType() reflect.Type {
return h.argElem
}
// NewArgValue creates a new arg elem value.
func (h *Handler) NewArgValue() reflect.Value {
return reflect.New(h.argElem)
}
// ReplyType returns the handler reply type
func (h *Handler) ReplyType() reflect.Type {
return h.reply
}
// IsCall checks if it is call handler or not.
func (h *Handler) IsCall() bool {
return h.routerTypeName == pnCall || h.routerTypeName == pnUnknownCall
}
// IsPush checks if it is push handler or not.
func (h *Handler) IsPush() bool {
return h.routerTypeName == pnPush || h.routerTypeName == pnUnknownPush
}
// IsUnknown checks if it is unknown handler(call/push) or not.
func (h *Handler) IsUnknown() bool {
return h.isUnknown
}
// RouterTypeName returns the router type name.
func (h *Handler) RouterTypeName() string {
return h.routerTypeName
}
Go
1
https://gitee.com/chenxianle/erpc.git
git@gitee.com:chenxianle/erpc.git
chenxianle
erpc
erpc
master

搜索帮助