-
Notifications
You must be signed in to change notification settings - Fork 1
/
resolver.go
1709 lines (1506 loc) · 47.5 KB
/
resolver.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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package yarql
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"mime/multipart"
"reflect"
"strconv"
"time"
"unsafe"
"github.com/mjarkk/yarql/bytecode"
"github.com/mjarkk/yarql/helpers"
"github.com/valyala/fastjson"
)
// Ctx contains all runtime information of a query
type Ctx struct {
// private
schema *Schema
query bytecode.ParserCtx
charNr int
context *context.Context
path []byte
getFormFile func(key string) (*multipart.FileHeader, error) // Get form file to support file uploading
operatorHasArguments bool
operatorArgumentsStartAt int
tracingEnabled bool
tracing *tracer
prefRecordingStartTime time.Time
rawVariables string
variablesParsed bool // the rawVariables are parsed into variables
variablesJSONParser *fastjson.Parser // Used to parse the variables
variables *fastjson.Value // Parsed variables, only use this if variablesParsed == true
// Zero alloc values
reflectValues [256]reflect.Value
currentReflectValueIdx uint8
funcInputs []reflect.Value
ctxReflection reflect.Value // ptr to the value
// public / kinda public fields
values *map[string]interface{} // API User values, user can put all their shitty things in here like poems or tax papers
}
func newCtx(s *Schema) *Ctx {
ctx := &Ctx{
schema: s,
query: *bytecode.NewParserCtx(),
charNr: 0,
reflectValues: [256]reflect.Value{},
currentReflectValueIdx: 0,
variablesJSONParser: &fastjson.Parser{},
tracing: newTracer(),
}
ctx.ctxReflection = reflect.ValueOf(ctx)
return ctx
}
func (ctx *Ctx) getGoValue() reflect.Value {
return ctx.reflectValues[ctx.currentReflectValueIdx]
}
func (ctx *Ctx) setNextGoValue(value reflect.Value) {
ctx.currentReflectValueIdx++
ctx.setGoValue(value)
}
func (ctx *Ctx) setGoValue(value reflect.Value) {
ctx.reflectValues[ctx.currentReflectValueIdx] = value
}
// GetValue returns a user defined value
func (ctx *Ctx) GetValue(key string) (value interface{}) {
if ctx.values == nil {
return nil
}
return (*ctx.values)[key]
}
// GetValueOk returns a user defined value with a boolean indicating if the value was found
func (ctx *Ctx) GetValueOk(key string) (value interface{}, found bool) {
if ctx.values == nil {
return nil, false
}
val, ok := (*ctx.values)[key]
return val, ok
}
// SetValue sets a user defined value
func (ctx *Ctx) SetValue(key string, value interface{}) {
if ctx.values == nil {
ctx.values = &map[string]interface{}{
key: value,
}
} else {
(*ctx.values)[key] = value
}
}
// GetContext returns the Go request context
func (ctx *Ctx) GetContext() context.Context {
if ctx.context == nil {
return nil
}
return *ctx.context
}
// SetContext overwrites the request's Go context
func (ctx *Ctx) SetContext(newContext context.Context) {
if newContext == nil {
ctx.context = nil
} else if ctx == nil {
ctx.context = &newContext
} else {
*ctx.context = newContext
}
}
// GetPath returns the graphql path to the current field json encoded
func (ctx *Ctx) GetPath() json.RawMessage {
if len(ctx.path) == 0 {
return []byte("[]")
}
return append(append([]byte{'['}, ctx.path[1:]...), ']')
}
func (ctx *Ctx) write(b []byte) {
ctx.schema.Result = append(ctx.schema.Result, b...)
}
func (ctx *Ctx) writeByte(b byte) {
ctx.schema.Result = append(ctx.schema.Result, b)
}
func (ctx *Ctx) writeQuoted(b []byte) {
ctx.writeByte('"')
ctx.write(b)
ctx.writeByte('"')
}
var nullBytes = []byte("null")
func (ctx *Ctx) writeNull() {
ctx.write(nullBytes)
}
// ResolveOptions are options for the (*Schema).Resolve method
type ResolveOptions struct {
NoMeta bool // Returns only the data
Context context.Context // Request context
OperatorTarget string
Values *map[string]interface{} // Passed directly to the request context
GetFormFile func(key string) (*multipart.FileHeader, error) // Get form file to support file uploading
Variables string // Expects valid JSON or empty string
Tracing bool // https://github.com/apollographql/apollo-tracing
}
// Resolve resolves a query and returns errors if any
// The result json is written to (*Schema).Result
func (s *Schema) Resolve(query []byte, opts ResolveOptions) []error {
if !s.parsed {
fmt.Println("CALL (*yarql.Schema).Parse() before resolve")
return []error{errors.New("invalid setup")}
}
s.Result = s.Result[:0]
ctx := s.ctx
*ctx = Ctx{
schema: ctx.schema,
query: ctx.query,
charNr: 0,
context: nil,
path: ctx.path[:0],
getFormFile: opts.GetFormFile,
rawVariables: opts.Variables,
variablesParsed: false,
variablesJSONParser: ctx.variablesJSONParser,
variables: ctx.variables,
tracingEnabled: opts.Tracing,
tracing: ctx.tracing,
prefRecordingStartTime: ctx.prefRecordingStartTime,
ctxReflection: ctx.ctxReflection,
reflectValues: ctx.reflectValues,
currentReflectValueIdx: 0,
funcInputs: ctx.funcInputs,
values: opts.Values,
}
if opts.Tracing {
ctx.tracing.reset()
}
if opts.Context != nil {
ctx.context = &opts.Context
}
ctx.startTrace()
ctx.query.Query = append(ctx.query.Query[:0], query...)
if len(opts.OperatorTarget) > 0 {
ctx.query.ParseQueryToBytecode(&opts.OperatorTarget)
} else {
ctx.query.ParseQueryToBytecode(nil)
}
if ctx.tracingEnabled {
// finish parsing trace
ctx.finishTrace(func(offset, duration int64) {
ctx.tracing.Parsing.StartOffset = offset
ctx.tracing.Parsing.Duration = duration
})
// Set the validation prop
ctx.tracing.Validation.StartOffset = time.Now().Sub(ctx.prefRecordingStartTime).Nanoseconds()
}
if !opts.NoMeta {
ctx.write([]byte(`{"data":`))
}
if len(ctx.query.Errors) == 0 {
ctx.charNr = ctx.query.TargetIdx
if ctx.charNr == -1 {
ctx.write([]byte("{}"))
if len(opts.OperatorTarget) > 0 {
ctx.err("no operator with name " + opts.OperatorTarget + " found")
} else {
ctx.err("no operator found")
}
} else {
ctx.writeByte('{')
ctx.resolveOperation()
ctx.writeByte('}')
}
} else {
ctx.write([]byte("{}"))
}
if !opts.NoMeta {
// TODO support custom extensions
// Add errors to output
errsLen := len(ctx.query.Errors)
if errsLen == 0 && !ctx.tracingEnabled {
ctx.write([]byte(`}`))
} else {
if errsLen != 0 {
ctx.write([]byte(`,"errors":[`))
for i, err := range ctx.query.Errors {
if i > 0 {
ctx.writeByte(',')
}
ctx.write([]byte(`{"message":`))
helpers.StringToJSON(err.Error(), &ctx.schema.Result)
errWPath, isErrWPath := err.(ErrorWPath)
if isErrWPath && len(errWPath.path) > 0 {
ctx.write([]byte(`,"path":[`))
ctx.write(errWPath.path)
ctx.writeByte(']')
}
errWLocation, isErrWLocation := err.(bytecode.ErrorWLocation)
if isErrWLocation {
ctx.write([]byte(`,"locations":[{"line":`))
ctx.schema.Result = strconv.AppendUint(ctx.schema.Result, uint64(errWLocation.Line), 10)
ctx.write([]byte(`,"column":`))
ctx.schema.Result = strconv.AppendUint(ctx.schema.Result, uint64(errWLocation.Column), 10)
ctx.write([]byte{'}', ']'})
}
ctx.writeByte('}')
}
ctx.writeByte(']')
}
if ctx.tracingEnabled {
ctx.write([]byte(`,"extensions":{"tracing":`))
ctx.tracing.finish()
tracingJSON, err := json.Marshal(ctx.tracing)
if err == nil {
ctx.write(tracingJSON)
} else {
ctx.writeNull()
}
ctx.write([]byte{'}', '}'})
} else {
ctx.write([]byte(`,"extensions":{}}`))
}
}
}
return ctx.query.Errors
}
// readInst reads the current instruction and increments the charNr
func (ctx *Ctx) readInst() byte {
c := ctx.query.Res[ctx.charNr]
ctx.charNr++
return c
}
func (ctx *Ctx) seekInst() byte {
return ctx.query.Res[ctx.charNr]
}
func (ctx *Ctx) skipInst(num int) {
ctx.charNr += num
}
func (ctx *Ctx) lastInst() byte {
return ctx.query.Res[ctx.charNr-1]
}
// ErrorWPath is an error mesage with a graphql path to the field that created the error
type ErrorWPath struct {
err error
path []byte // a json representation of the path without the [] around it
}
func (e ErrorWPath) Error() string {
return e.err.Error()
}
func (ctx *Ctx) err(msg string) bool {
err := errors.New(msg)
if len(ctx.path) == 0 {
ctx.query.Errors = append(ctx.query.Errors, err)
} else {
copiedPath := make([]byte, len(ctx.path)-1)
copy(copiedPath, ctx.path[1:])
ctx.query.Errors = append(ctx.query.Errors, ErrorWPath{
err: err,
path: copiedPath,
})
}
return true
}
func (ctx *Ctx) errf(msg string, args ...interface{}) bool {
return ctx.err(fmt.Sprintf(msg, args...))
}
func (ctx *Ctx) readUint32(startAt int) uint32 {
data := ctx.query.Res[startAt : startAt+4]
return uint32(data[0]) |
(uint32(data[1]) << 8) |
(uint32(data[2]) << 16) |
(uint32(data[3]) << 24)
}
func (ctx *Ctx) resolveOperation() bool {
ctx.charNr += 2 // read 0, [ActionOperator], [kind]
kind := ctx.readInst()
switch kind {
case bytecode.OperatorQuery:
ctx.reflectValues[0] = ctx.schema.rootQueryValue
case bytecode.OperatorMutation:
ctx.reflectValues[0] = ctx.schema.rootMethodValue
case bytecode.OperatorSubscription:
return ctx.err("subscriptions are not supported")
}
ctx.operatorHasArguments = ctx.readInst() == 't'
directivesCount := ctx.readInst()
if directivesCount > 0 {
// TODO
return ctx.err("operation directives unsupported")
}
for {
// Read name
if ctx.readInst() == 0 {
break
}
}
if ctx.operatorHasArguments {
argumentsLen := ctx.readUint32(ctx.charNr)
// Skip over arguments end location and null byte
ctx.operatorArgumentsStartAt = ctx.charNr + 5
ctx.skipInst(int(argumentsLen) + 5)
}
firstField := true
if kind == bytecode.OperatorMutation {
return ctx.resolveSelectionSet(ctx.schema.rootMethod, 0, &firstField)
}
return ctx.resolveSelectionSet(ctx.schema.rootQuery, 0, &firstField)
}
func (ctx *Ctx) resolveSelectionSet(typeObj *obj, dept uint8, firstField *bool) bool {
for {
switch ctx.readInst() {
case bytecode.ActionEnd:
// End of operator
return false
case bytecode.ActionField:
// Parse field
skipped, criticalErr := ctx.resolveField(typeObj, dept, !*firstField)
if criticalErr {
return criticalErr
}
if !skipped {
*firstField = false
}
case bytecode.ActionSpread:
criticalErr := ctx.resolveSpread(typeObj, dept, firstField)
if criticalErr {
return criticalErr
}
default:
return ctx.err("unsupported operation " + string(ctx.lastInst()))
}
}
}
func (ctx *Ctx) resolveSpread(typeObj *obj, dept uint8, firstField *bool) bool {
isInline := ctx.readInst() == 't'
directivesCount := ctx.readInst()
lenOfDirective := ctx.readUint32(ctx.charNr)
ctx.skipInst(4)
// Read name or on inline fragment the type name
nameStart := ctx.charNr
var endName int
for {
if ctx.readInst() == 0 {
endName = ctx.charNr - 1
break
}
}
nameLen := endName - nameStart
name := ctx.query.Res[nameStart:endName]
if directivesCount != 0 {
location := DirectiveLocationFragment
if isInline {
location = DirectiveLocationFragmentInline
}
for i := uint8(0); i < directivesCount; i++ {
modifer, criticalErr := ctx.resolveDirective(location)
if criticalErr || modifer.Skip {
ctx.charNr = nameStart + int(lenOfDirective) + 1
return criticalErr
}
}
}
if isInline {
if !bytes.Equal(typeObj.typeNameBytes, name) {
ctx.charNr = nameStart + int(lenOfDirective) + 1
return false
}
criticalErr := ctx.resolveSelectionSet(typeObj, dept, firstField)
ctx.charNr++
return criticalErr
}
ctxQueryResLen := len(ctx.query.Res)
for _, location := range ctx.query.FragmentLocations {
fragmentNameStart := location + 1
fragmentNameEnd := fragmentNameStart + nameLen
if fragmentNameEnd >= ctxQueryResLen {
continue
}
if bytes.Equal(ctx.query.Res[fragmentNameStart:fragmentNameEnd], name) {
originalCharNr := ctx.charNr
ctx.charNr = fragmentNameEnd + 1
// Read the type
typeNameStart := ctx.charNr
var typeNameEnd int
for {
if ctx.readInst() == 0 {
typeNameEnd = ctx.charNr - 1
break
}
}
if !bytes.Equal(typeObj.typeNameBytes, ctx.query.Res[typeNameStart:typeNameEnd]) {
ctx.charNr = nameStart + int(lenOfDirective) + 1
return false
}
criticalErr := ctx.resolveSelectionSet(typeObj, dept, firstField)
ctx.charNr = originalCharNr
return criticalErr
}
}
return ctx.err("fragment " + b2s(name) + " not defined")
}
func (ctx *Ctx) resolveField(typeObj *obj, dept uint8, addCommaBefore bool) (skipped bool, criticalErr bool) {
ctx.startTrace()
directivesCount := ctx.readInst()
fieldLen := ctx.readUint32(ctx.charNr)
ctx.skipInst(4)
nameKey := ctx.readUint32(ctx.charNr)
ctx.skipInst(4)
endOfField := ctx.charNr + int(fieldLen)
// Read field name/alias
aliasLen := int(ctx.readInst())
startOfAlias := ctx.charNr
endOfAlias := startOfAlias + aliasLen
alias := ctx.query.Res[startOfAlias:endOfAlias]
ctx.skipInst(aliasLen)
prefPathLen := len(ctx.path)
ctx.path = append(ctx.path, []byte(`,"`)...)
ctx.path = append(ctx.path, alias...)
ctx.path = append(ctx.path, '"')
// Note that from here on we should restore the path on errors
startOfName := startOfAlias
endOfName := endOfAlias
// If alias is used read the name
lenOfName := ctx.readInst()
if lenOfName != 0 {
startOfName = ctx.charNr
endOfName = startOfName + int(lenOfName)
ctx.skipInst(int(lenOfName))
}
ctx.skipInst(1)
if directivesCount != 0 {
for i := uint8(0); i < directivesCount; i++ {
modifier, criticalErr := ctx.resolveDirective(DirectiveLocationField)
if criticalErr || modifier.Skip {
// Restore the path
ctx.path = ctx.path[:prefPathLen]
ctx.charNr = endOfField + 1
return true, criticalErr
}
// TODO
// if modifier.ModifyOnWriteContent != nil {
// contentModifiers = append(contentModifiers, modifier.ModifyOnWriteContent)
// }
}
}
if addCommaBefore {
ctx.writeByte(',')
}
ctx.writeQuoted(alias)
ctx.writeByte(':')
fieldHasSelection := ctx.seekInst() != 'e'
typeObjField, ok := typeObj.objContents[nameKey]
if !ok {
name := b2s(ctx.query.Res[startOfName:endOfName])
if name == "__typename" {
if fieldHasSelection {
criticalErr = ctx.err("cannot have a selection set on this field")
} else {
ctx.writeQuoted(typeObj.typeNameBytes)
}
} else {
ctx.writeNull()
criticalErr = ctx.errf("%s does not exists on %s", name, typeObj.typeName)
}
} else {
goValue := ctx.getGoValue()
if typeObjField.customObjValue != nil {
ctx.setNextGoValue(*typeObjField.customObjValue)
} else if typeObjField.valueType == valueTypeMethod && typeObjField.method.isTypeMethod {
ctx.setNextGoValue(goValue.Method(typeObjField.structFieldIdx))
} else {
ctx.setNextGoValue(goValue.Field(typeObjField.structFieldIdx))
}
criticalErr = ctx.resolveFieldDataValue(typeObjField, dept, fieldHasSelection)
ctx.currentReflectValueIdx--
if ctx.tracingEnabled {
name := b2s(ctx.query.Res[startOfName:endOfName])
ctx.finishTrace(func(offset, duration int64) {
returnType := bytes.NewBuffer(nil)
ctx.schema.objToQlTypeName(typeObjField, returnType)
ctx.tracing.Execution.Resolvers = append(ctx.tracing.Execution.Resolvers, tracerResolver{
Path: ctx.GetPath(),
ParentType: typeObj.typeName,
FieldName: name,
ReturnType: returnType.String(),
StartOffset: offset,
Duration: duration,
})
})
}
}
// Restore the path
ctx.path = ctx.path[:prefPathLen]
ctx.charNr = endOfField + 1
return false, criticalErr
}
func (ctx *Ctx) callQlMethod(method *objMethod, goValue *reflect.Value, parseArguments bool) ([]reflect.Value, bool) {
ctx.funcInputs = ctx.funcInputs[:0]
for _, in := range method.ins {
if in.isCtx {
ctx.funcInputs = append(ctx.funcInputs, ctx.ctxReflection)
} else {
ctx.funcInputs = append(ctx.funcInputs, reflect.New(*in.goType).Elem())
}
}
if parseArguments {
criticalErr := ctx.walkInputObject(
func(key []byte) bool {
keyStr := b2s(key)
inField, ok := method.inFields[keyStr]
if !ok {
return ctx.err("undefined input: " + keyStr)
}
goField := ctx.funcInputs[inField.inputIdx].Field(inField.input.goFieldIdx)
_, criticalErr := ctx.bindInputToGoValue(&goField, &inField.input, true)
return criticalErr
},
)
if criticalErr {
return nil, criticalErr
}
}
outs := goValue.Call(ctx.funcInputs)
return outs, false
}
func (ctx *Ctx) resolveDirective(location DirectiveLocation) (modifer DirectiveModifier, criticalErr bool) {
ctx.skipInst(1) // read 'd'
hasArguments := ctx.readInst() == 't'
// Read name
nameStart := ctx.charNr
var nameEnd int
for {
if ctx.readInst() == 0 {
nameEnd = ctx.charNr - 1
break
}
}
directiveName := b2s(ctx.query.Res[nameStart:nameEnd])
directives, ok := ctx.schema.definedDirectives[location]
if !ok {
return modifer, ctx.err("unknown directive " + directiveName)
}
var foundDirective *Directive
for _, directive := range directives {
if directive.Name == directiveName {
foundDirective = directive
break
}
}
if foundDirective == nil {
return modifer, ctx.err("unknown directive " + directiveName)
}
method := foundDirective.parsedMethod
outs, criticalErr := ctx.callQlMethod(method, &foundDirective.methodReflection, hasArguments)
if criticalErr {
return modifer, criticalErr
}
modifer = outs[0].Interface().(DirectiveModifier)
return modifer, false
}
func (ctx *Ctx) resolveFieldDataValue(typeObj *obj, dept uint8, hasSubSelection bool) bool {
goValue := ctx.getGoValue()
if ctx.seekInst() == bytecode.ActionValue && typeObj.valueType != valueTypeMethod {
// Check there is no method behind a pointer
resolvedTypeObj := typeObj
for resolvedTypeObj.valueType == valueTypePtr {
resolvedTypeObj = resolvedTypeObj.innerContent
}
if resolvedTypeObj.valueType != valueTypeMethod {
// arguments are not allowed on any other value than methods
ctx.writeNull()
return ctx.err("field arguments not allowed")
}
}
switch typeObj.valueType {
case valueTypeUndefined:
ctx.writeNull()
case valueTypeArray:
// Using unsafe.Pointer(goValue.Pointer()) instead of goValue.isNil as it is faster
if goValue.Kind() == reflect.Slice && unsafe.Pointer(goValue.Pointer()) == nil {
ctx.writeNull()
return false
}
typeObj = typeObj.innerContent
ctx.writeByte('[')
ctx.currentReflectValueIdx++
goValueLen := goValue.Len()
startCharNr := ctx.charNr
for i := 0; i < goValueLen; i++ {
ctx.charNr = startCharNr
prefPathLen := len(ctx.path)
ctx.path = append(ctx.path, ',')
ctx.path = strconv.AppendInt(ctx.path, int64(i), 10)
ctx.setGoValue(goValue.Index(i))
ctx.resolveFieldDataValue(typeObj, dept, hasSubSelection)
if i != goValueLen-1 {
ctx.writeByte(',')
}
ctx.path = ctx.path[:prefPathLen]
}
ctx.currentReflectValueIdx--
ctx.writeByte(']')
case valueTypeObj, valueTypeObjRef:
if !hasSubSelection {
ctx.writeNull()
return ctx.err("must have a selection")
}
var ok bool
if typeObj.valueType == valueTypeObjRef {
typeObj, ok = ctx.schema.types[typeObj.typeName]
if !ok {
ctx.writeNull()
return false
}
}
dept++
if dept == ctx.schema.MaxDepth {
ctx.writeNull()
return ctx.err("reached max dept")
}
ctx.writeByte('{')
isFirstField := true
criticalErr := ctx.resolveSelectionSet(typeObj, dept, &isFirstField)
ctx.writeByte('}')
return criticalErr
case valueTypeData:
if hasSubSelection {
ctx.writeNull()
return ctx.err("cannot have a selection set on this field")
}
if typeObj.isID && typeObj.dataValueType != reflect.String {
// Graphql ID fields are always strings
ctx.writeByte('"')
ctx.valueToJSON(goValue, typeObj.dataValueType)
ctx.writeByte('"')
} else {
ctx.valueToJSON(goValue, typeObj.dataValueType)
}
case valueTypePtr:
if goValue.IsNil() {
ctx.writeNull()
} else {
ctx.reflectValues[ctx.currentReflectValueIdx] = goValue.Elem()
return ctx.resolveFieldDataValue(typeObj.innerContent, dept, hasSubSelection)
}
case valueTypeMethod:
method := typeObj.method
if !method.isTypeMethod && goValue.IsNil() {
ctx.writeNull()
return false
}
outs, criticalErr := ctx.callQlMethod(method, &goValue, ctx.seekInst() == 'v')
if criticalErr {
return criticalErr
}
hasSubSelection = ctx.seekInst() != 'e'
if method.errorOutNr != nil {
errOut := outs[*method.errorOutNr]
if !errOut.IsNil() {
err, ok := errOut.Interface().(error)
if !ok {
ctx.writeNull()
return ctx.err("returned a invalid kind of error")
} else if err != nil {
ctx.err(err.Error())
}
}
}
if ctx.context != nil {
err := (*ctx.context).Err()
if err != nil {
// Context ended
ctx.err(err.Error())
ctx.writeNull()
return false
}
}
ctx.setGoValue(outs[method.outNr])
criticalErr = ctx.resolveFieldDataValue(&method.outType, dept, hasSubSelection)
return criticalErr
case valueTypeEnum:
enum := ctx.schema.definedEnums[typeObj.enumTypeIndex]
switch enum.contentKind {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
underlayingValue := goValue.Int()
for _, entry := range enum.entries {
if entry.value.Int() == underlayingValue {
ctx.writeQuoted(entry.keyBytes)
return false
}
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
underlayingValue := goValue.Uint()
for _, entry := range enum.entries {
if entry.value.Uint() == underlayingValue {
ctx.writeQuoted(entry.keyBytes)
return false
}
}
case reflect.String:
underlayingValue := goValue.String()
for _, entry := range enum.entries {
if entry.value.String() == underlayingValue {
ctx.writeQuoted(entry.keyBytes)
return false
}
}
}
ctx.writeNull()
case valueTypeTime:
timeValue, ok := goValue.Interface().(time.Time)
if ok {
ctx.writeByte('"')
helpers.TimeToIso8601String(&ctx.schema.Result, timeValue)
ctx.writeByte('"')
} else {
ctx.writeNull()
}
case valueTypeInterface, valueTypeInterfaceRef:
if !hasSubSelection {
ctx.writeNull()
return ctx.err("must have a selection")
}
var ok bool
if typeObj.valueType == valueTypeInterfaceRef {
typeObj, ok = ctx.schema.interfaces[typeObj.typeName]
if !ok {
ctx.writeNull()
return false
}
}
if goValue.IsNil() {
ctx.writeNull()
return false
}
if goValue.Kind() == reflect.Interface {
goValue = goValue.Elem()
ctx.setNextGoValue(goValue)
}
goValueType := goValue.Type()
goValueName := goValueType.Name()
goValuePkgPath := goValueType.PkgPath()
// TODO improve performance of the below
for _, implementation := range typeObj.implementations {
if implementation.goTypeName == goValueName && implementation.goPkgPath == goValuePkgPath {
criticalErr := ctx.resolveFieldDataValue(implementation, dept+1, hasSubSelection)
ctx.currentReflectValueIdx--
return criticalErr
}
}
ctx.currentReflectValueIdx--
ctx.writeNull()
}
return false
}
func (ctx *Ctx) findOperatorArgument(nameToFind string) (foundArgument bool) {
if !ctx.operatorHasArguments {
return false
}
ctx.charNr = ctx.operatorArgumentsStartAt
ctx.skipInst(2)
for {
startOfArg := ctx.charNr
if ctx.readInst() == 'e' {
return false
}
argLen := ctx.readUint32(ctx.charNr)
ctx.charNr += 4
nameStart := ctx.charNr
var nameEnd int
for {
if ctx.readInst() == 0 {
nameEnd = ctx.charNr - 1
break
}
}
name := b2s(ctx.query.Res[nameStart:nameEnd])
if name == nameToFind {
return true
}
ctx.charNr = startOfArg + int(argLen) + 1
}
}
func (ctx *Ctx) bindOperatorArgumentTo(goValue *reflect.Value, valueStructure *input, argumentName string) (valueSet bool, criticalErr bool) {
// TODO Check for the required flag (L & N)
// These flags are to identify if the argument is required or not
// TODO the error messages in this function are garbage
resolvedValueStructure := valueStructure
c := ctx.readInst()
for {
if c != 'L' && c != 'l' {
break
}
if resolvedValueStructure.kind != reflect.Slice {
return false, ctx.err("variable $" + argumentName + " cannot be bind to " + resolvedValueStructure.kind.String())
}
resolvedValueStructure = resolvedValueStructure.elem
c = ctx.readInst()
}
if c == 'n' || c == 'N' {
// N = required type
// n = not required type
typeNameStart := ctx.charNr
var typeNameEnd int
for {
if ctx.readInst() == 0 {
typeNameEnd = ctx.charNr - 1
break
}
}
typeName := b2s(ctx.query.Res[typeNameStart:typeNameEnd])
if resolvedValueStructure.isEnum {
enum := ctx.schema.definedEnums[resolvedValueStructure.enumTypeIndex]
if typeName != enum.typeName && typeName != "String" {
return false, ctx.err("expected variable type " + enum.typeName + " but got " + typeName)
}
} else if resolvedValueStructure.isID {
if typeName != "ID" && typeName != "String" {
return false, ctx.err("expected variable type ID but got " + typeName)
}
} else if resolvedValueStructure.isFile {
if typeName != "File" && typeName != "String" {
return false, ctx.err("expected variable type File but got " + typeName)
}
} else if resolvedValueStructure.isTime {
if typeName != "Time" && typeName != "String" {
return false, ctx.err("expected variable type Time but got " + typeName)
}
} else {
switch resolvedValueStructure.kind {