-
Notifications
You must be signed in to change notification settings - Fork 0
/
ingest_rates.go
83 lines (71 loc) · 1.68 KB
/
ingest_rates.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
79
80
81
82
83
package telemetry
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/libp2p/go-libp2p/core/peer"
)
const telemetryPath = "/telemetry/providers"
type Rate struct {
Count uint64
Elapsed time.Duration
Samples int
}
func parseIndexerBaseURL(baseURL string) (*url.URL, error) {
if !strings.HasPrefix(baseURL, "http://") && !strings.HasPrefix(baseURL, "https://") {
baseURL = "http://" + baseURL
}
u, err := url.Parse(baseURL)
if err != nil {
return nil, err
}
u.Path = telemetryPath
return u, nil
}
func getIndexerTelemetry(ctx context.Context, baseURLs []*url.URL, providerID peer.ID) (Rate, bool, error) {
for _, baseURL := range baseURLs {
r, ok, err := getOneIndexerTelemetry(ctx, baseURL, providerID)
if err != nil {
return Rate{}, false, err
}
if ok {
return r, true, nil
}
}
return Rate{}, false, nil
}
func getOneIndexerTelemetry(ctx context.Context, baseURL *url.URL, providerID peer.ID) (Rate, bool, error) {
u := baseURL.JoinPath(providerID.String())
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return Rate{}, false, err
}
c := http.DefaultClient
resp, err := c.Do(req)
if err != nil {
return Rate{}, false, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return Rate{}, false, err
}
switch resp.StatusCode {
case http.StatusOK:
case http.StatusNoContent:
return Rate{}, false, nil
default:
return Rate{}, false, fmt.Errorf("%d %s", resp.StatusCode, resp.Status)
}
var ingestRate Rate
err = json.Unmarshal(body, &ingestRate)
if err != nil {
return Rate{}, false, err
}
return ingestRate, true, nil
}