-
Notifications
You must be signed in to change notification settings - Fork 837
/
Copy pathtimeout.go
73 lines (68 loc) · 2.42 KB
/
timeout.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
* Copyright 2023 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package streaming
import (
"context"
"fmt"
"runtime/debug"
"time"
"github.com/bytedance/gopkg/util/gopool"
"github.com/cloudwego/kitex/pkg/kerrors"
)
// CallWithTimeout executes a function with timeout.
// If timeout is 0, the function will be executed without timeout; panic is not recovered in this case;
// If time runs out, it will return a kerrors.ErrRPCTimeout;
// If your function panics, it will also return a kerrors.ErrRPCTimeout with the panic details;
// Other kinds of errors are always returned by your function.
//
// NOTE: the `cancel` function is necessary to cancel the underlying transport, otherwise the recv/send call
// will block until the transport is closed, which may cause surge of goroutines.
func CallWithTimeout(timeout time.Duration, cancel context.CancelFunc, f func() (err error)) error {
if timeout <= 0 {
return f()
}
if cancel == nil {
panic("nil cancel func. Please pass in the cancel func in the context (set in context BEFORE " +
"the client method call, NOT just before recv/send), to avoid blocking recv/send calls")
}
begin := time.Now()
timer := time.NewTimer(timeout)
defer timer.Stop()
finishChan := make(chan error, 1) // non-blocking channel to avoid goroutine leak
gopool.Go(func() {
var bizErr error
defer func() {
if r := recover(); r != nil {
cancel()
timeoutErr := fmt.Errorf(
"CallWithTimeout: panic in business code, timeout_config=%v, panic=%v, stack=%s",
timeout, r, debug.Stack())
bizErr = kerrors.ErrRPCTimeout.WithCause(timeoutErr)
}
finishChan <- bizErr
}()
bizErr = f()
})
select {
case <-timer.C:
cancel()
timeoutErr := fmt.Errorf("CallWithTimeout: timeout in business code, timeout_config=%v, actual=%v",
timeout, time.Since(begin))
return kerrors.ErrRPCTimeout.WithCause(timeoutErr)
case bizErr := <-finishChan:
return bizErr
}
}