-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathghapi.go
More file actions
2455 lines (2352 loc) · 69.8 KB
/
Copy pathghapi.go
File metadata and controls
2455 lines (2352 loc) · 69.8 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 devstatscode
import (
"context"
"database/sql"
"fmt"
"net/url"
"os"
"sort"
"strings"
"sync"
"time"
"github.com/google/go-github/v38/github"
"golang.org/x/oauth2"
)
// IssueConfig - holds issue data
type IssueConfig struct {
Repo string
Number int
IssueID int64
Pr bool
MilestoneID *int64
Labels string
LabelsMap map[int64]string
GhIssue *github.Issue
CreatedAt time.Time
EventID int64
EventType string
GhEvent *github.IssueEvent
AssigneeID *int64
Assignees string
AssigneesMap map[int64]string
}
func (ic IssueConfig) String() string {
var (
milestoneID int64
assigneeID int64
)
if ic.MilestoneID != nil {
milestoneID = *ic.MilestoneID
}
if ic.AssigneeID != nil {
assigneeID = *ic.AssigneeID
}
return fmt.Sprintf(
"{Repo: %s, Number: %d, IssueID: %d, EventID: %d, EventType: %s, Pr: %v, MilestoneID: %d, AssigneeID: %d, CreatedAt: %s, Labels: %s, LabelsMap: %+v, Assignees: %s, AssigneesMap: %+v}",
ic.Repo,
ic.Number,
ic.IssueID,
ic.EventID,
ic.EventType,
ic.Pr,
milestoneID,
assigneeID,
ToYMDHMSDate(ic.CreatedAt),
ic.Labels,
ic.LabelsMap,
ic.Assignees,
ic.AssigneesMap,
)
}
func (ic IssueConfig) configStr() string {
var (
milestoneID int64
assigneeID int64
)
if ic.MilestoneID != nil {
milestoneID = *ic.MilestoneID
}
if ic.AssigneeID != nil {
assigneeID = *ic.AssigneeID
}
return fmt.Sprintf(
"{Repo: %s, Number: %d, IssueID: %d, MilestoneID: %d, AssigneeID: %d, Labels: %s, Assignees: %s}",
ic.Repo,
ic.Number,
ic.IssueID,
milestoneID,
assigneeID,
ic.Labels,
ic.Assignees,
)
}
// outputIssuesInfo: display summary of issues data to process
func outputIssuesInfo(issues map[int64]IssueConfigAry, info string) {
Printf("%s:\n", info)
eids := make(map[int64][2]int64)
data := make(map[string][]string)
for _, cfgAry := range issues {
for _, cfg := range cfgAry {
eid := cfg.EventID
_, o := eids[eid]
if o {
eids[eid] = [2]int64{*cfg.GhIssue.ID, eids[eid][1] + 1}
} else {
eids[eid] = [2]int64{*cfg.GhIssue.ID, 1}
}
key := fmt.Sprintf("%s %d", cfg.Repo, cfg.Number)
val := fmt.Sprintf("%s %s", ToYMDHMSDate(cfg.CreatedAt), cfg.EventType)
_, ok := data[key]
if ok {
data[key] = append(data[key], val)
} else {
data[key] = []string{val}
}
}
}
keys := []string{}
for key := range data {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
values := data[key]
svalues := []string{}
for _, value := range values {
svalues = append(svalues, value)
}
sort.Strings(svalues)
Printf("%s: [%s]\n", key, strings.Join(svalues, ", "))
}
for eid, na := range eids {
if na[1] > 1 {
Printf("Warning: Duplicate event %d(%d): %v\n", eid, na[1], issues[na[0]])
}
}
for _, cfgAry := range issues {
l := len(cfgAry)
for i := 0; i < l; i++ {
for j := i + 1; j < l; j++ {
stateA := cfgAry[i].configStr()
stateB := cfgAry[j].configStr()
if stateA != stateB {
Printf("StateA: %v\n", stateA)
Printf("StateB: %v\n\n", stateB)
}
}
}
}
}
// outputPRsInfo: display summary of PRs data to process
func outputPRsInfo(prs map[int64]github.PullRequest, info string) {
Printf("%s:\n", info)
infos := []string{}
for prid, pr := range prs {
if pr.Number != nil && pr.Base != nil && pr.Base.Repo != nil && pr.Base.Repo.FullName != nil {
infos = append(infos, fmt.Sprintf("%s %d", *pr.Base.Repo.FullName, *pr.Number))
} else {
infos = append(infos, fmt.Sprintf("<%d>", prid))
}
}
sort.Strings(infos)
Printf("PRs: %s\n", strings.Join(infos, ", "))
}
// outputInfo: displays messages gathered in the map
func outputInfo(infos map[string][]string, info string) {
Printf("%s:\n", info)
keys := []string{}
for key := range infos {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
msgs := infos[key]
sort.Strings(msgs)
Printf("%s:\n\t%s\n", key, strings.Join(msgs, "\n\t"))
}
}
// IssueConfigAry - allows sorting IssueConfig array by IssueID annd then event creation date
type IssueConfigAry []IssueConfig
func (ic IssueConfigAry) Len() int { return len(ic) }
func (ic IssueConfigAry) Swap(i, j int) { ic[i], ic[j] = ic[j], ic[i] }
func (ic IssueConfigAry) Less(i, j int) bool {
if ic[i].IssueID != ic[j].IssueID {
return ic[i].IssueID < ic[j].IssueID
}
if ic[i].CreatedAt != ic[j].CreatedAt {
return ic[i].CreatedAt.Before(ic[j].CreatedAt)
}
return ic[i].EventID < ic[j].EventID
}
// rateLimitsCacheEntry - GetRateLimits result cached for `GHA2DB_GHAPI_RATE_LIMITS_CACHE` seconds
type rateLimitsCacheEntry struct {
at time.Time
nClients int
limits []int
remainings []int
durations []time.Duration
}
var (
// rateLimitsCache - cached GetRateLimits results, key: core flag (true: Core limits, false: Search limits)
rateLimitsCache = map[bool]*rateLimitsCacheEntry{}
// rateLimitsCacheMutex - protects rateLimitsCache, it is held while polling GitHub too, so concurrent
// callers wait for one poll instead of all polling at once
rateLimitsCacheMutex = &sync.Mutex{}
)
// InvalidateRateLimitsCache - drops cached GetRateLimits results, so the next call polls GitHub again
// called when a rate limit/abuse error is detected, so exhausted tokens are re-checked immediately
func InvalidateRateLimitsCache() {
rateLimitsCacheMutex.Lock()
rateLimitsCache = map[bool]*rateLimitsCacheEntry{}
rateLimitsCacheMutex.Unlock()
}
// rateLimitsHint - returns index of the client with most remaining API points
// ties are won by the client whose limit resets sooner
func rateLimitsHint(remainings []int, durations []time.Duration) int {
hint := 0
for idx := range remainings {
if remainings[idx] > remainings[hint] {
hint = idx
} else if idx != hint && remainings[idx] == remainings[hint] && durations[idx] < durations[hint] {
hint = idx
}
}
return hint
}
// pollRateLimits - asks all clients for their rate limits (concurrently, one /rate_limit call per client)
// error messages are printed in clients order after all calls finish, all durations are computed
// against the same "now", so equally loaded clients tie exactly (and the first one wins the hint)
func pollRateLimits(gctx context.Context, gcs []*github.Client, core bool) (limits, remainings []int, durations []time.Duration) {
n := len(gcs)
limits = make([]int, n)
remainings = make([]int, n)
durations = make([]time.Duration, n)
msgs := make([]string, n)
resets := make([]*time.Time, n)
wg := &sync.WaitGroup{}
for idx, gc := range gcs {
wg.Add(1)
go func(idx int, gc *github.Client) {
defer wg.Done()
rl, _, err := gc.RateLimits(gctx)
if err != nil {
rem, ok := PeriodParse(err.Error())
if ok {
msgs[idx] = fmt.Sprintf("Parsed wait time from error message: %v\n", rem)
limits[idx], remainings[idx], durations[idx] = -1, -1, rem
return
}
msgs[idx] = fmt.Sprintf("GetRateLimit(%d): %v\n", idx, err)
}
if rl == nil {
limits[idx], remainings[idx], durations[idx] = -1, -1, time.Duration(5)*time.Second
return
}
rate := rl.Core
if !core {
rate = rl.Search
}
limits[idx] = rate.Limit
remainings[idx] = rate.Remaining
reset := rate.Reset.Time
resets[idx] = &reset
}(idx, gc)
}
wg.Wait()
now := time.Now()
for idx, reset := range resets {
if reset != nil {
durations[idx] = reset.Sub(now) + time.Duration(1)*time.Second
}
}
for _, msg := range msgs {
if msg != "" {
Printf("%s", msg)
}
}
return
}
// GetRateLimits - returns all and remaining API points and duration to wait for reset
// when core=true - returns Core limits, when core=false returns Search limits
// Results are cached for ctx.GHAPIRateLimitsCache seconds (GHA2DB_GHAPI_RATE_LIMITS_CACHE, 0 disables the cache):
// every call is assumed to be followed by one API call using the hinted client, so cached remaining points
// of that client are decreased by one, cached durations are shortened by the elapsed time.
// Cache is not used (GitHub is polled) when it says that the best client has ctx.MinGHAPIPoints or less
// points left or that its limit was already reset, so waiting for the reset/aborting is always decided
// using fresh data.
func GetRateLimits(gctx context.Context, ctx *Ctx, gcs []*github.Client, core bool) (int, []int, []int, []time.Duration) {
var (
limits []int
remainings []int
durations []time.Duration
)
ttl := time.Duration(ctx.GHAPIRateLimitsCache) * time.Second
if ttl > 0 {
rateLimitsCacheMutex.Lock()
defer rateLimitsCacheMutex.Unlock()
cached := false
entry, ok := rateLimitsCache[core]
if ok && entry.nClients == len(gcs) && len(gcs) > 0 {
elapsed := time.Since(entry.at)
hint := rateLimitsHint(entry.remainings, entry.durations)
if elapsed < ttl && entry.remainings[hint] > ctx.MinGHAPIPoints && entry.durations[hint] > elapsed {
limits = append(limits, entry.limits...)
remainings = append(remainings, entry.remainings...)
for _, d := range entry.durations {
durations = append(durations, d-elapsed)
}
entry.remainings[hint]--
cached = true
}
}
if !cached {
limits, remainings, durations = pollRateLimits(gctx, gcs, core)
entry := &rateLimitsCacheEntry{
at: time.Now(),
nClients: len(gcs),
limits: append([]int{}, limits...),
remainings: append([]int{}, remainings...),
durations: append([]time.Duration{}, durations...),
}
if len(gcs) > 0 {
// This call is followed by an API call using the hinted client too
entry.remainings[rateLimitsHint(remainings, durations)]--
}
rateLimitsCache[core] = entry
}
} else {
limits, remainings, durations = pollRateLimits(gctx, gcs, core)
}
hint := rateLimitsHint(remainings, durations)
if ctx.GitHubDebug > 0 {
Printf("GetRateLimits: hint: %d, limits: %+v, remaining: %+v, reset: %+v\n", hint, limits, remainings, durations)
}
return hint, limits, remainings, durations
}
// GHClient - get GitHub client
func GHClient(ctx *Ctx) (ghCtx context.Context, clients []*github.Client) {
// Get GitHub OAuth from env or from file
oAuth := ctx.GitHubOAuth
if strings.Contains(ctx.GitHubOAuth, "/") {
bytes, err := ReadFile(ctx, ctx.GitHubOAuth)
FatalOnError(err)
oAuth = strings.TrimSpace(string(bytes))
}
// GitHub authentication or use public access
ghCtx = context.Background()
if oAuth == "-" {
client := github.NewClient(nil)
clients = append(clients, client)
} else {
oAuths := strings.Split(oAuth, ",")
for _, auth := range oAuths {
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: auth},
)
tc := oauth2.NewClient(ghCtx, ts)
client := github.NewClient(tc)
clients = append(clients, client)
}
}
// Optional API base URL override (GitHub Enterprise / testing)
if ctx.GitHubAPIURL != "" {
baseURL, err := url.Parse(ctx.GitHubAPIURL)
FatalOnError(err)
for _, client := range clients {
client.BaseURL = baseURL
}
}
return
}
// HandlePossibleError - display error specific message, detect rate limit and abuse
func HandlePossibleError(err error, cfg, info string) string {
if err != nil {
_, rate := err.(*github.RateLimitError)
_, abuse := err.(*github.AbuseRateLimitError)
if abuse || rate {
// Cached rate limits are stale now, re-poll GitHub before the next API call
InvalidateRateLimitsCache()
if rate {
Printf("Rate limit (%s) for %v\n", info, cfg)
return "rate"
}
if abuse {
Printf("Abuse detected (%s) for %v\n", info, cfg)
return Abuse
}
}
errStr := err.Error()
if strings.Contains(errStr, "410 This issue was deleted") {
Printf("Issue was deleted (%s) for %v: %v\n", info, cfg, err)
return IssueIsDeleted
} else if strings.Contains(errStr, "404 Not Found") {
Printf("Not found (%s) for %v: %v\n", info, cfg, err)
return NotFound
} else if strings.Contains(errStr, "502 Server Error") {
Printf("Server Error (%s) for %v: %v\n", info, cfg, err)
return "server_error"
} else if strings.Contains(errStr, "409 Git Repository is empty") {
Printf("Git repository empty (%s) for %v: %v\n", info, cfg, err)
return NotFound
} else if strings.Contains(errStr, "301") {
Printf("Moved Permanently (%s) for %v: %v\n", info, cfg, err)
return MovedPermanently
}
//FatalOnError(err)
Printf("%s error: %T:%v, non fatal, exiting 0 status\n", os.Args[0], err, err)
os.Exit(0)
}
return ""
}
func ghActorIDOrNil(actPtr *github.User) interface{} {
if actPtr == nil {
return nil
}
return actPtr.ID
}
func ghActorLoginOrNil(actPtr *github.User, maybeHide func(string) string) interface{} {
if actPtr == nil {
return nil
}
if actPtr.Login == nil {
return nil
}
return maybeHide(*actPtr.Login)
}
func ghMilestoneIDOrNil(milPtr *github.Milestone) interface{} {
if milPtr == nil {
return nil
}
return milPtr.ID
}
// ghEnsureEventActor - GitHub API can return an issue event without an actor (or with an
// actor missing id/login) when the account that performed the event was deleted.
// Such events cannot be stored (actor related columns are NOT NULL), so reassign them
// to the canonical GitHub placeholder actor 'ghost' (id 10137) - just like GitHub does.
func ghEnsureEventActor(cfg *IssueConfig) {
event := cfg.GhEvent
if event == nil {
return
}
actor := event.Actor
if actor != nil && actor.ID != nil && actor.Login != nil {
return
}
ghostID := GhostActorID
ghostLogin := GhostActorLogin
Printf(
"Warning: event %d for %s #%d (%s, %v) has no actor (deleted account?), reassigning to '%s' (id %d)\n",
cfg.EventID, cfg.Repo, cfg.Number, cfg.EventType, ToYMDHMSDate(cfg.CreatedAt), ghostLogin, ghostID,
)
event.Actor = &github.User{ID: &ghostID, Login: &ghostLogin}
}
// Inserts single GitHub User
func ghActor(con *sql.Tx, ctx *Ctx, actor *github.User, maybeHide func(string) string) {
if actor == nil || actor.Login == nil {
return
}
InsertActorTx(con, ctx, actor.ID, maybeHide(*actor.Login), "")
}
// Insert single GitHub milestone
// milestone: the milestone to insert - the issue's one for artificial issue events,
// the PR's one for artificial PR events (they can differ: the two API payloads are
// fetched separately and the PR payload can carry a milestone the issue payload lacks).
func ghMilestone(con *sql.Tx, ctx *Ctx, eid int64, ic *IssueConfig, repoID int64, milestone *github.Milestone, maybeHide func(string) string) {
// Defensive no-op for current callers: ArtificialEvent/ArtificialPREvent already skipped
// (GHA2DB_GHAPIALLOWINSERTFAIL) or ghost-reassigned actor-less events before calling here.
// Kept because the code below dereferences ev.Actor directly - protects any future caller.
ghEnsureEventActor(ic)
ev := ic.GhEvent
// gha_milestones
ExecSQLTxWithErr(
con,
ctx,
InsertIgnore(
fmt.Sprintf(
"into gha_milestones("+
"id, event_id, closed_at, closed_issues, created_at, creator_id, "+
"description, due_on, number, open_issues, state, title, updated_at, "+
"dup_actor_id, dup_actor_login, dup_repo_id, dup_repo_name, dup_type, dup_created_at, "+
"dupn_creator_login) values("+
"%s, %s, %s, %s, %s, %s, "+
"%s, %s, %s, %s, %s, %s, %s, "+
"%s, %s, %s, %s, %s, %s, "+
"%s)",
NValue(1),
NValue(2),
NValue(3),
NValue(4),
NValue(5),
NValue(6),
NValue(7),
NValue(8),
NValue(9),
NValue(10),
NValue(11),
NValue(12),
NValue(13),
NValue(14),
NValue(15),
NValue(16),
NValue(17),
NValue(18),
NValue(19),
NValue(20),
),
),
AnyArray{
milestone.ID,
eid,
milestone.ClosedAt,
milestone.ClosedIssues,
milestone.CreatedAt,
ghActorIDOrNil(milestone.Creator),
TruncStringOrNil(milestone.Description, 0xffff),
milestone.DueOn,
milestone.Number,
milestone.OpenIssues,
milestone.State,
TruncStringOrNil(milestone.Title, 200),
milestone.UpdatedAt,
ev.Actor.ID,
maybeHide(*ev.Actor.Login),
repoID,
ic.Repo,
ic.EventType,
ic.CreatedAt,
ghActorLoginOrNil(milestone.Creator, maybeHide),
}...,
)
}
// GetRecentRepos - get list of repos active last day
func GetRecentRepos(c *sql.DB, ctx *Ctx, dtFrom time.Time) (repos []string, rids []int64) {
rows := QuerySQLWithErr(
c,
ctx,
fmt.Sprintf(
"select distinct repo_id, dup_repo_name from gha_events "+
"where created_at > %s",
NValue(1),
),
dtFrom,
)
defer func() { FatalOnError(rows.Close()) }()
var (
repo string
rid int64
)
for rows.Next() {
FatalOnError(rows.Scan(&rid, &repo))
repos = append(repos, repo)
rids = append(rids, rid)
}
FatalOnError(rows.Err())
return
}
// GetTrackedRepos - every repository of gha_repos, one current name per repository id.
// A repository id can be listed under several names (renames); the current name is the one
// with the newest native GH Archive event (0 < id < 2^48), the other names are historical.
// Ids without any native event keep their alphabetically first name.
// Returns the current names (sorted), their ids (a name can be tracked under several ids,
// sorted ascending) and the sorted historical names (those that are current for no id).
func GetTrackedRepos(c *sql.DB, ctx *Ctx) (repos []string, ids map[string][]int64, historical []string) {
type named struct {
name string
createdAt time.Time
eventID int64
valid bool
}
rows := QuerySQLWithErr(
c,
ctx,
"select r.id, r.name, n.created_at, n.id from gha_repos r left join lateral ("+
"select e.created_at, e.id from gha_events e where e.repo_id = r.id and e.dup_repo_name = r.name "+
"and e.id > 0 and e.id < 281474976710656 order by e.created_at desc, e.id desc limit 1) n on true",
)
defer func() { FatalOnError(rows.Close()) }()
byID := make(map[int64][]named)
for rows.Next() {
var (
rid int64
name string
createdAt sql.NullTime
eventID sql.NullInt64
)
FatalOnError(rows.Scan(&rid, &name, &createdAt, &eventID))
byID[rid] = append(byID[rid], named{name: name, createdAt: createdAt.Time, eventID: eventID.Int64, valid: createdAt.Valid})
}
FatalOnError(rows.Err())
ids = make(map[string][]int64)
old := make(map[string]struct{})
for rid, names := range byID {
best := 0
for i := 1; i < len(names); i++ {
n, b := names[i], names[best]
switch {
case n.valid && !b.valid:
best = i
case n.valid && b.valid && (n.createdAt.After(b.createdAt) || (n.createdAt.Equal(b.createdAt) && n.eventID > b.eventID)):
best = i
case !n.valid && !b.valid && n.name < b.name:
best = i
}
}
for i, n := range names {
if i == best {
ids[n.name] = append(ids[n.name], rid)
} else {
old[n.name] = struct{}{}
}
}
}
for name, rids := range ids {
sort.Slice(rids, func(i, j int) bool { return rids[i] < rids[j] })
repos = append(repos, name)
}
sort.Strings(repos)
for name := range old {
if _, ok := ids[name]; !ok {
historical = append(historical, name)
}
}
sort.Strings(historical)
return
}
// repoIDByNameCache - CurrentRepoID answers per process (the data does not change under a run)
var repoIDByNameCache sync.Map
// CurrentRepoID - the repository id (and organization id, nil when none) behind a repository name.
// GH Archive lists some names under several ids (a placeholder repository created before a transfer,
// a fork that took over a name, id-less rows): the current id is the one whose newest native event
// (0 < id < 2^48) under that name is the newest - the same rule GetTrackedRepos uses for the current
// name of an id; ids without native events come after those with, ties go to the highest id.
// native=false: the id comes from gha_repos alone (no native event under the name yet).
// Names without a gha_repos row fall back to the events (highest repo_id). Returns ok=false when the
// name is unknown to both. Bug 68: `max(repo_id)` picked the placeholder id 40511817 for
// kubernetes/kubernetes (one CreateEvent from 2015) over the real 20580498, and once an artificial
// event carried it, `max` kept returning it - 2M artificial events ended up under the placeholder.
func CurrentRepoID(c *sql.DB, ctx *Ctx, name string) (repoID int64, orgID *int64, native, ok bool) {
type cached struct {
repoID int64
orgID *int64
native bool
ok bool
}
if v, hit := repoIDByNameCache.Load(name); hit {
cv := v.(cached)
return cv.repoID, cv.orgID, cv.native, cv.ok
}
// The lateral subquery walks events_repo_name_created_at_idx backwards: cheap unless the id
// carries millions of artificial events (the bug 68 placeholder before its repair), and then
// once per process per name
queries := []string{
"select r.id, coalesce(n.org_id, r.org_id), n.created_at is not null from gha_repos r left join lateral (" +
"select e.created_at, e.org_id from gha_events e where e.repo_id = r.id and e.dup_repo_name = r.name " +
"and e.id > 0 and e.id < 281474976710656 order by e.created_at desc limit 1) n on true " +
"where r.name = " + NValue(1) + " order by n.created_at desc nulls last, r.id desc limit 1",
"select max(repo_id), max(org_id), true from gha_events where dup_repo_name = " + NValue(1),
}
for _, query := range queries {
rows := QuerySQLWithErr(c, ctx, query, name)
var (
rid sql.NullInt64
oid sql.NullInt64
nat bool
)
for rows.Next() {
FatalOnError(rows.Scan(&rid, &oid, &nat))
}
FatalOnError(rows.Err())
FatalOnError(rows.Close())
if !rid.Valid {
continue
}
repoID, native, ok = rid.Int64, nat, true
if oid.Valid {
o := oid.Int64
orgID = &o
}
break
}
if ok && orgID == nil {
rows := QuerySQLWithErr(c, ctx, "select max(org_id) from gha_events where dup_repo_name = "+NValue(1), name)
var oid sql.NullInt64
for rows.Next() {
FatalOnError(rows.Scan(&oid))
}
FatalOnError(rows.Err())
FatalOnError(rows.Close())
if oid.Valid {
o := oid.Int64
orgID = &o
}
}
repoIDByNameCache.Store(name, cached{repoID: repoID, orgID: orgID, native: native, ok: ok})
return
}
// artificialRepoIDs - repo id (-1 when unknown, the legacy marker) and org id (nil when none)
// for the artificial events of a repository name
func artificialRepoIDs(c *sql.DB, ctx *Ctx, name string) (int64, interface{}) {
repoID, orgID, _, ok := CurrentRepoID(c, ctx, name)
if !ok {
return -1, nil
}
if orgID == nil {
return repoID, nil
}
return repoID, *orgID
}
// DeleteArtificialPREvent - create artificial API event (but from the past)
func DeleteArtificialPREvent(c *sql.DB, ctx *Ctx, cfg *IssueConfig) (err error) {
if ctx.SkipPDB {
if ctx.Debug > 0 {
Printf("No DB write: Delete PR '%v'\n", *cfg)
}
return nil
}
eid := 281474976710656 + cfg.EventID
condition := fmt.Sprintf(" where event_id = %d", eid)
deletes := []string{
"delete from gha_pull_requests" + condition,
"delete from gha_pull_requests_assignees" + condition,
"delete from gha_pull_requests_requested_reviewers" + condition,
}
// Start transaction
tc, err := c.Begin()
FatalOnError(err)
for _, del := range deletes {
ExecSQLTxWithErr(tc, ctx, del)
}
// Final commit
FatalOnError(tc.Commit())
//FatalOnError(tc.Rollback())
return
}
// ArtificialPREvent - create artificial API event (PR state for now())
func ArtificialPREvent(c *sql.DB, ctx *Ctx, cfg *IssueConfig, pr *github.PullRequest) (err error) {
if ctx.SkipPDB {
if ctx.Debug > 0 {
Printf("No DB write: PR '%v'\n", *cfg)
}
return nil
}
// To handle GDPR
maybeHide := MaybeHideFunc(GetHidden(ctx, HideCfgFile))
eventID := 281474976710656 + cfg.EventID
eType := cfg.EventType
eCreatedAt := cfg.CreatedAt
event := cfg.GhEvent
issue := cfg.GhIssue
iid := *issue.ID
// Bad GH API data: events performed by deleted GitHub accounts can have no actor.
// When GHA2DB_GHAPIALLOWINSERTFAIL is set: report and skip such events.
// Otherwise (default): reassign them to the 'ghost' placeholder actor instead of failing NOT NULL inserts.
if ctx.AllowGHAPIInsertFail && (event.Actor == nil || event.Actor.ID == nil || event.Actor.Login == nil) {
Printf("Warning: GHA2DB_GHAPIALLOWINSERTFAIL: skipped artificial PR event for %s %d (%s, %v): event has no actor\n", cfg.Repo, cfg.Number, cfg.EventType, ToYMDHMSDate(cfg.CreatedAt))
return nil
}
ghEnsureEventActor(cfg)
actor := event.Actor
// Repository id (bug 68: the current id of the name, not max(repo_id)) and organization id
repoID, orgID := artificialRepoIDs(c, ctx, cfg.Repo)
// Start transaction
tc, err := c.Begin()
FatalOnError(err)
// Event actor & user
ghActor(tc, ctx, actor, maybeHide)
ghActor(tc, ctx, pr.User, maybeHide)
baseSHA := ""
headSHA := ""
if pr.Base != nil && pr.Base.SHA != nil {
baseSHA = *pr.Base.SHA
}
if pr.Head != nil && pr.Head.SHA != nil {
headSHA = *pr.Head.SHA
}
if pr.MergedBy != nil {
ghActor(tc, ctx, pr.MergedBy, maybeHide)
}
if pr.Assignee != nil {
ghActor(tc, ctx, pr.Assignee, maybeHide)
}
if pr.Milestone != nil {
ghMilestone(tc, ctx, eventID, cfg, repoID, pr.Milestone, maybeHide)
}
prid := *pr.ID
ExecSQLTxWithErr(
tc,
ctx,
InsertIgnore(
fmt.Sprintf(
"into gha_pull_requests("+
"id, event_id, user_id, base_sha, head_sha, merged_by_id, assignee_id, milestone_id, "+
"number, state, title, body, created_at, updated_at, closed_at, merged_at, "+
"merge_commit_sha, merged, mergeable, mergeable_state, comments, "+
"maintainer_can_modify, commits, additions, deletions, changed_files, "+
"dup_actor_id, dup_actor_login, dup_repo_id, dup_repo_name, dup_type, dup_created_at, "+
// "dup_user_login, dupn_assignee_login, dupn_merged_by_login) values("+
"dup_user_login, dupn_merged_by_login) values("+
"%s, %s, %s, %s, %s, %s, %s, %s, "+
"%s, %s, %s, %s, %s, %s, %s, %s, "+
"%s, %s, %s, %s, %s, "+
"%s, %s, %s, %s, %s, "+
"%s, %s, %s, %s, %s, %s, "+
// "%s, %s, %s)",
"%s, %s)",
NValue(1),
NValue(2),
NValue(3),
NValue(4),
NValue(5),
NValue(6),
NValue(7),
NValue(8),
NValue(9),
NValue(10),
NValue(11),
NValue(12),
NValue(13),
NValue(14),
NValue(15),
NValue(16),
NValue(17),
NValue(18),
NValue(19),
NValue(20),
NValue(21),
NValue(22),
NValue(23),
NValue(24),
NValue(25),
NValue(26),
NValue(27),
NValue(28),
NValue(29),
NValue(30),
NValue(31),
NValue(32),
NValue(33),
NValue(34),
// NValue(35),
),
),
AnyArray{
prid,
eventID,
ghActorIDOrNil(pr.User),
baseSHA,
headSHA,
ghActorIDOrNil(pr.MergedBy),
ghActorIDOrNil(pr.Assignee),
ghMilestoneIDOrNil(pr.Milestone),
pr.Number,
pr.State,
pr.Title,
TruncStringOrNil(pr.Body, 0xffff),
pr.CreatedAt,
pr.UpdatedAt,
TimeOrNil(pr.ClosedAt),
TimeOrNil(pr.MergedAt),
StringOrNil(pr.MergeCommitSHA),
BoolOrNil(pr.Merged),
BoolOrNil(pr.Mergeable),
StringOrNil(pr.MergeableState),
IntOrNil(pr.Comments),
BoolOrNil(pr.MaintainerCanModify),
IntOrNil(pr.Commits),
IntOrNil(pr.Additions),
IntOrNil(pr.Deletions),
IntOrNil(pr.ChangedFiles),
actor.ID,
ghActorLoginOrNil(actor, maybeHide),
repoID,
cfg.Repo,
eType,
eCreatedAt,
ghActorLoginOrNil(pr.User, maybeHide),
// ghActorLoginOrNil(pr.Assignee, maybeHide),
ghActorLoginOrNil(pr.MergedBy, maybeHide),
}...,
)
// Create artificial event
ExecSQLTxWithErr(
tc,
ctx,
InsertIgnore(
fmt.Sprintf(
"into gha_events("+
// "id, type, actor_id, repo_id, public, created_at, "+
"id, type, actor_id, repo_id, created_at, "+
// "dup_actor_login, dup_repo_name, org_id, forkee_id) "+
"dup_actor_login, dup_repo_name, org_id) "+
// "values(%s, %s, %s, %s, true, %s, "+
"values(%s, %s, %s, %s, %s, "+
// "%s, %s, %s, null)",
"%s, %s, %s)",
NValue(1),
NValue(2),
NValue(3),
NValue(4),
NValue(5),
NValue(6),
NValue(7),
NValue(8),
),
),
AnyArray{
eventID,
cfg.EventType,
ghActorIDOrNil(event.Actor),
repoID,
eCreatedAt,
ghActorLoginOrNil(event.Actor, maybeHide),
cfg.Repo,
orgID,
}...,
)
// Create artificial event's payload
ExecSQLTxWithErr(
tc,
ctx,
InsertIgnore(
fmt.Sprintf(
"into gha_payloads("+
"event_id, push_id, size, ref, head, befor, action, "+
// "issue_id, pull_request_id, comment_id, ref_type, master_branch, commit, "+
"issue_id, pull_request_id, comment_id, commit, "+
// "description, number, forkee_id, release_id, member_id, "+
"number, forkee_id, release_id, member_id, "+
// "dup_actor_id, dup_actor_login, dup_repo_id, dup_repo_name, dup_type, dup_created_at) "+
"dup_actor_login, dup_repo_id, dup_repo_name, dup_type, dup_created_at) "+
"values(%s, null, null, null, null, null, %s, "+
// "%s, %s, null, null, null, null, "+
"%s, %s, null, null, "+
// "null, %s, null, null, null, "+
"%s, null, null, null, "+
// "%s, %s, %s, %s, %s, %s)",
"%s, %s, %s, %s, %s)",
NValue(1),
NValue(2),
NValue(3),
NValue(4),
NValue(5),
NValue(6),
NValue(7),
NValue(8),
NValue(9),
NValue(10),
// NValue(11),
),
),
AnyArray{
eventID,
cfg.EventType,
iid,
prid,
issue.Number,
// ghActorIDOrNil(event.Actor),
ghActorLoginOrNil(event.Actor, maybeHide),
repoID,
cfg.Repo,
cfg.EventType,
eCreatedAt,
}...,
)
// If such payload already existed, we need to set PR ID on it