Pull rpcplus in local for the time being. We need to modify it for server side middleware
This commit is contained in:
parent
8825b5c0a8
commit
0c9f8411bb
@ -12,7 +12,6 @@ import (
|
|||||||
"github.com/micro/go-micro/registry"
|
"github.com/micro/go-micro/registry"
|
||||||
"github.com/micro/go-micro/transport"
|
"github.com/micro/go-micro/transport"
|
||||||
|
|
||||||
rpc "github.com/youtube/vitess/go/rpcplus"
|
|
||||||
"golang.org/x/net/context"
|
"golang.org/x/net/context"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -94,7 +93,7 @@ func (r *rpcClient) call(ctx context.Context, address string, request Request, r
|
|||||||
}
|
}
|
||||||
defer c.Close()
|
defer c.Close()
|
||||||
|
|
||||||
client := rpc.NewClientWithCodec(newRpcPlusCodec(msg, c, cf))
|
client := newClientWithCodec(newRpcPlusCodec(msg, c, cf))
|
||||||
err = client.Call(ctx, request.Method(), request.Request(), response)
|
err = client.Call(ctx, request.Method(), request.Request(), response)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@ -126,7 +125,7 @@ func (r *rpcClient) stream(ctx context.Context, address string, request Request,
|
|||||||
return nil, errors.InternalServerError("go.micro.client", fmt.Sprintf("Error sending request: %v", err))
|
return nil, errors.InternalServerError("go.micro.client", fmt.Sprintf("Error sending request: %v", err))
|
||||||
}
|
}
|
||||||
|
|
||||||
client := rpc.NewClientWithCodec(newRpcPlusCodec(msg, c, cf))
|
client := newClientWithCodec(newRpcPlusCodec(msg, c, cf))
|
||||||
call := client.StreamGo(request.Method(), request.Request(), responseChan)
|
call := client.StreamGo(request.Method(), request.Request(), responseChan)
|
||||||
|
|
||||||
return &rpcStream{
|
return &rpcStream{
|
||||||
|
@ -7,7 +7,6 @@ import (
|
|||||||
"github.com/micro/go-micro/codec/jsonrpc"
|
"github.com/micro/go-micro/codec/jsonrpc"
|
||||||
"github.com/micro/go-micro/codec/protorpc"
|
"github.com/micro/go-micro/codec/protorpc"
|
||||||
"github.com/micro/go-micro/transport"
|
"github.com/micro/go-micro/transport"
|
||||||
rpc "github.com/youtube/vitess/go/rpcplus"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type rpcPlusCodec struct {
|
type rpcPlusCodec struct {
|
||||||
@ -63,7 +62,7 @@ func newRpcPlusCodec(req *transport.Message, client transport.Client, c codec.Ne
|
|||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *rpcPlusCodec) WriteRequest(req *rpc.Request, body interface{}) error {
|
func (c *rpcPlusCodec) WriteRequest(req *request, body interface{}) error {
|
||||||
m := &codec.Message{
|
m := &codec.Message{
|
||||||
Id: req.Seq,
|
Id: req.Seq,
|
||||||
Method: req.ServiceMethod,
|
Method: req.ServiceMethod,
|
||||||
@ -76,7 +75,7 @@ func (c *rpcPlusCodec) WriteRequest(req *rpc.Request, body interface{}) error {
|
|||||||
return c.client.Send(c.req)
|
return c.client.Send(c.req)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *rpcPlusCodec) ReadResponseHeader(r *rpc.Response) error {
|
func (c *rpcPlusCodec) ReadResponseHeader(r *response) error {
|
||||||
var m transport.Message
|
var m transport.Message
|
||||||
if err := c.client.Recv(&m); err != nil {
|
if err := c.client.Recv(&m); err != nil {
|
||||||
return err
|
return err
|
||||||
|
@ -1,13 +1,9 @@
|
|||||||
package client
|
package client
|
||||||
|
|
||||||
import (
|
|
||||||
rpc "github.com/youtube/vitess/go/rpcplus"
|
|
||||||
)
|
|
||||||
|
|
||||||
type rpcStream struct {
|
type rpcStream struct {
|
||||||
request Request
|
request Request
|
||||||
call *rpc.Call
|
call *call
|
||||||
client *rpc.Client
|
client *client
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *rpcStream) Request() Request {
|
func (r *rpcStream) Request() Request {
|
||||||
|
304
client/rpcplus_client.go
Normal file
304
client/rpcplus_client.go
Normal file
@ -0,0 +1,304 @@
|
|||||||
|
// Copyright 2009 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package client
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"reflect"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/youtube/vitess/go/trace"
|
||||||
|
"golang.org/x/net/context"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
lastStreamResponseError = "EOS"
|
||||||
|
)
|
||||||
|
|
||||||
|
// serverError represents an error that has been returned from
|
||||||
|
// the remote side of the RPC connection.
|
||||||
|
type serverError string
|
||||||
|
|
||||||
|
func (e serverError) Error() string {
|
||||||
|
return string(e)
|
||||||
|
}
|
||||||
|
|
||||||
|
// errShutdown holds the specific error for closing/closed connections
|
||||||
|
var errShutdown = errors.New("connection is shut down")
|
||||||
|
|
||||||
|
// call represents an active RPC.
|
||||||
|
type call struct {
|
||||||
|
ServiceMethod string // The name of the service and method to call.
|
||||||
|
Args interface{} // The argument to the function (*struct).
|
||||||
|
Reply interface{} // The reply from the function (*struct for single, chan * struct for streaming).
|
||||||
|
Error error // After completion, the error status.
|
||||||
|
Done chan *call // Strobes when call is complete (nil for streaming RPCs)
|
||||||
|
Stream bool // True for a streaming RPC call, false otherwise
|
||||||
|
Subseq uint64 // The next expected subseq in the packets
|
||||||
|
}
|
||||||
|
|
||||||
|
// client represents an RPC client.
|
||||||
|
// There may be multiple outstanding calls associated
|
||||||
|
// with a single client, and a client may be used by
|
||||||
|
// multiple goroutines simultaneously.
|
||||||
|
type client struct {
|
||||||
|
mutex sync.Mutex // protects pending, seq, request
|
||||||
|
sending sync.Mutex
|
||||||
|
request request
|
||||||
|
seq uint64
|
||||||
|
codec clientCodec
|
||||||
|
pending map[uint64]*call
|
||||||
|
closing bool
|
||||||
|
shutdown bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// A clientCodec implements writing of RPC requests and
|
||||||
|
// reading of RPC responses for the client side of an RPC session.
|
||||||
|
// The client calls WriteRequest to write a request to the connection
|
||||||
|
// and calls ReadResponseHeader and ReadResponseBody in pairs
|
||||||
|
// to read responses. The client calls Close when finished with the
|
||||||
|
// connection. ReadResponseBody may be called with a nil
|
||||||
|
// argument to force the body of the response to be read and then
|
||||||
|
// discarded.
|
||||||
|
type clientCodec interface {
|
||||||
|
WriteRequest(*request, interface{}) error
|
||||||
|
ReadResponseHeader(*response) error
|
||||||
|
ReadResponseBody(interface{}) error
|
||||||
|
|
||||||
|
Close() error
|
||||||
|
}
|
||||||
|
|
||||||
|
type request struct {
|
||||||
|
ServiceMethod string // format: "Service.Method"
|
||||||
|
Seq uint64 // sequence number chosen by client
|
||||||
|
next *request // for free list in Server
|
||||||
|
}
|
||||||
|
|
||||||
|
type response struct {
|
||||||
|
ServiceMethod string // echoes that of the Request
|
||||||
|
Seq uint64 // echoes that of the request
|
||||||
|
Error string // error, if any.
|
||||||
|
next *response // for free list in Server
|
||||||
|
}
|
||||||
|
|
||||||
|
func (client *client) send(call *call) {
|
||||||
|
client.sending.Lock()
|
||||||
|
defer client.sending.Unlock()
|
||||||
|
|
||||||
|
// Register this call.
|
||||||
|
client.mutex.Lock()
|
||||||
|
if client.shutdown {
|
||||||
|
call.Error = errShutdown
|
||||||
|
client.mutex.Unlock()
|
||||||
|
call.done()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
seq := client.seq
|
||||||
|
client.seq++
|
||||||
|
client.pending[seq] = call
|
||||||
|
client.mutex.Unlock()
|
||||||
|
|
||||||
|
// Encode and send the request.
|
||||||
|
client.request.Seq = seq
|
||||||
|
client.request.ServiceMethod = call.ServiceMethod
|
||||||
|
err := client.codec.WriteRequest(&client.request, call.Args)
|
||||||
|
if err != nil {
|
||||||
|
client.mutex.Lock()
|
||||||
|
call = client.pending[seq]
|
||||||
|
delete(client.pending, seq)
|
||||||
|
client.mutex.Unlock()
|
||||||
|
if call != nil {
|
||||||
|
call.Error = err
|
||||||
|
call.done()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (client *client) input() {
|
||||||
|
var err error
|
||||||
|
var resp response
|
||||||
|
for err == nil {
|
||||||
|
resp = response{}
|
||||||
|
err = client.codec.ReadResponseHeader(&resp)
|
||||||
|
if err != nil {
|
||||||
|
if err == io.EOF && !client.closing {
|
||||||
|
err = io.ErrUnexpectedEOF
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
seq := resp.Seq
|
||||||
|
client.mutex.Lock()
|
||||||
|
call := client.pending[seq]
|
||||||
|
client.mutex.Unlock()
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case call == nil:
|
||||||
|
// We've got no pending call. That usually means that
|
||||||
|
// WriteRequest partially failed, and call was already
|
||||||
|
// removed; response is a server telling us about an
|
||||||
|
// error reading request body. We should still attempt
|
||||||
|
// to read error body, but there's no one to give it to.
|
||||||
|
err = client.codec.ReadResponseBody(nil)
|
||||||
|
if err != nil {
|
||||||
|
err = errors.New("reading error body: " + err.Error())
|
||||||
|
}
|
||||||
|
case resp.Error != "":
|
||||||
|
// We've got an error response. Give this to the request;
|
||||||
|
// any subsequent requests will get the ReadResponseBody
|
||||||
|
// error if there is one.
|
||||||
|
if !(call.Stream && resp.Error == lastStreamResponseError) {
|
||||||
|
call.Error = serverError(resp.Error)
|
||||||
|
}
|
||||||
|
err = client.codec.ReadResponseBody(nil)
|
||||||
|
if err != nil {
|
||||||
|
err = errors.New("reading error payload: " + err.Error())
|
||||||
|
}
|
||||||
|
client.done(seq)
|
||||||
|
case call.Stream:
|
||||||
|
// call.Reply is a chan *T2
|
||||||
|
// we need to create a T2 and get a *T2 back
|
||||||
|
value := reflect.New(reflect.TypeOf(call.Reply).Elem().Elem()).Interface()
|
||||||
|
err = client.codec.ReadResponseBody(value)
|
||||||
|
if err != nil {
|
||||||
|
call.Error = errors.New("reading body " + err.Error())
|
||||||
|
} else {
|
||||||
|
// writing on the channel could block forever. For
|
||||||
|
// instance, if a client calls 'close', this might block
|
||||||
|
// forever. the current suggestion is for the
|
||||||
|
// client to drain the receiving channel in that case
|
||||||
|
reflect.ValueOf(call.Reply).Send(reflect.ValueOf(value))
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
err = client.codec.ReadResponseBody(call.Reply)
|
||||||
|
if err != nil {
|
||||||
|
call.Error = errors.New("reading body " + err.Error())
|
||||||
|
}
|
||||||
|
client.done(seq)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Terminate pending calls.
|
||||||
|
client.sending.Lock()
|
||||||
|
client.mutex.Lock()
|
||||||
|
client.shutdown = true
|
||||||
|
closing := client.closing
|
||||||
|
for _, call := range client.pending {
|
||||||
|
call.Error = err
|
||||||
|
call.done()
|
||||||
|
}
|
||||||
|
client.mutex.Unlock()
|
||||||
|
client.sending.Unlock()
|
||||||
|
if err != io.EOF && !closing {
|
||||||
|
log.Println("rpc: client protocol error:", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (client *client) done(seq uint64) {
|
||||||
|
client.mutex.Lock()
|
||||||
|
call := client.pending[seq]
|
||||||
|
delete(client.pending, seq)
|
||||||
|
client.mutex.Unlock()
|
||||||
|
|
||||||
|
if call != nil {
|
||||||
|
call.done()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (call *call) done() {
|
||||||
|
if call.Stream {
|
||||||
|
// need to close the channel. client won't be able to read any more.
|
||||||
|
reflect.ValueOf(call.Reply).Close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case call.Done <- call:
|
||||||
|
// ok
|
||||||
|
default:
|
||||||
|
// We don't want to block here. It is the caller's responsibility to make
|
||||||
|
// sure the channel has enough buffer space. See comment in Go().
|
||||||
|
log.Println("rpc: discarding call reply due to insufficient Done chan capacity")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewclientWithCodec is like Newclient but uses the specified
|
||||||
|
// codec to encode requests and decode responses.
|
||||||
|
func newClientWithCodec(codec clientCodec) *client {
|
||||||
|
client := &client{
|
||||||
|
codec: codec,
|
||||||
|
pending: make(map[uint64]*call),
|
||||||
|
}
|
||||||
|
go client.input()
|
||||||
|
return client
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close closes the client connection
|
||||||
|
func (client *client) Close() error {
|
||||||
|
client.mutex.Lock()
|
||||||
|
if client.shutdown || client.closing {
|
||||||
|
client.mutex.Unlock()
|
||||||
|
return errShutdown
|
||||||
|
}
|
||||||
|
client.closing = true
|
||||||
|
client.mutex.Unlock()
|
||||||
|
return client.codec.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Go invokes the function asynchronously. It returns the call structure representing
|
||||||
|
// the invocation. The done channel will signal when the call is complete by returning
|
||||||
|
// the same call object. If done is nil, Go will allocate a new channel.
|
||||||
|
// If non-nil, done must be buffered or Go will deliberately crash.
|
||||||
|
func (client *client) Go(ctx context.Context, serviceMethod string, args interface{}, reply interface{}, done chan *call) *call {
|
||||||
|
span := trace.NewSpanFromContext(ctx)
|
||||||
|
span.StartClient(serviceMethod)
|
||||||
|
defer span.Finish()
|
||||||
|
|
||||||
|
cal := new(call)
|
||||||
|
cal.ServiceMethod = serviceMethod
|
||||||
|
cal.Args = args
|
||||||
|
cal.Reply = reply
|
||||||
|
if done == nil {
|
||||||
|
done = make(chan *call, 10) // buffered.
|
||||||
|
} else {
|
||||||
|
// If caller passes done != nil, it must arrange that
|
||||||
|
// done has enough buffer for the number of simultaneous
|
||||||
|
// RPCs that will be using that channel. If the channel
|
||||||
|
// is totally unbuffered, it's best not to run at all.
|
||||||
|
if cap(done) == 0 {
|
||||||
|
log.Panic("rpc: done channel is unbuffered")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cal.Done = done
|
||||||
|
client.send(cal)
|
||||||
|
return cal
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamGo invokes the streaming function asynchronously. It returns the call structure representing
|
||||||
|
// the invocation.
|
||||||
|
func (client *client) StreamGo(serviceMethod string, args interface{}, replyStream interface{}) *call {
|
||||||
|
// first check the replyStream object is a stream of pointers to a data structure
|
||||||
|
typ := reflect.TypeOf(replyStream)
|
||||||
|
// FIXME: check the direction of the channel, maybe?
|
||||||
|
if typ.Kind() != reflect.Chan || typ.Elem().Kind() != reflect.Ptr {
|
||||||
|
log.Panic("rpc: replyStream is not a channel of pointers")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
call := new(call)
|
||||||
|
call.ServiceMethod = serviceMethod
|
||||||
|
call.Args = args
|
||||||
|
call.Reply = replyStream
|
||||||
|
call.Stream = true
|
||||||
|
call.Subseq = 0
|
||||||
|
client.send(call)
|
||||||
|
return call
|
||||||
|
}
|
||||||
|
|
||||||
|
// call invokes the named function, waits for it to complete, and returns its error status.
|
||||||
|
func (client *client) Call(ctx context.Context, serviceMethod string, args interface{}, reply interface{}) error {
|
||||||
|
call := <-client.Go(ctx, serviceMethod, args, reply, make(chan *call, 1)).Done
|
||||||
|
return call.Error
|
||||||
|
}
|
@ -7,7 +7,6 @@ import (
|
|||||||
"github.com/micro/go-micro/codec/jsonrpc"
|
"github.com/micro/go-micro/codec/jsonrpc"
|
||||||
"github.com/micro/go-micro/codec/protorpc"
|
"github.com/micro/go-micro/codec/protorpc"
|
||||||
"github.com/micro/go-micro/transport"
|
"github.com/micro/go-micro/transport"
|
||||||
rpc "github.com/youtube/vitess/go/rpcplus"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type rpcPlusCodec struct {
|
type rpcPlusCodec struct {
|
||||||
@ -47,7 +46,7 @@ func (rwc *readWriteCloser) Close() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func newRpcPlusCodec(req *transport.Message, socket transport.Socket, c codec.NewCodec) rpc.ServerCodec {
|
func newRpcPlusCodec(req *transport.Message, socket transport.Socket, c codec.NewCodec) serverCodec {
|
||||||
rwc := &readWriteCloser{
|
rwc := &readWriteCloser{
|
||||||
rbuf: bytes.NewBuffer(req.Body),
|
rbuf: bytes.NewBuffer(req.Body),
|
||||||
wbuf: bytes.NewBuffer(nil),
|
wbuf: bytes.NewBuffer(nil),
|
||||||
@ -61,7 +60,7 @@ func newRpcPlusCodec(req *transport.Message, socket transport.Socket, c codec.Ne
|
|||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *rpcPlusCodec) ReadRequestHeader(r *rpc.Request) error {
|
func (c *rpcPlusCodec) ReadRequestHeader(r *request) error {
|
||||||
var m codec.Message
|
var m codec.Message
|
||||||
err := c.codec.ReadHeader(&m, codec.Request)
|
err := c.codec.ReadHeader(&m, codec.Request)
|
||||||
r.ServiceMethod = m.Method
|
r.ServiceMethod = m.Method
|
||||||
@ -73,7 +72,7 @@ func (c *rpcPlusCodec) ReadRequestBody(b interface{}) error {
|
|||||||
return c.codec.ReadBody(b)
|
return c.codec.ReadBody(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *rpcPlusCodec) WriteResponse(r *rpc.Response, body interface{}, last bool) error {
|
func (c *rpcPlusCodec) WriteResponse(r *response, body interface{}, last bool) error {
|
||||||
c.buf.wbuf.Reset()
|
c.buf.wbuf.Reset()
|
||||||
m := &codec.Message{
|
m := &codec.Message{
|
||||||
Method: r.ServiceMethod,
|
Method: r.ServiceMethod,
|
||||||
|
@ -13,13 +13,12 @@ import (
|
|||||||
"github.com/micro/go-micro/transport"
|
"github.com/micro/go-micro/transport"
|
||||||
|
|
||||||
log "github.com/golang/glog"
|
log "github.com/golang/glog"
|
||||||
rpc "github.com/youtube/vitess/go/rpcplus"
|
|
||||||
|
|
||||||
"golang.org/x/net/context"
|
"golang.org/x/net/context"
|
||||||
)
|
)
|
||||||
|
|
||||||
type rpcServer struct {
|
type rpcServer struct {
|
||||||
rpc *rpc.Server
|
rpc *server
|
||||||
exit chan chan error
|
exit chan chan error
|
||||||
|
|
||||||
sync.RWMutex
|
sync.RWMutex
|
||||||
@ -31,7 +30,7 @@ type rpcServer struct {
|
|||||||
func newRpcServer(opts ...Option) Server {
|
func newRpcServer(opts ...Option) Server {
|
||||||
return &rpcServer{
|
return &rpcServer{
|
||||||
opts: newOptions(opts...),
|
opts: newOptions(opts...),
|
||||||
rpc: rpc.NewServer(),
|
rpc: newServer(),
|
||||||
handlers: make(map[string]Handler),
|
handlers: make(map[string]Handler),
|
||||||
subscribers: make(map[*subscriber][]broker.Subscriber),
|
subscribers: make(map[*subscriber][]broker.Subscriber),
|
||||||
exit: make(chan chan error),
|
exit: make(chan chan error),
|
||||||
|
490
server/rpcplus_server.go
Normal file
490
server/rpcplus_server.go
Normal file
@ -0,0 +1,490 @@
|
|||||||
|
// Copyright 2009 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
//
|
||||||
|
// Meh, we need to get rid of this shit
|
||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"golang.org/x/net/context"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
lastStreamResponseError = "EOS"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// A value sent as a placeholder for the server's response value when the server
|
||||||
|
// receives an invalid request. It is never decoded by the client since the Response
|
||||||
|
// contains an error when it is used.
|
||||||
|
invalidRequest = struct{}{}
|
||||||
|
|
||||||
|
// Precompute the reflect type for error. Can't use error directly
|
||||||
|
// because Typeof takes an empty interface value. This is annoying.
|
||||||
|
typeOfError = reflect.TypeOf((*error)(nil)).Elem()
|
||||||
|
)
|
||||||
|
|
||||||
|
type methodType struct {
|
||||||
|
sync.Mutex // protects counters
|
||||||
|
method reflect.Method
|
||||||
|
ArgType reflect.Type
|
||||||
|
ReplyType reflect.Type
|
||||||
|
ContextType reflect.Type
|
||||||
|
stream bool
|
||||||
|
numCalls uint
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *methodType) TakesContext() bool {
|
||||||
|
return m.ContextType != nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *methodType) NumCalls() (n uint) {
|
||||||
|
m.Lock()
|
||||||
|
n = m.numCalls
|
||||||
|
m.Unlock()
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
type service struct {
|
||||||
|
name string // name of service
|
||||||
|
rcvr reflect.Value // receiver of methods for the service
|
||||||
|
typ reflect.Type // type of the receiver
|
||||||
|
method map[string]*methodType // registered methods
|
||||||
|
}
|
||||||
|
|
||||||
|
type request struct {
|
||||||
|
ServiceMethod string // format: "Service.Method"
|
||||||
|
Seq uint64 // sequence number chosen by client
|
||||||
|
next *request // for free list in Server
|
||||||
|
}
|
||||||
|
|
||||||
|
type response struct {
|
||||||
|
ServiceMethod string // echoes that of the Request
|
||||||
|
Seq uint64 // echoes that of the request
|
||||||
|
Error string // error, if any.
|
||||||
|
next *response // for free list in Server
|
||||||
|
}
|
||||||
|
|
||||||
|
// server represents an RPC Server.
|
||||||
|
type server struct {
|
||||||
|
mu sync.Mutex // protects the serviceMap
|
||||||
|
serviceMap map[string]*service
|
||||||
|
reqLock sync.Mutex // protects freeReq
|
||||||
|
freeReq *request
|
||||||
|
respLock sync.Mutex // protects freeResp
|
||||||
|
freeResp *response
|
||||||
|
}
|
||||||
|
|
||||||
|
func newServer() *server {
|
||||||
|
return &server{serviceMap: make(map[string]*service)}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Is this an exported - upper case - name?
|
||||||
|
func isExported(name string) bool {
|
||||||
|
rune, _ := utf8.DecodeRuneInString(name)
|
||||||
|
return unicode.IsUpper(rune)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Is this type exported or a builtin?
|
||||||
|
func isExportedOrBuiltinType(t reflect.Type) bool {
|
||||||
|
for t.Kind() == reflect.Ptr {
|
||||||
|
t = t.Elem()
|
||||||
|
}
|
||||||
|
// PkgPath will be non-empty even for an exported type,
|
||||||
|
// so we need to check the type name as well.
|
||||||
|
return isExported(t.Name()) || t.PkgPath() == ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (server *server) Register(rcvr interface{}) error {
|
||||||
|
return server.register(rcvr, "", false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// prepareMethod returns a methodType for the provided method or nil
|
||||||
|
// in case if the method was unsuitable.
|
||||||
|
func prepareMethod(method reflect.Method) *methodType {
|
||||||
|
mtype := method.Type
|
||||||
|
mname := method.Name
|
||||||
|
var replyType, argType, contextType reflect.Type
|
||||||
|
|
||||||
|
stream := false
|
||||||
|
// Method must be exported.
|
||||||
|
if method.PkgPath != "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
switch mtype.NumIn() {
|
||||||
|
case 3:
|
||||||
|
// normal method
|
||||||
|
argType = mtype.In(1)
|
||||||
|
replyType = mtype.In(2)
|
||||||
|
contextType = nil
|
||||||
|
case 4:
|
||||||
|
// method that takes a context
|
||||||
|
argType = mtype.In(2)
|
||||||
|
replyType = mtype.In(3)
|
||||||
|
contextType = mtype.In(1)
|
||||||
|
default:
|
||||||
|
log.Println("method", mname, "of", mtype, "has wrong number of ins:", mtype.NumIn())
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// First arg need not be a pointer.
|
||||||
|
if !isExportedOrBuiltinType(argType) {
|
||||||
|
log.Println(mname, "argument type not exported:", argType)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// the second argument will tell us if it's a streaming call
|
||||||
|
// or a regular call
|
||||||
|
if replyType.Kind() == reflect.Func {
|
||||||
|
// this is a streaming call
|
||||||
|
stream = true
|
||||||
|
if replyType.NumIn() != 1 {
|
||||||
|
log.Println("method", mname, "sendReply has wrong number of ins:", replyType.NumIn())
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if replyType.In(0).Kind() != reflect.Interface {
|
||||||
|
log.Println("method", mname, "sendReply parameter type not an interface:", replyType.In(0))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if replyType.NumOut() != 1 {
|
||||||
|
log.Println("method", mname, "sendReply has wrong number of outs:", replyType.NumOut())
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if returnType := replyType.Out(0); returnType != typeOfError {
|
||||||
|
log.Println("method", mname, "sendReply returns", returnType.String(), "not error")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if replyType.Kind() != reflect.Ptr {
|
||||||
|
log.Println("method", mname, "reply type not a pointer:", replyType)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reply type must be exported.
|
||||||
|
if !isExportedOrBuiltinType(replyType) {
|
||||||
|
log.Println("method", mname, "reply type not exported:", replyType)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// Method needs one out.
|
||||||
|
if mtype.NumOut() != 1 {
|
||||||
|
log.Println("method", mname, "has wrong number of outs:", mtype.NumOut())
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// The return type of the method must be error.
|
||||||
|
if returnType := mtype.Out(0); returnType != typeOfError {
|
||||||
|
log.Println("method", mname, "returns", returnType.String(), "not error")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &methodType{method: method, ArgType: argType, ReplyType: replyType, ContextType: contextType, stream: stream}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (server *server) register(rcvr interface{}, name string, useName bool) error {
|
||||||
|
server.mu.Lock()
|
||||||
|
defer server.mu.Unlock()
|
||||||
|
if server.serviceMap == nil {
|
||||||
|
server.serviceMap = make(map[string]*service)
|
||||||
|
}
|
||||||
|
s := new(service)
|
||||||
|
s.typ = reflect.TypeOf(rcvr)
|
||||||
|
s.rcvr = reflect.ValueOf(rcvr)
|
||||||
|
sname := reflect.Indirect(s.rcvr).Type().Name()
|
||||||
|
if useName {
|
||||||
|
sname = name
|
||||||
|
}
|
||||||
|
if sname == "" {
|
||||||
|
log.Fatal("rpc: no service name for type", s.typ.String())
|
||||||
|
}
|
||||||
|
if !isExported(sname) && !useName {
|
||||||
|
s := "rpc Register: type " + sname + " is not exported"
|
||||||
|
log.Print(s)
|
||||||
|
return errors.New(s)
|
||||||
|
}
|
||||||
|
if _, present := server.serviceMap[sname]; present {
|
||||||
|
return errors.New("rpc: service already defined: " + sname)
|
||||||
|
}
|
||||||
|
s.name = sname
|
||||||
|
s.method = make(map[string]*methodType)
|
||||||
|
|
||||||
|
// Install the methods
|
||||||
|
for m := 0; m < s.typ.NumMethod(); m++ {
|
||||||
|
method := s.typ.Method(m)
|
||||||
|
if mt := prepareMethod(method); mt != nil {
|
||||||
|
s.method[method.Name] = mt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(s.method) == 0 {
|
||||||
|
s := "rpc Register: type " + sname + " has no exported methods of suitable type"
|
||||||
|
log.Print(s)
|
||||||
|
return errors.New(s)
|
||||||
|
}
|
||||||
|
server.serviceMap[s.name] = s
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (server *server) sendResponse(sending *sync.Mutex, req *request, reply interface{}, codec serverCodec, errmsg string, last bool) (err error) {
|
||||||
|
resp := server.getResponse()
|
||||||
|
// Encode the response header
|
||||||
|
resp.ServiceMethod = req.ServiceMethod
|
||||||
|
if errmsg != "" {
|
||||||
|
resp.Error = errmsg
|
||||||
|
reply = invalidRequest
|
||||||
|
}
|
||||||
|
resp.Seq = req.Seq
|
||||||
|
sending.Lock()
|
||||||
|
err = codec.WriteResponse(resp, reply, last)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("rpc: writing response:", err)
|
||||||
|
}
|
||||||
|
sending.Unlock()
|
||||||
|
server.freeResponse(resp)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *service) call(ctx context.Context, server *server, sending *sync.Mutex, mtype *methodType, req *request, argv, replyv reflect.Value, codec serverCodec) {
|
||||||
|
mtype.Lock()
|
||||||
|
mtype.numCalls++
|
||||||
|
mtype.Unlock()
|
||||||
|
function := mtype.method.Func
|
||||||
|
var returnValues []reflect.Value
|
||||||
|
|
||||||
|
if !mtype.stream {
|
||||||
|
|
||||||
|
// Invoke the method, providing a new value for the reply.
|
||||||
|
if mtype.TakesContext() {
|
||||||
|
returnValues = function.Call([]reflect.Value{s.rcvr, mtype.prepareContext(ctx), argv, replyv})
|
||||||
|
} else {
|
||||||
|
returnValues = function.Call([]reflect.Value{s.rcvr, argv, replyv})
|
||||||
|
}
|
||||||
|
|
||||||
|
// The return value for the method is an error.
|
||||||
|
errInter := returnValues[0].Interface()
|
||||||
|
errmsg := ""
|
||||||
|
if errInter != nil {
|
||||||
|
errmsg = errInter.(error).Error()
|
||||||
|
}
|
||||||
|
server.sendResponse(sending, req, replyv.Interface(), codec, errmsg, true)
|
||||||
|
server.freeRequest(req)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// declare a local error to see if we errored out already
|
||||||
|
// keep track of the type, to make sure we return
|
||||||
|
// the same one consistently
|
||||||
|
var lastError error
|
||||||
|
var firstType reflect.Type
|
||||||
|
|
||||||
|
sendReply := func(oneReply interface{}) error {
|
||||||
|
|
||||||
|
// we already triggered an error, we're done
|
||||||
|
if lastError != nil {
|
||||||
|
return lastError
|
||||||
|
}
|
||||||
|
|
||||||
|
// check the oneReply has the right type using reflection
|
||||||
|
typ := reflect.TypeOf(oneReply)
|
||||||
|
if firstType == nil {
|
||||||
|
firstType = typ
|
||||||
|
} else {
|
||||||
|
if firstType != typ {
|
||||||
|
log.Println("passing wrong type to sendReply",
|
||||||
|
firstType, "!=", typ)
|
||||||
|
lastError = errors.New("rpc: passing wrong type to sendReply")
|
||||||
|
return lastError
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lastError = server.sendResponse(sending, req, oneReply, codec, "", false)
|
||||||
|
if lastError != nil {
|
||||||
|
return lastError
|
||||||
|
}
|
||||||
|
|
||||||
|
// we manage to send, we're good
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Invoke the method, providing a new value for the reply.
|
||||||
|
if mtype.TakesContext() {
|
||||||
|
returnValues = function.Call([]reflect.Value{s.rcvr, mtype.prepareContext(ctx), argv, reflect.ValueOf(sendReply)})
|
||||||
|
} else {
|
||||||
|
returnValues = function.Call([]reflect.Value{s.rcvr, argv, reflect.ValueOf(sendReply)})
|
||||||
|
}
|
||||||
|
errInter := returnValues[0].Interface()
|
||||||
|
errmsg := ""
|
||||||
|
if errInter != nil {
|
||||||
|
// the function returned an error, we use that
|
||||||
|
errmsg = errInter.(error).Error()
|
||||||
|
} else if lastError != nil {
|
||||||
|
// we had an error inside sendReply, we use that
|
||||||
|
errmsg = lastError.Error()
|
||||||
|
} else {
|
||||||
|
// no error, we send the special EOS error
|
||||||
|
errmsg = lastStreamResponseError
|
||||||
|
}
|
||||||
|
|
||||||
|
// this is the last packet, we don't do anything with
|
||||||
|
// the error here (well sendStreamResponse will log it
|
||||||
|
// already)
|
||||||
|
server.sendResponse(sending, req, nil, codec, errmsg, true)
|
||||||
|
server.freeRequest(req)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *methodType) prepareContext(ctx context.Context) reflect.Value {
|
||||||
|
if contextv := reflect.ValueOf(ctx); contextv.IsValid() {
|
||||||
|
return contextv
|
||||||
|
}
|
||||||
|
return reflect.Zero(m.ContextType)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (server *server) ServeRequestWithContext(ctx context.Context, codec serverCodec) error {
|
||||||
|
sending := new(sync.Mutex)
|
||||||
|
service, mtype, req, argv, replyv, keepReading, err := server.readRequest(codec)
|
||||||
|
if err != nil {
|
||||||
|
if !keepReading {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// send a response if we actually managed to read a header.
|
||||||
|
if req != nil {
|
||||||
|
server.sendResponse(sending, req, invalidRequest, codec, err.Error(), true)
|
||||||
|
server.freeRequest(req)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
service.call(ctx, server, sending, mtype, req, argv, replyv, codec)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (server *server) getRequest() *request {
|
||||||
|
server.reqLock.Lock()
|
||||||
|
req := server.freeReq
|
||||||
|
if req == nil {
|
||||||
|
req = new(request)
|
||||||
|
} else {
|
||||||
|
server.freeReq = req.next
|
||||||
|
*req = request{}
|
||||||
|
}
|
||||||
|
server.reqLock.Unlock()
|
||||||
|
return req
|
||||||
|
}
|
||||||
|
|
||||||
|
func (server *server) freeRequest(req *request) {
|
||||||
|
server.reqLock.Lock()
|
||||||
|
req.next = server.freeReq
|
||||||
|
server.freeReq = req
|
||||||
|
server.reqLock.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (server *server) getResponse() *response {
|
||||||
|
server.respLock.Lock()
|
||||||
|
resp := server.freeResp
|
||||||
|
if resp == nil {
|
||||||
|
resp = new(response)
|
||||||
|
} else {
|
||||||
|
server.freeResp = resp.next
|
||||||
|
*resp = response{}
|
||||||
|
}
|
||||||
|
server.respLock.Unlock()
|
||||||
|
return resp
|
||||||
|
}
|
||||||
|
|
||||||
|
func (server *server) freeResponse(resp *response) {
|
||||||
|
server.respLock.Lock()
|
||||||
|
resp.next = server.freeResp
|
||||||
|
server.freeResp = resp
|
||||||
|
server.respLock.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (server *server) readRequest(codec serverCodec) (service *service, mtype *methodType, req *request, argv, replyv reflect.Value, keepReading bool, err error) {
|
||||||
|
service, mtype, req, keepReading, err = server.readRequestHeader(codec)
|
||||||
|
if err != nil {
|
||||||
|
if !keepReading {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// discard body
|
||||||
|
codec.ReadRequestBody(nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decode the argument value.
|
||||||
|
argIsValue := false // if true, need to indirect before calling.
|
||||||
|
if mtype.ArgType.Kind() == reflect.Ptr {
|
||||||
|
argv = reflect.New(mtype.ArgType.Elem())
|
||||||
|
} else {
|
||||||
|
argv = reflect.New(mtype.ArgType)
|
||||||
|
argIsValue = true
|
||||||
|
}
|
||||||
|
// argv guaranteed to be a pointer now.
|
||||||
|
if err = codec.ReadRequestBody(argv.Interface()); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if argIsValue {
|
||||||
|
argv = argv.Elem()
|
||||||
|
}
|
||||||
|
|
||||||
|
if !mtype.stream {
|
||||||
|
replyv = reflect.New(mtype.ReplyType.Elem())
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (server *server) readRequestHeader(codec serverCodec) (service *service, mtype *methodType, req *request, keepReading bool, err error) {
|
||||||
|
// Grab the request header.
|
||||||
|
req = server.getRequest()
|
||||||
|
err = codec.ReadRequestHeader(req)
|
||||||
|
if err != nil {
|
||||||
|
req = nil
|
||||||
|
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = errors.New("rpc: server cannot decode request: " + err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// We read the header successfully. If we see an error now,
|
||||||
|
// we can still recover and move on to the next request.
|
||||||
|
keepReading = true
|
||||||
|
|
||||||
|
serviceMethod := strings.Split(req.ServiceMethod, ".")
|
||||||
|
if len(serviceMethod) != 2 {
|
||||||
|
err = errors.New("rpc: service/method request ill-formed: " + req.ServiceMethod)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Look up the request.
|
||||||
|
server.mu.Lock()
|
||||||
|
service = server.serviceMap[serviceMethod[0]]
|
||||||
|
server.mu.Unlock()
|
||||||
|
if service == nil {
|
||||||
|
err = errors.New("rpc: can't find service " + req.ServiceMethod)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
mtype = service.method[serviceMethod[1]]
|
||||||
|
if mtype == nil {
|
||||||
|
err = errors.New("rpc: can't find method " + req.ServiceMethod)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// A serverCodec implements reading of RPC requests and writing of
|
||||||
|
// RPC responses for the server side of an RPC session.
|
||||||
|
// The server calls ReadRequestHeader and ReadRequestBody in pairs
|
||||||
|
// to read requests from the connection, and it calls WriteResponse to
|
||||||
|
// write a response back. The server calls Close when finished with the
|
||||||
|
// connection. ReadRequestBody may be called with a nil
|
||||||
|
// argument to force the body of the request to be read and discarded.
|
||||||
|
type serverCodec interface {
|
||||||
|
ReadRequestHeader(*request) error
|
||||||
|
ReadRequestBody(interface{}) error
|
||||||
|
WriteResponse(*response, interface{}, bool) error
|
||||||
|
|
||||||
|
Close() error
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user