-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathclient.go
More file actions
360 lines (293 loc) · 8.53 KB
/
client.go
File metadata and controls
360 lines (293 loc) · 8.53 KB
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
package fly
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"regexp"
"strings"
"time"
_ "github.com/Khan/genqlient/generate"
genq "github.com/Khan/genqlient/graphql"
"github.com/superfly/fly-go/tokens"
"github.com/superfly/graphql"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
var (
baseURL string
errorLog bool
instrumenter InstrumentationService
defaultTransport http.RoundTripper = http.DefaultTransport
)
var contextKeyAction = contextKey("gql_action")
func ctxWithAction(ctx context.Context, action string) context.Context {
return context.WithValue(ctx, contextKeyAction, action)
}
func actionFromCtx(ctx context.Context) string {
action := ctx.Value(contextKeyAction)
if action != nil {
return action.(string)
}
return "unknown_actiom"
}
// SetBaseURL - Sets the base URL for the API
func SetBaseURL(url string) {
baseURL = url
}
// SetErrorLog - Sets whether errors should be loddes
func SetErrorLog(log bool) {
errorLog = log
}
func SetInstrumenter(i InstrumentationService) {
instrumenter = i
}
func SetTransport(t http.RoundTripper) {
defaultTransport = t
}
type InstrumentationService interface {
ReportCallTiming(duration time.Duration)
}
// Client - API client encapsulating the http and GraphQL clients
type Client struct {
httpClient *http.Client
client *graphql.Client
genqClient genq.Client
tokens *tokens.Tokens
logger Logger
}
func (c *Client) Authenticated() bool {
return c.tokens.GraphQL() != ""
}
func (c *Client) GenqClient() genq.Client { return c.genqClient }
func (c *Client) SetGenqClient(client genq.Client) { c.genqClient = client }
// NewClient - creates a new Client, takes an access token
func NewClient(accessToken, name, version string, logger Logger) *Client {
return NewClientFromOptions(ClientOptions{
AccessToken: accessToken,
Name: name,
Version: version,
Logger: logger,
BaseURL: baseURL,
})
}
type ClientOptions struct {
AccessToken string
Tokens *tokens.Tokens
Name string
Version string
BaseURL string
Logger Logger
EnableDebugTrace *bool
FlyForceRegion *string
Transport *Transport
}
func (opts ClientOptions) tokens() *tokens.Tokens {
if opts.Tokens == nil {
opts.Tokens = tokens.Parse(opts.AccessToken)
}
return opts.Tokens
}
func (t *Transport) setDefaults(opts *ClientOptions) {
if t.UnderlyingTransport == nil {
t.UnderlyingTransport = defaultTransport
}
if t.Tokens == nil && t.Token == "" {
t.Tokens = opts.tokens()
}
if t.UserAgent == "" {
t.UserAgent = fmt.Sprintf("%s/%s", opts.Name, opts.Version)
}
if opts.EnableDebugTrace != nil {
t.EnableDebugTrace = *opts.EnableDebugTrace
} else {
v := os.Getenv("FLY_FORCE_TRACE")
t.EnableDebugTrace = v != "" && v != "0" && v != "false"
}
if opts.FlyForceRegion != nil {
t.FlyForceRegion = *opts.FlyForceRegion
} else if t.FlyForceRegion == "" {
if v := os.Getenv("FLY_FORCE_REGION"); v != "" {
t.FlyForceRegion = v
}
}
}
func NewClientFromOptions(opts ClientOptions) *Client {
if opts.BaseURL == "" {
opts.BaseURL = baseURL
}
transport := opts.Transport
if transport == nil {
transport = &Transport{}
}
transport.setDefaults(&opts)
httpClient, _ := NewHTTPClient(opts.Logger, transport)
url := fmt.Sprintf("%s/graphql", opts.BaseURL)
client := graphql.NewClient(url, graphql.WithHTTPClient(httpClient))
genqClient := genq.NewClient(url, httpClient)
tracingGenqClient := &tracingGenqlientClient{
client: genqClient,
}
return &Client{httpClient, client, tracingGenqClient, opts.tokens(), opts.Logger}
}
// NewRequest - creates a new GraphQL request
func (*Client) NewRequest(q string) *graphql.Request {
q = compactQueryString(q)
return graphql.NewRequest(q)
}
// Run - Runs a GraphQL request
func (c *Client) Run(req *graphql.Request) (Query, error) {
return c.RunWithContext(context.Background(), req)
}
func (c *Client) Logger() Logger { return c.logger }
func (c *Client) getRequestType(r *graphql.Request) string {
query := r.Query()
if strings.Contains(query, "mutation") {
return "mutation"
}
if strings.Contains(query, "query") {
return "query"
}
return "unknown"
}
func (c *Client) getErrorFromErrors(errors Errors) string {
errs := []string{}
for _, err := range errors {
errs = append(errs, err.Message)
}
return strings.Join(errs, ",")
}
// RunWithContext - Runs a GraphQL request within a Go context
func (c *Client) RunWithContext(ctx context.Context, req *graphql.Request) (Query, error) {
tracer := otel.GetTracerProvider().Tracer("github.com/superfly/fly-go")
ctx, span := tracer.Start(ctx, fmt.Sprintf("web.%s", actionFromCtx(ctx)), trace.WithAttributes(
attribute.String("request.action", actionFromCtx(ctx)),
attribute.String("request.type", c.getRequestType(req)),
))
defer span.End()
if instrumenter != nil {
start := time.Now()
defer func() {
instrumenter.ReportCallTiming(time.Since(start))
}()
}
var resp Query
err := c.client.Run(ctx, req, &resp)
if resp.Errors != nil {
span.RecordError(errors.New(c.getErrorFromErrors(resp.Errors)))
span.SetStatus(codes.Error, "failed to do grapqhl request")
}
if resp.Errors != nil && errorLog {
fmt.Fprintf(os.Stderr, "Error: %+v\n", resp.Errors)
}
if err == nil {
return resp, nil
}
return resp, fmt.Errorf("failed to run %s: %w", req.Query(), err)
}
var compactPattern = regexp.MustCompile(`\s+`)
func compactQueryString(q string) string {
q = strings.TrimSpace(q)
return compactPattern.ReplaceAllString(q, " ")
}
// GetAccessToken - uses email, password and possible otp to get token
func GetAccessToken(ctx context.Context, email, password, otp string) (token string, err error) {
var postData bytes.Buffer
if err = json.NewEncoder(&postData).Encode(map[string]any{
"data": map[string]any{
"attributes": map[string]string{
"email": email,
"password": password,
"otp": otp,
},
},
}); err != nil {
return
}
url := fmt.Sprintf("%s/api/v1/sessions", baseURL)
var req *http.Request
if req, err = http.NewRequestWithContext(ctx, http.MethodPost, url, &postData); err != nil {
return
}
req.Header.Set("Content-Type", "application/json")
var res *http.Response
if res, err = http.DefaultClient.Do(req); err != nil {
return
}
defer func() {
closeErr := res.Body.Close()
if err == nil {
err = closeErr
}
}()
switch {
case res.StatusCode >= http.StatusInternalServerError:
err = errors.New("an unknown server error occurred, please try again")
case res.StatusCode >= http.StatusBadRequest:
err = errors.New("incorrect email and password combination")
default:
var result map[string]map[string]map[string]string
if err = json.NewDecoder(res.Body).Decode(&result); err == nil {
token = result["data"]["attributes"]["access_token"]
}
}
return
}
type Transport struct {
UnderlyingTransport http.RoundTripper
UserAgent string
Token string // deprecated
Tokens *tokens.Tokens
EnableDebugTrace bool
FlyForceRegion string
}
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
t.addAuthorization(req)
req.Header.Set("User-Agent", t.UserAgent)
if t.EnableDebugTrace {
req.Header.Set("Fly-Force-Trace", "true")
}
if t.FlyForceRegion != "" {
req.Header.Set("Fly-Force-Region", t.FlyForceRegion)
}
return t.UnderlyingTransport.RoundTrip(req)
}
func (t *Transport) tokens() *tokens.Tokens {
if t.Tokens == nil {
t.Tokens = tokens.Parse(t.Token)
}
return t.Tokens
}
func (t *Transport) addAuthorization(req *http.Request) {
hdr, ok := req.Context().Value(contextKeyAuthorization).(string)
if !ok {
hdr = t.tokens().GraphQLHeader()
}
req.Header.Set("Authorization", hdr)
}
// tracingGenqlientClient wraps a genqlient client to add OTEL tracing with operation names
type tracingGenqlientClient struct {
client genq.Client
}
func (c *tracingGenqlientClient) MakeRequest(ctx context.Context, req *genq.Request, resp *genq.Response) error {
tracer := otel.GetTracerProvider().Tracer("github.com/superfly/fly-go")
// Create span name based on operation name if available, otherwise use generic name
spanName := "graphql.request"
if req.OpName != "" {
spanName = fmt.Sprintf("graphql.%s", req.OpName)
}
ctx, span := tracer.Start(ctx, spanName)
defer span.End()
if instrumenter != nil {
start := time.Now()
defer func() {
instrumenter.ReportCallTiming(time.Since(start))
}()
}
return c.client.MakeRequest(ctx, req, resp)
}