-
Notifications
You must be signed in to change notification settings - Fork 0
/
discovery.go
78 lines (67 loc) · 2.1 KB
/
discovery.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package gaudius
import (
"encoding"
"errors"
"fmt"
"time"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/go-resty/resty/v2"
)
// structure that manages the selected discovery node
type DiscoveryNode struct {
DiscoveryNodes []string
SelectedNode string
discoveryClient *resty.Client
discoveryFullClient *resty.Client
AcdcClient *ethclient.Client
}
func NewDiscoveryNode(nodes []string) (*DiscoveryNode, error) {
selectedNode, err := SelectHealthyDiscoveryNode(nodes)
if err != nil {
return nil, err
}
discoveryBaseUrl := fmt.Sprintf("%s/v1", selectedNode)
discoveryFullBaseUrl := fmt.Sprintf("%s/full", discoveryBaseUrl)
discoveryClient := resty.New().SetBaseURL(discoveryBaseUrl)
discoveryFullClient := resty.New().SetBaseURL(discoveryFullBaseUrl)
return &DiscoveryNode{DiscoveryNodes: nodes, SelectedNode: selectedNode, discoveryClient: discoveryClient, discoveryFullClient: discoveryFullClient}, nil
}
func SelectHealthyDiscoveryNode(discoveryNodes []string) (string, error) {
shuffle(discoveryNodes)
client := resty.New().SetTimeout(time.Second * 3).GetClient()
for _, endpoint := range discoveryNodes {
route := fmt.Sprintf("%s/health_check?enforce_block_diff=true&healthy_block_diff=250&plays_count_max_drift=720", endpoint)
res, err := client.Get(route)
if err != nil {
continue
}
if res.StatusCode == 200 {
return endpoint, nil
}
}
return "", errors.New("found no healthy discovery nodes")
}
func DiscoveryQuery[T encoding.BinaryUnmarshaler](sdk *AudiusSdk, path string, query map[string]string, response T) error {
dn := sdk.Discovery
res, err := dn.discoveryClient.R().SetQueryParams(query).Get(path)
if err != nil {
return err
}
err = response.UnmarshalBinary(res.Body())
if err != nil {
return err
}
return nil
}
func DiscoveryFullQuery[T encoding.BinaryUnmarshaler](sdk *AudiusSdk, path string, query map[string]string, response T) error {
dn := sdk.Discovery
res, err := dn.discoveryFullClient.R().SetQueryParams(query).Get(path)
if err != nil {
return err
}
err = response.UnmarshalBinary(res.Body())
if err != nil {
return err
}
return nil
}