ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

gRPC 拦截器简要说明及示例

2021-06-19 23:29:44  阅读:212  来源: 互联网

标签:拦截器 return nil err 示例 gRPC grpc func error


一、官方文档说明

Interceptor

gRPC provides simple APIs to implement and install interceptors on a per ClientConn/Server basis. Interceptor intercepts the execution of each RPC call. Users can use interceptors to do logging, authentication/authorization, metrics collection, and many other functionality that can be shared across RPCs.

Explanation

In gRPC, interceptors can be categorized into two kinds in terms of the type of RPC calls they intercept. The first one is the unary interceptor, which intercepts unary RPC calls. And the other is the stream interceptor which deals with streaming RPC calls. See here for explanation about unary RPCs and streaming RPCs. Each of client and server has their own types of unary and stream interceptors. Thus, there are in total four different types of interceptors in gRPC.

Client-side

Unary Interceptor

UnaryClientInterceptor is the type for client-side unary interceptor. It is essentially a function type with signature: func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error. An implementation of a unary interceptor can usually be divided into three parts: pre-processing, invoking RPC method, and post-processing.

For pre-processing, users can get info about the current RPC call by examining the args passed in, such as RPC context, method string, request to be sent, and CallOptions configured. With the info, users can even modify the RPC call. For instance, in the example, we examine the list of CallOptions and see if call credential has been configured. If not, configure it to use oauth2 with token "some-secret-token" as fallback. In our example, we intentionally omit configuring the per RPC credential to resort to fallback.

After pre-processing is done, use can invoke the RPC call by calling the invoker.

Once the invoker returns the reply and error, user can do post-processing of the RPC call. Usually, it's about dealing with the returned reply and error. In the example, we log the RPC timing and error info.

To install a unary interceptor on a ClientConn, configure Dial with DialOption WithUnaryInterceptor.

Stream Interceptor

StreamClientInterceptor is the type for client-side stream interceptor. It is a function type with signature: func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error). An implementation of a stream interceptor usually include pre-processing, and stream operation interception.

For pre-processing, it's similar to unary interceptor.

However, rather than doing the RPC method invocation and post-processing afterwards, stream interceptor intercepts the users' operation on the stream. First, the interceptor calls the passed-in streamer to get a ClientStream, and then wraps around the ClientStream and overloading its methods with intercepting logic. Finally, interceptors returns the wrapped ClientStream to user to operate on.

In the example, we define a new struct wrappedStream, which is embedded with a ClientStream. Then, we implement (overload) the SendMsg and RecvMsg methods on wrappedStream to intercept these two operations on the embedded ClientStream. In the example, we log the message type info and time info for interception purpose.

To install the stream interceptor for a ClientConn, configure Dial with DialOption WithStreamInterceptor.

Server-side

Server side interceptor is similar to client side, though with slightly different provided info.

Unary Interceptor

UnaryServerInterceptor is the type for server-side unary interceptor. It is a function type with signature: func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (resp interface{}, err error).

Refer to client-side unary interceptor section for detailed implementation explanation.

To install the unary interceptor for a Server, configure NewServer with ServerOption UnaryInterceptor.

Stream Interceptor

StreamServerInterceptor is the type for server-side stream interceptor. It is a function type with signature: func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error.

Refer to client-side stream interceptor section for detailed implementation explanation.

To install the stream interceptor for a Server, configure NewServer with ServerOption StreamInterceptor.

二、示例

Server端:

package main

import (
	"context"
	"flag"
	"fmt"
	"happy-go/microservice/grpc/data"
	pb "happy-go/microservice/grpc/features/proto/echo"
	"io"
	"log"
	"net"
	"strings"
	"time"

	"google.golang.org/grpc/credentials"

	"google.golang.org/grpc/metadata"

	"google.golang.org/grpc"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

var (
	port = flag.Int("port", 50051, "the port to serve on")

	errMissingMetadata = status.Errorf(codes.InvalidArgument, "missing metadata")
	errInvalidToken    = status.Errorf(codes.Unauthenticated, "invalid token")
)

//logger is to mock a sophisticated logging system.To simplify the example,we just print out the content.
func logger(format string, a ...interface{}) {
	fmt.Printf("LOG:\t"+format+"\n", a...)
}

type server struct {
	pb.UnimplementedEchoServer
}

func (s *server) UnaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) {
	fmt.Printf("unary echoing message %q\n", in.Message)
	return &pb.EchoResponse{Message: in.Message}, nil
}

func (s *server) BidirectionalStreamingEcho(stream pb.Echo_BidirectionalStreamingEchoServer) error {
	for {
		in, err := stream.Recv()
		if err != nil {
			if err == io.EOF {
				return nil
			}
			fmt.Printf("server:error receiving from stream: %v\n", err)
			return err
		}
		fmt.Printf("bidi echoing message %q\n", in.Message)
		stream.Send(&pb.EchoResponse{Message: in.Message})
	}
}

// valid validates the authorization
func valid(authorization []string) bool {
	if len(authorization) < 1 {
		return false
	}
	token := strings.TrimPrefix(authorization[0], "Bearer ")
	//Perform the token validation here.For the sake of this example,the code
	//here forgoes any of usual OAuth2 token validation and instead checks for
	// for token matching an arbitrary string.
	return token == "some-secret-token"
}

func unaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
	// authentication (token verification)
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return nil, errInvalidToken
	}
	if !valid(md["authorization"]) {
		return nil, errInvalidToken
	}
	m, err := handler(ctx, req)
	if err != nil {
		logger("RPC failed with error %v", err)
	}
	return m, err
}

// wrappedStream wraps around the embedded grpc.ServerStream,and intercepts the RecvMsg and SendMsg method call.
// SendMsg method call.
type wrappedStream struct {
	grpc.ServerStream
}

func (w *wrappedStream) RecvMsg(m interface{}) error {
	logger("Receive a message (Type: %T) at %s", m, time.Now().Format(time.RFC3339))
	return w.ServerStream.RecvMsg(m)
}

func (w *wrappedStream) SendMsg(m interface{}) error {
	logger("Send a message (Type: %T) at %v", m, time.Now().Format(time.RFC3339))
	return w.ServerStream.SendMsg(m)
}

func newWrappedStream(s grpc.ServerStream) grpc.ServerStream {
	return &wrappedStream{s}
}

func streamInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
	// authentication (token verification)
	md, ok := metadata.FromIncomingContext(ss.Context())
	if !ok {
		return errMissingMetadata
	}
	if !valid(md["authorization"]) {
		return errInvalidToken
	}

	err := handler(srv, newWrappedStream(ss))
	if err != nil {
		logger("RPC failed with error %v", err)
	}
	return err
}

func main() {
	flag.Parse()

	lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}

	// Create tls based credential
	creds, err := credentials.NewServerTLSFromFile(data.Path("x509/server_cert.pem"), data.Path("x509/server_key.pem"))
	if err != nil {
		log.Fatalf("failed to create credentials: %v", err)
	}

	s := grpc.NewServer(grpc.Creds(creds), grpc.UnaryInterceptor(unaryInterceptor), grpc.StreamInterceptor(streamInterceptor))

	// Register EchoServer on the server.
	pb.RegisterEchoServer(s, &server{})

	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to server: %v", err)
	}
}

client端:

package main

import (
	"context"
	"flag"
	"fmt"
	"happy-go/microservice/grpc/data"
	"io"
	"log"
	"time"

	"google.golang.org/grpc/credentials"

	"golang.org/x/oauth2"
	"google.golang.org/grpc/credentials/oauth"

	"google.golang.org/grpc"

	ecpb "happy-go/microservice/grpc/features/proto/echo"
)

var addr = flag.String("addr", "localhost:50051", "the address to connect to")

const fallbackToken = "some-secret-token"

// logger is to mock a sophisticated logging system.To simplify the example,we just print out the content
func logger(format string, a ...interface{}) {
	fmt.Printf("LOG:\t"+format+"\n", a...)
}

func unaryInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
	var credsConfigured bool
	for _, o := range opts {
		_, ok := o.(grpc.PerRPCCredsCallOption)
		if ok {
			credsConfigured = true
			break
		}
	}
	if !credsConfigured {
		opts = append(opts, grpc.PerRPCCredentials(oauth.NewOauthAccess(&oauth2.Token{
			AccessToken: fallbackToken,
		})))
	}
	start := time.Now()
	err := invoker(ctx, method, req, reply, cc, opts...)
	end := time.Now()
	logger("RPC: %s,start time: %s,end time: %s,err: %v", method, start.Format("Basic"), end.Format(time.RFC3339), err)
	return err
}

func streamInterceptor(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
	var credsConfigured bool
	for _, o := range opts {
		_, ok := o.(*grpc.PerRPCCredsCallOption)
		if ok {
			credsConfigured = true
			break
		}
	}
	if !credsConfigured {
		opts = append(opts, grpc.PerRPCCredentials(oauth.NewOauthAccess(&oauth2.Token{
			AccessToken: fallbackToken,
		})))
	}
	s, err := streamer(ctx, desc, cc, method, opts...)
	if err != nil {
		return nil, err
	}
	return newWrappedStream(s), nil
}

//UnaryEcho(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (*EchoResponse, error)
func callUnaryEcho(client ecpb.EchoClient, message string) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	resp, err := client.UnaryEcho(ctx, &ecpb.EchoRequest{Message: message})
	if err != nil {
		log.Fatalf("client.UnaryEcho(_) = _,%v: ", err)
	}
	fmt.Println("UnaryEcho: ", resp.Message)
}

//BidirectionalStreamingEcho(ctx context.Context, opts ...grpc.CallOption) (Echo_BidirectionalStreamingEchoClient, error)
func callBidiStreamingEcho(client ecpb.EchoClient) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	c, err := client.BidirectionalStreamingEcho(ctx)
	if err != nil {
		return
	}
	for i := 0; i < 5; i++ {
		if err := c.Send(&ecpb.EchoRequest{Message: fmt.Sprintf("Request %d", i+1)}); err != nil {
			log.Fatalf("failed to send request due to error: %v", err)
		}
	}
	c.CloseSend()
	for {
		resp, err := c.Recv()
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Fatalf("failed to receive response due to error: %v", err)
		}
		fmt.Println("BidiStreaming Echo: ", resp.Message)
	}
}

// wrappedStream wraps around the embedded grpc.ClientStream,and intercepts the RecvMsg and
// SendMsg method call.
type wrappedStream struct {
	grpc.ClientStream
}

func newWrappedStream(s grpc.ClientStream) grpc.ClientStream {
	return &wrappedStream{s}
}
func (w *wrappedStream) RecvMsg(m interface{}) error {
	logger("Receive a message (Type: %T) at %v", m, time.Now().Format(time.RFC3339))
	return w.ClientStream.RecvMsg(m)
}

func (w *wrappedStream) SendMsg(m interface{}) error {
	logger("Send a message (Type: %T) at %v", m, time.Now().Format(time.RFC3339))
	return w.ClientStream.SendMsg(m)
}
func main() {
	flag.Parse()

	// Create tls based credential
	creds, err := credentials.NewClientTLSFromFile(data.Path("x509/ca_cert.pem"), "x.test.example.com")
	if err != nil {
		log.Fatalf("failed to create credentials: %v", err)
	}

	// set up a connection to the server
	conn, err := grpc.Dial(*addr, grpc.WithTransportCredentials(creds), grpc.WithUnaryInterceptor(unaryInterceptor), grpc.WithStreamInterceptor(streamInterceptor), grpc.WithBlock())
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()

	// Make a echo client and send RPCs.
	rgc := ecpb.NewEchoClient(conn)
	callUnaryEcho(rgc, "hello world")
	callBidiStreamingEcho(rgc)
}

 

标签:拦截器,return,nil,err,示例,gRPC,grpc,func,error
来源: https://blog.csdn.net/hero_java/article/details/118060674

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有