fork of https://github.com/sourcegraph/zoekt
1// Copyright 2016 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package search
16
17import (
18 "bytes"
19 "context"
20 "flag"
21 "fmt"
22 "hash/fnv"
23 "io"
24 "log"
25 "math"
26 "os"
27 "reflect"
28 "runtime"
29 "sort"
30 "strconv"
31 "testing"
32 "testing/quick"
33 "time"
34
35 "github.com/RoaringBitmap/roaring"
36 "github.com/google/go-cmp/cmp"
37 "github.com/google/go-cmp/cmp/cmpopts"
38 "github.com/grafana/regexp"
39 sglog "github.com/sourcegraph/log"
40
41 "github.com/sourcegraph/zoekt/index"
42
43 "github.com/sourcegraph/zoekt"
44 "github.com/sourcegraph/zoekt/query"
45)
46
47func TestMain(m *testing.M) {
48 flag.Parse()
49 if !testing.Verbose() {
50 log.SetOutput(io.Discard)
51 }
52 os.Exit(m.Run())
53}
54
55type crashSearcher struct{}
56
57func (s *crashSearcher) Search(ctx context.Context, q query.Q, opts *zoekt.SearchOptions) (*zoekt.SearchResult, error) {
58 panic("search")
59}
60
61func (s *crashSearcher) List(ctx context.Context, q query.Q, opts *zoekt.ListOptions) (*zoekt.RepoList, error) {
62 panic("list")
63}
64
65func (s *crashSearcher) Stats() (*zoekt.RepoStats, error) {
66 return &zoekt.RepoStats{}, nil
67}
68
69func (s *crashSearcher) Close() {}
70
71func (s *crashSearcher) String() string { return "crashSearcher" }
72
73func TestCrashResilience(t *testing.T) {
74 out := &bytes.Buffer{}
75 oldOut := log.Writer()
76 log.SetOutput(out)
77 defer log.SetOutput(oldOut)
78
79 oldShardRecoveryLogger := shardRecoveryLogger
80 shardRecoveryLogger = sglog.NoOp
81 defer func() { shardRecoveryLogger = oldShardRecoveryLogger }()
82
83 ss := newShardedSearcher(2)
84 ss.ranked.Store([]*rankedShard{{Searcher: &crashSearcher{}}})
85
86 var wantCrashes int
87 test := func(t *testing.T) {
88 q := &query.Substring{Pattern: "hoi"}
89 opts := &zoekt.SearchOptions{}
90 if res, err := ss.Search(context.Background(), q, opts); err != nil {
91 t.Fatalf("Search: %v", err)
92 } else if res.Stats.Crashes != wantCrashes {
93 t.Errorf("got stats %#v, want crashes = %d", res.Stats, wantCrashes)
94 }
95
96 if res, err := ss.List(context.Background(), q, nil); err != nil {
97 t.Fatalf("List: %v", err)
98 } else if res.Crashes != wantCrashes {
99 t.Errorf("got result %#v, want crashes = %d", res, wantCrashes)
100 }
101 }
102
103 // Before we are marked as ready we have one extra crash
104 wantCrashes = 2
105 t.Run("loading", test)
106
107 // After marking as ready we should only have the crashSearcher
108 // contributing.
109 ss.markReady()
110 wantCrashes = 1
111 t.Run("ready", test)
112}
113
114type rankSearcher struct {
115 rank uint16
116 repo *zoekt.Repository
117}
118
119func (s *rankSearcher) Close() {
120}
121
122func (s *rankSearcher) String() string {
123 return ""
124}
125
126func (s *rankSearcher) Search(ctx context.Context, q query.Q, opts *zoekt.SearchOptions) (*zoekt.SearchResult, error) {
127 select {
128 case <-ctx.Done():
129 return &zoekt.SearchResult{}, nil
130 default:
131 }
132
133 // Ugly, but without sleep it's too fast, and we can't
134 // simulate the cutoff.
135 time.Sleep(time.Millisecond)
136 return &zoekt.SearchResult{
137 Files: []zoekt.FileMatch{
138 {
139 FileName: fmt.Sprintf("f%d", s.rank),
140 Score: float64(s.rank),
141 },
142 },
143 Stats: zoekt.Stats{
144 MatchCount: 1,
145 },
146 }, nil
147}
148
149func (s *rankSearcher) List(ctx context.Context, q query.Q, opts *zoekt.ListOptions) (*zoekt.RepoList, error) {
150 r := zoekt.Repository{}
151 if s.repo != nil {
152 r = *s.repo
153 }
154 r.Rank = s.rank
155 return &zoekt.RepoList{
156 Repos: []*zoekt.RepoListEntry{
157 {Repository: r},
158 },
159 }, nil
160}
161
162func (s *rankSearcher) Repository() *zoekt.Repository { return s.repo }
163
164func TestOrderByShard(t *testing.T) {
165 ss := newShardedSearcher(1)
166
167 n := 10 * runtime.GOMAXPROCS(0)
168 for i := range n {
169 ss.replace(map[string]zoekt.Searcher{
170 fmt.Sprintf("shard%d", i): &rankSearcher{rank: uint16(i)},
171 })
172 }
173
174 if res, err := ss.Search(context.Background(), &query.Substring{Pattern: "bla"}, &zoekt.SearchOptions{}); err != nil {
175 t.Errorf("Search: %v", err)
176 } else if len(res.Files) != n {
177 t.Fatalf("empty options: got %d results, want %d", len(res.Files), n)
178 }
179
180 opts := zoekt.SearchOptions{
181 TotalMaxMatchCount: 3,
182 }
183 res, err := ss.Search(context.Background(), &query.Substring{Pattern: "bla"}, &opts)
184 if err != nil {
185 t.Errorf("Search: %v", err)
186 }
187
188 if len(res.Files) < opts.TotalMaxMatchCount {
189 t.Errorf("got %d results, want %d", len(res.Files), opts.TotalMaxMatchCount)
190 }
191 if len(res.Files) == n {
192 t.Errorf("got %d results, want < %d", len(res.Files), n)
193 }
194 for i, f := range res.Files {
195 rev := n - 1 - i
196 want := fmt.Sprintf("f%d", rev)
197 got := f.FileName
198
199 if got != want {
200 t.Logf("%d: got %q, want %q", i, got, want)
201 }
202 }
203}
204
205func TestShardedSearcher_Ranking(t *testing.T) {
206 ss := newShardedSearcher(1)
207
208 var nextShardNum int
209 addShard := func(repo string, priority float64, docs ...index.Document) {
210 r := &zoekt.Repository{ID: hash(repo), Name: repo}
211 r.RawConfig = map[string]string{
212 "public": "1",
213 "priority": strconv.FormatFloat(priority, 'f', 2, 64),
214 }
215 b := testShardBuilder(t, r, docs...)
216 shard := searcherForTest(t, b)
217 ss.replace(map[string]zoekt.Searcher{
218 fmt.Sprintf("key-%d", nextShardNum): shard,
219 })
220 nextShardNum++
221 }
222
223 addShard("weekend-project", 20, index.Document{Name: "f2", Content: []byte("foo bas")})
224 addShard("moderately-popular", 500, index.Document{Name: "f3", Content: []byte("foo bar")})
225 addShard("weekend-project-2", 20, index.Document{Name: "f2", Content: []byte("foo bas")})
226 addShard("super-star", 5000, index.Document{Name: "f1", Content: []byte("foo bar bas")})
227
228 want := []string{
229 "super-star",
230 "moderately-popular",
231 "weekend-project",
232 "weekend-project-2",
233 }
234
235 var have []string
236 for _, s := range ss.getLoaded().shards {
237 for _, r := range s.repos {
238 have = append(have, r.Name)
239 }
240 }
241
242 if !reflect.DeepEqual(want, have) {
243 t.Fatalf("\nwant: %s\nhave: %s", want, have)
244 }
245}
246
247func TestShardedSearcher_DocumentRanking(t *testing.T) {
248 ss := newShardedSearcher(1)
249
250 var nextShardNum int
251 addShard := func(repo string, rank uint16, docs ...index.Document) {
252 r := &zoekt.Repository{ID: hash(repo), Name: repo}
253 r.RawConfig = map[string]string{
254 "public": "1",
255 }
256 r.Rank = rank
257 b := testShardBuilder(t, r, docs...)
258 shard := searcherForTest(t, b)
259 ss.replace(map[string]zoekt.Searcher{
260 fmt.Sprintf("key-%d", nextShardNum): shard,
261 })
262 nextShardNum++
263 }
264
265 addShard("old-project", 1, index.Document{Name: "f1", Content: []byte("foobar")})
266 addShard("recent", 2, index.Document{Name: "f2", Content: []byte("foobaz")})
267 addShard("old-project-2", 1, index.Document{Name: "f3", Content: []byte("foo bar")})
268 addShard("new", 3, index.Document{Name: "f4", Content: []byte("foo baz")},
269 index.Document{Name: "f5", Content: []byte("fooooo")})
270
271 // Run a stream search and gather the results
272 var results []*zoekt.SearchResult
273 opts := &zoekt.SearchOptions{
274 FlushWallTime: 100 * time.Millisecond,
275 }
276
277 err := ss.StreamSearch(context.Background(), &query.Substring{Pattern: "foo"}, opts,
278 zoekt.SenderFunc(func(event *zoekt.SearchResult) {
279 results = append(results, event)
280 }))
281 if err != nil {
282 t.Fatal(err)
283 }
284
285 // There should always be two stream results, first progress-only, then the file results
286 if len(results) != 2 {
287 t.Fatalf("expected 2 streamed results, but got %d", len(results))
288 }
289
290 // The ranking should be determined by whether it's an exact word match,
291 // followed by repository priority
292 want := []string{"f4", "f3", "f5", "f2", "f1"}
293
294 files := results[1].Files
295 got := make([]string, len(files))
296 for i := range files {
297 got[i] = files[i].FileName
298 }
299
300 if !reflect.DeepEqual(got, want) {
301 t.Errorf("got %v, want %v", got, want)
302 }
303}
304
305func TestFilteringShardsByRepoSetOrBranchesReposOrRepoIDs(t *testing.T) {
306 ss := newShardedSearcher(1)
307
308 // namePrefix is so we can create a repo:foo filter and match the same set
309 // of repos.
310 namePrefix := [3]string{"foo", "bar", "baz"}
311
312 repoSetNames := []string{}
313 repoIDs := []uint32{}
314 n := 10 * runtime.GOMAXPROCS(0)
315 for i := range n {
316 shardName := fmt.Sprintf("shard%d", i)
317 repoName := fmt.Sprintf("%s-repository%.3d", namePrefix[i%3], i)
318 repoID := hash(repoName)
319
320 if i%3 == 0 {
321 repoSetNames = append(repoSetNames, repoName)
322 repoIDs = append(repoIDs, repoID)
323 }
324
325 ss.replace(map[string]zoekt.Searcher{
326 shardName: &rankSearcher{
327 repo: &zoekt.Repository{ID: repoID, Name: repoName},
328 rank: uint16(n - i),
329 },
330 })
331 }
332
333 res, err := ss.Search(context.Background(), &query.Substring{Pattern: "bla"}, &zoekt.SearchOptions{})
334 if err != nil {
335 t.Errorf("Search: %v", err)
336 }
337 if len(res.Files) != n {
338 t.Fatalf("no reposet: got %d results, want %d", len(res.Files), n)
339 }
340
341 branchesRepos := &query.BranchesRepos{List: []query.BranchRepos{
342 {Branch: "HEAD", Repos: roaring.New()},
343 }}
344
345 for _, name := range repoSetNames {
346 branchesRepos.List[0].Repos.Add(hash(name))
347 }
348
349 set := query.NewRepoSet(repoSetNames...)
350 sub := &query.Substring{Pattern: "bla"}
351
352 repoIDsQuery := query.NewRepoIDs(repoIDs...)
353 repoQuery := &query.Repo{Regexp: regexp.MustCompile("^foo-.*")}
354
355 queries := []query.Q{
356 query.NewAnd(set, sub),
357 // Test with the same reposet again
358 query.NewAnd(set, sub),
359
360 query.NewAnd(branchesRepos, sub),
361 // Test with the same repoBranches with IDs again
362 query.NewAnd(branchesRepos, sub),
363
364 query.NewAnd(repoIDsQuery, sub),
365 // Test with the same repoIDs again
366 query.NewAnd(repoIDsQuery, sub),
367
368 query.NewAnd(repoQuery, sub),
369 query.NewAnd(repoQuery, sub),
370
371 // List has queries which are just the reposet atoms. We also test twice.
372 set,
373 set,
374 branchesRepos,
375 branchesRepos,
376 repoIDsQuery,
377 repoIDsQuery,
378 repoQuery,
379 repoQuery,
380 }
381
382 for _, q := range queries {
383 res, err = ss.Search(context.Background(), q, &zoekt.SearchOptions{})
384 if err != nil {
385 t.Errorf("Search(%s): %v", q, err)
386 }
387 // Note: Assertion is based on fact that `rankSearcher` always returns a
388 // result and using repoSet will half the number of results
389 if len(res.Files) != len(repoSetNames) {
390 t.Fatalf("%s: got %d results, want %d", q, len(res.Files), len(repoSetNames))
391 }
392 }
393}
394
395func TestFilteringShardsByMeta(t *testing.T) {
396 ss := newShardedSearcher(1)
397
398 // Create repos with different metadata values
399 // We'll create 30 repos total:
400 // - 10 with nickname="project-A"
401 // - 10 with nickname="project-B"
402 // - 10 with no metadata
403 n := 30
404 projectARepos := []string{}
405 projectBRepos := []string{}
406
407 // Common document that will be in all repos
408 doc := index.Document{
409 Name: "common.go",
410 Content: []byte("needle haystack"),
411 }
412
413 for i := range n {
414 shardName := fmt.Sprintf("shard%d", i)
415 repoName := fmt.Sprintf("repository%.3d", i)
416
417 var metadata map[string]string
418 if i < 10 {
419 // First 10 repos have project-A
420 metadata = map[string]string{"nickname": "project-A", "visibility": "public"}
421 projectARepos = append(projectARepos, repoName)
422 } else if i < 20 {
423 // Next 10 repos have project-B
424 metadata = map[string]string{"nickname": "project-B", "visibility": "private"}
425 projectBRepos = append(projectBRepos, repoName)
426 }
427 // Last 10 repos have no metadata
428
429 repo := &zoekt.Repository{
430 ID: uint32(i + 1),
431 Name: repoName,
432 Metadata: metadata,
433 }
434
435 ss.replace(map[string]zoekt.Searcher{
436 shardName: searcherForTest(t, testShardBuilder(t, repo, doc)),
437 })
438 }
439
440 // Test 1: Search without Meta filter - should search all shards
441 res, err := ss.Search(context.Background(), &query.Substring{Pattern: "needle"}, &zoekt.SearchOptions{})
442 if err != nil {
443 t.Fatalf("Search without filter: %v", err)
444 }
445 if len(res.Files) != n {
446 t.Fatalf("no meta filter: got %d results, want %d", len(res.Files), n)
447 }
448
449 sub := &query.Substring{Pattern: "needle"}
450
451 // Helper function to extract unique repo names from search results
452 getRepoNames := func(files []zoekt.FileMatch) []string {
453 repoSet := make(map[string]struct{})
454 for _, f := range files {
455 repoSet[f.Repository] = struct{}{}
456 }
457 repos := make([]string, 0, len(repoSet))
458 for repo := range repoSet {
459 repos = append(repos, repo)
460 }
461 sort.Strings(repos)
462 return repos
463 }
464
465 // Test 2: Filter by nickname="project-A" - should only search 10 shards
466 metaQueryA := &query.Meta{
467 Field: "nickname",
468 Value: regexp.MustCompile("^project-A$"),
469 }
470 res, err = ss.Search(context.Background(), query.NewAnd(metaQueryA, sub), &zoekt.SearchOptions{})
471 if err != nil {
472 t.Fatalf("Search with Meta filter A: %v", err)
473 }
474 gotRepos := getRepoNames(res.Files)
475 wantRepos := append([]string{}, projectARepos...)
476 sort.Strings(wantRepos)
477 if !reflect.DeepEqual(gotRepos, wantRepos) {
478 t.Fatalf("Meta(nickname=project-A):\ngot repos: %v\nwant repos: %v", gotRepos, wantRepos)
479 }
480
481 // Test 3: Filter by nickname="project-B" - should only search 10 shards
482 metaQueryB := &query.Meta{
483 Field: "nickname",
484 Value: regexp.MustCompile("^project-B$"),
485 }
486 res, err = ss.Search(context.Background(), query.NewAnd(metaQueryB, sub), &zoekt.SearchOptions{})
487 if err != nil {
488 t.Fatalf("Search with Meta filter B: %v", err)
489 }
490 gotRepos = getRepoNames(res.Files)
491 wantRepos = append([]string{}, projectBRepos...)
492 sort.Strings(wantRepos)
493 if !reflect.DeepEqual(gotRepos, wantRepos) {
494 t.Fatalf("Meta(nickname=project-B):\ngot repos: %v\nwant repos: %v", gotRepos, wantRepos)
495 }
496
497 // Test 4: Filter by visibility="public" - should only search 10 shards (project-A repos)
498 metaQueryPublic := &query.Meta{
499 Field: "visibility",
500 Value: regexp.MustCompile("^public$"),
501 }
502 res, err = ss.Search(context.Background(), query.NewAnd(metaQueryPublic, sub), &zoekt.SearchOptions{})
503 if err != nil {
504 t.Fatalf("Search with Meta filter public: %v", err)
505 }
506 gotRepos = getRepoNames(res.Files)
507 wantRepos = append([]string{}, projectARepos...)
508 sort.Strings(wantRepos)
509 if !reflect.DeepEqual(gotRepos, wantRepos) {
510 t.Fatalf("Meta(visibility=public):\ngot repos: %v\nwant repos: %v", gotRepos, wantRepos)
511 }
512
513 // Test 5: Filter by non-existent field - should return 0 results
514 metaQueryNonExistent := &query.Meta{
515 Field: "nonexistent_field",
516 Value: regexp.MustCompile(".*"),
517 }
518 res, err = ss.Search(context.Background(), query.NewAnd(metaQueryNonExistent, sub), &zoekt.SearchOptions{})
519 if err != nil {
520 t.Fatalf("Search with Meta filter non-existent: %v", err)
521 }
522 if len(res.Files) != 0 {
523 t.Fatalf("Meta(nonexistent_field): got %d results, want 0", len(res.Files))
524 }
525
526 // Test 6: Filter by regex pattern matching multiple values
527 metaQueryRegex := &query.Meta{
528 Field: "nickname",
529 Value: regexp.MustCompile("project-.*"), // Matches both project-A and project-B
530 }
531 res, err = ss.Search(context.Background(), query.NewAnd(metaQueryRegex, sub), &zoekt.SearchOptions{})
532 if err != nil {
533 t.Fatalf("Search with Meta regex filter: %v", err)
534 }
535 gotRepos = getRepoNames(res.Files)
536 wantRepos = append(append([]string{}, projectARepos...), projectBRepos...)
537 sort.Strings(wantRepos)
538 if !reflect.DeepEqual(gotRepos, wantRepos) {
539 t.Fatalf("Meta(nickname=project-.*):\ngot repos: %v\nwant repos: %v", gotRepos, wantRepos)
540 }
541
542 // Test 7: Test that Meta query alone (without content search) works
543 res, err = ss.Search(context.Background(), metaQueryA, &zoekt.SearchOptions{})
544 if err != nil {
545 t.Fatalf("Search with Meta query alone: %v", err)
546 }
547 gotRepos = getRepoNames(res.Files)
548 wantRepos = append([]string{}, projectARepos...)
549 sort.Strings(wantRepos)
550 if !reflect.DeepEqual(gotRepos, wantRepos) {
551 t.Fatalf("Meta query alone:\ngot repos: %v\nwant repos: %v", gotRepos, wantRepos)
552 }
553
554 // Test 8: Test with List operation (not just Search)
555 listRes, err := ss.List(context.Background(), metaQueryA, nil)
556 if err != nil {
557 t.Fatalf("List with Meta filter: %v", err)
558 }
559 gotListRepos := make([]string, len(listRes.Repos))
560 for i, r := range listRes.Repos {
561 gotListRepos[i] = r.Repository.Name
562 }
563 sort.Strings(gotListRepos)
564 wantRepos = append([]string{}, projectARepos...)
565 sort.Strings(wantRepos)
566 if !reflect.DeepEqual(gotListRepos, wantRepos) {
567 t.Fatalf("List with Meta(nickname=project-A):\ngot repos: %v\nwant repos: %v", gotListRepos, wantRepos)
568 }
569}
570
571func hash(name string) uint32 {
572 h := fnv.New32()
573 h.Write([]byte(name))
574 return h.Sum32()
575}
576
577type memSeeker struct {
578 data []byte
579}
580
581func (s *memSeeker) Name() string {
582 return "memseeker"
583}
584
585func (s *memSeeker) Close() {}
586func (s *memSeeker) Read(off, sz uint32) ([]byte, error) {
587 return s.data[off : off+sz], nil
588}
589
590func (s *memSeeker) Size() (uint32, error) {
591 return uint32(len(s.data)), nil
592}
593
594func TestUnloadIndex(t *testing.T) {
595 b := testShardBuilder(t, nil, index.Document{
596 Name: "filename",
597 Content: []byte("needle needle needle"),
598 })
599
600 var buf bytes.Buffer
601 if err := b.Write(&buf); err != nil {
602 t.Fatal(err)
603 }
604 indexBytes := buf.Bytes()
605 indexFile := &memSeeker{indexBytes}
606 searcher, err := index.NewSearcher(indexFile)
607 if err != nil {
608 t.Fatalf("NewSearcher: %v", err)
609 }
610
611 ss := newShardedSearcher(2)
612 ss.replace(map[string]zoekt.Searcher{"key": searcher})
613
614 var opts zoekt.SearchOptions
615 q := &query.Substring{Pattern: "needle"}
616 res, err := ss.Search(context.Background(), q, &opts)
617 if err != nil {
618 t.Fatalf("Search(%s): %v", q, err)
619 }
620
621 forbidden := byte(29)
622 for i := range indexBytes {
623 // non-ASCII
624 indexBytes[i] = forbidden
625 }
626
627 for _, f := range res.Files {
628 if bytes.Contains(f.Content, []byte{forbidden}) {
629 t.Errorf("found %d in content %q", forbidden, f.Content)
630 }
631 if bytes.Contains(f.Checksum, []byte{forbidden}) {
632 t.Errorf("found %d in checksum %q", forbidden, f.Checksum)
633 }
634
635 for _, l := range f.LineMatches {
636 if bytes.Contains(l.Line, []byte{forbidden}) {
637 t.Errorf("found %d in line %q", forbidden, l.Line)
638 }
639 }
640 }
641}
642
643func TestShardedSearcher_List(t *testing.T) {
644 repos := []*zoekt.Repository{
645 {
646 ID: 1234,
647 Name: "repo-a",
648 Branches: []zoekt.RepositoryBranch{{Name: "main"}, {Name: "dev"}},
649 RawConfig: map[string]string{"repoid": "1234"},
650 },
651 {
652 Name: "repo-b",
653 Branches: []zoekt.RepositoryBranch{{Name: "main"}, {Name: "dev"}},
654 },
655 }
656
657 doc := index.Document{
658 Name: "foo.go",
659 Content: []byte("bar\nbaz"),
660 Branches: []string{"main", "dev"},
661 }
662
663 // Test duplicate removal when ListOptions.Minimal is true and false
664 ss := newShardedSearcher(4)
665 ss.replace(map[string]zoekt.Searcher{
666 "1": searcherForTest(t, testShardBuilder(t, repos[0], doc)),
667 "2": searcherForTest(t, testShardBuilder(t, repos[0])),
668 "3": searcherForTest(t, testShardBuilder(t, repos[1], doc)),
669 "4": searcherForTest(t, testShardBuilder(t, repos[1])),
670 })
671 ss.markReady()
672
673 stats := zoekt.RepoStats{
674 Shards: 2,
675 Documents: 1,
676 IndexBytes: 196,
677 ContentBytes: 13,
678 NewLinesCount: 1,
679 DefaultBranchNewLinesCount: 1,
680 OtherBranchesNewLinesCount: 1,
681 }
682
683 aggStats := stats
684 aggStats.Add(&aggStats) // since both repos have the exact same stats, this works
685 aggStats.Repos = 2 // Add doesn't populate Repos, this is done in Shards based on the response sizes.
686
687 for _, tc := range []struct {
688 name string
689 opts *zoekt.ListOptions
690 want *zoekt.RepoList
691 }{
692 {
693 name: "nil opts",
694 opts: nil,
695 want: &zoekt.RepoList{
696 Repos: []*zoekt.RepoListEntry{
697 {
698 Repository: *repos[0],
699 Stats: stats,
700 },
701 {
702 Repository: *repos[1],
703 Stats: stats,
704 },
705 },
706 Stats: aggStats,
707 },
708 },
709 {
710 name: "default",
711 opts: &zoekt.ListOptions{},
712 want: &zoekt.RepoList{
713 Repos: []*zoekt.RepoListEntry{
714 {
715 Repository: *repos[0],
716 Stats: stats,
717 },
718 {
719 Repository: *repos[1],
720 Stats: stats,
721 },
722 },
723 Stats: aggStats,
724 },
725 },
726 {
727 name: "field=repos",
728 opts: &zoekt.ListOptions{Field: zoekt.RepoListFieldRepos},
729 want: &zoekt.RepoList{
730 Repos: []*zoekt.RepoListEntry{
731 {
732 Repository: *repos[0],
733 Stats: stats,
734 },
735 {
736 Repository: *repos[1],
737 Stats: stats,
738 },
739 },
740 Stats: aggStats,
741 },
742 },
743 {
744 name: "field=reposmap",
745 opts: &zoekt.ListOptions{Field: zoekt.RepoListFieldReposMap},
746 want: &zoekt.RepoList{
747 Repos: []*zoekt.RepoListEntry{
748 {
749 Repository: *repos[1],
750 Stats: stats,
751 },
752 },
753 ReposMap: zoekt.ReposMap{
754 repos[0].ID: {
755 HasSymbols: repos[0].HasSymbols,
756 Branches: repos[0].Branches,
757 },
758 },
759 Stats: aggStats,
760 },
761 },
762 } {
763 tc := tc
764 t.Run(tc.name, func(t *testing.T) {
765 t.Parallel()
766
767 q := &query.Repo{Regexp: regexp.MustCompile("repo")}
768
769 res, err := ss.List(context.Background(), q, tc.opts)
770 if err != nil {
771 t.Fatalf("List(%v, %s): %v", q, tc.opts, err)
772 }
773
774 sort.Slice(res.Repos, func(i, j int) bool {
775 return res.Repos[i].Repository.Name < res.Repos[j].Repository.Name
776 })
777
778 ignored := []cmp.Option{
779 cmpopts.EquateEmpty(),
780 cmpopts.IgnoreFields(zoekt.MinimalRepoListEntry{}, "IndexTimeUnix"),
781 cmpopts.IgnoreFields(zoekt.RepoListEntry{}, "IndexMetadata"),
782 cmpopts.IgnoreFields(zoekt.RepoStats{}, "IndexBytes"),
783 cmpopts.IgnoreFields(zoekt.Repository{}, "SubRepoMap"),
784 cmpopts.IgnoreFields(zoekt.Repository{}, "priority"),
785 }
786
787 if diff := cmp.Diff(tc.want, res, ignored...); diff != "" {
788 t.Fatalf("mismatch (-want +got):\n%s", diff)
789 }
790 })
791 }
792}
793
794func testShardBuilder(t testing.TB, repo *zoekt.Repository, docs ...index.Document) *index.ShardBuilder {
795 b, err := index.NewShardBuilder(repo)
796 if err != nil {
797 t.Fatalf("NewShardBuilder: %v", err)
798 }
799
800 for i, d := range docs {
801 if err := b.Add(d); err != nil {
802 t.Fatalf("Add %d: %v", i, err)
803 }
804 }
805 return b
806}
807
808func searcherForTest(t testing.TB, b *index.ShardBuilder) zoekt.Searcher {
809 var buf bytes.Buffer
810 if err := b.Write(&buf); err != nil {
811 t.Fatal(err)
812 }
813 f := &memSeeker{buf.Bytes()}
814
815 searcher, err := index.NewSearcher(f)
816 if err != nil {
817 t.Fatalf("NewSearcher: %v", err)
818 }
819
820 return searcher
821}
822
823func reposForTest(n int) (result []*zoekt.Repository) {
824 for i := range n {
825 result = append(result, &zoekt.Repository{
826 ID: uint32(i + 1),
827 Name: fmt.Sprintf("test-repository-%d", i),
828 })
829 }
830 return result
831}
832
833func testSearcherForRepo(b testing.TB, r *zoekt.Repository, numFiles int) zoekt.Searcher {
834 builder := testShardBuilder(b, r)
835
836 if err := builder.Add(index.Document{
837 Name: fmt.Sprintf("%s/filename-%d.go", r.Name, 0),
838 Content: []byte("needle needle needle haystack"),
839 }); err != nil {
840 b.Fatal(err)
841 }
842
843 for i := 1; i < numFiles; i++ {
844 if err := builder.Add(index.Document{
845 Name: fmt.Sprintf("%s/filename-%d.go", r.Name, i),
846 Content: []byte("haystack haystack haystack"),
847 }); err != nil {
848 b.Fatal(err)
849 }
850 }
851
852 return searcherForTest(b, builder)
853}
854
855func BenchmarkShardedSearch(b *testing.B) {
856 ss := newShardedSearcher(int64(runtime.GOMAXPROCS(0)))
857
858 filesPerRepo := 300
859 repos := reposForTest(3000)
860 var repoSetIDs []uint32
861
862 shards := make(map[string]zoekt.Searcher, len(repos))
863 for i, r := range repos {
864 shards[r.Name] = testSearcherForRepo(b, r, filesPerRepo)
865 if i%2 == 0 {
866 repoSetIDs = append(repoSetIDs, r.ID)
867 }
868 }
869
870 ss.replace(shards)
871
872 ctx := context.Background()
873 opts := &zoekt.SearchOptions{}
874
875 needleSub := &query.Substring{Pattern: "needle"}
876 haystackSub := &query.Substring{Pattern: "haystack"}
877 helloworldSub := &query.Substring{Pattern: "helloworld"}
878 haystackCap, err := query.Parse("hay(s(t))(a)ck")
879 if err != nil {
880 b.Fatal(err)
881 }
882
883 haystackNonCap, err := query.Parse("hay(?:s(?:t))(?:a)ck")
884 if err != nil {
885 b.Fatal(err)
886 }
887
888 setAnd := func(q query.Q) func() query.Q {
889 return func() query.Q {
890 return query.NewAnd(query.NewSingleBranchesRepos("head", repoSetIDs...), q)
891 }
892 }
893
894 search := func(b *testing.B, q query.Q, wantFiles int) {
895 b.Helper()
896
897 res, err := ss.Search(ctx, q, opts)
898 if err != nil {
899 b.Fatalf("Search(%s): %v", q, err)
900 }
901 if have := len(res.Files); have != wantFiles {
902 b.Fatalf("wrong number of file results. have=%d, want=%d", have, wantFiles)
903 }
904 }
905
906 benchmarks := []struct {
907 name string
908 q func() query.Q
909 wantFiles int
910 }{
911 {"substring all results", func() query.Q { return haystackSub }, len(repos) * filesPerRepo},
912 {"substring no results", func() query.Q { return helloworldSub }, 0},
913 {"substring some results", func() query.Q { return needleSub }, len(repos)},
914
915 {"regexp all results capture", func() query.Q { return haystackCap }, len(repos) * filesPerRepo},
916 {"regexp all results non-capture", func() query.Q { return haystackNonCap }, len(repos) * filesPerRepo},
917
918 {"substring all results and repo set", setAnd(haystackSub), len(repoSetIDs) * filesPerRepo},
919 {"substring some results and repo set", setAnd(needleSub), len(repoSetIDs)},
920 {"substring no results and repo set", setAnd(helloworldSub), 0},
921 }
922
923 for _, bb := range benchmarks {
924 b.Run(bb.name, func(b *testing.B) {
925 b.ReportAllocs()
926
927 for n := 0; n < b.N; n++ {
928 q := bb.q()
929
930 search(b, q, bb.wantFiles)
931 }
932 })
933 }
934}
935
936func TestRawQuerySearch(t *testing.T) {
937 ss := newShardedSearcher(1)
938
939 var nextShardNum int
940 addShard := func(repo string, rawConfig map[string]string, docs ...index.Document) {
941 r := &zoekt.Repository{Name: repo}
942 r.RawConfig = rawConfig
943 b := testShardBuilder(t, r, docs...)
944 shard := searcherForTest(t, b)
945 ss.replace(map[string]zoekt.Searcher{fmt.Sprintf("key-%d", nextShardNum): shard})
946 nextShardNum++
947 }
948 addShard("public", map[string]string{"public": "1"}, index.Document{Name: "f1", Content: []byte("foo bar bas")})
949 addShard("private_archived", map[string]string{"archived": "1"}, index.Document{Name: "f2", Content: []byte("foo bas")})
950 addShard("public_fork", map[string]string{"public": "1", "fork": "1"}, index.Document{Name: "f3", Content: []byte("foo bar")})
951
952 cases := []struct {
953 pattern string
954 flags query.RawConfig
955 wantRepos []string
956 wantFiles int
957 }{
958 {
959 pattern: "bas",
960 flags: query.RcOnlyPublic,
961 wantRepos: []string{"public"},
962 wantFiles: 1,
963 },
964 {
965 pattern: "foo",
966 flags: query.RcOnlyPublic,
967 wantRepos: []string{"public", "public_fork"},
968 wantFiles: 2,
969 },
970 {
971 pattern: "foo",
972 flags: query.RcOnlyPublic | query.RcNoForks,
973 wantRepos: []string{"public"},
974 wantFiles: 1,
975 },
976 {
977 pattern: "bar",
978 flags: query.RcOnlyForks,
979 wantRepos: []string{"public_fork"},
980 wantFiles: 1,
981 },
982 {
983 pattern: "bas",
984 flags: query.RcNoArchived,
985 wantRepos: []string{"public"},
986 wantFiles: 1,
987 },
988 {
989 pattern: "foo",
990 flags: query.RcNoForks,
991 wantRepos: []string{"public", "private_archived"},
992 wantFiles: 2,
993 },
994 {
995 pattern: "bas",
996 flags: query.RcOnlyArchived,
997 wantRepos: []string{"private_archived"},
998 wantFiles: 1,
999 },
1000 {
1001 pattern: "foo",
1002 flags: query.RcOnlyPrivate,
1003 wantRepos: []string{"private_archived"},
1004 wantFiles: 1,
1005 },
1006 {
1007 pattern: "foo",
1008 flags: query.RcOnlyPrivate | query.RcNoArchived,
1009 wantRepos: []string{},
1010 wantFiles: 0,
1011 },
1012 }
1013 for _, c := range cases {
1014 t.Run(fmt.Sprintf("pattern:%s", c.pattern), func(t *testing.T) {
1015 q := query.NewAnd(&query.Substring{Pattern: c.pattern}, c.flags)
1016
1017 sr, err := ss.Search(context.Background(), q, &zoekt.SearchOptions{})
1018 if err != nil {
1019 t.Fatal(err)
1020 }
1021
1022 if got := len(sr.Files); got != c.wantFiles {
1023 t.Fatalf("wanted %d, got %d", c.wantFiles, got)
1024 }
1025
1026 if c.wantFiles == 0 {
1027 return
1028 }
1029
1030 gotRepos := make([]string, 0, len(sr.RepoURLs))
1031 for k := range sr.RepoURLs {
1032 gotRepos = append(gotRepos, k)
1033 }
1034 sort.Strings(gotRepos)
1035 sort.Strings(c.wantRepos)
1036 if d := cmp.Diff(c.wantRepos, gotRepos); d != "" {
1037 t.Fatalf("(-want, +got):\n%s", d)
1038 }
1039 })
1040 }
1041}
1042
1043func TestPrioritySlice(t *testing.T) {
1044 p := &prioritySlice{}
1045 for step, oper := range []struct {
1046 isAppend bool
1047 value float64
1048 expectedMax float64
1049 }{
1050 {true, 1, 1},
1051 {true, 3, 3},
1052 {true, 2, 3},
1053 {false, 1, 3},
1054 {false, 3, 2},
1055 {false, 2, math.Inf(-1)},
1056 } {
1057 if oper.isAppend {
1058 p.append(oper.value)
1059 } else {
1060 p.remove(oper.value)
1061 }
1062 max := p.max()
1063 if max != oper.expectedMax {
1064 t.Errorf("%d: got %f, want %f", step, max, oper.expectedMax)
1065 }
1066 }
1067}
1068
1069func TestSendByRepository(t *testing.T) {
1070 wantStats := zoekt.Stats{}
1071 wantStats.ShardsScanned = 1
1072
1073 // n1, n2, n3 are the number of file matches for each of the 3 repositories in this
1074 // test.
1075 f := func(n1, n2, n3 uint8) bool {
1076 sr := createMockSearchResult(n1, n2, n3, wantStats)
1077
1078 mock := &mockSender{}
1079 sendByRepository(sr, &zoekt.SearchOptions{}, mock)
1080
1081 if diff := cmp.Diff(wantStats, mock.stats); diff != "" {
1082 t.Logf("-want,+got\n%s", diff)
1083 return false
1084 }
1085
1086 nonZero := 0
1087 for _, l := range []uint8{n1, n2, n3} {
1088 if l > 0 {
1089 nonZero++
1090 }
1091 }
1092 if l := len(mock.files); l != nonZero {
1093 t.Logf("wanted results from %d repositores, got %d", nonZero, l)
1094 return false
1095 }
1096
1097 gotTotal := 0
1098 for _, fs := range mock.files {
1099 gotTotal += len(fs)
1100 }
1101 wantTotal := int(n1) + int(n2) + int(n3)
1102 if gotTotal != wantTotal {
1103 t.Logf("wanted %d file matches, got %d", wantTotal, gotTotal)
1104 return false
1105 }
1106
1107 for _, fs := range mock.files {
1108 if len(fs) == 0 {
1109 t.Logf("got search result with 0 file matches after split")
1110 return false
1111 }
1112 }
1113 return true
1114 }
1115
1116 if err := quick.Check(f, nil); err != nil {
1117 t.Error(err)
1118 }
1119}
1120
1121type mockSender struct {
1122 stats zoekt.Stats
1123 files [][]zoekt.FileMatch
1124}
1125
1126func (s *mockSender) Send(sr *zoekt.SearchResult) {
1127 s.stats.Add(sr.Stats)
1128 if len(sr.Files) == 0 {
1129 return
1130 }
1131 s.files = append(s.files, sr.Files)
1132}
1133
1134func createMockSearchResult(n1, n2, n3 uint8, stats zoekt.Stats) *zoekt.SearchResult {
1135 sr := &zoekt.SearchResult{RepoURLs: make(map[string]string)}
1136 for i, n := range []uint8{n1, n2, n3} {
1137 if n == 0 {
1138 continue
1139 }
1140 tmp := mkSearchResult(int(n), uint32(i))
1141 sr.Files = append(sr.Files, tmp.Files...)
1142 for k := range tmp.RepoURLs {
1143 sr.RepoURLs[k] = ""
1144 }
1145 }
1146 sr.Stats = stats
1147 return sr
1148}
1149
1150func mkSearchResult(n int, repoID uint32) *zoekt.SearchResult {
1151 if n == 0 {
1152 return &zoekt.SearchResult{}
1153 }
1154 fm := make([]zoekt.FileMatch, 0, n)
1155 for range n {
1156 fm = append(fm, zoekt.FileMatch{Repository: fmt.Sprintf("repo%d", repoID), RepositoryID: repoID})
1157 }
1158
1159 return &zoekt.SearchResult{Files: fm, RepoURLs: map[string]string{fmt.Sprintf("repo%d", repoID): ""}}
1160}
1161
1162func TestFileBasedSearch(t *testing.T) {
1163 cases := []struct {
1164 name string
1165 testShardedSearch func(t *testing.T, q query.Q, ib *index.ShardBuilder, useDocumentRanks bool) []zoekt.FileMatch
1166 }{
1167 {"Search", testShardedSearch},
1168 {"StreamSearch", testShardedStreamSearch},
1169 }
1170
1171 c1 := []byte("I love bananas without skin")
1172 // -----------0123456789012345678901234567890123456789
1173 c2 := []byte("In Dutch, ananas means pineapple")
1174 // -----------0123456789012345678901234567890123456789
1175 b := testShardBuilder(t, nil,
1176 index.Document{Name: "f1", Content: c1},
1177 index.Document{Name: "f2", Content: c2},
1178 )
1179
1180 for _, tt := range cases {
1181 for _, useDocumentRanks := range []bool{false, true} {
1182 t.Run(tt.name, func(t *testing.T) {
1183 matches := tt.testShardedSearch(t, &query.Substring{
1184 CaseSensitive: false,
1185 Pattern: "ananas",
1186 }, b, useDocumentRanks)
1187
1188 if len(matches) != 2 {
1189 t.Fatalf("got %v, want 2 matches", matches)
1190 }
1191 if matches[0].FileName != "f2" || matches[1].FileName != "f1" {
1192 t.Fatalf("got %v, want matches {f1,f2}", matches)
1193 }
1194 if matches[0].LineMatches[0].LineFragments[0].Offset != 10 || matches[1].LineMatches[0].LineFragments[0].Offset != 8 {
1195 t.Fatalf("got %#v, want offsets 10,8", matches)
1196 }
1197 })
1198 }
1199 }
1200}
1201
1202func TestWordBoundaryRanking(t *testing.T) {
1203 cases := []struct {
1204 name string
1205 testShardedSearch func(t *testing.T, q query.Q, ib *index.ShardBuilder, useDocumentRanks bool) []zoekt.FileMatch
1206 }{
1207 {"Search", testShardedSearch},
1208 {"StreamSearch", testShardedStreamSearch},
1209 }
1210
1211 b := testShardBuilder(t, nil,
1212 index.Document{Name: "f1", Content: []byte("xbytex xbytex")},
1213 index.Document{Name: "f2", Content: []byte("xbytex\nbytex\nbyte bla")},
1214 // -----------------------------------------0123456 789012 34567890
1215 index.Document{Name: "f3", Content: []byte("xbytex ybytex")})
1216
1217 for _, tt := range cases {
1218 for _, useDocumentRanks := range []bool{false, true} {
1219 t.Run(tt.name, func(t *testing.T) {
1220 files := tt.testShardedSearch(t, &query.Substring{Pattern: "byte"}, b, useDocumentRanks)
1221
1222 if len(files) != 3 {
1223 t.Fatalf("got %#v, want 3 files", files)
1224 }
1225
1226 file0 := files[0]
1227 if file0.FileName != "f2" || len(file0.LineMatches) != 3 {
1228 t.Fatalf("got file %s, num matches %d (%#v), want 3 matches in file f2", file0.FileName, len(file0.LineMatches), file0)
1229 }
1230
1231 if file0.LineMatches[0].LineFragments[0].Offset != 13 {
1232 t.Fatalf("got first match %#v, want full word match", files[0].LineMatches[0])
1233 }
1234 if file0.LineMatches[1].LineFragments[0].Offset != 7 {
1235 t.Fatalf("got second match %#v, want partial word match", files[0].LineMatches[1])
1236 }
1237 })
1238 }
1239 }
1240}
1241
1242func TestAtomCountScore(t *testing.T) {
1243 cases := []struct {
1244 name string
1245 testShardedSearch func(t *testing.T, q query.Q, ib *index.ShardBuilder, useDocumentRanks bool) []zoekt.FileMatch
1246 }{
1247 {"Search", testShardedSearch},
1248 {"StreamSearch", testShardedStreamSearch},
1249 }
1250
1251 b := testShardBuilder(t,
1252 &zoekt.Repository{
1253 Branches: []zoekt.RepositoryBranch{
1254 {Name: "branches", Version: "v1"},
1255 {Name: "needle", Version: "v2"},
1256 },
1257 },
1258 index.Document{Name: "f1", Content: []byte("needle the bla"), Branches: []string{"branches"}},
1259 index.Document{Name: "needle-file-branch", Content: []byte("needle content"), Branches: []string{"needle"}},
1260 index.Document{Name: "needle-file", Content: []byte("needle content"), Branches: []string{"branches"}})
1261
1262 for _, tt := range cases {
1263 for _, useDocumentRanks := range []bool{false, true} {
1264 t.Run(tt.name, func(t *testing.T) {
1265 files := tt.testShardedSearch(t,
1266 query.NewOr(
1267 &query.Substring{Pattern: "needle"},
1268 &query.Substring{Pattern: "needle", FileName: true},
1269 &query.Branch{Pattern: "needle"},
1270 ), b, useDocumentRanks)
1271 var got []string
1272 for _, f := range files {
1273 got = append(got, f.FileName)
1274 }
1275 want := []string{"needle-file-branch", "needle-file", "f1"}
1276 if !reflect.DeepEqual(got, want) {
1277 t.Errorf("got %v, want %v", got, want)
1278 }
1279 })
1280 }
1281 }
1282}
1283
1284func TestUseBM25Scoring(t *testing.T) {
1285 b := testShardBuilder(t,
1286 &zoekt.Repository{},
1287 index.Document{Name: "f1", Content: []byte("one two two three")},
1288 index.Document{Name: "f2", Content: []byte("one two one two")},
1289 index.Document{Name: "f3", Content: []byte("one three three three")})
1290
1291 ss := newShardedSearcher(1)
1292 searcher := searcherForTest(t, b)
1293 ss.replace(map[string]zoekt.Searcher{"r1": searcher})
1294
1295 q := query.NewOr(
1296 &query.Substring{Pattern: "one"},
1297 &query.Substring{Pattern: "three"})
1298
1299 opts := zoekt.SearchOptions{
1300 UseBM25Scoring: true,
1301 }
1302
1303 results, err := ss.Search(context.Background(), q, &opts)
1304 if err != nil {
1305 t.Fatal(err)
1306 }
1307
1308 var got []string
1309 for _, f := range results.Files {
1310 got = append(got, f.FileName)
1311 }
1312
1313 want := []string{"f3", "f1", "f2"}
1314 if !reflect.DeepEqual(got, want) {
1315 t.Errorf("got %v, want %v", got, want)
1316 }
1317}
1318
1319func testShardedStreamSearch(t *testing.T, q query.Q, ib *index.ShardBuilder, useDocumentRanks bool) []zoekt.FileMatch {
1320 ss := newShardedSearcher(1)
1321 searcher := searcherForTest(t, ib)
1322 ss.replace(map[string]zoekt.Searcher{"r1": searcher})
1323
1324 var files []zoekt.FileMatch
1325 sender := zoekt.SenderFunc(func(result *zoekt.SearchResult) {
1326 files = append(files, result.Files...)
1327 })
1328
1329 opts := zoekt.SearchOptions{}
1330 if useDocumentRanks {
1331 opts.FlushWallTime = 10 * time.Millisecond
1332 }
1333 if err := ss.StreamSearch(context.Background(), q, &opts, sender); err != nil {
1334 t.Fatal(err)
1335 }
1336 return files
1337}
1338
1339func testShardedSearch(t *testing.T, q query.Q, ib *index.ShardBuilder, useDocumentRanks bool) []zoekt.FileMatch {
1340 ss := newShardedSearcher(1)
1341 searcher := searcherForTest(t, ib)
1342 ss.replace(map[string]zoekt.Searcher{"r1": searcher})
1343
1344 opts := zoekt.SearchOptions{}
1345 if useDocumentRanks {
1346 opts.FlushWallTime = 50 * time.Millisecond
1347 }
1348 sres, _ := ss.Search(context.Background(), q, &opts)
1349 return sres.Files
1350}
1351
1352// Ensure we work on empty shard directories.
1353func TestNewDirectorySearcher_empty(t *testing.T) {
1354 ctx := context.Background()
1355
1356 test := func(t *testing.T, ss zoekt.Streamer) {
1357 res, err := ss.Search(ctx, &query.Const{Value: true}, nil)
1358 if err != nil {
1359 t.Fatal("Search non-nil error", err)
1360 }
1361
1362 if diff := cmp.Diff(&zoekt.SearchResult{}, res, cmpopts.IgnoreFields(zoekt.Stats{}, "Duration", "Wait"), cmpopts.EquateEmpty()); diff != "" {
1363 t.Fatalf("Search had non empty results (-want, +got):\n%s", diff)
1364 }
1365
1366 rl, err := ss.List(ctx, &query.Const{Value: true}, nil)
1367 if err != nil {
1368 t.Fatal("List non-nil error", err)
1369 }
1370 if diff := cmp.Diff(&zoekt.RepoList{}, rl, cmpopts.EquateEmpty()); diff != "" {
1371 t.Fatalf("List had non empty results (-want, +got):\n%s", diff)
1372 }
1373 }
1374
1375 dir := t.TempDir()
1376 t.Run("blocking", func(t *testing.T) {
1377 ss, err := NewDirectorySearcher(dir)
1378 if err != nil {
1379 t.Fatal(err)
1380 }
1381 t.Cleanup(ss.Close)
1382
1383 // We expect crashes to be empty as soon as NewDirectorySearcher returns
1384 // so we can validate straight away.
1385 test(t, ss)
1386 })
1387
1388 t.Run("fast", func(t *testing.T) {
1389 ss, err := NewDirectorySearcherFast(dir)
1390 if err != nil {
1391 t.Fatal(err)
1392 }
1393 t.Cleanup(ss.Close)
1394
1395 deadline := testDeadline(t, 10*time.Second)
1396
1397 // Wait for scanning of directory to be done. We should be returning
1398 // non-zero crashes until then.
1399 waitForPredicate(deadline, 10*time.Millisecond, func() bool {
1400 res, err := ss.Search(ctx, &query.Const{Value: true}, nil)
1401 if err != nil {
1402 t.Fatal(err)
1403 }
1404 return res.Stats.Crashes == 0
1405 })
1406
1407 test(t, ss)
1408 })
1409}
1410
1411// testDeadline returns the deadline for t, but ensures it is no longer than
1412// maxTimeout away.
1413func testDeadline(t *testing.T, maxTimeout time.Duration) time.Time {
1414 deadline := time.Now().Add(maxTimeout)
1415 if d, ok := t.Deadline(); ok && d.Before(deadline) {
1416 // give 1s for us to do a final test run
1417 deadline = d.Add(-time.Second)
1418 }
1419 return deadline
1420}
1421
1422func waitForPredicate(deadline time.Time, tick time.Duration, pred func() bool) bool {
1423 for time.Now().Before(deadline) {
1424 if pred() {
1425 return true
1426 }
1427
1428 time.Sleep(tick)
1429 }
1430
1431 return pred()
1432}