-
Notifications
You must be signed in to change notification settings - Fork 240
/
curl.go
220 lines (183 loc) · 5.16 KB
/
curl.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package cmd
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"sync"
"time"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/cmdctx"
"github.com/superfly/flyctl/internal/client"
"github.com/dustin/go-humanize"
"github.com/logrusorgru/aurora"
"github.com/superfly/flyctl/docstrings"
"github.com/spf13/cobra"
)
func newCurlCommand(client *client.Client) *Command {
curlStrings := docstrings.Get("curl")
cmd := BuildCommandKS(nil, runCurl, curlStrings, client, requireSession)
cmd.Args = cobra.ExactArgs(1)
cmd.Hidden = true
return cmd
}
// TimingResponse - Results from timing a curl operations
type TimingResponse struct {
Err error
HTTPCode int `json:"http_code"`
SpeedDownload int `json:"speed_download"`
TimeTotal float64 `json:"time_total"`
TimeNameLookup float64 `json:"time_namelookup"`
TimeConnect float64 `json:"time_connect"`
TimePreTransfer float64 `json:"time_pretransfer"`
TimeAppConnect float64 `json:"time_appconnect"`
TimeStartTransfer float64 `json:"time_starttransfer"`
HTTPVersion string `json:"http_version"`
RemoteIP string `json:"remote_ip"`
Scheme string `json:"scheme"`
Region string `json:"region"`
}
// TimingRequest - Request to time a curl operation
type TimingRequest struct {
URL string `json:"url"`
Region string `json:"region"`
}
func TimeRegions(ctx *cmdctx.CmdContext, url string, includeNoGateway bool) ([]api.Region, <-chan TimingResponse, error) {
regions, _, err := ctx.Client.API().PlatformRegions()
if err != nil {
return nil, nil, err
}
results := make(chan TimingResponse, len(regions))
client := &http.Client{
Timeout: time.Second * 3,
}
var wg sync.WaitGroup
for _, r := range regions {
if includeNoGateway || r.GatewayAvailable {
wg.Add(1)
}
}
for _, region := range regions {
region := region
if !includeNoGateway && !region.GatewayAvailable {
continue
}
go func() {
defer wg.Done()
timingResp := TimingResponse{
Region: region.Code,
}
body, err := json.Marshal(TimingRequest{URL: url, Region: region.Code})
if err != nil {
log.Printf("invalid JSON from %s: %s", region.Code, err)
return
}
req, err := http.NewRequest("POST", "https://curl.fly.dev/timings", bytes.NewBuffer(body))
if err != nil {
log.Printf("can't make HTTP request to %s: %s", region.Code, err)
return
}
req.Header.Add("Authorization", "1q2w3e4r")
req.Header.Add("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
timingResp.Err = err
} else {
defer resp.Body.Close()
if resp.StatusCode != 200 {
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
timingResp.Err = err
} else {
err = errors.New(string(data))
timingResp.Err = err
}
} else {
err = json.NewDecoder(resp.Body).Decode(&timingResp)
if err != nil {
timingResp.Err = err
}
}
}
results <- timingResp
}()
}
go func() {
wg.Wait()
close(results)
}()
return regions, results, nil
}
func runCurl(ctx *cmdctx.CmdContext) error {
url := ctx.Args[0]
_, results, err := TimeRegions(ctx, url, true)
if err != nil {
return err
}
var timingRowFormat = "%s\t%s\t%s\t%s\t%s\t%s\t%s\n"
var timingRowErrorFormat = "%s\t%s\n"
failures := []TimingResponse{}
fmt.Printf(timingRowFormat, "Region", "Status", "DNS", "Connect", "TLS", "TTFB", "Total")
for result := range results {
if result.Err != nil {
failures = append(failures, result)
continue
}
fmt.Printf(timingRowFormat,
result.Region,
formatHTTPStatus(result.HTTPCode),
formatDNS(result),
formatConnect(result),
formatTLS(result),
formatTTFB(result),
formatTotal(result),
)
}
if len(failures) > 0 {
fmt.Println("\nFailures:")
for _, result := range failures {
fmt.Printf(timingRowErrorFormat, result.Region, result.Err)
}
}
return nil
}
func formatHTTPStatus(status int) interface{} {
text := strconv.Itoa(status)
return colorize(text, float64(status), 299, 399)
}
func formatDNS(result TimingResponse) interface{} {
return humanize.FtoaWithDigits(result.TimeNameLookup*1000, 1) + "ms"
}
func formatConnect(result TimingResponse) interface{} {
timing := result.TimeConnect * 1000
text := humanize.FtoaWithDigits(timing, 1) + "ms"
return colorize(text, timing, 200, 500)
}
func formatTLS(result TimingResponse) interface{} {
return humanize.FtoaWithDigits((result.TimeAppConnect+result.TimePreTransfer)*1000, 1) + "ms"
}
func formatTTFB(result TimingResponse) interface{} {
timing := result.TimeStartTransfer * 1000
text := humanize.FtoaWithDigits(timing, 1) + "ms"
return colorize(text, timing, 400, 1000)
}
func formatTotal(result TimingResponse) interface{} {
timing := result.TimeTotal * 1000
return humanize.FtoaWithDigits(timing, 1) + "ms"
}
func colorize(text string, val float64, greenCutoff float64, yellowCutoff float64) interface{} {
var color aurora.Color
switch {
case val <= greenCutoff:
color = aurora.GreenFg
case val <= yellowCutoff:
color = aurora.YellowFg
default:
color = aurora.RedFg
}
return aurora.Colorize(text, color)
}