FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
dgraph/worker/task.go at master · elasticjava/dgraph · GitHub
elasticjava
/
dgraph
Public
forked from
dgraph-io/dgraph
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
dgraph
/
worker
/
task.go
Copy path
More file actions
More file actions
Latest commit
History
History
History
2490 lines (2251 loc) · 68.8 KB
Breadcrumbs
dgraph
/
worker
/
task.go
Copy path
File metadata and controls
2490 lines (2251 loc) · 68.8 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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 2016-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
worker
import
(
"bytes"
"context"
"sort"
"strconv"
"strings"
"time"
"github.com/dgraph-io/badger/v3"
"github.com/dgraph-io/dgo/v210/protos/api"
"github.com/dgraph-io/dgraph/algo"
"github.com/dgraph-io/dgraph/codec"
"github.com/dgraph-io/dgraph/conn"
"github.com/dgraph-io/dgraph/posting"
"github.com/dgraph-io/dgraph/protos/pb"
"github.com/dgraph-io/dgraph/schema"
ctask
"github.com/dgraph-io/dgraph/task"
"github.com/dgraph-io/dgraph/tok"
"github.com/dgraph-io/dgraph/types"
"github.com/dgraph-io/dgraph/types/facets"
"github.com/dgraph-io/dgraph/x"
"github.com/dgraph-io/sroar"
"github.com/golang/glog"
"github.com/golang/protobuf/proto"
otrace
"go.opencensus.io/trace"
"golang.org/x/sync/errgroup"
cindex
"github.com/google/codesearch/index"
cregexp
"github.com/google/codesearch/regexp"
"github.com/pkg/errors"
)
func
invokeNetworkRequest
(
ctx
context.
Context
,
addr
string
,
f
func
(context.
Context
, pb.
WorkerClient
) (
interface
{},
error
)) (
interface
{},
error
) {
pl
,
err
:=
conn
.
GetPools
().
Get
(
addr
)
if
err
!=
nil
{
return
nil
,
errors
.
Wrapf
(
err
,
"dispatchTaskOverNetwork: while retrieving connection."
)
}
if
span
:=
otrace
.
FromContext
(
ctx
);
span
!=
nil
{
span
.
Annotatef
(
nil
,
"invokeNetworkRequest: Sending request to %v"
,
addr
)
}
c
:=
pb
.
NewWorkerClient
(
pl
.
Get
())
return
f
(
ctx
,
c
)
}
const
backupRequestGracePeriod
=
time
.
Second
// TODO: Cross-server cancellation as described in Jeff Dean's talk.
func
processWithBackupRequest
(
ctx
context.
Context
,
gid
uint32
,
f
func
(context.
Context
, pb.
WorkerClient
) (
interface
{},
error
)) (
interface
{},
error
) {
addrs
:=
groups
().
AnyTwoServers
(
gid
)
if
len
(
addrs
)
==
0
{
return
nil
,
errors
.
New
(
"No network connection"
)
}
if
len
(
addrs
)
==
1
{
reply
,
err
:=
invokeNetworkRequest
(
ctx
,
addrs
[
0
],
f
)
return
reply
,
err
}
type
taskresult
struct
{
reply
interface
{}
err
error
}
chResults
:=
make
(
chan
taskresult
,
len
(
addrs
))
ctx0
,
cancel
:=
context
.
WithCancel
(
ctx
)
defer
cancel
()
go
func
() {
reply
,
err
:=
invokeNetworkRequest
(
ctx0
,
addrs
[
0
],
f
)
chResults
<-
taskresult
{
reply
,
err
}
}()
timer
:=
time
.
NewTimer
(
backupRequestGracePeriod
)
defer
timer
.
Stop
()
select
{
case
<-
ctx
.
Done
():
return
nil
,
ctx
.
Err
()
case
<-
timer
.
C
:
go
func
() {
reply
,
err
:=
invokeNetworkRequest
(
ctx0
,
addrs
[
1
],
f
)
chResults
<-
taskresult
{
reply
,
err
}
}()
select
{
case
<-
ctx
.
Done
():
return
nil
,
ctx
.
Err
()
case
result
:=
<-
chResults
:
if
result
.
err
!=
nil
{
select
{
case
<-
ctx
.
Done
():
return
nil
,
ctx
.
Err
()
case
result
:=
<-
chResults
:
return
result
.
reply
,
result
.
err
}
}
else
{
return
result
.
reply
,
nil
}
}
case
result
:=
<-
chResults
:
if
result
.
err
!=
nil
{
cancel
()
// Might as well cleanup resources ASAP
timer
.
Stop
()
return
invokeNetworkRequest
(
ctx
,
addrs
[
1
],
f
)
}
return
result
.
reply
,
nil
}
}
// ProcessTaskOverNetwork is used to process the query and get the result from
// the instance which stores posting list corresponding to the predicate in the
// query.
func
ProcessTaskOverNetwork
(
ctx
context.
Context
,
q
*
pb.
Query
) (
*
pb.
Result
,
error
) {
attr
:=
q
.
Attr
gid
,
err
:=
groups
().
BelongsToReadOnly
(
attr
,
q
.
ReadTs
)
switch
{
case
err
!=
nil
:
return
nil
,
err
case
gid
==
0
:
return
nil
,
errNonExistentTablet
}
span
:=
otrace
.
FromContext
(
ctx
)
if
span
!=
nil
{
span
.
Annotatef
(
nil
,
"ProcessTaskOverNetwork. attr: %v gid: %v, readTs: %d, node id: %d"
,
attr
,
gid
,
q
.
ReadTs
,
groups
().
Node
.
Id
)
}
if
groups
().
ServesGroup
(
gid
) {
// No need for a network call, as this should be run from within this instance.
return
processTask
(
ctx
,
q
,
gid
)
}
result
,
err
:=
processWithBackupRequest
(
ctx
,
gid
,
func
(
ctx
context.
Context
,
c
pb.
WorkerClient
) (
interface
{},
error
) {
return
c
.
ServeTask
(
ctx
,
q
)
})
if
err
!=
nil
{
return
nil
,
err
}
reply
:=
result
.(
*
pb.
Result
)
if
span
!=
nil
{
span
.
Annotatef
(
nil
,
"Reply from server. len: %v gid: %v Attr: %v"
,
len
(
reply
.
UidMatrix
),
gid
,
attr
)
}
return
reply
,
nil
}
// convertValue converts the data to the schema.State() type of predicate.
func
convertValue
(
attr
,
data
string
) (types.
Val
,
error
) {
// Parse given value and get token. There should be only one token.
t
,
err
:=
schema
.
State
().
TypeOf
(
attr
)
if
err
!=
nil
{
return
types.
Val
{},
err
}
if
!
t
.
IsScalar
() {
return
types.
Val
{},
errors
.
Errorf
(
"Attribute %s is not valid scalar type"
,
x
.
ParseAttr
(
attr
))
}
src
:=
types.
Val
{
Tid
:
types
.
StringID
,
Value
: []
byte
(
data
)}
dst
,
err
:=
types
.
Convert
(
src
,
t
)
return
dst
,
err
}
// Returns nil byte on error
func
convertToType
(
v
types.
Val
,
typ
types.
TypeID
) (
*
pb.
TaskValue
,
error
) {
result
:=
&
pb.
TaskValue
{
ValType
:
typ
.
Enum
(),
Val
:
x
.
Nilbyte
}
if
v
.
Tid
==
typ
{
result
.
Val
=
v
.
Value
.([]
byte
)
return
result
,
nil
}
// convert data from binary to appropriate format
val
,
err
:=
types
.
Convert
(
v
,
typ
)
if
err
!=
nil
{
return
result
,
err
}
// Marshal
data
:=
types
.
ValueForType
(
types
.
BinaryID
)
err
=
types
.
Marshal
(
val
,
&
data
)
if
err
!=
nil
{
return
result
,
errors
.
Errorf
(
"Failed convertToType during Marshal"
)
}
result
.
Val
=
data
.
Value
.([]
byte
)
return
result
,
nil
}
// FuncType represents the type of a query function (aggregation, has, etc).
type
FuncType
int
const
(
notAFunction
FuncType
=
iota
aggregatorFn
compareAttrFn
compareScalarFn
geoFn
passwordFn
regexFn
fullTextSearchFn
hasFn
uidInFn
customIndexFn
matchFn
standardFn
=
100
)
func
parseFuncType
(
srcFunc
*
pb.
SrcFunction
) (
FuncType
,
string
) {
if
srcFunc
==
nil
{
return
notAFunction
,
""
}
ftype
,
fname
:=
parseFuncTypeHelper
(
srcFunc
.
Name
)
if
srcFunc
.
IsCount
&&
ftype
==
compareAttrFn
{
// gt(release_date, "1990") is 'CompareAttr' which
// takes advantage of indexed-attr
// gt(count(films), 0) is 'CompareScalar', we first do
// counting on attr, then compare the result as scalar with int
return
compareScalarFn
,
fname
}
return
ftype
,
fname
}
func
parseFuncTypeHelper
(
name
string
) (
FuncType
,
string
) {
if
len
(
name
)
==
0
{
return
notAFunction
,
""
}
f
:=
strings
.
ToLower
(
name
)
switch
f
{
case
"le"
,
"ge"
,
"lt"
,
"gt"
,
"eq"
,
"between"
:
return
compareAttrFn
,
f
case
"min"
,
"max"
,
"sum"
,
"avg"
:
return
aggregatorFn
,
f
case
"checkpwd"
:
return
passwordFn
,
f
case
"regexp"
:
return
regexFn
,
f
case
"alloftext"
,
"anyoftext"
:
return
fullTextSearchFn
,
f
case
"has"
:
return
hasFn
,
f
case
"uid_in"
:
return
uidInFn
,
f
case
"anyof"
,
"allof"
:
return
customIndexFn
,
f
case
"match"
:
return
matchFn
,
f
default
:
if
types
.
IsGeoFunc
(
f
) {
return
geoFn
,
f
}
return
standardFn
,
f
}
}
func
needsIndex
(
fnType
FuncType
,
uidList
*
pb.
List
)
bool
{
switch
fnType
{
case
compareAttrFn
:
if
uidList
!=
nil
{
// UidList is not nil means this is a filter. Filter predicate is not indexed, so
// instead of fetching values by index key, we will fetch value by data key
// (from uid and predicate) and apply filter on values.
return
false
}
return
true
case
geoFn
,
fullTextSearchFn
,
standardFn
,
matchFn
:
return
true
}
return
false
}
// needsIntersect checks if the function type needs algo.IntersectSorted() after the results
// are collected. This is needed for functions that require all values to match, like
// "allofterms", "alloftext", and custom functions with "allof".
// Returns true if function results need intersect, false otherwise.
func
needsIntersect
(
fnName
string
)
bool
{
return
strings
.
HasPrefix
(
fnName
,
"allof"
)
||
strings
.
HasSuffix
(
fnName
,
"allof"
)
}
type
funcArgs
struct
{
q
*
pb.
Query
gid
uint32
srcFn
*
functionContext
out
*
pb.
Result
}
// The function tells us whether we want to fetch value posting lists or uid posting lists.
func
(
srcFn
*
functionContext
)
needsValuePostings
(
typ
types.
TypeID
) (
bool
,
error
) {
switch
srcFn
.
fnType
{
case
aggregatorFn
,
passwordFn
:
return
true
,
nil
case
compareAttrFn
:
if
len
(
srcFn
.
tokens
)
>
0
{
return
false
,
nil
}
return
true
,
nil
case
geoFn
,
regexFn
,
fullTextSearchFn
,
standardFn
,
hasFn
,
customIndexFn
,
matchFn
:
// All of these require an index, hence would require fetching uid postings.
return
false
,
nil
case
uidInFn
,
compareScalarFn
:
// Operate on uid postings
return
false
,
nil
case
notAFunction
:
return
typ
.
IsScalar
(),
nil
}
return
false
,
errors
.
Errorf
(
"Unhandled case in fetchValuePostings for fn: %s"
,
srcFn
.
fname
)
}
// Handles fetching of value posting lists and filtering of uids based on that.
func
(
qs
*
queryState
)
handleValuePostings
(
ctx
context.
Context
,
args
funcArgs
)
error
{
srcFn
:=
args
.
srcFn
q
:=
args
.
q
facetsTree
,
err
:=
preprocessFilter
(
q
.
FacetsFilter
)
if
err
!=
nil
{
return
err
}
span
:=
otrace
.
FromContext
(
ctx
)
stop
:=
x
.
SpanTimer
(
span
,
"handleValuePostings"
)
defer
stop
()
if
span
!=
nil
{
span
.
Annotatef
(
nil
,
"Number of uids: %d. args.srcFn: %+v"
,
srcFn
.
n
,
args
.
srcFn
)
}
switch
srcFn
.
fnType
{
case
notAFunction
,
aggregatorFn
,
passwordFn
,
compareAttrFn
:
default
:
return
errors
.
Errorf
(
"Unhandled function in handleValuePostings: %s"
,
srcFn
.
fname
)
}
if
srcFn
.
atype
==
types
.
PasswordID
&&
srcFn
.
fnType
!=
passwordFn
{
// Silently skip if the user is trying to fetch an attribute of type password.
return
nil
}
if
srcFn
.
fnType
==
passwordFn
&&
srcFn
.
atype
!=
types
.
PasswordID
{
return
errors
.
Errorf
(
"checkpwd fn can only be used on attr: [%s] with schema type "
+
"password. Got type: %s"
,
x
.
ParseAttr
(
q
.
Attr
),
types
.
TypeID
(
srcFn
.
atype
).
Name
())
}
if
srcFn
.
n
==
0
{
return
nil
}
// srcFn.n should be equal to len(q.UidList.Uids) for below implementation(DivideAndRule and
// calculate) to work correctly. But we have seen some panics while forming DataKey in
// calculate(). panic is of the form "index out of range [4] with length 1". Hence return error
// from here when srcFn.n != len(q.UidList.Uids).
bm
:=
codec
.
FromList
(
q
.
UidList
)
if
sz
:=
int
(
bm
.
GetCardinality
());
srcFn
.
n
!=
sz
{
return
errors
.
Errorf
(
"srcFn.n: %d is not equal to len(q.UidList.Uids): %d, srcFn: %+v in "
+
"handleValuePostings"
,
srcFn
.
n
,
sz
,
srcFn
)
}
// This function has small boilerplate as handleUidPostings, around how the code gets
// concurrently executed. I didn't see much value in trying to separate it out, because the core
// logic constitutes most of the code volume here.
numGo
,
width
:=
x
.
DivideAndRule
(
srcFn
.
n
)
x
.
AssertTrue
(
width
>
0
)
span
.
Annotatef
(
nil
,
"Width: %d. NumGo: %d"
,
width
,
numGo
)
outputs
:=
make
([]
*
pb.
Result
,
numGo
)
listType
:=
schema
.
State
().
IsList
(
q
.
Attr
)
calculate
:=
func
(
idx
int
,
itr
*
sroar.
Iterator
)
error
{
out
:=
&
pb.
Result
{}
outputs
[
idx
]
=
out
for
uid
:=
itr
.
Next
();
uid
>
0
;
uid
=
itr
.
Next
() {
key
:=
x
.
DataKey
(
q
.
Attr
,
uid
)
// Get or create the posting list for an entity, attribute combination.
pl
,
err
:=
qs
.
cache
.
Get
(
key
)
if
err
!=
nil
{
return
err
}
// If count is being requested, there is no need to populate value and facets matrix.
if
q
.
DoCount
{
count
,
err
:=
countForValuePostings
(
args
,
pl
,
facetsTree
,
listType
)
if
err
!=
nil
&&
err
!=
posting
.
ErrNoValue
{
return
err
}
out
.
Counts
=
append
(
out
.
Counts
,
uint32
(
count
))
// Add an empty UID list to make later processing consistent.
out
.
UidMatrix
=
append
(
out
.
UidMatrix
,
&
pb.
List
{})
continue
}
vals
,
fcs
,
err
:=
retrieveValuesAndFacets
(
args
,
pl
,
facetsTree
,
listType
)
switch
{
case
err
==
posting
.
ErrNoValue
||
(
err
==
nil
&&
len
(
vals
)
==
0
):
// This branch is taken when the value does not exist in the pl or
// the number of values retreived is zero (there could still be facets).
// We add empty lists to the UidMatrix, FaceMatrix, ValueMatrix and
// LangMatrix so that all these data structure have predicatble layouts.
out
.
UidMatrix
=
append
(
out
.
UidMatrix
,
&
pb.
List
{})
out
.
FacetMatrix
=
append
(
out
.
FacetMatrix
,
&
pb.
FacetsList
{})
out
.
ValueMatrix
=
append
(
out
.
ValueMatrix
,
&
pb.
ValueList
{
Values
: []
*
pb.
TaskValue
{}})
if
q
.
ExpandAll
{
// To keep the cardinality same as that of ValueMatrix.
out
.
LangMatrix
=
append
(
out
.
LangMatrix
,
&
pb.
LangList
{})
}
continue
case
err
!=
nil
:
return
err
}
if
q
.
ExpandAll
{
langTags
,
err
:=
pl
.
GetLangTags
(
args
.
q
.
ReadTs
)
if
err
!=
nil
{
return
err
}
out
.
LangMatrix
=
append
(
out
.
LangMatrix
,
&
pb.
LangList
{
Lang
:
langTags
})
}
res
:=
sroar
.
NewBitmap
()
var
vl
pb.
ValueList
for
_
,
val
:=
range
vals
{
newValue
,
err
:=
convertToType
(
val
,
srcFn
.
atype
)
if
err
!=
nil
{
return
err
}
// This means we fetched the value directly instead of fetching index key and
// intersecting. Lets compare the value and add filter the uid.
if
srcFn
.
fnType
==
compareAttrFn
{
// Lets convert the val to its type.
if
val
,
err
=
types
.
Convert
(
val
,
srcFn
.
atype
);
err
!=
nil
{
return
err
}
switch
srcFn
.
fname
{
case
"eq"
:
for
_
,
eqToken
:=
range
srcFn
.
eqTokens
{
if
types
.
CompareVals
(
srcFn
.
fname
,
val
,
eqToken
) {
res
.
Set
(
uid
)
break
}
}
case
"between"
:
if
types
.
CompareBetween
(
val
,
srcFn
.
eqTokens
[
0
],
srcFn
.
eqTokens
[
1
]) {
res
.
Set
(
uid
)
}
default
:
if
types
.
CompareVals
(
srcFn
.
fname
,
val
,
srcFn
.
eqTokens
[
0
]) {
res
.
Set
(
uid
)
}
}
}
else
{
vl
.
Values
=
append
(
vl
.
Values
,
newValue
)
}
}
out
.
ValueMatrix
=
append
(
out
.
ValueMatrix
,
&
vl
)
// Add facets to result.
out
.
FacetMatrix
=
append
(
out
.
FacetMatrix
,
fcs
)
switch
{
case
srcFn
.
fnType
==
aggregatorFn
:
// Add an empty UID list to make later processing consistent
out
.
UidMatrix
=
append
(
out
.
UidMatrix
,
&
pb.
List
{})
case
srcFn
.
fnType
==
passwordFn
:
lastPos
:=
len
(
out
.
ValueMatrix
)
-
1
if
len
(
out
.
ValueMatrix
[
lastPos
].
Values
)
==
0
{
continue
}
newValue
:=
out
.
ValueMatrix
[
lastPos
].
Values
[
0
]
if
len
(
newValue
.
Val
)
==
0
{
out
.
ValueMatrix
[
lastPos
].
Values
[
0
]
=
ctask
.
FalseVal
}
pwd
:=
q
.
SrcFunc
.
Args
[
0
]
err
=
types
.
VerifyPassword
(
pwd
,
string
(
newValue
.
Val
))
if
err
!=
nil
{
out
.
ValueMatrix
[
lastPos
].
Values
[
0
]
=
ctask
.
FalseVal
}
else
{
out
.
ValueMatrix
[
lastPos
].
Values
[
0
]
=
ctask
.
TrueVal
}
// Add an empty UID list to make later processing consistent
out
.
UidMatrix
=
append
(
out
.
UidMatrix
,
&
pb.
List
{})
default
:
out
.
UidMatrix
=
append
(
out
.
UidMatrix
,
&
pb.
List
{
Bitmap
:
res
.
ToBuffer
()})
}
}
return
nil
}
// End of calculate function.
iters
:=
bm
.
NewRangeIterators
(
numGo
)
var
g
errgroup.
Group
for
i
:=
0
;
i
<
numGo
;
i
++
{
i
:=
i
g
.
Go
(
func
()
error
{
return
calculate
(
i
,
iters
[
i
])
})
}
if
err
:=
g
.
Wait
();
err
!=
nil
{
return
err
}
// All goroutines are done. Now attach their results.
out
:=
args
.
out
for
_
,
chunk
:=
range
outputs
{
out
.
UidMatrix
=
append
(
out
.
UidMatrix
,
chunk
.
UidMatrix
...
)
out
.
Counts
=
append
(
out
.
Counts
,
chunk
.
Counts
...
)
out
.
ValueMatrix
=
append
(
out
.
ValueMatrix
,
chunk
.
ValueMatrix
...
)
out
.
FacetMatrix
=
append
(
out
.
FacetMatrix
,
chunk
.
FacetMatrix
...
)
out
.
LangMatrix
=
append
(
out
.
LangMatrix
,
chunk
.
LangMatrix
...
)
}
return
nil
}
func
facetsFilterValuePostingList
(
args
funcArgs
,
pl
*
posting.
List
,
facetsTree
*
facetsTree
,
listType
bool
,
fn
func
(
p
*
pb.
Posting
))
error
{
q
:=
args
.
q
var
langMatch
*
pb.
Posting
var
err
error
// We need to pick multiple postings only in two cases:
// 1. ExpandAll is true.
// 2. Attribute type is of list type and no lang tag is specified in query.
pickMultiplePostings
:=
q
.
ExpandAll
||
(
listType
&&
len
(
q
.
Langs
)
==
0
)
if
!
pickMultiplePostings
{
// Retrieve the posting that matches the language preferences.
if
len
(
q
.
Langs
)
>
0
{
langMatch
,
err
=
pl
.
PostingFor
(
q
.
ReadTs
,
q
.
Langs
)
if
err
!=
nil
&&
err
!=
posting
.
ErrNoValue
{
return
err
}
}
}
// TODO(Ashish): This function starts iteration from start(afterUID is always 0). This can be
// optimized in come cases. For example when we know lang tag to fetch, we can directly jump
// to posting starting with that UID(check list.ValueFor()).
return
pl
.
Iterate
(
q
.
ReadTs
,
0
,
func
(
p
*
pb.
Posting
)
error
{
if
q
.
ExpandAll
{
// If q.ExpandAll is true we need to consider all postings irrespective of langs.
}
else
if
listType
&&
len
(
q
.
Langs
)
==
0
{
// Don't retrieve tagged values unless explicitly asked.
if
len
(
p
.
LangTag
)
>
0
{
return
nil
}
}
else
{
// Don't retrieve tagged values unless explicitly asked.
if
len
(
q
.
Langs
)
==
0
&&
len
(
p
.
LangTag
)
>
0
{
return
nil
}
// Only consider the posting that matches our language preferences.
if
len
(
q
.
Langs
)
>
0
&&
!
proto
.
Equal
(
p
,
langMatch
) {
return
nil
}
}
// If filterTree is nil, applyFacetsTree returns true and nil error.
picked
,
err
:=
applyFacetsTree
(
p
.
Facets
,
facetsTree
)
if
err
!=
nil
{
return
err
}
if
picked
{
fn
(
p
)
}
if
pickMultiplePostings
{
return
nil
// Continue iteration.
}
// We have picked the right posting, we can stop iteration now.
return
posting
.
ErrStopIteration
})
}
func
countForValuePostings
(
args
funcArgs
,
pl
*
posting.
List
,
facetsTree
*
facetsTree
,
listType
bool
) (
int
,
error
) {
var
filteredCount
int
err
:=
facetsFilterValuePostingList
(
args
,
pl
,
facetsTree
,
listType
,
func
(
p
*
pb.
Posting
) {
filteredCount
++
})
if
err
!=
nil
{
return
0
,
err
}
return
filteredCount
,
nil
}
func
retrieveValuesAndFacets
(
args
funcArgs
,
pl
*
posting.
List
,
facetsTree
*
facetsTree
,
listType
bool
) ([]types.
Val
,
*
pb.
FacetsList
,
error
) {
q
:=
args
.
q
var
vals
[]types.
Val
var
fcs
[]
*
pb.
Facets
err
:=
facetsFilterValuePostingList
(
args
,
pl
,
facetsTree
,
listType
,
func
(
p
*
pb.
Posting
) {
vals
=
append
(
vals
, types.
Val
{
Tid
:
types
.
TypeID
(
p
.
ValType
),
Value
:
p
.
Value
,
})
if
q
.
FacetParam
!=
nil
{
fcs
=
append
(
fcs
,
&
pb.
Facets
{
Facets
:
facets
.
CopyFacets
(
p
.
Facets
,
q
.
FacetParam
)})
}
})
if
err
!=
nil
{
return
nil
,
nil
,
err
}
return
vals
,
&
pb.
FacetsList
{
FacetsList
:
fcs
},
nil
}
func
facetsFilterUidPostingList
(
pl
*
posting.
List
,
facetsTree
*
facetsTree
,
opts
posting.
ListOptions
,
fn
func
(
*
pb.
Posting
))
error
{
// We want to iterate over this to allow picking up all the facets.
return
pl
.
IterateAll
(
opts
.
ReadTs
,
opts
.
AfterUid
,
func
(
p
*
pb.
Posting
)
error
{
// Only pick the UID postings.
if
p
.
PostingType
!=
pb
.
Posting_REF
{
return
nil
}
pick
,
err
:=
applyFacetsTree
(
p
.
Facets
,
facetsTree
)
if
err
!=
nil
{
return
err
}
if
pick
{
fn
(
p
)
}
return
nil
})
}
func
countForUidPostings
(
args
funcArgs
,
pl
*
posting.
List
,
facetsTree
*
facetsTree
,
opts
posting.
ListOptions
) (
int
,
error
) {
if
facetsTree
==
nil
{
return
pl
.
Length
(
opts
.
ReadTs
,
opts
.
AfterUid
),
nil
}
// We have a valid facetsTree. So, we'd do the filtering by iteration.
var
filteredCount
int
err
:=
facetsFilterUidPostingList
(
pl
,
facetsTree
,
opts
,
func
(
p
*
pb.
Posting
) {
filteredCount
++
})
return
filteredCount
,
err
}
func
retrieveUidsAndFacets
(
args
funcArgs
,
pl
*
posting.
List
,
facetsTree
*
facetsTree
,
opts
posting.
ListOptions
) (
*
pb.
List
, []
*
pb.
Facets
,
error
) {
q
:=
args
.
q
res
:=
sroar
.
NewBitmap
()
var
fcsList
[]
*
pb.
Facets
// [1] q.FacetParam == nil, facetsTree == nil => No facets. Pick all UIDs.
// [2] q.FacetParam == nil, facetsTree != nil => No facets. Pick selective UIDs.
// [3] q.FacetParam != nil, facetsTree != nil => Pick facets. Pick selective UIDs.
// [4] q.FacetParam != nil, facetsTree == nil => Pick facets. Pick all UIDs.
err
:=
facetsFilterUidPostingList
(
pl
,
facetsTree
,
opts
,
func
(
p
*
pb.
Posting
) {
res
.
Set
(
p
.
Uid
)
if
q
.
FacetParam
!=
nil
{
fcsList
=
append
(
fcsList
,
&
pb.
Facets
{
Facets
:
facets
.
CopyFacets
(
p
.
Facets
,
q
.
FacetParam
),
})
}
})
if
err
!=
nil
{
return
nil
,
nil
,
err
}
// TODO(Ahsan): Need to figure out for what all cases we need sortedList.
return
codec
.
ToSortedList
(
res
),
fcsList
,
nil
}
// This function handles operations on uid posting lists. Index keys, reverse keys and some data
// keys store uid posting lists.
func
(
qs
*
queryState
)
handleUidPostings
(
ctx
context.
Context
,
args
funcArgs
,
opts
posting.
ListOptions
)
error
{
srcFn
:=
args
.
srcFn
q
:=
args
.
q
facetsTree
,
err
:=
preprocessFilter
(
q
.
FacetsFilter
)
if
err
!=
nil
{
return
err
}
span
:=
otrace
.
FromContext
(
ctx
)
stop
:=
x
.
SpanTimer
(
span
,
"handleUidPostings"
)
defer
stop
()
if
span
!=
nil
{
span
.
Annotatef
(
nil
,
"Number of uids: %d. args.srcFn: %+v"
,
srcFn
.
n
,
args
.
srcFn
)
}
if
srcFn
.
n
==
0
{
return
nil
}
// srcFn.n should be equal to len(q.UidList.Uids) for below implementation(DivideAndRule and
// calculate) to work correctly. But we have seen some panics while forming DataKey in
// calculate(). panic is of the form "index out of range [4] with length 1". Hence return error
// from here when srcFn.n != len(q.UidList.Uids).
switch
srcFn
.
fnType
{
case
notAFunction
,
compareScalarFn
,
hasFn
,
uidInFn
:
c
:=
int
(
codec
.
ListCardinality
(
q
.
UidList
))
if
srcFn
.
n
!=
c
{
return
errors
.
Errorf
(
"srcFn.n: %d is not equal to len(q.UidList.Uids): %d, srcFn: %+v in "
+
"handleUidPostings"
,
srcFn
.
n
,
c
,
srcFn
)
}
}
// Divide the task into many goroutines.
numGo
,
width
:=
x
.
DivideAndRule
(
srcFn
.
n
)
x
.
AssertTrue
(
width
>
0
)
span
.
Annotatef
(
nil
,
"Width: %d. NumGo: %d"
,
width
,
numGo
)
errCh
:=
make
(
chan
error
,
numGo
)
outputs
:=
make
([]
*
pb.
Result
,
numGo
)
uids
:=
codec
.
GetUids
(
q
.
UidList
)
srcFnUidList
:=
&
pb.
List
{
Bitmap
:
srcFn
.
uidsPresent
.
ToBuffer
()}
calculate
:=
func
(
start
,
end
int
)
error
{
x
.
AssertTrue
(
start
%
width
==
0
)
out
:=
&
pb.
Result
{}
outputs
[
start
/
width
]
=
out
for
i
:=
start
;
i
<
end
;
i
++
{
if
i
%
100
==
0
{
select
{
case
<-
ctx
.
Done
():
return
ctx
.
Err
()
default
:
}
}
var
key
[]
byte
switch
srcFn
.
fnType
{
case
notAFunction
,
compareScalarFn
,
hasFn
,
uidInFn
:
if
q
.
Reverse
{
key
=
x
.
ReverseKey
(
q
.
Attr
,
uids
[
i
])
}
else
{
key
=
x
.
DataKey
(
q
.
Attr
,
uids
[
i
])
}
case
geoFn
,
regexFn
,
fullTextSearchFn
,
standardFn
,
customIndexFn
,
matchFn
,
compareAttrFn
:
key
=
x
.
IndexKey
(
q
.
Attr
,
srcFn
.
tokens
[
i
])
default
:
return
errors
.
Errorf
(
"Unhandled function in handleUidPostings: %s"
,
srcFn
.
fname
)
}
// Get or create the posting list for an entity, attribute combination.
pl
,
err
:=
qs
.
cache
.
Get
(
key
)
if
err
!=
nil
{
return
err
}
switch
{
case
q
.
DoCount
:
if
i
==
0
{
span
.
Annotate
(
nil
,
"DoCount"
)
}
count
,
err
:=
countForUidPostings
(
args
,
pl
,
facetsTree
,
opts
)
if
err
!=
nil
{
return
err
}
out
.
Counts
=
append
(
out
.
Counts
,
uint32
(
count
))
// Add an empty UID list to make later processing consistent.
out
.
UidMatrix
=
append
(
out
.
UidMatrix
,
&
pb.
List
{})
case
srcFn
.
fnType
==
compareScalarFn
:
if
i
==
0
{
span
.
Annotate
(
nil
,
"CompareScalarFn"
)
}
len
:=
pl
.
Length
(
args
.
q
.
ReadTs
,
0
)
if
len
==
-
1
{
return
posting
.
ErrTsTooOld
}
count
:=
int64
(
len
)
if
evalCompare
(
srcFn
.
fname
,
count
,
srcFn
.
threshold
[
0
]) {
tlist
:=
codec
.
OneUid
(
uids
[
i
])
out
.
UidMatrix
=
append
(
out
.
UidMatrix
,
tlist
)
}
case
srcFn
.
fnType
==
hasFn
:
if
i
==
0
{
span
.
Annotate
(
nil
,
"HasFn"
)
}
empty
,
err
:=
pl
.
IsEmpty
(
args
.
q
.
ReadTs
,
0
)
if
err
!=
nil
{
return
err
}
if
!
empty
{
tlist
:=
codec
.
OneUid
(
uids
[
i
])
out
.
UidMatrix
=
append
(
out
.
UidMatrix
,
tlist
)
}
case
srcFn
.
fnType
==
uidInFn
:
if
i
==
0
{
span
.
Annotate
(
nil
,
"UidInFn"
)
}
topts
:=
posting.
ListOptions
{
ReadTs
:
args
.
q
.
ReadTs
,
AfterUid
:
0
,
Intersect
:
srcFnUidList
,
First
:
int
(
args
.
q
.
First
+
args
.
q
.
Offset
),
}
plist
,
err
:=
pl
.
Uids
(
topts
)
if
err
!=
nil
{
return
err
}
if
codec
.
ListCardinality
(
plist
)
>
0
{
tlist
:=
codec
.
OneUid
(
uids
[
i
])
out
.
UidMatrix
=
append
(
out
.
UidMatrix
,
tlist
)
}
case
q
.
FacetParam
!=
nil
||
facetsTree
!=
nil
:
if
i
==
0
{
span
.
Annotate
(
nil
,
"default with facets"
)
}
uidList
,
fcsList
,
err
:=
retrieveUidsAndFacets
(
args
,
pl
,
facetsTree
,
opts
)
if
err
!=
nil
{
return
err
}
out
.
UidMatrix
=
append
(
out
.
UidMatrix
,
uidList
)
if
q
.
FacetParam
!=
nil
{
out
.
FacetMatrix
=
append
(
out
.
FacetMatrix
,
&
pb.
FacetsList
{
FacetsList
:
fcsList
})
}
default
:
if
i
==
0
{
span
.
Annotate
(
nil
,
"default no facets"
)
}
uidList
,
err
:=
pl
.
Uids
(
opts
)
if
err
!=
nil
{
return
err
}
out
.
UidMatrix
=
append
(
out
.
UidMatrix
,
uidList
)
}
}
return
nil
}
// End of calculate function.
for
i
:=
0
;
i
<
numGo
;
i
++
{
start
:=
i
*
width
end
:=
start
+
width
if
end
>
srcFn
.
n
{
end
=
srcFn
.
n
}
go
func
(
start
,
end
int
) {
errCh
<-
calculate
(
start
,
end
)
}(
start
,
end
)
}
for
i
:=
0
;
i
<
numGo
;
i
++
{
if
err
:=
<-
errCh
;
err
!=
nil
{
return
err
}
}
// All goroutines are done. Now attach their results.
out
:=
args
.
out
for
_
,
chunk
:=
range
outputs
{
out
.
FacetMatrix
=
append
(
out
.
FacetMatrix
,
chunk
.
FacetMatrix
...
)
out
.
Counts
=
append
(
out
.
Counts
,
chunk
.
Counts
...
)
out
.
UidMatrix
=
append
(
out
.
UidMatrix
,
chunk
.
UidMatrix
...
)
}
var
total
int
for
_
,
list
:=
range
out
.
UidMatrix
{
total
+=
int
(
codec
.
ListCardinality
(
list
))
}
span
.
Annotatef
(
nil
,
"Total number of elements in matrix: %d"
,
total
)
return
nil
}
const
(
// UseTxnCache indicates the transaction cache should be used.
UseTxnCache
=
iota
// NoCache indicates no caches should be used.
NoCache
)
// processTask processes the query, accumulates and returns the result.
func
processTask
(
ctx
context.
Context
,
q
*
pb.
Query
,
gid
uint32
) (
*
pb.
Result
,
error
) {
ctx
,
span
:=
otrace
.
StartSpan
(
ctx
,
"processTask."
+
q
.
Attr
)
defer
span
.
End
()
stop
:=
x
.
SpanTimer
(
span
,
"processTask"
+
q
.
Attr
)
defer
stop
()
span
.
Annotatef
(
nil
,
"Waiting for startTs: %d at node: %d, gid: %d"
,
q
.
ReadTs
,
groups
().
Node
.
Id
,
gid
)
if
err
:=
posting
.
Oracle
().
WaitForTs
(
ctx
,
q
.
ReadTs
);
err
!=
nil
{
return
nil
,
err
}
if
span
!=
nil
{
maxAssigned
:=
posting
.
Oracle
().
MaxAssigned
()
span
.
Annotatef
(
nil
,
"Done waiting for maxAssigned. Attr: %q ReadTs: %d Max: %d"
,
q
.
Attr
,
q
.
ReadTs
,
maxAssigned
)
}
if
err
:=
groups
().
ChecksumsMatch
(
ctx
);
err
!=
nil
{
return
nil
,
err
}
span
.
Annotatef
(
nil
,
"Done waiting for checksum match"
)
// If a group stops serving tablet and it gets partitioned away from group
// zero, then it wouldn't know that this group is no longer serving this
// predicate. There's no issue if a we are serving a particular tablet and
// we get partitioned away from group zero as long as it's not removed.
// BelongsToReadOnly is called instead of BelongsTo to prevent this alpha
// from requesting to serve this tablet.
knownGid
,
err
:=
groups
().
BelongsToReadOnly
(
q
.
Attr
,
q
.
ReadTs
)
switch
{
case
err
!=
nil
:
return
nil
,
err
case
knownGid
==
0
:
return
nil
,
errNonExistentTablet
case
knownGid
!=
groups
().
groupId
():
return
nil
,
errUnservedTablet
}
var
qs
queryState
if
q
.
Cache
==
UseTxnCache
{
qs
.
cache
=
posting
.
Oracle
().
CacheAt
(
q
.
ReadTs
)
}
if
qs
.
cache
==
nil
{
qs
.
cache
=
posting
.
NoCache
(
q
.
ReadTs
)
}
// For now, remove the query level cache. It is causing contention for queries with high
// fan-out.
out
,
err
:=
qs
.
helpProcessTask
(
ctx
,
q
,
gid
)
if
err
!=
nil
{
return
nil
,
err
}
return
out
,
nil
}
type
queryState
struct
{
cache
*
posting.
LocalCache
}
func
(
qs
*
queryState
)
helpProcessTask
(
ctx
context.
Context
,
q
*
pb.
Query
,
gid
uint32
) (
*
pb.
Result
,
error
) {
span
:=
otrace
.
FromContext
(
ctx
)
out
:=
new
(pb.
Result
)
attr
:=
q
.
Attr
srcFn
,
err
:=
parseSrcFn
(
ctx
,
q
)
if
err
!=
nil
{
return
nil
,
err
}
if
q
.
Reverse
&&
!
schema
.
State
().
IsReversed
(
ctx
,
attr
) {
return
nil
,
errors
.
Errorf
(
"Predicate %s doesn't have reverse edge"
,
x
.
ParseAttr
(
attr
))
}
if
needsIndex
(
srcFn
.
fnType
,
q
.
UidList
)
&&
!
schema
.
State
().
IsIndexed
(
ctx
,
q
.
Attr
) {
return
nil
,
errors
.
Errorf
(
"Predicate %s is not indexed"
,
x
.
ParseAttr
(
q
.
Attr
))
}
if
len
(
q
.
Langs
)
>
0
&&
!
schema
.
State
().
HasLang
(
attr
) {
return
nil
,
errors
.
Errorf
(
"Language tags can only be used with predicates of string type"
+
" having @lang directive in schema. Got: [%v]"
,
x
.
ParseAttr
(
attr
))
}
if
len
(
q
.
Langs
)
==
1
&&
q
.
Langs
[
0
]
==
"*"
{
// Reset the Langs fields. The ExpandAll field is set to true already so there's no
// more need to store the star value in this field.
q
.
Langs
=
nil
}
typ
,
err
:=
schema
.
State
().
TypeOf
(
attr
)
if
err
!=
nil
{
// All schema checks are done before this, this type is only used to
// convert it to schema type before returning.
// Schema type won't be present only if there is no data for that predicate
// or if we load through bulk loader.
typ
=
types
.
DefaultID
}
out
.
List
=
schema
.
State
().
IsList
(
attr
)
srcFn
.
atype
=
typ
// Reverse attributes might have more than 1 results even if the original attribute
// is not a list.
if
q
.
Reverse
{
out
.
List
=
true
}
opts
:=
posting.
ListOptions
{
ReadTs
:
q
.
ReadTs
,
AfterUid
:
q
.
AfterUid
,
First
:
int
(
q
.
First
+
q
.
Offset
),
}
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL