-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathdependency.go
48 lines (40 loc) · 1.09 KB
/
dependency.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
package detective
import (
"time"
)
// The DetectorFunc type represents the function signature to check the health of a dependency
type DetectorFunc func() error
// The Dependency type represents a detectable unit. The function provided in the Detect method will be called to monitor the state of the dependency
type Dependency struct {
name string
detector DetectorFunc
state State
}
func noopDetectorFunc() DetectorFunc {
return func() error {
return nil
}
}
func newDependency(name string) *Dependency {
return &Dependency{
name: name,
detector: noopDetectorFunc(),
}
}
// Detect registers a function that will be called to detect the health of a dependency. If the dependency is healthy, a nil value should be returned as the error.
func (d *Dependency) Detect(df DetectorFunc) {
d.detector = df
}
func (d *Dependency) updateState() {
d.state = d.getState()
}
func (d *Dependency) getState() State {
init := time.Now()
err := d.detector()
diff := time.Now().Sub(init)
s := State{Name: d.name, Latency: diff}
if err != nil {
return s.withError(err)
}
return s.withOk()
}