-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
212 lines (181 loc) · 5.32 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package rpcgo
import (
"context"
"errors"
"fmt"
"reflect"
"runtime/debug"
"sync"
"sync/atomic"
)
type Replyer struct {
channel Channel
replyed int32
codec Codec
req *RequestMsg
outInterceptor []func(*RequestMsg, interface{}, error)
}
func (r *Replyer) AppendOutInterceptor(interceptor func(*RequestMsg, interface{}, error)) {
r.outInterceptor = append(r.outInterceptor, interceptor)
}
func (r *Replyer) callOutInterceptor(ret interface{}, err error) {
for _, fn := range r.outInterceptor {
func() {
defer func() {
if r := recover(); r != nil {
logger.Errorf("%s ", fmt.Errorf(fmt.Sprintf("%v: %s", r, debug.Stack())))
}
}()
fn(r.req, ret, err)
}()
}
}
func (r *Replyer) Error(err error) {
if atomic.CompareAndSwapInt32(&r.replyed, 0, 1) {
r.callOutInterceptor(nil, err)
if r.req.Oneway {
return
}
resp := &ResponseMsg{
Seq: r.req.Seq,
}
if _, ok := err.(*Error); ok {
resp.Err = err.(*Error)
} else {
resp.Err = NewError(ErrMethod, err.Error())
}
if e := r.channel.Reply(resp); e != nil {
logger.Errorf("send rpc response to (%s) error:%s\n", r.channel.Name(), e.Error())
}
}
}
func (r *Replyer) Reply(ret interface{}) {
if atomic.CompareAndSwapInt32(&r.replyed, 0, 1) {
r.callOutInterceptor(ret, nil)
if r.req.Oneway {
return
}
resp := &ResponseMsg{
Seq: r.req.Seq,
}
if b, e := r.codec.Encode(ret); e != nil {
logger.Errorf("send rpc response to (%s) encode ret error:%s\n", r.channel.Name(), e.Error())
return
} else {
resp.Ret = b
}
if e := r.channel.Reply(resp); e != nil {
logger.Errorf("send rpc response to (%s) error:%s\n", r.channel.Name(), e.Error())
}
}
}
func (r *Replyer) Channel() Channel {
return r.channel
}
type methodCaller struct {
name string
argType reflect.Type
fn reflect.Value
}
// 接受的method func(context.Context, *Replyer,*Pointer)
func makeMethodCaller(name string, method interface{}) (*methodCaller, error) {
if method == nil {
return nil, errors.New("method is nil")
}
fnType := reflect.TypeOf(method)
if fnType.Kind() != reflect.Func {
return nil, errors.New("method should have type func(context.Contex,*Replyer,*Pointer)")
}
if fnType.NumIn() != 3 {
return nil, errors.New("method should have type func(context.Contex,*Replyer,*Pointer)")
}
if fnType.In(0) != reflect.TypeOf((*context.Context)(nil)).Elem() {
return nil, errors.New("method should have type func(context.Contex,*Replyer,*Pointer)")
}
if fnType.In(1) != reflect.TypeOf(&Replyer{}) {
return nil, errors.New("method should have type func(context.Context,*Replyer,*Pointer)")
}
if fnType.In(2).Kind() != reflect.Ptr {
return nil, errors.New("method should have type func(context.Context,*Replyer,*Pointer)")
}
caller := &methodCaller{
argType: fnType.In(2).Elem(),
fn: reflect.ValueOf(method),
name: name,
}
return caller, nil
}
type Server struct {
sync.RWMutex
methods map[string]*methodCaller
codec Codec
stoped atomic.Bool
inInterceptor []func(*Replyer, *RequestMsg) bool //入站管道线
}
func NewServer(codec Codec) *Server {
return &Server{
methods: map[string]*methodCaller{},
codec: codec}
}
func (s *Server) SetInInterceptor(interceptor []func(*Replyer, *RequestMsg) bool) *Server {
s.inInterceptor = interceptor
return s
}
func (s *Server) Stop() {
s.stoped.CompareAndSwap(false, true)
}
func (s *Server) Register(name string, method interface{}) error {
s.Lock()
defer s.Unlock()
if name == "" {
return errors.New("RegisterMethod nams is nil")
} else if caller, err := makeMethodCaller(name, method); err != nil {
return err
} else if _, ok := s.methods[name]; ok {
return fmt.Errorf("duplicate method:%s", name)
} else {
s.methods[name] = caller
return nil
}
}
func (s *Server) UnRegister(name string) {
s.Lock()
defer s.Unlock()
delete(s.methods, name)
}
func (s *Server) method(name string) *methodCaller {
s.RLock()
defer s.RUnlock()
return s.methods[name]
}
func (s *Server) OnMessage(context context.Context, channel Channel, req *RequestMsg) {
replyer := &Replyer{channel: channel, req: req, codec: s.codec}
if s.stoped.Load() {
replyer.Error(NewError(ErrServiceUnavaliable, "service unavaliable"))
return
}
caller := s.method(req.Method)
if caller == nil {
replyer.Error(NewError(ErrInvaildMethod, fmt.Sprintf("method %s not found", req.Method)))
return
}
arg := reflect.New(caller.argType).Interface()
if err := s.codec.Decode(req.Arg, arg); err != nil {
logger.Errorf("method:%s decode arg error:%s channel:%s", req.Method, err.Error(), replyer.channel.Name())
replyer.Error(NewError(ErrOther, fmt.Sprintf("arg decode error:%v", err)))
return
}
req.arg = arg
defer func() {
if r := recover(); r != nil {
logger.Errorf("method:%s channel:%s %s", req.Method, replyer.channel.Name(), fmt.Errorf(fmt.Sprintf("%v: %s", r, debug.Stack())))
replyer.Error(NewError(ErrOther, "method panic"))
}
}()
for _, v := range s.inInterceptor {
if !v(replyer, req) {
return
}
}
caller.fn.Call([]reflect.Value{reflect.ValueOf(context), reflect.ValueOf(replyer), reflect.ValueOf(arg)})
}