-
Notifications
You must be signed in to change notification settings - Fork 243
/
xrefs.go
1786 lines (1580 loc) · 55.1 KB
/
xrefs.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 2015 The Kythe Authors. All rights reserved.
*
* 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 xrefs provides a high-performance table-based implementation of the
// xrefs.Service.
//
// Table format:
//
// decor:<ticket> -> srvpb.FileDecorations
// docs:<ticket> -> srvpb.Document
// xrefs:<ticket> -> srvpb.PagedCrossReferences
// xrefPages:<page_key> -> srvpb.PagedCrossReferences_Page
package xrefs // import "kythe.io/kythe/go/serving/xrefs"
import (
"context"
"encoding/base64"
"flag"
"fmt"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"kythe.io/kythe/go/services/xrefs"
"kythe.io/kythe/go/storage/table"
"kythe.io/kythe/go/util/flagutil"
"kythe.io/kythe/go/util/kytheuri"
"kythe.io/kythe/go/util/log"
"kythe.io/kythe/go/util/schema/edges"
"kythe.io/kythe/go/util/schema/facts"
"kythe.io/kythe/go/util/schema/tickets"
"kythe.io/kythe/go/util/span"
"bitbucket.org/creachadair/stringset"
"github.com/golang/snappy"
"golang.org/x/net/trace"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
cpb "kythe.io/kythe/proto/common_go_proto"
ipb "kythe.io/kythe/proto/internal_go_proto"
srvpb "kythe.io/kythe/proto/serving_go_proto"
xpb "kythe.io/kythe/proto/xref_go_proto"
)
var (
mergeCrossReferences = flag.Bool("merge_cross_references", true, "Whether to merge nodes when responding to a CrossReferencesRequest")
experimentalCrossReferenceIndirectionKinds flagutil.StringMultimap
// TODO(schroederc): remove once relevant clients specify their required quality
defaultTotalsQuality = flag.String("experimental_default_totals_quality", "APPROXIMATE_TOTALS", "Default TotalsQuality when unspecified in CrossReferencesRequest")
pageReadAhead = flag.Uint("page_read_ahead", 0, "How many xref pages to read ahead concurrently (0 disables readahead)")
responseLeewayTime = flag.Duration("xrefs_response_leeway_time", 50*time.Millisecond, "If possible, leave this much time at the end of a CrossReferencesRequest to return any results already read")
)
func init() {
flag.Var(&experimentalCrossReferenceIndirectionKinds, "experimental_cross_reference_indirection_kinds",
`Comma-separated set of key-value pairs (node_kind=edge_kind) to indirect through in CrossReferences. For example, "talias=/kythe/edge/aliases" indicates that the targets of a 'talias' node's '/kythe/edge/aliases' related nodes will have their cross-references merged into the root 'talias' node's. A "*=edge_kind" entry indicates to indirect through the specified edge kind for any node kind.`)
}
type staticLookupTables interface {
fileDecorations(ctx context.Context, ticket string) (*srvpb.FileDecorations, error)
crossReferences(ctx context.Context, ticket string) (*srvpb.PagedCrossReferences, error)
crossReferencesPage(ctx context.Context, key string) (*srvpb.PagedCrossReferences_Page, error)
documentation(ctx context.Context, ticket string) (*srvpb.Document, error)
}
// SplitTable implements the xrefs Service interface using separate static
// lookup tables for each API component.
type SplitTable struct {
// Decorations is a table of srvpb.FileDecorations keyed by their source
// location tickets.
Decorations table.Proto
// CrossReferences is a table of srvpb.PagedCrossReferences keyed by their
// source node tickets.
CrossReferences table.Proto
// CrossReferencePages is a table of srvpb.PagedCrossReferences_Pages keyed by
// their page keys.
CrossReferencePages table.Proto
// Documentation is a table of srvpb.Documents keyed by their node ticket.
Documentation table.Proto
// RewriteEdgeLabel is an optional callback to rewrite edge labels.
// It will be called once per request; the function it returns will then be
// called once per edge.
RewriteEdgeLabel func(context.Context) func(string) string
}
func (s *SplitTable) rewriteFileDecorations(ctx context.Context, fd *srvpb.FileDecorations, err error) (*srvpb.FileDecorations, error) {
if fd == nil || err != nil || s.RewriteEdgeLabel == nil || fd.Decoration == nil {
return fd, err
}
f := s.RewriteEdgeLabel(ctx)
if f == nil {
return fd, err
}
for _, d := range fd.Decoration {
d.Kind = f(d.Kind)
}
return fd, err
}
func rewriteCrossReferencesGroup(g *srvpb.PagedCrossReferences_Group, f func(string) string) {
if f != nil && g != nil {
g.Kind = f(g.Kind)
}
}
func (s *SplitTable) rewriteCrossReferences(ctx context.Context, cr *srvpb.PagedCrossReferences, err error) (*srvpb.PagedCrossReferences, error) {
if cr == nil || err != nil || s.RewriteEdgeLabel == nil || cr.Group == nil {
return cr, err
}
f := s.RewriteEdgeLabel(ctx)
for _, g := range cr.Group {
rewriteCrossReferencesGroup(g, f)
}
return cr, err
}
func (s *SplitTable) rewriteCrossReferencesPage(ctx context.Context, cr *srvpb.PagedCrossReferences_Page, err error) (*srvpb.PagedCrossReferences_Page, error) {
if cr == nil || err != nil || s.RewriteEdgeLabel == nil || cr.Group == nil {
return cr, err
}
f := s.RewriteEdgeLabel(ctx)
rewriteCrossReferencesGroup(cr.Group, f)
return cr, err
}
func (s *SplitTable) fileDecorations(ctx context.Context, ticket string) (*srvpb.FileDecorations, error) {
tracePrintf(ctx, "Reading FileDecorations: %s", ticket)
var fd srvpb.FileDecorations
return s.rewriteFileDecorations(ctx, &fd, s.Decorations.Lookup(ctx, []byte(ticket), &fd))
}
func (s *SplitTable) crossReferences(ctx context.Context, ticket string) (*srvpb.PagedCrossReferences, error) {
tracePrintf(ctx, "Reading PagedCrossReferences: %s", ticket)
var cr srvpb.PagedCrossReferences
return s.rewriteCrossReferences(ctx, &cr, s.CrossReferences.Lookup(ctx, []byte(ticket), &cr))
}
func (s *SplitTable) crossReferencesPage(ctx context.Context, key string) (*srvpb.PagedCrossReferences_Page, error) {
tracePrintf(ctx, "Reading PagedCrossReferences.Page: %s", key)
var p srvpb.PagedCrossReferences_Page
return s.rewriteCrossReferencesPage(ctx, &p, s.CrossReferencePages.Lookup(ctx, []byte(key), &p))
}
func (s *SplitTable) documentation(ctx context.Context, ticket string) (*srvpb.Document, error) {
tracePrintf(ctx, "Reading Document: %s", ticket)
var d srvpb.Document
return &d, s.Documentation.Lookup(ctx, []byte(ticket), &d)
}
// Key prefixes for the combinedTable implementation.
const (
crossRefTablePrefix = "xrefs:"
crossRefPageTablePrefix = "xrefPages:"
decorTablePrefix = "decor:"
documentationTablePrefix = "docs:"
)
type combinedTable struct{ table.Proto }
func (c *combinedTable) fileDecorations(ctx context.Context, ticket string) (*srvpb.FileDecorations, error) {
var fd srvpb.FileDecorations
return &fd, c.Lookup(ctx, DecorationsKey(ticket), &fd)
}
func (c *combinedTable) crossReferences(ctx context.Context, ticket string) (*srvpb.PagedCrossReferences, error) {
var cr srvpb.PagedCrossReferences
return &cr, c.Lookup(ctx, CrossReferencesKey(ticket), &cr)
}
func (c *combinedTable) crossReferencesPage(ctx context.Context, key string) (*srvpb.PagedCrossReferences_Page, error) {
var p srvpb.PagedCrossReferences_Page
return &p, c.Lookup(ctx, CrossReferencesPageKey(key), &p)
}
func (c *combinedTable) documentation(ctx context.Context, ticket string) (*srvpb.Document, error) {
var d srvpb.Document
return &d, c.Lookup(ctx, DocumentationKey(ticket), &d)
}
// NewSplitTable returns a table based on the given serving tables for each API
// component.
func NewSplitTable(c *SplitTable) *Table { return &Table{staticLookupTables: c} }
// NewCombinedTable returns a table for the given combined xrefs lookup table.
// The table's keys are expected to be constructed using only the *Key functions.
func NewCombinedTable(t table.Proto) *Table { return &Table{staticLookupTables: &combinedTable{t}} }
// DecorationsKey returns the decorations CombinedTable key for the given source
// location ticket.
func DecorationsKey(ticket string) []byte {
return []byte(decorTablePrefix + ticket)
}
// CrossReferencesKey returns the cross-references CombinedTable key for the
// given node ticket.
func CrossReferencesKey(ticket string) []byte {
return []byte(crossRefTablePrefix + ticket)
}
// CrossReferencesPageKey returns the cross-references page CombinedTable key
// for the given key.
func CrossReferencesPageKey(key string) []byte {
return []byte(crossRefPageTablePrefix + key)
}
// DocumentationKey returns the documentation CombinedTable key for the given
// ticket.
func DocumentationKey(ticket string) []byte {
return []byte(documentationTablePrefix + ticket)
}
// Table implements the xrefs Service interface using static lookup tables.
type Table struct {
staticLookupTables
// MakePatcher returns a patching client that targets a Workspace.
MakePatcher func(context.Context, *xpb.Workspace) (MultiFilePatcher, error)
// ResolvePath is used to resolve CorpusPaths for filtering. If unset,
// DefaultResolvePath will be used.
ResolvePath PathResolver
}
// A PathResolver resolves a CorpusPath into a single filepath.
type PathResolver func(*cpb.CorpusPath) string
// DefaultResolvePath returns the default resolved path for the CorpusPath by
// joining its corpus, root, and path into a single filepath.
func DefaultResolvePath(cp *cpb.CorpusPath) string {
return filepath.Join(cp.GetCorpus(), cp.GetRoot(), cp.GetPath())
}
// A MultiFilePatcher provides an interface to patch sets of xref anchors to an
// underlying baseline, usually a Workspace.
//
// After creation, the client is required to call AddFile for each possible file
// referenced by any anchors that will be patched. After the files are added, a
// set of anchors may be passed to PatchAnchors.
type MultiFilePatcher interface {
// AddFile adds a file to current set of files to patch against.
AddFile(context.Context, *srvpb.FileInfo) error
// PatchAnchors updates the set of anchors given to match their referenced
// files' state as known by the MultiLinePatcher, usually based on a
// Workspace. If an anchor no longer exists, it will be ellided from the
// returned set. Otherwise, the ordering of the anchors will be retained.
PatchAnchors(context.Context, []*xpb.Anchor) ([]*xpb.Anchor, error)
// PatchRelatedAnchors updates the set of related anchors given to match their
// referenced files' state as known by the MultiLinePatcher, usually based on
// a Workspace. If an anchor no longer exists, it will be ellided from the
// returned set. Otherwise, the ordering of the anchors will be retained.
PatchRelatedAnchors(context.Context, []*xpb.CrossReferencesReply_RelatedAnchor) ([]*xpb.CrossReferencesReply_RelatedAnchor, error)
// Close releases any resources used the patcher. Further calls to the
// patcher will become invalid.
Close() error
}
const (
defaultPageSize = 2048
maxPageSize = 10000
)
type nodeConverter struct {
factPatterns []*regexp.Regexp
}
func (c *nodeConverter) ToInfo(n *srvpb.Node) *cpb.NodeInfo {
ni := &cpb.NodeInfo{Facts: make(map[string][]byte, len(n.Fact))}
for _, f := range n.Fact {
if xrefs.MatchesAny(f.Name, c.factPatterns) {
ni.Facts[f.Name] = f.Value
}
}
if len(ni.Facts) == 0 {
return nil
}
return ni
}
func corpusPathTicket(cp *cpb.CorpusPath) string { return kytheuri.FromCorpusPath(cp).String() }
// Decorations implements part of the xrefs Service interface.
func (t *Table) Decorations(ctx context.Context, req *xpb.DecorationsRequest) (*xpb.DecorationsReply, error) {
if req.GetLocation() == nil || req.GetLocation().Ticket == "" {
return nil, status.Error(codes.InvalidArgument, "missing location")
}
ticket, err := kytheuri.Fix(req.GetLocation().Ticket)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid ticket %q: %v", req.GetLocation().Ticket, err)
}
var multiPatcher MultiFilePatcher
if t.MakePatcher != nil && req.GetWorkspace() != nil && req.GetPatchAgainstWorkspace() {
multiPatcher, err = t.MakePatcher(ctx, req.GetWorkspace())
if isNonContextError(err) {
log.Errorf("creating patcher: %v", err)
}
if multiPatcher != nil {
defer func() {
if err := multiPatcher.Close(); isNonContextError(err) {
// No need to fail the request; just log the error.
log.Errorf("closing patcher: %v", err)
}
}()
}
}
decor, err := t.fileDecorations(ctx, ticket)
if err == table.ErrNoSuchKey {
return nil, xrefs.ErrDecorationsNotFound
} else if err != nil {
return nil, canonicalError(err, "file decorations", ticket)
}
if decor.File == nil {
if len(decor.Diagnostic) == 0 {
log.Errorf("FileDecorations.file is missing without related diagnostics: %q", req.Location.Ticket)
return nil, xrefs.ErrDecorationsNotFound
}
// FileDecorations may be saved without a File if the file does not exist in
// the index but related diagnostics do exist. If diagnostics were
// requested, we may return them successfully, but otherwise, an error
// indicating a missing file is returned.
if req.Diagnostics {
return &xpb.DecorationsReply{
Location: req.Location,
Diagnostic: decor.Diagnostic,
}, nil
}
return nil, xrefs.ErrDecorationsNotFound
}
text := decor.File.Text
if len(req.DirtyBuffer) > 0 {
text = req.DirtyBuffer
}
norm := span.NewNormalizer(text)
loc, err := norm.Location(req.GetLocation())
if err != nil {
return nil, err
}
fileInfos := makeFileInfoMap(decor.FileInfo)
reply := &xpb.DecorationsReply{
Location: loc,
Revision: fileInfos[loc.GetTicket()].GetRevision(),
}
for _, g := range decor.GeneratedBy {
uri, err := kytheuri.Parse(g)
if err != nil {
return nil, fmt.Errorf("unable to parse generated_by ticket %q: %w", g, err)
}
reply.GeneratedByFile = append(reply.GeneratedByFile, &xpb.File{
CorpusPath: &cpb.CorpusPath{
Corpus: uri.Corpus,
Root: uri.Root,
Path: uri.Path,
},
Revision: fileInfos[g].GetRevision(),
})
}
if req.SourceText && text != nil {
reply.Encoding = decor.File.Encoding
if loc.Kind == xpb.Location_FILE {
reply.SourceText = text
} else {
reply.SourceText = text[loc.Span.Start.ByteOffset:loc.Span.End.ByteOffset]
}
}
var patcher *span.Patcher
if len(req.DirtyBuffer) > 0 {
if multiPatcher != nil {
return nil, status.Errorf(codes.Unimplemented, "cannot patch decorations against Workspace with a dirty_buffer")
}
patcher, err = span.NewPatcher(decor.File.Text, req.DirtyBuffer)
if err != nil {
return nil, status.Errorf(codes.Internal, "error patching decorations for %s: %v", req.Location.Ticket, err)
}
}
// The span with which to constrain the set of returned anchor references.
var startBoundary, endBoundary int32
spanKind := req.SpanKind
if loc.Kind == xpb.Location_FILE {
startBoundary = 0
endBoundary = int32(len(text))
spanKind = xpb.DecorationsRequest_WITHIN_SPAN
} else {
startBoundary = loc.Span.Start.ByteOffset
endBoundary = loc.Span.End.ByteOffset
}
if req.References {
patterns := xrefs.ConvertFilters(req.Filter)
buildConfigs := stringset.New(req.BuildConfig...)
ac := &anchorConverter{fileInfos: fileInfos}
nc := &nodeConverter{patterns}
reply.Reference = make([]*xpb.DecorationsReply_Reference, 0, len(decor.Decoration))
reply.Nodes = make(map[string]*cpb.NodeInfo, len(decor.Target))
// Reference.TargetTicket -> NodeInfo (superset of reply.Nodes)
nodes := make(map[string]*cpb.NodeInfo, len(decor.Target))
if len(patterns) > 0 {
for _, n := range decor.Target {
if info := nc.ToInfo(n); info != nil {
nodes[n.Ticket] = info
}
}
}
tracePrintf(ctx, "Potential target nodes: %d", len(nodes))
// All known definition locations (Anchor.Ticket -> Anchor)
defs := make(map[string]*xpb.Anchor, len(decor.TargetDefinitions))
for _, def := range decor.TargetDefinitions {
a := ac.Convert(def).Anchor
defs[def.Ticket] = a
if multiPatcher != nil {
fileInfo := def.GetFileInfo()
if fileInfo == nil {
fileInfo = fileInfos[a.GetParent()]
}
if fileInfo != nil {
if err := multiPatcher.AddFile(ctx, fileInfo); isNonContextError(err) {
// Attempt to continue with the request, just log the error.
log.Errorf("adding file: %v", err)
}
}
}
}
if req.TargetDefinitions {
reply.DefinitionLocations = make(map[string]*xpb.Anchor, len(decor.TargetDefinitions))
}
tracePrintf(ctx, "Potential target defs: %d", len(defs))
bindings := stringset.New()
for _, d := range decor.Decoration {
// Filter decorations by requested build configs.
if len(buildConfigs) != 0 && !buildConfigs.Contains(d.Anchor.BuildConfiguration) {
continue
}
start, end, exists := patcher.Patch(d.Anchor.StartOffset, d.Anchor.EndOffset)
// Filter non-existent anchor. Anchors can no longer exist if we were
// given a dirty buffer and the anchor was inside a changed region.
if !exists || !span.InBounds(spanKind, start, end, startBoundary, endBoundary) {
continue
}
d.Anchor.StartOffset = start
d.Anchor.EndOffset = end
r := decorationToReference(norm, d)
if req.TargetDefinitions {
if def, ok := defs[d.TargetDefinition]; ok {
reply.DefinitionLocations[d.TargetDefinition] = def
}
} else {
r.TargetDefinition = ""
}
if !req.SemanticScopes {
r.SemanticScope = ""
}
// Populate any target revision, if known
r.TargetRevision = fileInfos[r.TargetTicket].GetRevision()
if req.ExtendsOverrides && (r.Kind == edges.Defines || r.Kind == edges.DefinesBinding) {
bindings.Add(r.TargetTicket)
}
reply.Reference = append(reply.Reference, r)
if n := nodes[r.TargetTicket]; n != nil {
reply.Nodes[r.TargetTicket] = n
}
}
tracePrintf(ctx, "References: %d", len(reply.Reference))
if len(decor.TargetOverride) > 0 {
// Read overrides from serving data
reply.ExtendsOverrides = make(map[string]*xpb.DecorationsReply_Overrides, len(bindings))
for _, o := range decor.TargetOverride {
if bindings.Contains(o.Overriding) {
def := defs[o.OverriddenDefinition]
if def != nil && len(buildConfigs) != 0 && !buildConfigs.Contains(def.BuildConfig) {
// Skip override with undesirable build configuration.
continue
}
os, ok := reply.ExtendsOverrides[o.Overriding]
if !ok {
os = &xpb.DecorationsReply_Overrides{}
reply.ExtendsOverrides[o.Overriding] = os
}
ov := &xpb.DecorationsReply_Override{
Target: o.Overridden,
Kind: xpb.DecorationsReply_Override_Kind(o.Kind),
MarkedSource: o.MarkedSource,
}
os.Override = append(os.Override, ov)
if n := nodes[o.Overridden]; n != nil {
reply.Nodes[o.Overridden] = n
}
if req.TargetDefinitions && def != nil {
ov.TargetDefinition = o.OverriddenDefinition
reply.DefinitionLocations[o.OverriddenDefinition] = def
}
}
}
tracePrintf(ctx, "ExtendsOverrides: %d", len(reply.ExtendsOverrides))
}
tracePrintf(ctx, "DefinitionLocations: %d", len(reply.DefinitionLocations))
}
if req.Diagnostics {
for _, diag := range decor.Diagnostic {
if diag.Span == nil {
reply.Diagnostic = append(reply.Diagnostic, diag)
} else {
start, end, exists := patcher.Patch(span.ByteOffsets(diag.Span))
// Filter non-existent (or out-of-bounds) diagnostic. Diagnostics can
// no longer exist if we were given a dirty buffer and the diagnostic
// was inside a changed region.
if !exists || !span.InBounds(spanKind, start, end, startBoundary, endBoundary) {
continue
}
diag.Span = norm.SpanOffsets(start, end)
reply.Diagnostic = append(reply.Diagnostic, diag)
}
}
tracePrintf(ctx, "Diagnostics: %d", len(reply.Diagnostic))
}
if req.Snippets == xpb.SnippetsKind_NONE {
for _, anchor := range reply.DefinitionLocations {
clearSnippet(anchor)
}
}
if multiPatcher != nil {
defs, err := patchDefLocations(ctx, multiPatcher, reply.GetDefinitionLocations())
if err != nil {
log.Errorf("patching definition locations: %v", err)
} else {
reply.DefinitionLocations = defs
}
}
return reply, nil
}
func patchDefLocations(ctx context.Context, patcher MultiFilePatcher, defLocs map[string]*xpb.Anchor) (map[string]*xpb.Anchor, error) {
if len(defLocs) == 0 {
return nil, nil
}
defs := make([]*xpb.Anchor, 0, len(defLocs))
for _, def := range defLocs {
defs = append(defs, def)
}
defs, err := patcher.PatchAnchors(ctx, defs)
if err != nil {
return defLocs, err
}
res := make(map[string]*xpb.Anchor, len(defs))
for _, def := range defs {
res[def.GetTicket()] = def
}
tracePrintf(ctx, "Patched DefinitionLocations: %d", len(defs))
return res, nil
}
func makeFileInfoMap(infos []*srvpb.FileInfo) map[string]*srvpb.FileInfo {
fileInfos := make(map[string]*srvpb.FileInfo, len(infos))
for _, info := range infos {
fileInfos[corpusPathTicket(info.CorpusPath)] = info
}
return fileInfos
}
func decorationToReference(norm *span.Normalizer, d *srvpb.FileDecorations_Decoration) *xpb.DecorationsReply_Reference {
span := norm.SpanOffsets(d.Anchor.StartOffset, d.Anchor.EndOffset)
return &xpb.DecorationsReply_Reference{
TargetTicket: d.Target,
Kind: d.Kind,
Span: span,
TargetDefinition: d.TargetDefinition,
BuildConfig: d.Anchor.BuildConfiguration,
SemanticScope: d.SemanticScope,
}
}
type xrefCategory int
const (
xrefCategoryNone xrefCategory = iota
xrefCategoryDef
xrefCategoryDecl
xrefCategoryRef
xrefCategoryCall
xrefCategoryRelated
xrefCategoryIndirection
)
func (c xrefCategory) AddCount(reply *xpb.CrossReferencesReply, idx *srvpb.PagedCrossReferences_PageIndex, pageSet *pageSet) {
switch c {
case xrefCategoryDef:
if pageSet.Contains(idx) {
reply.Total.Definitions += int64(idx.Count)
} else {
reply.Filtered.Definitions += int64(idx.Count)
}
case xrefCategoryDecl:
if pageSet.Contains(idx) {
reply.Total.Declarations += int64(idx.Count)
} else {
reply.Filtered.Declarations += int64(idx.Count)
}
case xrefCategoryRef:
if pageSet.Contains(idx) {
reply.Total.RefEdgeToCount[strings.TrimPrefix(idx.Kind, "%")] += int64(idx.Count)
reply.Total.References += int64(idx.Count)
} else {
reply.Filtered.RefEdgeToCount[strings.TrimPrefix(idx.Kind, "%")] += int64(idx.Count)
reply.Filtered.References += int64(idx.Count)
}
case xrefCategoryRelated:
if pageSet.Contains(idx) {
reply.Total.RelatedNodesByRelation[idx.Kind] += int64(idx.Count)
} else {
reply.Filtered.RelatedNodesByRelation[idx.Kind] += int64(idx.Count)
}
case xrefCategoryCall:
if pageSet.Contains(idx) {
reply.Total.Callers += int64(idx.Count)
} else {
reply.Filtered.Callers += int64(idx.Count)
}
}
}
// CrossReferences implements part of the xrefs.Service interface.
func (t *Table) CrossReferences(ctx context.Context, req *xpb.CrossReferencesRequest) (*xpb.CrossReferencesReply, error) {
tickets, err := xrefs.FixTickets(req.Ticket)
if err != nil {
return nil, err
}
var leewayTime time.Time
if d, ok := ctx.Deadline(); ok && *responseLeewayTime > 0 {
leewayTime = d.Add(-*responseLeewayTime)
if leewayTime.Before(time.Now()) {
// Clear leeway time; try to use entire leftover timeout.
leewayTime = time.Time{}
}
}
filter, err := compileCorpusPathFilters(req.GetCorpusPathFilters(), t.ResolvePath)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid corpus_path_filters %s: %v", strings.ReplaceAll(req.GetCorpusPathFilters().String(), "\n", " "), err)
}
pageReadGroupCtx, stopReadingPages := context.WithCancel(ctx)
defer stopReadingPages()
pageReadGroup, pageReadGroupCtx := errgroup.WithContext(pageReadGroupCtx)
pageReadGroup.SetLimit(int(*pageReadAhead) + 1)
single := new(syncCache[*srvpb.PagedCrossReferences_Page])
getCachedPage := func(ctx context.Context, pageKey string) (*srvpb.PagedCrossReferences_Page, error) {
return single.Get(pageKey, func() (*srvpb.PagedCrossReferences_Page, error) {
return t.crossReferencesPage(ctx, pageKey)
})
}
getFilteredPage := func(ctx context.Context, pageKey string) (*srvpb.PagedCrossReferences_Page, int, error) {
p, err := getCachedPage(ctx, pageKey)
if err != nil {
return nil, 0, err
}
// Clear page from cache; it should only be used once.
single.Delete(pageKey)
return p, filter.FilterGroup(p.GetGroup()), nil
}
stats := refStats{
max: int(req.PageSize),
refOptions: refOptions{
anchorText: req.AnchorText,
includeScopes: req.SemanticScopes,
},
}
if stats.max < 0 {
return nil, status.Errorf(codes.InvalidArgument, "invalid page_size: %d", req.PageSize)
} else if stats.max == 0 {
stats.max = defaultPageSize
} else if stats.max > maxPageSize {
stats.max = maxPageSize
}
var pageToken ipb.PageToken
if req.PageToken != "" {
rec, err := base64.StdEncoding.DecodeString(req.PageToken)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid page_token: %q", req.PageToken)
}
rec, err = snappy.Decode(nil, rec)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid page_token: %q", req.PageToken)
}
if err := proto.Unmarshal(rec, &pageToken); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid page_token: %q", req.PageToken)
}
for _, index := range pageToken.Indices {
if index < 0 {
return nil, status.Errorf(codes.InvalidArgument, "invalid page_token: %q", req.PageToken)
}
}
}
initialSkip := int(pageToken.Indices["skip"])
stats.skip = initialSkip
reply := &xpb.CrossReferencesReply{
CrossReferences: make(map[string]*xpb.CrossReferencesReply_CrossReferenceSet, len(req.Ticket)),
Nodes: make(map[string]*cpb.NodeInfo, len(req.Ticket)),
Total: &xpb.CrossReferencesReply_Total{
RefEdgeToCount: make(map[string]int64),
},
Filtered: &xpb.CrossReferencesReply_Total{
RefEdgeToCount: make(map[string]int64),
RelatedNodesByRelation: make(map[string]int64),
},
}
// Before we return reply, remove all RefEdgeToCount map entries that point to a 0 count.
defer cleanupRefEdgeToCount(reply)
if len(req.Filter) > 0 {
reply.Total.RelatedNodesByRelation = make(map[string]int64)
}
if req.NodeDefinitions {
reply.DefinitionLocations = make(map[string]*xpb.Anchor)
}
stats.reply = reply
buildConfigs := stringset.New(req.BuildConfig...)
patterns := xrefs.ConvertFilters(req.Filter)
stats.nodeConverter = nodeConverter{patterns}
nextPageToken := &ipb.PageToken{
SubTokens: make(map[string]string),
Indices: make(map[string]int32),
}
mergeInto := make(map[string]string)
for _, ticket := range tickets {
mergeInto[ticket] = ticket
}
relatedKinds := stringset.New(req.RelatedNodeKind...)
wantMoreCrossRefs := (req.DefinitionKind != xpb.CrossReferencesRequest_NO_DEFINITIONS ||
req.DeclarationKind != xpb.CrossReferencesRequest_NO_DECLARATIONS ||
req.ReferenceKind != xpb.CrossReferencesRequest_NO_REFERENCES ||
req.CallerKind != xpb.CrossReferencesRequest_NO_CALLERS ||
len(req.Filter) > 0)
totalsQuality := req.TotalsQuality
if totalsQuality == xpb.CrossReferencesRequest_UNSPECIFIED_TOTALS {
totalsQuality = xpb.CrossReferencesRequest_TotalsQuality(xpb.CrossReferencesRequest_TotalsQuality_value[strings.ToUpper(*defaultTotalsQuality)])
}
var patcher MultiFilePatcher
if t.MakePatcher != nil && req.GetWorkspace() != nil && req.GetPatchAgainstWorkspace() {
patcher, err = t.MakePatcher(ctx, req.GetWorkspace())
if isNonContextError(err) {
log.Errorf("creating patcher: %v", err)
}
if patcher != nil {
defer func() {
if err := patcher.Close(); isNonContextError(err) {
// No need to fail the request; just log the error.
log.Errorf("closing patcher: %v", err)
}
}()
stats.refOptions.patcherFunc = func(f *srvpb.FileInfo) {
if err := patcher.AddFile(ctx, f); isNonContextError(err) {
// Attempt to continue with the request, just log the error.
log.Errorf("adding file: %v", err)
}
}
}
}
// Set of xref page keys to read for further indirection nodes.
var indirectionPages []string
var foundCrossRefs bool
readLoop:
for i := 0; i < len(tickets); i++ {
if totalsQuality == xpb.CrossReferencesRequest_APPROXIMATE_TOTALS && stats.done() {
break
}
if !leewayTime.IsZero() && time.Now().After(leewayTime) {
log.Warning("hit soft deadline; trying to return already read xrefs")
break
}
ticket := tickets[i]
cr, err := t.crossReferences(ctx, ticket)
if err == table.ErrNoSuchKey {
continue
} else if err != nil {
return nil, canonicalError(err, "cross-references", ticket)
}
foundCrossRefs = true
// If this node is to be merged into another, we will use that node's ticket
// for all further book-keeping purposes.
ticket = mergeInto[ticket]
// We may have partially completed the xrefs set due merge nodes.
crs := reply.CrossReferences[ticket]
if crs == nil {
crs = &xpb.CrossReferencesReply_CrossReferenceSet{
Ticket: ticket,
}
reply.CrossReferences[ticket] = crs
// If visiting a non-merge node and facts are requested, add them to the result.
if ticket == cr.SourceTicket && len(patterns) > 0 && cr.SourceNode != nil {
if _, ok := reply.Nodes[ticket]; !ok {
if info := stats.ToInfo(cr.SourceNode); info != nil {
reply.Nodes[ticket] = info
}
}
}
}
if crs.MarkedSource == nil {
crs.MarkedSource = cr.MarkedSource
}
if *mergeCrossReferences {
// Add any additional merge nodes to the set of table lookups
for _, mergeNode := range cr.MergeWith {
tickets = addMergeNode(mergeInto, tickets, ticket, mergeNode)
}
}
// Read the set of indirection edge kinds for the given node kind.
nodeKind := nodeKind(cr.SourceNode)
indirections := experimentalCrossReferenceIndirectionKinds[nodeKind].
Union(experimentalCrossReferenceIndirectionKinds["*"])
for _, grp := range cr.Group {
// Filter anchor groups based on requested build configs
if len(buildConfigs) != 0 && !buildConfigs.Contains(grp.BuildConfig) && !xrefs.IsRelatedNodeKind(relatedKinds, grp.Kind) {
continue
}
switch {
case xrefs.IsDefKind(req.DefinitionKind, grp.Kind, cr.Incomplete):
filtered := filter.FilterGroup(grp)
reply.Total.Definitions += int64(len(grp.Anchor))
reply.Total.Definitions += int64(countRefs(grp.GetScopedReference()))
reply.Filtered.Definitions += int64(filtered)
if wantMoreCrossRefs {
stats.addAnchors(&crs.Definition, grp)
}
case xrefs.IsDeclKind(req.DeclarationKind, grp.Kind, cr.Incomplete):
filtered := filter.FilterGroup(grp)
reply.Total.Declarations += int64(len(grp.Anchor))
reply.Total.Declarations += int64(countRefs(grp.GetScopedReference()))
reply.Filtered.Declarations += int64(filtered)
if wantMoreCrossRefs {
stats.addAnchors(&crs.Declaration, grp)
}
case xrefs.IsRefKind(req.ReferenceKind, grp.Kind):
filtered := filter.FilterGroup(grp)
reply.Total.RefEdgeToCount[strings.TrimPrefix(grp.Kind, "%")] += int64(len(grp.Anchor))
reply.Total.References += int64(len(grp.Anchor))
reply.Total.RefEdgeToCount[strings.TrimPrefix(grp.Kind, "%")] += int64(countRefs(grp.GetScopedReference()))
reply.Total.References += int64(countRefs(grp.GetScopedReference()))
reply.Filtered.RefEdgeToCount[strings.TrimPrefix(grp.Kind, "%")] += int64(filtered)
reply.Filtered.References += int64(filtered)
if wantMoreCrossRefs {
stats.addAnchors(&crs.Reference, grp)
}
case len(grp.RelatedNode) > 0:
// If requested, add related nodes to merge node set.
if indirections.Contains(grp.Kind) {
for _, rn := range grp.RelatedNode {
tickets = addMergeNode(mergeInto, tickets, ticket, rn.Node.GetTicket())
}
}
if len(req.Filter) > 0 && xrefs.IsRelatedNodeKind(relatedKinds, grp.Kind) {
filtered := filter.FilterGroup(grp)
reply.Total.RelatedNodesByRelation[grp.Kind] += int64(len(grp.RelatedNode))
reply.Filtered.RelatedNodesByRelation[grp.Kind] += int64(filtered)
if wantMoreCrossRefs {
stats.addRelatedNodes(crs, grp)
}
}
case xrefs.IsCallerKind(req.CallerKind, grp.Kind):
filtered := filter.FilterGroup(grp)
reply.Total.Callers += int64(len(grp.Caller))
reply.Filtered.Callers += int64(filtered)
if wantMoreCrossRefs {
stats.addCallers(crs, grp)
}
}
}
pageSet := filter.PageSet(cr)
pageCategory := func(idx *srvpb.PagedCrossReferences_PageIndex) xrefCategory {
// Filter anchor pages based on requested build configs
if len(buildConfigs) != 0 && !buildConfigs.Contains(idx.BuildConfig) && !xrefs.IsRelatedNodeKind(relatedKinds, idx.Kind) {
return xrefCategoryNone
}
switch {
case xrefs.IsDefKind(req.DefinitionKind, idx.Kind, cr.Incomplete):
return xrefCategoryDef
case xrefs.IsDeclKind(req.DeclarationKind, idx.Kind, cr.Incomplete):
return xrefCategoryDecl
case xrefs.IsRefKind(req.ReferenceKind, idx.Kind):
return xrefCategoryRef
case len(req.Filter) > 0 && xrefs.IsRelatedNodeKind(relatedKinds, idx.Kind):
return xrefCategoryRelated
case indirections.Contains(idx.Kind):
return xrefCategoryIndirection
case xrefs.IsCallerKind(req.CallerKind, idx.Kind):
return xrefCategoryCall
default:
return xrefCategoryNone
}
}
// Find the first unskipped page index so proper read ahead.
firstUnskippedPage := len(cr.GetPageIndex())
for i, idx := range cr.GetPageIndex() {
c := pageCategory(idx)
if c == xrefCategoryNone {
continue
}
if !stats.skipPage(idx) {
firstUnskippedPage = i
break
}
c.AddCount(reply, idx, pageSet)
}
// If enabled, start reading pages concurrently starting from the first
// unskipped page.
if *pageReadAhead > 0 {
pageReadGroup.Go(func() error {
ctx := pageReadGroupCtx
for _, idx := range cr.GetPageIndex()[firstUnskippedPage:] {