/
context.go
255 lines (219 loc) · 6.57 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
package resolve
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"time"
"go.uber.org/atomic"
)
type Context struct {
ctx context.Context
Variables []byte
Request Request
RenameTypeNames []RenameTypeName
TracingOptions TraceOptions
RateLimitOptions RateLimitOptions
InitialPayload []byte
Extensions []byte
Stats Stats
LoaderHooks LoaderHooks
authorizer Authorizer
rateLimiter RateLimiter
subgraphErrors error
}
type AuthorizationDeny struct {
Reason string
}
type Authorizer interface {
// AuthorizePreFetch is called prior to making a fetch in the loader
// This allows to implement policies to prevent fetches to an origin
// E.g. for Mutations, it might be undesired to just filter out the response
// You'd want to prevent sending the Operation to the Origin completely
//
// The input argument is the final render of the datasource input
AuthorizePreFetch(ctx *Context, dataSourceID string, input json.RawMessage, coordinate GraphCoordinate) (result *AuthorizationDeny, err error)
// AuthorizeObjectField operates on the response and can solely be used to implement policies to filter out response fields
// In contrast to AuthorizePreFetch, this cannot be used to prevent origin requests
// This function only allows you to filter the response before rendering it to the client
//
// The object argument is the flat render of the field-enclosing response object
// Flat render means, we're only rendering scalars, not arrays or objects
AuthorizeObjectField(ctx *Context, dataSourceID string, object json.RawMessage, coordinate GraphCoordinate) (result *AuthorizationDeny, err error)
HasResponseExtensionData(ctx *Context) bool
RenderResponseExtension(ctx *Context, out io.Writer) error
}
func (c *Context) SetAuthorizer(authorizer Authorizer) {
c.authorizer = authorizer
}
func (c *Context) SetEngineLoaderHooks(hooks LoaderHooks) {
c.LoaderHooks = hooks
}
type RateLimitOptions struct {
// Enable switches rate limiting on or off
Enable bool
// IncludeStatsInResponseExtension includes the rate limit stats in the response extensions
IncludeStatsInResponseExtension bool
Rate int
Burst int
Period time.Duration
RateLimitKey string
RejectExceedingRequests bool
}
type RateLimitDeny struct {
Reason string
}
type RateLimiter interface {
RateLimitPreFetch(ctx *Context, info *FetchInfo, input json.RawMessage) (result *RateLimitDeny, err error)
RenderResponseExtension(ctx *Context, out io.Writer) error
}
func (c *Context) SetRateLimiter(limiter RateLimiter) {
c.rateLimiter = limiter
}
func (c *Context) SubgraphErrors() error {
return c.subgraphErrors
}
func (c *Context) appendSubgraphError(err error) {
c.subgraphErrors = errors.Join(c.subgraphErrors, err)
}
type Stats struct {
NumberOfFetches atomic.Int32
CombinedResponseSize atomic.Int64
ResolvedNodes int
ResolvedObjects int
ResolvedLeafs int
}
func (s *Stats) Reset() {
s.NumberOfFetches.Store(0)
s.CombinedResponseSize.Store(0)
s.ResolvedNodes = 0
s.ResolvedObjects = 0
s.ResolvedLeafs = 0
}
type Request struct {
ID string
Header http.Header
}
func NewContext(ctx context.Context) *Context {
if ctx == nil {
panic("nil context.Context")
}
return &Context{
ctx: ctx,
}
}
func (c *Context) Context() context.Context {
return c.ctx
}
func (c *Context) WithContext(ctx context.Context) *Context {
if ctx == nil {
panic("nil context.Context")
}
cpy := *c
cpy.ctx = ctx
return &cpy
}
func (c *Context) clone(ctx context.Context) *Context {
cpy := *c
cpy.ctx = ctx
cpy.Variables = append([]byte(nil), c.Variables...)
cpy.Request.Header = c.Request.Header.Clone()
cpy.RenameTypeNames = append([]RenameTypeName(nil), c.RenameTypeNames...)
return &cpy
}
func (c *Context) Free() {
c.ctx = nil
c.Variables = nil
c.Request.Header = nil
c.RenameTypeNames = nil
c.TracingOptions.DisableAll()
c.Extensions = nil
c.Stats.Reset()
c.subgraphErrors = nil
c.authorizer = nil
c.LoaderHooks = nil
}
type traceStartKey struct{}
type TraceInfo struct {
TraceStart time.Time `json:"-"`
TraceStartTime string `json:"trace_start_time"`
TraceStartUnix int64 `json:"trace_start_unix"`
ParseStats PhaseStats `json:"parse_stats"`
NormalizeStats PhaseStats `json:"normalize_stats"`
ValidateStats PhaseStats `json:"validate_stats"`
PlannerStats PhaseStats `json:"planner_stats"`
debug bool
}
type PhaseStats struct {
DurationNano int64 `json:"duration_nanoseconds"`
DurationPretty string `json:"duration_pretty"`
DurationSinceStartNano int64 `json:"duration_since_start_nanoseconds"`
DurationSinceStartPretty string `json:"duration_since_start_pretty"`
}
func SetTraceStart(ctx context.Context, predictableDebugTimings bool) context.Context {
info := &TraceInfo{}
if predictableDebugTimings {
info.debug = true
info.TraceStart = time.UnixMilli(0)
info.TraceStartUnix = 0
info.TraceStartTime = ""
} else {
info.TraceStart = time.Now()
info.TraceStartUnix = info.TraceStart.Unix()
info.TraceStartTime = info.TraceStart.Format(time.RFC3339)
}
return context.WithValue(ctx, traceStartKey{}, info)
}
func GetDurationNanoSinceTraceStart(ctx context.Context) int64 {
info, ok := ctx.Value(traceStartKey{}).(*TraceInfo)
if !ok {
return 0
}
if info.debug {
return 1
}
return time.Since(info.TraceStart).Nanoseconds()
}
func SetDebugStats(info *TraceInfo, stats PhaseStats, phaseNo int64) PhaseStats {
if info.debug {
stats.DurationSinceStartNano = phaseNo * 5
stats.DurationSinceStartPretty = time.Duration(phaseNo * 5).String()
stats.DurationNano = 5
stats.DurationPretty = time.Duration(5).String()
}
return stats
}
func GetTraceInfo(ctx context.Context) *TraceInfo {
// The context might not have trace info, in that case we return nil
info, _ := ctx.Value(traceStartKey{}).(*TraceInfo)
return info
}
func SetParseStats(ctx context.Context, stats PhaseStats) {
info := GetTraceInfo(ctx)
if info == nil {
return
}
info.ParseStats = SetDebugStats(info, stats, 1)
}
func SetNormalizeStats(ctx context.Context, stats PhaseStats) {
info := GetTraceInfo(ctx)
if info == nil {
return
}
info.NormalizeStats = SetDebugStats(info, stats, 2)
}
func SetValidateStats(ctx context.Context, stats PhaseStats) {
info := GetTraceInfo(ctx)
if info == nil {
return
}
info.ValidateStats = SetDebugStats(info, stats, 3)
}
func SetPlannerStats(ctx context.Context, stats PhaseStats) {
info := GetTraceInfo(ctx)
if info == nil {
return
}
info.PlannerStats = SetDebugStats(info, stats, 4)
}