-
Notifications
You must be signed in to change notification settings - Fork 69
/
context.go
455 lines (376 loc) · 12.7 KB
/
context.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
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
package core
import (
"context"
"net/http"
"net/url"
"sync"
"time"
"github.com/wundergraph/cosmo/router/pkg/authentication"
ctrace "github.com/wundergraph/cosmo/router/pkg/trace"
"github.com/wundergraph/graphql-go-tools/v2/pkg/engine/resolve"
"go.uber.org/zap"
)
type key string
const requestContextKey = key("request")
const subgraphsContextKey = key("subgraphs")
var _ RequestContext = (*requestContext)(nil)
type Subgraph struct {
Id string
Name string
Url *url.URL
}
type ClientInfo struct {
// Name contains the client name, derived from the request headers
Name string
// Version contains the client version, derived from the request headers
Version string
// WGRequestToken contains the token to authenticate the request from the platform
WGRequestToken string
}
func NewClientInfoFromRequest(r *http.Request) *ClientInfo {
clientName := ctrace.GetClientInfo(r.Header, "graphql-client-name", "apollographql-client-name", "unknown")
clientVersion := ctrace.GetClientInfo(r.Header, "graphql-client-version", "apollographql-client-version", "missing")
requestToken := r.Header.Get("X-WG-Token")
return &ClientInfo{
Name: clientName,
Version: clientVersion,
WGRequestToken: requestToken,
}
}
type RequestContext interface {
// ResponseWriter is the original response writer received by the router.
ResponseWriter() http.ResponseWriter
// Request is the original request received by the router.
Request() *http.Request
// Logger is the logger for the request
Logger() *zap.Logger
// Operation is the GraphQL operation
Operation() OperationContext
// SendError returns the most recent error occurred while trying to make the origin request.
SendError() error
// Set is used to store a new key/value pair exclusively for this context.
Set(string, any)
// Get returns the value for the given key, ie: (value, true).
Get(string) (value any, exists bool)
// GetString returns the value associated with the key as a string.
GetString(string) string
// MustGet returns the value for the given key if it exists, otherwise it panics.
MustGet(string) any
// GetBool returns the value associated with the key as a boolean.
GetBool(string) bool
// GetInt returns the value associated with the key as an integer.
GetInt(string) int
// GetInt64 returns the value associated with the key as an integer.
GetInt64(string) int64
// GetUint returns the value associated with the key as an unsigned integer.
GetUint(string) uint
// GetUint64 returns the value associated with the key as an unsigned integer.
GetUint64(string) uint64
// GetFloat64 returns the value associated with the key as a float64.
GetFloat64(string) float64
// GetTime returns the value associated with the key as time.
GetTime(string) time.Time
// GetDuration returns the value associated with the key as a duration.
GetDuration(string) time.Duration
// GetStringSlice returns the value associated with the key as a slice of strings.
GetStringSlice(string) []string
// GetStringMap returns the value associated with the key as a map of interfaces.
GetStringMap(string) map[string]any
// GetStringMapString returns the value associated with the key as a map of strings.
GetStringMapString(string) map[string]string
// GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
GetStringMapStringSlice(string) map[string][]string
// ActiveSubgraph returns the current subgraph to which the request is made to
ActiveSubgraph(subgraphRequest *http.Request) *Subgraph
// SubgraphByID return the subgraph by its ID
SubgraphByID(subgraphID string) *Subgraph
// Authentication returns the authentication information for the request, if any
Authentication() authentication.Authentication
}
// requestContext is the default implementation of RequestContext
// It is accessible to custom modules in the request lifecycle
type requestContext struct {
logger *zap.Logger
// This mutex protects keys map.
mu sync.RWMutex
// keys is a key/value pair exclusively for the context of each request.
keys map[string]any
// responseWriter is the original response writer received by the router.
responseWriter http.ResponseWriter
// error indicates if the request / response has an error. Due to the nature of GraphQL
// Error can be set even if the response status code is 200.
error error
// request is the original request received by the router.
request *http.Request
// operation is the GraphQL operation context
operation *operationContext
// sendError returns the most recent error occurred while trying to make the origin request.
sendError error
// subgraphs is the list of subgraphs taken from the router config
subgraphs []Subgraph
}
func (c *requestContext) SendError() error {
return c.sendError
}
func (c *requestContext) Operation() OperationContext {
return c.operation
}
func (c *requestContext) Request() *http.Request {
return c.request
}
func withRequestContext(ctx context.Context, operation *requestContext) context.Context {
return context.WithValue(ctx, requestContextKey, operation)
}
func getRequestContext(ctx context.Context) *requestContext {
if ctx == nil {
return nil
}
op := ctx.Value(requestContextKey)
if op == nil {
return nil
}
return op.(*requestContext)
}
func (c *requestContext) ResponseWriter() http.ResponseWriter {
return c.responseWriter
}
func (c *requestContext) Logger() *zap.Logger {
return c.logger
}
// Set is used to store a new key/value pair exclusively for this context.
// It also lazy initializes c.keys if it was not used previously.
func (c *requestContext) Set(key string, value any) {
c.mu.Lock()
defer c.mu.Unlock()
if c.keys == nil {
c.keys = make(map[string]any)
}
c.keys[key] = value
}
// Get returns the value for the given key, ie: (value, true).
// If the value does not exist it returns (nil, false)
func (c *requestContext) Get(key string) (value any, exists bool) {
c.mu.RLock()
defer c.mu.RUnlock()
value, exists = c.keys[key]
return
}
// MustGet returns the value for the given key if it exists, otherwise it panics.
func (c *requestContext) MustGet(key string) any {
if value, exists := c.Get(key); exists {
return value
}
panic("Key \"" + key + "\" does not exist")
}
// GetString returns the value associated with the key as a string.
func (c *requestContext) GetString(key string) (s string) {
if val, ok := c.Get(key); ok && val != nil {
s, _ = val.(string)
}
return
}
// GetBool returns the value associated with the key as a boolean.
func (c *requestContext) GetBool(key string) (b bool) {
if val, ok := c.Get(key); ok && val != nil {
b, _ = val.(bool)
}
return
}
// GetInt returns the value associated with the key as an integer.
func (c *requestContext) GetInt(key string) (i int) {
if val, ok := c.Get(key); ok && val != nil {
i, _ = val.(int)
}
return
}
// GetInt64 returns the value associated with the key as an integer.
func (c *requestContext) GetInt64(key string) (i64 int64) {
if val, ok := c.Get(key); ok && val != nil {
i64, _ = val.(int64)
}
return
}
// GetUint returns the value associated with the key as an unsigned integer.
func (c *requestContext) GetUint(key string) (ui uint) {
if val, ok := c.Get(key); ok && val != nil {
ui, _ = val.(uint)
}
return
}
// GetUint64 returns the value associated with the key as an unsigned integer.
func (c *requestContext) GetUint64(key string) (ui64 uint64) {
if val, ok := c.Get(key); ok && val != nil {
ui64, _ = val.(uint64)
}
return
}
// GetFloat64 returns the value associated with the key as a float64.
func (c *requestContext) GetFloat64(key string) (f64 float64) {
if val, ok := c.Get(key); ok && val != nil {
f64, _ = val.(float64)
}
return
}
// GetTime returns the value associated with the key as time.
func (c *requestContext) GetTime(key string) (t time.Time) {
if val, ok := c.Get(key); ok && val != nil {
t, _ = val.(time.Time)
}
return
}
// GetDuration returns the value associated with the key as a duration.
func (c *requestContext) GetDuration(key string) (d time.Duration) {
if val, ok := c.Get(key); ok && val != nil {
d, _ = val.(time.Duration)
}
return
}
// GetStringSlice returns the value associated with the key as a slice of strings.
func (c *requestContext) GetStringSlice(key string) (ss []string) {
if val, ok := c.Get(key); ok && val != nil {
ss, _ = val.([]string)
}
return
}
// GetStringMap returns the value associated with the key as a map of interfaces.
func (c *requestContext) GetStringMap(key string) (sm map[string]any) {
if val, ok := c.Get(key); ok && val != nil {
sm, _ = val.(map[string]any)
}
return
}
// GetStringMapString returns the value associated with the key as a map of strings.
func (c *requestContext) GetStringMapString(key string) (sms map[string]string) {
if val, ok := c.Get(key); ok && val != nil {
sms, _ = val.(map[string]string)
}
return
}
// GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
func (c *requestContext) GetStringMapStringSlice(key string) (smss map[string][]string) {
if val, ok := c.Get(key); ok && val != nil {
smss, _ = val.(map[string][]string)
}
return
}
func (c *requestContext) ActiveSubgraph(subgraphRequest *http.Request) *Subgraph {
for _, sg := range c.subgraphs {
if sg.Url != nil && sg.Url.String() == subgraphRequest.URL.String() {
return &sg
}
}
return nil
}
func (c *requestContext) SubgraphByID(subgraphID string) *Subgraph {
for _, sg := range c.subgraphs {
if sg.Url != nil && sg.Id == subgraphID {
return &sg
}
}
return nil
}
func (c *requestContext) Authentication() authentication.Authentication {
return authentication.FromContext(c.request.Context())
}
const operationContextKey = key("graphql")
type OperationContext interface {
// Name is the name of the operation
Name() string
// Type is the type of the operation (query, mutation, subscription)
Type() string
// Hash is the hash of the operation
Hash() uint64
// Content is the content of the operation
Content() string
// ClientInfo returns information about the client that initiated this operation
ClientInfo() ClientInfo
}
var _ OperationContext = (*operationContext)(nil)
// operationContext contains information about the current GraphQL operation
type operationContext struct {
// Name is the name of the operation
name string
// opType is the type of the operation (query, mutation, subscription)
opType string
// Hash is the hash of the operation
hash uint64
// Content is the content of the operation
content string
variables []byte
clientInfo *ClientInfo
// preparedPlan is the prepared plan of the operation
preparedPlan *planWithMetaData
traceOptions resolve.TraceOptions
planCacheHit bool
initialPayload []byte
extensions []byte
persistedID string
protocol OperationProtocol
}
func (o *operationContext) Variables() []byte {
return o.variables
}
func (o *operationContext) Name() string {
return o.name
}
func (o *operationContext) Type() string {
return o.opType
}
func (o *operationContext) Hash() uint64 {
return o.hash
}
func (o *operationContext) Content() string {
return o.content
}
func (o *operationContext) PersistedID() string {
return o.persistedID
}
func (o *operationContext) Protocol() OperationProtocol {
return o.protocol
}
func (o *operationContext) ClientInfo() ClientInfo {
return *o.clientInfo
}
func withOperationContext(ctx context.Context, operation *operationContext) context.Context {
return context.WithValue(ctx, operationContextKey, operation)
}
// getOperationContext returns the request context.
// It provides information about the current operation like the name, type, hash and content.
// If no operation context is found, nil is returned.
func getOperationContext(ctx context.Context) *operationContext {
if ctx == nil {
return nil
}
op := ctx.Value(operationContextKey)
if op == nil {
return nil
}
return op.(*operationContext)
}
// isMutationRequest returns true if the current request is a mutation request
func isMutationRequest(ctx context.Context) bool {
op := getRequestContext(ctx)
if op == nil {
return false
}
return op.Operation().Type() == "mutation"
}
func withSubgraphs(ctx context.Context, subgraphs []Subgraph) context.Context {
return context.WithValue(ctx, subgraphsContextKey, subgraphs)
}
func subgraphsFromContext(ctx context.Context) []Subgraph {
subgraphs, _ := ctx.Value(subgraphsContextKey).([]Subgraph)
return subgraphs
}
func buildRequestContext(w http.ResponseWriter, r *http.Request, opContext *operationContext, requestLogger *zap.Logger) *requestContext {
subgraphs := subgraphsFromContext(r.Context())
requestContext := &requestContext{
logger: requestLogger,
keys: map[string]any{},
responseWriter: w,
request: r,
operation: opContext,
subgraphs: subgraphs,
}
return requestContext
}