From 6809554b76842eda0b964ce477d56ac33c8fb433 Mon Sep 17 00:00:00 2001 From: Andrenerd Date: Fri, 16 Apr 2021 23:52:32 +0200 Subject: [PATCH] set timeout for grpc requests --- .../0chain.net/blobbercore/handler/grpchandler.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/code/go/0chain.net/blobbercore/handler/grpchandler.go b/code/go/0chain.net/blobbercore/handler/grpchandler.go index 8346f5bc4..53e6a2f22 100644 --- a/code/go/0chain.net/blobbercore/handler/grpchandler.go +++ b/code/go/0chain.net/blobbercore/handler/grpchandler.go @@ -1,6 +1,7 @@ package handler import ( + "time" "context" "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap" @@ -28,6 +29,10 @@ type blobberGRPCService struct { blobbergrpc.UnimplementedBlobberServer } +const ( + TIMEOUT_SECONDS = 10 // to set deadline for requests +) + func unaryDatabaseTransactionInjector() grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { logger := ctxzap.Extract(ctx) @@ -52,6 +57,14 @@ func unaryDatabaseTransactionInjector() grpc.UnaryServerInterceptor { } } +func unaryTimeoutInterceptor() grpc.UnaryServerInterceptor { + return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + deadline := time.Now().Add(time.Duration(TIMEOUT_SECONDS * time.Second)) + ctx, _ = context.WithDeadline(ctx, deadline) + return handler(ctx, req) + } +} + func NewServerWithMiddlewares() *grpc.Server { return grpc.NewServer( grpc.ChainStreamInterceptor( @@ -62,6 +75,7 @@ func NewServerWithMiddlewares() *grpc.Server { grpc_zap.UnaryServerInterceptor(logging.Logger), grpc_recovery.UnaryServerInterceptor(), unaryDatabaseTransactionInjector(), + unaryTimeoutInterceptor(), // should always be the lastest, to be "innermost" ), ) }