interceptor

package
v1.3.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 3, 2023 License: MIT Imports: 23 Imported by: 17

README

interceptor

Commonly used grpc client and server-side interceptors.


Example of use

jwt
// grpc server

func getServerOptions() []grpc.ServerOption {
	var options []grpc.ServerOption

	// token authorization
	options = append(options, grpc.UnaryInterceptor(
	    interceptor.UnaryServerJwtAuth(
	        // middleware.WithAuthClaimsName("tokenInfo"), // set the name of the forensic information attached to the ctx, the default is tokenInfo
	        middleware.WithAuthIgnoreMethods( // add a way to ignore token validation
	            "/proto.Account/Register",
	        ),
	    ),
	))

	return options
}

// generate forensic information authorization
func (a *Account) Register(ctx context.Context, req *serverNameV1.RegisterRequest) (*serverNameV1.RegisterReply, error) {
    // ......
	token, err := jwt.GenerateToken(uid)
	// handle err
	authorization = middleware.GetAuthorization(token)
    // ......
}

// the client must pass in the authentication information via the context when calling the method, and the key name must be authorization
func getUser(client serverNameV1.AccountClient, req *serverNameV1.RegisterReply) error {
	md := metadata.Pairs("authorization", req.Authorization)
	ctx := metadata.NewOutgoingContext(context.Background(), md)

	resp, err := client.GetUser(ctx, &serverNameV1.GetUserRequest{Id: req.Id})
	if err != nil {
		return err
	}

	fmt.Println("get user success", resp)
	return nil
}

logging
var logger *zap.Logger

func getServerOptions() []grpc.ServerOption {
	var options []grpc.ServerOption

	// log setting, which prints client disconnection information by default, example https://pkg.go.dev/github.com/grpc-ecosystem/go-grpc-middleware/logging/zap
	options = append(options, grpc_middleware.WithUnaryServerChain(
		interceptor.UnaryServerZapLogging(
			logger.Get(), // zap
			// middleware.WithLogFields(map[string]interface{}{"serverName": "userExample"}), // additional print fields
			middleware.WithLogIgnoreMethods("/proto.userExampleService/GetByID"), // ignore the specified method print, you can specify more than one
		),
	))

	return options
}

recovery
func getServerOptions() []grpc.ServerOption {
	var options []grpc.ServerOption

	recoveryOption := grpc_middleware.WithUnaryServerChain(
		interceptor.UnaryServerRecovery(),
	)
	options = append(options, recoveryOption)

	return options
}

retry
func getDialOptions() []grpc.DialOption {
	var options []grpc.DialOption

	// use insecure transfer
	options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

	// retry
	option := grpc.WithUnaryInterceptor(
		grpc_middleware.ChainUnaryClient(
			interceptor.UnaryClientRetry(
                //middleware.WithRetryTimes(5), // modify the default number of retries to 3 by default
                //middleware.WithRetryInterval(100*time.Millisecond), // modify the default retry interval, default 50 milliseconds
                //middleware.WithRetryErrCodes(), // add trigger retry error code, default is codes.Internal, codes.DeadlineExceeded, codes.Unavailable
			),
		),
	)
	options = append(options, option)

	return options
}

rate limiter
func getDialOptions() []grpc.DialOption {
	var options []grpc.DialOption

	// use insecure transfer
	options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

	// circuit breaker
	option := grpc.WithUnaryInterceptor(
		grpc_middleware.ChainUnaryClient(
			interceptor.UnaryRateLimit(),
		),
	)
	options = append(options, option)

	return options
}

Circuit Breaker
func getDialOptions() []grpc.DialOption {
	var options []grpc.DialOption

	// use insecure transfer
	options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

	// circuit breaker
	option := grpc.WithUnaryInterceptor(
		grpc_middleware.ChainUnaryClient(
			interceptor.UnaryClientCircuitBreaker(),
		),
	)
	options = append(options, option)

	return options
}

timeout
func getDialOptions() []grpc.DialOption {
	var options []grpc.DialOption

	// use insecure transfer
	options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

	// timeout
	option := grpc.WithUnaryInterceptor(
		grpc_middleware.ChainUnaryClient(
			middleware.ContextTimeout(time.Second), // set timeout
		),
	)
	options = append(options, option)

	return options
}

tracing
// initialize tracing
func InitTrace(serviceName string) {
	exporter, err := tracer.NewJaegerAgentExporter("192.168.3.37", "6831")
	if err != nil {
		panic(err)
	}

	resource := tracer.NewResource(
		tracer.WithServiceName(serviceName),
		tracer.WithEnvironment("dev"),
		tracer.WithServiceVersion("demo"),
	)

	tracer.Init(exporter, resource) // collect all by default
}

// set up trace on the client side
func getDialOptions() []grpc.DialOption {
	var options []grpc.DialOption

	// use insecure transfer
	options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

	// use tracing
	options = append(options, grpc.WithUnaryInterceptor(
		interceptor.UnaryClientTracing(),
	))

	return options
}

// set up trace on the server side
func getServerOptions() []grpc.ServerOption {
	var options []grpc.ServerOption

	// use tracing
	options = append(options, grpc.UnaryInterceptor(
		interceptor.UnaryServerTracing(),
	))

	return options
}

// if necessary, you can create a span in the program
func SpanDemo(serviceName string, spanName string, ctx context.Context) {
	_, span := otel.Tracer(serviceName).Start(
		ctx, spanName,
		trace.WithAttributes(attribute.String(spanName, time.Now().String())), // customised attributes
	)
	defer span.End()

	// ......
}

metrics

example metrics.


Request id

(1) server side

func getServerOptions() []grpc.ServerOption {
	var options []grpc.ServerOption

	recoveryOption := grpc_middleware.WithUnaryServerChain(
		interceptor.UnaryServerRequestID(),
	)
	options = append(options, recoveryOption)

	return options
}

(2) client side

func getDialOptions() []grpc.DialOption {
	var options []grpc.DialOption

	// use insecure transfer
	options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

	option := grpc.WithUnaryInterceptor(
		grpc_middleware.ChainUnaryClient(
			interceptor.UnaryClientRequestID(),
		),
	)
	options = append(options, option)

	return options
}

Documentation

Index

Constants

View Source
const (
	// ContextRequestIDKey context request id for context
	ContextRequestIDKey = "request_id"
)

Variables

View Source
var ErrLimitExceed = rl.ErrLimitExceed

ErrLimitExceed is returned when the rate limiter is triggered and the request is rejected due to limit exceeded.

ErrNotAllowed error not allowed.

Functions

func ClientCtxRequestID added in v1.3.2

func ClientCtxRequestID(ctx context.Context) string

ClientCtxRequestID get request id from rpc client context.Context

func ClientCtxRequestIDField added in v1.3.2

func ClientCtxRequestIDField(ctx context.Context) zap.Field

ClientCtxRequestIDField get request id field from rpc client context.Context

func GetAuthCtxKey

func GetAuthCtxKey() string

GetAuthCtxKey get the name of Claims

func GetAuthorization

func GetAuthorization(token string) string

GetAuthorization combining tokens into authentication information

func JwtVerify

func JwtVerify(ctx context.Context) (context.Context, error)

JwtVerify get authorization from context to verify legitimacy, authorization composition format: authScheme token

func ServerCtxRequestID added in v1.3.2

func ServerCtxRequestID(ctx context.Context) string

ServerCtxRequestID get request id from rpc server context.Context

func ServerCtxRequestIDField added in v1.3.2

func ServerCtxRequestIDField(ctx context.Context) zap.Field

ServerCtxRequestIDField get request id field from rpc server context.Context

func SteamClientCircuitBreaker

func SteamClientCircuitBreaker(opts ...CircuitBreakerOption) grpc.StreamClientInterceptor

SteamClientCircuitBreaker client-side stream circuit breaker interceptor

func SteamServerCircuitBreaker

func SteamServerCircuitBreaker(opts ...CircuitBreakerOption) grpc.StreamServerInterceptor

SteamServerCircuitBreaker server-side stream circuit breaker interceptor

func StreamClientLog

func StreamClientLog(logger *zap.Logger) grpc.StreamClientInterceptor

StreamClientLog client log stream interceptor

func StreamClientLog2 added in v1.3.2

func StreamClientLog2(logger *zap.Logger, opts ...grpc_zap.Option) grpc.StreamClientInterceptor

StreamClientLog2 client log stream interceptor

func StreamClientMetrics

func StreamClientMetrics() grpc.StreamClientInterceptor

StreamClientMetrics client-side metrics stream interceptor

func StreamClientRequestID added in v1.3.2

func StreamClientRequestID() grpc.StreamClientInterceptor

StreamClientRequestID client request id stream interceptor

func StreamClientRetry

func StreamClientRetry(opts ...RetryOption) grpc.StreamClientInterceptor

StreamClientRetry client-side retry stream interceptor

func StreamClientTimeout added in v1.2.0

func StreamClientTimeout(d time.Duration) grpc.StreamClientInterceptor

StreamClientTimeout server-side timeout interceptor

func StreamClientTracing

func StreamClientTracing() grpc.StreamClientInterceptor

StreamClientTracing client-side tracing stream interceptor

func StreamServerJwtAuth

func StreamServerJwtAuth(opts ...AuthOption) grpc.StreamServerInterceptor

StreamServerJwtAuth jwt stream interceptor

func StreamServerLog

func StreamServerLog(logger *zap.Logger, opts ...LogOption) grpc.StreamServerInterceptor

StreamServerLog Server-side log stream interceptor

func StreamServerLog2 added in v1.3.2

func StreamServerLog2(logger *zap.Logger, opts ...LogOption) grpc.StreamServerInterceptor

StreamServerLog2 Server-side log stream interceptor

func StreamServerMetrics

func StreamServerMetrics(opts ...metrics.Option) grpc.StreamServerInterceptor

StreamServerMetrics server-side metrics stream interceptor

func StreamServerRateLimit

func StreamServerRateLimit(opts ...RatelimitOption) grpc.StreamServerInterceptor

StreamServerRateLimit server-side stream circuit breaker interceptor

func StreamServerRecovery

func StreamServerRecovery() grpc.StreamServerInterceptor

StreamServerRecovery recovery stream interceptor

func StreamServerRequestID added in v1.3.2

func StreamServerRequestID() grpc.StreamServerInterceptor

StreamServerRequestID server-side request id stream interceptor

func StreamServerTracing

func StreamServerTracing() grpc.StreamServerInterceptor

StreamServerTracing server-side tracing stream interceptor

func UnaryClientCircuitBreaker

func UnaryClientCircuitBreaker(opts ...CircuitBreakerOption) grpc.UnaryClientInterceptor

UnaryClientCircuitBreaker client-side unary circuit breaker interceptor

func UnaryClientLog

func UnaryClientLog(logger *zap.Logger) grpc.UnaryClientInterceptor

UnaryClientLog client log unary interceptor

func UnaryClientLog2 added in v1.3.2

func UnaryClientLog2(logger *zap.Logger, opts ...grpc_zap.Option) grpc.UnaryClientInterceptor

UnaryClientLog2 client log unary interceptor

func UnaryClientMetrics

func UnaryClientMetrics() grpc.UnaryClientInterceptor

UnaryClientMetrics client-side metrics unary interceptor

func UnaryClientRequestID added in v1.3.2

func UnaryClientRequestID() grpc.UnaryClientInterceptor

UnaryClientRequestID client-side request_id unary interceptor

func UnaryClientRetry

func UnaryClientRetry(opts ...RetryOption) grpc.UnaryClientInterceptor

UnaryClientRetry client-side retry unary interceptor

func UnaryClientTimeout added in v1.2.0

func UnaryClientTimeout(d time.Duration) grpc.UnaryClientInterceptor

UnaryClientTimeout client-side timeout unary interceptor

func UnaryClientTracing

func UnaryClientTracing() grpc.UnaryClientInterceptor

UnaryClientTracing client-side tracing unary interceptor

func UnaryServerCircuitBreaker

func UnaryServerCircuitBreaker(opts ...CircuitBreakerOption) grpc.UnaryServerInterceptor

UnaryServerCircuitBreaker server-side unary circuit breaker interceptor

func UnaryServerJwtAuth

func UnaryServerJwtAuth(opts ...AuthOption) grpc.UnaryServerInterceptor

UnaryServerJwtAuth jwt unary interceptor

func UnaryServerLog

func UnaryServerLog(logger *zap.Logger, opts ...LogOption) grpc.UnaryServerInterceptor

UnaryServerLog server-side log unary interceptor

func UnaryServerLog2 added in v1.3.2

func UnaryServerLog2(logger *zap.Logger, opts ...LogOption) grpc.UnaryServerInterceptor

UnaryServerLog2 server-side log unary interceptor

func UnaryServerMetrics

func UnaryServerMetrics(opts ...metrics.Option) grpc.UnaryServerInterceptor

UnaryServerMetrics server-side metrics unary interceptor

func UnaryServerRateLimit

func UnaryServerRateLimit(opts ...RatelimitOption) grpc.UnaryServerInterceptor

UnaryServerRateLimit server-side unary circuit breaker interceptor

func UnaryServerRecovery

func UnaryServerRecovery() grpc.UnaryServerInterceptor

UnaryServerRecovery recovery unary interceptor

func UnaryServerRequestID added in v1.3.2

func UnaryServerRequestID() grpc.UnaryServerInterceptor

UnaryServerRequestID server-side request_id unary interceptor

func UnaryServerTracing

func UnaryServerTracing() grpc.UnaryServerInterceptor

UnaryServerTracing server-side tracing unary interceptor

Types

type AuthOption

type AuthOption func(*AuthOptions)

AuthOption setting the Authentication Field

func WithAuthClaimsName

func WithAuthClaimsName(claimsName string) AuthOption

WithAuthClaimsName set the key name of the information in ctx for authentication

func WithAuthIgnoreMethods

func WithAuthIgnoreMethods(fullMethodNames ...string) AuthOption

WithAuthIgnoreMethods ways to ignore forensics fullMethodName format: /packageName.serviceName/methodName, example /api.userExample.v1.userExampleService/GetByID

func WithAuthScheme

func WithAuthScheme(scheme string) AuthOption

WithAuthScheme set the message prefix for authentication

type AuthOptions

type AuthOptions struct {
	// contains filtered or unexported fields
}

AuthOptions settings

type CircuitBreakerOption

type CircuitBreakerOption func(*circuitBreakerOptions)

CircuitBreakerOption set the circuit breaker circuitBreakerOptions.

func WithGroup

func WithGroup(g *group.Group) CircuitBreakerOption

WithGroup with circuit breaker group. NOTE: implements generics circuitbreaker.CircuitBreaker

type LogOption

type LogOption func(*logOptions)

LogOption log settings

func WithLogFields

func WithLogFields(kvs map[string]interface{}) LogOption

WithLogFields adding a custom print field

func WithLogIgnoreMethods

func WithLogIgnoreMethods(fullMethodNames ...string) LogOption

WithLogIgnoreMethods ignore printing methods fullMethodName format: /packageName.serviceName/methodName, example /api.userExample.v1.userExampleService/GetByID

type RatelimitOption

type RatelimitOption func(*ratelimitOptions)

RatelimitOption set the rate limits ratelimitOptions.

func WithBucket

func WithBucket(b int) RatelimitOption

WithBucket with bucket size.

func WithCPUQuota

func WithCPUQuota(quota float64) RatelimitOption

WithCPUQuota with real cpu quota(if it can not collect from process correct);

func WithCPUThreshold

func WithCPUThreshold(threshold int64) RatelimitOption

WithCPUThreshold with cpu threshold

func WithWindow

func WithWindow(d time.Duration) RatelimitOption

WithWindow with window size.

type RetryOption

type RetryOption func(*retryOptions)

RetryOption set the retry retryOptions.

func WithRetryErrCodes

func WithRetryErrCodes(errCodes ...codes.Code) RetryOption

WithRetryErrCodes set the trigger retry error code

func WithRetryInterval

func WithRetryInterval(t time.Duration) RetryOption

WithRetryInterval set the retry interval from 1 ms to 10 seconds

func WithRetryTimes

func WithRetryTimes(n uint) RetryOption

WithRetryTimes set number of retries, max 10

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL