forked from sourcegraph/sourcegraph-public-snapshot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.go
More file actions
1318 lines (1138 loc) · 48.2 KB
/
service.go
File metadata and controls
1318 lines (1138 loc) · 48.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package codenav
import (
"context"
"strings"
traceLog "github.com/opentracing/opentracing-go/log"
"github.com/sourcegraph/sourcegraph/internal/actor"
"github.com/sourcegraph/sourcegraph/internal/api"
"github.com/sourcegraph/sourcegraph/internal/authz"
"github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/internal/lsifstore"
"github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/internal/store"
"github.com/sourcegraph/sourcegraph/internal/codeintel/codenav/shared"
codeintelgitserver "github.com/sourcegraph/sourcegraph/internal/codeintel/shared/gitserver"
"github.com/sourcegraph/sourcegraph/internal/codeintel/shared/types"
"github.com/sourcegraph/sourcegraph/internal/database"
"github.com/sourcegraph/sourcegraph/internal/observation"
"github.com/sourcegraph/sourcegraph/lib/codeintel/precise"
"github.com/sourcegraph/sourcegraph/lib/errors"
)
type Service struct {
store store.Store
lsifstore lsifstore.LsifStore
gitserver GitserverClient
uploadSvc UploadService
operations *operations
}
func newService(
store store.Store,
lsifstore lsifstore.LsifStore,
uploadSvc UploadService,
gitserver GitserverClient,
observationContext *observation.Context,
) *Service {
return &Service{
store: store,
lsifstore: lsifstore,
gitserver: gitserver,
uploadSvc: uploadSvc,
operations: newOperations(observationContext),
}
}
// GetHover returns the set of locations defining the symbol at the given position.
func (s *Service) GetHover(ctx context.Context, args shared.RequestArgs, requestState RequestState) (_ string, _ types.Range, _ bool, err error) {
ctx, trace, endObservation := observeResolver(ctx, &err, s.operations.getHover, serviceObserverThreshold, observation.Args{
LogFields: []traceLog.Field{
traceLog.Int("repositoryID", args.RepositoryID),
traceLog.String("commit", args.Commit),
traceLog.String("path", args.Path),
traceLog.Int("numUploads", len(requestState.GetCacheUploads())),
traceLog.String("uploads", uploadIDsToString(requestState.GetCacheUploads())),
traceLog.Int("line", args.Line),
traceLog.Int("character", args.Character),
},
})
defer endObservation()
adjustedUploads, err := s.getVisibleUploads(ctx, args.Line, args.Character, requestState)
if err != nil {
return "", types.Range{}, false, err
}
// Keep track of each adjusted range we know about enclosing the requested position.
//
// If we don't have hover text within the index where the range is defined, we'll
// have to look in the definition index and search for the text there. We don't
// want to return the range associated with the definition, as the range is used
// as a hint to highlight a range in the current document.
adjustedRanges := make([]types.Range, 0, len(adjustedUploads))
cachedUploads := requestState.GetCacheUploads()
for i := range adjustedUploads {
adjustedUpload := adjustedUploads[i]
trace.Log(traceLog.Int("uploadID", adjustedUpload.Upload.ID))
// Fetch hover text from the index
text, rn, exists, err := s.lsifstore.GetHover(
ctx,
adjustedUpload.Upload.ID,
adjustedUpload.TargetPathWithoutRoot,
adjustedUpload.TargetPosition.Line,
adjustedUpload.TargetPosition.Character,
)
if err != nil {
return "", types.Range{}, false, errors.Wrap(err, "lsifStore.Hover")
}
if !exists {
continue
}
// Adjust the highlighted range back to the appropriate range in the target commit
_, adjustedRange, _, err := s.getSourceRange(ctx, args, requestState, cachedUploads[i].RepositoryID, cachedUploads[i].Commit, args.Path, rn)
if err != nil {
return "", types.Range{}, false, err
}
if text != "" {
// Text attached to source range
return text, adjustedRange, true, nil
}
adjustedRanges = append(adjustedRanges, adjustedRange)
}
// The Slow path:
//
// The indexes we searched in doesn't attach hover text to externally defined symbols.
// Each indexer is free to make that choice as it's a compromise between ease of development,
// efficiency of indexing, index output sizes, etc. We can deal with this situation by
// looking for hover text attached to the precise definition (if one exists).
// The range we will end up returning is interpreted within the context of the current text
// document, so any range inside of a remote index would be of no use. We'll return the first
// (inner-most) range that we adjusted from the source index traversals above.
var adjustedRange types.Range
if len(adjustedRanges) > 0 {
adjustedRange = adjustedRanges[0]
}
// Gather all import monikers attached to the ranges enclosing the requested position
orderedMonikers, err := s.getOrderedMonikers(ctx, adjustedUploads, "import")
if err != nil {
return "", types.Range{}, false, err
}
trace.Log(
traceLog.Int("numMonikers", len(orderedMonikers)),
traceLog.String("monikers", monikersToString(orderedMonikers)),
)
// Determine the set of uploads over which we need to perform a moniker search. This will
// include all all indexes which define one of the ordered monikers. This should not include
// any of the indexes we have already performed an LSIF graph traversal in above.
uploads, err := s.getUploadsWithDefinitionsForMonikers(ctx, orderedMonikers, requestState)
if err != nil {
return "", types.Range{}, false, err
}
trace.Log(
traceLog.Int("numDefinitionUploads", len(uploads)),
traceLog.String("definitionUploads", uploadIDsToString(uploads)),
)
// Perform the moniker search. This returns a set of locations defining one of the monikers
// attached to one of the source ranges.
locations, _, err := s.getBulkMonikerLocations(ctx, uploads, orderedMonikers, "definitions", DefinitionsLimit, 0)
if err != nil {
return "", types.Range{}, false, err
}
trace.Log(traceLog.Int("numLocations", len(locations)))
for i := range locations {
// Fetch hover text attached to a definition in the defining index
text, _, exists, err := s.lsifstore.GetHover(
ctx,
locations[i].DumpID,
locations[i].Path,
locations[i].Range.Start.Line,
locations[i].Range.Start.Character,
)
if err != nil {
return "", types.Range{}, false, errors.Wrap(err, "lsifStore.Hover")
}
if exists && text != "" {
// Text attached to definition
return text, adjustedRange, true, nil
}
}
// No text available
return "", types.Range{}, false, nil
}
// GetReferences returns the list of source locations that reference the symbol at the given position.
func (s *Service) GetReferences(ctx context.Context, args shared.RequestArgs, requestState RequestState, cursor shared.ReferencesCursor) (_ []types.UploadLocation, _ shared.ReferencesCursor, err error) {
ctx, trace, endObservation := observeResolver(ctx, &err, s.operations.getReferences, serviceObserverThreshold, observation.Args{
LogFields: []traceLog.Field{
traceLog.Int("repositoryID", args.RepositoryID),
traceLog.String("commit", args.Commit),
traceLog.String("path", args.Path),
traceLog.Int("numUploads", len(requestState.GetCacheUploads())),
traceLog.String("uploads", uploadIDsToString(requestState.GetCacheUploads())),
traceLog.Int("line", args.Line),
traceLog.Int("character", args.Character),
},
})
defer endObservation()
// Adjust the path and position for each visible upload based on its git difference to
// the target commit. This data may already be stashed in the cursor decoded above, in
// which case we don't need to hit the database.
// References at the given file:line:character could come from multiple uploads, so we
// need to look in all uploads and merge the results.
adjustedUploads, cursorsToVisibleUploads, err := s.getVisibleUploadsFromCursor(ctx, args.Line, args.Character, &cursor.CursorsToVisibleUploads, requestState)
if err != nil {
return nil, cursor, err
}
// Update the cursors with the updated visible uploads.
cursor.CursorsToVisibleUploads = cursorsToVisibleUploads
// Gather all monikers attached to the ranges enclosing the requested position. This data
// may already be stashed in the cursor decoded above, in which case we don't need to hit
// the database.
if cursor.OrderedMonikers == nil {
if cursor.OrderedMonikers, err = s.getOrderedMonikers(ctx, adjustedUploads, "import", "export"); err != nil {
return nil, cursor, err
}
}
trace.Log(
traceLog.Int("numMonikers", len(cursor.OrderedMonikers)),
traceLog.String("monikers", monikersToString(cursor.OrderedMonikers)),
)
// Phase 1: Gather all "local" locations via LSIF graph traversal. We'll continue to request additional
// locations until we fill an entire page (the size of which is denoted by the given limit) or there are
// no more local results remaining.
var locations []shared.Location
if cursor.Phase == "local" {
localLocations, hasMore, err := s.getPageLocalLocations(
ctx,
s.lsifstore.GetReferenceLocations,
adjustedUploads,
&cursor.LocalCursor,
args.Limit-len(locations),
trace,
)
if err != nil {
return nil, cursor, err
}
locations = append(locations, localLocations...)
if !hasMore {
// No more local results, move on to phase 2
cursor.Phase = "remote"
}
}
// Phase 2: Gather all "remote" locations via moniker search. We only do this if there are no more local
// results. We'll continue to request additional locations until we fill an entire page or there are no
// more local results remaining, just as we did above.
if cursor.Phase == "remote" {
if cursor.RemoteCursor.UploadBatchIDs == nil {
cursor.RemoteCursor.UploadBatchIDs = []int{}
definitionUploads, err := s.getUploadsWithDefinitionsForMonikers(ctx, cursor.OrderedMonikers, requestState)
if err != nil {
return nil, cursor, err
}
for i := range definitionUploads {
found := false
for j := range adjustedUploads {
if definitionUploads[i].ID == adjustedUploads[j].Upload.ID {
found = true
break
}
}
if !found {
cursor.RemoteCursor.UploadBatchIDs = append(cursor.RemoteCursor.UploadBatchIDs, definitionUploads[i].ID)
}
}
}
for len(locations) < args.Limit {
remoteLocations, hasMore, err := s.getPageRemoteLocations(ctx, "references", adjustedUploads, cursor.OrderedMonikers, &cursor.RemoteCursor, args.Limit-len(locations), trace, args, requestState)
if err != nil {
return nil, cursor, err
}
locations = append(locations, remoteLocations...)
if !hasMore {
cursor.Phase = "done"
break
}
}
}
trace.Log(traceLog.Int("numLocations", len(locations)))
// Adjust the locations back to the appropriate range in the target commits. This adjusts
// locations within the repository the user is browsing so that it appears all references
// are occurring at the same commit they are looking at.
referenceLocations, err := s.getUploadLocations(ctx, args, requestState, locations, true)
if err != nil {
return nil, cursor, err
}
trace.Log(traceLog.Int("numReferenceLocations", len(referenceLocations)))
return referenceLocations, cursor, nil
}
// getUploadsWithDefinitionsForMonikers returns the set of uploads that provide any of the given monikers.
// This method will not return uploads for commits which are unknown to gitserver.
func (s *Service) getUploadsWithDefinitionsForMonikers(ctx context.Context, orderedMonikers []precise.QualifiedMonikerData, requestState RequestState) ([]types.Dump, error) {
dumps, err := s.uploadSvc.GetDumpsWithDefinitionsForMonikers(ctx, orderedMonikers)
if err != nil {
return nil, errors.Wrap(err, "dbstore.DefinitionDumps")
}
uploads := copyDumps(dumps)
requestState.dataLoader.SetUploadInCacheMap(uploads)
uploadsWithResolvableCommits, err := s.removeUploadsWithUnknownCommits(ctx, uploads, requestState)
if err != nil {
return nil, err
}
return uploadsWithResolvableCommits, nil
}
// monikerLimit is the maximum number of monikers that can be returned from orderedMonikers.
const monikerLimit = 10
func (r *Service) getOrderedMonikers(ctx context.Context, visibleUploads []visibleUpload, kinds ...string) ([]precise.QualifiedMonikerData, error) {
monikerSet := newQualifiedMonikerSet()
for i := range visibleUploads {
rangeMonikers, err := r.lsifstore.GetMonikersByPosition(
ctx,
visibleUploads[i].Upload.ID,
visibleUploads[i].TargetPathWithoutRoot,
visibleUploads[i].TargetPosition.Line,
visibleUploads[i].TargetPosition.Character,
)
if err != nil {
return nil, errors.Wrap(err, "lsifStore.MonikersByPosition")
}
for _, monikers := range rangeMonikers {
for _, moniker := range monikers {
if moniker.PackageInformationID == "" || !sliceContains(kinds, moniker.Kind) {
continue
}
packageInformationData, _, err := r.lsifstore.GetPackageInformation(
ctx,
visibleUploads[i].Upload.ID,
visibleUploads[i].TargetPathWithoutRoot,
string(moniker.PackageInformationID),
)
if err != nil {
return nil, errors.Wrap(err, "lsifStore.PackageInformation")
}
monikerSet.add(precise.QualifiedMonikerData{
MonikerData: moniker,
PackageInformationData: packageInformationData,
})
if len(monikerSet.monikers) >= monikerLimit {
return monikerSet.monikers, nil
}
}
}
}
return monikerSet.monikers, nil
}
type getLocationsFn = func(ctx context.Context, bundleID int, path string, line int, character int, limit int, offset int) ([]shared.Location, int, error)
// getPageLocalLocations returns a slice of the (local) result set denoted by the given cursor fulfilled by
// traversing the LSIF graph. The given cursor will be adjusted to reflect the offsets required to resolve
// the next page of results. If there are no more pages left in the result set, a false-valued flag is returned.
func (s *Service) getPageLocalLocations(ctx context.Context, getLocations getLocationsFn, visibleUploads []visibleUpload, cursor *shared.LocalCursor, limit int, trace observation.TraceLogger) ([]shared.Location, bool, error) {
var allLocations []shared.Location
for i := range visibleUploads {
if len(allLocations) >= limit {
// We've filled the page
break
}
if i < cursor.UploadOffset {
// Skip indexes we've searched completely
continue
}
locations, totalCount, err := getLocations(
ctx,
visibleUploads[i].Upload.ID,
visibleUploads[i].TargetPathWithoutRoot,
visibleUploads[i].TargetPosition.Line,
visibleUploads[i].TargetPosition.Character,
limit-len(allLocations),
cursor.LocationOffset,
)
if err != nil {
return nil, false, errors.Wrap(err, "in an lsifstore locations call")
}
numLocations := len(locations)
trace.Log(traceLog.Int("pageLocalLocations.numLocations", numLocations))
cursor.LocationOffset += numLocations
if cursor.LocationOffset >= totalCount {
// Skip this index on next request
cursor.LocationOffset = 0
cursor.UploadOffset++
}
allLocations = append(allLocations, locations...)
}
return allLocations, cursor.UploadOffset < len(visibleUploads), nil
}
// getPageRemoteLocations returns a slice of the (remote) result set denoted by the given cursor fulfilled by
// performing a moniker search over a group of indexes. The given cursor will be adjusted to reflect the
// offsets required to resolve the next page of results. If there are no more pages left in the result set,
// a false-valued flag is returned.
func (s *Service) getPageRemoteLocations(
ctx context.Context,
lsifDataTable string,
visibleUploads []visibleUpload,
orderedMonikers []precise.QualifiedMonikerData,
cursor *shared.RemoteCursor,
limit int,
trace observation.TraceLogger,
args shared.RequestArgs,
requestState RequestState,
) ([]shared.Location, bool, error) {
for len(cursor.UploadBatchIDs) == 0 {
if cursor.UploadOffset < 0 {
// No more batches
return nil, false, nil
}
ignoreIDs := []int{}
for _, adjustedUpload := range visibleUploads {
ignoreIDs = append(ignoreIDs, adjustedUpload.Upload.ID)
}
// Find the next batch of indexes to perform a moniker search over
referenceUploadIDs, recordsScanned, totalRecords, err := s.uploadSvc.GetUploadIDsWithReferences(
ctx,
orderedMonikers,
ignoreIDs,
args.RepositoryID,
args.Commit,
requestState.maximumIndexesPerMonikerSearch,
cursor.UploadOffset,
)
if err != nil {
return nil, false, err
}
cursor.UploadBatchIDs = referenceUploadIDs
cursor.UploadOffset += recordsScanned
if cursor.UploadOffset >= totalRecords {
// Signal no batches remaining
cursor.UploadOffset = -1
}
}
// Fetch the upload records we don't currently have hydrated and insert them into the map
monikerSearchUploads, err := s.getUploadsByIDs(ctx, cursor.UploadBatchIDs, requestState)
if err != nil {
return nil, false, err
}
// Perform the moniker search
locations, totalCount, err := s.getBulkMonikerLocations(ctx, monikerSearchUploads, orderedMonikers, lsifDataTable, limit, cursor.LocationOffset)
if err != nil {
return nil, false, err
}
numLocations := len(locations)
trace.Log(traceLog.Int("pageLocalLocations.numLocations", numLocations))
cursor.LocationOffset += numLocations
if cursor.LocationOffset >= totalCount {
// Require a new batch on next page
cursor.LocationOffset = 0
cursor.UploadBatchIDs = []int{}
}
// Perform an in-place filter to remove specific duplicate locations. Ranges that enclose the
// target position will be returned by both an LSIF graph traversal as well as a moniker search.
// We remove the latter instances.
filtered := locations[:0]
for _, location := range locations {
if !isSourceLocation(visibleUploads, location) {
filtered = append(filtered, location)
}
}
// We have another page if we still have results in the current batch of reference indexes, or if
// we can query a next batch of reference indexes. We may return true here when we are actually
// out of references. This behavior may change in the future.
hasAnotherPage := len(cursor.UploadBatchIDs) > 0 || cursor.UploadOffset >= 0
return filtered, hasAnotherPage, nil
}
// getUploadLocations translates a set of locations into an equivalent set of locations in the requested
// commit. If includeFallbackLocations is true, then any range in the indexed commit that cannot be translated
// will use the indexed location. Otherwise, such location are dropped.
func (s *Service) getUploadLocations(ctx context.Context, args shared.RequestArgs, requestState RequestState, locations []shared.Location, includeFallbackLocations bool) ([]types.UploadLocation, error) {
uploadLocations := make([]types.UploadLocation, 0, len(locations))
checkerEnabled := authz.SubRepoEnabled(requestState.authChecker)
var a *actor.Actor
if checkerEnabled {
a = actor.FromContext(ctx)
}
for _, location := range locations {
upload, ok := requestState.dataLoader.GetUploadFromCacheMap(location.DumpID)
if !ok {
continue
}
adjustedLocation, ok, err := s.getUploadLocation(ctx, args, requestState, upload, location)
if err != nil {
return nil, err
}
if !includeFallbackLocations && !ok {
continue
}
if !checkerEnabled {
uploadLocations = append(uploadLocations, adjustedLocation)
} else {
repo := api.RepoName(adjustedLocation.Dump.RepositoryName)
if include, err := authz.FilterActorPath(ctx, requestState.authChecker, a, repo, adjustedLocation.Path); err != nil {
return nil, err
} else if include {
uploadLocations = append(uploadLocations, adjustedLocation)
}
}
}
return uploadLocations, nil
}
// getUploadLocation translates a location (relative to the indexed commit) into an equivalent location in
// the requested commit. If the translation fails, then the original commit and range are used as the
// commit and range of the adjusted location and a false flag is returned.
func (s *Service) getUploadLocation(ctx context.Context, args shared.RequestArgs, requestState RequestState, dump types.Dump, location shared.Location) (types.UploadLocation, bool, error) {
adjustedCommit, adjustedRange, ok, err := s.getSourceRange(ctx, args, requestState, dump.RepositoryID, dump.Commit, dump.Root+location.Path, location.Range)
if err != nil {
return types.UploadLocation{}, ok, err
}
return types.UploadLocation{
Dump: dump,
Path: dump.Root + location.Path,
TargetCommit: adjustedCommit,
TargetRange: adjustedRange,
}, ok, nil
}
// getSourceRange translates a range (relative to the indexed commit) into an equivalent range in the requested
// commit. If the translation fails, then the original commit and range are returned along with a false-valued
// flag.
func (s *Service) getSourceRange(ctx context.Context, args shared.RequestArgs, requestState RequestState, repositoryID int, commit, path string, rng types.Range) (string, types.Range, bool, error) {
if repositoryID != args.RepositoryID {
// No diffs between distinct repositories
return commit, rng, true, nil
}
if _, sourceRange, ok, err := requestState.GitTreeTranslator.GetTargetCommitRangeFromSourceRange(ctx, commit, path, rng, true); err != nil {
return "", types.Range{}, false, errors.Wrap(err, "gitTreeTranslator.GetTargetCommitRangeFromSourceRange")
} else if ok {
return args.Commit, sourceRange, true, nil
}
return commit, rng, false, nil
}
// getUploadsByIDs returns a slice of uploads with the given identifiers. This method will not return a
// new upload record for a commit which is unknown to gitserver. The given upload map is used as a
// caching mechanism - uploads present in the map are not fetched again from the database.
func (s *Service) getUploadsByIDs(ctx context.Context, ids []int, requestState RequestState) ([]types.Dump, error) {
missingIDs := make([]int, 0, len(ids))
existingUploads := make([]types.Dump, 0, len(ids))
for _, id := range ids {
if upload, ok := requestState.dataLoader.GetUploadFromCacheMap(id); ok {
existingUploads = append(existingUploads, upload)
} else {
missingIDs = append(missingIDs, id)
}
}
uploads, err := s.uploadSvc.GetDumpsByIDs(ctx, missingIDs)
if err != nil {
return nil, errors.Wrap(err, "service.GetDumpsByIDs")
}
uploadsWithResolvableCommits, err := s.removeUploadsWithUnknownCommits(ctx, uploads, requestState)
if err != nil {
return nil, nil
}
requestState.dataLoader.SetUploadInCacheMap(uploadsWithResolvableCommits)
allUploads := append(existingUploads, uploadsWithResolvableCommits...)
return allUploads, nil
}
// removeUploadsWithUnknownCommits removes uploads for commits which are unknown to gitserver from the given
// slice. The slice is filtered in-place and returned (to update the slice length).
func (s *Service) removeUploadsWithUnknownCommits(ctx context.Context, uploads []types.Dump, requestState RequestState) ([]types.Dump, error) {
rcs := make([]codeintelgitserver.RepositoryCommit, 0, len(uploads))
for _, upload := range uploads {
rcs = append(rcs, codeintelgitserver.RepositoryCommit{
RepositoryID: upload.RepositoryID,
Commit: upload.Commit,
})
}
exists, err := requestState.commitCache.AreCommitsResolvable(ctx, rcs)
if err != nil {
return nil, err
}
filtered := uploads[:0]
for i, upload := range uploads {
if exists[i] {
filtered = append(filtered, upload)
}
}
return filtered, nil
}
// getBulkMonikerLocations returns the set of locations (within the given uploads) with an attached moniker
// whose scheme+identifier matches any of the given monikers.
func (s *Service) getBulkMonikerLocations(ctx context.Context, uploads []types.Dump, orderedMonikers []precise.QualifiedMonikerData, tableName string, limit, offset int) ([]shared.Location, int, error) {
ids := make([]int, 0, len(uploads))
for i := range uploads {
ids = append(ids, uploads[i].ID)
}
args := make([]precise.MonikerData, 0, len(orderedMonikers))
for _, moniker := range orderedMonikers {
args = append(args, moniker.MonikerData)
}
locations, totalCount, err := s.lsifstore.GetBulkMonikerLocations(ctx, tableName, ids, args, limit, offset)
if err != nil {
return nil, 0, errors.Wrap(err, "lsifStore.GetBulkMonikerLocations")
}
return locations, totalCount, nil
}
// DefinitionsLimit is maximum the number of locations returned from Definitions.
const DefinitionsLimit = 100
func (s *Service) GetImplementations(ctx context.Context, args shared.RequestArgs, requestState RequestState, cursor shared.ImplementationsCursor) (_ []types.UploadLocation, _ shared.ImplementationsCursor, err error) {
ctx, trace, endObservation := observeResolver(ctx, &err, s.operations.getImplementations, serviceObserverThreshold, observation.Args{
LogFields: []traceLog.Field{
traceLog.Int("repositoryID", args.RepositoryID),
traceLog.String("commit", args.Commit),
traceLog.String("path", args.Path),
traceLog.Int("numUploads", len(requestState.GetCacheUploads())),
traceLog.String("uploads", uploadIDsToString(requestState.GetCacheUploads())),
traceLog.Int("line", args.Line),
traceLog.Int("character", args.Character),
},
})
defer endObservation()
// Adjust the path and position for each visible upload based on its git difference to
// the target commit. This data may already be stashed in the cursor decoded above, in
// which case we don't need to hit the database.
visibleUploads, cursorsToVisibleUploads, err := s.getVisibleUploadsFromCursor(ctx, args.Line, args.Character, &cursor.CursorsToVisibleUploads, requestState)
if err != nil {
return nil, cursor, err
}
// Update the cursors with the updated visible uploads.
cursor.CursorsToVisibleUploads = cursorsToVisibleUploads
// Gather all monikers attached to the ranges enclosing the requested position. This data
// may already be stashed in the cursor decoded above, in which case we don't need to hit
// the database.
if cursor.OrderedImplementationMonikers == nil {
if cursor.OrderedImplementationMonikers, err = s.getOrderedMonikers(ctx, visibleUploads, precise.Implementation); err != nil {
return nil, cursor, err
}
}
trace.Log(
traceLog.Int("numImplementationMonikers", len(cursor.OrderedImplementationMonikers)),
traceLog.String("implementationMonikers", monikersToString(cursor.OrderedImplementationMonikers)),
)
if cursor.OrderedExportMonikers == nil {
if cursor.OrderedExportMonikers, err = s.getOrderedMonikers(ctx, visibleUploads, "export"); err != nil {
return nil, cursor, err
}
}
trace.Log(
traceLog.Int("numExportMonikers", len(cursor.OrderedExportMonikers)),
traceLog.String("exportMonikers", monikersToString(cursor.OrderedExportMonikers)),
)
// Phase 1: Gather all "local" locations via LSIF graph traversal. We'll continue to request additional
// locations until we fill an entire page (the size of which is denoted by the given limit) or there are
// no more local results remaining.
var locations []shared.Location
if cursor.Phase == "local" {
for len(locations) < args.Limit {
localLocations, hasMore, err := s.getPageLocalLocations(ctx, s.lsifstore.GetImplementationLocations, visibleUploads, &cursor.LocalCursor, args.Limit-len(locations), trace)
if err != nil {
return nil, cursor, err
}
locations = append(locations, localLocations...)
if !hasMore {
cursor.Phase = "dependencies"
break
}
}
}
// Phase 2: Gather all "remote" locations in dependencies via moniker search. We only do this if
// there are no more local results. We'll continue to request additional locations until we fill an
// entire page or there are no more local results remaining, just as we did above.
if cursor.Phase == "dependencies" {
uploads, err := s.getUploadsWithDefinitionsForMonikers(ctx, cursor.OrderedImplementationMonikers, requestState)
if err != nil {
return nil, cursor, err
}
trace.Log(
traceLog.Int("numGetUploadsWithDefinitionsForMonikers", len(uploads)),
traceLog.String("getUploadsWithDefinitionsForMonikers", uploadIDsToString(uploads)),
)
definitionLocations, _, err := s.getBulkMonikerLocations(ctx, uploads, cursor.OrderedImplementationMonikers, "definitions", DefinitionsLimit, 0)
if err != nil {
return nil, cursor, err
}
locations = append(locations, definitionLocations...)
cursor.Phase = "dependents"
}
// Phase 3: Gather all "remote" locations in dependents via moniker search.
if cursor.Phase == "dependents" {
for len(locations) < args.Limit {
remoteLocations, hasMore, err := s.getPageRemoteLocations(ctx, "implementations", visibleUploads, cursor.OrderedExportMonikers, &cursor.RemoteCursor, args.Limit-len(locations), trace, args, requestState)
if err != nil {
return nil, cursor, err
}
locations = append(locations, remoteLocations...)
if !hasMore {
cursor.Phase = "done"
break
}
}
}
trace.Log(traceLog.Int("numLocations", len(locations)))
// Adjust the locations back to the appropriate range in the target commits. This adjusts
// locations within the repository the user is browsing so that it appears all implementations
// are occurring at the same commit they are looking at.
implementationLocations, err := s.getUploadLocations(ctx, args, requestState, locations, true)
if err != nil {
return nil, cursor, err
}
trace.Log(traceLog.Int("numImplementationsLocations", len(implementationLocations)))
return implementationLocations, cursor, nil
}
// GetDefinitions returns the set of locations defining the symbol at the given position.
func (s *Service) GetDefinitions(ctx context.Context, args shared.RequestArgs, requestState RequestState) (_ []types.UploadLocation, err error) {
ctx, trace, endObservation := observeResolver(ctx, &err, s.operations.getDefinitions, serviceObserverThreshold, observation.Args{
LogFields: []traceLog.Field{
traceLog.Int("repositoryID", args.RepositoryID),
traceLog.String("commit", args.Commit),
traceLog.String("path", args.Path),
traceLog.Int("numUploads", len(requestState.GetCacheUploads())),
traceLog.String("uploads", uploadIDsToString(requestState.GetCacheUploads())),
traceLog.Int("line", args.Line),
traceLog.Int("character", args.Character),
},
})
defer endObservation()
// Adjust the path and position for each visible upload based on its git difference to
// the target commit.
visibleUploads, err := s.getVisibleUploads(ctx, args.Line, args.Character, requestState)
if err != nil {
return nil, err
}
// Gather the "local" reference locations that are reachable via a referenceResult vertex.
// If the definition exists within the index, it should be reachable via an LSIF graph
// traversal and should not require an additional moniker search in the same index.
for i := range visibleUploads {
trace.Log(traceLog.Int("uploadID", visibleUploads[i].Upload.ID))
locations, _, err := s.lsifstore.GetDefinitionLocations(
ctx,
visibleUploads[i].Upload.ID,
visibleUploads[i].TargetPathWithoutRoot,
visibleUploads[i].TargetPosition.Line,
visibleUploads[i].TargetPosition.Character,
DefinitionsLimit,
0,
)
if err != nil {
return nil, errors.Wrap(err, "lsifStore.Definitions")
}
if len(locations) > 0 {
// If we have a local definition, we won't find a better one and can exit early
return s.getUploadLocations(ctx, args, requestState, locations, true)
}
}
// Gather all import monikers attached to the ranges enclosing the requested position
orderedMonikers, err := s.getOrderedMonikers(ctx, visibleUploads, "import")
if err != nil {
return nil, err
}
trace.Log(
traceLog.Int("numMonikers", len(orderedMonikers)),
traceLog.String("monikers", monikersToString(orderedMonikers)),
)
// Determine the set of uploads over which we need to perform a moniker search. This will
// include all all indexes which define one of the ordered monikers. This should not include
// any of the indexes we have already performed an LSIF graph traversal in above.
uploads, err := s.getUploadsWithDefinitionsForMonikers(ctx, orderedMonikers, requestState)
if err != nil {
return nil, err
}
trace.Log(
traceLog.Int("numXrepoDefinitionUploads", len(uploads)),
traceLog.String("xrepoDefinitionUploads", uploadIDsToString(uploads)),
)
// Perform the moniker search
locations, _, err := s.getBulkMonikerLocations(ctx, uploads, orderedMonikers, "definitions", DefinitionsLimit, 0)
if err != nil {
return nil, err
}
trace.Log(traceLog.Int("numXrepoLocations", len(locations)))
// Adjust the locations back to the appropriate range in the target commits. This adjusts
// locations within the repository the user is browsing so that it appears all definitions
// are occurring at the same commit they are looking at.
adjustedLocations, err := s.getUploadLocations(ctx, args, requestState, locations, true)
if err != nil {
return nil, err
}
trace.Log(traceLog.Int("numAdjustedXrepoLocations", len(adjustedLocations)))
return adjustedLocations, nil
}
func (s *Service) GetDiagnostics(ctx context.Context, args shared.RequestArgs, requestState RequestState) (diagnosticsAtUploads []shared.DiagnosticAtUpload, _ int, err error) {
ctx, trace, endObservation := observeResolver(ctx, &err, s.operations.getDiagnostics, serviceObserverThreshold, observation.Args{
LogFields: []traceLog.Field{
traceLog.Int("repositoryID", args.RepositoryID),
traceLog.String("commit", args.Commit),
traceLog.String("path", args.Path),
traceLog.Int("numUploads", len(requestState.GetCacheUploads())),
traceLog.String("uploads", uploadIDsToString(requestState.GetCacheUploads())),
traceLog.Int("limit", args.Limit),
},
})
defer endObservation()
visibleUploads, err := s.getUploadPaths(ctx, args.Path, requestState)
if err != nil {
return nil, 0, err
}
totalCount := 0
checkerEnabled := authz.SubRepoEnabled(requestState.authChecker)
var a *actor.Actor
if checkerEnabled {
a = actor.FromContext(ctx)
}
for i := range visibleUploads {
trace.Log(traceLog.Int("uploadID", visibleUploads[i].Upload.ID))
diagnostics, count, err := s.lsifstore.GetDiagnostics(
ctx,
visibleUploads[i].Upload.ID,
visibleUploads[i].TargetPathWithoutRoot,
args.Limit-len(diagnosticsAtUploads),
0,
)
if err != nil {
return nil, 0, errors.Wrap(err, "lsifStore.Diagnostics")
}
for _, diagnostic := range diagnostics {
adjustedDiagnostic, err := s.getRequestedCommitDiagnostic(ctx, args, requestState, visibleUploads[i], diagnostic)
if err != nil {
return nil, 0, err
}
if !checkerEnabled {
diagnosticsAtUploads = append(diagnosticsAtUploads, adjustedDiagnostic)
continue
}
// sub-repo checker is enabled, proceeding with check
if include, err := authz.FilterActorPath(ctx, requestState.authChecker, a, api.RepoName(adjustedDiagnostic.Dump.RepositoryName), adjustedDiagnostic.Path); err != nil {
return nil, 0, err
} else if include {
diagnosticsAtUploads = append(diagnosticsAtUploads, adjustedDiagnostic)
}
}
totalCount += count
}
if len(diagnosticsAtUploads) > args.Limit {
diagnosticsAtUploads = diagnosticsAtUploads[:args.Limit]
}
trace.Log(
traceLog.Int("totalCount", totalCount),
traceLog.Int("numDiagnostics", len(diagnosticsAtUploads)),
)
return diagnosticsAtUploads, totalCount, nil
}
// getRequestedCommitDiagnostic translates a diagnostic (relative to the indexed commit) into an equivalent diagnostic
// in the requested commit.
func (s *Service) getRequestedCommitDiagnostic(ctx context.Context, args shared.RequestArgs, requestState RequestState, adjustedUpload visibleUpload, diagnostic shared.Diagnostic) (shared.DiagnosticAtUpload, error) {
rn := types.Range{
Start: types.Position{
Line: diagnostic.StartLine,
Character: diagnostic.StartCharacter,
},
End: types.Position{
Line: diagnostic.EndLine,
Character: diagnostic.EndCharacter,
},
}
// Adjust path in diagnostic before reading it. This value is used in the adjustRange
// call below, and is also reflected in the embedded diagnostic value in the return.
diagnostic.Path = adjustedUpload.Upload.Root + diagnostic.Path
adjustedCommit, adjustedRange, _, err := s.getSourceRange(
ctx,
args,
requestState,
adjustedUpload.Upload.RepositoryID,
adjustedUpload.Upload.Commit,
diagnostic.Path,
rn,
)
if err != nil {
return shared.DiagnosticAtUpload{}, err
}
return shared.DiagnosticAtUpload{
Diagnostic: diagnostic,
Dump: adjustedUpload.Upload,
AdjustedCommit: adjustedCommit,
AdjustedRange: adjustedRange,
}, nil
}
// getUploadPaths adjusts the current target path for each upload visible from the current target
// commit. If an upload cannot be adjusted, it will be omitted from the returned slice.
func (s *Service) getUploadPaths(ctx context.Context, path string, requestState RequestState) ([]visibleUpload, error) {
cacheUploads := requestState.GetCacheUploads()
visibleUploads := make([]visibleUpload, 0, len(cacheUploads))
for _, cu := range cacheUploads {
targetPath, ok, err := requestState.GitTreeTranslator.GetTargetCommitPathFromSourcePath(ctx, cu.Commit, path, false)
if err != nil {
return nil, errors.Wrap(err, "r.GitTreeTranslator.GetTargetCommitPathFromSourcePath")
}
if !ok {
continue
}
visibleUploads = append(visibleUploads, visibleUpload{
Upload: cu,
TargetPath: targetPath,
TargetPathWithoutRoot: strings.TrimPrefix(targetPath, cu.Root),
})
}
return visibleUploads, nil
}
func (s *Service) GetRanges(ctx context.Context, args shared.RequestArgs, requestState RequestState, startLine, endLine int) (adjustedRanges []shared.AdjustedCodeIntelligenceRange, err error) {
ctx, trace, endObservation := observeResolver(ctx, &err, s.operations.getRanges, serviceObserverThreshold, observation.Args{
LogFields: []traceLog.Field{
traceLog.Int("repositoryID", args.RepositoryID),
traceLog.String("commit", args.Commit),