forked from sourcegraph/sourcegraph-public-snapshot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.go
More file actions
1283 lines (1133 loc) · 39 KB
/
Copy pathgithub.go
File metadata and controls
1283 lines (1133 loc) · 39 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 repos
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/grafana/regexp"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/sourcegraph/log"
"github.com/sourcegraph/sourcegraph/internal/conf/reposource"
"github.com/sourcegraph/sourcegraph/internal/extsvc"
"github.com/sourcegraph/sourcegraph/internal/extsvc/auth"
"github.com/sourcegraph/sourcegraph/internal/extsvc/github"
ghauth "github.com/sourcegraph/sourcegraph/internal/extsvc/github/auth"
"github.com/sourcegraph/sourcegraph/internal/httpcli"
"github.com/sourcegraph/sourcegraph/internal/jsonc"
"github.com/sourcegraph/sourcegraph/internal/lazyregexp"
"github.com/sourcegraph/sourcegraph/internal/ratelimit"
"github.com/sourcegraph/sourcegraph/internal/types"
"github.com/sourcegraph/sourcegraph/lib/errors"
"github.com/sourcegraph/sourcegraph/schema"
)
// A GitHubSource yields repositories from a single GitHub connection configured
// in Sourcegraph via the external services configuration.
type GitHubSource struct {
svc *types.ExternalService
config *schema.GitHubConnection
exclude excludeFunc
githubDotCom bool
baseURL *url.URL
v3Client *github.V3Client
v4Client *github.V4Client
// searchClient is for using the GitHub search API, which has an independent
// rate limit much lower than non-search API requests.
searchClient *github.V3Client
// originalHostname is the hostname of config.Url (differs from client APIURL, whose host is api.github.com
// for an originalHostname of github.com).
originalHostname string
logger log.Logger
}
var (
_ Source = &GitHubSource{}
_ UserSource = &GitHubSource{}
_ AffiliatedRepositorySource = &GitHubSource{}
_ VersionSource = &GitHubSource{}
)
// NewGitHubSource returns a new GitHubSource from the given external service.
func NewGitHubSource(ctx context.Context, logger log.Logger, svc *types.ExternalService, cf *httpcli.Factory) (*GitHubSource, error) {
rawConfig, err := svc.Config.Decrypt(ctx)
if err != nil {
return nil, errors.Errorf("external service id=%d config error: %s", svc.ID, err)
}
var c schema.GitHubConnection
if err := jsonc.Unmarshal(rawConfig, &c); err != nil {
return nil, errors.Errorf("external service id=%d config error: %s", svc.ID, err)
}
return newGitHubSource(ctx, logger, svc, &c, cf)
}
var githubRemainingGauge = promauto.NewGaugeVec(prometheus.GaugeOpts{
// _v2 since we have an older metric defined in github-proxy
Name: "src_github_rate_limit_remaining_v2",
Help: "Number of calls to GitHub's API remaining before hitting the rate limit.",
}, []string{"resource", "name"})
var githubRatelimitWaitCounter = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "src_github_rate_limit_wait_duration_seconds",
Help: "The amount of time spent waiting on the rate limit",
}, []string{"resource", "name"})
func newGitHubSource(
ctx context.Context,
logger log.Logger,
svc *types.ExternalService,
c *schema.GitHubConnection,
cf *httpcli.Factory,
) (*GitHubSource, error) {
baseURL, err := url.Parse(c.Url)
if err != nil {
return nil, err
}
baseURL = extsvc.NormalizeBaseURL(baseURL)
originalHostname := baseURL.Hostname()
apiURL, githubDotCom := github.APIRoot(baseURL)
if cf == nil {
cf = httpcli.ExternalClientFactory
}
opts := []httpcli.Opt{
// Use a 30s timeout to avoid running into EOF errors, because GitHub
// closes idle connections after 60s
httpcli.NewIdleConnTimeoutOpt(30 * time.Second),
}
if c.Certificate != "" {
opts = append(opts, httpcli.NewCertPoolOpt(c.Certificate))
}
cli, err := cf.Doer(opts...)
if err != nil {
return nil, err
}
var (
eb excludeBuilder
excludeForks bool
)
excludeArchived := func(repo any) bool {
if githubRepo, ok := repo.(github.Repository); ok {
return githubRepo.IsArchived
}
return false
}
excludeFork := func(repo any) bool {
if githubRepo, ok := repo.(github.Repository); ok {
return githubRepo.IsFork
}
return false
}
for _, r := range c.Exclude {
if r.Archived {
eb.Generic(excludeArchived)
}
if r.Forks {
excludeForks = true
eb.Generic(excludeFork)
}
eb.Exact(r.Name)
eb.Exact(r.Id)
eb.Pattern(r.Pattern)
}
exclude, err := eb.Build()
if err != nil {
return nil, err
}
auther, err := ghauth.FromConnection(ctx, c)
if err != nil {
return nil, err
}
urn := svc.URN()
var (
v3ClientLogger = log.Scoped("source", "github client for github source")
v3Client = github.NewV3Client(v3ClientLogger, urn, apiURL, auther, cli)
v4Client = github.NewV4Client(urn, apiURL, auther, cli)
searchClientLogger = log.Scoped("search", "github client for search")
searchClient = github.NewV3SearchClient(searchClientLogger, urn, apiURL, auther, cli)
)
for resource, monitor := range map[string]*ratelimit.Monitor{
"rest": v3Client.ExternalRateLimiter(),
"graphql": v4Client.ExternalRateLimiter(),
"search": searchClient.ExternalRateLimiter(),
} {
// Copy the resource or funcs below will use the last one seen while iterating
// the map
resource := resource
// Copy displayName so that the funcs below don't capture the svc pointer
displayName := svc.DisplayName
monitor.SetCollector(&ratelimit.MetricsCollector{
Remaining: func(n float64) {
githubRemainingGauge.WithLabelValues(resource, displayName).Set(n)
},
WaitDuration: func(n time.Duration) {
githubRatelimitWaitCounter.WithLabelValues(resource, displayName).Add(n.Seconds())
},
})
}
return &GitHubSource{
svc: svc,
config: c,
exclude: exclude,
baseURL: baseURL,
githubDotCom: githubDotCom,
v3Client: v3Client,
v4Client: v4Client,
searchClient: searchClient,
originalHostname: originalHostname,
logger: logger.With(
log.Object("GitHubSource",
log.Bool("excludeForks", excludeForks),
log.Bool("githubDotCom", githubDotCom),
log.String("originalHostname", originalHostname),
),
),
}, nil
}
func (s *GitHubSource) WithAuthenticator(a auth.Authenticator) (Source, error) {
sc := *s
sc.v3Client = sc.v3Client.WithAuthenticator(a)
sc.v4Client = sc.v4Client.WithAuthenticator(a)
sc.searchClient = sc.searchClient.WithAuthenticator(a)
return &sc, nil
}
type githubResult struct {
err error
repo *github.Repository
}
func (s *GitHubSource) ValidateAuthenticator(ctx context.Context) error {
var err error
_, err = s.v3Client.GetAuthenticatedOAuthScopes(ctx)
return err
}
func (s *GitHubSource) Version(ctx context.Context) (string, error) {
return s.v3Client.GetVersion(ctx)
}
func (s *GitHubSource) CheckConnection(ctx context.Context) error {
_, err := s.v3Client.GetAuthenticatedUser(ctx)
if err != nil {
return errors.Wrap(err, "connection check failed. could not fetch authenticated user")
}
return nil
}
// ListRepos returns all Github repositories accessible to all connections configured
// in Sourcegraph via the external services configuration.
func (s *GitHubSource) ListRepos(ctx context.Context, results chan SourceResult) {
unfiltered := make(chan *githubResult)
go func() {
s.listAllRepositories(ctx, unfiltered)
close(unfiltered)
}()
seen := make(map[int64]bool)
for res := range unfiltered {
if res.err != nil {
results <- SourceResult{Source: s, Err: res.err}
continue
}
s.logger.Debug("unfiltered", log.String("repo", res.repo.NameWithOwner))
if !seen[res.repo.DatabaseID] && !s.excludes(res.repo) {
results <- SourceResult{Source: s, Repo: s.makeRepo(res.repo)}
s.logger.Debug("sent to result", log.String("repo", res.repo.NameWithOwner))
seen[res.repo.DatabaseID] = true
}
}
}
// SearchRepositories returns the Github repositories matching the repositoryQuery and excluded repositories criteria.
func (s *GitHubSource) SearchRepositories(ctx context.Context, query string, first int, excludedRepos []string, results chan SourceResult) {
// default to fetching affiliated repositories
if query == "" {
s.fetchReposAffiliated(ctx, first, excludedRepos, results)
} else {
s.searchReposSinglePage(ctx, query, first, excludedRepos, results)
}
}
func (s *GitHubSource) searchReposSinglePage(ctx context.Context, query string, first int, excludedRepos []string, results chan SourceResult) {
unfiltered := make(chan *githubResult)
var queryWithExcludeBuilder strings.Builder
queryWithExcludeBuilder.WriteString(query)
for _, repo := range excludedRepos {
fmt.Fprintf(&queryWithExcludeBuilder, " -repo:%s", repo)
}
queryWithExclude := queryWithExcludeBuilder.String()
repoQuery := repositoryQuery{Query: queryWithExclude, First: first, Searcher: s.v4Client, Logger: s.logger}
go func() {
repoQuery.DoSingleRequest(ctx, unfiltered)
close(unfiltered)
}()
s.logger.Debug("fetch github repos by search query", log.String("query", query), log.Int("excluded repos count", len(excludedRepos)))
for res := range unfiltered {
if res.err != nil {
results <- SourceResult{Source: s, Err: res.err}
continue
}
results <- SourceResult{Source: s, Repo: s.makeRepo(res.repo)}
s.logger.Debug("sent to result", log.String("repo", res.repo.NameWithOwner))
}
}
func (s *GitHubSource) fetchReposAffiliated(ctx context.Context, first int, excludedRepos []string, results chan SourceResult) {
unfiltered := make(chan *githubResult)
// request larger page of results to account for exclusion taking effect afterwards
bufferedFirst := first + len(excludedRepos)
go func() {
s.listAffiliatedPage(ctx, bufferedFirst, unfiltered)
close(unfiltered)
}()
var eb excludeBuilder
// Only exclude on exact nameWithOwner match
for _, r := range excludedRepos {
eb.Exact(r)
}
exclude, err := eb.Build()
if err != nil {
results <- SourceResult{Source: s, Err: err}
return
}
s.logger.Debug("fetch github repos by affiliation", log.Int("excluded repos count", len(excludedRepos)))
for res := range unfiltered {
if first < 1 {
continue // drain the remaining githubResults from unfiltered
}
if res.err != nil {
results <- SourceResult{Source: s, Err: res.err}
continue
}
s.logger.Debug("unfiltered", log.String("repo", res.repo.NameWithOwner))
if !exclude(res.repo.NameWithOwner) {
results <- SourceResult{Source: s, Repo: s.makeRepo(res.repo)}
s.logger.Debug("sent to result", log.String("repo", res.repo.NameWithOwner))
first--
}
}
}
// ExternalServices returns a singleton slice containing the external service.
func (s *GitHubSource) ExternalServices() types.ExternalServices {
return types.ExternalServices{s.svc}
}
// ListNamespaces returns all Github organizations accessible to the given source defined
// via the external service configuration.
func (s *GitHubSource) ListNamespaces(ctx context.Context, results chan SourceNamespaceResult) {
var err error
orgs := make([]*github.Org, 0)
hasNextPage := true
for page := 1; hasNextPage; page++ {
if err = ctx.Err(); err != nil {
results <- SourceNamespaceResult{Err: err}
return
}
var pageOrgs []*github.Org
pageOrgs, hasNextPage, _, err = s.v3Client.GetAuthenticatedUserOrgsForPage(ctx, page)
if err != nil {
results <- SourceNamespaceResult{Source: s, Err: err}
continue
}
orgs = append(orgs, pageOrgs...)
}
for _, org := range orgs {
results <- SourceNamespaceResult{Source: s, Namespace: &types.ExternalServiceNamespace{ID: org.ID, Name: org.Login, ExternalID: org.NodeID}}
}
}
// GetRepo returns the GitHub repository with the given name and owner
// ("org/repo-name")
func (s *GitHubSource) GetRepo(ctx context.Context, nameWithOwner string) (*types.Repo, error) {
r, err := s.getRepository(ctx, nameWithOwner)
if err != nil {
return nil, err
}
return s.makeRepo(r), nil
}
func sanitizeToUTF8(s string) string {
return strings.ToValidUTF8(strings.ReplaceAll(s, "\x00", ""), "")
}
func (s *GitHubSource) makeRepo(r *github.Repository) *types.Repo {
urn := s.svc.URN()
metadata := *r
// This field flip flops depending on which token was used to retrieve the repo
// so we don't want to store it.
metadata.ViewerPermission = ""
metadata.Description = sanitizeToUTF8(metadata.Description)
return &types.Repo{
Name: reposource.GitHubRepoName(
s.config.RepositoryPathPattern,
s.originalHostname,
r.NameWithOwner,
),
URI: string(reposource.GitHubRepoName(
"",
s.originalHostname,
r.NameWithOwner,
)),
ExternalRepo: github.ExternalRepoSpec(r, s.baseURL),
Description: sanitizeToUTF8(r.Description),
Fork: r.IsFork,
Archived: r.IsArchived,
Stars: r.StargazerCount,
Private: r.IsPrivate,
Sources: map[string]*types.SourceInfo{
urn: {
ID: urn,
CloneURL: s.remoteURL(r),
},
},
Metadata: &metadata,
}
}
// remoteURL returns the repository's Git remote URL
//
// note: this used to contain credentials but that is no longer the case
// if you need to get an authenticated clone url use repos.CloneURL
func (s *GitHubSource) remoteURL(repo *github.Repository) string {
if s.config.GitURLType == "ssh" {
assembledURL := fmt.Sprintf("git@%s:%s.git", s.originalHostname, repo.NameWithOwner)
return assembledURL
}
return repo.URL
}
func (s *GitHubSource) excludes(r *github.Repository) bool {
if r.IsLocked || r.IsDisabled {
return true
}
if s.exclude(r.NameWithOwner) || s.exclude(r.ID) || s.exclude(*r) {
return true
}
return false
}
// repositoryPager is a function that returns repositories on a given `page`.
// It also returns:
// - `hasNext` bool: if there is a next page
// - `cost` int: rate limit cost used to determine recommended wait before next call
// - `err` error: if something goes wrong
type repositoryPager func(page int) (repos []*github.Repository, hasNext bool, cost int, err error)
// paginate returns all the repositories from the given repositoryPager.
// It repeatedly calls `pager` with incrementing page count until it
// returns false for hasNext.
func (s *GitHubSource) paginate(ctx context.Context, results chan *githubResult, pager repositoryPager) {
hasNext := true
for page := 1; hasNext; page++ {
if err := ctx.Err(); err != nil {
results <- &githubResult{err: err}
return
}
var pageRepos []*github.Repository
var err error
pageRepos, hasNext, _, err = pager(page)
if err != nil {
results <- &githubResult{err: err}
return
}
for _, r := range pageRepos {
if err := ctx.Err(); err != nil {
results <- &githubResult{err: err}
return
}
results <- &githubResult{repo: r}
}
}
}
// listOrg handles the `org` config option.
// It returns all the repositories belonging to the given organization
// by hitting the /orgs/:org/repos endpoint.
//
// It returns an error if the request fails on the first page.
func (s *GitHubSource) listOrg(ctx context.Context, org string, results chan *githubResult) {
dedupC := make(chan *githubResult)
// Currently, the Github API doesn't return internal repos
// when calling it with the "all" type.
// We need to call it twice, once with the "all" type and
// once with the "internal" type.
// However, since we don't have any guarantee that this behavior
// will always remain the same and that Github will never fix this issue,
// we need to deduplicate the results before sending them to the results channel.
getReposByType := func(tp string) error {
var oerr error
s.paginate(ctx, dedupC, func(page int) (repos []*github.Repository, hasNext bool, cost int, err error) {
defer func() {
if page == 1 {
var e *github.APIError
if errors.As(err, &e) && e.Code == 404 {
oerr = errors.Errorf("organisation %q (specified in configuration) not found", org)
err = nil
}
}
remaining, reset, retry, _ := s.v3Client.ExternalRateLimiter().Get()
s.logger.Debug(
"github sync: ListOrgRepositories",
log.Int("repos", len(repos)),
log.Int("rateLimitCost", cost),
log.Int("rateLimitRemaining", remaining),
log.Duration("rateLimitReset", reset),
log.Duration("retryAfter", retry),
log.String("type", tp),
)
}()
return s.v3Client.ListOrgRepositories(ctx, org, page, tp)
})
return oerr
}
go func() {
defer close(dedupC)
err := getReposByType("all")
// Handle 404 from org repos endpoint by trying user repos endpoint
if err != nil && ctx.Err() == nil {
if s.listUser(ctx, org, dedupC) != nil {
dedupC <- &githubResult{err: err}
}
return
}
if err := ctx.Err(); err != nil {
dedupC <- &githubResult{err: err}
return
}
// if the first call succeeded,
// call the same endpoint with the "internal" type
if err = getReposByType("internal"); err != nil {
dedupC <- &githubResult{err: err}
}
}()
seen := make(map[string]bool)
for res := range dedupC {
if res.err == nil {
if seen[res.repo.ID] {
continue
}
seen[res.repo.ID] = true
}
results <- res
}
}
// listUser returns all the repositories belonging to the given user
// by hitting the /users/:user/repos endpoint.
//
// It returns an error if the request fails on the first page.
func (s *GitHubSource) listUser(ctx context.Context, user string, results chan *githubResult) (fail error) {
s.paginate(ctx, results, func(page int) (repos []*github.Repository, hasNext bool, cost int, err error) {
defer func() {
if err != nil && page == 1 {
fail, err = err, nil
}
remaining, reset, retry, _ := s.v3Client.ExternalRateLimiter().Get()
s.logger.Debug(
"github sync: ListUserRepositories",
log.Int("repos", len(repos)),
log.Int("rateLimitCost", cost),
log.Int("rateLimitRemaining", remaining),
log.Duration("rateLimitReset", reset),
log.Duration("retryAfter", retry),
)
}()
return s.v3Client.ListUserRepositories(ctx, user, page)
})
return
}
// listAppInstallation returns all the repositories belonging to the authenticated GitHub App installation
// by hitting the /installation/repositories endpoint.
//
// It returns an error if the request fails on the first page.
func (s *GitHubSource) listAppInstallation(ctx context.Context, results chan *githubResult) (fail error) {
s.paginate(ctx, results, func(page int) (repos []*github.Repository, hasNext bool, cost int, err error) {
defer func() {
if err != nil && page == 1 {
fail, err = err, nil
}
remaining, reset, retry, _ := s.v3Client.ExternalRateLimiter().Get()
s.logger.Debug(
"github sync: ListInstallationRepositories",
log.Int("repos", len(repos)),
log.Int("rateLimitCost", cost),
log.Int("rateLimitRemaining", remaining),
log.Duration("rateLimitReset", reset),
log.Duration("retryAfter", retry),
)
}()
return s.v3Client.ListInstallationRepositories(ctx, page)
})
return
}
// listRepos returns the valid repositories from the given list of repository names.
// This is done by hitting the /repos/:owner/:name endpoint for each of the given
// repository names.
func (s *GitHubSource) listRepos(ctx context.Context, repos []string, results chan *githubResult) {
if err := s.fetchAllRepositoriesInBatches(ctx, results); err == nil {
return
} else {
if err := ctx.Err(); err != nil {
return
}
// The way we fetch repositories in batches through the GraphQL API -
// using aliases to query multiple repositories in one query - is
// currently "undefined behaviour". Very rarely but unreproducibly it
// resulted in EOF errors while testing. And since we rely on fetching
// to work, we fall back to the (slower) sequential fetching in case we
// run into an GraphQL API error
s.logger.Warn("github sync: fetching in batches failed, falling back to sequential fetch", log.Error(err))
}
// Admins normally add to end of lists, so end of list most likely has new
// repos => stream them first.
for i := len(repos) - 1; i >= 0; i-- {
nameWithOwner := repos[i]
if err := ctx.Err(); err != nil {
results <- &githubResult{err: errors.Wrapf(err, "context error for repository: namewithOwner=%s", nameWithOwner)}
return
}
owner, name, err := github.SplitRepositoryNameWithOwner(nameWithOwner)
if err != nil {
results <- &githubResult{err: errors.Newf("Invalid GitHub repository: nameWithOwner=%s", nameWithOwner)}
return
}
var repo *github.Repository
repo, err = s.v3Client.GetRepository(ctx, owner, name)
if err != nil {
// TODO(tsenart): When implementing dry-run, reconsider alternatives to return
// 404 errors on external service config validation.
if github.IsNotFound(err) {
s.logger.Warn("skipping missing github.repos entry:", log.String("name", nameWithOwner), log.Error(err))
} else {
results <- &githubResult{err: errors.Wrapf(err, "Error getting GitHub repository: nameWithOwner=%s", nameWithOwner)}
}
continue
}
s.logger.Debug("github sync: GetRepository", log.String("repo", repo.NameWithOwner))
results <- &githubResult{repo: repo}
}
}
// listPublic handles the `public` keyword of the `repositoryQuery` config option.
// It returns the public repositories listed on the /repositories endpoint.
func (s *GitHubSource) listPublic(ctx context.Context, results chan *githubResult) {
if s.githubDotCom {
results <- &githubResult{err: errors.New(`unsupported configuration "public" for "repositoryQuery" for github.com`)}
return
}
// The regular Github API endpoint for listing public repos doesn't return whether the repo is archived, so we have to list
// all of the public archived repos first so we know if a repo is archived or not.
// TODO: Remove querying for archived repos first when https://github.com/orgs/community/discussions/12554 gets resolved
archivedReposChan := make(chan *githubResult)
archivedRepos := make(map[string]struct{})
archivedReposCtx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
s.listPublicArchivedRepos(archivedReposCtx, archivedReposChan)
close(archivedReposChan)
}()
for res := range archivedReposChan {
if res.err != nil {
results <- &githubResult{err: errors.Wrap(res.err, "failed to list public archived Github repositories")}
return
}
archivedRepos[res.repo.ID] = struct{}{}
}
var sinceRepoID int64
for {
if err := ctx.Err(); err != nil {
results <- &githubResult{err: err}
return
}
repos, hasNextPage, err := s.v3Client.ListPublicRepositories(ctx, sinceRepoID)
if err != nil {
apiError := &github.APIError{}
// If the error is a http.StatusNotFound, we have paginated past the last page
if errors.As(err, &apiError) && apiError.Code == http.StatusNotFound {
return
}
results <- &githubResult{err: errors.Wrapf(err, "failed to list public repositories: sinceRepoID=%d", sinceRepoID)}
return
}
if !hasNextPage {
return
}
s.logger.Debug("github sync public", log.Int("repos", len(repos)), log.Error(err))
for _, r := range repos {
_, isArchived := archivedRepos[r.ID]
r.IsArchived = isArchived
if err := ctx.Err(); err != nil {
results <- &githubResult{err: err}
return
}
results <- &githubResult{repo: r}
if sinceRepoID < r.DatabaseID {
sinceRepoID = r.DatabaseID
}
}
}
}
// listPublicArchivedRepos returns all of the public archived repositories listed on the /search/repositories endpoint.
// NOTE: There is a limitation on the search API that this uses, if there are more than 1000 public archived repos that
// were created in the same time (to the second), this list will miss any repos that lie outside of the first 1000.
func (s *GitHubSource) listPublicArchivedRepos(ctx context.Context, results chan *githubResult) {
s.listSearch(ctx, "archived:true is:public", results)
}
// listAffiliated handles the `affiliated` keyword of the `repositoryQuery` config option.
// It returns the repositories affiliated with the client token by hitting the /user/repos
// endpoint.
//
// Affiliation is present if the user: (1) owns the repo, (2) is a part of an org that
// the repo belongs to, or (3) is a collaborator.
func (s *GitHubSource) listAffiliated(ctx context.Context, results chan *githubResult) {
s.paginate(ctx, results, func(page int) (repos []*github.Repository, hasNext bool, cost int, err error) {
defer func() {
remaining, reset, retry, _ := s.v3Client.ExternalRateLimiter().Get()
s.logger.Debug(
"github sync: ListAffiliated",
log.Int("repos", len(repos)),
log.Int("rateLimitCost", cost),
log.Int("rateLimitRemaining", remaining),
log.Duration("rateLimitReset", reset),
log.Duration("retryAfter", retry),
)
}()
return s.v3Client.ListAffiliatedRepositories(ctx, github.VisibilityAll, page, 100)
})
}
func (s *GitHubSource) listAffiliatedPage(ctx context.Context, first int, results chan *githubResult) {
repos, _, _, err := s.v3Client.ListAffiliatedRepositories(ctx, github.VisibilityAll, 0, first)
if err != nil {
results <- &githubResult{err: err}
return
}
for _, r := range repos {
if err := ctx.Err(); err != nil {
results <- &githubResult{err: err}
return
}
results <- &githubResult{repo: r}
}
}
// listSearch handles the `repositoryQuery` config option when a keyword is not present.
// It returns the repositories matching a GitHub's advanced repository search query
// via the GraphQL API.
func (s *GitHubSource) listSearch(ctx context.Context, q string, results chan *githubResult) {
newRepositoryQuery(q, s.v4Client, s.logger).DoWithRefinedWindow(ctx, results)
}
// GitHub was founded on February 2008, so this minimum date covers all repos
// created on it.
var minCreated = time.Date(2007, time.June, 1, 0, 0, 0, 0, time.UTC)
type dateRange struct{ From, To time.Time }
var createdRegexp = regexp.MustCompile(`created:([^\s]+)`) // Matches the term "created:" followed by all non-white-space text
// stripDateRange strips the `created:` filter from the given string (modifying it in place)
// and returns a pointer to the resulting dateRange object.
// If no dateRange could be parsed from the string, nil is returned and the string is left unchanged.
func stripDateRange(s *string) *dateRange {
matches := createdRegexp.FindStringSubmatch(*s)
if len(matches) < 2 {
return nil
}
dateStr := matches[1]
parseDate := func(dateStr string, untilEndOfDay bool) (time.Time, error) {
if strings.Contains(dateStr, "T") {
if strings.Contains(dateStr, "+") || strings.Contains(dateStr, "Z") {
return time.Parse(time.RFC3339, dateStr)
}
return time.Parse("2006-01-02T15:04:05", dateStr)
}
t, err := time.Parse("2006-01-02", dateStr)
if err != nil {
return t, err
}
// If we need to match until the end of the day, the time should be 23:59:59
// This only applies if no time was specified
if untilEndOfDay {
t = t.Add(24 * time.Hour).Add(-1 * time.Second)
}
return t, err
}
var fromDateStr, toDateStr string
var fromTimeAdd, toTimeAdd time.Duration // Time to add to the respective dates in case of exclusive bounds
var toEndOfDay bool // Whether or not the "To" date should include the entire day (for inclusive bounds checks)
switch {
case strings.HasPrefix(dateStr, ">="):
fromDateStr = dateStr[2:]
case strings.HasPrefix(dateStr, ">"):
fromDateStr = dateStr[1:]
fromTimeAdd = 1 * time.Second
case strings.HasPrefix(dateStr, "<="):
toDateStr = dateStr[2:]
toEndOfDay = true
case strings.HasPrefix(dateStr, "<"):
toDateStr = dateStr[1:]
toTimeAdd = -1 * time.Second
default:
rangeParts := strings.Split(dateStr, "..")
if len(rangeParts) != 2 {
return nil
}
fromDateStr = rangeParts[0]
toDateStr = rangeParts[1]
if toDateStr != "*" {
toEndOfDay = true
}
}
var err error
dr := &dateRange{}
if fromDateStr != "" && fromDateStr != "*" {
dr.From, err = parseDate(fromDateStr, false)
if err != nil {
return nil
}
dr.From = dr.From.Add(fromTimeAdd)
}
if toDateStr != "" && toDateStr != "*" {
dr.To, err = parseDate(toDateStr, toEndOfDay)
if err != nil {
return nil
}
dr.To = dr.To.Add(toTimeAdd)
}
*s = strings.ReplaceAll(*s, matches[0], "")
return dr
}
func (r dateRange) String() string {
const dateFormat = "2006-01-02T15:04:05-07:00"
return fmt.Sprintf("%s..%s",
r.From.Format(dateFormat),
r.To.Format(dateFormat),
)
}
func (r dateRange) Size() time.Duration { return r.To.Sub(r.From) }
type searchReposCount struct {
known bool
count int
}
type repositoryQuery struct {
Query string
Created *dateRange
Cursor github.Cursor
First int
Limit int
Searcher *github.V4Client
Logger log.Logger
RepoCount searchReposCount
}
func newRepositoryQuery(query string, searcher *github.V4Client, logger log.Logger) *repositoryQuery {
// First we need to parse the query to see if it is querying within a date range,
// and if so, strip that date range from the query.
dr := stripDateRange(&query)
if dr == nil {
dr = &dateRange{}
}
if dr.From.IsZero() {
dr.From = minCreated
}
if dr.To.IsZero() {
dr.To = time.Now()
}
return &repositoryQuery{
Query: query,
Searcher: searcher,
Logger: logger,
Created: dr,
}
}
// DoWithRefinedWindow attempts to retrieve all matching repositories by refining the window of acceptable Created dates
// to smaller windows and re-running the search (down to a minimum window size)
// and exiting once all repositories are returned.
func (q *repositoryQuery) DoWithRefinedWindow(ctx context.Context, results chan *githubResult) {
if q.First == 0 {
q.First = 100
}
if q.Limit == 0 {
// GitHub's search API returns a maximum of 1000 results
q.Limit = 1000
}
if q.Created == nil {
q.Created = &dateRange{
From: minCreated,
To: time.Now(),
}
}
if err := q.doRecursively(ctx, results); err != nil {
select {
case <-ctx.Done():
case results <- &githubResult{err: errors.Wrapf(err, "failed to search GitHub repositories with %q", q)}:
}
}
}
// DoSingleRequest accepts the first n results and does not refine the search window on Created date.
// Missing some repositories which match the criteria is acceptable.
func (q *repositoryQuery) DoSingleRequest(ctx context.Context, results chan *githubResult) {
if q.First == 0 {
q.First = 100
}
if err := ctx.Err(); err != nil {
results <- &githubResult{err: err}
}
res, err := q.Searcher.SearchRepos(ctx, github.SearchReposParams{
Query: q.String(),
First: q.First,
After: q.Cursor,
})
if err != nil {
select {
case <-ctx.Done():
case results <- &githubResult{err: errors.Wrapf(err, "failed to search GitHub repositories with %q", q)}:
}
}
for i := range res.Repos {
out:
select {
case <-ctx.Done():
break out
case results <- &githubResult{repo: &res.Repos[i]}:
}
}
}
func (q *repositoryQuery) split(ctx context.Context, results chan *githubResult) error {
middle := q.Created.From.Add(q.Created.To.Sub(q.Created.From) / 2)
q1, q2 := *q, *q
q1.RepoCount.known = false
q1.Created = &dateRange{
From: q.Created.From,
To: middle.Add(-1 * time.Second),
}
q2.Created = &dateRange{
From: middle,
To: q.Created.To,
}
if err := q1.doRecursively(ctx, results); err != nil {
return err
}
// We now know the repoCount of q2 by subtracting the repoCount of q1 from the original q
q2.RepoCount = searchReposCount{
known: true,
count: q.RepoCount.count - q1.RepoCount.count,
}