-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
outputnode.go
1574 lines (1410 loc) · 43.3 KB
/
outputnode.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
/*
* Copyright 2017-2018 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 query
import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"unsafe"
gqlSchema "github.com/dgraph-io/dgraph/graphql/schema"
"github.com/golang/glog"
"github.com/pkg/errors"
geom "github.com/twpayne/go-geom"
"github.com/twpayne/go-geom/encoding/geojson"
"github.com/dgraph-io/dgo/v200/protos/api"
"github.com/dgraph-io/dgraph/algo"
"github.com/dgraph-io/dgraph/protos/pb"
"github.com/dgraph-io/dgraph/task"
"github.com/dgraph-io/dgraph/types"
"github.com/dgraph-io/dgraph/types/facets"
"github.com/dgraph-io/dgraph/x"
"github.com/dgraph-io/ristretto/z"
)
// ToJson converts the list of subgraph into a JSON response by calling toFastJSON.
func ToJson(ctx context.Context, l *Latency, sgl []*SubGraph, field gqlSchema.Field) ([]byte,
error) {
sgr := &SubGraph{}
for _, sg := range sgl {
if sg.Params.Alias == "var" || sg.Params.Alias == "shortest" {
continue
}
if sg.Params.GetUid {
sgr.Params.GetUid = true
}
sgr.Children = append(sgr.Children, sg)
}
data, err := sgr.toFastJSON(ctx, l, field)
// don't log or wrap GraphQL errors
if x.IsGqlErrorList(err) {
return data, err
}
if err != nil {
glog.Errorf("while running ToJson: %v\n", err)
}
return data, errors.Wrapf(err, "while running ToJson")
}
// We are capping maxEncoded size to 4GB, as grpc encoding fails
// for a response size > math.MaxUint32.
const maxEncodedSize = uint64(4 << 30)
type encoder struct {
// attrMap has mapping of string predicates to uint16 ids.
// For each predicate one unique id is assigned to save space.
attrMap map[string]uint16
// idSlice contains mapping from predicate id to predicate.
idSlice []string
// arena is used to store scalarVal for fastJsonNodes. Offset of scalarVal inside arena buffer
// is stored in fastJsonNode meta.
arena *arena
// curSize is current estimated size of the encoded response. It should be less than actual
// response size after encoding. If curSize exceeds a threshold size(maxEncodedSize), we return
// query response with error saying response is too big. Currently curSize tracking has been
// kept very simple. curSize is crossing threshold value or not is only checked at leaf(scalar)
// nodes as of now. curSize is updated in following cases:
// 1. By adding predicate len, while expanding it for an uid in preTraverse().
// 2. By adding scalarVal len in setScalarVal function for a leaf(scalar) node.
// TODO(Ashish): currently we are not including facets/groupby/aggregations fields in curSize
// for simplicity. curSize can be made more accurate by adding these fields.
curSize uint64
// Allocator for nodes.
alloc *z.Allocator
// Cache uid attribute, which is very commonly used.
uidAttr uint16
}
type node struct {
// meta stores meta information for a fastJsonNode in an uint64. Layout is as follows.
// Bytes 4-1 contains offset(uint32) for Arena.
// Bytes 7-6 contains attr.
// Bit MSB(first bit in Byte-8) contains list field value.
// Bit SecondMSB(second bit in Byte-8) contains facetsParent field value.
// Bit ThirdMSB(third bit in Byte-8) stores if the node contains uid value
// Bit FourthMSB(fourth bit in Byte-8) stores if the order of node's children has been fixed.
// Bit FifthMSB(fifth bit in Byte-8) stores if node contains value for a @custom GraphQL field.
// Byte-5 is not getting used as of now.
// |-----------------------------------------------------------------------------|
// | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 |
// |-----------------------------------------------------------------------------|
// | MSB - list | | Unused | |
// | SecondMSB - facetsParent | Attr ID | For | Offset inside Arena |
// | ThirdMSB - uid | | Now | |
// | FourthMSB - Order Info | | | |
// | FifthMSB - @custom GraphQL | | | |
// |-----------------------------------------------------------------------------|
meta uint64
next *node
child *node
}
var nodeSize = int(unsafe.Sizeof(node{}))
func newEncoder() *encoder {
idSlice := make([]string, 1)
a := (arenaPool.Get()).(*arena)
a.reset()
e := &encoder{
attrMap: make(map[string]uint16),
idSlice: idSlice,
arena: a,
alloc: z.NewAllocator(4 << 10),
}
e.uidAttr = e.idForAttr("uid")
return e
}
func (enc *encoder) idForAttr(attr string) uint16 {
if attr == "uid" && enc.uidAttr > 0 {
return enc.uidAttr
}
if id, ok := enc.attrMap[attr]; ok {
return id
}
enc.idSlice = append(enc.idSlice, attr)
enc.attrMap[attr] = uint16(len(enc.idSlice) - 1) // TODO(Ashish): check for overflow.
return uint16(len(enc.idSlice) - 1)
}
func (enc *encoder) attrForID(id uint16) string {
// For now we are not returning error from here.
if id == 0 || id >= uint16(len(enc.idSlice)) {
return ""
}
return enc.idSlice[id]
}
// makeScalarNode returns a fastJsonNode with all of its meta data, scalarVal populated.
func (enc *encoder) makeScalarNode(attr uint16, val []byte, list bool) (fastJsonNode, error) {
fj := enc.newNode(attr)
if err := enc.setScalarVal(fj, val); err != nil {
return nil, err
}
enc.setList(fj, list)
return fj, nil
}
func (enc *encoder) makeUidNode(attr uint16, uid uint64) (*node, error) {
fj := enc.newNode(attr)
fj.meta |= uidNodeBit
var tmp [8]byte
binary.BigEndian.PutUint64(tmp[:], uid)
if err := enc.setScalarVal(fj, tmp[:]); err != nil {
return nil, err
}
return fj, nil
}
// makeCustomNode returns a fastJsonNode that stores the given val for a @custom GraphQL field.
func (enc *encoder) makeCustomNode(attr uint16, val []byte) (fastJsonNode, error) {
fj := enc.newNode(attr)
if err := enc.setScalarVal(fj, val); err != nil {
return nil, err
}
enc.setCustom(fj)
return fj, nil
}
const (
// Value with most significant bit set to 1.
listBit = 1 << 63
// Value with second most significant bit set to 1.
facetsBit = 1 << 62
// Value with third most significant bit set to 1.
uidNodeBit = 1 << 61
// Node has been visited for fixing the children order.
visitedBit = 1 << 60
// customBit is a value with fifth most significant bit set to 1. If a node has customBit set
// in its meta, it means that node stores the value for a @custom GraphQL field.
customBit = 1 << 59
// Value with all bits set to 1 for bytes 7 and 6.
setBytes76 = uint64(0x00FFFF0000000000)
// Compliment value of setBytes76.
unsetBytes76 = uint64(^setBytes76)
// Value with all bits set to 1 for bytes 4 to 1.
setBytes4321 = 0x00000000FFFFFFFF
)
// fastJsonNode represents node of a tree, which is formed to convert a subgraph into json response
// for a query. A fastJsonNode has following meta data:
// 1. Attr => predicate associated with this node.
// 2. ScalarVal => Any value associated with node, if it is a leaf node.
// 3. List => Stores boolean value, true if this node is part of list.
// 4. FacetsParent => Stores boolean value, true if this node is a facetsParent. facetsParent is
// node which is parent for facets values for a scalar list predicate. Eg: node "city|country"
// will have FacetsParent value as true.
// {
// "city": ["Bengaluru", "San Francisco"],
// "city|country": {
// "0": "india",
// "1": "US"
// }
// }
// 5. Children(Attrs) => List of all children.
// 6. Visited => Stores boolen values, true if node has been visited for fixing children's order.
//
// All of the data for fastJsonNode tree is stored in encoder to optimise memory usage. fastJsonNode
// struct is pointer to node object. node object stores below information.
// 1. meta information.
// 2. Pointer to its first child.
// 3. Pointer to its sibling.
type fastJsonNode *node
// newNode returns a fastJsonNode with its attr set to attr,
// and all other meta set to their default value.
func (enc *encoder) newNode(attr uint16) fastJsonNode {
b := enc.alloc.AllocateAligned(nodeSize)
n := (*node)(unsafe.Pointer(&b[0]))
enc.setAttr(n, attr)
return n
}
func (enc *encoder) setAttr(fj fastJsonNode, attr uint16) {
// There can be some cases where we change name of attr for fastJsoNode and
// hence first clear the existing attr, then store new one.
fj.meta &= unsetBytes76
fj.meta |= (uint64(attr) << 40)
}
func (enc *encoder) setScalarVal(fj fastJsonNode, sv []byte) error {
offset, err := enc.arena.put(sv)
if err != nil {
return err
}
fj.meta |= uint64(offset)
// Also increase curSize.
enc.curSize += uint64(len(sv))
if size := uint64(enc.alloc.Size()) + enc.curSize; size > maxEncodedSize {
return fmt.Errorf("estimated response size: %d is bigger than threshold: %d",
size, maxEncodedSize)
}
return nil
}
func (enc *encoder) setList(fj fastJsonNode, list bool) {
if list {
fj.meta |= listBit
} else {
fj.meta &^= listBit
}
}
func (enc *encoder) setVisited(fj fastJsonNode, visited bool) {
if visited {
fj.meta |= visitedBit
} else {
fj.meta &^= visitedBit
}
}
func (enc *encoder) setFacetsParent(fj fastJsonNode) {
fj.meta |= facetsBit
}
func (enc *encoder) setCustom(fj fastJsonNode) {
fj.meta |= customBit
}
func (enc *encoder) appendAttrs(fj, child fastJsonNode) {
enc.addChildren(fj, child)
}
// addChildren appends attrs to existing fj's attrs.
func (enc *encoder) addChildren(fj, head fastJsonNode) {
if fj.child == nil {
fj.child = head
return
}
tail := head
for tail.next != nil {
tail = tail.next
}
// We're inserting the node in between. This would need to be fixed later via fixOrder.
// Single child additions:
// Child 1
// Child 2 -> 1
// Child 3 -> 2 -> 1
// Child 4 -> 3 -> 2 -> 1
// Child 5 -> 4 -> 3 -> 2 -> 1
//
// If child has siblings, then it could look like this.
// addChildren(13 -> 12 -> 11)
// Child 5 -> 4 -> 3 -> 2 -> 1
//
// What we want:
// 13 -> 12 -> 11 -> 5 -> 4 -> 3 -> 2 -> 1
fj.child, tail.next = head, fj.child
}
// fixOrder would recursively fix the ordering issue caused by addChildren, across the entire
// tree.
// fixOrder would fix the order from
// 5 -> 4 -> 3 -> 2 -> 1 to
// 1 -> 2 -> 3 -> 4 -> 5
func (enc *encoder) fixOrder(fj fastJsonNode) {
// If you call this again on the same fastJsonNode, then this would become wrong. Due to
// children being copied over, the same node can be referenced by multiple nodes. Thus, the node
// would be visited again, it would be fixed multiple times, causing ordering issue.
// To avoid this, we keep track of the node by marking it.
if (fj.meta & visitedBit) > 0 {
return
}
enc.setVisited(fj, true)
tail := fj.child // This is node 5 in the chain mentioned above.
// Edge cases: Child is nil, or only child.
if tail == nil {
return
}
if tail.next == nil {
enc.fixOrder(tail)
return
}
left, right := tail, tail.next // Left is 5, right is 4.
left.next = nil // Make left the last child.
for right != nil {
next := right.next // right of ptr2 (points to 3)
right.next = left // ptr2 now points left to ptr1 (4 -> 5)
left, right = right, next // Advance both pointers (left = 4, right = 3 and so on)
}
// left is now pointing to 1.
fj.child = left // Child is now pointed to 1.
// Now recurse to fix up all children.
child := fj.child
for child != nil {
enc.fixOrder(child)
child = child.next
}
}
func (enc *encoder) getAttr(fj fastJsonNode) uint16 {
return uint16((fj.meta & setBytes76) >> 40)
}
func (enc *encoder) getScalarVal(fj fastJsonNode) ([]byte, error) {
offset := uint32(fj.meta & setBytes4321)
data, err := enc.arena.get(offset)
if err != nil {
return nil, err
}
if (fj.meta & uidNodeBit) > 0 {
uid := binary.BigEndian.Uint64(data)
return x.ToHex(uid, false), nil
}
return data, nil
}
func (enc *encoder) getList(fj fastJsonNode) bool {
return (fj.meta & listBit) > 0
}
func (enc *encoder) getFacetsParent(fj fastJsonNode) bool {
return (fj.meta & facetsBit) > 0
}
func (enc *encoder) getCustom(fj fastJsonNode) bool {
return (fj.meta & customBit) > 0
}
func (enc *encoder) children(fj fastJsonNode) fastJsonNode {
// Return nil if no attrs are found.
return fj.child
}
func (enc *encoder) AddValue(fj fastJsonNode, attr uint16, v types.Val) error {
return enc.AddListValue(fj, attr, v, false)
}
func (enc *encoder) AddListValue(fj fastJsonNode, attr uint16, v types.Val, list bool) error {
bs, err := valToBytes(v)
if err != nil {
return nil // Ignore this.
}
sn, err := enc.makeScalarNode(attr, bs, list)
if err != nil {
return err
}
enc.addChildren(fj, sn)
return nil
}
func (enc *encoder) AddMapChild(fj, val fastJsonNode) {
var childNode fastJsonNode
child := enc.children(fj)
for child != nil {
if enc.getAttr(child) == enc.getAttr(val) {
childNode = child
break
}
child = child.next
}
if childNode == nil {
enc.addChildren(fj, val)
} else {
enc.addChildren(childNode, enc.children(val))
}
}
func (enc *encoder) AddListChild(fj, child fastJsonNode) {
enc.setList(child, true)
enc.addChildren(fj, child)
}
func (enc *encoder) SetUID(fj fastJsonNode, uid uint64, attr uint16) error {
// if we're in debug mode, uid may be added second time, skip this
if attr == enc.uidAttr {
fjAttrs := enc.children(fj)
for fjAttrs != nil {
if enc.getAttr(fjAttrs) == attr {
return nil
}
fjAttrs = fjAttrs.next
}
}
un, err := enc.makeUidNode(attr, uid)
if err != nil {
return err
}
enc.addChildren(fj, un)
return nil
}
func (enc *encoder) IsEmpty(fj fastJsonNode) bool {
return fj.child == nil
}
var (
boolTrue = []byte("true")
boolFalse = []byte("false")
// Below variables are used in stringJsonMarshal function.
bufferPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
hex = "0123456789abcdef"
escapeHTML = true
)
// stringJsonMarshal is replacement for json.Marshal() function only for string type.
// This function is encodeState.string(string, escapeHTML) in "encoding/json/encode.go".
// It should be in sync with encodeState.string function.
func stringJsonMarshal(s string) []byte {
e := bufferPool.Get().(*bytes.Buffer)
e.Reset()
e.WriteByte('"')
start := 0
for i := 0; i < len(s); {
if b := s[i]; b < utf8.RuneSelf {
if htmlSafeSet[b] || (!escapeHTML && safeSet[b]) {
i++
continue
}
if start < i {
e.WriteString(s[start:i])
}
e.WriteByte('\\')
switch b {
case '\\', '"':
e.WriteByte(b)
case '\n':
e.WriteByte('n')
case '\r':
e.WriteByte('r')
case '\t':
e.WriteByte('t')
default:
// This encodes bytes < 0x20 except for \t, \n and \r.
// If escapeHTML is set, it also escapes <, >, and &
// because they can lead to security holes when
// user-controlled strings are rendered into JSON
// and served to some browsers.
e.WriteString(`u00`)
e.WriteByte(hex[b>>4])
e.WriteByte(hex[b&0xF])
}
i++
start = i
continue
}
c, size := utf8.DecodeRuneInString(s[i:])
if c == utf8.RuneError && size == 1 {
if start < i {
e.WriteString(s[start:i])
}
e.WriteString(`\ufffd`)
i += size
start = i
continue
}
// U+2028 is LINE SEPARATOR.
// U+2029 is PARAGRAPH SEPARATOR.
// They are both technically valid characters in JSON strings,
// but don't work in JSONP, which has to be evaluated as JavaScript,
// and can lead to security holes there. It is valid JSON to
// escape them, so we do so unconditionally.
// See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion.
if c == '\u2028' || c == '\u2029' {
if start < i {
e.WriteString(s[start:i])
}
e.WriteString(`\u202`)
e.WriteByte(hex[c&0xF])
i += size
start = i
continue
}
i += size
}
if start < len(s) {
e.WriteString(s[start:])
}
e.WriteByte('"')
buf := append([]byte(nil), e.Bytes()...)
bufferPool.Put(e)
return buf
}
func valToBytes(v types.Val) ([]byte, error) {
switch v.Tid {
case types.StringID, types.DefaultID:
switch str := v.Value.(type) {
case string:
return stringJsonMarshal(str), nil
default:
return json.Marshal(str)
}
case types.BinaryID:
return []byte(fmt.Sprintf("%q", v.Value)), nil
case types.IntID:
// In types.Convert(), we always convert to int64 for IntID type. fmt.Sprintf is slow
// and hence we are using strconv.FormatInt() here. Since int64 and int are most common int
// types we are using FormatInt for those.
switch num := v.Value.(type) {
case int64:
return []byte(strconv.FormatInt(num, 10)), nil
case int:
return []byte(strconv.FormatInt(int64(num), 10)), nil
default:
return []byte(fmt.Sprintf("%d", v.Value)), nil
}
case types.FloatID:
f, fOk := v.Value.(float64)
// +Inf, -Inf and NaN are not representable in JSON.
// Please see https://golang.org/src/encoding/json/encode.go?s=6458:6501#L573
if !fOk || math.IsInf(f, 0) || math.IsNaN(f) {
return nil, errors.New("Unsupported floating point number in float field")
}
return []byte(fmt.Sprintf("%f", f)), nil
case types.BoolID:
if v.Value.(bool) {
return boolTrue, nil
}
return boolFalse, nil
case types.DateTimeID:
t := v.Value.(time.Time)
return t.MarshalJSON()
case types.GeoID:
return geojson.Marshal(v.Value.(geom.T))
case types.UidID:
return []byte(fmt.Sprintf("\"%#x\"", v.Value)), nil
case types.PasswordID:
return []byte(fmt.Sprintf("%q", v.Value.(string))), nil
default:
return nil, errors.New("Unsupported types.Val.Tid")
}
}
func (enc *encoder) writeKey(fj fastJsonNode, out *bytes.Buffer) error {
if _, err := out.WriteRune('"'); err != nil {
return err
}
attrID := enc.getAttr(fj)
if _, err := out.WriteString(enc.attrForID(attrID)); err != nil {
return err
}
if _, err := out.WriteRune('"'); err != nil {
return err
}
if _, err := out.WriteRune(':'); err != nil {
return err
}
return nil
}
func (enc *encoder) attachFacets(fj fastJsonNode, fieldName string, isList bool,
fList []*api.Facet, facetIdx int) error {
idxFieldID := enc.idForAttr(strconv.Itoa(facetIdx))
for _, f := range fList {
fName := facetName(fieldName, f)
fVal, err := facets.ValFor(f)
if err != nil {
return err
}
if !isList {
if err := enc.AddValue(fj, enc.idForAttr(fName), fVal); err != nil {
return err
}
} else {
facetNode := enc.newNode(enc.idForAttr(fName))
err := enc.AddValue(facetNode, idxFieldID, fVal)
if err != nil {
return err
}
// Mark this node as facetsParent.
enc.setFacetsParent(facetNode)
enc.AddMapChild(fj, facetNode)
}
}
return nil
}
func (enc *encoder) encode(fj fastJsonNode, out *bytes.Buffer) error {
child := enc.children(fj)
// This is a scalar value.
if child == nil {
val, err := enc.getScalarVal(fj)
if err != nil {
return err
}
_, err = out.Write(val)
return err
}
// This is an internal node.
if _, err := out.WriteRune('{'); err != nil {
return err
}
cnt := 0
var cur, next fastJsonNode
for child != nil {
cnt++
validNext := false
cur = child
if cur.next != nil {
next = cur.next
validNext = true
}
if validNext && enc.getAttr(cur) == enc.getAttr(next) {
if cnt == 1 {
if err := enc.writeKey(cur, out); err != nil {
return err
}
if _, err := out.WriteRune('['); err != nil {
return err
}
}
if err := enc.encode(cur, out); err != nil {
return err
}
} else {
if cnt == 1 {
if err := enc.writeKey(cur, out); err != nil {
return err
}
if enc.getList(cur) {
if _, err := out.WriteRune('['); err != nil {
return err
}
}
}
if err := enc.encode(cur, out); err != nil {
return err
}
if cnt > 1 || enc.getList(cur) {
if _, err := out.WriteRune(']'); err != nil {
return err
}
}
cnt = 0 // Reset the count.
}
// We need to print comma except for the last attribute.
if child.next != nil {
if _, err := out.WriteRune(','); err != nil {
return err
}
}
child = child.next
}
if _, err := out.WriteRune('}'); err != nil {
return err
}
return nil
}
func (enc *encoder) copyFastJsonList(fj fastJsonNode) (fastJsonNode, int) {
if fj == nil {
return fj, 0
}
var head, tail fastJsonNode
nodeCount := 0
for fj != nil {
nodeCount++
nn := enc.copySingleNode(fj)
if tail == nil {
head, tail = nn, nn
fj = fj.next
continue
}
tail.next = nn
fj, tail = fj.next, tail.next
}
return head, nodeCount
}
func (enc *encoder) copySingleNode(fj fastJsonNode) fastJsonNode {
if fj == nil {
return nil
}
nn := enc.newNode(enc.getAttr(fj))
nn.meta = fj.meta
nn.child = fj.child
nn.next = nil
return nn
}
func (enc *encoder) merge(parent, child []fastJsonNode) ([]fastJsonNode, error) {
if len(parent) == 0 {
return child, nil
}
// Here we merge two slices of maps.
mergedList := make([]fastJsonNode, 0)
cnt := 0
for _, pa := range parent {
for _, ca := range child {
paCopy, paNodeCount := enc.copyFastJsonList(pa)
caCopy, caNodeCount := enc.copyFastJsonList(ca)
cnt += paNodeCount + caNodeCount
if cnt > x.Config.NormalizeNodeLimit {
return nil, errors.Errorf(
"Couldn't evaluate @normalize directive - too many results")
}
if paCopy == nil {
paCopy = caCopy
} else {
temp := paCopy
for temp.next != nil {
temp = temp.next
}
temp.next = caCopy
}
mergedList = append(mergedList, paCopy)
}
}
return mergedList, nil
}
// normalize returns all attributes of fj and its children (if any).
func (enc *encoder) normalize(fj fastJsonNode) ([]fastJsonNode, error) {
cnt := 0
chead := enc.children(fj)
for chead != nil {
// Here we are counting all non-scalar children of fj. If there are any such
// children, we will flatten them, otherwise we will return all children.
// We should only consider those children(of fj) for flattening which have
// children and are not facetsParent.
if enc.children(chead) != nil && !enc.getFacetsParent(chead) {
cnt++
}
chead = chead.next
}
if cnt == 0 {
// Recursion base case
// There are no children, we can just return slice with fj.child.
return []fastJsonNode{enc.children(fj)}, nil
}
parentSlice := make([]fastJsonNode, 0, 5)
// First separate children of fj which are scalar.
var shead, curScalar fastJsonNode
chead = enc.children(fj)
for chead != nil {
if enc.children(chead) != nil && enc.getFacetsParent(chead) == false {
chead = chead.next
continue
}
// Here, add all nodes which have either no children or they are facetsParent.
copyNode := enc.copySingleNode(chead)
if curScalar == nil {
shead, curScalar = copyNode, copyNode
} else {
curScalar.next = copyNode
curScalar = copyNode
}
chead = chead.next
}
parentSlice = append(parentSlice, shead)
chead = enc.children(fj)
for chead != nil {
childNode := chead
// Here, exclude all nodes which have either no children or they are facetsParent.
if enc.children(childNode) == nil || enc.getFacetsParent(childNode) {
chead = chead.next
continue
}
childSlice := make([]fastJsonNode, 0, 5)
for chead != nil && enc.getAttr(childNode) == enc.getAttr(chead) {
childSlice = append(childSlice, enc.children(chead))
chead = chead.next
}
var err error
parentSlice, err = enc.merge(parentSlice, childSlice)
if err != nil {
return nil, err
}
}
for _, slice := range parentSlice {
// From every slice we need to remove node with attribute "uid".
var prev, cur fastJsonNode
cur = slice
for cur != nil {
if enc.getAttr(cur) == enc.uidAttr {
if prev == nil {
slice = cur
cur = cur.next
continue
} else {
prev.next = cur.next
}
}
prev = cur
cur = cur.next
}
if prev == nil {
slice = nil
}
}
return parentSlice, nil
}
func (sg *SubGraph) addGroupby(enc *encoder, fj fastJsonNode,
res *groupResults, fname string) error {
// Don't add empty groupby
if len(res.group) == 0 {
return nil
}
g := enc.newNode(enc.idForAttr(fname))
for _, grp := range res.group {
uc := enc.newNode(enc.idForAttr("@groupby"))
for _, it := range grp.keys {
if err := enc.AddValue(uc, enc.idForAttr(it.attr), it.key); err != nil {
return err
}
}
for _, it := range grp.aggregates {
if err := enc.AddValue(uc, enc.idForAttr(it.attr), it.key); err != nil {
return err
}
}
enc.AddListChild(g, uc)
}
enc.AddListChild(fj, g)
return nil
}
func (sg *SubGraph) addAggregations(enc *encoder, fj fastJsonNode) error {
for _, child := range sg.Children {
aggVal, ok := child.Params.UidToVal[0]
if !ok {
if len(child.Params.NeedsVar) == 0 {
return errors.Errorf("Only aggregated variables allowed within empty block.")
}
// the aggregation didn't happen, most likely was called with unset vars.
// See: query.go:fillVars
// In this case we do nothing. The aggregate value in response will be returned as NULL.
}
if child.Params.Normalize && child.Params.Alias == "" {
continue
}
fieldName := child.aggWithVarFieldName()
n1 := enc.newNode(enc.idForAttr(sg.Params.Alias))
if err := enc.AddValue(n1, enc.idForAttr(fieldName), aggVal); err != nil {
return err
}
enc.AddListChild(fj, n1)
}
if enc.IsEmpty(fj) {
enc.AddListChild(fj, enc.newNode(enc.idForAttr(sg.Params.Alias)))
}
return nil
}
func (sg *SubGraph) handleCountUIDNodes(enc *encoder, n fastJsonNode, count int) (bool, error) {
addedNewChild := false
fieldName := sg.fieldName()
sgFieldID := enc.idForAttr(fieldName)
for _, child := range sg.Children {
uidCount := child.Attr == "uid" && child.Params.DoCount && child.IsInternal()
normWithoutAlias := child.Params.Alias == "" && child.Params.Normalize
if uidCount && !normWithoutAlias {
addedNewChild = true
c := types.ValueForType(types.IntID)
c.Value = int64(count)
field := child.Params.Alias
if field == "" {
field = "count"
}
fjChild := enc.newNode(sgFieldID)
if err := enc.AddValue(fjChild, enc.idForAttr(field), c); err != nil {
return false, err
}
enc.AddListChild(n, fjChild)
}
}
return addedNewChild, nil
}
func processNodeUids(fj fastJsonNode, enc *encoder, sg *SubGraph) error {
if sg.Params.IsEmpty {
return sg.addAggregations(enc, fj)
}