You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/fx/timeout.go

59 lines
1.3 KiB
Go

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