forked from dgraph-io/dgraph
-
Notifications
You must be signed in to change notification settings - Fork 1
/
task.go
1418 lines (1300 loc) · 38.5 KB
/
task.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 (C) 2017 Dgraph Labs, Inc. and Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package worker
import (
"errors"
"fmt"
"math/rand"
"sort"
"strconv"
"strings"
"time"
"google.golang.org/grpc/metadata"
"github.com/dgraph-io/badger"
"golang.org/x/net/context"
"golang.org/x/net/trace"
"gopkg.in/adibiarsotp/dgraph.v82/algo"
"gopkg.in/adibiarsotp/dgraph.v82/conn"
"gopkg.in/adibiarsotp/dgraph.v82/posting"
"gopkg.in/adibiarsotp/dgraph.v82/protos"
"gopkg.in/adibiarsotp/dgraph.v82/schema"
ctask "gopkg.in/adibiarsotp/dgraph.v82/task"
"gopkg.in/adibiarsotp/dgraph.v82/tok"
"gopkg.in/adibiarsotp/dgraph.v82/types"
"gopkg.in/adibiarsotp/dgraph.v82/types/facets"
"gopkg.in/adibiarsotp/dgraph.v82/x"
cindex "github.com/google/codesearch/index"
cregexp "github.com/google/codesearch/regexp"
)
var (
emptyUIDList protos.List
emptyResult protos.Result
emptyValueList = protos.ValueList{Values: []*protos.TaskValue{&protos.TaskValue{Val: x.Nilbyte}}}
)
func invokeNetworkRequest(
ctx context.Context, addr string, f func(context.Context, protos.WorkerClient) (interface{}, error)) (interface{}, error) {
pl, err := conn.Get().Get(addr)
if err != nil {
return &emptyResult, x.Wrapf(err, "dispatchTaskOverNetwork: while retrieving connection.")
}
conn := pl.Get()
if tr, ok := trace.FromContext(ctx); ok {
tr.LazyPrintf("Sending request to %v", addr)
}
c := protos.NewWorkerClient(conn)
return f(ctx, c)
}
const backupRequestGracePeriod = 10 * time.Millisecond
// TODO: Cross-server cancellation as described in Jeff Dean's talk.
func processWithBackupRequest(
ctx context.Context,
gid uint32,
f func(context.Context, protos.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 *protos.Query) (*protos.Result, error) {
attr := q.Attr
gid := groups().BelongsTo(attr)
if gid == 0 {
return &protos.Result{}, errUnservedTablet
}
if tr, ok := trace.FromContext(ctx); ok {
tr.LazyPrintf("attr: %v groupId: %v", attr, gid)
}
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 protos.WorkerClient) (interface{}, error) {
if tr, ok := trace.FromContext(ctx); ok {
id := fmt.Sprintf("%d", rand.Int())
tr.LazyPrintf("Sending request to server, id: %s", id)
ctx = metadata.NewOutgoingContext(ctx, metadata.Pairs("trace", id))
}
return c.ServeTask(ctx, q)
})
if err != nil {
if tr, ok := trace.FromContext(ctx); ok {
tr.LazyPrintf("Error while worker.ServeTask: %v", err)
}
return nil, err
}
reply := result.(*protos.Result)
if tr, ok := trace.FromContext(ctx); ok {
tr.LazyPrintf("Reply from server. length: %v Group: %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{}, x.Errorf("Attribute %s is not valid scalar type", attr)
}
src := types.Val{types.StringID, []byte(data)}
dst, err := types.Convert(src, t)
return dst, err
}
// Returns nil byte on error
func convertToType(v types.Val, typ types.TypeID) (*protos.TaskValue, error) {
result := &protos.TaskValue{ValType: int32(typ), 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, x.Errorf("Failed convertToType during Marshal")
}
result.Val = data.Value.([]byte)
return result, nil
}
type FuncType int
const (
NotAFunction FuncType = iota
AggregatorFn
CompareAttrFn
CompareScalarFn
GeoFn
PasswordFn
RegexFn
FullTextSearchFn
HasFn
UidInFn
StandardFn = 100
)
func parseFuncType(srcFunc *protos.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":
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
default:
if types.IsGeoFunc(f) {
return GeoFn, f
}
return StandardFn, f
}
}
func needsIndex(fnType FuncType) bool {
switch fnType {
case CompareAttrFn, GeoFn, RegexFn, FullTextSearchFn, StandardFn:
return true
default:
return false
}
}
type result struct {
uid uint64
facets []*protos.Facet
}
type funcArgs struct {
q *protos.Query
gid uint32
srcFn *functionContext
out *protos.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:
// All of these require 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
default:
return false, x.Errorf("Unhandled case in fetchValuePostings for fn: %s", srcFn.fname)
}
return true, nil
}
// Handles fetching of value posting lists and filtering of uids based on that.
func handleValuePostings(ctx context.Context, args funcArgs) error {
srcFn := args.srcFn
q := args.q
attr := q.Attr
out := args.out
switch srcFn.fnType {
case NotAFunction, AggregatorFn, PasswordFn, CompareAttrFn:
default:
return x.Errorf("Unhandled function in handleValuePostings: %s", srcFn.fname)
}
var key []byte
var err error
listType := schema.State().IsList(attr)
for i := 0; i < srcFn.n; i++ {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
key = x.DataKey(attr, q.UidList.Uids[i])
// Get or create the posting list for an entity, attribute combination.
pl := posting.Get(key)
var vals []types.Val
// Even if its a list type and value is asked in a language we return that.
if listType && len(q.Langs) == 0 {
vals, err = pl.AllValues()
} else {
var val types.Val
val, err = pl.ValueFor(q.Langs)
if val.Tid == types.PasswordID && srcFn.fnType != PasswordFn {
return x.Errorf("Attribute `%s` of type password cannot be fetched", attr)
}
vals = append(vals, val)
}
if err != nil || len(vals) == 0 {
out.UidMatrix = append(out.UidMatrix, &emptyUIDList)
out.ValueMatrix = append(out.ValueMatrix, &emptyValueList)
continue
}
valTid := vals[0].Tid
newValue := &protos.TaskValue{ValType: int32(valTid), Val: x.Nilbyte}
uidList := new(protos.List)
var vl protos.ValueList
for _, val := range vals {
newValue, err = convertToType(val, srcFn.atype)
// 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
}
if types.CompareVals(srcFn.fname, val, srcFn.ineqValue) {
uidList.Uids = append(uidList.Uids, q.UidList.Uids[i])
break
}
} else {
vl.Values = append(vl.Values, newValue)
}
}
out.ValueMatrix = append(out.ValueMatrix, &vl)
if q.FacetsFilter != nil { // else part means isValueEdge
// This is Value edge and we are asked to do facet filtering. Not supported.
return x.Errorf("Facet filtering is not supported on values.")
}
// add facets to result.
if q.FacetParam != nil {
fs, err := pl.Facets(q.FacetParam, q.Langs)
if err != nil {
fs = []*protos.Facet{}
}
out.FacetMatrix = append(out.FacetMatrix,
&protos.FacetsList{[]*protos.Facets{{fs}}})
}
switch {
case q.DoCount:
out.Counts = append(out.Counts, uint32(pl.Length(0)))
// Add an empty UID list to make later processing consistent
out.UidMatrix = append(out.UidMatrix, &emptyUIDList)
case srcFn.fnType == AggregatorFn:
// Add an empty UID list to make later processing consistent
out.UidMatrix = append(out.UidMatrix, &emptyUIDList)
case srcFn.fnType == PasswordFn:
lastPos := len(out.ValueMatrix) - 1
newValue := out.ValueMatrix[lastPos].Values[0]
if len(newValue.Val) == 0 {
// TODO - Check that this is safe.
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, &emptyUIDList)
default:
out.UidMatrix = append(out.UidMatrix, uidList)
}
}
return nil
}
// This function handles operations on uid posting lists. Index keys, reverse keys and some data
// keys store uid posting lists.
func handleUidPostings(ctx context.Context, args funcArgs, opts posting.ListOptions) error {
srcFn := args.srcFn
q := args.q
attr := q.Attr
out := args.out
facetsTree, err := preprocessFilter(q.FacetsFilter)
if err != nil {
return err
}
for i := 0; i < srcFn.n; i++ {
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(attr, q.UidList.Uids[i])
} else {
key = x.DataKey(attr, q.UidList.Uids[i])
}
case GeoFn, RegexFn, FullTextSearchFn, StandardFn:
key = x.IndexKey(attr, srcFn.tokens[i])
case CompareAttrFn:
key = x.IndexKey(attr, srcFn.tokens[i])
default:
return x.Errorf("Unhandled function in handleUidPostings: %s", srcFn.fname)
}
// Get or create the posting list for an entity, attribute combination.
pl := posting.Get(key)
// get filtered uids and facets.
var filteredRes []*result
out.ValueMatrix = append(out.ValueMatrix, &emptyValueList)
var perr error
filteredRes = make([]*result, 0, pl.Length(opts.AfterUID))
pl.Postings(opts, func(p *protos.Posting) bool {
res := true
res, perr = applyFacetsTree(p.Facets, facetsTree)
if perr != nil {
return false // break loop.
}
if res {
filteredRes = append(filteredRes, &result{
uid: p.Uid,
facets: facets.CopyFacets(p.Facets, q.FacetParam)})
}
return true // continue iteration.
})
if perr != nil {
return perr
}
// add facets to result.
if q.FacetParam != nil {
var fcsList []*protos.Facets
for _, fres := range filteredRes {
fcsList = append(fcsList, &protos.Facets{fres.facets})
}
out.FacetMatrix = append(out.FacetMatrix, &protos.FacetsList{fcsList})
}
switch {
case q.DoCount:
out.Counts = append(out.Counts, uint32(pl.Length(0)))
// Add an empty UID list to make later processing consistent
out.UidMatrix = append(out.UidMatrix, &emptyUIDList)
case srcFn.fnType == CompareScalarFn:
count := int64(pl.Length(0))
if EvalCompare(srcFn.fname, count, srcFn.threshold) {
tlist := &protos.List{[]uint64{q.UidList.Uids[i]}}
out.UidMatrix = append(out.UidMatrix, tlist)
}
case srcFn.fnType == HasFn:
count := int64(pl.Length(0))
if EvalCompare("gt", count, 0) {
tlist := &protos.List{[]uint64{q.UidList.Uids[i]}}
out.UidMatrix = append(out.UidMatrix, tlist)
}
case srcFn.fnType == UidInFn:
reqList := &protos.List{[]uint64{srcFn.uidPresent}}
topts := posting.ListOptions{
AfterUID: 0,
Intersect: reqList,
}
plist := pl.Uids(topts)
if len(plist.Uids) > 0 {
tlist := &protos.List{[]uint64{q.UidList.Uids[i]}}
out.UidMatrix = append(out.UidMatrix, tlist)
}
default:
// The more usual case: Getting the UIDs.
uidList := new(protos.List)
for _, fres := range filteredRes {
uidList.Uids = append(uidList.Uids, fres.uid)
}
out.UidMatrix = append(out.UidMatrix, uidList)
}
}
return nil
}
// This function should only be used by upsert. Upsert mutation also does a query which will wait
// for the mutation to complete and hence would get stuck. Therefore, we only need to wait till
// index - 1.
func (n *node) processUpsertTask(ctx context.Context, t *task, gid uint32) (*protos.Result, error) {
if err := n.Applied.WaitForMark(ctx, t.rid-1); err != nil {
return nil, err
}
return helpProcessTask(ctx, t.upsert, gid)
}
// processTask processes the query, accumulates and returns the result.
func processTask(ctx context.Context, q *protos.Query, gid uint32) (*protos.Result, error) {
n := groups().Node
if err := n.WaitLinearizableRead(ctx); err != nil {
return &emptyResult, err
}
// 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 paritioned away from
// group zero as long as it's not removed.
if !groups().ServesTablet(q.Attr) {
return &emptyResult, errUnservedTablet
}
return helpProcessTask(ctx, q, gid)
}
func helpProcessTask(ctx context.Context, q *protos.Query, gid uint32) (*protos.Result, error) {
out := new(protos.Result)
attr := q.Attr
srcFn, err := parseSrcFn(q)
if err != nil {
return nil, err
}
if q.Reverse && !schema.State().IsReversed(attr) {
return nil, x.Errorf("Predicate %s doesn't have reverse edge", attr)
}
if needsIndex(srcFn.fnType) && !schema.State().IsIndexed(q.Attr) {
return nil, x.Errorf("Predicate %s is not indexed", q.Attr)
}
typ, err := schema.State().TypeOf(attr)
if err != nil {
if q.UidList == nil {
return out, nil
}
// Schema not defined, so lets add dummy values and return.
// Adding dummy values is important because the code assumes that len(SrcUids) equals
// len(uidMatrix)
for i := 0; i < len(q.UidList.Uids); i++ {
out.UidMatrix = append(out.UidMatrix, &emptyUIDList)
out.ValueMatrix = append(out.ValueMatrix, &emptyValueList)
}
return out, nil
}
srcFn.atype = typ
opts := posting.ListOptions{
AfterUID: uint64(q.AfterUid),
}
// If we have srcFunc and Uids, it means its a filter. So we intersect.
if srcFn.fnType != NotAFunction && q.UidList != nil && len(q.UidList.Uids) > 0 {
opts.Intersect = q.UidList
}
args := funcArgs{q, gid, srcFn, out}
needsValPostings, err := srcFn.needsValuePostings(typ)
if err != nil {
return nil, err
}
if needsValPostings {
if err = handleValuePostings(ctx, args); err != nil {
return nil, err
}
} else {
if err = handleUidPostings(ctx, args, opts); err != nil {
return nil, err
}
}
if srcFn.fnType == HasFn && srcFn.isFuncAtRoot {
if err := handleHasFunction(funcArgs{q, gid, srcFn, out}); err != nil {
return nil, err
}
}
if srcFn.fnType == CompareScalarFn && srcFn.isFuncAtRoot {
if err := handleCompareScalarFunction(funcArgs{q, gid, srcFn, out}); err != nil {
return nil, err
}
}
if srcFn.fnType == RegexFn {
// Go through the indexkeys for the predicate and match them with
// the regex matcher.
if err := handleRegexFunction(ctx, funcArgs{q, gid, srcFn, out}); err != nil {
return nil, err
}
}
// We fetch the actual value for the uids, compare them to the value in the
// request and filter the uids only if the tokenizer IsLossy.
if srcFn.fnType == CompareAttrFn && len(srcFn.tokens) > 0 {
if err := handleCompareFunction(ctx, funcArgs{q, gid, srcFn, out}); err != nil {
return nil, err
}
}
// If geo filter, do value check for correctness.
if srcFn.geoQuery != nil {
filterGeoFunction(funcArgs{q, gid, srcFn, out})
}
// For string matching functions, check the language.
if needsStringFiltering(srcFn, q.Langs) {
filterStringFunction(funcArgs{q, gid, srcFn, out})
}
out.IntersectDest = srcFn.intersectDest
return out, nil
}
func needsStringFiltering(srcFn *functionContext, langs []string) bool {
return srcFn.isStringFn && langForFunc(langs) != "." &&
(srcFn.fnType == StandardFn || srcFn.fnType == HasFn ||
srcFn.fnType == FullTextSearchFn || srcFn.fnType == CompareAttrFn)
}
func handleHasFunction(arg funcArgs) error {
attr := arg.q.Attr
if ok := schema.State().HasCount(attr); !ok {
return x.Errorf("Need @count directive in schema for attr: %s for fn: %s at root.",
attr, arg.srcFn.fname)
}
cp := countParams{
count: 0,
fn: "gt",
attr: attr,
gid: arg.gid,
reverse: arg.q.Reverse,
}
cp.evaluate(arg.out)
return nil
}
func handleCompareScalarFunction(arg funcArgs) error {
attr := arg.q.Attr
if ok := schema.State().HasCount(attr); !ok {
return x.Errorf("Need @count directive in schema for attr: %s for fn: %s at root",
attr, arg.srcFn.fname)
}
count := arg.srcFn.threshold
cp := countParams{
fn: arg.srcFn.fname,
count: count,
attr: attr,
gid: arg.gid,
reverse: arg.q.Reverse,
}
cp.evaluate(arg.out)
return nil
}
func handleRegexFunction(ctx context.Context, arg funcArgs) error {
attr := arg.q.Attr
typ, err := schema.State().TypeOf(attr)
if err != nil || !typ.IsScalar() {
return x.Errorf("Attribute not scalar: %s %v", attr, typ)
}
if typ != types.StringID {
return x.Errorf("Got non-string type. Regex match is allowed only on string type.")
}
tokenizers := schema.State().TokenizerNames(attr)
var found bool
for _, t := range tokenizers {
if t == "trigram" { // TODO(tzdybal) - maybe just rename to 'regex' tokenizer?
found = true
}
}
if !found {
return x.Errorf("Attribute %v does not have trigram index for regex matching.", attr)
}
query := cindex.RegexpQuery(arg.srcFn.regex.Syntax)
empty := protos.List{}
uids, err := uidsForRegex(attr, arg.gid, query, &empty)
lang := langForFunc(arg.q.Langs)
if uids != nil {
arg.out.UidMatrix = append(arg.out.UidMatrix, uids)
var values []types.Val
for _, uid := range uids.Uids {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
key := x.DataKey(attr, uid)
pl := posting.Get(key)
var val types.Val
if lang != "" {
val, err = pl.ValueForTag(lang)
} else {
val, err = pl.Value()
}
if err != nil {
continue
}
// conver data from binary to appropriate format
strVal, err := types.Convert(val, types.StringID)
if err == nil {
values = append(values, strVal)
}
}
filtered := matchRegex(uids, values, arg.srcFn.regex)
for i := 0; i < len(arg.out.UidMatrix); i++ {
algo.IntersectWith(arg.out.UidMatrix[i], filtered, arg.out.UidMatrix[i])
}
} else {
return err
}
return nil
}
func handleCompareFunction(ctx context.Context, arg funcArgs) error {
attr := arg.q.Attr
tokenizer, err := pickTokenizer(attr, arg.srcFn.fname)
// We should already have checked this in getInequalityTokens.
x.Check(err)
// Only if the tokenizer that we used IsLossy, then we need to fetch
// and compare the actual values.
if tokenizer.IsLossy() {
// Need to evaluate inequality for entries in the first bucket.
typ, err := schema.State().TypeOf(attr)
if err != nil || !typ.IsScalar() {
return x.Errorf("Attribute not scalar: %s %v", attr, typ)
}
x.AssertTrue(len(arg.out.UidMatrix) > 0)
rowsToFilter := 0
if arg.srcFn.fname == eq {
// If fn is eq, we could have multiple arguments and hence multiple rows
// to filter.
rowsToFilter = len(arg.srcFn.tokens)
} else if arg.srcFn.tokens[0] == arg.srcFn.ineqValueToken {
// If operation is not eq and ineqValueToken equals first token,
// then we need to filter first row..
rowsToFilter = 1
}
lang := langForFunc(arg.q.Langs)
for row := 0; row < rowsToFilter; row++ {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
algo.ApplyFilter(arg.out.UidMatrix[row], func(uid uint64, i int) bool {
switch lang {
case "":
pl := posting.GetNoStore(x.DataKey(attr, uid))
sv, err := pl.Value()
if err == nil {
dst, err := types.Convert(sv, typ)
return err == nil &&
types.CompareVals(arg.q.SrcFunc.Name, dst, arg.srcFn.eqTokens[row])
}
return false
case ".":
pl := posting.GetNoStore(x.DataKey(attr, uid))
values, _ := pl.AllValues()
for _, sv := range values {
dst, err := types.Convert(sv, typ)
if err == nil &&
types.CompareVals(arg.q.SrcFunc.Name, dst, arg.srcFn.eqTokens[row]) {
return true
}
}
return false
default:
sv, err := fetchValue(uid, attr, arg.q.Langs, typ)
if sv.Value == nil || err != nil {
return false
}
return types.CompareVals(arg.q.SrcFunc.Name, sv, arg.srcFn.eqTokens[row])
}
})
}
}
return nil
}
func filterGeoFunction(arg funcArgs) {
attr := arg.q.Attr
var values []*protos.TaskValue
uids := algo.MergeSorted(arg.out.UidMatrix)
for _, uid := range uids.Uids {
key := x.DataKey(attr, uid)
pl := posting.Get(key)
val, err := pl.Value()
newValue := &protos.TaskValue{ValType: int32(val.Tid)}
if err == nil {
newValue.Val = val.Value.([]byte)
} else {
newValue.Val = x.Nilbyte
}
values = append(values, newValue)
}
filtered := types.FilterGeoUids(uids, values, arg.srcFn.geoQuery)
for i := 0; i < len(arg.out.UidMatrix); i++ {
algo.IntersectWith(arg.out.UidMatrix[i], filtered, arg.out.UidMatrix[i])
}
}
func filterStringFunction(arg funcArgs) {
attr := arg.q.Attr
uids := algo.MergeSorted(arg.out.UidMatrix)
var values [][]types.Val
filteredUids := make([]uint64, 0, len(uids.Uids))
lang := langForFunc(arg.q.Langs)
for _, uid := range uids.Uids {
key := x.DataKey(attr, uid)
pl := posting.Get(key)
var vals []types.Val
var val types.Val
var err error
if lang == "" {
if schema.State().IsList(attr) {
vals, err = pl.AllValues()
} else {
val, err = pl.Value()
vals = append(vals, val)
}
} else {
val, err = pl.ValueForTag(lang)
vals = append(vals, val)
}
if err != nil {
continue
}
var strVals []types.Val
for _, v := range vals {
// convert data from binary to appropriate format
strVal, err := types.Convert(v, types.StringID)
if err != nil {
continue
}
strVals = append(strVals, strVal)
}
if len(strVals) > 0 {
values = append(values, strVals)
filteredUids = append(filteredUids, uid)
}
}
filtered := &protos.List{Uids: filteredUids}
filter := stringFilter{
funcName: arg.srcFn.fname,
funcType: arg.srcFn.fnType,
lang: lang,
}
switch arg.srcFn.fnType {
case HasFn:
// Dont do anything, as filtering based on lang is already
// done above.
case FullTextSearchFn, StandardFn:
filter.tokens = arg.srcFn.tokens
filter.match = defaultMatch
filtered = matchStrings(filtered, values, filter)
case CompareAttrFn:
filter.ineqValue = arg.srcFn.ineqValue
filter.eqVals = arg.srcFn.eqTokens
filter.match = ineqMatch
filtered = matchStrings(uids, values, filter)
}
for i := 0; i < len(arg.out.UidMatrix); i++ {
algo.IntersectWith(arg.out.UidMatrix[i], filtered, arg.out.UidMatrix[i])
}
}
func matchRegex(uids *protos.List, values []types.Val, regex *cregexp.Regexp) *protos.List {
rv := &protos.List{}
for i := 0; i < len(values); i++ {
if len(values[i].Value.(string)) == 0 {
continue
}
if regex.MatchString(values[i].Value.(string), true, true) > 0 {
rv.Uids = append(rv.Uids, uids.Uids[i])
}
}
return rv
}
type functionContext struct {
tokens []string
geoQuery *types.GeoQueryData
intersectDest bool
ineqValue types.Val
eqTokens []types.Val
ineqValueToken string
n int
threshold int64
uidPresent uint64
fname string
fnType FuncType
regex *cregexp.Regexp
isFuncAtRoot bool
isStringFn bool
atype types.TypeID
}
const (
eq = "eq" // equal
)
func ensureArgsCount(srcFunc *protos.SrcFunction, expected int) error {
if len(srcFunc.Args) != expected {
return x.Errorf("Function '%s' requires %d arguments, but got %d (%v)",
srcFunc.Name, expected, len(srcFunc.Args), srcFunc.Args)
}
return nil
}
func checkRoot(q *protos.Query, fc *functionContext) {
if q.UidList == nil {
// Fetch Uids from Store and populate in q.UidList.
fc.n = 0
fc.isFuncAtRoot = true
} else {
fc.n = len(q.UidList.Uids)
}
}
// We allow atmost one lang in functions. We can inline in 1.9.
func langForFunc(langs []string) string {
x.AssertTrue(len(langs) <= 1)
if len(langs) == 0 {
return ""
}
return langs[0]
}
func parseSrcFn(q *protos.Query) (*functionContext, error) {
fnType, f := parseFuncType(q.SrcFunc)
attr := q.Attr
fc := &functionContext{fnType: fnType, fname: f}
var err error
t, err := schema.State().TypeOf(attr)