-
Notifications
You must be signed in to change notification settings - Fork 651
/
client.go
56 lines (45 loc) · 1.4 KB
/
client.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
56
// (c) 2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package health
import (
"errors"
"time"
"github.com/ava-labs/avalanchego/utils/rpc"
)
var errInvalidNumberOfChecks = errors.New("expected at least 1 check attempt")
// Client for Avalanche Health API Endpoint
type Client struct {
requester rpc.EndpointRequester
}
// NewClient returns a client to interact with Health API endpoint
func NewClient(uri string, requestTimeout time.Duration) *Client {
return &Client{
requester: rpc.NewEndpointRequester(uri, "/ext/health", "health", requestTimeout),
}
}
// Health returns a health check on the Avalanche node
func (c *Client) Health() (*APIHealthReply, error) {
res := &APIHealthReply{}
err := c.requester.SendRequest("health", struct{}{}, res)
return res, err
}
// AwaitHealthy queries the Health endpoint [checks] times, with a pause of
// [interval] in between checks and returns early if Health returns healthy
func (c *Client) AwaitHealthy(checks int, interval time.Duration) (bool, error) {
if checks < 1 {
return false, errInvalidNumberOfChecks
}
// Check health once outside the loop to avoid sleeping unnecessarily.
res, err := c.Health()
if err == nil && res.Healthy {
return true, nil
}
for i := 1; i < checks; i++ {
time.Sleep(interval)
res, err = c.Health()
if err == nil && res.Healthy {
return true, nil
}
}
return false, err
}