github.com/msales/pkg/v3@v3.24.0/grpcx/options.go (about) 1 package grpcx 2 3 import ( 4 "context" 5 "time" 6 7 "github.com/msales/pkg/v3/grpcx/middleware" 8 "github.com/msales/pkg/v3/log" 9 "github.com/msales/pkg/v3/stats" 10 "google.golang.org/grpc" 11 "google.golang.org/grpc/balancer/roundrobin" 12 ) 13 14 // UnaryClientCommonOpts returns commonly options for an unary client. 15 func UnaryClientCommonOpts(ctx context.Context, timeout time.Duration, additional ...grpc.UnaryClientInterceptor) []grpc.DialOption { 16 l, s := getLoggerAndStats(ctx) 17 18 interceptors := []grpc.UnaryClientInterceptor{ 19 middleware.WithUnaryClientLogger(l), 20 middleware.WithUnaryClientStats(s), 21 middleware.WithUnaryClientRecovery(), 22 middleware.WithUnaryClientContextTimeout(timeout), 23 } 24 25 interceptors = append(interceptors, additional...) 26 27 return []grpc.DialOption{ 28 grpc.WithInsecure(), 29 grpc.WithBalancerName(roundrobin.Name), 30 middleware.WithUnaryClientInterceptors(interceptors...), 31 } 32 } 33 34 // UnaryServerCommonOpts returns commonly options for an unary server. 35 func UnaryServerCommonOpts(ctx context.Context, statsTagsFns ...TagsFunc) []grpc.ServerOption { 36 l, s := getLoggerAndStats(ctx) 37 38 return []grpc.ServerOption{ 39 middleware.WithUnaryServerInterceptors( 40 middleware.WithUnaryServerLogger(l), 41 middleware.WithUnaryServerStats(s), 42 middleware.WithUnaryServerRecovery(), 43 ), 44 grpc.StatsHandler( 45 WithRPCStats(s, statsTagsFns...), 46 ), 47 } 48 } 49 50 // StreamServerCommonOpts returns commonly options for a stream server. 51 func StreamServerCommonOpts(ctx context.Context, statsTagsFns ...TagsFunc) []grpc.ServerOption { 52 l, s := getLoggerAndStats(ctx) 53 54 return []grpc.ServerOption{ 55 middleware.WithStreamServerInterceptors( 56 middleware.WithStreamServerLogger(l), 57 middleware.WithStreamServerStats(s), 58 middleware.WithStreamServerRecovery(), 59 ), 60 grpc.StatsHandler( 61 WithRPCStats(s, statsTagsFns...), 62 ), 63 } 64 } 65 66 func getLoggerAndStats(ctx context.Context) (log.Logger, stats.Stats) { 67 l, ok := log.FromContext(ctx) 68 if !ok { 69 l = log.Null 70 } 71 72 s, ok := stats.FromContext(ctx) 73 if !ok { 74 s = stats.Null 75 } 76 77 return l, s 78 }