-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathquery.go
263 lines (227 loc) · 8.04 KB
/
query.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
/*
* Copyright 2019 Dgraph Labs, Inc. and Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package resolve
import (
"context"
"encoding/json"
"errors"
"strconv"
"github.com/golang/glog"
otrace "go.opencensus.io/trace"
dgoapi "github.com/dgraph-io/dgo/v200/protos/api"
"github.com/dgraph-io/dgraph/gql"
"github.com/dgraph-io/dgraph/graphql/dgraph"
"github.com/dgraph-io/dgraph/graphql/schema"
"github.com/dgraph-io/dgraph/x"
)
var errNotScalar = errors.New("provided value is not a scalar, can't convert it to string")
// A QueryResolver can resolve a single query.
type QueryResolver interface {
Resolve(ctx context.Context, query schema.Query) *Resolved
}
// A QueryRewriter can build a Dgraph gql.GraphQuery from a GraphQL query,
type QueryRewriter interface {
Rewrite(ctx context.Context, q schema.Query) ([]*gql.GraphQuery, error)
}
// QueryResolverFunc is an adapter that allows to build a QueryResolver from
// a function. Based on the http.HandlerFunc pattern.
type QueryResolverFunc func(ctx context.Context, query schema.Query) *Resolved
// Resolve calls qr(ctx, query)
func (qr QueryResolverFunc) Resolve(ctx context.Context, query schema.Query) *Resolved {
return qr(ctx, query)
}
// NewQueryResolver creates a new query resolver. The resolver runs the pipeline:
// 1) rewrite the query using qr (return error if failed)
// 2) execute the rewritten query with ex (return error if failed)
func NewQueryResolver(qr QueryRewriter, ex DgraphExecutor) QueryResolver {
return &queryResolver{queryRewriter: qr, executor: ex, resultCompleter: CompletionFunc(noopCompletion)}
}
// NewEntitiesQueryResolver ...
func NewEntitiesQueryResolver(qr QueryRewriter, ex DgraphExecutor) QueryResolver {
return &queryResolver{queryRewriter: qr, executor: ex, resultCompleter: CompletionFunc(entitiesCompletion)}
}
// a queryResolver can resolve a single GraphQL query field.
type queryResolver struct {
queryRewriter QueryRewriter
executor DgraphExecutor
resultCompleter ResultCompleter
}
func (qr *queryResolver) Resolve(ctx context.Context, query schema.Query) *Resolved {
span := otrace.FromContext(ctx)
stop := x.SpanTimer(span, "resolveQuery")
defer stop()
resolverTrace := &schema.ResolverTrace{
Path: []interface{}{query.ResponseName()},
ParentType: "Query",
FieldName: query.ResponseName(),
ReturnType: query.Type().String(),
}
timer := newtimer(ctx, &resolverTrace.OffsetDuration)
timer.Start()
defer timer.Stop()
resolved := qr.rewriteAndExecute(ctx, query)
qr.resultCompleter.Complete(ctx, resolved)
resolverTrace.Dgraph = resolved.Extensions.Tracing.Execution.Resolvers[0].Dgraph
resolved.Extensions.Tracing.Execution.Resolvers[0] = resolverTrace
return resolved
}
func (qr *queryResolver) rewriteAndExecute(ctx context.Context, query schema.Query) *Resolved {
dgraphQueryDuration := &schema.LabeledOffsetDuration{Label: "query"}
ext := &schema.Extensions{
Tracing: &schema.Trace{
Execution: &schema.ExecutionTrace{
Resolvers: []*schema.ResolverTrace{
{Dgraph: []*schema.LabeledOffsetDuration{dgraphQueryDuration}},
},
},
},
}
emptyResult := func(err error) *Resolved {
return &Resolved{
// all the auto-generated queries are nullable, but users may define queries with
// @custom(dql: ...) which may be non-nullable. So, we need to set the Data field
// only if the query was nullable and keep it nil if it was non-nullable.
// query.NullResponse() method handles that.
Data: query.NullResponse(),
Field: query,
Err: schema.SetPathIfEmpty(err, query.ResponseName()),
Extensions: ext,
}
}
dgQuery, err := qr.queryRewriter.Rewrite(ctx, query)
if err != nil {
return emptyResult(schema.GQLWrapf(err, "couldn't rewrite query %s",
query.ResponseName()))
}
qry := dgraph.AsString(dgQuery)
queryTimer := newtimer(ctx, &dgraphQueryDuration.OffsetDuration)
queryTimer.Start()
resp, err := qr.executor.Execute(ctx, &dgoapi.Request{Query: qry, ReadOnly: true}, query)
queryTimer.Stop()
if err != nil && !x.IsGqlErrorList(err) {
err = schema.GQLWrapf(err, "Dgraph query failed")
glog.Infof("Dgraph query execution failed : %s", err)
}
ext.TouchedUids = resp.GetMetrics().GetNumUids()[touchedUidsKey]
resolved := &Resolved{
Data: resp.GetJson(),
Field: query,
Err: schema.SetPathIfEmpty(err, query.ResponseName()),
Extensions: ext,
}
return resolved
}
func NewCustomDQLQueryResolver(ex DgraphExecutor) QueryResolver {
return &customDQLQueryResolver{executor: ex}
}
type customDQLQueryResolver struct {
executor DgraphExecutor
}
func (qr *customDQLQueryResolver) Resolve(ctx context.Context, query schema.Query) *Resolved {
span := otrace.FromContext(ctx)
stop := x.SpanTimer(span, "resolveCustomDQLQuery")
defer stop()
resolverTrace := &schema.ResolverTrace{
Path: []interface{}{query.ResponseName()},
ParentType: "Query",
FieldName: query.ResponseName(),
ReturnType: query.Type().String(),
}
timer := newtimer(ctx, &resolverTrace.OffsetDuration)
timer.Start()
defer timer.Stop()
resolved := qr.rewriteAndExecute(ctx, query)
resolverTrace.Dgraph = resolved.Extensions.Tracing.Execution.Resolvers[0].Dgraph
resolved.Extensions.Tracing.Execution.Resolvers[0] = resolverTrace
return resolved
}
func (qr *customDQLQueryResolver) rewriteAndExecute(ctx context.Context,
query schema.Query) *Resolved {
dgraphQueryDuration := &schema.LabeledOffsetDuration{Label: "query"}
ext := &schema.Extensions{
Tracing: &schema.Trace{
Execution: &schema.ExecutionTrace{
Resolvers: []*schema.ResolverTrace{
{Dgraph: []*schema.LabeledOffsetDuration{dgraphQueryDuration}},
},
},
},
}
emptyResult := func(err error) *Resolved {
resolved := EmptyResult(query, err)
resolved.Extensions = ext
return resolved
}
dgQuery := query.DQLQuery()
args := query.Arguments()
vars := make(map[string]string)
for k, v := range args {
// dgoapi.Request{}.Vars accepts only string values for variables,
// so need to convert all variable values to string
vStr, err := convertScalarToString(v)
if err != nil {
return emptyResult(schema.GQLWrapf(err, "couldn't convert argument %s to string", k))
}
// the keys in dgoapi.Request{}.Vars are assumed to be prefixed with $
vars["$"+k] = vStr
}
queryTimer := newtimer(ctx, &dgraphQueryDuration.OffsetDuration)
queryTimer.Start()
resp, err := qr.executor.Execute(ctx, &dgoapi.Request{Query: dgQuery, Vars: vars,
ReadOnly: true}, nil)
queryTimer.Stop()
if err != nil {
return emptyResult(schema.GQLWrapf(err, "Dgraph query failed"))
}
ext.TouchedUids = resp.GetMetrics().GetNumUids()[touchedUidsKey]
var respJson map[string]interface{}
if err = schema.Unmarshal(resp.Json, &respJson); err != nil {
return emptyResult(schema.GQLWrapf(err, "couldn't unmarshal Dgraph result"))
}
resolved := DataResult(query, respJson, nil)
resolved.Extensions = ext
return resolved
}
func resolveIntrospection(ctx context.Context, q schema.Query) *Resolved {
data, err := schema.Introspect(q)
return &Resolved{
Data: data,
Field: q,
Err: err,
}
}
// converts scalar values received from GraphQL arguments to go string
// If it is a scalar only possible cases are: string, bool, int64, float64 and nil.
func convertScalarToString(val interface{}) (string, error) {
var str string
switch v := val.(type) {
case string:
str = v
case bool:
str = strconv.FormatBool(v)
case int64:
str = strconv.FormatInt(v, 10)
case float64:
str = strconv.FormatFloat(v, 'f', -1, 64)
case json.Number:
str = v.String()
case nil:
str = ""
default:
return "", errNotScalar
}
return str, nil
}