micro/proxy/grpc/grpc.go

247 lines
5.5 KiB
Go
Raw Normal View History

2020-08-09 18:47:00 +03:00
// Package grpc is a grpc proxy built for the go-micro/server
2019-06-03 20:44:43 +03:00
package grpc
import (
"context"
"io"
2020-08-09 18:57:34 +03:00
"strings"
2019-06-03 20:44:43 +03:00
"github.com/micro/go-micro/v3/client"
2020-08-09 18:47:00 +03:00
grpcc "github.com/micro/go-micro/v3/client/grpc"
"github.com/micro/go-micro/v3/codec"
2020-08-09 18:47:00 +03:00
"github.com/micro/go-micro/v3/codec/bytes"
"github.com/micro/go-micro/v3/errors"
"github.com/micro/go-micro/v3/logger"
"github.com/micro/go-micro/v3/proxy"
"github.com/micro/go-micro/v3/server"
2020-08-09 18:47:00 +03:00
"google.golang.org/grpc"
2019-06-03 20:44:43 +03:00
)
2020-08-09 18:47:00 +03:00
// Proxy will transparently proxy requests to an endpoint.
// If no endpoint is specified it will call a service using the client.
type Proxy struct {
2020-08-09 18:47:00 +03:00
// embed options
2019-12-16 17:55:47 +03:00
options proxy.Options
2019-06-03 20:44:43 +03:00
2020-08-09 18:47:00 +03:00
// The client to use for outbound requests in the local network
2019-06-03 20:44:43 +03:00
Client client.Client
2020-08-09 18:57:34 +03:00
// Endpoint to route all calls to
Endpoint string
2019-06-03 20:44:43 +03:00
}
// read client request and write to server
func readLoop(r server.Request, s client.Stream) error {
// request to backend server
req := s.Request()
for {
// get data from client
// no need to decode it
body, err := r.Read()
if err == io.EOF {
return nil
}
2020-08-09 18:47:00 +03:00
2019-06-03 20:44:43 +03:00
if err != nil {
return err
}
// get the header from client
hdr := r.Header()
msg := &codec.Message{
Type: codec.Request,
Header: hdr,
Body: body,
}
2020-08-09 18:47:00 +03:00
2019-06-03 20:44:43 +03:00
// write the raw request
err = req.Codec().Write(msg, nil)
if err == io.EOF {
return nil
} else if err != nil {
return err
}
}
}
// ProcessMessage acts as a message exchange and forwards messages to ongoing topics
// TODO: should we look at p.Endpoint and only send to the local endpoint? probably
func (p *Proxy) ProcessMessage(ctx context.Context, msg server.Message) error {
// TODO: check that we're not broadcast storming by sending to the same topic
// that we're actually subscribed to
2020-08-09 18:47:00 +03:00
if logger.V(logger.TraceLevel, logger.DefaultLogger) {
logger.Tracef("Proxy received message for %s", msg.Topic())
}
// directly publish to the local client
return p.Client.Publish(ctx, msg)
2019-08-23 16:05:11 +03:00
}
2020-08-09 18:47:00 +03:00
// ServeRequest honours the server.Router interface
func (p *Proxy) ServeRequest(ctx context.Context, req server.Request, rsp server.Response) error {
2020-08-09 18:47:00 +03:00
// service name to call
service := req.Service()
// endpoint to call
endpoint := req.Endpoint()
if len(service) == 0 {
return errors.BadRequest("go.micro.proxy", "service name is blank")
2019-06-03 20:44:43 +03:00
}
2020-08-09 18:47:00 +03:00
if logger.V(logger.TraceLevel, logger.DefaultLogger) {
logger.Tracef("Proxy received request for %s %s", service, endpoint)
}
2019-06-03 20:44:43 +03:00
2020-08-09 18:57:34 +03:00
// no retries with the proxy
2020-08-09 18:47:00 +03:00
opts := []client.CallOption{
client.WithRetries(0),
}
2019-06-03 20:44:43 +03:00
2020-08-09 18:57:34 +03:00
// call a specific backend
if len(p.Endpoint) > 0 {
// address:port
if parts := strings.Split(p.Endpoint, ":"); len(parts) > 1 {
opts = append(opts, client.WithAddress(p.Endpoint))
// use as service name
} else {
service = p.Endpoint
}
}
2020-08-09 18:47:00 +03:00
// serve the normal way
return p.serveRequest(ctx, p.Client, service, endpoint, req, rsp, opts...)
}
func (p *Proxy) serveRequest(ctx context.Context, link client.Client, service, endpoint string, req server.Request, rsp server.Response, opts ...client.CallOption) error {
// read initial request
body, err := req.Read()
if err != nil {
return err
2019-06-03 20:44:43 +03:00
}
// create new request with raw bytes body
2020-08-09 18:47:00 +03:00
creq := link.NewRequest(service, endpoint, &bytes.Frame{Data: body}, client.WithContentType(req.ContentType()))
// not a stream so make a client.Call request
if !req.Stream() {
crsp := new(bytes.Frame)
// make a call to the backend
if err := link.Call(ctx, creq, crsp, opts...); err != nil {
return err
}
// write the response
if err := rsp.Write(crsp.Data); err != nil {
return err
}
return nil
}
// new context with cancel
ctx, cancel := context.WithCancel(ctx)
2019-06-03 20:44:43 +03:00
// create new stream
2020-08-09 18:47:00 +03:00
stream, err := link.Stream(ctx, creq, opts...)
2019-06-03 20:44:43 +03:00
if err != nil {
return err
}
defer stream.Close()
2020-08-09 18:47:00 +03:00
// with a grpc stream we have to refire the initial request
// client request to start the server side
// get the header from client
msg := &codec.Message{
Type: codec.Request,
Header: req.Header(),
Body: body,
}
// write the raw request
err = stream.Request().Codec().Write(msg, nil)
if err == io.EOF {
return nil
} else if err != nil {
return err
}
// create client request read loop if streaming
go func() {
err := readLoop(req, stream)
if err != nil && err != io.EOF {
// cancel the context
cancel()
}
}()
2019-06-03 20:44:43 +03:00
// get raw response
resp := stream.Response()
// create server response write loop
for {
// read backend response body
body, err := resp.Read()
2020-08-09 18:47:00 +03:00
if err != nil {
// when we're done if its a grpc stream we have to set the trailer
if cc, ok := stream.(grpc.ClientStream); ok {
if ss, ok := resp.Codec().(grpc.ServerStream); ok {
ss.SetTrailer(cc.Trailer())
}
}
}
2019-06-03 20:44:43 +03:00
if err == io.EOF {
return nil
} else if err != nil {
return err
}
// read backend response header
hdr := resp.Header()
// write raw response header to client
rsp.WriteHeader(hdr)
// write raw response body to client
err = rsp.Write(body)
if err == io.EOF {
return nil
} else if err != nil {
return err
}
}
}
2019-12-16 18:18:20 +03:00
func (p *Proxy) String() string {
2019-12-16 20:36:47 +03:00
return "grpc"
2019-12-16 18:18:20 +03:00
}
2020-08-09 18:47:00 +03:00
// NewProxy returns a new proxy which will route based on mucp headers
2019-12-16 17:55:47 +03:00
func NewProxy(opts ...proxy.Option) proxy.Proxy {
var options proxy.Options
2020-08-09 18:47:00 +03:00
2019-12-16 17:55:47 +03:00
for _, o := range opts {
o(&options)
}
2020-08-09 18:47:00 +03:00
// create a new grpc proxy
2019-12-16 17:55:47 +03:00
p := new(Proxy)
2020-08-09 18:47:00 +03:00
p.options = options
2020-08-09 18:47:00 +03:00
// set the client
p.Client = options.Client
2020-08-09 18:57:34 +03:00
// set the endpoint
p.Endpoint = options.Endpoint
2020-08-09 18:47:00 +03:00
// set the default client
if p.Client == nil {
p.Client = grpcc.NewClient()
2019-06-03 20:44:43 +03:00
}
2020-08-09 18:47:00 +03:00
return p
2019-06-03 20:44:43 +03:00
}