-
Notifications
You must be signed in to change notification settings - Fork 5
/
api.go
273 lines (243 loc) · 7.09 KB
/
api.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
package apifu
import (
"context"
"net/http"
"reflect"
"strconv"
"sync"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/ccbrown/api-fu/graphql"
)
// API is responsible for serving your API traffic. Construct an API by creating a Config, then
// calling NewAPI.
type API struct {
schema *graphql.Schema
config *Config
logger logrus.FieldLogger
execute func(*graphql.Request, *RequestInfo) *graphql.Response
graphqlWSConnectionsMutex sync.Mutex
graphqlWSConnections map[graphqlWSConnection]struct{}
}
func (api *API) Schema() *graphql.Schema {
return api.schema
}
type RequestInfo struct {
Cost int
}
func normalizeModelType(t reflect.Type) reflect.Type {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
return t
}
// NewAPI validates your schema and builds an API ready to serve requests.
func NewAPI(cfg *Config) (*API, error) {
schema, err := cfg.graphqlSchema()
if err != nil {
return nil, errors.Wrap(err, "error building graphql schema")
}
logger := cfg.Logger
if logger == nil {
logger = logrus.StandardLogger()
}
execute := cfg.Execute
if execute == nil {
execute = func(r *graphql.Request, info *RequestInfo) *graphql.Response {
return graphql.Execute(r)
}
}
return &API{
config: cfg,
schema: schema,
logger: logger,
execute: execute,
graphqlWSConnections: map[graphqlWSConnection]struct{}{},
}, nil
}
type apiContextKeyType int
var apiContextKey apiContextKeyType
func ctxAPI(ctx context.Context) *API {
return ctx.Value(apiContextKey).(*API)
}
type asyncResolution struct {
Result graphql.ResolveResult
Dest graphql.ResolvePromise
}
type apiRequest struct {
asyncResolutions chan asyncResolution
chainedAsyncResolutions map[graphql.ResolvePromise]struct{}
batches map[*int]*batch
}
func (r *apiRequest) IdleHandler() {
for {
if len(r.batches) > 0 {
// Go ahead and resolve all the batches.
var wg sync.WaitGroup
for _, b := range r.batches {
wg.Add(1)
b := b
go func() {
defer wg.Done()
for i, result := range b.resolver(b.items) {
b.dests[i] <- result
}
}()
}
wg.Wait()
r.batches = map[*int]*batch{}
} else {
// Block until we've fully resolved something.
resolution := <-r.asyncResolutions
resolution.Dest <- resolution.Result
if _, ok := r.chainedAsyncResolutions[resolution.Dest]; ok {
delete(r.chainedAsyncResolutions, resolution.Dest)
continue
}
}
// Move along anything else that we happen to also be done resolving.
for {
select {
case resolution := <-r.asyncResolutions:
resolution.Dest <- resolution.Result
default:
return
}
}
}
}
type apiRequestContextKeyType int
var apiRequestContextKey apiRequestContextKeyType
func ctxAPIRequest(ctx context.Context) *apiRequest {
return ctx.Value(apiRequestContextKey).(*apiRequest)
}
func chain(ctx context.Context, p graphql.ResolvePromise, f func(interface{}) (interface{}, error)) graphql.ResolvePromise {
apiRequest := ctxAPIRequest(ctx)
if apiRequest.chainedAsyncResolutions == nil {
apiRequest.chainedAsyncResolutions = map[graphql.ResolvePromise]struct{}{}
}
apiRequest.chainedAsyncResolutions[p] = struct{}{}
return Go(ctx, func() (interface{}, error) {
result := <-p
if !isNil(result.Error) {
return nil, result.Error
}
return f(result.Value)
})
}
func join(ctx context.Context, p []graphql.ResolvePromise, f func([]interface{}) (interface{}, error)) graphql.ResolvePromise {
apiRequest := ctxAPIRequest(ctx)
if apiRequest.chainedAsyncResolutions == nil {
apiRequest.chainedAsyncResolutions = map[graphql.ResolvePromise]struct{}{}
}
for _, p := range p {
apiRequest.chainedAsyncResolutions[p] = struct{}{}
}
return Go(ctx, func() (interface{}, error) {
values := make([]interface{}, len(p))
for i, p := range p {
result := <-p
if !isNil(result.Error) {
return nil, result.Error
}
values[i] = result.Value
}
return f(values)
})
}
// Go completes resolution asynchronously and concurrently with any other asynchronous resolutions.
func Go(ctx context.Context, f func() (interface{}, error)) graphql.ResolvePromise {
apiRequest := ctxAPIRequest(ctx)
if apiRequest.asyncResolutions == nil {
apiRequest.asyncResolutions = make(chan asyncResolution)
}
ch := make(graphql.ResolvePromise, 1)
go func() {
v, err := f()
apiRequest.asyncResolutions <- asyncResolution{
Result: graphql.ResolveResult{
Value: v,
Error: err,
},
Dest: ch,
}
}()
return ch
}
type batch struct {
resolver func([]graphql.FieldContext) []graphql.ResolveResult
items []graphql.FieldContext
dests []chan graphql.ResolveResult
}
// Batch batches up the resolver invocations into a single call. As queries are executed, whenever
// resolution gets "stuck", all pending batch resolvers will be triggered concurrently. Batch
// resolvers must return one result for every field context it receives.
func Batch(f func([]graphql.FieldContext) []graphql.ResolveResult) func(graphql.FieldContext) (interface{}, error) {
var x int
key := &x
return func(ctx graphql.FieldContext) (interface{}, error) {
apiRequest := ctxAPIRequest(ctx.Context)
b, ok := apiRequest.batches[key]
if !ok {
b = &batch{
resolver: f,
}
if apiRequest.batches == nil {
apiRequest.batches = map[*int]*batch{}
}
apiRequest.batches[key] = b
}
ch := make(graphql.ResolvePromise, 1)
b.items = append(b.items, ctx)
b.dests = append(b.dests, ch)
return ch, nil
}
}
// ServeGraphQL serves GraphQL HTTP requests. Requests may be GET requests using query string
// parameters or POST requests with either the application/json or application/graphql content type.
func (api *API) ServeGraphQL(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), apiContextKey, api)
apiRequest := &apiRequest{}
ctx = context.WithValue(ctx, apiRequestContextKey, apiRequest)
r = r.WithContext(ctx)
req, code, err := graphql.NewRequestFromHTTP(r)
if err != nil {
http.Error(w, err.Error(), code)
return
}
req.Schema = api.schema
req.IdleHandler = apiRequest.IdleHandler
if api.config.Features != nil {
req.Features = api.config.Features(ctx)
}
execute := func(req *graphql.Request) *graphql.Response {
var info RequestInfo
if doc, errs := graphql.ParseAndValidate(req.Query, req.Schema, req.Features, req.ValidateCost(-1, &info.Cost, api.config.DefaultFieldCost)); len(errs) > 0 {
return &graphql.Response{
Errors: errs,
}
} else {
req.Document = doc
return api.execute(req, &info)
}
}
if storage := api.config.PersistedQueryStorage; storage != nil {
execute = PersistedQueryExtension(storage, execute)
}
body, err := jsoniter.Marshal(execute(req))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", strconv.Itoa(len(body)))
w.Write(body)
}
func isNil(v interface{}) bool {
if v == nil {
return true
}
rv := reflect.ValueOf(v)
return (rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Interface) && rv.IsNil()
}