-
Notifications
You must be signed in to change notification settings - Fork 127
/
Copy pathpolling.go
53 lines (45 loc) · 1.07 KB
/
polling.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
package client
import (
"errors"
"fmt"
"time"
)
var AsyncProcessTimeoutError = errors.New("timed out after waiting for async process")
type PollingOptions struct {
Timeout time.Duration
CheckInterval time.Duration
FailedState string
}
func NewPollingOptions() *PollingOptions {
return &PollingOptions{
FailedState: "FAILED",
Timeout: time.Minute * 5,
CheckInterval: time.Second,
}
}
type getStateFunc func() (string, string, error)
func PollForStateOrTimeout(getState getStateFunc, successState string, opts *PollingOptions) error {
if opts == nil {
opts = NewPollingOptions()
}
timeout := time.After(opts.Timeout)
ticker := time.NewTicker(opts.CheckInterval)
defer ticker.Stop()
for {
select {
case <-timeout:
return AsyncProcessTimeoutError
case <-ticker.C:
state, cfError, err := getState()
if err != nil {
return err
}
switch state {
case successState:
return nil
case opts.FailedState:
return fmt.Errorf("received state %s while waiting for async process: %s", opts.FailedState, cfError)
}
}
}
}