forked from adriancooney/await
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathawaiter.go
More file actions
83 lines (71 loc) · 1.65 KB
/
awaiter.go
File metadata and controls
83 lines (71 loc) · 1.65 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"context"
"errors"
"time"
)
const retryDelay = 500 * time.Millisecond
type timeoutError struct {
Reason error
}
// Error implements the error interface.
func (e *timeoutError) Error() string {
return e.Reason.Error()
}
type awaiter struct {
logger *LevelLogger
timeout time.Duration
}
func (a *awaiter) run(resources []resource) error {
if a.logger == nil {
a.logger = NewLogger(errorLevel)
}
ctx, cancel := context.WithTimeout(context.Background(), a.timeout)
var latestErr error
go func() {
for _, res := range resources {
a.logger.Infof("Awaiting resource: %s", res)
for {
select {
case <-ctx.Done():
// Exceeded timeout
return
default:
// Still time left, let's continue
}
if latestErr = res.Await(ctx); latestErr != nil {
if e, ok := latestErr.(*unavailabilityError); ok {
// transient error
a.logger.Debugf("Resource unavailable: %v", e)
} else {
// Maybe transient error
a.logger.Errorf("Error: failed to await resource: %v", latestErr)
}
time.Sleep(retryDelay)
} else {
a.logger.Infof("Resource found: %s", res)
// Resource found, move on to next one
break
}
}
}
cancel() // All resources are available
}()
<-ctx.Done()
switch ctx.Err() {
case context.Canceled:
if latestErr != nil {
return latestErr
}
// All resources are available
return nil
case context.DeadlineExceeded:
if latestErr == nil {
// Time out even before the first try
latestErr = errors.New("initial await did not finish")
}
return &unavailabilityError{latestErr}
default:
return errors.New("unknown error")
}
}