-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
57 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
package conn | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"fmt" | ||
"time" | ||
|
||
"google.golang.org/grpc" | ||
) | ||
|
||
type TimeoutError struct { | ||
wrapped error | ||
} | ||
|
||
func (t *TimeoutError) Error() string { | ||
return fmt.Sprintf("gosdk request timeout: %s", t.wrapped.Error()) | ||
} | ||
|
||
func (t *TimeoutError) Unwrap() error { | ||
return t.wrapped | ||
} | ||
|
||
// UnaryClientTimeoutInterceptor returns a new unary client interceptor that sets a timeout on the request context. | ||
func UnaryClientTimeoutInterceptor(timeout time.Duration) grpc.UnaryClientInterceptor { | ||
return func( | ||
ctx context.Context, | ||
method string, | ||
req, reply any, | ||
cc *grpc.ClientConn, | ||
invoker grpc.UnaryInvoker, | ||
opts ...grpc.CallOption, | ||
) error { | ||
timedCtx, cancel := context.WithTimeout(ctx, timeout) | ||
defer cancel() | ||
err := invoker(timedCtx, method, req, reply, cc, opts...) | ||
if err != nil { | ||
if errors.Is(err, context.DeadlineExceeded) { | ||
select { | ||
case <-ctx.Done(): | ||
return err | ||
default: | ||
return &TimeoutError{wrapped: err} | ||
} | ||
} | ||
// Otherwise, return the original error | ||
return err | ||
} | ||
return nil | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters