Codebase list golang-github-vbauerster-mpb / 3ed31a5
timeout err simulation Vladimir Bauer 6 years ago
1 changed file(s) with 37 addition(s) and 12 deletion(s). Raw diff Collapse all Expand all
44 "fmt"
55 "io"
66 "math/rand"
7 "sync"
78 "time"
89
910 "github.com/vbauerster/mpb/v4"
2526 newCustomPercentage(decor.Percentage(), nextCh),
2627 ),
2728 )
29 ew := &errorWrapper{}
30 time.AfterFunc(2*time.Second, func() {
31 ew.reset(errors.New("timeout"))
32 })
2833 // simulating some work
2934 go func() {
3035 rng := rand.New(rand.NewSource(time.Now().UnixNano()))
3136 max := 100 * time.Millisecond
32 var err error
3337 for i := 0; i < total; i++ {
34 if err != nil {
38 time.Sleep(time.Duration(rng.Intn(10)+1) * max / 10)
39 if ew.isErr() {
40 msgCh <- fmt.Sprintf("%s at %d, retrying...", ew.Error(), i)
41 go ew.reset(nil)
42 i--
3543 bar.SetRefill(int64(i))
3644 time.Sleep(3 * time.Second)
3745 resumeCh <- struct{}{}
38 err = nil
39 } else {
40 time.Sleep(time.Duration(rng.Intn(10)+1) * max / 10)
41 }
42 if i == 33 {
43 err = errors.New("some error")
44 msgCh <- fmt.Sprintf("%s retrying...", err.Error())
46 continue
4547 }
4648 bar.Increment()
4749 }
4850 }()
4951
5052 p.Wait()
53 }
54
55 type errorWrapper struct {
56 sync.RWMutex
57 err error
58 }
59
60 func (ew *errorWrapper) Error() string {
61 ew.RLock()
62 defer ew.RUnlock()
63 return ew.err.Error()
64 }
65
66 func (ew *errorWrapper) isErr() bool {
67 ew.RLock()
68 defer ew.RUnlock()
69 return ew.err != nil
70 }
71
72 func (ew *errorWrapper) reset(err error) {
73 ew.Lock()
74 ew.err = err
75 ew.Unlock()
5176 }
5277
5378 type customFiller struct {
6489 base := mpb.NewBarFiller(mpb.DefaultBarStyle, false)
6590 nextCh := make(chan struct{}, 1)
6691 var msg *string
67 filler := mpb.FillerFunc(func(w io.Writer, width int, st *decor.Statistics) {
92 filler := func(w io.Writer, width int, st *decor.Statistics) {
6893 select {
6994 case m := <-ch:
7095 defer func() {
82107 } else {
83108 base.Fill(w, width, st)
84109 }
85 })
110 }
86111 cf := &customFiller{
87 Filler: filler,
112 Filler: mpb.FillerFunc(filler),
88113 base: base,
89114 }
90115 return cf, nextCh