timeout err simulation
Vladimir Bauer
6 years ago
| 4 | 4 | "fmt" |
| 5 | 5 | "io" |
| 6 | 6 | "math/rand" |
| 7 | "sync" | |
| 7 | 8 | "time" |
| 8 | 9 | |
| 9 | 10 | "github.com/vbauerster/mpb/v4" |
| 25 | 26 | newCustomPercentage(decor.Percentage(), nextCh), |
| 26 | 27 | ), |
| 27 | 28 | ) |
| 29 | ew := &errorWrapper{} | |
| 30 | time.AfterFunc(2*time.Second, func() { | |
| 31 | ew.reset(errors.New("timeout")) | |
| 32 | }) | |
| 28 | 33 | // simulating some work |
| 29 | 34 | go func() { |
| 30 | 35 | rng := rand.New(rand.NewSource(time.Now().UnixNano())) |
| 31 | 36 | max := 100 * time.Millisecond |
| 32 | var err error | |
| 33 | 37 | 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-- | |
| 35 | 43 | bar.SetRefill(int64(i)) |
| 36 | 44 | time.Sleep(3 * time.Second) |
| 37 | 45 | 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 | |
| 45 | 47 | } |
| 46 | 48 | bar.Increment() |
| 47 | 49 | } |
| 48 | 50 | }() |
| 49 | 51 | |
| 50 | 52 | 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() | |
| 51 | 76 | } |
| 52 | 77 | |
| 53 | 78 | type customFiller struct { |
| 64 | 89 | base := mpb.NewBarFiller(mpb.DefaultBarStyle, false) |
| 65 | 90 | nextCh := make(chan struct{}, 1) |
| 66 | 91 | 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) { | |
| 68 | 93 | select { |
| 69 | 94 | case m := <-ch: |
| 70 | 95 | defer func() { |
| 82 | 107 | } else { |
| 83 | 108 | base.Fill(w, width, st) |
| 84 | 109 | } |
| 85 | }) | |
| 110 | } | |
| 86 | 111 | cf := &customFiller{ |
| 87 | Filler: filler, | |
| 112 | Filler: mpb.FillerFunc(filler), | |
| 88 | 113 | base: base, |
| 89 | 114 | } |
| 90 | 115 | return cf, nextCh |