-
Notifications
You must be signed in to change notification settings - Fork 17
/
try.go
55 lines (50 loc) · 1.13 KB
/
try.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
package grill
import (
"fmt"
"time"
)
func Try(deadline time.Duration, minSuccess int, assertion Assertion) Assertion {
return &tryAssertion{
assertion: assertion,
deadline: deadline,
minSuccess: minSuccess,
}
}
type tryAssertion struct {
assertion Assertion
deadline time.Duration
minSuccess int
}
func (assert *tryAssertion) Assert() error {
checkC := time.Tick(assert.deadline / time.Duration(assert.minSuccess*3+3))
quitC := time.Tick(assert.deadline)
var successCount = 0
var errors []string
for {
select {
case <-checkC:
if err := assert.assertion.Assert(); err != nil {
errors = append(errors, err.Error())
successCount = 0
continue
}
successCount += 1
if successCount >= assert.minSuccess {
return nil
}
case <-quitC:
return fmt.Errorf("couldn't complete in given deadline, max consecutive success=%d, errors=%v", successCount, uniq(errors))
}
}
}
func uniq(errors []string) []string {
temp := map[string]struct{}{}
var result []string
for _, e := range errors {
if _, ok := temp[e]; !ok {
result = append(result, e)
temp[e] = struct{}{}
}
}
return result
}