Skip to content

Commit ffa9699

Browse files
grpc: Add client-side timeouts
1 parent 7a5f683 commit ffa9699

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

grpc/client.go

+14-2
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ import (
1919
grpc_retry "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/retry"
2020
)
2121

22+
const (
23+
timeout = time.Minute
24+
)
25+
2226
// Deprecated: Use NewClient instead.
2327
func DialContext(_ context.Context, addr string) (*grpc.ClientConn, error) {
2428
return NewClient(addr)
@@ -44,7 +48,11 @@ func NewClient(addr string) (*grpc.ClientConn, error) {
4448
grpc_retry.StreamClientInterceptor(opts...),
4549
func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
4650
start := time.Now()
47-
cs, err := streamer(prepareClientContext(ctx), desc, cc, method, opts...)
51+
52+
ctx, cancel := context.WithTimeout(prepareClientContext(ctx), timeout)
53+
defer cancel()
54+
55+
cs, err := streamer(ctx, desc, cc, method, opts...)
4856
log.Ctx(ctx).Debug().Str("method", method).
4957
Dur("duration", time.Since(start)).
5058
Str("type", "stream").
@@ -58,7 +66,11 @@ func NewClient(addr string) (*grpc.ClientConn, error) {
5866
grpc_retry.UnaryClientInterceptor(opts...),
5967
func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
6068
start := time.Now()
61-
err := invoker(prepareClientContext(ctx), method, req, reply, cc, opts...)
69+
70+
ctx, cancel := context.WithTimeout(prepareClientContext(ctx), timeout)
71+
defer cancel()
72+
73+
err := invoker(ctx, method, req, reply, cc, opts...)
6274
log.Ctx(ctx).Debug().Str("method", method).
6375
Dur("duration", time.Since(start)).
6476
Str("type", "unary").

0 commit comments

Comments
 (0)