go-zero/core/fx/timeout.go

59 lines
1.3 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package fx
import (
"context"
2021-08-15 15:33:45 +08:00
"fmt"
"runtime/debug"
"strings"
2020-07-26 17:09:05 +08:00
"time"
)
var (
2021-02-19 17:49:39 +08:00
// ErrCanceled is the error returned when the context is canceled.
2020-07-26 17:09:05 +08:00
ErrCanceled = context.Canceled
2021-02-19 17:49:39 +08:00
// ErrTimeout is the error returned when the context's deadline passes.
ErrTimeout = context.DeadlineExceeded
2020-07-26 17:09:05 +08:00
)
2021-02-19 17:49:39 +08:00
// DoOption defines the method to customize a DoWithTimeout call.
type DoOption func() context.Context
2020-07-26 17:09:05 +08:00
2021-02-19 17:49:39 +08:00
// DoWithTimeout runs fn with timeout control.
func DoWithTimeout(fn func() error, timeout time.Duration, opts ...DoOption) error {
2020-07-26 17:09:05 +08:00
parentCtx := context.Background()
for _, opt := range opts {
parentCtx = opt()
}
ctx, cancel := context.WithTimeout(parentCtx, timeout)
2020-07-26 17:09:05 +08:00
defer cancel()
// create channel with buffer size 1 to avoid goroutine leak
done := make(chan error, 1)
panicChan := make(chan any, 1)
2020-07-26 17:09:05 +08:00
go func() {
defer func() {
if p := recover(); p != nil {
2021-08-15 15:33:45 +08:00
// attach call stack to avoid missing in different goroutine
panicChan <- fmt.Sprintf("%+v\n\n%s", p, strings.TrimSpace(string(debug.Stack())))
2020-07-26 17:09:05 +08:00
}
}()
done <- fn()
}()
select {
case p := <-panicChan:
panic(p)
case err := <-done:
return err
case <-ctx.Done():
return ctx.Err()
}
}
2021-02-19 17:49:39 +08:00
// WithContext customizes a DoWithTimeout call with given ctx.
func WithContext(ctx context.Context) DoOption {
2020-07-26 17:09:05 +08:00
return func() context.Context {
return ctx
}
}