-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdsgithub.go
5661 lines (5580 loc) · 170 KB
/
dsgithub.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package dads
import (
"context"
"fmt"
"io/ioutil"
"math/rand"
"os"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/google/go-github/v38/github"
jsoniter "github.com/json-iterator/go"
"golang.org/x/oauth2"
)
const (
// GitHubBackendVersion - backend version
GitHubBackendVersion = "0.1.0"
// GitHubURLRoot - GitHub URL root
GitHubURLRoot = "https://github.com/"
// MaxGitHubUsersFileCacheAge 90 days (in seconds) - file is considered too old anywhere between 90-180 days
MaxGitHubUsersFileCacheAge = 7776000
// MaxCommentBodyLength - max comment body length
MaxCommentBodyLength = 4096
// MaxIssueBodyLength - max issue body length
MaxIssueBodyLength = 4096
// MaxPullBodyLength - max pull request body length
MaxPullBodyLength = 4096
// MaxReviewBodyLength - max review body length
MaxReviewBodyLength = 4096
// MaxReviewCommentBodyLength - max review comment body length
MaxReviewCommentBodyLength = 4096
// ItemsPerPage - how many items in a page
ItemsPerPage = 100
// AbuseWaitSeconds - N - wait random(N:2N) seconds if GitHub detected abuse
// 7 means from 7 to 13 seconds, 10 on average
AbuseWaitSeconds = 7
// CacheGitHubRepo - cache this?
CacheGitHubRepo = true
// CacheGitHubIssues - cache this?
CacheGitHubIssues = false
// CacheGitHubUser - cache this?
CacheGitHubUser = true
// CacheGitHubUserFiles - cache this in files?
CacheGitHubUserFiles = true
// CacheGitHubIssueComments - cache this?
CacheGitHubIssueComments = false
// CacheGitHubCommentReactions - cache this?
CacheGitHubCommentReactions = false
// CacheGitHubIssueReactions - cache this?
CacheGitHubIssueReactions = false
// CacheGitHubPull - cache this?
CacheGitHubPull = false
// CacheGitHubPulls - cache this?
CacheGitHubPulls = false
// CacheGitHubPullReviews - cache this?
CacheGitHubPullReviews = false
// CacheGitHubPullReviewComments - cache this?
CacheGitHubPullReviewComments = false
// CacheGitHubReviewCommentReactions - cache this?
CacheGitHubReviewCommentReactions = false
// CacheGitHubPullRequestedReviewers - cache this?
CacheGitHubPullRequestedReviewers = false
// CacheGitHubPullCommits - cache this?
CacheGitHubPullCommits = false
// CacheGitHubUserOrgs - cache this?
CacheGitHubUserOrgs = true
// WantEnrichIssueAssignees - do we want to create rich documents for issue assignees (it contains identity data too).
WantEnrichIssueAssignees = true
// WantEnrichIssueCommentReactions - do we want to create rich documents for issue comment reactions (it contains identity data too).
WantEnrichIssueCommentReactions = true
// WantEnrichIssueReactions - do we want to create rich documents for issue reactions (it contains identity data too).
WantEnrichIssueReactions = true
// WantEnrichPullRequestAssignees - do we want to create rich documents for pull request assignees (it contains identity data too).
WantEnrichPullRequestAssignees = true
// WantEnrichPullRequestCommentReactions - do we want to create rich documents for pull request comment reactions (it contains identity data too).
WantEnrichPullRequestCommentReactions = true
// WantEnrichPullRequestRequestedReviewers - do we want to create rich documents for pull request requested reviewers (it contains identity data too).
WantEnrichPullRequestRequestedReviewers = true
)
var (
// GitHubRawMapping - GitHub raw index mapping
// GitHubRawMapping = []byte(`{"properties":{"metadata__updated_on":{"type":"date"}}}`)
GitHubRawMapping = []byte(`{"dynamic":true,"properties":{"metadata__updated_on":{"type":"date","format":"strict_date_optional_time||epoch_millis"},"data":{"properties":{"comments_data":{"dynamic":false,"properties":{"body":{"type":"text","index":true}}},"review_comments_data":{"dynamic":false,"properties":{"body":{"type":"text","index":true},"diff_hunk":{"type":"text","index":true}}},"reviews_data":{"dynamic":false,"properties":{"body":{"type":"text","index":true}}},"body":{"type":"text","index":true}}}}}`)
// GitHubRichMapping - GitHub rich index mapping
// GitHubRichMapping = []byte(`{"properties":{"metadata__updated_on":{"type":"date"},"merge_author_geolocation":{"type":"geo_point"},"assignee_geolocation":{"type":"geo_point"},"state":{"type":"keyword"},"user_geolocation":{"type":"geo_point"},"title_analyzed":{"type":"text","index":true}}}`)
// GitHubRichMapping = []byte(`{"dynamic":true,"properties":{"metadata__updated_on":{"type":"date","format":"strict_date_optional_time||epoch_millis"},"merge_author_geolocation":{"type":"geo_point"},"assignee_geolocation":{"type":"geo_point"},"id_in_repo":{"type":"long"},"state":{"type":"keyword"},"user_geolocation":{"type":"geo_point"},"title_analyzed":{"type":"text","index":true},"body_analyzed":{"type":"text","index":true},"code_merge_duration":{"type":"float"},"time_open_days":{"type":"float"},"time_to_close_days":{"type":"float"},"time_to_first_attention":{"type":"float"},"time_to_merge_request_response":{"type":"float"},"id_in_repo":{"type":"long"}},"dynamic_templates":[{"notanalyzed":{"match":"*","unmatch":"body","match_mapping_type":"string","mapping":{"type":"keyword"}}},{"formatdate":{"match":"*","match_mapping_type":"date","mapping":{"format":"strict_date_optional_time||epoch_millis","type":"date"}}}]}`)
GitHubRichMapping = []byte(`{"dynamic":true,"properties":{"metadata__updated_on":{"type":"date","format":"strict_date_optional_time||epoch_millis"},"merge_author_geolocation":{"type":"geo_point"},"assignee_geolocation":{"type":"geo_point"},"state":{"type":"keyword"},"user_geolocation":{"type":"geo_point"},"title_analyzed":{"type":"text","index":true},"body_analyzed":{"type":"text","index":true},"code_merge_duration":{"type":"float"},"time_open_days":{"type":"float"},"time_to_close_days":{"type":"float"},"time_to_first_attention":{"type":"float"},"time_to_merge_request_response":{"type":"float"},"id_in_repo":{"type":"long"}},"dynamic_templates":[{"notanalyzed":{"match":"*","unmatch":"body","match_mapping_type":"string","mapping":{"type":"keyword"}}},{"formatdate":{"match":"*","match_mapping_type":"date","mapping":{"format":"strict_date_optional_time||epoch_millis","type":"date"}}}]}`)
// GitHubCategories - categories defined for GitHub
GitHubCategories = map[string]struct{}{"issue": {}, "pull_request": {}, "repository": {}}
// GitHubIssueRoles - roles to fetch affiliation data for github issue
GitHubIssueRoles = []string{"user_data", "assignee_data"}
// GitHubIssueCommentRoles - roles to fetch affiliation data for github issue comment
GitHubIssueCommentRoles = []string{"user_data"}
// GitHubIssueAssigneeRoles - roles to fetch affiliation data for github issue comment
GitHubIssueAssigneeRoles = []string{"assignee"}
// GitHubIssueReactionRoles - roles to fetch affiliation data for github issue reactions or issue comment reactions
GitHubIssueReactionRoles = []string{"user_data"}
// GitHubPullRequestRoles - roles to fetch affiliation data for github pull request
GitHubPullRequestRoles = []string{"user_data", "assignee_data", "merged_by_data"}
// GitHubPullRequestCommentRoles - roles to fetch affiliation data for github pull request comment
GitHubPullRequestCommentRoles = []string{"user_data"}
// GitHubPullRequestAssigneeRoles - roles to fetch affiliation data for github pull request comment
GitHubPullRequestAssigneeRoles = []string{"assignee"}
// GitHubPullRequestReactionRoles - roles to fetch affiliation data for github pull request comment reactions
GitHubPullRequestReactionRoles = []string{"user_data"}
// GitHubPullRequestRequestedReviewerRoles - roles to fetch affiliation data for github pull request requested reviewer
GitHubPullRequestRequestedReviewerRoles = []string{"requested_reviewer"}
// GitHubPullRequestReviewRoles - roles to fetch affiliation data for github pull request comment
GitHubPullRequestReviewRoles = []string{"user_data"}
)
// DSGitHub - DS implementation for GitHub
type DSGitHub struct {
DS string // From DA_DS - data source type "github"
Org string // From DA_GITHUB_ORG - github org
Repo string // From DA_GITHUB_REPO - github repo
Category string // From DA_GITHUB_CATEGORY - issue, pull_request, repository
Tokens string // From DA_GITHUB_TOKENS - "," separated list of OAuth tokens
URL string
Clients []*github.Client
Context context.Context
OAuthKeys []string
ThrN int
Hint int
RateHandled bool
CanCache bool
CacheDir string
GitHubMtx *sync.RWMutex
GitHubRepoMtx *sync.RWMutex
GitHubIssuesMtx *sync.RWMutex
GitHubUserMtx *sync.RWMutex
GitHubIssueCommentsMtx *sync.RWMutex
GitHubCommentReactionsMtx *sync.RWMutex
GitHubIssueReactionsMtx *sync.RWMutex
GitHubPullMtx *sync.RWMutex
GitHubPullsMtx *sync.RWMutex
GitHubPullReviewsMtx *sync.RWMutex
GitHubPullReviewCommentsMtx *sync.RWMutex
GitHubReviewCommentReactionsMtx *sync.RWMutex
GitHubPullRequestedReviewersMtx *sync.RWMutex
GitHubPullCommitsMtx *sync.RWMutex
GitHubUserOrgsMtx *sync.RWMutex
GitHubRateMtx *sync.RWMutex
GitHubRepo map[string]map[string]interface{}
GitHubIssues map[string][]map[string]interface{}
GitHubUser map[string]map[string]interface{}
GitHubIssueComments map[string][]map[string]interface{}
GitHubCommentReactions map[string][]map[string]interface{}
GitHubIssueReactions map[string][]map[string]interface{}
GitHubPull map[string]map[string]interface{}
GitHubPulls map[string][]map[string]interface{}
GitHubPullReviews map[string][]map[string]interface{}
GitHubPullReviewComments map[string][]map[string]interface{}
GitHubReviewCommentReactions map[string][]map[string]interface{}
GitHubPullRequestedReviewers map[string][]map[string]interface{}
GitHubPullCommits map[string][]map[string]interface{}
GitHubUserOrgs map[string][]map[string]interface{}
}
func (j *DSGitHub) getRateLimits(gctx context.Context, ctx *Ctx, gcs []*github.Client, core bool) (int, []int, []int, []time.Duration) {
var (
limits []int
remainings []int
durations []time.Duration
)
display := false
for idx, gc := range gcs {
rl, _, err := gc.RateLimits(gctx)
if err != nil {
rem, ok := PeriodParse(err.Error())
if ok {
Printf("Parsed wait time from api non-success response message: %v: %s\n", rem, err.Error())
limits = append(limits, -1)
remainings = append(remainings, -1)
durations = append(durations, rem)
display = true
continue
}
Printf("GetRateLimit(%d): %v\n", idx, err)
}
if rl == nil {
limits = append(limits, -1)
remainings = append(remainings, -1)
durations = append(durations, time.Duration(5)*time.Second)
continue
}
if core {
limits = append(limits, rl.Core.Limit)
remainings = append(remainings, rl.Core.Remaining)
durations = append(durations, rl.Core.Reset.Time.Sub(time.Now())+time.Duration(1)*time.Second)
continue
}
limits = append(limits, rl.Search.Limit)
remainings = append(remainings, rl.Search.Remaining)
durations = append(durations, rl.Search.Reset.Time.Sub(time.Now())+time.Duration(1)*time.Second)
}
hint := 0
for idx := range limits {
if remainings[idx] > remainings[hint] {
hint = idx
} else if idx != hint && remainings[idx] == remainings[hint] && durations[idx] < durations[hint] {
hint = idx
}
}
if display || ctx.Debug > 0 {
Printf("GetRateLimits: hint: %d, limits: %+v, remaining: %+v, reset: %+v\n", hint, limits, remainings, durations)
}
return hint, limits, remainings, durations
}
func (j *DSGitHub) handleRate(ctx *Ctx) (aHint int, canCache bool) {
if j.GitHubRateMtx != nil {
j.GitHubRateMtx.RLock()
}
handled := j.RateHandled
if handled {
aHint = j.Hint
canCache = j.CanCache
}
if j.GitHubRateMtx != nil {
j.GitHubRateMtx.RUnlock()
}
if handled {
Printf("%s/%s: rate is already handled elsewhere, returning #%d token\n", j.URL, j.Category, aHint)
return
}
if j.GitHubRateMtx != nil {
j.GitHubRateMtx.Lock()
defer j.GitHubRateMtx.Unlock()
}
h, _, rem, wait := j.getRateLimits(j.Context, ctx, j.Clients, true)
for {
if ctx.Debug > 1 {
Printf("Checking token %d %+v %+v\n", h, rem, wait)
}
if rem[h] <= 5 {
Printf("All GH API tokens are overloaded, maximum points %d, waiting %+v\n", rem[h], wait[h])
time.Sleep(time.Duration(1) * time.Second)
time.Sleep(wait[h])
h, _, rem, wait = j.getRateLimits(j.Context, ctx, j.Clients, true)
continue
}
if rem[h] >= 500 {
canCache = true
}
break
}
aHint = h
j.Hint = aHint
j.CanCache = canCache
if ctx.Debug > 1 {
Printf("Found usable token %d/%d/%v, cache enabled: %v\n", aHint, rem[h], wait[h], canCache)
}
j.RateHandled = true
Printf("%s/%s: selected new token #%d\n", j.URL, j.Category, j.Hint)
return
}
func (j *DSGitHub) isAbuse(e error) (abuse, rateLimit bool) {
if e == nil {
return
}
defer func() {
// if abuse || rateLimit {
// Clear rate handled flag on every error - chances are that next rate handle will recover
Printf("%s/%s: GitHub error: abuse:%v, rate limit:%v\n", j.URL, j.Category, abuse, rateLimit)
if e != nil {
if j.GitHubRateMtx != nil {
j.GitHubRateMtx.Lock()
}
j.RateHandled = false
if j.GitHubRateMtx != nil {
j.GitHubRateMtx.Unlock()
}
}
}()
errStr := e.Error()
// GitHub can return '401 Bad credentials' when token(s) was/were revoken
// abuse = strings.Contains(errStr, "403 You have triggered an abuse detection mechanism") || strings.Contains(errStr, "401 Bad credentials")
abuse = strings.Contains(errStr, "403 You have triggered an abuse detection mechanism")
rateLimit = strings.Contains(errStr, "403 API rate limit")
return
}
func (j *DSGitHub) githubRepo(ctx *Ctx, org, repo string) (repoData map[string]interface{}, err error) {
var found bool
origin := org + "/" + repo
// Try memory cache 1st
if CacheGitHubRepo {
if j.GitHubRepoMtx != nil {
j.GitHubRepoMtx.RLock()
}
repoData, found = j.GitHubRepo[origin]
if j.GitHubRepoMtx != nil {
j.GitHubRepoMtx.RUnlock()
}
if found {
if ctx.Debug > 2 {
Printf("repos found in cache: %+v\n", repoData)
}
return
}
}
var c *github.Client
if j.GitHubMtx != nil {
j.GitHubMtx.RLock()
}
c = j.Clients[j.Hint]
if j.GitHubMtx != nil {
j.GitHubMtx.RUnlock()
}
retry := false
for {
var (
response *github.Response
rep *github.Repository
e error
)
rep, response, e = c.Repositories.Get(j.Context, org, repo)
if ctx.Debug > 2 {
Printf("GET %s/%s -> {%+v, %+v, %+v}\n", org, repo, rep, response, e)
}
if e != nil && strings.Contains(e.Error(), "404 Not Found") {
if CacheGitHubRepo {
if j.GitHubRepoMtx != nil {
j.GitHubRepoMtx.Lock()
}
j.GitHubRepo[origin] = nil
if j.GitHubRepoMtx != nil {
j.GitHubRepoMtx.Unlock()
}
}
if ctx.Debug > 1 {
Printf("githubRepos: repo not found %s: %v\n", origin, e)
}
return
}
if e != nil && !retry {
Printf("Unable to get %s repo: response: %+v, because: %+v, retrying rate\n", origin, response, e)
Printf("githubRepos: handle rate\n")
abuse, rateLimit := j.isAbuse(e)
if abuse {
sleepFor := AbuseWaitSeconds + rand.Intn(AbuseWaitSeconds)
Printf("GitHub detected abuse (get repo %s), waiting for %ds\n", origin, sleepFor)
time.Sleep(time.Duration(sleepFor) * time.Second)
}
if rateLimit {
Printf("Rate limit reached on a token (get repo %s) waiting 1s before token switch\n", origin)
time.Sleep(time.Duration(1) * time.Second)
}
if j.GitHubMtx != nil {
j.GitHubMtx.Lock()
}
j.Hint, _ = j.handleRate(ctx)
c = j.Clients[j.Hint]
if j.GitHubMtx != nil {
j.GitHubMtx.Unlock()
}
if !abuse && !rateLimit {
retry = true
}
continue
}
if e != nil {
err = e
return
}
jm, _ := jsoniter.Marshal(rep)
_ = jsoniter.Unmarshal(jm, &repoData)
if ctx.Debug > 2 {
Printf("repos got from API: %+v\n", repoData)
}
break
}
if CacheGitHubRepo {
if j.GitHubRepoMtx != nil {
j.GitHubRepoMtx.Lock()
}
j.GitHubRepo[origin] = repoData
if j.GitHubRepoMtx != nil {
j.GitHubRepoMtx.Unlock()
}
}
return
}
func (j *DSGitHub) githubUser(ctx *Ctx, login string) (user map[string]interface{}, found bool, err error) {
var ok bool
// Try memory cache 1st
if CacheGitHubUser {
if j.GitHubUserMtx != nil {
j.GitHubUserMtx.RLock()
}
user, ok = j.GitHubUser[login]
if j.GitHubUserMtx != nil {
j.GitHubUserMtx.RUnlock()
}
if ok {
found = len(user) > 0
if ctx.Debug > 1 {
Printf("user found in memory cache: %+v\n", user)
}
return
}
// Try file cache 2nd
if CacheGitHubUserFiles {
path := j.CacheDir + login + ".json"
lockPath := path + ".lock"
file, e := os.Stat(path)
if e == nil {
for {
waited := 0
_, e := os.Stat(lockPath)
if e == nil {
if ctx.Debug > 0 {
Printf("user %s lock file %s present, waiting 1s\n", user, lockPath)
}
time.Sleep(time.Duration(1) * time.Second)
waited++
continue
}
if waited > 0 {
if ctx.Debug > 0 {
Printf("user %s lock file %s was present, waited %ds\n", user, lockPath, waited)
}
}
file, _ = os.Stat(path)
break
}
modified := file.ModTime()
age := int(time.Now().Sub(modified).Seconds())
allowedAge := MaxGitHubUsersFileCacheAge + rand.Intn(MaxGitHubUsersFileCacheAge)
if age <= allowedAge {
bts, e := ioutil.ReadFile(path)
if e == nil {
e = jsoniter.Unmarshal(bts, &user)
bts = nil
if e == nil {
found = len(user) > 0
if found {
if j.GitHubUserMtx != nil {
j.GitHubUserMtx.Lock()
}
j.GitHubUser[login] = user
if j.GitHubUserMtx != nil {
j.GitHubUserMtx.Unlock()
}
if ctx.Debug > 1 {
Printf("user found in files cache: %+v\n", user)
}
return
}
Printf("githubUser: unmarshaled %s cache file is empty\n", path)
}
Printf("githubUser: cannot unmarshal %s cache file: %v\n", path, e)
} else {
Printf("githubUser: cannot read %s user cache file: %v\n", path, e)
}
} else {
Printf("githubUser: %s user cache file is too old: %v (allowed %v)\n", path, time.Duration(age)*time.Second, time.Duration(allowedAge)*time.Second)
}
} else {
if ctx.Debug > 1 {
Printf("githubUser: no %s user cache file: %v\n", path, e)
}
}
locked := false
lockFile, e := os.Create(lockPath)
if e != nil {
Printf("githubUser: create %s lock file failed: %v\n", lockPath, e)
} else {
locked = true
_ = lockFile.Close()
}
defer func() {
if locked {
defer func() {
if ctx.Debug > 1 {
Printf("remove lock file %s\n", lockPath)
}
_ = os.Remove(lockPath)
}()
}
if err != nil {
return
}
// path := j.CacheDir + login + ".json"
bts, err := jsoniter.Marshal(user)
if err != nil {
Printf("githubUser: cannot marshal user %s to file %s\n", login, path)
return
}
err = ioutil.WriteFile(path, bts, 0644)
if err != nil {
Printf("githubUser: cannot write file %s, %d bytes: %v\n", path, len(bts), err)
return
}
if ctx.Debug > 0 {
Printf("githubUser: saved %s user file\n", path)
}
}()
}
}
// Try GitHub API 3rd
var c *github.Client
if j.GitHubMtx != nil {
j.GitHubMtx.RLock()
}
c = j.Clients[j.Hint]
if j.GitHubMtx != nil {
j.GitHubMtx.RUnlock()
}
retry := false
for {
var (
response *github.Response
usr *github.User
e error
)
usr, response, e = c.Users.Get(j.Context, login)
if ctx.Debug > 2 {
Printf("GET %s -> {%+v, %+v, %+v}\n", login, usr, response, e)
}
if e != nil && strings.Contains(e.Error(), "404 Not Found") {
if CacheGitHubUser {
if j.GitHubUserMtx != nil {
j.GitHubUserMtx.Lock()
}
if ctx.Debug > 0 {
Printf("user not found using API: %s\n", login)
}
j.GitHubUser[login] = map[string]interface{}{}
if j.GitHubUserMtx != nil {
j.GitHubUserMtx.Unlock()
}
}
return
}
if e != nil && !retry {
Printf("Unable to get %s user: response: %+v, because: %+v, retrying rate\n", login, response, e)
Printf("githubUser: handle rate\n")
abuse, rateLimit := j.isAbuse(e)
if abuse {
sleepFor := AbuseWaitSeconds + rand.Intn(AbuseWaitSeconds)
Printf("GitHub detected abuse (get user %s), waiting for %ds\n", login, sleepFor)
time.Sleep(time.Duration(sleepFor) * time.Second)
}
if rateLimit {
Printf("Rate limit reached on a token (get user %s) waiting 1s before token switch\n", login)
time.Sleep(time.Duration(1) * time.Second)
}
if j.GitHubMtx != nil {
j.GitHubMtx.Lock()
}
j.Hint, _ = j.handleRate(ctx)
c = j.Clients[j.Hint]
if j.GitHubMtx != nil {
j.GitHubMtx.Unlock()
}
if !abuse && !rateLimit {
retry = true
}
continue
}
if e != nil {
err = e
return
}
if usr != nil {
jm, _ := jsoniter.Marshal(usr)
_ = jsoniter.Unmarshal(jm, &user)
user["organizations"], err = j.githubUserOrgs(ctx, login)
if err != nil {
return
}
if ctx.Debug > 1 {
Printf("user found using API: %+v\n", user)
}
found = true
}
break
}
if CacheGitHubUser {
if j.GitHubUserMtx != nil {
j.GitHubUserMtx.Lock()
}
j.GitHubUser[login] = user
if j.GitHubUserMtx != nil {
j.GitHubUserMtx.Unlock()
}
}
return
}
func (j *DSGitHub) githubIssues(ctx *Ctx, org, repo string, since *time.Time) (issuesData []map[string]interface{}, err error) {
var found bool
origin := org + "/" + repo
// Try memory cache 1st
if CacheGitHubIssues {
if j.GitHubIssuesMtx != nil {
j.GitHubIssuesMtx.RLock()
}
issuesData, found = j.GitHubIssues[origin]
if j.GitHubIssuesMtx != nil {
j.GitHubIssuesMtx.RUnlock()
}
if found {
if ctx.Debug > 2 {
Printf("issues found in cache: %+v\n", issuesData)
}
return
}
}
var c *github.Client
if j.GitHubMtx != nil {
j.GitHubMtx.RLock()
}
c = j.Clients[j.Hint]
if j.GitHubMtx != nil {
j.GitHubMtx.RUnlock()
}
opt := &github.IssueListByRepoOptions{
State: "all",
Sort: "updated",
Direction: "asc",
}
opt.PerPage = ItemsPerPage
if since != nil {
opt.Since = *since
}
retry := false
for {
var (
response *github.Response
issues []*github.Issue
e error
)
issues, response, e = c.Issues.ListByRepo(j.Context, org, repo, opt)
if ctx.Debug > 2 {
Printf("GET %s/%s -> {%+v, %+v, %+v}\n", org, repo, issues, response, e)
}
if e != nil && strings.Contains(e.Error(), "404 Not Found") {
if CacheGitHubIssues {
if j.GitHubIssuesMtx != nil {
j.GitHubIssuesMtx.Lock()
}
j.GitHubIssues[origin] = []map[string]interface{}{}
if j.GitHubIssuesMtx != nil {
j.GitHubIssuesMtx.Unlock()
}
}
if ctx.Debug > 1 {
Printf("githubIssues: issues not found %s: %v\n", origin, e)
}
return
}
if e != nil && !retry {
Printf("Unable to get %s issues: response: %+v, because: %+v, retrying rate\n", origin, response, e)
Printf("githubIssues: handle rate\n")
abuse, rateLimit := j.isAbuse(e)
if abuse {
sleepFor := AbuseWaitSeconds + rand.Intn(AbuseWaitSeconds)
Printf("GitHub detected abuse (get issues %s), waiting for %ds\n", origin, sleepFor)
time.Sleep(time.Duration(sleepFor) * time.Second)
}
if rateLimit {
Printf("Rate limit reached on a token (get issues %s) waiting 1s before token switch\n", origin)
time.Sleep(time.Duration(1) * time.Second)
}
if j.GitHubMtx != nil {
j.GitHubMtx.Lock()
}
j.Hint, _ = j.handleRate(ctx)
c = j.Clients[j.Hint]
if j.GitHubMtx != nil {
j.GitHubMtx.Unlock()
}
if !abuse && !rateLimit {
retry = true
}
continue
}
if e != nil {
err = e
return
}
for _, issue := range issues {
iss := map[string]interface{}{}
jm, _ := jsoniter.Marshal(issue)
_ = jsoniter.Unmarshal(jm, &iss)
body, ok := Dig(iss, []string{"body"}, false, true)
if ok {
nBody := len(body.(string))
if nBody > MaxIssueBodyLength {
iss["body"] = body.(string)[:MaxIssueBodyLength]
}
}
iss["body_analyzed"], _ = iss["body"]
iss["is_pull"] = issue.IsPullRequest()
issuesData = append(issuesData, iss)
}
if response.NextPage == 0 {
break
}
opt.Page = response.NextPage
if ctx.Debug > 0 {
runtime.GC()
Printf("%s/%s: processing next issues page: %d\n", j.URL, j.Category, opt.Page)
}
retry = false
}
if ctx.Debug > 2 {
Printf("issues got from API: %+v\n", issuesData)
}
if CacheGitHubIssues {
if j.GitHubIssuesMtx != nil {
j.GitHubIssuesMtx.Lock()
}
j.GitHubIssues[origin] = issuesData
if j.GitHubIssuesMtx != nil {
j.GitHubIssuesMtx.Unlock()
}
}
return
}
func (j *DSGitHub) githubIssueComments(ctx *Ctx, org, repo string, number int) (comments []map[string]interface{}, err error) {
var found bool
key := fmt.Sprintf("%s/%s/%d", org, repo, number)
// Try memory cache 1st
if CacheGitHubIssueComments {
if j.GitHubIssueCommentsMtx != nil {
j.GitHubIssueCommentsMtx.RLock()
}
comments, found = j.GitHubIssueComments[key]
if j.GitHubIssueCommentsMtx != nil {
j.GitHubIssueCommentsMtx.RUnlock()
}
if found {
if ctx.Debug > 2 {
Printf("issue comments found in cache: %+v\n", comments)
}
return
}
}
var c *github.Client
if j.GitHubMtx != nil {
j.GitHubMtx.RLock()
}
c = j.Clients[j.Hint]
if j.GitHubMtx != nil {
j.GitHubMtx.RUnlock()
}
opt := &github.IssueListCommentsOptions{}
opt.PerPage = ItemsPerPage
retry := false
for {
var (
response *github.Response
comms []*github.IssueComment
e error
)
comms, response, e = c.Issues.ListComments(j.Context, org, repo, number, opt)
if ctx.Debug > 2 {
Printf("GET %s/%s -> {%+v, %+v, %+v}\n", org, repo, comms, response, e)
}
if e != nil && strings.Contains(e.Error(), "404 Not Found") {
if CacheGitHubIssueComments {
if j.GitHubIssueCommentsMtx != nil {
j.GitHubIssueCommentsMtx.Lock()
}
j.GitHubIssueComments[key] = []map[string]interface{}{}
if j.GitHubIssueCommentsMtx != nil {
j.GitHubIssueCommentsMtx.Unlock()
}
}
if ctx.Debug > 1 {
Printf("githubIssueComments: comments not found %s: %v\n", key, e)
}
return
}
if e != nil && !retry {
Printf("Unable to get %s issue comments: response: %+v, because: %+v, retrying rate\n", key, response, e)
Printf("githubIssueComments: handle rate\n")
abuse, rateLimit := j.isAbuse(e)
if abuse {
sleepFor := AbuseWaitSeconds + rand.Intn(AbuseWaitSeconds)
Printf("GitHub detected abuse (get issue comments %s), waiting for %ds\n", key, sleepFor)
time.Sleep(time.Duration(sleepFor) * time.Second)
}
if rateLimit {
Printf("Rate limit reached on a token (get issue comments %s) waiting 1s before token switch\n", key)
time.Sleep(time.Duration(1) * time.Second)
}
if j.GitHubMtx != nil {
j.GitHubMtx.Lock()
}
j.Hint, _ = j.handleRate(ctx)
c = j.Clients[j.Hint]
if j.GitHubMtx != nil {
j.GitHubMtx.Unlock()
}
if !abuse && !rateLimit {
retry = true
}
continue
}
if e != nil {
err = e
return
}
for _, comment := range comms {
com := map[string]interface{}{}
jm, _ := jsoniter.Marshal(comment)
_ = jsoniter.Unmarshal(jm, &com)
body, ok := Dig(com, []string{"body"}, false, true)
if ok {
nBody := len(body.(string))
if nBody > MaxCommentBodyLength {
com["body"] = body.(string)[:MaxCommentBodyLength]
}
}
com["body_analyzed"], _ = com["body"]
userLogin, ok := Dig(com, []string{"user", "login"}, false, true)
if ok {
com["user_data"], _, err = j.githubUser(ctx, userLogin.(string))
if err != nil {
return
}
}
iCnt, ok := Dig(com, []string{"reactions", "total_count"}, false, true)
if ok {
com["reactions_data"] = []interface{}{}
cnt := int(iCnt.(float64))
if cnt > 0 {
cid, ok := Dig(com, []string{"id"}, false, true)
if ok {
com["reactions_data"], err = j.githubCommentReactions(ctx, org, repo, int64(cid.(float64)))
if err != nil {
return
}
}
}
}
comments = append(comments, com)
}
if response.NextPage == 0 {
break
}
opt.Page = response.NextPage
if ctx.Debug > 0 {
Printf("processing next issue comments page: %d\n", opt.Page)
}
retry = false
}
if ctx.Debug > 2 {
Printf("issue comments got from API: %+v\n", comments)
}
if CacheGitHubIssueComments {
if j.GitHubIssueCommentsMtx != nil {
j.GitHubIssueCommentsMtx.Lock()
}
j.GitHubIssueComments[key] = comments
if j.GitHubIssueCommentsMtx != nil {
j.GitHubIssueCommentsMtx.Unlock()
}
}
return
}
func (j *DSGitHub) githubCommentReactions(ctx *Ctx, org, repo string, cid int64) (reactions []map[string]interface{}, err error) {
var found bool
key := fmt.Sprintf("%s/%s/%d", org, repo, cid)
if ctx.Debug > 1 {
fmt.Printf("githubCommentReactions %s\n", key)
}
// Try memory cache 1st
if CacheGitHubCommentReactions {
if j.GitHubCommentReactionsMtx != nil {
j.GitHubCommentReactionsMtx.RLock()
}
reactions, found = j.GitHubCommentReactions[key]
if j.GitHubCommentReactionsMtx != nil {
j.GitHubCommentReactionsMtx.RUnlock()
}
if found {
if ctx.Debug > 2 {
Printf("comment reactions found in cache: %+v\n", reactions)
}
return
}
}
var c *github.Client
if j.GitHubMtx != nil {
j.GitHubMtx.RLock()
}
c = j.Clients[j.Hint]
if j.GitHubMtx != nil {
j.GitHubMtx.RUnlock()
}
opt := &github.ListOptions{}
opt.PerPage = ItemsPerPage
retry := false
for {
var (
response *github.Response
reacts []*github.Reaction
e error
)
reacts, response, e = c.Reactions.ListIssueCommentReactions(j.Context, org, repo, cid, opt)
if ctx.Debug > 2 {
Printf("GET %s/%s/%d -> {%+v, %+v, %+v}\n", org, repo, cid, reacts, response, e)
}
if e != nil && strings.Contains(e.Error(), "404 Not Found") {
if CacheGitHubCommentReactions {
if j.GitHubCommentReactionsMtx != nil {
j.GitHubCommentReactionsMtx.Lock()
}
j.GitHubCommentReactions[key] = []map[string]interface{}{}
if j.GitHubCommentReactionsMtx != nil {
j.GitHubCommentReactionsMtx.Unlock()
}
}
if ctx.Debug > 1 {
Printf("githubCommentReactions: reactions not found %s: %v\n", key, e)
}
return
}
if e != nil && !retry {
Printf("Unable to get %s comment reactions: response: %+v, because: %+v, retrying rate\n", key, response, e)
Printf("githubCommentReactions: handle rate\n")
abuse, rateLimit := j.isAbuse(e)
if abuse {
sleepFor := AbuseWaitSeconds + rand.Intn(AbuseWaitSeconds)
Printf("GitHub detected abuse (get comment reactions %s), waiting for %ds\n", key, sleepFor)
time.Sleep(time.Duration(sleepFor) * time.Second)
}
if rateLimit {
Printf("Rate limit reached on a token (get comment reactions %s) waiting 1s before token switch\n", key)
time.Sleep(time.Duration(1) * time.Second)
}
if j.GitHubMtx != nil {
j.GitHubMtx.Lock()
}
j.Hint, _ = j.handleRate(ctx)
c = j.Clients[j.Hint]
if j.GitHubMtx != nil {
j.GitHubMtx.Unlock()
}
if !abuse && !rateLimit {
retry = true
}
continue
}
if e != nil {
err = e
return
}
for _, reaction := range reacts {
react := map[string]interface{}{}
jm, _ := jsoniter.Marshal(reaction)
_ = jsoniter.Unmarshal(jm, &react)
userLogin, ok := Dig(react, []string{"user", "login"}, false, true)
if ok {
react["user_data"], _, err = j.githubUser(ctx, userLogin.(string))
if err != nil {
return
}
}
reactions = append(reactions, react)
}
if response.NextPage == 0 {
break
}
opt.Page = response.NextPage
if ctx.Debug > 0 {
Printf("processing next comment reactions page: %d\n", opt.Page)
}
retry = false
}
if ctx.Debug > 2 {
Printf("comment reactions got from API: %+v\n", reactions)
}
if CacheGitHubCommentReactions {
if j.GitHubCommentReactionsMtx != nil {
j.GitHubCommentReactionsMtx.Lock()
}
j.GitHubCommentReactions[key] = reactions
if j.GitHubCommentReactionsMtx != nil {
j.GitHubCommentReactionsMtx.Unlock()
}
}
return